path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/scenes/home/informationForm/formComponents/identifier.js
tal87/operationcode_frontend
import React, { Component } from 'react'; import Form from 'shared/components/form/form'; import PropTypes from 'prop-types'; import FormSelect from 'shared/components/form/formSelect/formSelect'; import { IDENTIFIERS } from 'shared/constants/status'; import styles from './formComponents.css'; class Identifier extends Component { // call the init method upon component creation componentDidMount() { if (this.props.init) { this.props.init(); } } render() { return ( <Form className={styles.signup}> <FormSelect id="identifier" options={IDENTIFIERS} prompt="Which describes you" onChange={e => this.props.update(e, e.target.value)} className={styles.signup} validationFunc={e => this.props.validationFunc(e)} /> { !this.props.isValid && this.props.validationErrorMessage } </Form> ); } } Identifier.propTypes = { update: PropTypes.func, validationFunc: PropTypes.func, isValid: PropTypes.bool, validationErrorMessage: PropTypes.string, init: PropTypes.func }; Identifier.defaultProps = { update: null, validationFunc: null, isValid: true, validationErrorMessage: null, init: null }; export default Identifier;
js/react/shopping-cart/components/Cart.js
topliceanu/learn
import React from 'react' import CartContents from './CartContents.js' import CartTotal from './CartTotal.js' let Cart = React.createClass({ propTypes: { items: React.PropTypes.arrayOf(React.PropTypes.shape({ id: React.PropTypes.any.isRequired, count: React.PropTypes.number, value: React.PropTypes.number, desc: React.PropTypes.string })) }, getDefaultProps () { return { items: [], }; }, getInitialState () { return this.props }, findItemById (itemId) { let found = this.state.items.filter((item) => { return item.id == itemId; }); if (found !== undefined) { return found[0]; } }, incrementItem (itemId) { let item = this.findItemById(itemId); if (item === undefined) { return; } item.count += 1; this.setState({items: this.state.items}); }, decrementItem (itemId) { let item = this.findItemById(itemId); if (item === undefined) { return; } item.count -= 1; this.setState({items: this.state.items}); }, render () { return (<div> <CartContents ref="contents" items={this.state.items} inc={this.incrementItem} dec={this.decrementItem}/> <CartTotal ref="total" items={this.state.items}/> </div>); } }); export default Cart;
src/components/Book.js
pjamieson/westindiesbooks-react-redux
import React, { Component } from 'react'; import './Book.css'; class Book extends Component { static propTypes = { book: React.PropTypes.object.isRequired }; render() { const book = this.props.book; const summary_paragraphs = []; book.summary.forEach((paragraph) => { summary_paragraphs.push( <p key={paragraph} dangerouslySetInnerHTML={{__html: paragraph}} /> ); }); return ( <div className="Book"> <h5 className="book-title">{book.title}</h5> <p className="book-subtitle">{book.subtitle}</p> <div className="book-summary"> {summary_paragraphs} </div> </div> ); } } export default Book;
app/javascript/mastodon/features/report/components/status_check_box.js
d6rkaiz/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Toggle from 'react-toggle'; import noop from 'lodash/noop'; import StatusContent from '../../../components/status_content'; import { MediaGallery, Video } from '../../ui/util/async-components'; import Bundle from '../../ui/components/bundle'; export default class StatusCheckBox extends React.PureComponent { static propTypes = { status: ImmutablePropTypes.map.isRequired, checked: PropTypes.bool, onToggle: PropTypes.func.isRequired, disabled: PropTypes.bool, }; render () { const { status, checked, onToggle, disabled } = this.props; let media = null; if (status.get('reblog')) { return null; } if (status.get('media_attachments').size > 0) { if (status.get('media_attachments').some(item => item.get('type') === 'unknown')) { } else if (status.getIn(['media_attachments', 0, 'type']) === 'video') { const video = status.getIn(['media_attachments', 0]); media = ( <Bundle fetchComponent={Video} loading={this.renderLoadingVideoPlayer} > {Component => ( <Component preview={video.get('preview_url')} blurhash={video.get('blurhash')} src={video.get('url')} alt={video.get('description')} width={239} height={110} inline sensitive={status.get('sensitive')} onOpenVideo={noop} /> )} </Bundle> ); } else { media = ( <Bundle fetchComponent={MediaGallery} loading={this.renderLoadingMediaGallery} > {Component => <Component media={status.get('media_attachments')} sensitive={status.get('sensitive')} height={110} onOpenMedia={noop} />} </Bundle> ); } } return ( <div className='status-check-box'> <div className='status-check-box__status'> <StatusContent status={status} /> {media} </div> <div className='status-check-box-toggle'> <Toggle checked={checked} onChange={onToggle} disabled={disabled} /> </div> </div> ); } }
public/javascripts/routers/targetSearch.js
helloworldzxy/CarDetection
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, IndexRoute, hashHistory } from 'react-router'; import { HeaderBanner } from '../components/display/headerBanner.js'; import Navigation from '../components/display/navigation.js'; //注意二者引入方式,一个带大括号一个不带 import Motor from '../components/container/motor.js'; require('../../stylesheets/common.css'); class TargetSearch extends Component { //该class继承自Component, 用于下面的Route中 render() { //这里用的是大括号 包裹着函数体 与display/headerBanner.js对比 return <div> <HeaderBanner/> <div className="container"> <Navigation/> <div className="content">{this.props.children}</div> </div> </div>; } } // for test~~~ // ReactDOM.render( // <h1>Hello world~</h1> // , document.getElementById('main')); //不需要路由时可以这么写 // ReactDOM.render( // <div> // <HeaderBanner/> // <div className="container"> // <Navigation/> // <div className="content">targetSearch content targetSearch content targetSearch content</div> // </div> // </div> // , document.getElementById("main")); // const Motor = () => { return <div><div>MotorMotorMotorMotorMotorMotor</div></div>; }; const NonMotor = () => { return <div><div>NonMotorNonMotorNonMotorNonMotorNonMotorNonMotor</div></div>; }; const Staff = () => { return <div><div>StaffStaffStaffStaffStaff</div></div>; }; /* - Router组件有一个参数history,它的值hashHistory表示,路由的切换由URL的hash变化决定,即URL的#部分发生变化。 以下,用户访问localhost:3002/targetSearch,实际会看到的是localhost:3002/targetSearchs/#/; 访问localhost:3002/targetSearch/motor, 实际会看到的是localhost:3002/targetSearchs/#/motor. - 用户访问根路由localhost:3002/targetSearch,组件TargetSearch就会加载到`document.getElementById('main')`. - Route组件可以嵌套。如下,用户访问/motor, 会先加载TargetSearch组件,然后在它内部加载Motor组件。 - 如果不写IndexRoute,则用户访问根路由时,不会加载任何子组件,也即TargetSearch组件的`this.props.children`为`undefined`. */ ReactDOM.render( <Router history={hashHistory}> <Route path="/" component={TargetSearch}> <IndexRoute component={Motor}/> <Route path="/motor" component={Motor}/> <Route path="/nonMotor" component={NonMotor}/> <Route path="/staff" component={Staff}/> </Route> </Router> , document.getElementById('main'));
addons/knobs/src/components/PropField.js
rhalff/storybook
/* eslint-disable no-underscore-dangle */ import PropTypes from 'prop-types'; import React from 'react'; import TypeMap from './types'; const InvalidType = () => <span>Invalid Type</span>; const stylesheet = { field: { display: 'table-row', padding: '5px', }, label: { display: 'table-cell', boxSizing: 'border-box', verticalAlign: 'top', paddingRight: 5, paddingTop: 5, textAlign: 'right', width: 80, fontSize: 12, color: 'rgb(68, 68, 68)', fontWeight: 600, }, }; stylesheet.textarea = { ...stylesheet.input, height: '100px', }; stylesheet.checkbox = { ...stylesheet.input, width: 'auto', }; export default class PropField extends React.Component { constructor(props) { super(props); this._onChange = this.onChange.bind(this); } onChange(e) { this.props.onChange(e.target.value); } render() { const { onChange, onClick, knob } = this.props; const InputType = TypeMap[knob.type] || InvalidType; return ( <div style={stylesheet.field}> <label htmlFor={knob.name} style={stylesheet.label}> {!knob.hideLabel && `${knob.name}`} </label> <InputType knob={knob} onChange={onChange} onClick={onClick} /> </div> ); } } PropField.propTypes = { knob: PropTypes.shape({ name: PropTypes.string, value: PropTypes.any, }).isRequired, onChange: PropTypes.func.isRequired, onClick: PropTypes.func.isRequired, };
app/js/index.js
yukiB/Splarm
import React from 'react' import ReactDOM from 'react-dom' import Container from './components/Container' ReactDOM.render( <Container />, document.getElementById('container') )
src/app.js
blackLearning/react-hackernews
/* 入口启动文件 */ import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import { Router } from 'react-router' import store, { history } from 'STORE' import routes from 'ROUTE' const MOUNT_NODE = document.getElementById('app') // <Provider /> 是由 React Redux 提供的高阶组件,用来让你将 Redux 绑定到 React (详见 搭配 React)。 // 我们将用 <Provider /> 包裹 <Router />,以便于路由处理器可以访问 store // 只要你不需要兼容古老的浏览器,比如IE9,你都可以使用 browserHistory。 // <Provider store> 使组件层级中的 connect() 方法都能够获得 Redux store。 // 正常情况下,你的根组件应该嵌套在 <Provider> 中才能使用 connect() 方法。 ReactDOM.render( <Provider store={store}> <Router history={history} children={routes} /> </Provider>, MOUNT_NODE )
examples/absolute-layout/src/App.js
react-tools/react-table
import React from 'react' import styled from 'styled-components' import { useTable, useAbsoluteLayout } from 'react-table' import makeData from './makeData' const Styles = styled.div` padding: 1rem; * { box-sizing: border-box; } .table { border: 1px solid #000; max-width: 700px; overflow-x: auto; } .header { font-weight: bold; } .rows { overflow-y: auto; } .row { border-bottom: 1px solid #000; height: 32px; &.body { :last-child { border: 0; } } } .cell { height: 100%; line-height: 30px; border-right: 1px solid #000; padding-left: 5px; :last-child { border: 0; } } ` function Table({ columns, data }) { // Use the state and functions returned from useTable to build your UI const defaultColumn = React.useMemo( () => ({ width: 150, }), [] ) const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow, } = useTable( { columns, data, defaultColumn, }, useAbsoluteLayout ) // Render the UI for your table return ( <div {...getTableProps()} className="table"> <div> {headerGroups.map(headerGroup => ( <div {...headerGroup.getHeaderGroupProps()} className="row header-group" > {headerGroup.headers.map(column => ( <div {...column.getHeaderProps()} className="cell header"> {column.render('Header')} </div> ))} </div> ))} </div> <div className="rows" {...getTableBodyProps()}> {rows.map((row, i) => { prepareRow(row) return ( <div {...row.getRowProps()} className="row body"> {row.cells.map((cell, index) => ( <div {...cell.getCellProps()} key={index} className="cell"> {cell.render('Cell')} </div> ))} </div> ) })} </div> </div> ) } function App() { const columns = React.useMemo( () => [ { Header: 'Name', columns: [ { Header: 'First Name', accessor: 'firstName', }, { Header: 'Last Name', accessor: 'lastName', }, ], }, { Header: 'Info', columns: [ { Header: 'Age', accessor: 'age', width: 50, }, { Header: 'Visits', accessor: 'visits', width: 60, }, { Header: 'Status', accessor: 'status', }, { Header: 'Profile Progress', accessor: 'progress', }, ], }, ], [] ) const data = React.useMemo(() => makeData(20), []) return ( <Styles> <Table columns={columns} data={data} /> </Styles> ) } export default App
src/components/Login.js
danesparza/appliance-monitor-cloud
// React import React, { Component } from 'react'; import { Container } from 'reactstrap'; // Components: import PageError from './../components/PageError'; // Stores import LoginPageStore from './../stores/LoginPageStore'; // Auth Utils import CognitoAuthUtils from './../utils/CognitoAuthUtils'; // Button text constants: const buttonNormal = "Sign in"; const buttonSigningIn = "Signing in..."; class Login extends Component { constructor(){ super(); // Set the initial username and password this.state = { Email: '', Password: '', signingIn: false, pageError: LoginPageStore.getError() }; this._onEmailChange = this._onEmailChange.bind(this); this._onPasswordChange = this._onPasswordChange.bind(this); this._onLogin = this._onLogin.bind(this); this._onError = this._onError.bind(this); } componentDidMount(){ // Add store listeners ... and notify ME of changes this.loginListener = LoginPageStore.addListener(this._onError); } componentWillUnmount() { // Remove store listeners this.loginListener.remove(); } render() { // Set the button text: let buttonText = buttonNormal; if(this.state.signingIn) { buttonText = buttonSigningIn; } return ( <div> <Container> <form className="form-signin"> <h3 className="form-signin-heading">Sign in</h3> <PageError error={this.state.pageError} /> <div className="form-group"> <label htmlFor="txtEmail"><strong>Email</strong></label> <input disabled={this.state.signingIn} required autoFocus type="email" id="txtEmail" className="form-control" value={this.state.Email} onChange={this._onEmailChange} maxLength="200" /> </div> <div className="form-group"> <label htmlFor="txtPassword"><strong>Password</strong></label> <input disabled={this.state.signingIn} id="txtPassword" className="form-control" type="password" value={this.state.Password} onChange={this._onPasswordChange} maxLength="200" required/> </div> <button className="btn btn-lg btn-primary btn-block" disabled={this.state.signingIn} onClick={this._onLogin}>{buttonText}</button> <div className="checkbox"> <label> <input type="checkbox" value="remember-me"/> Keep me signed in </label> </div> <div className="a-divider a-divider-break"> <h5>New to Appliance Monitor Cloud?</h5> </div> <a className="btn btn-sm btn-secondary btn-block" href="/#/register">Create your account</a> </form> </Container> </div> ); } _onEmailChange(e){ this.setState({ Email: e.target.value }); } _onPasswordChange(e){ this.setState({ Password: e.target.value }); } _onError(){ this.setState({ pageError: LoginPageStore.getError(), signingIn: false }); } _onLogin(e) { e.preventDefault(); // Lock the form from further modification: this.setState({ signingIn: true }); // Register the user: CognitoAuthUtils.login(this.state.Email, this.state.Password); } } export default Login;
src/app-client.js
cessien/buzzer
// src/app-client.js import React from 'react'; import ReactDOM from 'react-dom'; import AppRoutes from './components/AppRoutes'; window.onload = () => { ReactDOM.render(<AppRoutes/>, document.getElementById('main')); };
src/components/ProgressBar.js
bradparks/filepizza_javascript_send_files_webrtc
import React from 'react' import classnames from 'classnames' function formatProgress(dec) { return (dec * 100).toPrecision(3) + "%" } export default class ProgressBar extends React.Component { render() { const failed = this.props.value < 0; const inProgress = this.props.value < 1 && this.props.value >= 0; const classes = classnames('progress-bar', { 'progress-bar-failed': failed, 'progress-bar-in-progress': inProgress, 'progress-bar-small': this.props.small }) const formatted = formatProgress(this.props.value) return <div className={classes}> {failed ? <div className="progress-bar-text">Failed</div> : inProgress ? <div className="progress-bar-inner" style={{width: formatted}}> <div className="progress-bar-text"> {formatted} </div> </div> : <div className="progress-bar-text">Delivered</div>} </div> } } ProgressBar.propTypes = { value: React.PropTypes.number.isRequired, small: React.PropTypes.bool } ProgressBar.defaultProps = { small: false }
frontend/src/containers/AttackListDetails.js
dionyziz/rupture
import React from 'react'; import AttackItem from './AttackItem'; import _ from 'lodash'; export default class AttackListDetails extends React.Component { constructor() { super(); this.state = { completed: [], runpaused: [] } } deleted = () => { this.props.onReload(); } createAttackItem = (attacks) => { return attacks.map((attack) => { return <AttackItem key={ attack.victim_id } attack={ attack } onReload={ this.deleted }/>; }); } completedAttacks = () => { return( <div> <h2 className='btn' data-toggle='collapse' data-target='#complete'>Completed</h2> <ul className='line collapse in' id='complete'> { this.createAttackItem(this.state.completed) } </ul> </div> ); } runpausedAttacks = () => { return( <div> <h2 className='btn' data-toggle='collapse' data-target='#running'>Running &amp; Paused</h2> <ul className='line collapse in' id='running'> { this.createAttackItem(this.state.runpaused) } </ul> </div> ); } componentDidMount() { if (this.props.attacks) { let attacks = _.partition(this.props.attacks, { state: 'completed' }); this.setState({ completed: attacks[0], runpaused: attacks[1] }); } } render() { return( <div> { this.state.completed.length > 0 ? this.completedAttacks(this.state.completed) : null } { this.state.runpaused.length > 0 ? this.runpausedAttacks(this.state.runpaused) : null } </div> ); } }
frontend/app_v2/src/components/ByAlphabet/ByAlphabetPresentation.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' import { Link } from 'react-router-dom' import DictionaryListPresentation from 'components/DictionaryList/DictionaryListPresentation' import DictionaryGrid from 'components/DictionaryGrid' import AudioButton from 'components/AudioButton' import Tabs from 'components/Tabs' import useIcon from 'common/useIcon' function ByAlphabetPresentation({ actions, characters, currentCharacter, docType, filterResults, infiniteScroll, loadRef, isLoading, items, kids, moreActions, onSortByClick, selectedTab, sitename, sorting, tabs, }) { const getAlphabetList = () => { return characters.map(({ title, id }) => { return ( <Link data-testid={'SearchFilter_' + currentCharacter.id} className={`border col-span-1 font-medium inline-flex justify-center m-1 p-2 rounded-lg shadow text-3xl ${ currentCharacter?.id === id ? 'bg-primary text-white' : '' }`} key={id} to={`/${sitename}/${kids ? 'kids/' : ''}alphabet/${title}?docType=${docType}`} > {title} </Link> ) }) } const getNoResultsMessage = () => { let typeLabel = '' switch (docType) { case 'WORD': typeLabel = 'words' break case 'PHRASE': typeLabel = 'phrases' break default: typeLabel = 'entries' break } return ( <> There are currently no {typeLabel} beginning with{' '} <span className="text-2xl font-bold">{currentCharacter.title}</span> on this language site. </> ) } return ( <> <span className="hidden text-4xl font-bold text-center print:block">{currentCharacter.title}</span> <div className="grid grid-cols-11 md:p-2"> <div className="col-span-11 md:col-span-4 xl:col-span-3 mt-2 md:mt-5 print:hidden"> <div className="hidden md:block xl:p-2"> <div data-testid={'SearchFilter_' + currentCharacter.id} className="font-medium flex justify-center mx-auto p-2 xl:p-4 text-5xl xl:text-7xl text-primary" > {currentCharacter.title} {currentCharacter?.relatedAudio?.[0]?.id && ( <div className="ml-2"> <AudioButton audioArray={[currentCharacter?.relatedAudio?.[0]?.id]} iconStyling={'fill-current h-8 w-8'} /> </div> )} </div> </div> <div className="block md:p-3"> <div className="grid grid-cols-6 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 mx-auto md:pt-5 md:border-t-2 md:border-gray-300"> {getAlphabetList()} </div> </div> {kids ? null : ( <div className="hidden lg:block mt-5"> <h2 className="text-2xl font-medium ml-7 text-fv-charcoal">BROWSE BY:</h2> <ul className="list-none"> <li id={'CategoryLink'} className="inline-block md:block transition duration-500 ease-in-out md:my-3 md:ml-8" > <Link className="transition duration-500 ease-in-out p-3 grow rounded-lg capitalize cursor-pointer text-xl text-fv-charcoal" to={`/${sitename}/categories?docType=${docType}`} > {useIcon('Categories', 'inline-flex fill-current w-8 lg:mr-5')}Categories </Link> </li> <li id={'WordsLink'} className="inline-block md:block transition duration-500 ease-in-out md:my-3 md:ml-8" > <Link className="transition duration-500 ease-in-out p-3 grow rounded-lg capitalize cursor-pointer text-xl text-fv-charcoal" to={`/${sitename}/words`} > {useIcon('Word', 'inline-flex fill-current w-8 lg:mr-5')}Words </Link> </li> <li id={'PhrasesLink'} className="inline-block md:block transition duration-500 ease-in-out md:my-3 md:ml-8" > <Link className="transition duration-500 ease-in-out p-3 grow rounded-lg capitalize cursor-pointer text-xl text-fv-charcoal" to={`/${sitename}/phrases`} > {useIcon('Phrase', 'inline-flex fill-current w-8 lg:mr-5 mb-2')}Phrases </Link> </li> </ul> </div> )} </div> {kids ? ( <div className="min-h-220 col-span-11 md:col-span-7 xl:col-span-8"> <div className="bg-gray-100 p-4"> <DictionaryGrid.Presentation actions={actions} infiniteScroll={infiniteScroll} isLoading={isLoading} items={items} moreActions={moreActions} sitename={sitename} showType={docType === 'WORD_AND_PHRASE'} hasSideNav kids /> </div> </div> ) : ( <div className="min-h-220 col-span-11 md:col-span-7 xl:col-span-8 border-l-2 border-gray-300 md:pl-3 xl:pl-6"> <div className="block py-4"> <div className="flex items-center border-b border-gray-200 px-3 pb-5 print:hidden"> <Tabs.Presentation tabs={tabs} currentTab={selectedTab} setTab={filterResults} accentColor={'primary'} /> </div> <div className="hidden md:block p-2 print:block"> <DictionaryListPresentation actions={actions} infiniteScroll={infiniteScroll} isLoading={isLoading} items={items} moreActions={moreActions} noResultsMessage={getNoResultsMessage()} onSortByClick={onSortByClick} sitename={sitename} sorting={sorting} showType /> </div> <div className="block md:hidden print:hidden"> <DictionaryGrid.Presentation actions={actions} infiniteScroll={infiniteScroll} isLoading={isLoading} items={items} moreActions={moreActions} sitename={sitename} showType={docType === 'WORD_AND_PHRASE'} /> </div> </div> </div> )} </div> <div ref={loadRef} className="w-full h-5" /> </> ) } // PROPTYPES const { array, bool, func, object, string } = PropTypes ByAlphabetPresentation.propTypes = { actions: array, characters: array, currentCharacter: object, docType: string, filterResults: func, infiniteScroll: object, loadRef: object, isLoading: bool, items: object, kids: bool, moreActions: array, onSortByClick: func, selectedTab: object, sitename: string, sorting: object, tabs: array, } export default ByAlphabetPresentation
client/src/index.js
mikelearning91/seeme-starter
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, browserHistory } from 'react-router'; import cookie from 'react-cookie'; import routes from './routes'; import 'bootstrap/dist/css/bootstrap.css'; import './App.css'; // import './js/script.js'; // import './js/jquery.mousewheel.js'; // import './js/disable-scroll.js'; // import ReactGA from 'react-ga'; // import { AUTH_USER } from './actions/types'; // // Import stylesheets // import './public/stylesheets/base.scss'; // // Initialize Google Analytics // ReactGA.initialize('UA-000000-01'); // function logPageView() { // ReactGA.pageview(window.location.pathname); // } // NOT USING REDUX // const token = cookie.load('token'); // if (token) { // // Update application state. User has token and is probably authenticated // store.dispatch({ type: AUTH_USER }); // } ReactDOM.render( <div> <Router history={browserHistory} routes={routes} /> </div>, document.querySelector('.wrapper'));
app/components/NavBarTop.js
BenGoldstein88/portfolio
import React from 'react'; export default class NavBarTop extends React.Component { constructor(props) { super(props); this.handleNavButtonClick = this.handleNavButtonClick.bind(this) } handleNavButtonClick(e) { e.preventDefault() var newView = e.target.getAttribute("name") this.props.onTopNavClick(newView); } render() { return ( <nav className="pt-navbar pt-fixed-top"> <div className="pt-navbar-group pt-align-left"> <button name="home" style={this.props.topNavStyles.home} onClick={this.handleNavButtonClick} className="pt-navbar-heading pt-button pt-minimal"> Ben Goldstein </button> </div> <div className="pt-navbar-group pt-align-right"> <button name="contact" style={this.props.topNavStyles.contact} onClick={this.handleNavButtonClick} className="pt-button pt-minimal"> Contact </button> <button name="projects" style={this.props.topNavStyles.projects} onClick={this.handleNavButtonClick} className="pt-button pt-minimal"> Projects </button> <button name="music" style={this.props.topNavStyles.music} onClick={this.handleNavButtonClick} className="pt-button pt-minimal"> Music </button> <button name="settings" onClick={this.handleNavButtonClick} className="pt-button pt-minimal pt-icon-cog"> </button> </div> </nav> ); } }
frontend/src/components/frame/components/Snackbar.js
jf248/scrape-the-plate
import React from 'react'; import { Snackbar as SnackbarController } from 'controllers/snackbar'; import SnackbarPres from './SnackbarPres'; function Snackbar() { const renderFunc = ({ onClose, isOpen, extraProps }) => { return <SnackbarPres {...{ onClose, isOpen, ...extraProps }} />; }; return <SnackbarController provider render={renderFunc} />; } export default Snackbar;
src/server/helpers/html.js
canonical-ols/build.snapcraft.io
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import ReactDOM from 'react-dom/server'; import Helmet from 'react-helmet'; import { Provider } from 'react-redux'; import { conf } from '../helpers/config'; import style from '../../common/style/vanilla/css/footer.css'; const GAID = conf.get('GOOGLE_ANALYTICS_ID'); const OPTID = conf.get('GOOGLE_OPTIMIZE_ID'); const GTMID = conf.get('GOOGLE_TAG_MANAGER_ID'); const SENTRY_DSN_PUBLIC = conf.get('SENTRY_DSN_PUBLIC'); const googleOptimizePageHideCss = GAID && OPTID ? <style dangerouslySetInnerHTML={{ __html: '.async-hide { opacity: 0 !important}' }} /> : null; const googleOptimizePageHide = GAID && OPTID ? <script dangerouslySetInnerHTML={{ __html: ` (function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date; h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')}; (a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c; })(window,document.documentElement,'async-hide','dataLayer',4000, {'${OPTID}':true});` }} /> : null; const googleAnalytics = GAID && OPTID ? <script dangerouslySetInnerHTML={{ __html: ` (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', '${GAID}', 'auto', {'allowLinker': true}); ga('require', 'linker'); ga('linker:autoLink', ['snapcraft.io', 'build.snapcraft.io', 'dashboard.snapcraft.io', 'conjure-up.io', 'login.ubuntu.com', 'www.ubuntu.com', 'ubuntu.com', 'insights.ubuntu.com', 'developer.ubuntu.com', 'cn.ubuntu.com', 'design.ubuntu.com', 'maas.io', 'canonical.com', 'landscape.canonical.com', 'pages.ubuntu.com', 'tutorials.ubuntu.com', 'docs.ubuntu.com']); ga('require', '${OPTID}');` }} /> : null; const googleTagManager = GTMID ? <script dangerouslySetInnerHTML={{ __html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer', '${GTMID}')` }} /> : null; const googleTagManagerNoScript = GTMID ? <noscript> <iframe src="https://www.googletagmanager.com/ns.html?id=${GTMID}" height="0" width="0" style={{ display: 'none', visibility: 'hidden' }} /> </noscript> : null; export default class Html extends Component { render() { const { assets, store, component, config, csrfToken } = this.props; const preloadedState = store.getState(); const content = component ? this.renderComponent(component, store) : ''; // read Helmet props after component is rendered const head = Helmet.renderStatic(); const attrs = head.htmlAttributes.toComponent(); return ( <html {...attrs}> <head> { googleOptimizePageHideCss } { googleOptimizePageHide } { googleAnalytics } { googleTagManager } {head.title.toComponent()} {head.meta.toComponent()} {head.link.toComponent()} {head.script.toComponent()} <link rel="icon" type="image/png" href="https://assets.ubuntu.com/v1/fdc99abe-ico_16px.png" sizes="16x16" /> <link rel="icon" type="image/png" href="https://assets.ubuntu.com/v1/0f3c662c-ico_32px.png" sizes="32x32" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu:300,400" /> <link rel="stylesheet" href={ assets.main.css } /> { /* Insert third party scripts (e.g. Stripe) here. Trying to load them with Helmet will make them load twice. */ } </head> <body> { googleTagManagerNoScript } <div id="content" className={ style.hasStickyFooter } dangerouslySetInnerHTML={{ __html: content }}/> { SENTRY_DSN_PUBLIC && <script src="https://cdn.ravenjs.com/3.25.1/raven.min.js" crossOrigin="anonymous"></script> } { SENTRY_DSN_PUBLIC && <script dangerouslySetInnerHTML={{ __html: `Raven.config('${ SENTRY_DSN_PUBLIC }').install();` }} /> } <script dangerouslySetInnerHTML={{ __html: `window.__CONFIG__ = ${JSON.stringify(config)}` }} /> <script dangerouslySetInnerHTML={{ __html: `window.__CSRF_TOKEN__ = ${JSON.stringify(csrfToken)}` }} /> <script dangerouslySetInnerHTML={{ __html: `window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState)}` }} /> <script src={ assets.main.js } /> </body> </html> ); } renderComponent(component, store) { return ReactDOM.renderToString( <Provider store={store} key="provider"> { component } </Provider> ); } } Html.propTypes = { config: PropTypes.object, component: PropTypes.node, store: PropTypes.object, csrfToken: PropTypes.string, assets: PropTypes.shape({ main: PropTypes.shape({ js: PropTypes.string, css: PropTypes.string }) }) };
ui/src/containers/Visualisations/components/CustomCard/index.js
LearningLocker/learninglocker
import React from 'react'; import PropTypes from 'prop-types'; import styled, { css } from 'styled-components'; const iconActiveMixin = css` box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3); background: #eee; `; const VisualisationIcon = styled.div` text-align: center; vertical-align: top; display: inline-block; margin: 3px; width: 109px; cursor: pointer; transition: background 0.2s; ${props => props.active && iconActiveMixin || ''} &:hover { background: #eee; } img { width: 100%; } h5 { text-align: center; padding: 0 4px; font-size: 12px; font-weight: bold; margin-top: 0; } `; /** * @param {string} props.title * @param {image file} props.srcImage * @param {boolean} props.active * @param {() => void} props.onClick */ const CustomCard = ({ title, srcImage, active, onClick, }) => ( <VisualisationIcon onClick={onClick} active={active}> <img src={srcImage} alt={title} /> <h5>{title}</h5> </VisualisationIcon> ); CustomCard.propTypes = { title: PropTypes.string.isRequired, srcImage: PropTypes.string.isRequired, active: PropTypes.bool.isRequired, onClick: PropTypes.func.isRequired, }; export default React.memo(CustomCard);
src/components/TodoForm.js
pekkis/react-broilerplate-legacy
import React from 'react'; import uuid from 'node-uuid'; import styles from './TodoForm.pcss'; export default class TodoForm extends React.Component { render() { return ( <div className={styles.root}> <form onSubmit={this.onSubmit.bind(this)}> <label>Got something to do?</label> <input ref="text" type="text" placeholder="What u gonna todo?" /> <button type="submit">Add</button> </form> </div> ); } onSubmit(e) { e.preventDefault(); const newTodo = { id: uuid.v4(), text: this.refs.text.value, category: 0, }; this.refs.text.value = ''; this.props.onAdd(newTodo); } }
webpack/scenes/Subscriptions/Details/SubscriptionDetails.js
cfouant/katello
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { translate as __ } from 'foremanReact/common/I18n'; import { Nav, NavItem, TabPane, TabContent, TabContainer, Grid, Row, Col } from 'patternfly-react'; import BreadcrumbsBar from 'foremanReact/components/BreadcrumbBar'; import SubscriptionDetailInfo from './SubscriptionDetailInfo'; import SubscriptionDetailAssociations from './SubscriptionDetailAssociations'; import SubscriptionDetailProducts from './SubscriptionDetailProducts'; import SubscriptionDetailProductContent from './SubscriptionDetailProductContent'; import { LoadingState } from '../../../move_to_pf/LoadingState'; import { notify } from '../../../move_to_foreman/foreman_toast_notifications'; import api, { orgId } from '../../../services/api'; class SubscriptionDetails extends Component { constructor() { super(); this.handleBreadcrumbSwitcherItem = this.handleBreadcrumbSwitcherItem.bind(this); } componentDidMount() { // eslint-disable-next-line react/prop-types const routerParams = this.props.match.params; this.props.loadSubscriptionDetails(parseInt(routerParams.id, 10)); this.props.loadProducts({ subscription_id: parseInt(routerParams.id, 10), include_available_content: true, enabled: true, }); } componentDidUpdate(prevProps) { const routerParams = this.props.match.params; if (routerParams.id !== prevProps.match.params.id) { this.props.loadSubscriptionDetails(parseInt(routerParams.id, 10)); this.props.loadProducts({ subscription_id: parseInt(routerParams.id, 10), include_available_content: true, enabled: true, }); } } handleBreadcrumbSwitcherItem(e, url) { this.props.history.push(url); e.preventDefault(); } render() { const { subscriptionDetails } = this.props; const resource = { nameField: 'name', resourceUrl: api.getApiUrl(`/organizations/${orgId()}/subscriptions`), switcherItemUrl: '/subscriptions/:id', }; if (subscriptionDetails.error) { notify({ message: subscriptionDetails.error }); } return ( <div> {!subscriptionDetails.loading && <BreadcrumbsBar onSwitcherItemClick={(e, url) => this.handleBreadcrumbSwitcherItem(e, url)} data={{ isSwitchable: true, breadcrumbItems: [ { caption: __('Subscriptions'), onClick: () => this.props.history.push('/subscriptions'), }, { caption: String(subscriptionDetails.name), }, ], resource, }} />} <TabContainer id="subscription-tabs-container" defaultActiveKey={1}> <div> <LoadingState loading={subscriptionDetails.loading} loadingText={__('Loading')}> <Nav bsClass="nav nav-tabs"> <NavItem eventKey={1}> <div>{__('Details')}</div> </NavItem> <NavItem eventKey={2}> <div>{__('Product Content')}</div> </NavItem> </Nav> <Grid bsClass="container-fluid"> <TabContent animation={false}> <TabPane eventKey={1}> <div> <Row> <Col sm={6}> <SubscriptionDetailInfo subscriptionDetails={subscriptionDetails} /> </Col> <Col sm={6}> <SubscriptionDetailAssociations subscriptionDetails={subscriptionDetails} /> <SubscriptionDetailProducts subscriptionDetails={subscriptionDetails} /> </Col> </Row> </div> </TabPane> <TabPane eventKey={2}> <div> <Row> <Col sm={12}> <SubscriptionDetailProductContent productContent={subscriptionDetails.productContent} /> </Col> </Row> </div> </TabPane> </TabContent> </Grid> </LoadingState> </div> </TabContainer> </div> ); } } SubscriptionDetails.propTypes = { loadSubscriptionDetails: PropTypes.func.isRequired, loadProducts: PropTypes.func.isRequired, subscriptionDetails: PropTypes.shape({}).isRequired, history: PropTypes.shape({ push: PropTypes.func.isRequired }).isRequired, match: PropTypes.shape({ params: PropTypes.shape({ id: PropTypes.string.isRequired, }).isRequired, }).isRequired, }; export default SubscriptionDetails;
src/components/Header/HeaderContainer.js
MinisterioPublicoRJ/inLoco-2.0
import React from 'react' import Header from './Header' import { connect } from 'react-redux' import { showMenuLayer } from '../../actions/actions.js' const mapStateToProps = (state) => { return { showTooltipMenu: state.showTooltipMenu, } } const mapDispatchToProps = (dispatch) => { return { onHeaderClick: () => { dispatch(showMenuLayer()) } } } const HeaderContainer = connect( mapStateToProps, mapDispatchToProps, )(Header) export default HeaderContainer
examples/with-redux/src/App.js
casesandberg/react-color
/* eslint-disable no-console */ import React from 'react' import { connect } from 'react-redux' import { actions as appActions } from './reducer' import { SketchPicker } from 'react-color' export const App = ({ color, onChangeColor }) => { return ( <div> <SketchPicker color={ color } onChangeComplete={ onChangeColor } /> </div> ) } const mapStateToProps = state => ({ color: state.color, }) const mapDispatchToProps = { onChangeColor: appActions.changeColor, } export default connect(mapStateToProps, mapDispatchToProps)(App)
src/components/TopPlayers/TopPlayers.js
RetroGameNight/rgn-ui
/* * Retro Game Night * Copyright (c) 2015 Sasha Fahrenkopf, Cameron White * * 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 FluxComponent from 'flummox/component' import Table from '../Table/Table' export default class TopPlayers extends React.Component { render() { return ( <FluxComponent connectToStores={['api']}> <TopPlayersInner {...this.props} /> </FluxComponent> ) } } class TopPlayersInner extends React.Component { render() { const headers = ['Rank', 'Player'] return ( <Table headers={headers}/> ) } }
src/components/portfolio/case_study_items.js
prodigygod0209/prodigygod0209.github.io
import React from 'react'; import Helmet from 'react-helmet'; import Link from 'gatsby-link'; import styled from 'styled-components'; import img from '../../img/showcase_movie-search.png'; const Caselink = styled.a` display: block; width: 80%; opacity: 1; height: 480px; background-color: #1c1d25; position: relative; box-shadow: 0 20px 80px 0 rgba(0, 0, 0, .45); margin-left: auto; margin-right: auto; background-position: 50%; background-size: cover; background-repeat: no-repeat; transition: all .35s ease z-index:1; cursor: pointer; &:before{ position: absolute; left: 0; top: 0; height: 100%; width: 100%; display: block; content: " "; background: #1c1d25; opacity: .85; transition: opacity .3s ease; z-index: 2; } &:hover{ :before{ background-color: rgba(28,29,37,.9); background: linear-gradient(270deg,rgba(35,90,166,.9),rgba(16,27,59,.9)); } } ` const CaseStudyTextSection = styled.div` position: absolute; z-index: 10; left: 90px; bottom: 140px; max-width: 550px; ` const TextTitle = styled.h4` font-size: 45px; font-weight: 400; letter-spacing:2px; color: #fff; ` const Text = styled.p` font-size: 16px; font-wight: 300; color: #fff; opacity: .9; ` const MainButton = styled.button` background: #D24D57; border: 2px solid #D24D57; color: #fff; cursor: pointer; padding: 8px 27px 8px 27px; position: relative; margin-top: 20px; &:after { -webkit-transition: all 0.3s; -moz-transition: all 0.3s; -o-transition: all 0.3s; transition: all 0.3s; height: 0; left: 0; top: 0; width: 100%; background: #D24D57; content: ''; position: absolute; z-index: -1; } &:hover:after { height: 100%; } ` export default function CaseStudyItems (props){ let image = props.image; const styled = { backgroundImage: "url("+image+")", } return ( <li> <Caselink href={props.href} style = {styled}> <CaseStudyTextSection> <TextTitle>{props.title}</TextTitle> <MainButton> Github</MainButton> </CaseStudyTextSection> </Caselink > </li> ) }
src/utils/ValidComponentChildren.js
tonylinyy/react-bootstrap
import React from 'react'; /** * Maps children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The mapFunction provided index will be normalised to the components mapped, * so an invalid component would not increase the index. * * @param {?*} children Children tree container. * @param {function(*, int)} mapFunction. * @param {*} mapContext Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapValidComponents(children, func, context) { let index = 0; return React.Children.map(children, function (child) { if (React.isValidElement(child)) { let lastIndex = index; index++; return func.call(context, child, lastIndex); } return child; }); } /** * Iterates through children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc. * @param {*} forEachContext Context for forEachContext. */ function forEachValidComponents(children, func, context) { let index = 0; return React.Children.forEach(children, function (child) { if (React.isValidElement(child)) { func.call(context, child, index); index++; } }); } /** * Count the number of "valid components" in the Children container. * * @param {?*} children Children tree container. * @returns {number} */ function numberOfValidComponents(children) { let count = 0; React.Children.forEach(children, function (child) { if (React.isValidElement(child)) { count++; } }); return count; } /** * Determine if the Child container has one or more "valid components". * * @param {?*} children Children tree container. * @returns {boolean} */ function hasValidComponent(children) { let hasValid = false; React.Children.forEach(children, function (child) { if (!hasValid && React.isValidElement(child)) { hasValid = true; } }); return hasValid; } export default { map: mapValidComponents, forEach: forEachValidComponents, numberOf: numberOfValidComponents, hasValidComponent };
src/components/locationCard/index.js
nickfranciosi/terminal-frontend
import React from 'react'; import cn from 'classnames'; import styles from './style.module.css'; const LocationCard = ({imgSrc, parentPlace, city, comingSoon, className, style }) => { return ( <div className={cn(styles.card, className)} style={{ backgroundImage: `url(${imgSrc})`, ...style, }} > <div className={styles.textBlock}> <span>{parentPlace}</span> <h2>{city}</h2> </div> {comingSoon && <div className={styles.preview}><span>Coming soon</span></div>} </div> ); } export default LocationCard;
docs/app/Examples/collections/Grid/Variations/GridExampleRelaxedVery.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { Grid, Image } from 'semantic-ui-react' const GridExampleRelaxedVery = () => ( <Grid relaxed='very' columns={4}> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> </Grid> ) export default GridExampleRelaxedVery
src/Portal.js
PeterDaveHello/react-bootstrap
import React from 'react'; import CustomPropTypes from './utils/CustomPropTypes'; import domUtils from './utils/domUtils'; let Portal = React.createClass({ displayName: 'Portal', propTypes: { /** * The DOM Node that the Component will render it's children into */ container: CustomPropTypes.mountable }, componentDidMount() { this._renderOverlay(); }, componentDidUpdate() { this._renderOverlay(); }, componentWillUnmount() { this._unrenderOverlay(); this._unmountOverlayTarget(); }, _mountOverlayTarget() { if (!this._overlayTarget) { this._overlayTarget = document.createElement('div'); this.getContainerDOMNode() .appendChild(this._overlayTarget); } }, _unmountOverlayTarget() { if (this._overlayTarget) { this.getContainerDOMNode() .removeChild(this._overlayTarget); this._overlayTarget = null; } }, _renderOverlay() { let overlay = !this.props.children ? null : React.Children.only(this.props.children); // Save reference for future access. if (overlay !== null) { this._mountOverlayTarget(); this._overlayInstance = React.render(overlay, this._overlayTarget); } else { // Unrender if the component is null for transitions to null this._unrenderOverlay(); this._unmountOverlayTarget(); } }, _unrenderOverlay() { if (this._overlayTarget) { React.unmountComponentAtNode(this._overlayTarget); this._overlayInstance = null; } }, render() { return null; }, getOverlayDOMNode() { if (!this.isMounted()) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } if (this._overlayInstance) { if (this._overlayInstance.getWrappedDOMNode) { return this._overlayInstance.getWrappedDOMNode(); } else { return React.findDOMNode(this._overlayInstance); } } return null; }, getContainerDOMNode() { return React.findDOMNode(this.props.container) || domUtils.ownerDocument(this).body; } }); export default Portal;
test/integration/image-component/default/pages/prose.js
flybayer/next.js
import Image from 'next/image' import React from 'react' import * as styles from './prose.module.css' const Page = () => { return ( <div className={styles.prose}> <p>Hello World</p> <Image id="prose-image" src="/test.jpg" width="400" height="400"></Image> <p id="stubtext">This is the rotated page</p> </div> ) } export default Page
react/gameday2/components/embeds/EmbedLivestream.js
tsteward/the-blue-alliance
import React from 'react' import { webcastPropType } from '../../utils/webcastUtils' const EmbedLivestream = (props) => { const channel = props.webcast.channel const file = props.webcast.file const iframeSrc = `https://new.livestream.com/accounts/${channel}/events/${file}/player?width=640&height=360&autoPlay=true&mute=false` return ( <iframe src={iframeSrc} frameBorder="0" scrolling="no" height="100%" width="100%" /> ) } EmbedLivestream.propTypes = { webcast: webcastPropType.isRequired, } export default EmbedLivestream
node_modules/re-base/examples/firestore/github-notetaker/app/components/Github/UserProfile.js
aggiedefenders/aggiedefenders.github.io
import React from 'react'; import PropTypes from 'prop-types'; class UserProfiles extends React.Component { render() { return ( <div> <h3> User Profile </h3> <ul className="list-group"> {this.props.bio.avatar_url && ( <li className="list-group-item"> <img src={this.props.bio.avatar_url} className="img-rounded img-responsive" /> </li> )} {this.props.bio.name && ( <li className="list-group-item">Name: {this.props.bio.name}</li> )} {this.props.bio.login && ( <li className="list-group-item"> Username: {this.props.bio.login} </li> )} {this.props.bio.email && ( <li className="list-group-item">Email: {this.props.bio.email}</li> )} {this.props.bio.location && ( <li className="list-group-item"> Location: {this.props.bio.location} </li> )} {this.props.bio.company && ( <li className="list-group-item"> Company: {this.props.bio.company} </li> )} {this.props.bio.followers && ( <li className="list-group-item"> Followers: {this.props.bio.followers} </li> )} {this.props.bio.following && ( <li className="list-group-item"> Following: {this.props.bio.following} </li> )} {this.props.bio.following && ( <li className="list-group-item"> Public Repos: {this.props.bio.public_repos} </li> )} {this.props.bio.blog && ( <li className="list-group-item"> Blog: <a href={this.props.bio.blog}> {this.props.bio.blog}</a> </li> )} </ul> </div> ); } } UserProfiles.propTypes = { username: PropTypes.string.isRequired, bio: PropTypes.object.isRequired }; export default UserProfiles;
node_modules/redux-form/es/Form.js
victor335882/ReduxSimpleStarter-4
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React, { Component } from 'react'; import PropTypes from 'prop-types'; var Form = function (_Component) { _inherits(Form, _Component); function Form(props, context) { _classCallCheck(this, Form); var _this = _possibleConstructorReturn(this, (Form.__proto__ || Object.getPrototypeOf(Form)).call(this, props, context)); if (!context._reduxForm) { throw new Error('Form must be inside a component decorated with reduxForm()'); } return _this; } _createClass(Form, [{ key: 'componentWillMount', value: function componentWillMount() { this.context._reduxForm.registerInnerOnSubmit(this.props.onSubmit); } }, { key: 'render', value: function render() { return React.createElement('form', this.props); } }]); return Form; }(Component); Form.propTypes = { onSubmit: PropTypes.func.isRequired }; Form.contextTypes = { _reduxForm: PropTypes.object }; export default Form;
src/client/app/components/Panels/FoodPanel/FoodMenuItem.js
sysart/dashboard
import React from 'react'; import styles from './styles.css'; class FoodMenuItem extends React.Component { constructor(props) { super(props); } render() { const components = this.props.set.components.map((component, index) => { return (<div key={index} className={styles.item}>{component}</div>); }); return ( <div className={styles.container}> {this.props.set.name && ( <div className={styles.name}>{this.props.set.name}</div> )} {components} {this.props.set.price && ( <div className={styles.price}>Hinta: {this.props.set.price}</div> )} </div> ) } } export default FoodMenuItem;
app/components/icons/Favorite.js
buildkite/frontend
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; const starColor = "#f8cc1c"; const StarSVG = styled.svg` .star { fill: ${(props) => props.favorite ? starColor : 'none'}; fill-opacity: 0.3; fill-rule: evenodd; stroke: ${(props) => props.favorite ? starColor : 'currentColor'}; stroke-width: 1px; } &:hover .star { fill: ${(props) => props.favorite ? 'none' : starColor}; stroke: ${starColor}; } `; class Favorite extends React.PureComponent { static propTypes = { favorite: PropTypes.bool.isRequired }; render() { return ( <StarSVG width="20px" height="15px" viewBox="0 0 16 15" favorite={this.props.favorite}> <title>Favorite</title> <g className="star" transform="translate(-1103, -19)"> <polygon points="1111 31 1106.29772 33.472136 1107.19577 28.236068 1103.39155 24.527864 1108.64886 23.763932 1111 19 1113.35114 23.763932 1118.60845 24.527864 1114.80423 28.236068 1115.70228 33.472136" /> </g> </StarSVG> ); } } export default Favorite;
lib/views/TypographySectionView.js
tuomashatakka/reduced-dark-ui
'use babel' import React from 'react' import { Task } from 'atom' import { applyFont } from '../core/configuration' import { QueryField } from '../components/QueryField' import { Icon } from '../components/base' import Field from '../components/layout/Field' import { PACKAGE_NAME } from '../constants' const FontQueryField = (props) => { let { scope } = props let lastChange = Date.now() scope = `${PACKAGE_NAME}.${scope}` let font = atom.config.get(scope) // let {title, description} = atom.config.getSchema(scope) let exeq = (...a) => new Promise(resolve => { let task = Task.once(require.resolve('../proc/provide-fonts.js'), ...a) task.on('load', data => resolve(data)) }) let dispatcher = exeq('families', font, 'google') let content = <label className='control-group'> <Icon icon="ios-arrow-right" iconset='ion' /> Font family <div className='controls'> <QueryField adapter={dispatcher} initialValue={font} onUpdate={val => { let v = val || font // let dt = (Date.now() - lastChange) / 1000 // console.log(v) // if (dt < 1) // return let fontFaceDef = exeq('font-face', v, 'google') atom.config.set(scope, v) // lastChange = Date.now() fontFaceDef.then(data => { applyFont(v, data) }) .catch(e => console.warn("ERROR", e)) }} /> </div> </label> return content } const TypographySection = (props) => { return ( <section className='section'> <FontQueryField scope='decor.uiFont' style='primary' /> <Field scope='decor.uiFontWeight' style='primary' /> <Field scope='env.GOOGLE_API_KEY' style='primary' /> </section> ) } export default TypographySection
examples/active-links/app.js
djkirby/react-router
import React from 'react' import { render } from 'react-dom' import { Router, Route, IndexRoute, Link, IndexLink, browserHistory } from 'react-router' import withExampleBasename from '../withExampleBasename' const ACTIVE = { color: 'red' } const App = ({ children }) => ( <div> <h1>APP!</h1> <ul> <li><Link to="/" activeStyle={ACTIVE}>/</Link></li> <li><IndexLink to="/" activeStyle={ACTIVE}>/ IndexLink</IndexLink></li> <li><Link to="/users" activeStyle={ACTIVE}>/users</Link></li> <li><IndexLink to="/users" activeStyle={ACTIVE}>/users IndexLink</IndexLink></li> <li><Link to="/users/ryan" activeStyle={ACTIVE}>/users/ryan</Link></li> <li><Link to={{ pathname: '/users/ryan', query: { foo: 'bar' } }} activeStyle={ACTIVE}>/users/ryan?foo=bar</Link></li> <li><Link to="/about" activeStyle={ACTIVE}>/about</Link></li> </ul> {children} </div> ) const Index = () => ( <div> <h2>Index!</h2> </div> ) const Users = ({ children }) => ( <div> <h2>Users</h2> {children} </div> ) const UsersIndex = () => ( <div> <h3>UsersIndex</h3> </div> ) const User = ({ params: { id } }) => ( <div> <h3>User {id}</h3> </div> ) const About = () => ( <div> <h2>About</h2> </div> ) render(( <Router history={withExampleBasename(browserHistory, __dirname)}> <Route path="/" component={App}> <IndexRoute component={Index}/> <Route path="/about" component={About}/> <Route path="users" component={Users}> <IndexRoute component={UsersIndex}/> <Route path=":id" component={User}/> </Route> </Route> </Router> ), document.getElementById('example'))
src/app/views/oil.js
nazar/soapee-ui
import _ from 'lodash'; import React from 'react'; import Reflux from 'reflux'; import DocMeta from 'react-doc-meta'; import { Link, State } from 'react-router'; import oilActions from 'actions/oil'; import oilStore from 'stores/oil'; import oilsStore from 'stores/oils'; import calculatorStore from 'stores/calculator'; import oilComments from 'stores/oilComments'; import Spinner from 'components/spinner'; import FacebookComments from 'components/facebookComments'; import ButtonFBLike from 'components/buttonFBLike'; import ButtonGPlusLike from 'components/buttonGPlusLike'; import Commentable from 'components/commentable'; import RecipesLinkTable from 'components/recipesLinkTable'; export default React.createClass( { statics: { willTransitionTo: function ( transition, params ) { oilActions.getOilById( params.id ); } }, mixins: [ State, Reflux.connect( oilStore, 'oil' ), Reflux.connect( oilComments, 'comments' ) ], render() { return ( <div id="oil"> { this.renderLoading() } { this.renderOil() } </div> ); }, renderOil() { let oilName; if ( this.pageIsForRequestedOil() ) { oilName = this.state.oil.name; document.title = `Soapee - ${ oilName }`; return ( <div> <DocMeta tags={ this.tags() } /> <ol className="breadcrumb"> <li><Link to="home">Home</Link></li> <li><Link to="oils">Oils</Link></li> <li className="active">{oilName}</li> </ol> <legend><h1>{oilName}</h1></legend> <div className="row"> <div className="col-sm-4 col-xs-6"> <div className="panel panel-primary"> <div className="panel-heading"> <h3 className="panel-title">Fatty Acids</h3> </div> { this.renderFattyAcids() } </div> </div> <div className="col-sm-3 col-xs-6"> <div className="panel panel-primary"> <div className="panel-heading"> <h3 className="panel-title">Oil Properties</h3> </div> { this.renderProperties() } </div> </div> <div className="col-sm-4 col-xs-6"> <div className="panel panel-primary"> <div className="panel-heading"> <h3 className="panel-title">Saponification Values</h3> </div> { this.renderSaponification() } </div> </div> <div className="col-sm-1 col-xs-6 text-center hidden-xs"> <div className="social"> <ButtonFBLike url={ window.location } /> <ButtonGPlusLike url={ window.location } /> </div> </div> </div> <div className="row" > <div className="col-md-12"> <ul className="nav nav-tabs" role="tablist"> <li role="presentation" className="active"><a href="#in-recipes" aria-controls="in-recipes" role="tab" data-toggle="tab">Used in Recipes</a></li> <li role="presentation"><a href="#comments" aria-controls="comments" role="tab" data-toggle="tab">User Comments {this.countComments()}</a></li> <li role="presentation"><a href="#facebook" aria-controls="facebook" role="tab" data-toggle="tab">Facebook Comments</a></li> </ul> <div className="tab-content"> <div role="tabpanel" className="tab-pane active" id="in-recipes"> { this.renderInRecipes() } </div> <div role="tabpanel" className="tab-pane" id="comments"> <Commentable store={ oilComments } /> </div> <div role="tabpanel" className="tab-pane" id="facebook"> <FacebookComments url={ window.location } /> </div> </div> </div> </div> </div> ); } }, renderSaponification() { let oil = this.state.oil; return ( <div className="properties-container"> <table className="table table-striped table-condensed table-super-condensed"> <tbody> <tr> <td>KOH</td> <td>{oil.sap}</td> </tr> <tr> <td>NaOH</td> <td>{calculatorStore.sapForNaOh(oil)}</td> </tr> </tbody> </table> </div> ); }, renderFattyAcids() { let oil = this.state.oil; let labels = { saturated: 'Saturated', monoSaturated: 'Mono-unsaturated', polySaturated: 'Poly-unsaturated' }; let breakdowns = _.transform( oilsStore.getAllFats(), ( output, fat ) => { let breakdown = oil.breakdown[ fat ]; if ( breakdown ) { output.push( <tr> <td>{_.capitalize(fat)}</td> <td>{breakdown}%</td> </tr> ); } }, [] ); let saturations = _( oil.saturation ) .pick( 'saturated', 'monoSaturated', 'polySaturated' ) .map( ( satType, saturation ) => { return ( <tr> <td>{ labels[ saturation ] }:</td> <td>{ satType }%</td> </tr> ); } ) .value(); let ratios = `${oil.saturation.saturated} : ${ 100 - oil.saturation.saturated }`; let ratiosRow = ( <tr> <td>Saturation Ratio</td> <td>{ ratios }</td> </tr> ); return ( <div className="properties-container"> <table className="table table-striped table-condensed table-super-condensed"> <tbody> { breakdowns } { this.gap() } { saturations } { this.gap() } { ratiosRow } </tbody> </table> </div> ); }, renderProperties() { let oil = this.state.oil; let properties; function render( property ) { return ( <tr> <td>{_.capitalize( property )}</td> <td>{oil.properties[ property ]}%</td> </tr> ); } properties = _( oil.properties ) .keys() .sort() .map( render, this ) .value(); return ( <div className="properties-container"> <table className="table table-striped table-condensed table-super-condensed"> <tbody> { properties } </tbody> </table> </div> ); }, renderInRecipes() { let oil = this.state.oil; if ( oil.recipes && oil.recipes.length ) { return ( <RecipesLinkTable recipes={ oil.recipes } /> ); } else { return ( <div>Not used in any recipes.</div> ); } }, countComments() { let count = oilComments.count(); if ( count ) { return <span>({ count })</span>; } }, renderLoading() { if ( !(this.pageIsForRequestedOil()) ) { return <Spinner />; } }, pageIsForRequestedOil() { let requested = Number( this.getParams().id ); let got = Number( _.get( this.state.oil, 'id' ) ); return requested === got; }, gap() { return ( <tr> <td colSpan="2"></td> </tr> ); }, tags() { let description = `Soapee Oil - ${ this.state.oil.name }`; return [ {name: 'description', content: description}, {name: 'twitter:card', content: description}, {name: 'twitter:title', content: description}, {property: 'og:title', content: description} ]; } } );
src/containers/App/AppView.js
amaurymartiny/react-redux-auth0-kit
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Switch, Route } from 'react-router-dom'; import Header from '../Header/Header'; import HomePage from '../../components/HomePage/HomePage'; import AboutPage from '../../components/AboutPage/AboutPage'; import NotFoundPage from '../../components/NotFoundPage/NotFoundPage'; import * as AuthService from '../../utils/AuthService'; class AppView extends Component { static propTypes = { history: PropTypes.shape({ push: PropTypes.func.isRequired }).isRequired, loginError: PropTypes.func.isRequired, loginSuccess: PropTypes.func.isRequired }; componentWillMount() { const { history, loginError, loginSuccess } = this.props; // Add callback for lock's `authenticated` event AuthService.lock.on('authenticated', authResult => { AuthService.lock.getUserInfo(authResult.accessToken, (error, profile) => { if (error) { return loginError(error); } AuthService.setToken(authResult.idToken); // static method AuthService.setProfile(profile); // static method loginSuccess(profile); history.push({ pathname: '/' }); AuthService.lock.hide(); }); }); // Add callback for lock's `authorization_error` event AuthService.lock.on('authorization_error', error => { loginError(error); history.push({ pathname: '/' }); }); } render() { return ( <div> <Header /> <Switch> <Route exact path="/" component={HomePage} /> <Route path="/about" component={AboutPage} /> <Route component={NotFoundPage} /> </Switch> </div> ); } } export default AppView;
src/Notification1B/index.js
DuckyTeam/ducky-components
import Icon from '../Icon'; import Wrapper from '../Wrapper'; import NotificationItem from '../NotificationItem'; import React from 'react'; import PropTypes from 'prop-types'; import styles from './styles.css'; function Notification1B(props) { return ( <NotificationItem buttonClicked={props.buttonClicked} buttonText={props.buttonText} children={props.children} className={props.className} dateTime={props.dateTime} icon={props.icon} name={props.name} onClick={props.onClick} seen={props.seen} text={props.text} textBeforeName={props.textBeforeName} type={props.type} > <Icon className={styles.icon} size={'standard'} icon={props.mainIcon} /> </NotificationItem> ); } Notification1B.propTypes = { buttonClicked: PropTypes.func, buttonText: PropTypes.string, children: PropTypes.node, className: PropTypes.string, dateTime: PropTypes.string, disabled: PropTypes.bool, icon: PropTypes.string, mainIcon: PropTypes.string, name: PropTypes.string, onClick: PropTypes.func, seen: PropTypes.bool, size: PropTypes.oneOf(['standard', 'main']), text: PropTypes.string, textBeforeName: PropTypes.string, type: PropTypes.string }; export default Notification1B;
src/docs/components/topology/TopologyDoc.js
grommet/grommet-docs
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Topology from 'grommet/components/Topology'; import Box from 'grommet/components/Box'; import Button from 'grommet/components/Button'; import DocsArticle from '../../../components/DocsArticle'; export default class TopologyDoc extends Component { render () { return ( <DocsArticle title='Topology' action={ <Button primary={true} path='/docs/topology/examples' label='Examples' /> }> <section> <p>Visualize structure and connectivity.</p> <Box align='start' pad='medium'> <Topology links={[ {colorIndex: 'graph-1', ids: ['p1', 'p2']} ]}> <Topology.Parts> <Topology.Part id='p1' status='ok' label='1' align='center' /> <Topology.Part id='p2' status='ok' label='2' align='center' /> </Topology.Parts> </Topology> </Box> </section> <section> <h2>Properties</h2> <dl> <dt><code>links {'[{...}]'}</code></dt> <dd>An array of: <code> {'{ids: [<id>, ...], colorIndex: <string>}'} </code>. The ids should reference id properties of contained Topology.Part components.</dd> </dl> </section> <section> <h2>Available Sub Components</h2> <h3>Toplogy.Part</h3> <p>An individual part. I Part can contain Parts or another Part.</p> <h4>Properties</h4> <dl> <dt><code>align start|center|between|end|stretch</code></dt> <dd>How to align the contents along the cross axis.</dd> <dt><code>demarcate true|false</code></dt> <dd>Whether or not to visually demarcate the boundaries of the Part.</dd> <dt><code>direction row|column</code></dt> <dd>The orientation to layout any child components in.</dd> <dt><code>id {'{string}'}</code></dt> <dd>The id of this part. The id should at least be unique within the Topology.</dd> <dt><code>justify start|center|between|end</code></dt> <dd>How to align the contents along the main axis.</dd> <dt><code>label {'{string}'}</code></dt> <dd>The label of this part. This could be a part name or number, for example.</dd> <dt><code>reverse true|false</code></dt> <dd>Whether to reverse the order of the child components.</dd> <dt><code>status error|warning|ok|disabled|unknown</code></dt> <dd>If provided, adds the corresponding status icon.</dd> </dl> <h3>Toplogy.Parts</h3> <p>A container for Part components. It is provided purely to assist with Part layout.</p> <h4>Properties</h4> <dl> <dt><code>direction row|column</code></dt> <dd>The orientation to layout the child components in.</dd> <dt><code>uniform true|false</code></dt> <dd>Whether or not to all children should be the same size.</dd> </dl> <h3>Toplogy.Label</h3> <p>A label. It provides finer control over how Part labels are rendered.</p> </section> </DocsArticle> ); } };
src/decorators/HashTag/index.js
michalko/draft-wyswig
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import './styles.css'; class Hashtag { constructor(config) { this.className = config.className; this.hashCharacter = config.hashCharacter || '#'; this.separator = config.separator || ' '; } getHashtagComponent = () => { const className = this.className; const HashtagComponent = ({ children }) => { const text = children[0].props.text; return ( <a href={text} className={classNames('rdw-hashtag-link', className)}> {children} </a> ); }; HashtagComponent.propTypes = { children: PropTypes.object, }; return HashtagComponent; }; findHashtagEntities = (contentBlock, callback) => { let text = contentBlock.getText(); let startIndex = 0; let counter = 0; for (;text.length > 0 && startIndex >= 0;) { if (text[0] === this.hashCharacter) { startIndex = 0; counter = 0; text = text.substr(this.hashCharacter.length); } else { startIndex = text.indexOf(this.separator + this.hashCharacter); if (startIndex >= 0) { text = text.substr(startIndex + (this.separator + this.hashCharacter).length); counter += startIndex + this.separator.length; } } if (startIndex >= 0) { const endIndex = text.indexOf(this.separator) >= 0 ? text.indexOf(this.separator) : text.length; const hashtagText = text.substr(0, endIndex); if (hashtagText && hashtagText.length > 0) { callback(counter, counter + hashtagText.length + this.hashCharacter.length); counter += this.hashCharacter.length; } } } }; getHashtagDecorator = () => ({ strategy: this.findHashtagEntities, component: this.getHashtagComponent(), }); } const getDecorator = config => (new Hashtag(config)).getHashtagDecorator(); module.exports = getDecorator;
blueocean-material-icons/src/js/components/svg-icons/image/blur-linear.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageBlurLinear = (props) => ( <SvgIcon {...props}> <path d="M5 17.5c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5-1.5.67-1.5 1.5.67 1.5 1.5 1.5zM9 13c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0-4c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zM3 21h18v-2H3v2zM5 9.5c.83 0 1.5-.67 1.5-1.5S5.83 6.5 5 6.5 3.5 7.17 3.5 8 4.17 9.5 5 9.5zm0 4c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5-1.5.67-1.5 1.5.67 1.5 1.5 1.5zM9 17c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm8-.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zM3 3v2h18V3H3zm14 5.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zm0 4c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zM13 9c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0 4c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0 4c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1z"/> </SvgIcon> ); ImageBlurLinear.displayName = 'ImageBlurLinear'; ImageBlurLinear.muiName = 'SvgIcon'; export default ImageBlurLinear;
src/app/components/footer/index.js
jackyzhen/coffee-tracker
import React from 'react'; export default function Footer() { return ( <div /> ); } Footer.displayName = 'Header'; Footer.propTypes = { };
src/view/dashboard/components/quote.js
fishmankkk/mircowater2.0
import React from 'react' import PropTypes from 'prop-types' import styles from './quote.less' function Quote ({ name, content, title, avatar }) { return ( <div className={styles.quote}> <div className={styles.inner}> {content} </div> <div className={styles.footer}> <div className={styles.description}> <p>-{name}-</p> <p>{title}</p> </div> <div className={styles.avatar} style={{ backgroundImage: `url(${avatar})` }} /> </div> </div> ) } Quote.propTypes = { name: PropTypes.string, content: PropTypes.string, title: PropTypes.string, avatar: PropTypes.string, } export default Quote
react-native-app/src/components/art/easeTitle.js
nnecec/laboratory
import React from 'react'; import { Animated, Text, View } from 'react-native'; class EaseTitle extends React.Component { state = { fadeAnim: new Animated.Value(0), // Initial value for opacity: 0 } componentDidMount() { Animated.spring( // Animate over time this.state.fadeAnim, // The animated value to drive { toValue: 1, // Animate to opacity: 1 (opaque) duration: 4000, // Make it take a while } ).start(); // Starts the animation } render() { let { fadeAnim } = this.state; return ( <Animated.View style={{ ...this.props.style, transfrom: [{ translateY: fadeAnim }], }} > {this.props.children} </Animated.View> ); } } export default EaseTitle
src/routes.js
zebogen/film-bff-client
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import FilmBffLayout from 'layouts/FilmBffLayout'; import HomeContainer from 'containers/HomeContainer'; import LoginContainer from 'containers/LoginContainer'; import WatchListsEditor from 'containers/WatchListsEditor'; import PublicWatchLists from 'containers/PublicWatchLists'; import UserProfile from 'containers/UserProfile'; export default ( <Route path="/" component={FilmBffLayout}> <IndexRoute component={HomeContainer} /> <Route path="login" component={LoginContainer} /> <Route path="watchlists" component={WatchListsEditor} /> <Route path="public_lists" component={PublicWatchLists} /> <Route path="users/:id" component={UserProfile} /> </Route> );
src/TimePicker.js
mohitgupta8888/react-timepicker
import React from 'react' import onClickOutside from 'react-onclickoutside' import {parseSettings} from './Utils/Settings' import TimeParser from './Utils/TimeParser' import lang from './Lang' var globalSettings; var defaults = { className: null, maxTime: null, minTime: null, selectOnBlur: false, step: 30, timeFormat: 'g:ia', typeaheadHighlight: true, useSelect: false, wrapHours: true } class TimePicker extends React.Component { constructor(props) { super(props); var settings = Object.assign({}, defaults, props); if (settings.lang) { Object.assign(lang, settings.lang); } globalSettings = parseSettings(settings); var timeOptions = TimeParser.prepareTimeOptions({ timeFormat: globalSettings.timeFormat, step: globalSettings.step, minTime: globalSettings.minTime, maxTime: globalSettings.maxTime }) var defaultIndex; if (props.value && !globalSettings.useSelect) { //this.formatValue(); defaultIndex = this.getDefaultIndex(timeOptions, props.value); } this.state = { value: props.value, timeOptions: timeOptions, selectedIndex: defaultIndex } this.keydownhandler = this.keydownhandler.bind(this); this.keyuphandler = this.keyuphandler.bind(this); } getDefaultIndex(timeOptions, timeString) { if (timeString === "") { return; } var settings = globalSettings; var seconds = TimeParser.time2int(timeString, settings.wrapHours); var selectedOption = this.findTimeOption(timeOptions, seconds); if (selectedOption) return selectedOption.index; } findTimeOption(timeOptions, timeInt) { if (!timeInt && timeInt !== 0) { return false; } var settings = globalSettings; var out = false; var timeInt = TimeParser.roundingFunction(timeInt, settings.step); // loop through the menu items timeOptions.every(function (timeOption, index) { if (timeOption.timeInt == timeInt) { out = timeOption; return false; } return true; }, this); return out; } setSelected() { var timeValue = TimeParser.time2int(this.state.value, globalSettings.wrapHours); if (timeValue === null) { return; } var selected = this.findTimeOption(this.state.timeOptions, timeValue); if (selected) { this.setState({ selectedIndex: selected.index }); } } formatValue() { if (this.state.value === '') { return; } var settings = globalSettings; var seconds = TimeParser.time2int(this.state.value, settings.wrapHours); if (seconds === null) { if (this.props.timeFormatError) this.props.timeFormatError(); return; } var rangeError = false; // check that the time in within bounds if ((settings.minTime !== null && settings.maxTime !== null) && (seconds < settings.minTime || seconds > settings.maxTime)) { rangeError = true; } var prettyTime = TimeParser.int2time(seconds, settings.timeFormat); if (rangeError) { if (this.setTimeValue(prettyTime)) { if (this.props.timeRangeError) this.props.timeRangeError(); } } else { this.setTimeValue(prettyTime); } } setTimeValue(prettyTime) { if (this.props.onSelect) this.props.onSelect(prettyTime); } getSelectedIndexValue() { if (typeof this.state.selectedIndex === "undefined") return; return ((this.state.timeOptions[this.state.selectedIndex]).timeString); } setSelectedIndexValue() { var prettyTime = this.getSelectedIndexValue(); this.setState({ value: prettyTime }, () => { this.setTimeValue(prettyTime) }) } changeSelectedIndex(change) { if (!this.state.timeOptions) return; var optionsLength = this.state.timeOptions.length; if (optionsLength == 0) return; var currentIndex = this.state.selectedIndex; var newIndex = currentIndex + change; if (change == -1) { if (currentIndex <= 0) { newIndex = optionsLength - 1; } } else if (change == 1) { if (currentIndex === optionsLength - 1) { newIndex = 0; } } this.setState({ selectedIndex: newIndex }); } /* * Keyboard navigation via arrow keys */ keydownhandler(e) { switch (e.keyCode) { case 13: // return this.setSelectedIndexValue(); e.preventDefault(); return false; case 38: // up this.changeSelectedIndex(-1) return false; case 40: // down this.changeSelectedIndex(1) return false; case 9: //tab this.close(); break; case 27: // escape this.close(); break; default: return true; } } /* * Time typeahead */ keyuphandler(e) { var settings = globalSettings; switch (e.keyCode) { case 96: // numpad numerals case 97: case 98: case 99: case 100: case 101: case 102: case 103: case 104: case 105: case 48: // numerals case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 65: // a case 77: // m case 80: // p case 186: // colon case 8: // backspace case 46: // delete if (settings.typeaheadHighlight) { this.setSelected(); } else { //list.hide(); } break; } } scrollToIndex() { if (typeof this.state.selectedIndex !== "number") return; var timeOptions = this.state.timeOptions.length; var container = this.container; if (!container) return; var scrollHeight = container.scrollHeight; var scrollRatio = Math.floor(scrollHeight / timeOptions) container.scrollTop = ((this.state.selectedIndex * scrollRatio) - Math.floor(container.clientHeight / 2)); } componentDidMount() { //this.setSelected(); window.addEventListener("keydown", this.keydownhandler); window.addEventListener("keyup", this.keyuphandler); this.scrollToIndex(); } componentDidUpdate() { this.scrollToIndex(); } componentWillUnmount() { var timeValue = TimeParser.time2int(this.state.value, globalSettings.wrapHours); if (timeValue !== null) { var prettyTime = TimeParser.int2time(timeValue, globalSettings.timeFormat); this.setTimeValue(prettyTime); } window.removeEventListener("keydown", this.keydownhandler); window.removeEventListener("keyup", this.keyuphandler); } componentWillReceiveProps(nextProps) { // if (nextProps.value == "0524") { // debugger; // } var timeValue = TimeParser.time2int(nextProps.value, globalSettings.wrapHours); var selectedTimeOption = this.findTimeOption(this.state.timeOptions, timeValue); var selectedIndex = selectedTimeOption ? selectedTimeOption.index : null; this.setState({ value: nextProps.value, selectedIndex: selectedIndex }); } close() { if (this.props.onClose) this.props.onClose(); } onTimeSelect(prettyTime, index) { this.setState({ selectedIndex: index, value: prettyTime }, () => { this.setTimeValue(prettyTime) }) } getListOptions() { var settings = globalSettings; var listOptions = []; this.state.timeOptions.forEach(function (timeOption, index) { var timeInt = timeOption.timeInt; var timeString = timeOption.timeString; if (settings.useSelect) { var row = <option key={index} value={timeString}>{timeString}</option> } else { var rowCssClass = timeInt % 86400 < 43200 ? 'ui-timepicker-am' : 'ui-timepicker-pm'; if (this.state.selectedIndex == index) rowCssClass = rowCssClass + " ui-timepicker-selected"; var timeIntVal = (timeInt <= 86400 ? timeInt : timeInt % 86400); var row = <li key={index} className={rowCssClass} onClick={this.onTimeSelect.bind(this, timeString, index) }>{timeString}</li> } listOptions.push(row); }, this); return listOptions; } handleClickOutside(evt) { // ..handling code goes here... if (this.props.inputRef && evt.target.isSameNode(this.props.inputRef)) return; this.close(); } render() { if (!this.state.timeOptions instanceof (Array)) return null; var settings = globalSettings; var listOptions = this.getListOptions(); var reactControl; var controlCss = []; if (settings.className) controlCss.push(settings.className); if (settings.useSelect) { controlCss.push("ui-timepicker-select"); reactControl = ( <select className={controlCss.join(" ") }> {listOptions} </select> ); } else { controlCss.push("ui-timepicker-wrapper"); reactControl = ( <div className={controlCss.join(" ") } tabIndex="-1" style={{ position: "absolute" }} ref={(container) => this.container = container}> <ul className="ui-timepicker-list"> {listOptions} </ul> </div> ) } return reactControl; } } export default onClickOutside(TimePicker)
docs/app/Examples/modules/Accordion/Usage/index.js
koenvg/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' import { Message } from 'semantic-ui-react' const AccordionUsageExamples = () => ( <ExampleSection title='Usage'> <ComponentExample title='Active Index' description='The `activeIndex` prop controls which panel is open.' examplePath='modules/Accordion/Usage/AccordionExampleActiveIndex' > <Message info> An <code>active</code> prop on an {' '}<code>&lt;Accordion.Title&gt;</code> or <code>&lt;Accordion.Content&gt;</code> {' '}will override the <code>&lt;Accordion&gt;</code> <code>&lt;activeIndex&gt;</code> prop. </Message> </ComponentExample> <ComponentExample title='Panels Prop with custom title and content' examplePath='modules/Accordion/Usage/AccordionExamplePanelsPropWithCustomTitleAndContent' /> </ExampleSection> ) export default AccordionUsageExamples
examples/huge-apps/routes/Course/routes/Assignments/routes/Assignment/components/Assignment.js
mjw56/react-router
import React from 'react'; class Assignment extends React.Component { render () { var { courseId, assignmentId } = this.props.params; var { title, body } = COURSES[courseId].assignments[assignmentId] return ( <div> <h4>{title}</h4> <p>{body}</p> </div> ); } } export default Assignment;
app/js/components/source/changeLanguage.js
jagatjeevan/dakiya
// Frameworks import React from 'react'; import Cookie from 'js-cookie'; function changeLanguage(lang) { Cookie.set('lang', lang); /* eslint no-def: 0 */ location.reload(); } const ChooseLanguage = () => ( <div className="language-selector"> <button onClick={() => changeLanguage('en')}>English</button> <button onClick={() => changeLanguage('fr')}>Français</button> </div> ); export default ChooseLanguage;
src/svg-icons/action/swap-vert.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSwapVert = (props) => ( <SvgIcon {...props}> <path d="M16 17.01V10h-2v7.01h-3L15 21l4-3.99h-3zM9 3L5 6.99h3V14h2V6.99h3L9 3z"/> </SvgIcon> ); ActionSwapVert = pure(ActionSwapVert); ActionSwapVert.displayName = 'ActionSwapVert'; ActionSwapVert.muiName = 'SvgIcon'; export default ActionSwapVert;
src/renderer/index.js
venobo/app
console.time('init') import debounce from 'debounce' import {clipboard, remote, ipcRenderer} from 'electron' import React from 'react' import ReactDOM from 'react-dom' //import {error, log} from './lib/logger' import MetadataAdapter from './api/metadata/adapter' import dispatch, {setupDispatchHandlers} from './lib/dispatcher' import crashReporter from '../crashReporter' import State from './lib/state' import createApp from './app' import createStore from './redux/store' import sound from './lib/sound' import config from '../config' import HTTP from './lib/http' class Renderer { store: Object cast: Object state: Object api: Object dispatchHandlers: Object constructor() { // Initialize crash reporter crashReporter() // Load state State.load((err, state) => { if (err) throw new Error(err) this.onState(state) }) } onState(state) { // Make available for easier debugging this.state = state //const _telemetry = this.telemetry = new Telemetry(state) // Log uncaught JS errors /*window.addEventListener( 'error', (e) => _telemetry.logUncaughtError('window', e), true )*/ // Create Redux store this.store = createStore(state) // Setup dispatch handlers setupDispatchHandlers(state, this.store) // Setup MetadataAdapter MetadataAdapter.setup(state) // Setup API HTTP this.api = new HTTP({ baseURL: config.APP.API }) // Setup App this.setupApp() // Listen for messages from the main process this.setupIpc() // ...focus and blur. Needed to show correct dock icon text ('badge') in OSX window.addEventListener('focus', (e) => this.onFocus(e)) window.addEventListener('blur', (e) => this.onBlur(e)) if (remote.getCurrentWindow().isVisible()) { sound('STARTUP') } // To keep app startup fast, some code is delayed. window.setTimeout(() => this.delayedInit(), config.DELAYED_INIT) // Done! Ideally we want to get here < 700ms after the user clicks the app console.timeEnd('init') } // Runs a few seconds after the app loads, to avoid slowing down startup time delayedInit() { //const {telemetry} = this //telemetry.send(this.state) // Send Telemetry data every 6 hours, for users who keep the app running // for extended periods of time //setInterval(() => telemetry.send(state), 6 * 3600 * 1000) // Warn if the download dir is gone, eg b/c an external drive is unplugged dispatch('checkDownloadPath') // ...window visibility state. document.addEventListener('webkitvisibilitychange', () => this.onVisibilityChange()) this.onVisibilityChange() this.lazyLoadCast() } lazyLoadCast() { let {cast, update, state} = this if (!cast) { cast = require('./lib/cast') cast.init(state) } return cast } // Some state changes can't be reflected in the DOM, instead we have to // tell the main process to update the window or OS integrations /*updateElectron() { const {window, prev, dock} = this.state if (window.title !== prev.title && window.title !== null) { prev.title = window.title ipcRenderer.send('setTitle', window.title) } if (dock.progress.toFixed(2) !== prev.progress.toFixed(2)) { prev.progress = dock.progress ipcRenderer.send('setProgress', dock.progress) } if (dock.badge !== prev.badge) { prev.badge = dock.badge ipcRenderer.send('setBadge', dock.badge || 0) } }*/ setupApp() { const { state, store, api } = this const { iso2 } = state.saved.prefs api.fetchCache(`translation/${iso2}`) .then(translation => createApp(store, state, translation)) .catch(err => { dispatch('error', err) const path = require('path') const fs = require('fs') let translation try { let translationFile = fs.readFileSync(path.join(config.PATH.TRANSLATIONS, `${iso2}.json`), 'utf-8') translation = JSON.parse(translationFile) } catch(e) { throw e } createApp(store, state, translation) }) } setupIpc() { const ipc = ipcRenderer ipc.on('log', (e, ...args) => console.log(...args)) ipc.on('error', (e, ...args) => console.error(...args)) ipc.on('dispatch', (e, ...args) => dispatch(...args)) ipc.on('fullscreenChanged', (e, ...args) => this.onFullscreenChanged(e, ...args)) ipc.on('windowBoundsChanged', (e, ...args) => this.onWindowBoundsChanged(e, ...args)) ipc.send('ipcReady') State.on('stateSaved', () => ipc.send('stateSaved')) } onFocus(e) { const {state} = this state.window.isFocused = true state.dock.badge = 0 //this.update() } onBlur() { this.state.window.isFocused = false //this.update() } onVisibilityChange() { this.state.window.isVisible = !document.webkitHidden } onFullscreenChanged(e, isFullScreen) { const {state} = this state.window.isFullScreen = isFullScreen if (!isFullScreen) { // Aspect ratio gets reset in fullscreen mode, so restore it (Mac) ipcRenderer.send('setAspectRatio', state.playing.aspectRatio) } //this.update() } onWindowBoundsChanged(e, newBounds) { const {state, dispatch} = this if (state.location.pathname !== '/player') { state.saved.bounds = newBounds dispatch('stateSave') } } } export default new Renderer
src/index.js
taggartbg/connectjs2015
import ReactDOM from 'react-dom'; import React from 'react'; import List from './List'; ReactDOM.render(<List />, document.getElementById('root'));
public/assets/js/node_modules/react-router/es6/IndexLink.js
ngocson8b/6jar
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; }; import React from 'react'; import Link from './Link'; /** * An <IndexLink> is used to link to an <IndexRoute>. */ var IndexLink = React.createClass({ displayName: 'IndexLink', render: function render() { return React.createElement(Link, _extends({}, this.props, { onlyActiveOnIndex: true })); } }); export default IndexLink;
app/javascript/mastodon/features/notifications/components/notification.js
clworld/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import StatusContainer from '../../../containers/status_container'; import AccountContainer from '../../../containers/account_container'; import { injectIntl, FormattedMessage } from 'react-intl'; import Permalink from '../../../components/permalink'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { HotKeys } from 'react-hotkeys'; import Icon from 'mastodon/components/icon'; const notificationForScreenReader = (intl, message, timestamp) => { const output = [message]; output.push(intl.formatDate(timestamp, { hour: '2-digit', minute: '2-digit', month: 'short', day: 'numeric' })); return output.join(', '); }; export default @injectIntl class Notification extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { notification: ImmutablePropTypes.map.isRequired, hidden: PropTypes.bool, onMoveUp: PropTypes.func.isRequired, onMoveDown: PropTypes.func.isRequired, onMention: PropTypes.func.isRequired, onFavourite: PropTypes.func.isRequired, onReblog: PropTypes.func.isRequired, onToggleHidden: PropTypes.func.isRequired, status: ImmutablePropTypes.map, intl: PropTypes.object.isRequired, getScrollPosition: PropTypes.func, updateScrollBottom: PropTypes.func, cacheMediaWidth: PropTypes.func, cachedMediaWidth: PropTypes.number, }; handleMoveUp = () => { const { notification, onMoveUp } = this.props; onMoveUp(notification.get('id')); } handleMoveDown = () => { const { notification, onMoveDown } = this.props; onMoveDown(notification.get('id')); } handleOpen = () => { const { notification } = this.props; if (notification.get('status')) { this.context.router.history.push(`/statuses/${notification.get('status')}`); } else { this.handleOpenProfile(); } } handleOpenProfile = () => { const { notification } = this.props; this.context.router.history.push(`/accounts/${notification.getIn(['account', 'id'])}`); } handleMention = e => { e.preventDefault(); const { notification, onMention } = this.props; onMention(notification.get('account'), this.context.router.history); } handleHotkeyFavourite = () => { const { status } = this.props; if (status) this.props.onFavourite(status); } handleHotkeyBoost = e => { const { status } = this.props; if (status) this.props.onReblog(status, e); } handleHotkeyToggleHidden = () => { const { status } = this.props; if (status) this.props.onToggleHidden(status); } getHandlers () { return { reply: this.handleMention, favourite: this.handleHotkeyFavourite, boost: this.handleHotkeyBoost, mention: this.handleMention, open: this.handleOpen, openProfile: this.handleOpenProfile, moveUp: this.handleMoveUp, moveDown: this.handleMoveDown, toggleHidden: this.handleHotkeyToggleHidden, }; } renderFollow (notification, account, link) { const { intl } = this.props; return ( <HotKeys handlers={this.getHandlers()}> <div className='notification notification-follow focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage({ id: 'notification.follow', defaultMessage: '{name} followed you' }, { name: account.get('acct') }), notification.get('created_at'))}> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <Icon id='user-plus' fixedWidth /> </div> <span title={notification.get('created_at')}> <FormattedMessage id='notification.follow' defaultMessage='{name} followed you' values={{ name: link }} /> </span> </div> <AccountContainer id={account.get('id')} withNote={false} hidden={this.props.hidden} /> </div> </HotKeys> ); } renderMention (notification) { return ( <StatusContainer id={notification.get('status')} withDismiss hidden={this.props.hidden} onMoveDown={this.handleMoveDown} onMoveUp={this.handleMoveUp} contextType='notifications' getScrollPosition={this.props.getScrollPosition} updateScrollBottom={this.props.updateScrollBottom} cachedMediaWidth={this.props.cachedMediaWidth} cacheMediaWidth={this.props.cacheMediaWidth} /> ); } renderFavourite (notification, link) { const { intl } = this.props; return ( <HotKeys handlers={this.getHandlers()}> <div className='notification notification-favourite focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage({ id: 'notification.favourite', defaultMessage: '{name} favourited your status' }, { name: notification.getIn(['account', 'acct']) }), notification.get('created_at'))}> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <Icon id='star' className='star-icon' fixedWidth /> </div> <span title={notification.get('created_at')}> <FormattedMessage id='notification.favourite' defaultMessage='{name} favourited your status' values={{ name: link }} /> </span> </div> <StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={!!this.props.hidden} getScrollPosition={this.props.getScrollPosition} updateScrollBottom={this.props.updateScrollBottom} cachedMediaWidth={this.props.cachedMediaWidth} cacheMediaWidth={this.props.cacheMediaWidth} /> </div> </HotKeys> ); } renderReblog (notification, link) { const { intl } = this.props; return ( <HotKeys handlers={this.getHandlers()}> <div className='notification notification-reblog focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage({ id: 'notification.reblog', defaultMessage: '{name} boosted your status' }, { name: notification.getIn(['account', 'acct']) }), notification.get('created_at'))}> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <Icon id='retweet' fixedWidth /> </div> <span title={notification.get('created_at')}> <FormattedMessage id='notification.reblog' defaultMessage='{name} boosted your status' values={{ name: link }} /> </span> </div> <StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={this.props.hidden} getScrollPosition={this.props.getScrollPosition} updateScrollBottom={this.props.updateScrollBottom} cachedMediaWidth={this.props.cachedMediaWidth} cacheMediaWidth={this.props.cacheMediaWidth} /> </div> </HotKeys> ); } renderPoll (notification) { const { intl } = this.props; return ( <HotKeys handlers={this.getHandlers()}> <div className='notification notification-poll focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage({ id: 'notification.poll', defaultMessage: 'A poll you have voted in has ended' }), notification.get('created_at'))}> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <Icon id='tasks' fixedWidth /> </div> <span title={notification.get('created_at')}> <FormattedMessage id='notification.poll' defaultMessage='A poll you have voted in has ended' /> </span> </div> <StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={this.props.hidden} getScrollPosition={this.props.getScrollPosition} updateScrollBottom={this.props.updateScrollBottom} cachedMediaWidth={this.props.cachedMediaWidth} cacheMediaWidth={this.props.cacheMediaWidth} /> </div> </HotKeys> ); } render () { const { notification } = this.props; const account = notification.get('account'); const displayNameHtml = { __html: account.get('display_name_html') }; const link = <bdi><Permalink className='notification__display-name' href={account.get('url')} title={account.get('acct')} to={`/accounts/${account.get('id')}`} dangerouslySetInnerHTML={displayNameHtml} /></bdi>; switch(notification.get('type')) { case 'follow': return this.renderFollow(notification, account, link); case 'mention': return this.renderMention(notification); case 'favourite': return this.renderFavourite(notification, link); case 'reblog': return this.renderReblog(notification, link); case 'poll': return this.renderPoll(notification); } return null; } }
src/docs/components/select/SelectDoc.js
grommet/grommet-docs
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Select from 'grommet/components/Select'; import Form from 'grommet/components/Form'; import FormField from 'grommet/components/FormField'; import Button from 'grommet/components/Button'; import DocsArticle from '../../../components/DocsArticle'; Select.displayName = 'Select'; const VALUES = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']; export default class SelectDoc extends Component { constructor () { super(); this._onSearch = this._onSearch.bind(this); this._onChange = this._onChange.bind(this); this.state = { value: VALUES[0], options: VALUES }; } _onSearch (event) { const regexp = new RegExp('^' + event.target.value); const options = VALUES.filter(val => { return regexp.test(val); }); this.setState({ options: options }); } _onChange (pseudoEvent) { this.setState({ value: pseudoEvent.option, options: VALUES }); } render () { return ( <DocsArticle title="Select" action={ <Button primary={true} path='/docs/select/examples' label='Examples' /> }> <section> <p>An select-like field with optional search capability.</p> <Form> <FormField> <Select id="item1" name="item-1" value={this.state.value} onSearch={this._onSearch} onChange={this._onChange} options={this.state.options} /> </FormField> </Form> </section> <section> <h2>Properties</h2> <dl> <dt><code>inline true|false</code></dt> <dd>Whether to display the options inline or via a drop down. The default is <code>false</code>.</dd> <dt><code>multiple true|false</code></dt> <dd>Whether to allow multiple options to be selected. The default is <code>false</code>.</dd> <dt><code>onChange { "{function ({target: , option: , value: })}"} </code></dt> <dd>Function that will be called when the user selects an option. The <code>target</code> corresponds to the embedded input element, allowing you to distinguish which component triggered the event. The <code>option</code> contains the object chosen from the supplied options. The <code>value</code> contains all selected options when <code>multiple={'{true}'}</code>.</dd> <dt><code>onSearch {"{function (event)}"}</code></dt> <dd>Function that will be called when the user types in the search input. If this property is not provided, no search field will be rendered.</dd> <dt><code>options {"[{value: , label: }|{string}, ...]"} </code></dt> <dd>Options can be either a string or an object. The <code>label</code> property of option objects can be a string or a React element. This allows rendering richer option representations.</dd> <dt><code>placeHolder {"{string}"}</code></dt> <dd>Placeholder text to use when the search input is empty.</dd> <dt><code>value {"{value: , label: }|{string}"}</code></dt> <dd>What text to put in the input.</dd> </dl> </section> </DocsArticle> ); } };
frontend/src/Components/Form/IndexerFlagsSelectInputConnector.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import EnhancedSelectInput from './EnhancedSelectInput'; function createMapStateToProps() { return createSelector( (state, { indexerFlags }) => indexerFlags, (state) => state.settings.indexerFlags, (selectedFlags, indexerFlags) => { const value = []; indexerFlags.items.forEach((item) => { // eslint-disable-next-line no-bitwise if ((selectedFlags & item.id) === item.id) { value.push(item.id); } }); const values = indexerFlags.items.map(({ id, name }) => { return { key: id, value: name }; }); return { value, values }; } ); } class IndexerFlagsSelectInputConnector extends Component { onChange = ({ name, value }) => { let indexerFlags = 0; value.forEach((flagId) => { indexerFlags += flagId; }); this.props.onChange({ name, value: indexerFlags }); } // // Render render() { return ( <EnhancedSelectInput {...this.props} onChange={this.onChange} /> ); } } IndexerFlagsSelectInputConnector.propTypes = { name: PropTypes.string.isRequired, indexerFlags: PropTypes.number.isRequired, value: PropTypes.arrayOf(PropTypes.number).isRequired, values: PropTypes.arrayOf(PropTypes.object).isRequired, onChange: PropTypes.func.isRequired }; export default connect(createMapStateToProps)(IndexerFlagsSelectInputConnector);
fontend/src/routes/IndexPage.js
bingweichen/GOKU
import React from 'react'; import { connect } from 'dva'; import styles from './IndexPage.css'; import auth from '../utils/Auth'; import Footer from '../components/MainLayout/Footer.jsx'; function IndexPage({ location }) { const tab = location.query.tab ? location.query.tab : 'shop'; auth(); return ( <div > <Footer tab={tab} /> </div> ); } IndexPage.propTypes = { }; export default connect()(IndexPage);
app/javascript/mastodon/features/account_gallery/index.js
tootsuite/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { lookupAccount, fetchAccount } from 'mastodon/actions/accounts'; import { expandAccountMediaTimeline } from '../../actions/timelines'; import LoadingIndicator from 'mastodon/components/loading_indicator'; import Column from '../ui/components/column'; import ColumnBackButton from 'mastodon/components/column_back_button'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { getAccountGallery } from 'mastodon/selectors'; import MediaItem from './components/media_item'; import HeaderContainer from '../account_timeline/containers/header_container'; import ScrollContainer from 'mastodon/containers/scroll_container'; import LoadMore from 'mastodon/components/load_more'; import MissingIndicator from 'mastodon/components/missing_indicator'; import { openModal } from 'mastodon/actions/modal'; import { FormattedMessage } from 'react-intl'; const mapStateToProps = (state, { params: { acct, id } }) => { const accountId = id || state.getIn(['accounts_map', acct]); if (!accountId) { return { isLoading: true, }; } return { accountId, isAccount: !!state.getIn(['accounts', accountId]), attachments: getAccountGallery(state, accountId), isLoading: state.getIn(['timelines', `account:${accountId}:media`, 'isLoading']), hasMore: state.getIn(['timelines', `account:${accountId}:media`, 'hasMore']), suspended: state.getIn(['accounts', accountId, 'suspended'], false), blockedBy: state.getIn(['relationships', accountId, 'blocked_by'], false), }; }; class LoadMoreMedia extends ImmutablePureComponent { static propTypes = { maxId: PropTypes.string, onLoadMore: PropTypes.func.isRequired, }; handleLoadMore = () => { this.props.onLoadMore(this.props.maxId); } render () { return ( <LoadMore disabled={this.props.disabled} onClick={this.handleLoadMore} /> ); } } export default @connect(mapStateToProps) class AccountGallery extends ImmutablePureComponent { static propTypes = { params: PropTypes.shape({ acct: PropTypes.string, id: PropTypes.string, }).isRequired, accountId: PropTypes.string, dispatch: PropTypes.func.isRequired, attachments: ImmutablePropTypes.list.isRequired, isLoading: PropTypes.bool, hasMore: PropTypes.bool, isAccount: PropTypes.bool, blockedBy: PropTypes.bool, suspended: PropTypes.bool, multiColumn: PropTypes.bool, }; state = { width: 323, }; _load () { const { accountId, isAccount, dispatch } = this.props; if (!isAccount) dispatch(fetchAccount(accountId)); dispatch(expandAccountMediaTimeline(accountId)); } componentDidMount () { const { params: { acct }, accountId, dispatch } = this.props; if (accountId) { this._load(); } else { dispatch(lookupAccount(acct)); } } componentDidUpdate (prevProps) { const { params: { acct }, accountId, dispatch } = this.props; if (prevProps.accountId !== accountId && accountId) { this._load(); } else if (prevProps.params.acct !== acct) { dispatch(lookupAccount(acct)); } } handleScrollToBottom = () => { if (this.props.hasMore) { this.handleLoadMore(this.props.attachments.size > 0 ? this.props.attachments.last().getIn(['status', 'id']) : undefined); } } handleScroll = e => { const { scrollTop, scrollHeight, clientHeight } = e.target; const offset = scrollHeight - scrollTop - clientHeight; if (150 > offset && !this.props.isLoading) { this.handleScrollToBottom(); } } handleLoadMore = maxId => { this.props.dispatch(expandAccountMediaTimeline(this.props.accountId, { maxId })); }; handleLoadOlder = e => { e.preventDefault(); this.handleScrollToBottom(); } handleOpenMedia = attachment => { const { dispatch } = this.props; const statusId = attachment.getIn(['status', 'id']); if (attachment.get('type') === 'video') { dispatch(openModal('VIDEO', { media: attachment, statusId, options: { autoPlay: true } })); } else if (attachment.get('type') === 'audio') { dispatch(openModal('AUDIO', { media: attachment, statusId, options: { autoPlay: true } })); } else { const media = attachment.getIn(['status', 'media_attachments']); const index = media.findIndex(x => x.get('id') === attachment.get('id')); dispatch(openModal('MEDIA', { media, index, statusId })); } } handleRef = c => { if (c) { this.setState({ width: c.offsetWidth }); } } render () { const { attachments, isLoading, hasMore, isAccount, multiColumn, blockedBy, suspended } = this.props; const { width } = this.state; if (!isAccount) { return ( <Column> <MissingIndicator /> </Column> ); } if (!attachments && isLoading) { return ( <Column> <LoadingIndicator /> </Column> ); } let loadOlder = null; if (hasMore && !(isLoading && attachments.size === 0)) { loadOlder = <LoadMore visible={!isLoading} onClick={this.handleLoadOlder} />; } let emptyMessage; if (suspended) { emptyMessage = <FormattedMessage id='empty_column.account_suspended' defaultMessage='Account suspended' />; } else if (blockedBy) { emptyMessage = <FormattedMessage id='empty_column.account_unavailable' defaultMessage='Profile unavailable' />; } return ( <Column> <ColumnBackButton multiColumn={multiColumn} /> <ScrollContainer scrollKey='account_gallery'> <div className='scrollable scrollable--flex' onScroll={this.handleScroll}> <HeaderContainer accountId={this.props.accountId} /> {(suspended || blockedBy) ? ( <div className='empty-column-indicator'> {emptyMessage} </div> ) : ( <div role='feed' className='account-gallery__container' ref={this.handleRef}> {attachments.map((attachment, index) => attachment === null ? ( <LoadMoreMedia key={'more:' + attachments.getIn(index + 1, 'id')} maxId={index > 0 ? attachments.getIn(index - 1, 'id') : null} onLoadMore={this.handleLoadMore} /> ) : ( <MediaItem key={attachment.get('id')} attachment={attachment} displayWidth={width} onOpenMedia={this.handleOpenMedia} /> ))} {loadOlder} </div> )} {isLoading && attachments.size === 0 && ( <div className='scrollable__append'> <LoadingIndicator /> </div> )} </div> </ScrollContainer> </Column> ); } }
app/common/components/Toolbar/index.js
testpackbin/testpackbin
import React from 'react'; import {Decorator as Cerebral} from 'cerebral-view-react'; import styles from './styles.css'; @Cerebral({ recorder: ['recorder'] }) class Toolbar extends React.Component { constructor() { super(); } render() { return ( <div className={styles.wrapper}> { this.props.recorder.isPlaying ? <div className={styles.toolbarOverlay}></div> : null } {this.props.children} </div> ); } } export default Toolbar;
src/components/inputs/TextField.js
rghorbani/react-native-common
import React from 'react'; import PropTypes from 'prop-types'; import { TextInput as RNTextInput, StyleSheet, Animated } from 'react-native'; import _ from 'lodash'; import { Colors, Constants, Modal, Text, Typography, View, } from 'react-native-ui-lib'; import BaseInput from './BaseInput'; import TextArea from './TextArea'; const DEFAULT_COLOR_BY_STATE = { default: Colors.dark40, focus: Colors.blue30, error: Colors.red30, }; const DEFAULT_UNDERLINE_COLOR_BY_STATE = { default: Colors.dark70, focus: Colors.blue30, error: Colors.red30, }; /** * @description: A wrapper for Text Input component with extra functionality like floating placeholder * @extends: TextInput * @extendslink: https://facebook.github.io/react-native/docs/textinput.html * @modifiers: Typography * @gif: https://media.giphy.com/media/xULW8su8Cs5Z9Fq4PS/giphy.gif, https://media.giphy.com/media/3ohc1dhDcLS9FvWLJu/giphy.gif, https://media.giphy.com/media/oNUSOxnHdMP5ZnKYsh/giphy.gif * @example: https://github.com/wix/react-native-ui-lib/blob/master/demo/src/screens/componentScreens/InputsScreen.js */ export default class TextField extends BaseInput { static displayName = 'TextField'; static propTypes = { ...RNTextInput.propTypes, ...BaseInput.propTypes, /** * should placeholder have floating behavior */ floatingPlaceholder: PropTypes.bool, /** * floating placeholder color as a string or object of states, ex. {default: 'black', error: 'red', focus: 'blue'} */ floatingPlaceholderColor: PropTypes.oneOfType([ PropTypes.string, PropTypes.object, ]), /** * This text will appear as a placeholder when the textInput becomes focused, only when passing floatingPlaceholder * as well (NOT for expandable textInputs) */ helperText: PropTypes.string, /** * hide text input underline, by default false */ hideUnderline: PropTypes.bool, /** * underline color as a string or object of states, ex. {default: 'black', error: 'red', focus: 'blue'} */ underlineColor: PropTypes.oneOfType([PropTypes.string, PropTypes.object]), /** * should text input be align to center */ centered: PropTypes.bool, /** * input error message, should be empty if no error exists */ error: PropTypes.string, /** * should the input component support error messages */ enableErrors: PropTypes.bool, /** * should the input expand to another text area modal */ expandable: PropTypes.bool, /** * allow custom rendering of expandable content when clicking on the input (useful for pickers) * accept props and state as params, ex. (props, state) => {...} * use toggleExpandableModal(false) method to toggle off the expandable content */ renderExpandable: PropTypes.func, /** * The picker modal top bar props */ topBarProps: PropTypes.shape(Modal.TopBar.propTypes), /** * transform function executed on value and return transformed value */ transformer: PropTypes.func, /** * Fixed title that will displayed above the input (note: floatingPlaceholder MUST be 'false') */ title: PropTypes.string, /** * The title's color as a string or object of states, ex. {default: 'black', error: 'red', focus: 'blue'} */ titleColor: PropTypes.oneOfType([PropTypes.string, PropTypes.object]), /** * Additional styles for the title (not including 'color') */ titleStyle: PropTypes.oneOfType([ PropTypes.object, PropTypes.number, PropTypes.array, ]), /** * should the input display a character counter (only when passing 'maxLength') */ showCharacterCounter: PropTypes.bool, /** * Use to identify the component in tests */ testId: PropTypes.string, }; static defaultProps = { placeholderTextColor: DEFAULT_COLOR_BY_STATE.default, enableErrors: true, }; constructor(props) { super(props); this.onChangeText = this.onChangeText.bind(this); this.onFocus = this.onFocus.bind(this); this.onBlur = this.onBlur.bind(this); this.onDoneEditingExpandableInput = this.onDoneEditingExpandableInput.bind( this, ); this.updateFloatingPlaceholderState = this.updateFloatingPlaceholderState.bind( this, ); this.toggleExpandableModal = this.toggleExpandableModal.bind(this); this.shouldShowHelperText = this.shouldShowHelperText.bind(this); this.state = { value: props.value, floatingPlaceholderState: new Animated.Value( this.hasText(props.value) || this.shouldShowHelperText() ? 1 : 0, ), showExpandableModal: false, }; this.generatePropsWarnings(props); } componentWillReceiveProps(nextProps) { if (nextProps.value !== this.props.value) { this.setState( { value: nextProps.value, }, this.updateFloatingPlaceholderState, ); } } componentDidMount() { this.getHeight(); } generatePropsWarnings(props) { if (props.maxLength === 0) { console.warn('Setting maxLength to zero will block typing in this input'); } if (props.showCharacterCounter && !props.maxLength) { console.warn( "In order to use showCharacterCount please pass 'maxLength' prop", ); } } generateStyles() { this.styles = createStyles(this.props); } getStateColor(colorProp, isUnderline) { const { focused } = this.state; const { error } = this.props; const colorByState = _.cloneDeep( isUnderline ? DEFAULT_UNDERLINE_COLOR_BY_STATE : DEFAULT_COLOR_BY_STATE, ); if (colorProp) { if (_.isString(colorProp)) { // use given color for any state return colorProp; } else if (_.isObject(colorProp)) { // set given colors by states _.merge(colorByState, colorProp); } } // return the right color for the current state let color = colorByState.default; if (error && isUnderline) { color = colorByState.error; } else if (focused) { color = colorByState.focus; } return color; } getCharCount() { const { value } = this.state; return _.size(value); } isCounterLimit() { const { maxLength } = this.props; const counter = this.getCharCount(); return counter === 0 ? false : maxLength === counter; } hasText(value) { return !_.isEmpty(value || this.state.value); } shouldShowHelperText() { const { focused } = this.state; const { helperText } = this.props; return focused && helperText; } shouldFakePlaceholder() { const { floatingPlaceholder, centered } = this.props; return Boolean(floatingPlaceholder && !centered); } getHeight() { const { multiline } = this.props; if (!multiline) { const typography = this.getTypography(); return typography.lineHeight; } return this.getLinesHeightLimit(); } // numberOfLines support for both platforms getLinesHeightLimit() { const { multiline, numberOfLines } = this.props; if (multiline && numberOfLines) { const typography = this.getTypography(); return typography.lineHeight * numberOfLines; } } renderPlaceholder() { const { floatingPlaceholderState } = this.state; const { centered, expandable, placeholder, placeholderTextColor, floatingPlaceholderColor, multiline, } = this.props; const typography = this.getTypography(); const floatingTypography = Typography.text90; if (this.shouldFakePlaceholder()) { return ( <Animated.Text style={[ this.styles.floatingPlaceholder, this.styles.placeholder, typography, centered && this.styles.placeholderCentered, !centered && { top: floatingPlaceholderState.interpolate({ inputRange: [0, 1], outputRange: [multiline ? 30 : 28, multiline ? 7 : 0], }), fontSize: floatingPlaceholderState.interpolate({ inputRange: [0, 1], outputRange: [typography.fontSize, floatingTypography.fontSize], }), color: floatingPlaceholderState.interpolate({ inputRange: [0, 1], outputRange: [ placeholderTextColor, this.getStateColor(floatingPlaceholderColor), ], }), lineHeight: this.hasText() || this.shouldShowHelperText() ? floatingTypography.lineHeight : typography.lineHeight, }, ]} onPress={() => expandable && this.toggleExpandableModal(true)} > {placeholder} </Animated.Text> ); } } renderTitle() { const { floatingPlaceholder, title, titleColor, titleStyle } = this.props; const color = this.getStateColor(titleColor); if (!floatingPlaceholder && title) { return ( <Text style={[{ color }, this.styles.title, titleStyle]}>{title}</Text> ); } } renderCharCounter() { const { focused } = this.state; const { maxLength, showCharacterCounter } = this.props; if (maxLength && showCharacterCounter) { const counter = this.getCharCount(); const color = this.isCounterLimit() && focused ? DEFAULT_COLOR_BY_STATE.error : DEFAULT_COLOR_BY_STATE.default; return ( <Text style={[{ color }, this.styles.charCounter]}> {counter} / {maxLength} </Text> ); } } renderError() { const { enableErrors, error } = this.props; if (enableErrors) { return <Text style={this.styles.errorMessage}>{error}</Text>; } } renderExpandableModal() { const { renderExpandable, topBarProps } = this.props; const { showExpandableModal } = this.state; if (_.isFunction(renderExpandable) && showExpandableModal) { return renderExpandable(this.props, this.state); } return ( <Modal animationType={'slide'} visible={showExpandableModal} onRequestClose={() => this.toggleExpandableModal(false)} > <Modal.TopBar {...topBarProps} onCancel={() => this.toggleExpandableModal(false)} onDone={this.onDoneEditingExpandableInput} /> <View style={this.styles.expandableModalContent}> <TextArea ref={textarea => { this.expandableInput = textarea; }} {...this.props} value={this.state.value} /> </View> </Modal> ); } renderExpandableInput() { const { style, floatingPlaceholder, placeholder } = this.props; const { value } = this.state; const typography = this.getTypography(); const color = this.props.color || this.extractColorValue(); const minHeight = typography.lineHeight; const shouldShowPlaceholder = _.isEmpty(value) && !floatingPlaceholder; const inputStyle = [ this.styles.input, typography, color && { color }, style, ]; return ( <Text style={[ { minHeight }, inputStyle, shouldShowPlaceholder && this.styles.placeholder, ]} numberOfLines={3} onPress={() => this.toggleExpandableModal(true)} > {shouldShowPlaceholder ? placeholder : value} </Text> ); } renderTextInput() { const { value } = this.state; const color = this.props.color || this.extractColorValue(); const typography = this.getTypography(); const { style, placeholder, floatingPlaceholder, centered, multiline, numberOfLines, helperText, ...others } = this.props; const inputStyle = [ this.styles.input, typography, color && { color }, // with the right flex on the tree hierarchy we might not need this // {height: this.getHeight()}, style, ]; const placeholderText = this.shouldFakePlaceholder() ? this.shouldShowHelperText() ? helperText : undefined : placeholder; return ( <RNTextInput {...others} value={value} placeholder={placeholderText} underlineColorAndroid="transparent" style={inputStyle} multiline={multiline} numberOfLines={numberOfLines} onChangeText={this.onChangeText} onChange={this.onChange} onFocus={this.onFocus} onBlur={this.onBlur} ref={input => { this.input = input; }} /> ); } render() { const { expandable, containerStyle, underlineColor } = this.props; const underlineStateColor = this.getStateColor(underlineColor, true); return ( <View style={[this.styles.container, containerStyle]} collapsable={false}> {this.renderTitle()} <View style={[ this.styles.innerContainer, { borderColor: underlineStateColor }, ]} > {this.renderPlaceholder()} {expandable ? this.renderExpandableInput() : this.renderTextInput()} {this.renderExpandableModal()} </View> <View row> <View flex>{this.renderError()}</View> {this.renderCharCounter()} </View> </View> ); } toggleExpandableModal(value) { this.setState({ showExpandableModal: value }); } updateFloatingPlaceholderState(withoutAnimation) { if (withoutAnimation) { this.state.floatingPlaceholderState.setValue( this.hasText() || this.shouldShowHelperText() ? 1 : 0, ); } else { Animated.spring(this.state.floatingPlaceholderState, { toValue: this.hasText() || this.shouldShowHelperText() ? 1 : 0, duration: 150, }).start(); } } onDoneEditingExpandableInput() { const expandableInputValue = _.get(this.expandableInput, 'state.value'); this.setState({ value: expandableInputValue, }); this.state.floatingPlaceholderState.setValue(expandableInputValue ? 1 : 0); _.invoke(this.props, 'onChangeText', expandableInputValue); this.toggleExpandableModal(false); } onChangeText(text) { const { transformer } = this.props; let transformedText = text; if (_.isFunction(transformer)) { transformedText = transformer(text); } _.invoke(this.props, 'onChangeText', transformedText); this.setState( { value: transformedText, }, this.updateFloatingPlaceholderState, ); } onFocus(...args) { _.invoke(this.props, 'onFocus', ...args); this.setState({ focused: true }, this.updateFloatingPlaceholderState); } onBlur(...args) { _.invoke(this.props, 'onBlur', ...args); this.setState({ focused: false }, this.updateFloatingPlaceholderState); } } function createStyles({ placeholderTextColor, hideUnderline, centered, floatingPlaceholder, }) { return StyleSheet.create({ container: {}, innerContainer: { flexDirection: 'row', borderBottomWidth: hideUnderline ? 0 : 1, borderColor: Colors.dark70, justifyContent: centered ? 'center' : undefined, paddingTop: floatingPlaceholder ? 25 : undefined, flexGrow: 1, }, focusedUnderline: { borderColor: Colors.blue30, }, errorUnderline: { borderColor: Colors.red30, }, input: { flexGrow: 1, marginBottom: hideUnderline ? undefined : Constants.isIOS ? 10 : 5, padding: 0, textAlign: centered ? 'center' : undefined, backgroundColor: 'transparent', // backgroundColor: 'red' }, floatingPlaceholder: { position: 'absolute', }, placeholder: { color: placeholderTextColor, }, placeholderCentered: { left: 0, right: 0, textAlign: 'center', }, errorMessage: { color: Colors.red30, textAlign: centered ? 'center' : 'left', ...Typography.text90, // height: Typography.text90.lineHeight, marginTop: 1, }, expandableModalContent: { flex: 1, paddingTop: 15, paddingHorizontal: 20, }, title: { top: 0, ...Typography.text90, height: Typography.text90.lineHeight, marginBottom: Constants.isIOS ? 5 : 4, textAlign: 'left', }, charCounter: { ...Typography.text90, height: Typography.text90.lineHeight, marginTop: 1, }, }); }
src/pages/app/subscribe.js
getinsomnia/website
import React from 'react'; import PropTypes from 'prop-types'; import * as session from '../../lib/session'; import App from '../../lib/app-wrapper'; import Link from '../../components/link'; const planTypeTeam = 'team'; const planTypePlus = 'plus'; const planCycleMonthly = 'monthly'; const planCycleYearly = 'yearly'; const minTeamSize = 2; const pricePerMember = 8; const planIdMap = { 'plus-monthly-1': [planTypePlus, planCycleMonthly, 1], 'plus-yearly-1': [planTypePlus, planCycleYearly, 1], 'team-monthly-1': [planTypeTeam, planCycleMonthly, 5], 'team-yearly-1': [planTypeTeam, planCycleYearly, 5] }; class Subscribe extends React.Component { constructor (props) { super(props); const {billingDetails, whoami} = props; const quantity = Math.max( minTeamSize, billingDetails ? billingDetails.subQuantity : 5 ); let planDescription; if (window.location.hash === '#teams') { planDescription = planIdMap['team-monthly-1']; } else if (window.location.hash === '#plus') { planDescription = planIdMap['plus-monthly-1']; } else { planDescription = planIdMap[whoami.planId]; } const fullName = `${whoami.firstName} ${whoami.lastName}`.trim(); this.state = { loading: false, planType: planDescription ? planDescription[0] : planTypePlus, planCycle: planDescription ? planDescription[1] : planCycleMonthly, quantity: quantity || 5, useExistingBilling: billingDetails && billingDetails.hasCard, fullName: fullName, cardNumber: '', expireMonth: '01', expireYear: new Date().getFullYear() + 1, cvc: '', zip: '', error: '', memo: billingDetails ? billingDetails.subMemo : '', }; } componentDidMount () { const s = document.createElement('script'); s.src = 'https://js.stripe.com/v2/'; document.body.appendChild(s); s.addEventListener('load', () => { let key; if (window.location.hostname === 'staging.insomnia.rest') { key = 'pk_test_MbOhGu5jCPvr7Jt4VC6oySdH'; } else if (window.location.hostname === 'localhost') { key = 'pk_test_MbOhGu5jCPvr7Jt4VC6oySdH'; } else { key = 'pk_live_L8TkSkePPugJj7o73EclQFUI00JnQyPegW'; } window.Stripe.setPublishableKey(key); }); } _handleCardNumberChange (e) { // Using timeout or else target.value will not have been updated yet const value = e.target.value.trim(); if (!value) { return; } const cardType = window.Stripe.card.cardType(value); const lastChar = value[e.target.value.length - 1]; const num = value.replace(/[^0-9]*/g, ''); let newNum = ''; if (cardType.match(/american express/i)) { // 1111 222222 33333 const g1 = num.slice(0, 4); const g2 = num.slice(4, 10); const g3 = num.slice(10, 15); newNum = g1; newNum += g2 ? ` ${g2}` : ''; newNum += g3 ? ` ${g3}` : ''; } else if (cardType.match(/diners club/i)) { // 1111 2222 3333 44 const g1 = num.slice(0, 4); const g2 = num.slice(4, 8); const g3 = num.slice(8, 12); const g4 = num.slice(12, 14); newNum = g1; newNum += g2 ? ` ${g2}` : ''; newNum += g3 ? ` ${g3}` : ''; newNum += g4 ? ` ${g4}` : ''; } else { // 1111 2222 3333 4444 const g1 = num.slice(0, 4); const g2 = num.slice(4, 8); const g3 = num.slice(8, 12); const g4 = num.slice(12, 16); newNum = g1; newNum += g2 ? ` ${g2}` : ''; newNum += g3 ? ` ${g3}` : ''; newNum += g4 ? ` ${g4}` : ''; } // Handle trailing dash so we can add and delete dashes properly if (lastChar === ' ') { newNum += ' '; } // this.setState({cardType: cardType === 'Unknown' ? '' : cardType}); if (cardType.toLowerCase() !== 'unknown') { this.setState({cardType}); } else { this.setState({cardType: ''}); } // Only update number if it changed from the user's original to prevent cursor jump if (newNum !== value) { e.target.value = newNum; } if (window.Stripe.card.validateCardNumber(newNum)) { e.target.setCustomValidity(''); } else { e.target.setCustomValidity('Invalid card number'); } this._handleUpdateInput(e); } _handleUpdateInput (e) { const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value; this.setState({[e.target.name]: value, error: ''}); } async _handleSubmit (e) { e.preventDefault(); const { useExistingBilling, cardNumber, fullName, cvc, expireMonth, expireYear, zip, planType, planCycle, memo, quantity: quantityRaw, } = this.state; if (!useExistingBilling && !fullName.trim()) { this.setState({error: 'Card Error: No name provided'}); return; } if (!useExistingBilling && !zip.trim()) { this.setState({error: 'Card Error: No zip/postal provided'}); return; } if (!useExistingBilling && !cvc.trim()) { this.setState({error: 'Card Error: No cvc provided'}); return; } this.setState({loading: true}); const params = { cvc, name: fullName, number: cardNumber.replace(/ /g, ''), exp_month: parseInt(expireMonth, 10), exp_year: parseInt(expireYear, 10), address_zip: zip }; const teamSize = Math.max(minTeamSize, quantityRaw); const quantity = planType === planTypePlus ? 1 : teamSize; const planId = `${planType}-${planCycle}-1`; const d = new Date(); const subErrorKey = `subErrors_${d.getFullYear()}-${d.getMonth()}-${d.getDay()}`; const subErrors = parseInt(localStorage.getItem(subErrorKey) || '0'); const finishBilling = async tokenId => { try { await session.subscribe(tokenId, planId, quantity, memo); window.location = '/app/account/'; } catch (err) { this.setState({error: err.message, loading: false}); localStorage.setItem(subErrorKey, subErrors + 1); } }; if (useExistingBilling) { await finishBilling(); } else if (subErrors > 10) { setTimeout(() => { this.setState({ error: `Card Error: Your card was declined`, loading: false }); }, 3000); } else { window.Stripe.card.createToken(params, async (status, response) => { if (status === 200) { await finishBilling(response.id); } else { const msg = response.error ? response.error.message : 'Unknown error (112)'; this.setState({error: `Card Error: ${msg}`}); } this.setState({loading: false}); }); } } static _calculatePrice (planType, planCycle, quantity) { quantity = Math.max(quantity, minTeamSize); const priceIndex = planCycle === planCycleMonthly ? 0 : 1; const price = planType === planTypePlus ? [5, 50] : [pricePerMember * quantity, pricePerMember * 10 * quantity]; return price[priceIndex]; } static _getPlanDescription (planType, planCycle, quantity) { const cycle = planCycle === planCycleMonthly ? 'month' : 'year'; const price = Subscribe._calculatePrice(planType, planCycle, quantity); return `$${price} / ${cycle}`; } renderBillingNotice () { const {whoami, billingDetails} = this.props; const trialEndDate = new Date(whoami.trialEnd * 1000); const trialEndMillis = trialEndDate.getTime() - Date.now(); const trialDays = Math.ceil(trialEndMillis / 1000 / 60 / 60 / 24); if (!billingDetails && trialDays > 0) { return ( <p className="notice info"> You still have <strong>{trialDays}</strong> day{trialDays === 1 ? '' : 's'}{' '} left on your free trial </p> ); } return null; } render () { const { loading, error, cardType, planType, planCycle, expireMonth, expireYear, quantity, useExistingBilling, fullName, memo, } = this.state; const {billingDetails} = this.props; let subscribeBtn = null; if (loading && billingDetails) { subscribeBtn = ( <button type="button" disabled className="button"> Updating... </button> ); } else if (loading && !billingDetails) { subscribeBtn = ( <button type="button" disabled className="button"> Subscribing... </button> ); } else if (!loading && billingDetails) { subscribeBtn = ( <React.Fragment> <button type="submit" className="button"> Change to {' '} {Subscribe._getPlanDescription(planType, planCycle, quantity)} </button> <p className="text-xs subtle"> *Upgrades are billed immediately and downgrades will apply a credit on the next invoice </p> </React.Fragment> ); } else if (!loading && !billingDetails) { subscribeBtn = ( <button type="submit" className="button"> Subscribe for{' '} {Subscribe._getPlanDescription(planType, planCycle, quantity)} </button> ); } return ( <form onSubmit={this._handleSubmit.bind(this)}> {this.renderBillingNotice()} <div className="form-control"> <label> Plan Type <select className="wide" name="planType" defaultValue={planType} autoFocus onChange={this._handleUpdateInput.bind(this)}> <option value={planTypePlus}>Plus (Individual)</option> <option value={planTypeTeam}>Teams</option> </select> </label> </div> {planType === planTypeTeam ? ( <div className="form-control"> <label> Team Size{' '} {quantity < minTeamSize ? ( <small> &#40;billed for a minimum of {minTeamSize} members&#41; </small> ) : null} <input type="number" defaultValue={quantity} onChange={this._handleUpdateInput.bind(this)} min="1" max="500" title="Number of Team Members" name="quantity" /> </label> </div> ) : null} <div className="form-row center"> <div className="form-control"> <label> <input type="radio" name="planCycle" checked={planCycle === planCycleMonthly} onChange={this._handleUpdateInput.bind(this)} value={planCycleMonthly} /> {Subscribe._getPlanDescription(planType, planCycleMonthly, quantity)} </label> </div> <div className="form-control"> <label> <input type="radio" name="planCycle" checked={planCycle === planCycleYearly} onChange={this._handleUpdateInput.bind(this)} value={planCycleYearly} /> {Subscribe._getPlanDescription(planType, planCycleYearly, quantity)} </label> </div> </div> <hr className="hr--skinny"/> {billingDetails && billingDetails.hasCard ? ( <div className="form-control"> <label> <input type="checkbox" name="useExistingBilling" onChange={this._handleUpdateInput.bind(this)} defaultChecked={useExistingBilling} /> Use card ending in <code>{billingDetails.lastFour}</code> </label> </div> ) : null} {useExistingBilling ? ( <div/> ) : ( <div> <div className="form-control"> <label> Full Name <input type="text" name="fullName" placeholder="Maria Garcia" defaultValue={fullName} onChange={this._handleUpdateInput.bind(this)} required /> </label> </div> <div className="form-control"> <label> Card Number {cardType ? `(${cardType})` : null} <input type="text" name="cardNumber" placeholder="XXXX XXXX XXXX XXXX" onChange={this._handleCardNumberChange.bind(this)} required /> </label> </div> <div className="form-row"> <div className="form-control"> <label>Expiration Date</label> <br/> <select name="expireMonth" title="expire month" defaultValue={expireMonth} onChange={this._handleUpdateInput.bind(this)}> <option value="--">-- Month --</option> <option value="01">01 – January</option> <option value="02">02 – February</option> <option value="03">03 – March</option> <option value="04">04 – April</option> <option value="05">05 – May</option> <option value="06">06 – June</option> <option value="07">07 – July</option> <option value="08">08 – August</option> <option value="09">09 – September</option> <option value="10">10 – October</option> <option value="11">11 – November</option> <option value="12">12 – December</option> </select>{' '} <select name="expireYear" title="expire year" defaultValue={expireYear} onChange={this._handleUpdateInput.bind(this)}> <option value="--">-- Year --</option> <option value="2016">2016</option> <option value="2017">2017</option> <option value="2018">2018</option> <option value="2019">2019</option> <option value="2020">2020</option> <option value="2021">2021</option> <option value="2022">2022</option> <option value="2023">2023</option> <option value="2024">2024</option> <option value="2025">2025</option> <option value="2026">2026</option> <option value="2027">2027</option> <option value="2028">2028</option> <option value="2029">2029</option> <option value="2030">2030</option> <option value="2031">2031</option> <option value="2032">2032</option> <option value="2033">2033</option> <option value="2034">2034</option> <option value="2035">2035</option> <option value="2036">2036</option> <option value="2037">2037</option> <option value="2038">2038</option> <option value="2039">2039</option> </select> </div> <div className="form-control"> <label> Security Code (CVC) <input type="text" name="cvc" onChange={this._handleUpdateInput.bind(this)} required /> </label> </div> </div> <div className="form-control"> <label> Zip/Postal Code <input required type="text" name="zip" onChange={this._handleUpdateInput.bind(this)} /> </label> </div> </div> )} <hr className="hr--skinny"/> <div className="form-control"> <label> Additional Information for invoice (Address, VAT, etc) <textarea rows="3" value={memo} name="memo" onChange={this._handleUpdateInput.bind(this)} /> </label> </div> {error ? ( <small className="form-control error">** {error}</small> ) : null} <div className="form-control right padding-top-sm"> {subscribeBtn} </div> <hr className="hr--skinny"/> <p className="small subtle center"> Payments secured by{' '} <Link to="https://stripe.com" target="_blank"> Stripe </Link> </p> </form> ); } } Subscribe.propTypes = { whoami: PropTypes.shape({ planId: PropTypes.string.isRequired }).isRequired, billingDetails: PropTypes.shape({ subQuantity: PropTypes.number.isRequired, subMemo: PropTypes.string.isRequired, hasCard: PropTypes.bool.isRequired, lastFour: PropTypes.string.isRequired, isBillingAdmin: PropTypes.bool.isRequired, }), }; export default () => ( <App title="Subscribe to Plan" subTitle="Visa, MasterCard, or American Express"> {props => <Subscribe {...props} />} </App> );
src/client/components/TopicSelector.js
busyorg/busy
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import SortSelector from './SortSelector/SortSelector'; import Topic from './Button/Topic'; import './TopicSelector.less'; const TopicSelector = ({ sort, isSingle, topics, onTopicClose, onSortChange }) => ( <div className="TopicSelector"> <div className="TopicSelector__topics"> {topics && topics.map(topic => ( <Topic key={topic} closable={!isSingle} name={topic} onClose={onTopicClose} /> ))} </div> <SortSelector sort={sort} onChange={onSortChange}> <SortSelector.Item key="trending"> <FormattedMessage id="sort_trending" defaultMessage="Trending" /> </SortSelector.Item> <SortSelector.Item key="created"> <FormattedMessage id="sort_created" defaultMessage="Created" /> </SortSelector.Item> <SortSelector.Item key="hot"> <FormattedMessage id="sort_hot" defaultMessage="Hot" /> </SortSelector.Item> </SortSelector> </div> ); TopicSelector.propTypes = { sort: PropTypes.string, isSingle: PropTypes.bool, topics: PropTypes.arrayOf(PropTypes.string), onTopicClose: PropTypes.func, onSortChange: PropTypes.func, }; TopicSelector.defaultProps = { sort: 'trending', isSingle: true, topics: [], onTopicClose: () => {}, onSortChange: () => {}, }; export default TopicSelector;
src/pages/indexPage/index.js
chenchenyuyu/zhihuDaily-react
import React from 'react'; // import { connect } from 'react-redux'; import CYComponent from 'components/base/index'; import HomeHeader from 'components/home-header/index'; import ListDefault from 'components/list-default/index'; import Img from '../../components/list-default/images/chenyu.png'; const res = [ { date: '今日新闻', stories: [{ id: 0, title: '1111', pic: Img }, { id: 1, title: '2111', pic: Img }] }, { date: '2017-8-1', stories: [{ id: 2, title: '2222', pic: Img }, { id: 3, title: '2222', pic: Img }] }, { date: '2017-8-2', stories: [{ id: 4, title: '3333', pic: Img }, { id: 5, title: '2222', pic: Img }] }, ]; const sideRes = [ { name: 'aaa' }, { name: 'bbb' }, { name: 'ccc' }, { name: 'ddd' }, { name: 'bb' }, { name: 'cc' }, { name: 'aa' }, { name: 'fdfbb' }, { name: 'ccdff' }, { name: 'aaddf' }, { name: 'bbbdd' }, { name: 'cccggg' }, ]; class IndexPage extends CYComponent { constructor(props) { super(props); this.state = { dataList: res, sideList: sideRes, }; } render() { const datalist = this.state.dataList; // const sideList = this.state.sideList; console.log('datalistFU', datalist); return ( <div> <HomeHeader /> <div style={{ marginTop: 40 }}> <ListDefault dataList={datalist} /> {/* <SideBar sideList={sideList} /> */} </div> </div> ); } } export default IndexPage;
javascript/ql/experimental/adaptivethreatmodeling/test/endpoint_large_scale/autogenerated/Xss/XssThroughDom/forms.js
github/codeql
import React from 'react'; import { Formik, withFormik, useFormikContext } from 'formik'; const FormikBasic = () => ( <div> <Formik initialValues={{ email: '', password: '' }} validate={values => { $("#id").html(values.foo); // NOT OK }} onSubmit={(values, { setSubmitting }) => { $("#id").html(values.bar); // NOT OK }} > {(inputs) => ( <form onSubmit={handleSubmit}></form> )} </Formik> </div> ); const FormikEnhanced = withFormik({ mapPropsToValues: () => ({ name: '' }), validate: values => { $("#id").html(values.email); // NOT OK }, handleSubmit: (values, { setSubmitting }) => { $("#id").html(values.email); // NOT OK } })(MyForm); (function () { const { values, submitForm } = useFormikContext(); $("#id").html(values.email); // NOT OK $("#id").html(submitForm.email); // OK }) import { Form } from 'react-final-form' const App = () => ( <Form onSubmit={async values => { $("#id").html(values.stooge); // NOT OK }} initialValues={{ stooge: 'larry', employed: false }} render={({ handleSubmit, form, submitting, pristine, values }) => ( <form onSubmit={handleSubmit}> <input type="text" name="stooge"></input> </form> )} /> ); function plainSubmit(e) { $("#id").html(e.target.value); // NOT OK } const plainReact = () => ( <form onSubmit={e => plainSubmit(e)}> <input type="text" value={this.state.value} onChange={this.handleChange} /> <input type="submit" value="Submit" /> </form> ) import { useForm } from 'react-hook-form'; function HookForm() { const { register, handleSubmit, errors } = useForm(); // initialize the hook const onSubmit = (data) => { $("#id").html(data.name); // NOT OK }; return ( <form onSubmit={handleSubmit(onSubmit)}> <input name="name" ref={register({ required: true })} /> <input type="submit" /> </form> ); } function HookForm2() { const { register, getValues } = useForm(); return ( <form> <input name="name" ref={register} /> <button type="button" onClick={() => { const values = getValues(); // { test: "test-input", test1: "test1-input" } $("#id").html(values.name); // NOT OK }} > </button> </form> ); } function vanillaJS() { document.querySelector("form.myform").addEventListener("submit", e => { $("#id").html(e.target.value); // NOT OK }); document.querySelector("form.myform").onsubmit = function (e) { $("#id").html(e.target.value); // NOT OK } }
app/components/SettingOptions.js
SuperDOgePx/chrome-extension-react
// import _ from 'lodash'; import React, { Component } from 'react'; class SettingOptions extends Component { openOptions() { chrome.runtime.sendMessage({ service: 'open-options' }); } render() { return ( <div className="btn-group"> <div className={`btn tooltip-right`} onClick={this.openOptions} data-tooltip="Options" ><i className="fa fa-cogs"></i></div> </div> ); } } export default SettingOptions;
src/components/layout.js
sioked/ecomchicago
import React from 'react'; import PropTypes from 'prop-types'; import Helmet from 'react-helmet'; import Header from './Header'; import Footer from './Footer'; import content from '../constants/content.js'; import './layout.scss'; const TemplateWrapper = ({ children }) => ( <div> <Helmet title={content.siteTitle} meta={[ { name: 'description', content: 'Sample' }, { name: 'keywords', content: 'sample, something' }, ]} /> <Header /> <div>{children}</div> <Footer /> </div> ); TemplateWrapper.propTypes = { children: PropTypes.func.isRequired, }; export default TemplateWrapper;
src/components/tile.js
sugerPocket/react-redux-2048
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import style from '../styles/tile.sass'; export default class Tile extends Component { render() { const { value, x, y, width, height, isExisting, isNew, merged, dispatch } = this.props; let tileMerged = merged ? ' tile-merged' : ''; let tileNew = isNew ? ' tile-new' : ''; let tileExsting = isExisting ? '' : ' tile-nonexisted'; return ( <div className={`tile value-${value}${tileNew}${tileMerged}${tileExsting}`} style={{ left: '' + (100 / width) * x + '%', top: '' + (100 / height) * y + '%' }} > <span>{value}</span> </div> ); } } Tile.propTypes = { value: PropTypes.number.isRequired, x: PropTypes.number.isRequired, y: PropTypes.number.isRequired };
src/selectable-group.js
leopoldjoy/react-selectable-extended
import React from 'react'; import ReactDOM from 'react-dom'; import isNodeInRoot from './nodeInRoot'; import getBoundsForNode from './getBoundsForNode'; import doObjectsCollide from './doObjectsCollide'; class SelectableGroup extends React.Component { constructor (props) { super(props); this.state = { isBoxSelecting: false, boxWidth: 0, boxHeight: 0, currentItems: [], selectingItems: [] } this._mouseDownStarted = false; this._mouseMoveStarted = false; this._mouseUpStarted = false; this._mouseDownData = null; this._registry = []; this._openSelector = this._openSelector.bind(this); this._click = this._click.bind(this); this._mouseDown = this._mouseDown.bind(this); this._mouseUp = this._mouseUp.bind(this); this._selectElements = this._selectElements.bind(this); this._registerSelectable = this._registerSelectable.bind(this); this._unregisterSelectable = this._unregisterSelectable.bind(this); this._clearSelections = this._clearSelections.bind(this); this._clearSelectings = this._clearSelectings.bind(this); this._updatedSelecting = this._updatedSelecting.bind(this); this._desktopEventCoords = this._desktopEventCoords.bind(this); } getChildContext () { return { selectable: { register: this._registerSelectable, unregister: this._unregisterSelectable } }; } componentDidMount () { ReactDOM.findDOMNode(this).addEventListener('mousedown', this._mouseDown); ReactDOM.findDOMNode(this).addEventListener('touchstart', this._mouseDown); } /** * Remove global event listeners */ componentWillUnmount () { ReactDOM.findDOMNode(this).removeEventListener('mousedown', this._mouseDown); ReactDOM.findDOMNode(this).removeEventListener('touchstart', this._mouseDown); } _registerSelectable (key, domNode) { this._registry.push({key, domNode}); } _unregisterSelectable (key) { this._registry = this._registry.filter(data => data.key !== key); } /** * Called while moving the mouse with the button down. Changes the boundaries * of the selection box */ _openSelector (e) { if(this._mouseMoveStarted) return; this._mouseMoveStarted = true; e = this._desktopEventCoords(e); const w = Math.abs(this._mouseDownData.initialW - e.pageX); const h = Math.abs(this._mouseDownData.initialH - e.pageY); this.setState({ isBoxSelecting: true, boxWidth: w, boxHeight: h, boxLeft: Math.min(e.pageX, this._mouseDownData.initialW), boxTop: Math.min(e.pageY, this._mouseDownData.initialH), selectingItems: this._updatedSelecting() // Update list of currently selected items... }, () => { this._mouseMoveStarted = false; }); this.props.duringSelection(this.state.selectingItems); } /** * Returns array of all of the elements that are currently under the selector box. */ _updatedSelecting () { var selectbox = ReactDOM.findDOMNode(this.refs.selectbox); var tolerance = this.props.tolerance; if (!selectbox) return []; var currentItems = []; this._registry.forEach(itemData => { if(itemData.domNode && doObjectsCollide(selectbox, itemData.domNode, tolerance)) { currentItems.push(itemData.key); } }); return currentItems; } /** * Called when a user clicks on an item (and doesn't drag). Selects the clicked item. * Called by the _selectElements() function. */ _click (e) { const node = ReactDOM.findDOMNode(this); const {tolerance, dontClearSelection} = this.props, selectbox = ReactDOM.findDOMNode(this.refs.selectbox); var newItems = []; // For holding the clicked item if(!dontClearSelection){ // Clear exisiting selections this._clearSelections(); }else{ newItems = this.state.currentItems; } this._registry.forEach(itemData => { if(itemData.domNode && doObjectsCollide(selectbox, itemData.domNode, tolerance)) { if(!dontClearSelection){ newItems.push(itemData.key); // Only clicked item will be selected now }else{ // Toggle item selection if(newItems.indexOf(itemData.key) == -1){ // Not selected currently, mark item as selected newItems.push(itemData.key); }else{ // Selected currently, mark item as unselected var index = newItems.indexOf(itemData.key); newItems.splice(index, 1); } } } }); // Clear array for duringSelection, since the "selecting" is now finished this._clearSelectings(); this.props.duringSelection(this.state.selectingItems); // Last time duringSelection() will be called since drag is complete. // Close selector and update currently selected items this.setState({ isBoxSelecting: false, boxWidth: 0, boxHeight: 0, currentItems: newItems }); this.props.onSelection(this.state.currentItems); } /** * Called when a user presses the mouse button. Determines if a select box should * be added, and if so, attach event listeners */ _mouseDown (e) { if(this._mouseDownStarted) return; this._mouseDownStarted = true; this._mouseUpStarted = false; e = this._desktopEventCoords(e); const node = ReactDOM.findDOMNode(this); let collides, offsetData, distanceData; ReactDOM.findDOMNode(this).addEventListener('mouseup', this._mouseUp); ReactDOM.findDOMNode(this).addEventListener('touchend', this._mouseUp); // Right clicks if(e.which === 3 || e.button === 2) return; if(!isNodeInRoot(e.target, node)) { offsetData = getBoundsForNode(node); collides = doObjectsCollide( { top: offsetData.top, left: offsetData.left, bottom: offsetData.offsetHeight, right: offsetData.offsetWidth }, { top: e.pageY, left: e.pageX, offsetWidth: 0, offsetHeight: 0 } ); if(!collides) return; } this._mouseDownData = { boxLeft: e.pageX, boxTop: e.pageY, initialW: e.pageX, initialH: e.pageY }; e.preventDefault(); ReactDOM.findDOMNode(this).addEventListener('mousemove', this._openSelector); ReactDOM.findDOMNode(this).addEventListener('touchmove', this._openSelector); } /** * Called when the user has completed selection */ _mouseUp (e) { if(this._mouseUpStarted) return; this._mouseUpStarted = true; this._mouseDownStarted = false; ReactDOM.findDOMNode(this).removeEventListener('mousemove', this._openSelector); ReactDOM.findDOMNode(this).removeEventListener('mouseup', this._mouseUp); ReactDOM.findDOMNode(this).removeEventListener('touchmove', this._openSelector); ReactDOM.findDOMNode(this).removeEventListener('touchend', this._mouseUp); if(!this._mouseDownData) return; return this._selectElements(e); } /** * Selects multiple children given x/y coords of the mouse */ _selectElements (e) { // Clear array for duringSelection, since the "selecting" is now finished this._clearSelectings(); this.props.duringSelection(this.state.selectingItems); // Last time duringSelection() will be called since drag is complete. const {tolerance, dontClearSelection} = this.props, selectbox = ReactDOM.findDOMNode(this.refs.selectbox); if(!dontClearSelection){ // Clear old selection if feature is not enabled this._clearSelections(); } if(!selectbox){ // Since the selectbox is null, no drag event occured. Thus, we will process this as a click event... this.setState({ isBoxSelecting: true, boxWidth: 0, boxHeight: 0, boxLeft: this._mouseDownData.boxLeft, boxTop: this._mouseDownData.boxTop }, function(){ this._click(); }); return; } // Mouse is now up... this._mouseDownData = null; var newItems = []; var allNewItemsAlreadySelected = true; // Book keeping for dontClearSelection feature this._registry.forEach(itemData => { if(itemData.domNode && doObjectsCollide(selectbox, itemData.domNode, tolerance)) { newItems.push(itemData.key); if(this.state.currentItems.indexOf(itemData.key) == -1 && dontClearSelection){ allNewItemsAlreadySelected = false; } } }); var newCurrentItems = []; if(!dontClearSelection||!allNewItemsAlreadySelected){ // dontClearSelection is not enabled or // newItems should be added to the selection newCurrentItems = this.state.currentItems.concat(newItems); }else{ newCurrentItems = this.state.currentItems.filter(function(i) {return newItems.indexOf(i) < 0;}); // Delete newItems from currentItems } this.setState({ isBoxSelecting: false, boxWidth: 0, boxHeight: 0, currentItems: newCurrentItems }); this.props.onSelection(this.state.currentItems); } /** * Unselects all items, clearing this.state.currentItems */ _clearSelections (){ this.state.currentItems = []; } /** * Empties the array of items that were under selector box while selecting, * clearing this.state.selectingItems */ _clearSelectings (){ this.state.selectingItems = []; } /** * Used to return event object with desktop (non-touch) format of event * coordinates, regardless of whether the action is from mobile or desktop. */ _desktopEventCoords (e){ if(e.pageX==undefined || e.pageY==undefined){ // Touch-device e.pageX = e.targetTouches[0].pageX; e.pageY = e.targetTouches[0].pageY; } return e; } /** * Renders the component * @return {ReactComponent} */ render () { const boxStyle = { left: this.state.boxLeft, top: this.state.boxTop, width: this.state.boxWidth, height: this.state.boxHeight, zIndex: 9000, position: this.props.fixedPosition ? 'fixed' : 'absolute', cursor: 'default' }; const spanStyle = { backgroundColor: 'transparent', border: '1px dashed #999', width: '100%', height: '100%', float: 'left' }; return ( <this.props.component {...this.props}> {this.state.isBoxSelecting && <div style={boxStyle} ref="selectbox"><span style={spanStyle}></span></div> } {this.props.children} </this.props.component> ); } } SelectableGroup.propTypes = { /** * Event that will fire when items are selected. Passes an array of keys. */ onSelection: React.PropTypes.func, /** * Event that will fire rapidly during selection (while the selector is * being dragged). Passes an array of keys. */ duringSelection: React.PropTypes.func, /** * The component that will represent the Selectable DOM node */ component: React.PropTypes.node, /** * Amount of forgiveness an item will offer to the selectbox before registering * a selection, i.e. if only 1px of the item is in the selection, it shouldn't be * included. */ tolerance: React.PropTypes.number, /** * In some cases, it the bounding box may need fixed positioning, if your layout * is relying on fixed positioned elements, for instance. * @type boolean */ fixedPosition: React.PropTypes.bool, /** * When enabled, makes all new selections add to the already selected items, * except for selections that contain only previously selected items--in this case * it unselects those items. */ dontClearSelection: React.PropTypes.bool }; SelectableGroup.defaultProps = { onSelection: () => {}, duringSelection: () => {}, component: 'div', tolerance: 0, fixedPosition: false, dontClearSelection: false }; SelectableGroup.childContextTypes = { selectable: React.PropTypes.object }; export default SelectableGroup;
test/utils.js
planttheidea/crio
// test import test from 'ava'; import React from 'react'; import sinon from 'sinon'; // src import * as utils from 'src/utils'; import * as is from 'src/is'; import CrioArray from 'src/CrioArray'; import CrioObject from 'src/CrioObject'; test('if createIterator will create an iterator method', (t) => { const key = 'foo'; const value = 'bar'; const object = { [key]: value, keys() { return [key]; }, }; const iterator = utils.createIterator(); object.iterator = iterator; const iterable = object.iterator(); t.deepEqual(iterable.next(), { done: false, value, }); t.deepEqual(iterable.next(), { done: true, }); }); test('if every will return true when every result matches', (t) => { const key = 'foo'; const value = 'bar'; const otherKey = 'bar'; const otherValue = value; const object = { [key]: value, keys() { return [key, otherKey]; }, [otherKey]: otherValue, }; const fn = (item) => item === value; t.true(utils.every(object, fn)); }); test('if every will return false when not every result matches', (t) => { const key = 'foo'; const value = 'bar'; const otherKey = 'bar'; const otherValue = 'baz'; const object = { [key]: value, keys() { return [key, otherKey]; }, [otherKey]: otherValue, }; const fn = (item) => item === value; t.false(utils.every(object, fn)); }); test('if every will return true when no keys exist', (t) => { const object = { keys() { return []; }, }; const fn = (item) => item === 'never run'; t.true(utils.every(object, fn)); }); test('if find will find the value that exists in the object at key', (t) => { const key = 'foo'; const value = 'bar'; const otherKey = 'bar'; const otherValue = value; const object = { [key]: value, keys() { return [key, otherKey]; }, [otherKey]: otherValue, }; const fn = (item) => item === value; const isKey = false; const isFromEnd = false; const result = utils.find(object, fn, isKey, isFromEnd); t.is(result, value); }); test('if find will return undefined if a match could not be found in the object at key', (t) => { const key = 'foo'; const value = 'bar'; const otherKey = 'bar'; const otherValue = value; const object = { [key]: value, keys() { return [key, otherKey]; }, [otherKey]: otherValue, }; const fn = (item) => item === 'quz'; const isKey = false; const isFromEnd = false; const result = utils.find(object, fn, isKey, isFromEnd); t.is(result, undefined); }); test('if find will find the key that exists in the object at key', (t) => { const key = 'foo'; const value = 'bar'; const otherKey = 'bar'; const otherValue = value; const object = { [key]: value, keys() { return [key, otherKey]; }, [otherKey]: otherValue, }; const fn = (item) => item === value; const isKey = true; const isFromEnd = false; const result = utils.find(object, fn, isKey, isFromEnd); t.is(result, key); }); test('if find will return undefined when the key could not be found in the object at key', (t) => { const key = 'foo'; const value = 'bar'; const otherKey = 'bar'; const otherValue = value; const object = { isArray() { return false; }, [key]: value, keys() { return [key, otherKey]; }, [otherKey]: otherValue, }; const fn = (item) => item === 'quz'; const isKey = true; const isFromEnd = false; const result = utils.find(object, fn, isKey, isFromEnd); t.is(result, undefined); }); test('if find will return undefined when the key could not be found in the array at key', (t) => { const key = 'foo'; const value = 'bar'; const otherKey = 'bar'; const otherValue = value; const object = { isArray() { return true; }, [key]: value, keys() { return [key, otherKey]; }, [otherKey]: otherValue, }; const fn = (item) => item === 'quz'; const isKey = true; const isFromEnd = false; const result = utils.find(object, fn, isKey, isFromEnd); t.is(result, -1); }); test('if find will find the value that exists in the object at key starting from the end', (t) => { const key = 'foo'; const value = 'bar'; const otherKey = 'bar'; const otherValue = value; const object = { [key]: value, keys() { return [key, otherKey]; }, [otherKey]: otherValue, }; const fn = (item) => item === value; const isKey = false; const isFromEnd = true; const result = utils.find(object, fn, isKey, isFromEnd); t.is(result, otherValue); }); test('if find will find the key that exists in the object at key starting from the end', (t) => { const key = 'foo'; const value = 'bar'; const otherKey = 'bar'; const otherValue = value; const object = { [key]: value, keys() { return [key, otherKey]; }, [otherKey]: otherValue, }; const fn = (item) => item === value; const isKey = true; const isFromEnd = true; const result = utils.find(object, fn, isKey, isFromEnd); t.is(result, otherKey); }); test('if getCrioedObject will return the object if it is falsy', (t) => { const object = null; const isArraySpy = sinon.spy(is, 'isArray'); const isObjectSpy = sinon.spy(is, 'isObject'); const result = utils.getCrioedObject(object); t.is(result, object); t.true(isArraySpy.notCalled); isArraySpy.restore(); t.true(isObjectSpy.notCalled); isObjectSpy.restore(); }); test('if getCrioedObject will return the object if it is not typeof object', (t) => { const object = 'foo'; const isArraySpy = sinon.spy(is, 'isArray'); const isObjectSpy = sinon.spy(is, 'isObject'); const result = utils.getCrioedObject(object); t.is(result, object); t.true(isArraySpy.notCalled); isArraySpy.restore(); t.true(isObjectSpy.notCalled); isObjectSpy.restore(); }); test('if getCrioedObject will return the object if it is a CrioArray', (t) => { const object = new CrioArray([]); const isArraySpy = sinon.spy(is, 'isArray'); const isObjectSpy = sinon.spy(is, 'isObject'); const result = utils.getCrioedObject(object); t.is(result, object); t.true(isArraySpy.calledOnce); t.true(isArraySpy.calledWith(object)); isArraySpy.restore(); t.true(isObjectSpy.notCalled); isObjectSpy.restore(); }); test('if getCrioedObject will return the object if it is a CrioObject', (t) => { const object = new CrioObject({}); const isArraySpy = sinon.spy(is, 'isArray'); const isObjectSpy = sinon.spy(is, 'isObject'); const result = utils.getCrioedObject(object); t.is(result, object); t.true(isArraySpy.calledOnce); t.true(isArraySpy.calledWith(object)); isArraySpy.restore(); t.true(isObjectSpy.calledOnce); t.true(isObjectSpy.calledWith(object)); isObjectSpy.restore(); }); test('if getCrioedObject will return the object if it is a react element', (t) => { const object = <div />; const isArraySpy = sinon.spy(is, 'isArray'); const isObjectSpy = sinon.spy(is, 'isObject'); const result = utils.getCrioedObject(object); t.is(result, object); t.true(isArraySpy.calledOnce); t.true(isArraySpy.calledWith(object)); isArraySpy.restore(); t.true(isObjectSpy.calledOnce); t.true(isObjectSpy.calledWith(object)); isObjectSpy.restore(); }); test('if getCrioedObject will return the CrioArray if it is an array', (t) => { const object = ['foo']; const isArraySpy = sinon.spy(is, 'isArray'); const isObjectSpy = sinon.spy(is, 'isObject'); const result = utils.getCrioedObject(object); t.deepEqual(result, new CrioArray(object)); t.true(isArraySpy.called); t.deepEqual(isArraySpy.args[0], [object]); isArraySpy.restore(); t.true(isObjectSpy.notCalled); isObjectSpy.restore(); }); test('if getCrioedObject will return the CrioObject if it is an object', (t) => { const object = {foo: 'bar'}; const isArraySpy = sinon.spy(is, 'isArray'); const isObjectSpy = sinon.spy(is, 'isObject'); const result = utils.getCrioedObject(object); t.deepEqual(result, new CrioObject(object)); t.true(isArraySpy.called); t.deepEqual(isArraySpy.args[0], [object]); isArraySpy.restore(); t.true(isObjectSpy.called); t.deepEqual(isObjectSpy.args[0], [object]); isObjectSpy.restore(); }); test('if getCrioedObject will return the object if no matches', (t) => { const object = /foo/; const isArraySpy = sinon.spy(is, 'isArray'); const isObjectSpy = sinon.spy(is, 'isObject'); const result = utils.getCrioedObject(object); t.is(result, object); t.true(isArraySpy.called); t.deepEqual(isArraySpy.args[0], [object]); isArraySpy.restore(); t.true(isObjectSpy.called); t.deepEqual(isObjectSpy.args[0], [object]); isObjectSpy.restore(); }); test('if getEntries will map the keys and values as pairs', (t) => { const key = 'foo'; const value = 'bar'; const otherKey = 'bar'; const otherValue = 'baz'; const object = { [key]: value, keys() { return new CrioArray([key, otherKey]); }, [otherKey]: otherValue, }; const result = utils.getEntries(object); t.true(result instanceof CrioArray); t.deepEqual(result.thaw(), [[key, value], [otherKey, otherValue]]); }); test('if getRelativeValue will return the max of the length + value and 0 if less than 0', (t) => { const value = -1; const length = 2; const result = utils.getRelativeValue(value, length); t.is(result, length + value); }); test('if getRelativeValue will return the min of the value and length if greater than 0', (t) => { const value = 4; const length = 2; const result = utils.getRelativeValue(value, length); t.is(result, length); }); test('if getValues will map the values', (t) => { const key = 'foo'; const value = 'bar'; const otherKey = 'bar'; const otherValue = 'baz'; const object = { [key]: value, keys() { return new CrioArray([key, otherKey]); }, [otherKey]: otherValue, }; const result = utils.getValues(object); t.true(result instanceof CrioArray); t.deepEqual(result.thaw(), [value, otherValue]); }); test('if some will return true when any result matches', (t) => { const key = 'foo'; const value = 'bar'; const otherKey = 'bar'; const otherValue = 'baz'; const object = { [key]: value, keys() { return [key, otherKey]; }, [otherKey]: otherValue, }; const fn = (item) => item === value; t.true(utils.some(object, fn)); }); test('if some will return false when no result matches', (t) => { const key = 'foo'; const value = 'bar'; const otherKey = 'bar'; const otherValue = 'baz'; const object = { [key]: value, keys() { return [key, otherKey]; }, [otherKey]: otherValue, }; const fn = (item) => item === 'quz'; t.false(utils.some(object, fn)); }); test('if some will return false when no keys exist', (t) => { const object = { keys() { return []; }, }; const fn = (item) => item === 'never run'; t.false(utils.some(object, fn)); }); test('if thaw will return the deeply-uncrioed version of all the objects', (t) => { const rawObject = [ { some: [ { deep: 'nesting', }, ], }, ]; const crio = new CrioArray(rawObject); const result = utils.thaw(crio); t.not(result instanceof CrioArray); t.not(result, rawObject); t.deepEqual(result, rawObject); });
docs/pages/api-docs/modal.js
lgollut/material-ui
import React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown'; const pageFilename = 'api/modal'; const requireRaw = require.context('!raw-loader!./', false, /\/modal\.md$/); export default function Page({ docs }) { return <MarkdownDocs docs={docs} />; } Page.getInitialProps = () => { const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw }); return { demos, docs }; };
src/svg-icons/av/queue.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvQueue = (props) => ( <SvgIcon {...props}> <path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9h-4v4h-2v-4H9V9h4V5h2v4h4v2z"/> </SvgIcon> ); AvQueue = pure(AvQueue); AvQueue.displayName = 'AvQueue'; AvQueue.muiName = 'SvgIcon'; export default AvQueue;
packages/lightning-core/accounts/ChannelList.js
DaReaper/lightning-app
import React from 'react' import _ from 'lodash' import reactCSS from 'reactcss' import { Icon } from 'lightning-components' import { LoadingIcon } from '../common' import ChannelListItem from './ChannelListItem' export const ChannelList = ({ channels, loading }) => { const styles = reactCSS({ 'default': { list: { borderTop: '1px solid #ddd', display: 'flex', flexDirection: 'column', flex: 1, }, empty: { display: 'flex', flexDirection: 'column', flex: 1, alignItems: 'center', justifyContent: 'center', color: '#bbb', userSelect: 'none', cursor: 'default', }, emptyLabel: { fontSize: 24, paddingTop: 10, }, }, }) return ( <div style={ styles.list }> { _.map(channels, (channel, i) => ( <ChannelListItem { ...channel } key={ i } /> )) } { loading ? ( <div style={ styles.empty }> <LoadingIcon /> </div> ) : null } { !channels.length && !loading ? ( <div style={ styles.empty }> <Icon name="playlist-remove" large /> <div style={ styles.emptyLabel }>No Channels Yet</div> </div> ) : null } </div> ) } export default ChannelList
client/src/core-components/form.js
ivandiazwm/opensupports
import React from 'react'; import _ from 'lodash'; import classNames from 'classnames'; import {reactDFS, renderChildrenWithProps} from 'lib-core/react-dfs'; import ValidationFactory from 'lib-app/validations/validator-factory'; import FormField from 'core-components/form-field'; class Form extends React.Component { static propTypes = { loading: React.PropTypes.bool, errors: React.PropTypes.object, onValidateErrors: React.PropTypes.func, onChange: React.PropTypes.func, values: React.PropTypes.object, onSubmit: React.PropTypes.func, defaultValues: React.PropTypes.object }; static childContextTypes = { loading: React.PropTypes.bool }; constructor(props) { super(props); this.state = { form: props.defaultValues || {}, validations: {}, errors: {} }; } getChildContext() { return { loading: this.props.loading }; } componentDidMount() { this.setState(this.getInitialFormAndValidations()); } render() { return ( <form {...this.getProps()}> {renderChildrenWithProps(this.props.children, this.getFieldProps.bind(this))} </form> ); } getProps() { let props = _.clone(this.props); props.className = this.getClass(); props.onSubmit = this.handleSubmit.bind(this); delete props.errors; delete props.loading; delete props.onValidateErrors; delete props.values; delete props.onChange; return props; } getClass() { let classes = { 'form': true }; classes[this.props.className] = (this.props.className); return classNames(classes); } getFieldProps({props, type}) { let additionalProps = {}; if (this.isValidField({type})) { let fieldName = props.name; additionalProps = { ref: fieldName, value: this.getFormValue()[fieldName], error: this.getFieldError(fieldName), onChange: this.handleFieldChange.bind(this, fieldName), onBlur: this.validateField.bind(this, fieldName) } } return additionalProps; } getFieldError(fieldName) { let error = this.state.errors[fieldName]; if (this.props.errors) { error = this.props.errors[fieldName] } return error; } getFirstErrorField() { let fieldName = _.findKey(this.state.errors); let fieldNode; if (fieldName) { fieldNode = this.refs[fieldName]; } return fieldNode; } getAllFieldErrors() { let form = this.getFormValue(); let fields = Object.keys(form); let errors = {}; _.each(fields, (fieldName) => { errors = this.getErrorsWithValidatedField(fieldName, form, errors); }); return errors; } getErrorsWithValidatedField(fieldName, form = this.getFormValue(), errors = this.state.errors) { let newErrors = _.clone(errors); if (this.state.validations[fieldName]) { newErrors[fieldName] = this.state.validations[fieldName].performValidation(form[fieldName], form); } return newErrors; } getInitialFormAndValidations() { let form = {}; let validations = {}; reactDFS(this.props.children, (child) => { if (this.isValidField(child)) { form[child.props.name] = child.props.value || FormField.getDefaultValue(child.props.field); if (child.props.required) { validations[child.props.name] = ValidationFactory.getValidator(child.props.validation || 'DEFAULT'); } } }); return { form: form, validations: validations } } handleSubmit(event) { event.preventDefault(); const form = this.getFormValue(); if (this.hasFormErrors()) { this.updateErrors(this.getAllFieldErrors(), this.focusFirstErrorField.bind(this)); } else if (this.props.onSubmit) { this.props.onSubmit(form); } } handleFieldChange(fieldName, event) { let form = _.clone(this.getFormValue()); form[fieldName] = event.target.value; if(this.props.values === undefined) this.setState({form}); if (this.props.onChange) { this.props.onChange(form); } } isValidField(node) { return node.type === FormField; } hasFormErrors() { return _.some(this.getAllFieldErrors()); } validateField(fieldName) { this.updateErrors(this.getErrorsWithValidatedField(fieldName)); } updateErrors(errors, callback) { this.setState({ errors }, callback); if (this.props.onValidateErrors) { this.props.onValidateErrors(errors); } } getFormValue() { return (this.props.values !== undefined) ? this.props.values : this.state.form; } focusFirstErrorField() { let firstErrorField = this.getFirstErrorField(); if (firstErrorField) { firstErrorField.focus(); } } } export default Form;
addons/comments/src/manager/components/CommentsPanel/index.js
enjoylife/storybook
import PropTypes from 'prop-types'; import React from 'react'; import CommentList from '../CommentList'; import CommentForm from '../CommentForm'; import style from './style'; export default function CommentsPanel(props) { if (props.loading) { return ( <div style={style.wrapper}> <div style={style.message}>loading...</div> </div> ); } if (props.appNotAvailable) { const appsUrl = 'https://hub.getstorybook.io/apps'; return ( <div style={style.wrapper}> <div style={style.message}> <a style={style.button} href={appsUrl}>Create an app for this repo on Storybook Hub</a> </div> </div> ); } return ( <div style={style.wrapper}> <CommentList key="list" {...props} /> <CommentForm key="form" {...props} /> </div> ); } CommentsPanel.defaultProps = { loading: false, appNotAvailable: false, }; CommentsPanel.propTypes = { loading: PropTypes.bool, appNotAvailable: PropTypes.bool, };
js/components/developer/create-job-screen/calendarCard.js
justarrived/p2p-client
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Grid, Col, Form, Card, CardItem } from 'native-base'; import CardHeader from '../../common/card-header/cardHeader'; import { setHStartDate, setHStartTime } from '../../../actions/jobCreation'; import I18n from '../../../i18n'; import JADatePicker from '../../common/ja-date-picker/datePicker'; import { JA_DATEPICKER_TYPE } from '../../../resources/constants'; // Card with input fields to specify when the job should be started. class CalendarCard extends Component { static propTypes = { setDate: React.PropTypes.func.isRequired, setTime: React.PropTypes.func.isRequired, date: React.PropTypes.string.isRequired, time: React.PropTypes.string.isRequired, }; render() { return ( <Card> <CardHeader icon="calendar" title={I18n.t('date_and_time.date')} subtitle={I18n.t('task.when_will_the_task_be_performed')} /> <Form > <Grid> <Col> <JADatePicker typeOfInput={JA_DATEPICKER_TYPE.DATE} onChange={this.props.setDate} currentPickerValue={this.props.date} /> </Col> <Col> <JADatePicker typeOfInput={JA_DATEPICKER_TYPE.TIME} onChange={this.props.setTime} currentPickerValue={this.props.time} /> </Col> </Grid> </Form> <CardItem footer /> </Card> ); } } const mapStateToProps = state => ({ date: state.jobCreation.helperDate.date, time: state.jobCreation.helperDate.time, }); function bindAction(dispatch) { return { setDate: hours => dispatch(setHStartDate(hours)), setTime: time => dispatch(setHStartTime(time)), }; } export default connect(mapStateToProps, bindAction)(CalendarCard);
examples/real-world/index.js
aheuermann/redux
import 'babel-core/polyfill'; import React from 'react'; import Root from './containers/Root'; import BrowserHistory from 'react-router/lib/BrowserHistory'; React.render( <Root history={new BrowserHistory()} />, document.getElementById('root') );
src/pages/index.js
kbariotis/kostasbariotis.com
import React from 'react'; import PropTypes from 'prop-types'; import { Row, Col } from 'react-flexbox-grid'; import { graphql, Link } from 'gatsby'; import IndexLayout from '../components/layouts/Index'; import Separator from '../components/blog/Separator'; import AuthorHeader from '../components/blog/AuthorHeader'; import RedHeader from '../components/blog/RedHeader'; import Posts from '../components/blog/Posts'; import MetaTags from '../components/blog/MetaTags'; import WebPageSchema from '../components/blog/schemas/WebPageSchema'; import Variables from './../components/blog/variables'; export default function Index({ data }) { let { edges: posts } = data.allMarkdownRemark; let { description } = data.site.siteMetadata; posts = posts.map(post => post.node); return ( <IndexLayout> <WebPageSchema /> <MetaTags title={'Home'} description={description} /> <Row> <Col sm={8} smOffset={2}> <AuthorHeader /> <RedHeader>Latest Posts</RedHeader> <Separator /> <Posts posts={posts} /> <Separator /> <article css={{ marginBottom: '2em', color: 'rgba(255, 255, 255, 0.8)', }} > <header> <h3 css={{ fontSize: '1.5em', fontWeight: '700', float: 'right', color: Variables.lightblue, '@media(max-width: 768px)': { textAlign: 'left', }, }} > <Link to="/page/2">Older Posts &gt;</Link> </h3> </header> </article> </Col> </Row> </IndexLayout> ); } Index.propTypes = { data: PropTypes.object, }; export const pageQuery = graphql` query IndexQuery { site { siteMetadata { description } } allMarkdownRemark( sort: { order: DESC, fields: [frontmatter___date] } limit: 5 filter: { frontmatter: { draft: { ne: true } } } ) { edges { node { excerpt(pruneLength: 250) id frontmatter { title date(formatString: "MMMM DD, YYYY") path tags draft } } } } } `;
examples/withLazyReducer-demo/src/modules/lazyCounter/LazyCounter.js
KeyFE/lazy-reducer
import React from 'react' import { connect } from 'react-redux' import { withLazyReducer } from 'lazy-reducer' import lazyCounterReducer, { increase, decrease } from './reducer' const LazyCounter = props => { return ( <div style={{ margin: '12px' }}> LazyCounter result: <span style={{ fontWeight: 'bold' }}>{props.lazyCounter}</span> <div> <input style={{ fontSize: '20px', fontWeight: 'bold' }} type="button" onClick={props.increase} value="+" /> <input style={{ fontSize: '20px', fontWeight: 'bold' }} type="button" onClick={props.decrease} value="-" /> </div> </div> ) } const mapStateToProps = (state, ownState) => { return { lazyCounter: state.lazyCounter } } const mapDispathchToProps = dispatch => { return { increase: increase(dispatch), decrease: decrease(dispatch) } } const LazyCounterWithConnect = connect(mapStateToProps, mapDispathchToProps)(LazyCounter) // use Lazy Reducer export default withLazyReducer(done => { setTimeout(() => { done({ lazyCounter: lazyCounterReducer }) }, 1000) })(LazyCounterWithConnect)
core/src/plugins/access.ajxp_conf/res/js/AdminWorkspaces/meta/MetaList.js
huzergackl/pydio-core
/* * Copyright 2007-2017 Charles du Jeu - Abstrium SAS <team (at) pyd.io> * This file is part of Pydio. * * Pydio is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pydio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Pydio. If not, see <http://www.gnu.org/licenses/>. * * The latest code can be found at <https://pydio.com>. */ import React from 'react' import {FlatButton} from 'material-ui' export default React.createClass({ mixins:[AdminComponents.MessagesConsumerMixin], propTypes: { currentMetas: React.PropTypes.object, edit:React.PropTypes.string, metaSourceProvider:React.PropTypes.object, closeCurrent: React.PropTypes.func, setEditState: React.PropTypes.func, featuresEditable:React.PropTypes.bool }, render: function(){ var features = []; var metas = Object.keys(this.props.currentMetas); metas.sort(function(k1, k2){ var type1 = k1.split('.').shift(); var type2 = k2.split('.').shift(); if(type1 == 'metastore' || type2 == 'index') return -1; if(type1 == 'index' || type2 == 'metastore') return 1; return (k1 > k2 ? 1:-1); }); if(metas){ features = metas.map(function(k){ var removeButton, description; if(this.props.edit == k && this.props.featuresEditable){ var remove = function(event){ event.stopPropagation(); this.props.metaSourceProvider.removeMetaSource(k); }.bind(this); removeButton = ( <div style={{textAlign:'right'}}> <FlatButton label={this.context.getMessage('ws.31')} primary={true} onTouchTap={remove}/> </div> ); } description = <div className="legend">{this.props.metaSourceProvider.getMetaSourceDescription(k)}</div>; return ( <PydioComponents.PaperEditorNavEntry key={k} keyName={k} selectedKey={this.props.edit} onClick={this.props.setEditState}> {this.props.metaSourceProvider.getMetaSourceLabel(k)} {description} {removeButton} </PydioComponents.PaperEditorNavEntry> ); }.bind(this)); } if(this.props.featuresEditable){ features.push( <div className="menu-entry" key="add-feature" onClick={this.props.metaSourceProvider.showMetaSourceForm.bind(this.props.metaSourceProvider)}>+ {this.context.getMessage('ws.32')}</div> ); } return ( <div>{features}</div> ); } });
app/javascript/mastodon/features/ui/components/video_modal.js
salvadorpla/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import Video from 'mastodon/features/video'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { FormattedMessage } from 'react-intl'; export const previewState = 'previewVideoModal'; export default class VideoModal extends ImmutablePureComponent { static propTypes = { media: ImmutablePropTypes.map.isRequired, status: ImmutablePropTypes.map, time: PropTypes.number, onClose: PropTypes.func.isRequired, }; static contextTypes = { router: PropTypes.object, }; componentDidMount () { if (this.context.router) { const history = this.context.router.history; history.push(history.location.pathname, previewState); this.unlistenHistory = history.listen(() => { this.props.onClose(); }); } } componentWillUnmount () { if (this.context.router) { this.unlistenHistory(); if (this.context.router.history.location.state === previewState) { this.context.router.history.goBack(); } } } handleStatusClick = e => { if (e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(`/statuses/${this.props.status.get('id')}`); } } render () { const { media, status, time, onClose } = this.props; const link = status && <a href={status.get('url')} onClick={this.handleStatusClick}><FormattedMessage id='lightbox.view_context' defaultMessage='View context' /></a>; return ( <div className='modal-root__modal video-modal'> <div> <Video preview={media.get('preview_url')} blurhash={media.get('blurhash')} src={media.get('url')} startTime={time} onCloseVideo={onClose} link={link} detailed alt={media.get('description')} /> </div> </div> ); } }
internals/templates/app.js
7ruth/PadStats2
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ // Needed for redux-saga es6 generator support import 'babel-polyfill'; // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { useScroll } from 'react-router-scroll'; import 'sanitize.css/sanitize.css'; // Import root app import App from 'containers/App'; // Import selector for `syncHistoryWithStore` import { makeSelectLocationState } from 'containers/App/selectors'; // Import Language Provider import LanguageProvider from 'containers/LanguageProvider'; // Load the favicon, the manifest.json file and the .htaccess file /* eslint-disable import/no-unresolved, import/extensions */ import '!file-loader?name=[name].[ext]!./favicon.ico'; import '!file-loader?name=[name].[ext]!./manifest.json'; import 'file-loader?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved, import/extensions */ import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import CSS reset and Global Styles import './global-styles'; // Import root routes import createRoutes from './routes'; // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: makeSelectLocationState(), }); // Set up the router, wrapping all Routes in the App component const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = (messages) => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={messages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(import('intl')); })) .then(() => Promise.all([ import('intl/locale-data/jsonp/en.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require }
src/routes.js
CodeTaha/react-redux-starter
/** * Created by taha on 9/10/17. */ import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/App'; import HomePage from './components/home/HomePage'; import AboutPage from './components/about/AboutPage'; import CoursesPage from './components/course/CoursesPage'; import ManageCoursePage from './components/course/ManageCoursePage'; export default ( <Route path="/" component={App}> <IndexRoute component={HomePage} /> <Route path="courses" component={CoursesPage} /> <Route path="course" component={ManageCoursePage} /> <Route path="course/:id" component={ManageCoursePage} /> <Route path="about" component={AboutPage} /> </Route> );
src/pages/person/PartyFee.js
zzelune/neam
/* * @Author: caixin1.zh * @Date: 2017-10-19 06:06:10 * @Last Modified by: zhaozheng1.zh * @Last Modified time: 2017-12-06 10:42:46 */ import React from 'react'; import { AppRegistry, StyleSheet, Text, View, processColor, ScrollView, FlatList,Root,Dimensions } from 'react-native'; import Toast, { DURATION } from 'react-native-easy-toast'; import { Button, Card, CardItem } from 'native-base'; import Icon from 'react-native-vector-icons/FontAwesome'; import EmptyView from '../../components/EmptyView'; import { getUser } from '../../utils/StorageUtil' import { fetchPost } from '../../utils/fetchAPI'; import LoadingView from '../../components/LoadingView'; import W from '../../common/index'; class PartyFee extends React.Component { constructor(props) { super(props); this.data = []; this.now = new Date() this.totalAmount = 0 this.payAmount = 0 this.state = { ready: false, year: this.now.getFullYear(), showLoading: true } } async componentDidMount() { u = await getUser(); fetchPost('A08463104', { thpyadthmsStmUsrId: u.thpyadthmsStmUsrId, yrYyyy: this.state.year + "" }, this._success.bind(this), this._failure.bind(this)); } _success(resp) { console.log(JSON.stringify(resp)); if (resp.BK_STATUS == "00") { this.data =[]; this.totalAmount = 0 this.payAmount = 0 for (let i = 0; resp.list != undefined && i < resp.list.length; i++) { let item = { month:'', money:'', status:'00' }; if(resp.list[i].thpyadthmsPyfStcd == '01') { this.payAmount += resp.list[i].thpyadthmsactPyfAmt; } else if(resp.list[i].thpyadthmsPyfStcd == '02') { this.totalAmount += resp.list[i].thpyadthmsactPyfAmt; } item.month = resp.list[i].moMo; item.money = resp.list[i].thpyadthmsactPyfAmt; item.status = resp.list[i].thpyadthmsPyfStcd; this.data.push(item); } this.setState({showLoading:false}); //this.setState({year: resp.yrYyyy}); } else { this.setState({showLoading:false},()=> this.refs.toast.show(error, DURATION.LENGTH_SHORT)); } } _failure(error) { console.log(error); this.setState({showLoading:false},()=> this.refs.toast.show("网络连接失败,请稍后再试!", DURATION.LENGTH_LONG) ); }; _onClick = year => { if(year == this.state.year) return; this.setState({showLoading:true, year:year}); fetchPost('A08463104', { thpyadthmsStmUsrId: u.thpyadthmsStmUsrId, yrYyyy: year + "" }, this._success.bind(this), this._failure.bind(this)) } _renderItemComponent = ({ item }) => { let color = ''; switch (item.status) { case '02': color = 'skyblue'; break; case '01': color = 'red'; break; default: color = 'grey'; } return ( <View style={{width: (Dimensions.get('window').width - 40) /3, margin:5 }}> <Card style={{flexDirection:'column'}}> <View style={{flex:1, backgroundColor: color, justifyContent: 'center',alignItems:'center',paddingVertical:10}}> <Text>{item.month}月</Text> </View> <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', paddingVertical: 10}}> <Text>{item.money}元</Text> </View> </Card> </View> ); } render() { return ( <View style={{ flex: 1, margin: 5 }}> <ScrollView> <View style={{ flexDirection: 'row', justifyContent: 'space-around' }}> <Text style={{ flex: 1 }}>本次应缴党费:</Text> <View style={{ flexDirection: 'row' }}> <Icon name='rmb' size={18} color='gold' /> <Text> {this.payAmount}元</Text> </View> </View> <EmptyView h={10} /> <View style={{ flexDirection: 'row', justifyContent: 'space-around' }}> <Text style={{ flex: 1 }}>历史已缴党费:</Text> <View style={{ flexDirection: 'row' }}> <Icon name='rmb' size={18} color='gold' /> <Text> {this.totalAmount}元</Text> </View> </View> <EmptyView h={10} /> <View style={{ height: 1, backgroundColor: 'grey' }} /> <View style={{ flexDirection: 'row', justifyContent: 'space-around', marginTop: 5 }}> { this.state.year == this.now.getFullYear() ? <Button info style={styles.butt} onPress={() => this._onClick(parseInt(this.now.getFullYear()))}> <Text style={{ textAlign: 'center' }}>{this.now.getFullYear()}年</Text> </Button> : <Button bordered style={styles.butt} onPress={() => this._onClick(parseInt(this.now.getFullYear()))}> <Text style={{ textAlign: 'center' }}>{this.now.getFullYear()}年</Text> </Button> } { this.state.year == this.now.getFullYear() - 1 ? <Button info style={styles.butt} onPress={() => this._onClick(parseInt(this.now.getFullYear()) - 1)}> <Text style={{ textAlign: 'center' }}>{"" + (parseInt(this.now.getFullYear() - 1))}年</Text> </Button> : <Button bordered style={styles.butt} onPress={() => this._onClick(parseInt(this.now.getFullYear()) - 1)}> <Text style={{ textAlign: 'center' }}>{"" + (parseInt(this.now.getFullYear() - 1))}年</Text> </Button> } { this.state.year == this.now.getFullYear() - 2 ? <Button info style={styles.butt} onPress={() => this._onClick(parseInt(this.now.getFullYear()) - 2)}> <Text style={{ textAlign: 'center' }}>{"" + (parseInt(this.now.getFullYear() - 2))}年</Text> </Button> : <Button bordered style={styles.butt} onPress={() => this._onClick(parseInt(this.now.getFullYear()) - 2)}> <Text style={{ textAlign: 'center' }}>{"" + (parseInt(this.now.getFullYear() - 2))}年</Text> </Button> } </View> <EmptyView h={10} /> {this.data.length > 0? <FlatList data={this.data} horizontal={false} numColumns={3} columnWrapperStyle={{ justifyContent: 'flex-start' }} keyExtractor={(item, index) => item.month} renderItem={this._renderItemComponent} />:<Text style={{fontSize:16}}> 无数据 </Text>} </ScrollView> <LoadingView showLoading={this.state.showLoading} backgroundColor='#323233' opacity={0.8} /> <Toast ref="toast"/> </View> ); } } const styles = StyleSheet.create({ butt: { width: W.width / 3 - 30, height: 28, marginHorizontal: 5, justifyContent: 'center' } }); export default PartyFee;
coral/components/NavigationBar.js
fdjiangwu/Coral
import React from 'react'; import {StyleSheet, Platform, View, Text, StatusBar, TouchableOpacity} from 'react-native'; import Icon from 'react-native-vector-icons/Ionicons'; import {connect} from 'react-redux'; import theme from '../constants/theme'; import px2dp from '../utils/px2dp'; class NavigationBar extends React.Component { static propTypes = { title: React.PropTypes.string.isRequired, leftBtnIcon: React.PropTypes.string, leftBtnText: React.PropTypes.string, leftBtnPress: React.PropTypes.func, rightBtnIcon: React.PropTypes.string, rightBtnText: React.PropTypes.string, rightBtnPress: React.PropTypes.func }; render() { const {title, mainThemeColor, leftBtnIcon, leftBtnText, leftBtnPress, rightBtnIcon, rightBtnText, rightBtnPress} = this.props; return ( <View style={styles.container}> <StatusBar translucent={true} backgroundColor={mainThemeColor}/> <View style={[styles.toolbar, {backgroundColor: mainThemeColor}]}> <View style={styles.fixedCell}> { (leftBtnIcon || leftBtnText) ? <Button icon={leftBtnIcon} text={leftBtnText} onPress={leftBtnPress}/> : null } </View> <View style={styles.centerCell}> <Text style={styles.title}>{title}</Text> </View> <View style={styles.fixedCell}> { (rightBtnIcon || rightBtnText) ? <Button icon={rightBtnIcon} text={rightBtnText} onPress={rightBtnPress}/> : null } </View> </View> </View> ); } } class Button extends React.Component { static propTypes = { icon: React.PropTypes.string, text: React.PropTypes.string, onPress: React.PropTypes.func }; render() { const {icon, onPress, text} = this.props; let afterIcon = null; if (icon) { if (Platform.OS === 'android') { afterIcon = 'md-' + icon; } else { afterIcon = 'ios-' + icon; } } return ( <TouchableOpacity onPress={onPress} activeOpacity={theme.touchableOpacityActiveOpacity} > <View style={styles.btn}> {afterIcon ? <Icon name={afterIcon} color="#fff" size={px2dp(23)}/> : <Text style={styles.btnText}>{text}</Text> } </View> </TouchableOpacity> ); } } const styles = StyleSheet.create({ container: { height: theme.toolbar.height + px2dp(4), width: theme.screenWidth, backgroundColor: 'rgba(0, 0, 0, 0)' }, toolbar: { height: theme.toolbar.height, //backgroundColor: theme.toolbar.barTintColor, flexDirection: 'row', paddingTop: Platform.OS === 'android' ? 0 : px2dp(6), elevation: 3, shadowColor: 'rgb(0, 0, 0)', shadowOffset: {height: 2, width: 1}, shadowOpacity: 0.25, shadowRadius: 3 }, fixedCell: { width: theme.toolbar.height, height: theme.toolbar.height, flexDirection: 'row' }, centerCell: { flex: 1, height: theme.toolbar.height, justifyContent: 'center', alignItems: 'center' }, title: { fontSize: theme.toolbar.titleSize, color: theme.toolbar.titleColor }, btn: { flex: 1, justifyContent: 'center', alignItems: 'center', width: theme.toolbar.height, height: Platform.OS === 'android' ? theme.toolbar.height : theme.toolbar.height - px2dp(6) }, btnText: { color: theme.toolbar.titleColor, fontSize: theme.toolbar.textBtnSize } }); const mapStateToProps = (state) => { return { mainThemeColor: state.settingState.colorScheme.mainThemeColor } }; export default connect(mapStateToProps)(NavigationBar);
src/app.js
CodersInTheCommunity/curve-calculator
import React from 'react'; import ReactDOM from 'react-dom'; import update from 'react-addons-update'; import PossiblePoints from './components/PossiblePoints'; import TargetPercentage from './components/TargetPercentage' import Input from './components/Input'; import Scores from './components/Scores'; import Curve from './components/Curve'; export default class App extends React.Component { constructor(props) { super(props); this.state = { possiblePoints: '', targetPercentage: '', scores: [] } } setPossiblePoints(value) { this.setState({ possiblePoints: value }); } setTargetPercentage(value) { this.setState({ targetPercentage: value }); } addScore(score) { this.setState({ scores: this.state.scores.concat([score]) }); } removeScore(i) { this.setState({ scores: update(this.state.scores, {$splice: [[i, 1]]}) }); } render() { return( <div className="app-container"> <h1>Curve Calculator</h1> <PossiblePoints value={this.state.possiblePoints} setValue={this.setPossiblePoints.bind(this)} /> <br/> <TargetPercentage value={this.state.targetPercentage} setValue={this.setTargetPercentage.bind(this)} /> <br/> <Input addScore={this.addScore.bind(this)} /> <br/> <Scores scores={this.state.scores} removeScore={this.removeScore.bind(this)} /> <Curve possiblePoints={this.state.possiblePoints} targetPercentage={this.state.targetPercentage} scores={this.state.scores} /> </div> ); } } ReactDOM.render( <App />, document.getElementById('app') );
app/Components/MyNavigationBar.js
csujedihy/react-native-textgo
'use strict'; import NavigationBar from 'react-native-navbar'; import React, { Component } from 'react'; import {StyleSheet} from 'react-native'; /* This is just a wrapper of Navbar */ export default class MyNavigationBar extends Component { constructor(props) { super(props); } render() { let styles = StyleSheet.create({ myNavigationBarWrapper: { borderBottomWidth: 1, borderBottomColor: '#BABABA' } }); return( <NavigationBar {...this.props} style={styles.myNavigationBarWrapper}/> ); } }
web/static/js/components/user_nav.js
babie/goal-server
import React from 'react'; import {Component} from 'flumpt'; class UserNavComponent extends Component { render() { return ( <nav id="user-nav"> <ul> <li> <i className="fa fa-user fa-2x fa-fw"></i> </li> <li> <i className="fa fa-search fa-2x fa-fw"></i> </li> <li> <i className="fa fa-folder-o fa-2x fa-fw"></i> </li> <li> <i className="fa fa-paper-plane-o fa-2x fa-fw"></i> </li> <li> <i className="fa fa-gear fa-2x fa-fw"></i> </li> </ul> </nav> ); } } export default UserNavComponent;
src/click-game/ChildQues5.js
mrinalkrishnanm/Sld
import React from 'react'; import Navbar from '../Navbar'; import Modal from 'react-modal'; import { browserHistory } from "react-router"; import _ from 'lodash'; class ChildQues5 extends React.Component{ constructor(){ super(); this.state={ counter: 10, modalIsOpen: true, score:5, button1_visibility:"o-90", button2_visibility:"o-0", button3_visibility:"o-0" } } closeModal(){ this.setState({modalIsOpen: false}); } start(){ this.setState({button1_visibility:"o-0"}); setInterval(this.counterStart.bind(this),3000); } counterStart(){ if(this.state.counter%2==0 && this.state.counter>0) { var position=Math.floor(Math.random() * 3) + 1; if(position==1){ this.setState({button2_visibility:"o-90 ma1"}); } else if(position==2){ this.setState({button2_visibility:"o-90 ma4"}); } else if(position==3){ this.setState({button2_visibility:"o-90 ma5"}); } this.setState({counter: this.state.counter-1}); console.log(this.state.counter) } else if(this.state.counter==0) { this.setState({button2_visibility:"o-0"}); this.setState({button3_visibility:"o-90"}); } else { this.setState({button2_visibility:"o-0"}); console.log(this.state.counter) this.setState({counter: this.state.counter-1}); } console.log(this.state.score); } next(){ if(this.state.score>3) { var retrievedObject = localStorage.getItem('attributes'); var answers = JSON.parse(retrievedObject); var attribute = ["DA","ED"] for (var key in answers) { //console.log(key) if (answers.hasOwnProperty(key)) { if(_.includes(attribute,key)) answers[key] = answers[key] + 30 } } localStorage.setItem('attributes', JSON.stringify(answers)); var retrievedObject = localStorage.getItem('attributes'); console.log('retrievedObject: ', JSON.parse(retrievedObject)); } browserHistory.push("/child6"); } submit(){ this.setState({score: this.state.score-1}); console.log(this.state.score) } render(){ var button1_visibility = this.state.button1_visibility var button2_visibility = this.state.button2_visibility var button3_visibility = this.state.button3_visibility var counter = this.state.counter return( <div> <Navbar /> <Modal isOpen={this.state.modalIsOpen} onAfterOpen={this.afterOpenModal} onRequestClose={this.closeModal} // style={customStyles} contentLabel="Example Modal" > <h1>Click Game</h1> <h2>Rules</h2> <p>TIn this game a certain number of button will appear in random position at random time. The parent should note down whether the child is able to respond quickly and press the buttons as they appear.</p> <button onClick={this.closeModal.bind(this)}>close</button> </Modal> <div className="shadow-4 pa6 w-70 mv6 ml7 bg-washed-blue ba b--blue"> <button onClick={this.start.bind(this)} className={button1_visibility}>Start</button> <button className={button2_visibility} onClick={this.submit.bind(this)}>Click</button> <button className={button3_visibility} onClick={this.next.bind(this)}>Submit</button> </div> </div> ); } } module.exports = ChildQues5;
app/javascript/mastodon/features/lists/components/new_list_form.js
primenumber/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { changeListEditorTitle, submitListEditor } from '../../../actions/lists'; import IconButton from '../../../components/icon_button'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ label: { id: 'lists.new.title_placeholder', defaultMessage: 'New list title' }, title: { id: 'lists.new.create', defaultMessage: 'Add list' }, }); const mapStateToProps = state => ({ value: state.getIn(['listEditor', 'title']), disabled: state.getIn(['listEditor', 'isSubmitting']), }); const mapDispatchToProps = dispatch => ({ onChange: value => dispatch(changeListEditorTitle(value)), onSubmit: () => dispatch(submitListEditor(true)), }); export default @connect(mapStateToProps, mapDispatchToProps) @injectIntl class NewListForm extends React.PureComponent { static propTypes = { value: PropTypes.string.isRequired, disabled: PropTypes.bool, intl: PropTypes.object.isRequired, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, }; handleChange = e => { this.props.onChange(e.target.value); } handleSubmit = e => { e.preventDefault(); this.props.onSubmit(); } handleClick = () => { this.props.onSubmit(); } render () { const { value, disabled, intl } = this.props; const label = intl.formatMessage(messages.label); const title = intl.formatMessage(messages.title); return ( <form className='column-inline-form' onSubmit={this.handleSubmit}> <label> <span style={{ display: 'none' }}>{label}</span> <input className='setting-text' value={value} disabled={disabled} onChange={this.handleChange} placeholder={label} /> </label> <IconButton disabled={disabled || !value} icon='plus' title={title} onClick={this.handleClick} /> </form> ); } }
packages/cf-component-dynamic-content/example/basic/component.js
manatarms/cf-ui
import React from 'react'; import DynamicContent from 'cf-component-dynamic-content'; class DynamicContentComponent extends React.Component { render() { return ( <DynamicContent dangerouslySetInnerHTML={{ __html: '<p>Not an XSS attack, I swear.</p>' }} /> ); } } export default DynamicContentComponent;
src/svg-icons/action/settings-bluetooth.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsBluetooth = (props) => ( <SvgIcon {...props}> <path d="M11 24h2v-2h-2v2zm-4 0h2v-2H7v2zm8 0h2v-2h-2v2zm2.71-18.29L12 0h-1v7.59L6.41 3 5 4.41 10.59 10 5 15.59 6.41 17 11 12.41V20h1l5.71-5.71-4.3-4.29 4.3-4.29zM13 3.83l1.88 1.88L13 7.59V3.83zm1.88 10.46L13 16.17v-3.76l1.88 1.88z"/> </SvgIcon> ); ActionSettingsBluetooth = pure(ActionSettingsBluetooth); ActionSettingsBluetooth.displayName = 'ActionSettingsBluetooth'; ActionSettingsBluetooth.muiName = 'SvgIcon'; export default ActionSettingsBluetooth;
src/components/children/PlaylistSavedDialog.js
Nfinley/Showcase-Playlist-Generator
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogTitle from '@material-ui/core/DialogTitle'; import Slide from '@material-ui/core/Slide'; import { Link } from 'react-router-dom'; function Transition(props) { return <Slide direction="up" {...props} />; } // eslint-disable-next-line class PlaylistSavedDialog extends Component { render() { const { isOpen, handleClose, playlistName } = this.props; return ( <div> <Dialog open={isOpen} TransitionComponent={Transition} keepMounted onClose={handleClose} aria-labelledby="alert-dialog-slide-title" aria-describedby="alert-dialog-slide-description" > <DialogTitle id="alert-dialog-slide-title"> Playlist Saved! </DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-slide-description"> You have successfully saved your playlist to your Spotify account. </DialogContentText> <DialogContentText id="alert-dialog-slide-description"> It is called <strong>{playlistName}</strong> </DialogContentText> </DialogContent> <DialogActions> <Button onClick={() => handleClose('spotify')} color="primary" name="spotify"> <h5> View in Spotify</h5> </Button> <Button onClick={handleClose} color="primary"> <h5> Back to Dashboard </h5> </Button> <Link to="/search"> <Button onClick={handleClose} color="primary" id="search"> <h5> Search Again </h5> </Button> </Link> </DialogActions> </Dialog> </div> ); } } PlaylistSavedDialog.propTypes = { isOpen: PropTypes.bool.isRequired, handleClose: PropTypes.func.isRequired, playlistName: PropTypes.string.isRequired }; export default PlaylistSavedDialog;
src/routes.js
davidraleigh/universal-redux-starter-todo
import React from 'react'; import { Route } from 'react-router'; import App from './containers/App/App'; export default () => { return ( <Route path="/" component={App} /> ); };
src/components/video_list_item.js
Jaime691/ReactTube
import React from 'react'; const VideoListItem = ({video, onVideoSelect}) => { // const video = props.video; const imageUrl = video.snippet.thumbnails.default.url; return ( <li onClick= {()=> onVideoSelect(video)} className="list-group-item"> <div className="video-list media"> <div className="media-left"> <img className="media-object" src={imageUrl}/> </div> <div className="media-body"> <div className="media-heading"> {video.snippet.title} </div> </div> </div> </li> ); } export default VideoListItem;
src/browser/app/Footer.react.js
SidhNor/este-cordova-starter-kit
import Component from 'react-pure-render/component'; import React from 'react'; import { FormattedHTMLMessage, defineMessages } from 'react-intl'; // Messages collocation ftw. // https://github.com/yahoo/react-intl/wiki/API#definemessages const messages = defineMessages({ madeByHtml: { defaultMessage: 'Sample este+cordova starter kit', id: 'footer.madeByHtml' } }); export default class Footer extends Component { render() { return ( <footer> <p> <FormattedHTMLMessage {...messages.madeByHtml} /> </p> </footer> ); } }
src/js/components/ItemProject/index.js
waagsociety/ams.datahub.client
import React from 'react' import Li from '../Li' export default function ItemProject({ data }) { const { source, projectLeader, projectPartner, temporal, spatial } = data return <section className='ItemProject content'> <h1>Project</h1> <ul> <Li header='Project Leader' content={projectLeader}/> <Li header='Project Partner' content={projectPartner}/> <Li header='Project Duration' content={temporal}/> <Li header='Geographical Focus Area' content={spatial}/> </ul> { source.length ? <a href={source} target='_blank'>Project Website</a> : null } </section> }
src/app.js
Schubidu/gambling-block
import React from 'react'; import ReactDOM from 'react-dom'; import createBrowserHistory from 'history/lib/createHashHistory'; import { syncReduxAndRouter } from 'redux-simple-router'; import routes from './routes'; import Root from './containers/Root'; import configureStore from './redux/configureStore'; const history = createBrowserHistory(); const store = configureStore(window.__INITIAL_STATE__); syncReduxAndRouter(history, store, (state) => state.router); // Render the React application to the DOM ReactDOM.render( <Root history={history} routes={routes} store={store}/>, document.getElementById('root') );
src/components/widgets/InputRange.js
rsamec/react-designer
import React from 'react'; import InputRange from 'react-input-range'; import styleFont from './utils/font'; let Renderer = (props) => { var style = props.style || {}; styleFont(style, props.font); var valueLink = props.valueLink || { value: props.value, requestChange: ()=> { } }; var handleChange = function (comp, values) { valueLink.requestChange(values); }; return ( <div style={style}> <InputRange {...props} value={valueLink.value} onChange={handleChange}/> </div> ); } Renderer.defaultProps = {value:50,minValue:0,maxValue:100}; export default Renderer;