path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/svg-icons/notification/wifi.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationWifi = (props) => ( <SvgIcon {...props}> <path d="M1 9l2 2c4.97-4.97 13.03-4.97 18 0l2-2C16.93 2.93 7.08 2.93 1 9zm8 8l3 3 3-3c-1.65-1.66-4.34-1.66-6 0zm-4-4l2 2c2.76-2.76 7.24-2.76 10 0l2-2C15.14 9.14 8.87 9.14 5 13z"/> </SvgIcon> ); NotificationWifi = pure(NotificationWifi); NotificationWifi.displayName = 'NotificationWifi'; NotificationWifi.muiName = 'SvgIcon'; export default NotificationWifi;
app/client/src/routes/manageCampaignVolunteers/index.js
uprisecampaigns/uprise-app
import React from 'react'; import ManageCampaignVolunteers from 'scenes/ManageCampaignVolunteers'; import Layout from 'components/Layout'; import organizeCampaignPaths from 'routes/organizeCampaignPaths'; export default organizeCampaignPaths({ path: '/organize/:slug/volunteers', component: campaign => ( <Layout> <ManageCampaignVolunteers campaignId={campaign.id} /> </Layout> ), });
src/svg-icons/image/broken-image.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBrokenImage = (props) => ( <SvgIcon {...props}> <path d="M21 5v6.59l-3-3.01-4 4.01-4-4-4 4-3-3.01V5c0-1.1.9-2 2-2h14c1.1 0 2 .9 2 2zm-3 6.42l3 3.01V19c0 1.1-.9 2-2 2H5c-1.1 0-2-.9-2-2v-6.58l3 2.99 4-4 4 4 4-3.99z"/> </SvgIcon> ); ImageBrokenImage = pure(ImageBrokenImage); ImageBrokenImage.displayName = 'ImageBrokenImage'; ImageBrokenImage.muiName = 'SvgIcon'; export default ImageBrokenImage;
packages/carbon-react/src/components/Layer/index.js
carbon-design-system/carbon-components
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import { usePrefix } from '../../internal/usePrefix'; export function Layer({ as: BaseComponent = 'div', className: customClassName, children, ...rest }) { const prefix = usePrefix(); const className = cx(`${prefix}--layer`, customClassName); return ( <BaseComponent {...rest} className={className}> {children} </BaseComponent> ); } Layer.propTypes = { /** * Specify a custom component or element to be rendered as the top-level * element in the component */ as: PropTypes.oneOfType([ PropTypes.func, PropTypes.string, PropTypes.elementType, ]), /** * Provide child elements to be rendered inside of `Theme` */ children: PropTypes.node, /** * Provide a custom class name to be used on the outermost element rendered by * the component */ className: PropTypes.string, };
src/containers/EditPetition.js
iris-dni/iris-frontend
import React from 'react'; import Helmet from 'react-helmet'; import { withRouter } from 'react-router'; import { connect } from 'react-redux'; import { fetchPetition } from 'actions/PetitionActions'; import { updateSuggestionInputValue } from 'actions/AutocompleteActions'; import settings from 'settings'; import citySuggestionFormatter from 'helpers/citySuggestionFormatter'; import EditPetition from 'components/EditPetition'; import getPetitionForm from 'selectors/petitionForm'; const EditPetitionContainer = React.createClass({ componentWillMount () { const { petition, params, fetchPetition, updateSuggestionInputValue } = this.props; if (!petition.id) { fetchPetition(params.id) .then(({ petition }) => { updateSuggestionInputValue( citySuggestionFormatter(petition.city.data) ); }); } else { updateSuggestionInputValue( citySuggestionFormatter(this.props.petition.city) ); } }, render () { return ( <div> <Helmet title={settings.editPetitionPage.title} /> <EditPetition petition={this.props.petition} /> </div> ); } }); export const mapStateToProps = ({ petition }) => ({ petition: getPetitionForm(petition) }); export const mapDispatchToProps = (dispatch) => ({ fetchPetition: (id) => dispatch(fetchPetition(id)), updateSuggestionInputValue: (city) => dispatch(updateSuggestionInputValue(city)) }); export default withRouter(connect( mapStateToProps, mapDispatchToProps )(EditPetitionContainer));
src/components/App.js
migueliriano/react-anime-project
import React from 'react'; import { Provider } from 'react-redux'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import { Switch, Route } from 'react-router-dom'; import Home from 'containers/Home'; import SingleAnimePage from 'containers/SingleAnimePage'; import configureStore from 'configureStore'; import 'index.css'; const store = configureStore(); const App = () => ( <Provider store={store}> <MuiThemeProvider> <Switch>Home <Route exact path="/" component={Home} /> <Route path="/anime/:id" component={SingleAnimePage} /> </Switch> </MuiThemeProvider> </Provider> ); export default App;
examples/example4.js
gabrielbull/react-tether2
import React, { Component } from 'react'; import Target from './example4/target'; import Source from './example4/source'; class Example4 extends Component { getTarget = () => this.refs.target; render() { return ( <div style={{ background: 'red', position: 'relative', padding: '20px' }}> <div style={{ height: '600px', background: 'purple' }}> </div> <Target ref="target"/> <Source target={this.getTarget}/> </div> ); } } export default Example4;
packages/react-scripts/fixtures/kitchensink/src/features/webpack/CssInclusion.js
Bogala/create-react-app-awesome-ts
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import './assets/style.css'; export default () => <p id="feature-css-inclusion">We love useless text.</p>;
examples/with-algolia-react-instantsearch/components/app.js
arunoda/next.js
import React from 'react' import PropTypes from 'prop-types' import { RefinementList, SearchBox, Hits, Configure, Highlight, Pagination } from 'react-instantsearch/dom' import { InstantSearch } from './instantsearch' const HitComponent = ({ hit }) => <div className='hit'> <div> <div className='hit-picture'> <img src={`${hit.image}`} /> </div> </div> <div className='hit-content'> <div> <Highlight attributeName='name' hit={hit} /> <span> {' '}- ${hit.price} </span> <span> {' '}- {hit.rating} stars </span> </div> <div className='hit-type'> <Highlight attributeName='type' hit={hit} /> </div> <div className='hit-description'> <Highlight attributeName='description' hit={hit} /> </div> </div> </div> HitComponent.propTypes = { hit: PropTypes.object } export default class extends React.Component { static propTypes = { searchState: PropTypes.object, resultsState: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), onSearchStateChange: PropTypes.func }; render () { return ( <InstantSearch appId='appId' // change this apiKey='apiKey' // change this indexName='indexName' // change this resultsState={this.props.resultsState} onSearchStateChange={this.props.onSearchStateChange} searchState={this.props.searchState} > <Configure hitsPerPage={10} /> <header> <h1>React InstantSearch + Next.Js</h1> <SearchBox /> </header> <content> <menu> <RefinementList attributeName='category' /> </menu> <results> <Hits hitComponent={HitComponent} /> </results> </content> <footer> <Pagination /> <div> See{' '} <a href='https://github.com/algolia/react-instantsearch/tree/master/packages/react-instantsearch/examples/next-app'> source code </a>{' '} on github </div> </footer> </InstantSearch> ) } }
src/redux/components/App.js
davidraleigh/universal-redux-starter-todo
import React from 'react' import Footer from './Footer' import AddTodo from '../containers/AddTodo' import VisibleTodoList from '../containers/VisibleTodoList' const App = () => ( <div> <AddTodo /> <VisibleTodoList /> <Footer /> </div> ) export default App
admin/client/App/screens/Item/components/EditFormHeader.js
benkroeger/keystone
import React from 'react'; import { findDOMNode } from 'react-dom'; import { connect } from 'react-redux'; import Toolbar from './Toolbar'; import ToolbarSection from './Toolbar/ToolbarSection'; import EditFormHeaderSearch from './EditFormHeaderSearch'; import { Link } from 'react-router'; import Drilldown from './Drilldown'; import { GlyphButton, ResponsiveText } from '../../../elemental'; export const EditFormHeader = React.createClass({ displayName: 'EditFormHeader', propTypes: { data: React.PropTypes.object, list: React.PropTypes.object, toggleCreate: React.PropTypes.func, }, getInitialState () { return { searchString: '', }; }, toggleCreate (visible) { this.props.toggleCreate(visible); }, searchStringChanged (event) { this.setState({ searchString: event.target.value, }); }, handleEscapeKey (event) { const escapeKeyCode = 27; if (event.which === escapeKeyCode) { findDOMNode(this.refs.searchField).blur(); } }, renderDrilldown () { return ( <ToolbarSection left> {this.renderDrilldownItems()} {this.renderSearch()} </ToolbarSection> ); }, renderDrilldownItems () { const { data, list } = this.props; const items = data.drilldown ? data.drilldown.items : []; let backPath = `${Keystone.adminPath}/${list.path}`; const backStyles = { paddingLeft: 0, paddingRight: 0 }; // Link to the list page the user came from if (this.props.listActivePage && this.props.listActivePage > 1) { backPath = `${backPath}?page=${this.props.listActivePage}`; } // return a single back button when no drilldown exists if (!items.length) { return ( <GlyphButton component={Link} data-e2e-editform-header-back glyph="chevron-left" position="left" style={backStyles} to={backPath} variant="link" > {list.plural} </GlyphButton> ); } // prepare the drilldown elements const drilldown = []; items.forEach((item, idx) => { // FIXME @jedwatson // we used to support relationships of type MANY where items were // represented as siblings inside a single list item; this got a // bit messy... item.items.forEach(link => { drilldown.push({ href: link.href, label: link.label, title: item.list.singular, }); }); }); // add the current list to the drilldown drilldown.push({ href: backPath, label: list.plural, }); return ( <Drilldown items={drilldown} /> ); }, renderSearch () { var list = this.props.list; return ( <form action={`${Keystone.adminPath}/${list.path}`} className="EditForm__header__search"> <EditFormHeaderSearch value={this.state.searchString} onChange={this.searchStringChanged} onKeyUp={this.handleEscapeKey} /> {/* <GlyphField glyphColor="#999" glyph="search"> <FormInput ref="searchField" type="search" name="search" value={this.state.searchString} onChange={this.searchStringChanged} onKeyUp={this.handleEscapeKey} placeholder="Search" style={{ paddingLeft: '2.3em' }} /> </GlyphField> */} </form> ); }, renderInfo () { return ( <ToolbarSection right> {this.renderCreateButton()} </ToolbarSection> ); }, renderCreateButton () { const { nocreate, autocreate, singular } = this.props.list; if (nocreate) return null; let props = {}; if (autocreate) { props.href = '?new' + Keystone.csrf.query; } else { props.onClick = () => { this.toggleCreate(true); }; } return ( <GlyphButton data-e2e-item-create-button="true" color="success" glyph="plus" position="left" {...props}> <ResponsiveText hiddenXS={`New ${singular}`} visibleXS="Create" /> </GlyphButton> ); }, render () { return ( <Toolbar> {this.renderDrilldown()} {this.renderInfo()} </Toolbar> ); }, }); export default connect((state) => ({ listActivePage: state.lists.page.index, }))(EditFormHeader);
app/views/Resume.js
sysrex/sysrex
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { withRouter } from 'react-router'; import Helmet from 'react-helmet'; import axios from 'axios'; import Main from '../layouts/Main'; import Education from '../components/Resume/Education'; import Experience from '../components/Resume/Experience'; import Skills from '../components/Resume/Skills'; import Courses from '../components/Resume/Courses'; import References from '../components/Resume/References'; const sections = [ 'Education', 'Experience', 'Skills', 'Courses', 'References', ]; class Resume extends Component { constructor(props) { super(props); this.state = { data: {}, }; } componentWillMount() { axios.get('/api/resume').then(({ data }) => { if (!data.success) { return Promise.reject(data.error); } return this.setState({ data }); }).catch((error) => { console.error('resume-api-fetch-error', error); this.props.history.push('/login'); // eslint-disable-line react/prop-types }); } render() { return ( <Main> <Helmet title="Resume" /> <article className="post" id="resume"> <header> <div className="title"> <h2><Link to="/resume">Resume</Link></h2> <div className="link-container"> {sections.map(sec => ( <h4 key={sec}> <a href={`#${sec.toLowerCase()}`}>{sec}</a> </h4>))} </div> </div> </header> <Education data={this.state.data.degrees} /> <Experience data={this.state.data.positions} /> <Skills skills={this.state.data.skills} categories={this.state.data.categories} /> <Courses data={this.state.data.courses} /> <References /> </article> </Main> ); } } export default withRouter(Resume);
src/svg-icons/action/zoom-in.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionZoomIn = (props) => ( <SvgIcon {...props}> <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14zm2.5-4h-2v2H9v-2H7V9h2V7h1v2h2v1z"/> </SvgIcon> ); ActionZoomIn = pure(ActionZoomIn); ActionZoomIn.displayName = 'ActionZoomIn'; ActionZoomIn.muiName = 'SvgIcon'; export default ActionZoomIn;
react-components/src/library/components/site-notices/notices.js
concord-consortium/rigse
import React from 'react' import Notice from './notice' import css from './style.scss' export default class Notices extends React.Component { constructor (props) { super(props) this.renderNoNotices = this.renderNoNotices.bind(this) } renderNoNotices () { return ( <div className={css.adminSiteNoticesNone}> You have no notices.<br /> To create a notice click the "Create New Notice" button. </div> ) } render () { const { notices, receivedData } = this.props if (!receivedData) { return ( <div> Loading notices... </div> ) } if (notices.length === 0) { return ( this.renderNoNotices() ) } return ( <table id={css.notice_list} className={css.adminSiteNoticesList}> <tbody> <tr> <th>Notice</th> <th>Updated</th> <th>Options</th> </tr> { notices.map(notice => <Notice key={notice.id} notice={notice} getPortalData={this.props.getPortalData} />) } </tbody> </table> ) } }
static/src/containers/Group.js
cas-x/cas-server
/** * @Author: BingWu Yang <detailyang> * @Date: 2016-03-14T10:30:11+08:00 * @Email: [email protected] * @Last modified by: detailyang * @Last modified time: 2016-04-21T17:23:02+08:00 * @License: The MIT License (MIT) */ import React, { Component } from 'react'; import Antd, { Table, Button, Row, Col, Input, Icon, Popconfirm } from 'antd'; import { connect } from 'react-redux'; import GroupEditModal from './GroupEditModal'; import GroupMemberModal from './GroupMemberModal'; import { fetchGroupList, setGroupPage, setGroupKeyword, deleteGroup } from '../actions'; const InputGroup = Input.Group; class Group extends Component { constructor(props) { super(props); this.state = { editModalVisible: false, editModalId: 0, memberModalVisible: false, memberModalTitle: '', memberModalId: 0, }; } componentWillMount() { this.fetchGroupList(); } handleCreateClick() { this.setState({ editModalVisible: true, editModalId: 0 }); } handleEditClick(record) { this.setState({ editModalVisible: true, editModalId: record.id }); } handleDeleteClick(record) { this.props.deleteGroup(record.id) .then(() => { Antd.message.success('删除成功'); this.fetchGroupList(); }) .catch(() => { Antd.message.error('删除失败'); }); } handleKeywordKeyDown(e) { if (e.key === 'Enter') { this.handleSearchClick(); } } handleSearchClick() { this.fetchGroupList(); } openMemberModal(record) { this.setState({ memberModalTitle: record.name, memberModalId: record.id, memberModalVisible: true, }); } fetchGroupList() { return this.props.fetchGroupList() .catch(error => Antd.message.error(error.message)); } renderTable() { const columns = [ { title: '组名', dataIndex: 'name', key: 'name', }, { title: '描述', dataIndex: 'desc', key: 'desc', }, { title: '创建时间', dataIndex: 'created_at', key: 'created_at', }, { title: '操作', dataIndex: 'x', key: 'x', className: 'text-rigth', render: (value, record) => { return ( <div> <Button type="ghost" size="small" onClick={() => this.openMemberModal(record)} > 成员 </Button> <Button type="ghost" size="small" onClick={() => this.handleEditClick(record)} > 编辑 </Button> <Popconfirm placement="left" title="确认删除?" onConfirm={() => this.handleDeleteClick(record)} > <Button type="ghost" size="small">删除</Button> </Popconfirm> </div> ); }, }, ]; const { group: { list, loading, page, per_page, total }, setGroupPage, } = this.props; list.forEach(item => { item.key = item.id; }); const pagination = { total, current: page, pageSize: per_page, showTotal: (_total) => `共 ${_total} 条`, onChange: (_page) => { setGroupPage(_page); this.fetchGroupList(); }, }; return ( <Table dataSource={list} loading={loading} columns={columns} pagination={pagination} />); } renderFilter() { const { setGroupKeyword } = this.props; return ( <Row style={{ marginBottom: '10px' }}> <Col span="2"> <Button type="primary" onClick={::this.handleCreateClick}> <Icon type="plus" />新建 </Button> </Col> <Col span="4" offset="18"> <InputGroup className="ant-search-input" size="default"> <Input defaultValue={this.state.keyword} onChange={e => { setGroupKeyword(e.target.value); }} onKeyDown={::this.handleKeywordKeyDown} /> <div className="ant-input-group-wrap"> <Button className="ant-search-btn" onClick={this.handleSearchClick}> <Icon type="search" /> </Button> </div> </InputGroup> </Col> </Row> ); } renderEditModal() { if (!this.state.editModalVisible) { return ''; } const handleOk = () => { this.setState({ editModalVisible: false }); this.fetchGroupList(); }; const handleCancel = () => { this.setState({ editModalVisible: false }); }; return ( <GroupEditModal id={this.state.editModalId} visible={this.state.editModalVisible} onOk={handleOk} onCancel={handleCancel} />); } renderMemberModal() { if (!this.state.memberModalVisible) { return ''; } const handleClose = () => { this.setState({ memberModalVisible: false }); }; return ( <GroupMemberModal visible={this.state.memberModalVisible} title={this.state.memberModalTitle} id={this.state.memberModalId} onOk={handleClose} onCancel={handleClose} />); } render() { return ( <div> {this.renderEditModal()} {this.renderMemberModal()} {this.renderFilter()} {this.renderTable()} </div> ); } } export default connect( ({ group }) => ({ group }), { fetchGroupList, setGroupPage, setGroupKeyword, deleteGroup } )(Group);
src/components/Promises/promises_categories_tabs.js
Betree/democracy-watcher
import React from 'react' import TabsView from '../Utils/tabs_view' import PromisesList from './promises_list' const PromisesCategoriesTabs = ({categories, promises}) => { // Categorize promises in an object const promisesTabs = [] for(let category of categories) { const promisesList = <PromisesList promises={promises[category]}/> promisesTabs.push(TabsView.create_tab(category, category, promisesList)) } return <TabsView className="tabs-view" tabs={promisesTabs}/> } export default PromisesCategoriesTabs
src/index.js
chasm/react-redux-base
import React from 'react' import ReactDOM from 'react-dom' import App from './components/App.jsx' const app = document.createElement('div') document.body.appendChild(app) ReactDOM.render(<App/>, app)
newclient/scripts/components/user/sidebar-step/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ import styles from './style'; import React from 'react'; import classNames from 'classnames'; import {CurrentStepIcon} from '../../dynamic-icons/current-step-icon'; import {CompletedStepIcon} from '../../dynamic-icons/completed-step-icon'; import {DisclosureActions} from '../../../actions/disclosure-actions'; export class SidebarStep extends React.Component { constructor() { super(); this.navigate = this.navigate.bind(this); } navigate() { DisclosureActions.jumpToStep(this.props.step); } render() { switch (this.props.state.toLowerCase()) { case 'complete': return ( <div className={classNames(styles.clickable, this.props.className)} onClick={this.navigate}> <li className={styles.container}> <CompletedStepIcon className={`${styles.override} ${styles.icon}`} color={window.colorBlindModeOn ? 'black' : '#0095A0'} /> <span className={styles.stepName}>{this.props.label}</span> </li> </div> ); case 'active': return ( <div className={classNames(this.props.className)}> <li className={`${styles.container} ${styles.selected}`}> <CurrentStepIcon className={`${styles.override} ${styles.icon}`} color={window.colorBlindModeOn ? 'black' : '#0095A0'} /> <span className={styles.stepName}>{this.props.label}</span> </li> </div> ); case 'incomplete': if (this.props.visited) { return ( <li className={classNames(styles.container, styles.clickable, this.props.className)} onClick={this.navigate}> <i className={`fa fa-circle ${styles.futureIcon}`} /> <span className={styles.stepName}>{this.props.label}</span> </li> ); } return ( <li className={classNames(styles.container, styles.incomplete, this.props.className)}> <i className={`fa fa-circle ${styles.futureIcon} ${styles.incomplete}`} /> <span className={styles.stepName}>{this.props.label}</span> </li> ); } } } SidebarStep.defaultProps = { state: '' };
frontend/src/AddMovie/AddNewMovie/AddNewMovieConnector.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { clearAddMovie, lookupMovie } from 'Store/Actions/addMovieActions'; import { clearQueueDetails, fetchQueueDetails } from 'Store/Actions/queueActions'; import { fetchRootFolders } from 'Store/Actions/rootFolderActions'; import { fetchImportExclusions } from 'Store/Actions/Settings/importExclusions'; import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector'; import parseUrl from 'Utilities/String/parseUrl'; import AddNewMovie from './AddNewMovie'; function createMapStateToProps() { return createSelector( (state) => state.addMovie, (state) => state.movies.items.length, (state) => state.router.location, createUISettingsSelector(), (addMovie, existingMoviesCount, location, uiSettings) => { const { params } = parseUrl(location.search); return { ...addMovie, term: params.term, hasExistingMovies: existingMoviesCount > 0, colorImpairedMode: uiSettings.enableColorImpairedMode }; } ); } const mapDispatchToProps = { lookupMovie, clearAddMovie, fetchRootFolders, fetchImportExclusions, fetchQueueDetails, clearQueueDetails }; class AddNewMovieConnector extends Component { // // Lifecycle constructor(props, context) { super(props, context); this._movieLookupTimeout = null; } componentDidMount() { this.props.fetchRootFolders(); this.props.fetchImportExclusions(); this.props.fetchQueueDetails(); } componentWillUnmount() { if (this._movieLookupTimeout) { clearTimeout(this._movieLookupTimeout); } this.props.clearAddMovie(); this.props.clearQueueDetails(); } // // Listeners onMovieLookupChange = (term) => { if (this._movieLookupTimeout) { clearTimeout(this._movieLookupTimeout); } if (term.trim() === '') { this.props.clearAddMovie(); } else { this._movieLookupTimeout = setTimeout(() => { this.props.lookupMovie({ term }); }, 300); } }; onClearMovieLookup = () => { this.props.clearAddMovie(); }; // // Render render() { const { term, ...otherProps } = this.props; return ( <AddNewMovie term={term} {...otherProps} onMovieLookupChange={this.onMovieLookupChange} onClearMovieLookup={this.onClearMovieLookup} /> ); } } AddNewMovieConnector.propTypes = { term: PropTypes.string, lookupMovie: PropTypes.func.isRequired, clearAddMovie: PropTypes.func.isRequired, fetchRootFolders: PropTypes.func.isRequired, fetchImportExclusions: PropTypes.func.isRequired, fetchQueueDetails: PropTypes.func.isRequired, clearQueueDetails: PropTypes.func.isRequired }; export default connect(createMapStateToProps, mapDispatchToProps)(AddNewMovieConnector);
stories/Dropdown/ExampleWithCustomValue.js
skyiea/wix-style-react
import React from 'react'; import Dropdown from 'wix-style-react/Dropdown'; import Checkbox from 'wix-style-react/Checkbox'; const style = { display: 'inline-block', padding: '0 5px 0', width: '200px', lineHeight: '22px', marginBottom: '350px' }; class CustomValuesInDropdown extends React.Component { constructor(props) { super(props); this.state = {checkboxChecked: false}; } render() { const valueParser = option => (typeof option.value === 'string') ? option.value : option.value.props.children[0].props.children; const onSelect = option => console.log('Selected ', valueParser(option)); const onChange = () => this.setState({checkboxChecked: !this.state.checkboxChecked}); const customValue = ( <div> <span>Custom Value</span> <span style={{marginLeft: '5px'}} onClick={e => e.stopPropagation()}> <Checkbox onChange={onChange} checked={this.state.checkboxChecked}/> </span> </div> ); const options = [ {id: 1, value: 'Option 1'}, {id: 2, value: 'Option 2'}, {id: 3, value: 'Option 3'}, {id: 4, value: 'Option 4', disabled: true}, {id: 5, value: 'Option 5'}, {id: 6, value: customValue}, {id: 7, value: customValue} ]; return ( <Dropdown options={options} selectedId={6} placeholder={'Choose an option'} valueParser={valueParser} onSelect={onSelect} /> ); } } export default () => <div className="ltr" style={style}> <CustomValuesInDropdown/> </div>;
src/components/App/index.js
mvaldas9/wallscreen
import './styles.css'; import React from 'react'; import Background from '../Background'; import Clock from '../Clock'; import Board from '../Board'; import Settings from '../Settings'; class App extends React.Component { render() { return ( <div className="app"> <Background /> <Clock /> <Board /> <Settings /> </div> ); } } export default App;
src/components/Main.js
bjhan/mytesthome
require('normalize.css/normalize.css'); require('styles/App.css'); import React from 'react'; //获取图片的信息 var imageDatas = require('../data/imageDatas.json'); //利用自执行函数,返回图片的URL信息 imageDatas = (function getImageURL(imageDatasArr) { for(var i = 0;i < imageDatasArr.length; i++){ var singleImageData = imageDatasArr[i]; singleImageData.imgURL = require('../images/' + singleImageData.filename); imageDatasArr[i] = singleImageData; } return imageDatasArr; })(imageDatas); class ImgFigures extends React.Component { render() { return ( <figure className = "img-figure"> <img src={this.props.data.imgURL} alt={this.props.data.title}/> <figcaption> <h2 className = "img-title">{this.props.data.title}</h2> </figcaption> </figure> ); } } class AppComponent extends React.Component { Constant:{ centerPos:{ left: 0; right: 0; }, hPosRange: { leftSecX: [0,0], rightSecX: [0,0], y: [0,0] }, vPosRange: { x: [0,0], topY: [0,0] } }; //获取区间内随机值 function getRangeRandom(low, high) { return Math.ceil(Math.random() * (high - low) + low); } rearange = function (centerIndex) { var imgsArrangeArr = this.state.imgsArrangeArr, Constant = this.Constant, centerPos = Constant.centerPos, hPosRange = Constant.hPosRange, vPosRange = Constant.vPosRange, hPosRangeLeftSecX = hPosRange.leftSecX, hPosRangeRightSecX = hPosRange.rightSecx, hPosRangeY = hPosRange.y, vPosRangeTopY = vPosRange.topY, vPosRangeX = vPosRange.x, imgsArrangeTopArr = [], topImgNum = Math.ceil(Math.random() * 2), topImgSpliceIndex = 0, imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex,1); //居中 imgsArrangeCenterArr[0].pos = centerPos; //取出布局上册图片的状态信息 topImgSpliceIndex = Math.ceil(Math.random * (imgsArrangeArr.length - topImgNum)); imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex,topImgNum); //布局上册图片 imgsArrangeTopArr.forEach(function (value,index) { imgsArrangeTopArr[index].pos = { top: , left: } }); } getInitialState() { return { imgsArrangeArr: [ /* { pos: { left: 0, right: 0 } } */ ] }; } //组件加载以后为每一张图片计算范围 componentDidMount() { //拿到舞台大小 var stageDom = this.refs.stage, stageWidth = stageDom.scrollWidth, stageHeight = stageDom.scrollHeight, halfStageW = Math.ceil(stageWidth / 2), halfStageH = Math.ceil(stageHeight / 2); //拿到imageFigure大小 var imgFigureDom = this.refs.imageFigure0, imageW = imgFigureDom.scrollWidth, imageH = imgFigureDom.scrollHeight, halfImgW = Math.ceil(imageW / 2), halfImgH = Math.ceil(imageH / 2); //计算中心图片的位置点 this.Constant.centerPos = { left: halfStageW - halfImgW, top: halfStageH - halfImgH } //计算左侧右侧区域图片排布图片取值范围 this.Constant.hPosRange.leftSecX[0] = -halfImgW; this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3; this.Constant.hPosRange.rightSecX[0] = halfStageW - halfImgW; this.Constant.hPosRange.rightSecX[1] = stageWidth -halfImgW; this.Constant.hPosRange.y[0] = -halfImgH; this.Constant.hPosRange.y[1] = stageHeight - halfImgH; //计算上侧区域图片排布位置的取值范围 this.Constant.vPosRange.topY[0] = -halfImgH; this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3; this.Constant.vPosRange.x[0] = halfImgW -imageW; this.Constant.vPosRange.x[1] = halfImgW this.rearange(0); } render() { var controllerUnits = [], imgFigure = []; imageDatas.forEach(function (value,index) { if(!this.state.imgsArrangeArr[index]){ this.state.imgsArrangeArr[index] = { pos: { left: 0, top: 0 } } } imgFigure.push(<ImgFigures data = {value} key = {value.filename} ref ={'imageFigure'+index}/>); }.bind(this)); return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFigure} </section> <nav className="controller-nav"> {controllerUnits} </nav> </section> ); } } AppComponent.defaultProps = { }; export default AppComponent;
packages/reactor-tests/src/App.js
dbuhrman/extjs-reactor
import React, { Component } from 'react'; import { Router, Route, IndexRoute, Link, hashHistory } from 'react-router' import * as tests from './tests'; import Layout from './Layout'; import TestIndex from './TestIndex'; export default class App extends Component { render() { return ( <Router history={hashHistory}> <Route path="/" component={Layout}> <IndexRoute component={TestIndex}/> { Object.keys(tests).map(name => ( <Route key={name} path={name} component={tests[name]}/> ))} </Route> </Router> ) } }
src/Tooltip.js
adampickeral/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import CustomPropTypes from './utils/CustomPropTypes'; const Tooltip = React.createClass({ mixins: [BootstrapMixin], propTypes: { /** * An html id attribute, necessary for accessibility * @type {string} * @required */ id: CustomPropTypes.isRequiredForA11y( React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]) ), /** * Sets the direction the Tooltip is positioned towards. */ placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "left" position value for the Tooltip. */ positionLeft: React.PropTypes.number, /** * The "top" position value for the Tooltip. */ positionTop: React.PropTypes.number, /** * The "left" position value for the Tooltip arrow. */ arrowOffsetLeft: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]), /** * The "top" position value for the Tooltip arrow. */ arrowOffsetTop: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]), /** * Title text */ title: React.PropTypes.node }, getDefaultProps() { return { placement: 'right' }; }, render() { const classes = { 'tooltip': true, [this.props.placement]: true }; const style = { 'left': this.props.positionLeft, 'top': this.props.positionTop, ...this.props.style }; const arrowStyle = { 'left': this.props.arrowOffsetLeft, 'top': this.props.arrowOffsetTop }; return ( <div role='tooltip' {...this.props} className={classNames(this.props.className, classes)} style={style}> <div className="tooltip-arrow" style={arrowStyle} /> <div className="tooltip-inner"> {this.props.children} </div> </div> ); } }); export default Tooltip;
packages/watif-display/src/components/display.js
jwillesen/watif
import React from 'react' import {func, string} from 'prop-types' import {FontAwesomeIcon} from '@fortawesome/react-fontawesome' import {faBook, faEye, faSearch, faHandHoldingBox} from '@fortawesome/pro-regular-svg-icons' import {Tabs, TabPanel} from './tabs' import InteractiveDescription from './interactive-description' import Watext from './watext' import {storyShape} from '../property-shapes' import './display.css' export default class Display extends React.Component { static propTypes = { storyState: storyShape.isRequired, executeVerb: func, // ({ id: verb-id, subject: item-id, target: (item-id | null) }) title: string, } constructor(...args) { super(...args) this.state = { activeTab: 'look', } } handleTabRequest = tabPanelId => { this.setState({activeTab: tabPanelId}) } handleItemClick = itemId => { if (this.props.executeVerb) { this.props.executeVerb({ id: 'examine', subject: itemId, target: null, }) } this.setState({activeTab: 'examine'}) } handleCurrentItemVerbClick = verb => { if (!this.props.executeVerb) return this.props.executeVerb({ id: verb.id, subject: this.props.storyState.universe.currentItemId, }) // this.setState({activeTab: 'events'}) } handleCurrentRoomVerbClick = verb => { if (!this.props.executeVerb) return this.props.executeVerb({ id: verb.id, subject: this.props.storyState.universe.currentRoomId, }) // this.setState({activeTab: 'events'}) } icon(fa) { return <FontAwesomeIcon icon={fa} size="lg" /> } render() { return ( <div styleName="root"> <div styleName="log-header"> <div styleName="log-header-icon"> {this.icon(faBook)} {this.props.title} </div> </div> <div styleName="log"> <Watext watext={this.props.storyState.universe.log} /> </div> <div styleName="tabs"> <Tabs label="Story Content" activeTab={this.state.activeTab} onTabRequest={this.handleTabRequest} > <TabPanel id="look" label={this.icon(faEye)} a11yLabel="look around"> <InteractiveDescription title="Look Around" emptyText="No Current Room" watext={this.props.storyState.currentRoomDescription} verbs={this.props.storyState.currentRoomVerbs} onItemClick={this.handleItemClick} onVerbClick={this.handleCurrentRoomVerbClick} /> </TabPanel> <TabPanel id="examine" label={this.icon(faSearch)} a11yLabel="examine"> <InteractiveDescription title="Examine" emptyText="No Current Item" watext={this.props.storyState.currentItemDescription} verbs={this.props.storyState.currentItemVerbs} onItemClick={this.handleItemClick} onVerbClick={this.handleCurrentItemVerbClick} /> </TabPanel> <TabPanel id="inventory" label={this.icon(faHandHoldingBox)} a11yLabel="inventory"> <span>Inventory</span> </TabPanel> </Tabs> </div> </div> ) } }
src/svg-icons/editor/vertical-align-center.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorVerticalAlignCenter = (props) => ( <SvgIcon {...props}> <path d="M8 19h3v4h2v-4h3l-4-4-4 4zm8-14h-3V1h-2v4H8l4 4 4-4zM4 11v2h16v-2H4z"/> </SvgIcon> ); EditorVerticalAlignCenter = pure(EditorVerticalAlignCenter); EditorVerticalAlignCenter.displayName = 'EditorVerticalAlignCenter'; EditorVerticalAlignCenter.muiName = 'SvgIcon'; export default EditorVerticalAlignCenter;
node_modules/react-bootstrap/es/Badge.js
ProjectSunday/rooibus
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; // TODO: `pullRight` doesn't belong here. There's no special handling here. var propTypes = { pullRight: React.PropTypes.bool }; var defaultProps = { pullRight: false }; var Badge = function (_React$Component) { _inherits(Badge, _React$Component); function Badge() { _classCallCheck(this, Badge); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Badge.prototype.hasContent = function hasContent(children) { var result = false; React.Children.forEach(children, function (child) { if (result) { return; } if (child || child === 0) { result = true; } }); return result; }; Badge.prototype.render = function render() { var _props = this.props, pullRight = _props.pullRight, className = _props.className, children = _props.children, props = _objectWithoutProperties(_props, ['pullRight', 'className', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), { 'pull-right': pullRight, // Hack for collapsing on IE8. hidden: !this.hasContent(children) }); return React.createElement( 'span', _extends({}, elementProps, { className: classNames(className, classes) }), children ); }; return Badge; }(React.Component); Badge.propTypes = propTypes; Badge.defaultProps = defaultProps; export default bsClass('badge', Badge);
frontend/assets/js/layout/GenreSlide.js
fga-verival/2017-1Grupo2
import React from 'react'; import Slider from 'react-slick' require("slick-carousel/slick/slick.css"); require("slick-carousel/slick/slick-theme.css"); import GameCard from "../components/cards/GameCard"; import { gameListApi } from '../resource/GameApi'; import { Link } from 'react-router-dom' import { Grid } from 'semantic-ui-react' const slideHeight = { "height": "280px", "position":"relative", "minHeight":"180px", }; export default class GenreSlide extends React.Component { constructor (props) { super(props); this.state = {"games": []}; } componentWillMount () { gameListApi((games) => { this.setState({games}) }); } render() { const gameCards = this.mountCards(); const settings = { dots: true, centerMode: true, infinite: true, speed: 500, slidesToShow: 3, slidesToScroll: 1, responsive: [ { breakpoint: 980, settings: { arrows: false, centerMode: true, centerPadding: '40px', slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: false, centerMode: true, centerPadding: '40px', slidesToShow: 1 } } ] }; if(gameCards.length){ return ( <div style={slideHeight}> <Grid.Column> <Slider {...settings}> {gameCards} </Slider> </Grid.Column> </div> ); }else{ return <img/> } } mountCards(){ const gameCards = [], cardsAmount = 6; for(var i=0; i < cardsAmount && i < this.state.games.length - 1; i++){ const image = (<div> <Link to={"games/" + this.state.games[i].pk}> <GameCard data={this.state.games[i]} /> </Link> </div>) gameCards.push(image); } return gameCards; } }
app/containers/App.js
lumibloc/tabloc
// @flow import React, { Component } from 'react'; import type { Children } from 'react'; export default class App extends Component { props: { children: Children }; render() { return ( <div> {this.props.children} </div> ); } }
docs/src/Anchor.js
roderickwang/react-bootstrap
import React from 'react'; const Anchor = React.createClass({ propTypes: { id: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]) }, render() { return ( <a id={this.props.id} href={'#' + this.props.id} className="anchor"> <span className="anchor-icon">#</span> {this.props.children} </a> ); } }); export default Anchor;
imports/ui/pages/reset-password.js
irvinlim/free4all
import React from 'react'; import { Grid, Row, Col, Alert, FormGroup, ControlLabel, FormControl, Button } from 'react-bootstrap'; import { handleResetPassword } from '../../modules/reset-password'; export class ResetPassword extends React.Component { componentDidMount() { handleResetPassword({ component: this, token: this.props.params.token, }); } handleSubmit(event) { event.preventDefault(); } render() { return <Grid> <Row> <Col xs={ 12 } sm={ 6 } md={ 4 }> <h4 className="page-header">Reset Password</h4> <Alert bsStyle="info"> To reset your password, enter a new one below. You will be logged in with your new password. </Alert> <form ref="resetPassword" className="reset-password" onSubmit={ this.handleSubmit }> <FormGroup> <ControlLabel>New Password</ControlLabel> <FormControl type="password" ref="newPassword" name="newPassword" placeholder="New Password" /> </FormGroup> <FormGroup> <ControlLabel>Repeat New Password</ControlLabel> <FormControl type="password" ref="repeatNewPassword" name="repeatNewPassword" placeholder="Repeat New Password" /> </FormGroup> <Button type="submit" bsStyle="success">Reset Password &amp; Login</Button> </form> </Col> </Row> </Grid>; } } ResetPassword.propTypes = { params: React.PropTypes.object, };
src/index.js
GiacomoSorbi/8-form-elements
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
app/common/components/AuthenticationManager.js
BitLooter/Stuffr-frontend
import React from 'react' import { connect } from 'react-redux' import PropTypes from 'prop-types' import log from 'loglevel' import LoginDialog from './LoginDialog' import RegisterDialog from './RegisterDialog' import PasswordResetDialog from './PasswordResetDialog' const MODE_LOGIN = Symbol('MODE_LOGIN') const MODE_REGISTER = Symbol('MODE_REGISTER') const MODE_PWRESET = Symbol('MODE_PWRESET') const reduxWrapper = connect( function mapStateToProps (state) { return { authenticated: state.auth.authenticated } } ) class AuthenticationManagerComponent extends React.Component { static propTypes = { children: PropTypes.node.isRequired, authenticated: PropTypes.bool.isRequired, onLogin: PropTypes.func.isRequired, onRegister: PropTypes.func } constructor (props) { super(props) this.state = { mode: MODE_LOGIN } } switchMode (mode) { log.info(`Authentication mode switching to ${String(mode)}`) this.setState({mode}) } render () { // onRegister is optional const handleRegister = this.props.onRegister || this.props.onLogin let component // TODO: Password reset mode if (this.props.authenticated) { // Rest of the UI is only rendered if user is authenticated component = <div>{this.props.children}</div> } else if (this.state.mode === MODE_LOGIN) { // TODO: Allow to disable user register button component = <LoginDialog onLogin={this.props.onLogin} handleSwitchToRegister={() => this.switchMode(MODE_REGISTER)} handleSwitchToPWReset={() => this.switchMode(MODE_PWRESET)} /> } else if (this.state.mode === MODE_REGISTER) { component = <RegisterDialog onRegister={handleRegister} handleSwitchToLogin={() => this.switchMode(MODE_LOGIN)} /> } else if (this.state.mode === MODE_PWRESET) { component = <PasswordResetDialog handleSwitchToLogin={() => this.switchMode(MODE_LOGIN)} /> } else { log.error(`AuthenticationManager: Unknown mode ${this.state.mode}`) } return component } } const AuthenticationManager = reduxWrapper(AuthenticationManagerComponent) export default AuthenticationManager
src/index.js
nebgnahz/marry-guess
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
src/index.js
mitchallen/react-card-grey
/* Module: @mitchallen/react-card-grey Author: Mitch Allen */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; // import { withRouter } from 'react-router-dom'; import Paper from 'material-ui/Paper'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; const paperStyle = { height: 300, width: 300, margin: 20, textAlign: 'center', display: 'inline-block', backgroundColor: 'rgba(0, 0, 0, 0.5)' }; // const CardGrey = ({ children, ...props }) => ( const CardGrey = ({ children }) => ( <div> <MuiThemeProvider> <Paper style={paperStyle} zDepth={5}> {children} </Paper> </MuiThemeProvider> </div> ); CardGrey.propTypes = { children: PropTypes.object }; export default CardGrey;
node_modules/antd/es/anchor/index.js
prodigalyijun/demo-by-antd
import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import addEventListener from 'rc-util/es/Dom/addEventListener'; import AnchorLink from './AnchorLink'; import Affix from '../affix'; import AnchorHelper, { getDefaultTarget } from './anchorHelper'; var Anchor = function (_React$Component) { _inherits(Anchor, _React$Component); function Anchor(props) { _classCallCheck(this, Anchor); var _this = _possibleConstructorReturn(this, (Anchor.__proto__ || Object.getPrototypeOf(Anchor)).call(this, props)); _this.handleScroll = function () { _this.setState({ activeAnchor: _this.anchorHelper.getCurrentAnchor(_this.props.offsetTop, _this.props.bounds) }); }; _this.updateInk = function () { var activeAnchor = _this.anchorHelper.getCurrentActiveAnchor(); if (activeAnchor) { _this.refs.ink.style.top = activeAnchor.offsetTop + activeAnchor.clientHeight / 2 - 4.5 + 'px'; } }; _this.clickAnchorLink = function (href, component) { _this._avoidInk = true; _this.refs.ink.style.top = component.offsetTop + component.clientHeight / 2 - 4.5 + 'px'; _this.anchorHelper.scrollTo(href, _this.props.offsetTop, getDefaultTarget, function () { _this._avoidInk = false; }); }; _this.renderAnchorLink = function (child) { var href = child.props.href; var type = child.type; if (type.__ANT_ANCHOR_LINK && href) { _this.anchorHelper.addLink(href); return React.cloneElement(child, { onClick: _this.clickAnchorLink, prefixCls: _this.props.prefixCls, bounds: _this.props.bounds, affix: _this.props.affix || _this.props.showInkInFixed, offsetTop: _this.props.offsetTop }); } return child; }; _this.state = { activeAnchor: null, animated: true }; _this.anchorHelper = new AnchorHelper(); return _this; } _createClass(Anchor, [{ key: 'getChildContext', value: function getChildContext() { return { anchorHelper: this.anchorHelper }; } }, { key: 'componentDidMount', value: function componentDidMount() { this.handleScroll(); this.updateInk(); this.scrollEvent = addEventListener((this.props.target || getDefaultTarget)(), 'scroll', this.handleScroll); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { if (this.scrollEvent) { this.scrollEvent.remove(); } } }, { key: 'componentDidUpdate', value: function componentDidUpdate() { if (!this._avoidInk) { this.updateInk(); } } }, { key: 'render', value: function render() { var _classNames; var _props = this.props, prefixCls = _props.prefixCls, offsetTop = _props.offsetTop, style = _props.style, _props$className = _props.className, className = _props$className === undefined ? '' : _props$className, affix = _props.affix, showInkInFixed = _props.showInkInFixed; var _state = this.state, activeAnchor = _state.activeAnchor, animated = _state.animated; var inkClass = classNames((_classNames = {}, _defineProperty(_classNames, prefixCls + '-ink-ball', true), _defineProperty(_classNames, 'animated', animated), _defineProperty(_classNames, 'visible', !!activeAnchor), _classNames)); var wrapperClass = classNames(_defineProperty({}, prefixCls + '-wrapper', true), className); var anchorClass = classNames(prefixCls, { 'fixed': !affix && !showInkInFixed }); var anchorContent = React.createElement( 'div', { className: wrapperClass, style: style }, React.createElement( 'div', { className: anchorClass }, React.createElement( 'div', { className: prefixCls + '-ink' }, React.createElement('span', { className: inkClass, ref: 'ink' }) ), React.Children.toArray(this.props.children).map(this.renderAnchorLink) ) ); return !affix ? anchorContent : React.createElement( Affix, { offsetTop: offsetTop }, anchorContent ); } }]); return Anchor; }(React.Component); export default Anchor; Anchor.Link = AnchorLink; Anchor.defaultProps = { prefixCls: 'ant-anchor', affix: true, showInkInFixed: false }; Anchor.childContextTypes = { anchorHelper: PropTypes.any };
src/svg-icons/social/group-add.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialGroupAdd = (props) => ( <SvgIcon {...props}> <path d="M8 10H5V7H3v3H0v2h3v3h2v-3h3v-2zm10 1c1.66 0 2.99-1.34 2.99-3S19.66 5 18 5c-.32 0-.63.05-.91.14.57.81.9 1.79.9 2.86s-.34 2.04-.9 2.86c.28.09.59.14.91.14zm-5 0c1.66 0 2.99-1.34 2.99-3S14.66 5 13 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm6.62 2.16c.83.73 1.38 1.66 1.38 2.84v2h3v-2c0-1.54-2.37-2.49-4.38-2.84zM13 13c-2 0-6 1-6 3v2h12v-2c0-2-4-3-6-3z"/> </SvgIcon> ); SocialGroupAdd = pure(SocialGroupAdd); SocialGroupAdd.displayName = 'SocialGroupAdd'; export default SocialGroupAdd;
src/encoded/static/components/anno_viz.js
T2DREAM/t2dream-portal
import React from 'react'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; import _ from 'underscore'; import moment from 'moment'; import globals from './globals'; import { Panel, PanelHeading, TabPanel, TabPanelPane } from '../libs/bootstrap/panel'; import { Modal, ModalHeader, ModalBody, ModalFooter } from '../libs/bootstrap/modal'; import { auditDecor, auditsDisplayed, AuditIcon } from './audit'; import StatusLabel from './statuslabel'; import { requestFiles, DownloadableAccession, BrowserSelector } from './objectutils'; import { Graph, JsonGraph } from './graph'; import { qcModalContent, qcIdToDisplay } from './quality_metric'; import { softwareVersionList } from './software'; import { FetchedData, Param } from './fetched'; import { collapseIcon } from '../libs/svg-icons'; import { SortTablePanel, SortTable } from './sorttable'; var button = require('../libs/bootstrap/button'); export const FileGallery = createReactClass({ propTypes: { context: PropTypes.object, // Dataset object whose annotations we're rendering }, contextTypes: { session: PropTypes.object, // Login information location_href: PropTypes.string, // URL of this variant search page, including query string stuff }, render: function () { const { context } = this.props; return ( <FetchedData ignoreErrors> <Param name="schemas" url="/profiles/" /> <FileGalleryRenderer context={context} session={this.context.session} /> </FetchedData> ); }, }); export function assembleGraph(context, session, infoNodeId, query, regions, viz) { // Create an empty graph architecture that we fill in next. const jsonGraph = new JsonGraph(context.accession); const queryNodeId = query; const queryNodeLabel = query; const fileCssClass = `pipeline-node-file${infoNodeId === queryNodeId ? ' active' : ''}`; jsonGraph.addNode(queryNodeId, queryNodeLabel, { cssClass: fileCssClass, type: 'Viz', shape: 'rect', cornerRadius: 16, }); Object.keys(viz).forEach((vizId) => { const annotations = viz[vizId]; const annotationNodeId = annotations['id']; const annotationNodeLabel = annotations['id']; const regionNodeId = annotations['value']; const regionNodeLabel = annotations['value']; jsonGraph.addNode(annotationNodeId, annotationNodeLabel, { cssClass: fileCssClass, type: 'Viz', shape: 'rect', cornerRadius: 16, }); jsonGraph.addNode(regionNodeId, regionNodeLabel, { cssClass: fileCssClass, type: 'Viz', shape: 'rect', cornerRadius: 16, }); jsonGraph.addEdge(queryNodeId, annotationNodeId); jsonGraph.addEdge(annotationNodeId, regionNodeId); }); return { graph: jsonGraph }; } // Function to render the variant annotation graph, and it gets called after the viz results i.e. annotation type, state and biosample const FileGalleryRenderer = createReactClass({ propTypes: { context: PropTypes.object, // Dataset whose files we're rendering hideGraph: PropTypes.bool, // T to hide graph display }, contextTypes: { session: PropTypes.object, session_properties: PropTypes.object, location_href: PropTypes.string, }, getInitialState: function () { return { infoNodeId: '', // @id of node whose info panel is open infoModalOpen: false, // True if info modal is open relatedFiles: [], }; }, // Called from child components when the selected node changes. setInfoNodeId: function (nodeId) { this.setState({ infoNodeId: nodeId }); }, setInfoNodeVisible: function (visible) { this.setState({ infoNodeVisible: visible }); }, render: function () { const { context, schemas, hideGraph } = this.props; let jsonGraph; const query = context['query']; const regions = context['regions']; const viz = context['viz']; const loggedIn = this.context.session && this.context.session['auth.userid']; // Build node graph of the files and analysis steps with this experiment if ( regions && regions.length ) { const { graph } = assembleGraph(context, this.context.session, this.state.infoNodeId, query, regions, viz); jsonGraph = graph; return ( <Panel> {/* Display the strip of filgering controls */} {!hideGraph ? <FileGraph context={context} items={regions} graph={jsonGraph} query={query} viz={viz} session={this.context.session} infoNodeId={this.state.infoNodeId} setInfoNodeId={this.setInfoNodeId} infoNodeVisible={this.state.infoNodeVisible} setInfoNodeVisible={this.setInfoNodeVisible} sessionProperties={this.context.session_properties} forceRedraw /> : null} </Panel> ); } else { return <div className="browser-error"> No results available for selection</div>; } } }); const CollapsingTitle = createReactClass({ propTypes: { title: PropTypes.string.isRequired, // Title to display in the title bar handleCollapse: PropTypes.func.isRequired, // Function to call to handle click in collapse button collapsed: PropTypes.bool, // T if the panel this is over has been collapsed }, render: function () { const { title, handleCollapse, collapsed } = this.props; return ( <div className="collapsing-title"> <button className="collapsing-title-trigger pull-left" data-trigger onClick={handleCollapse}>{collapseIcon(collapsed, 'collapsing-title-icon')}</button> <h4>{title}</h4> </div> ); }, }); const FileGraphComponent = createReactClass({ propTypes: { items: PropTypes.array, // Array of annotation information we're graphing graph: PropTypes.object, // JsonGraph object generated from files setInfoNodeId: PropTypes.func, // Function to call to set the currently selected node ID setInfoNodeVisible: PropTypes.func, // Function to call to set the visibility of the node's modal infoNodeId: PropTypes.string, // ID of selected node in graph infoNodeVisible: PropTypes.bool, // True if node's modal is vibible session: PropTypes.object, // Current user's login information sessionProperties: PropTypes.object, // True if logged in user is an admin }, getInitialState: function () { return { infoModalOpen: false, // Graph information modal open }; }, // Render metadata if a graph node is selected. // jsonGraph: JSON graph data. // infoNodeId: ID of the selected node detailNodes: function (jsonGraph, infoNodeId, session, sessionProperties) { let meta; // Find data matching selected node, if any if (infoNodeId) { if (infoNodeId.indexOf('qc:') >= 0) { // QC subnode. const subnode = jsonGraph.getSubnode(infoNodeId); if (subnode) { meta = qcDetailsView(subnode, this.props.schemas); meta.type = subnode['@type'][0]; } } else if (infoNodeId.indexOf('coalesced:') >= 0) { // Coalesced contributing files. const node = jsonGraph.getNode(infoNodeId); if (node) { const currCoalescedFiles = this.state.coalescedFiles; if (currCoalescedFiles[node.metadata.contributing]) { // We have the requested coalesced files in the cache, so just display // them. node.metadata.coalescedFiles = currCoalescedFiles[node.metadata.contributing]; meta = coalescedDetailsView(node); meta.type = 'File'; } else if (!this.contributingRequestOutstanding) { // We don't have the requested coalesced files in the cache, so we have to // request them from the DB. this.contributingRequestOutstanding = true; requestFiles(node.metadata.ref).then((contributingFiles) => { this.contributingRequestOutstanding = false; currCoalescedFiles[node.metadata.contributing] = contributingFiles; this.setState({ coalescedFiles: currCoalescedFiles }); }).catch(() => { this.contributingRequestOutstanding = false; currCoalescedFiles[node.metadata.contributing] = []; this.setState({ coalescedFiles: currCoalescedFiles }); }); } } } else { // A regular or contributing file. const node = jsonGraph.getNode(infoNodeId); if (node) { if (node.metadata.contributing) { // This is a contributing file, and its @id is in // node.metadata.contributing. See if the file is in the cache. const currContributing = this.state.contributingFiles; if (currContributing[node.metadata.contributing]) { // We have this file's object in the cache, so just display it. node.metadata.ref = currContributing[node.metadata.contributing]; meta = globals.graph_detail.lookup(node)(node, this.handleNodeClick, this.props.auditIndicators, this.props.auditDetail, session, sessionProperties); meta.type = node['@type'][0]; } else if (!this.contributingRequestOutstanding) { // We don't have this file's object in the cache, so request it from // the DB. this.contributingRequestOutstanding = true; requestFiles([node.metadata.contributing]).then((contributingFile) => { this.contributingRequestOutstanding = false; currContributing[node.metadata.contributing] = contributingFile[0]; this.setState({ contributingFiles: currContributing }); }).catch(() => { this.contributingRequestOutstanding = false; currContributing[node.metadata.contributing] = {}; this.setState({ contributingFiles: currContributing }); }); } } else { // Regular File data in the node from when we generated the graph. Just // display the file data from there. meta = globals.graph_detail.lookup(node)(node, this.handleNodeClick, this.props.auditIndicators, this.props.auditDetail, session, sessionProperties); meta.type = node['@type'][0]; } } } } return meta; }, handleCollapse: function () { // Handle click on panel collapse icon this.setState({ collapsed: !this.state.collapsed }); }, closeModal: function () { // Called when user wants to close modal somehow this.props.setInfoNodeVisible(false); }, render: function () { const { session, sessionProperties, items, graph, infoNodeId, infoNodeVisible } = this.props; const files = items; const modalTypeMap = { File: 'file', Step: 'analysis-step', Viz: 'viz', QualityMetric: 'quality-metric', }; // If we have a graph, or if we have a selected assembly/annotation, draw the graph panel const goodGraph = graph && Object.keys(graph).length; const loggedIn = this.context.session && this.context.session['auth.userid']; if (goodGraph){ const meta = this.detailNodes(graph, infoNodeId, session, sessionProperties); const modalClass = meta ? `graph-modal-${modalTypeMap[meta.type]}` : ''; return ( <div> <Graph graph={graph} nodeClickHandler={this.handleNodeClick} nodeMouseenterHandler={this.handleHoverIn} nodeMouseleaveHandler={this.handleHoverOut} noDefaultClasses forceRedraw /> {meta && infoNodeVisible ? <Modal closeModal={this.closeModal}> <ModalHeader closeModal={this.closeModal} addCss={modalClass}> {meta ? meta.header : null} </ModalHeader> <ModalBody> {meta ? meta.body : null} </ModalBody> <ModalFooter closeModal={<button className="btn btn-info" onClick={this.closeModal}>Close</button>} /> </Modal> : null} </div> ); return null; } }, }); const FileGraph = auditDecor(FileGraphComponent); // Display the metadata of the selected file in the graph const FileDetailView = function (node, qcClick, auditIndicators, auditDetail, session, sessionProperties) { // The node is for a file const selectedFile = node.metadata.ref; let body = null; let header = null; const loggedIn = !!(session && session['auth.userid']); const adminUser = !!(sessionProperties && sessionProperties.admin); if (selectedFile && Object.keys(selectedFile).length) { let contributingAccession; if (node.metadata.contributing) { const accessionStart = selectedFile.dataset.indexOf('/', 1) + 1; const accessionEnd = selectedFile.dataset.indexOf('/', accessionStart) - accessionStart; contributingAccession = selectedFile.dataset.substr(accessionStart, accessionEnd); } const dateString = !!selectedFile.date_created && moment.utc(selectedFile.date_created).format('YYYY-MM-DD'); header = ( <div className="details-view-info"> <h4>{selectedFile.file_type} <a href={selectedFile['@id']}>{selectedFile.title}</a></h4> </div> ); body = ( <div> <dl className="key-value"> {selectedFile.output_type ? <div data-test="output"> <dt>Output</dt> <dd>{selectedFile.output_type}</dd> </div> : null} </dl> </div> ); } else { header = ( <div className="details-view-info"> <h4>Unknown</h4> </div> ); body = <p className="browser-error">No information available</p>; } return { header: header, body: body }; }; globals.graph_detail.register(FileDetailView, 'File');
src/Footer.js
leeppolis/bookmarks
import React, { Component } from 'react'; class Footer extends Component { render() { return ( <div className="body-wrapper"> <footer> <small> © <a href="https://simonelippolis.com">Simone Lippolis</a>. All opinions are mine. </small> </footer> </div> ); } } export default Footer;
app/javascript/mastodon/features/getting_started/index.js
ikuradon/mastodon
import React from 'react'; import Column from '../ui/components/column'; import ColumnLink from '../ui/components/column_link'; import ColumnSubheading from '../ui/components/column_subheading'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { me, profile_directory, showTrends } from '../../initial_state'; import { fetchFollowRequests } from 'mastodon/actions/accounts'; import { List as ImmutableList } from 'immutable'; import NavigationContainer from '../compose/containers/navigation_container'; import Icon from 'mastodon/components/icon'; import LinkFooter from 'mastodon/features/ui/components/link_footer'; import TrendsContainer from './containers/trends_container'; const messages = defineMessages({ home_timeline: { id: 'tabs_bar.home', defaultMessage: 'Home' }, notifications: { id: 'tabs_bar.notifications', defaultMessage: 'Notifications' }, public_timeline: { id: 'navigation_bar.public_timeline', defaultMessage: 'Federated timeline' }, settings_subheading: { id: 'column_subheading.settings', defaultMessage: 'Settings' }, community_timeline: { id: 'navigation_bar.community_timeline', defaultMessage: 'Local timeline' }, direct: { id: 'navigation_bar.direct', defaultMessage: 'Direct messages' }, bookmarks: { id: 'navigation_bar.bookmarks', defaultMessage: 'Bookmarks' }, preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' }, follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' }, favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' }, blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' }, domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Hidden domains' }, mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' }, pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned toots' }, lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' }, discover: { id: 'navigation_bar.discover', defaultMessage: 'Discover' }, personal: { id: 'navigation_bar.personal', defaultMessage: 'Personal' }, security: { id: 'navigation_bar.security', defaultMessage: 'Security' }, menu: { id: 'getting_started.heading', defaultMessage: 'Getting started' }, profile_directory: { id: 'getting_started.directory', defaultMessage: 'Profile directory' }, }); const mapStateToProps = state => ({ myAccount: state.getIn(['accounts', me]), columns: state.getIn(['settings', 'columns']), unreadFollowRequests: state.getIn(['user_lists', 'follow_requests', 'items'], ImmutableList()).size, }); const mapDispatchToProps = dispatch => ({ fetchFollowRequests: () => dispatch(fetchFollowRequests()), }); const badgeDisplay = (number, limit) => { if (number === 0) { return undefined; } else if (limit && number >= limit) { return `${limit}+`; } else { return number; } }; const NAVIGATION_PANEL_BREAKPOINT = 600 + (285 * 2) + (10 * 2); export default @connect(mapStateToProps, mapDispatchToProps) @injectIntl class GettingStarted extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object.isRequired, }; static propTypes = { intl: PropTypes.object.isRequired, myAccount: ImmutablePropTypes.map.isRequired, columns: ImmutablePropTypes.list, multiColumn: PropTypes.bool, fetchFollowRequests: PropTypes.func.isRequired, unreadFollowRequests: PropTypes.number, unreadNotifications: PropTypes.number, }; componentDidMount () { const { fetchFollowRequests, multiColumn } = this.props; if (!multiColumn && window.innerWidth >= NAVIGATION_PANEL_BREAKPOINT) { this.context.router.history.replace('/home'); return; } fetchFollowRequests(); } render () { const { intl, myAccount, columns, multiColumn, unreadFollowRequests } = this.props; const navItems = []; let height = (multiColumn) ? 0 : 60; if (multiColumn) { navItems.push( <ColumnSubheading key='header-discover' text={intl.formatMessage(messages.discover)} />, <ColumnLink key='community_timeline' icon='users' text={intl.formatMessage(messages.community_timeline)} to='/public/local' />, <ColumnLink key='public_timeline' icon='globe' text={intl.formatMessage(messages.public_timeline)} to='/public' />, ); height += 34 + 48*2; if (profile_directory) { navItems.push( <ColumnLink key='directory' icon='address-book' text={intl.formatMessage(messages.profile_directory)} to='/directory' />, ); height += 48; } navItems.push( <ColumnSubheading key='header-personal' text={intl.formatMessage(messages.personal)} />, ); height += 34; } else if (profile_directory) { navItems.push( <ColumnLink key='directory' icon='address-book' text={intl.formatMessage(messages.profile_directory)} to='/directory' />, ); height += 48; } if (multiColumn && !columns.find(item => item.get('id') === 'HOME')) { navItems.push( <ColumnLink key='home' icon='home' text={intl.formatMessage(messages.home_timeline)} to='/home' />, ); height += 48; } navItems.push( <ColumnLink key='direct' icon='envelope' text={intl.formatMessage(messages.direct)} to='/conversations' />, <ColumnLink key='bookmark' icon='bookmark' text={intl.formatMessage(messages.bookmarks)} to='/bookmarks' />, <ColumnLink key='favourites' icon='star' text={intl.formatMessage(messages.favourites)} to='/favourites' />, <ColumnLink key='lists' icon='list-ul' text={intl.formatMessage(messages.lists)} to='/lists' />, ); height += 48*4; if (myAccount.get('locked') || unreadFollowRequests > 0) { navItems.push(<ColumnLink key='follow_requests' icon='user-plus' text={intl.formatMessage(messages.follow_requests)} badge={badgeDisplay(unreadFollowRequests, 40)} to='/follow_requests' />); height += 48; } if (!multiColumn) { navItems.push( <ColumnSubheading key='header-settings' text={intl.formatMessage(messages.settings_subheading)} />, <ColumnLink key='preferences' icon='gears' text={intl.formatMessage(messages.preferences)} href='/settings/preferences' />, ); height += 34 + 48; } return ( <Column bindToDocument={!multiColumn} label={intl.formatMessage(messages.menu)}> {multiColumn && <div className='column-header__wrapper'> <h1 className='column-header'> <button> <Icon id='bars' className='column-header__icon' fixedWidth /> <FormattedMessage id='getting_started.heading' defaultMessage='Getting started' /> </button> </h1> </div>} <div className='getting-started'> <div className='getting-started__wrapper' style={{ height }}> {!multiColumn && <NavigationContainer />} {navItems} </div> {!multiColumn && <div className='flex-spacer' />} <LinkFooter withHotkeys={multiColumn} /> </div> {multiColumn && showTrends && <TrendsContainer />} </Column> ); } }
src/components/sortable_list/sortable_list.js
thinktopography/reframe
import PropTypes from 'prop-types' import React from 'react' import Item from './item' import _ from 'lodash' class SortableList extends React.Component { render() { const { items } = this.props return ( <div className="reframe-sortable-list"> { items.map((item, index) => ( <Item key={`item_${index}`} { ...this._getItem(item, index) } /> ))} </div> ) } componentDidMount() { if(this.props.defaultValue) this._handleSet() } componentDidUpdate(prevProps) { const { defaultValue, items, onUpdate } = this.props if(!_.isEqual(prevProps.items, items)) onUpdate(items) if(!_.isEqual(prevProps.defaultValue, defaultValue)) this._handleSet() } _getItem(item, index) { const { onMove, onToggle } = this.props return { label: item.label, checked: item.checked, index, onMove: onMove.bind(this), onToggle: onToggle.bind(this) } } _handleSet() { const { defaultValue, onSet } = this.props onSet(defaultValue.map(item => ({ ...item, checked: item.checked !== false }))) } } export default SortableList
src/routes/Editor/components/EmailsTab.js
peksi/ilmomasiina
import React from 'react'; import PropTypes from 'prop-types'; import { Textarea } from 'formsy-react-components'; class EmailsTab extends React.Component { static propTypes = { onDataChange: PropTypes.func.isRequired, event: PropTypes.object, }; render() { return ( <div> <Textarea rows={10} name="verificationEmail" value={this.props.event.verification} label="Vahvistusviesti sähköpostiin" onChange={this.props.onDataChange} /> </div> ); } } export default EmailsTab;
docs/src/examples/elements/Step/Variations/StepExampleSizeBig.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Icon, Step } from 'semantic-ui-react' const StepExampleSizeBig = () => ( <Step.Group size='big'> <Step> <Icon name='truck' /> <Step.Content> <Step.Title>Shipping</Step.Title> </Step.Content> </Step> <Step active> <Icon name='payment' /> <Step.Content> <Step.Title>Billing</Step.Title> </Step.Content> </Step> </Step.Group> ) export default StepExampleSizeBig
src/Divider/Divider.js
IsenrichO/mui-with-arrows
import React from 'react'; import PropTypes from 'prop-types'; const Divider = (props, context) => { const { inset, style, ...other } = props; const { baseTheme, prepareStyles, } = context.muiTheme; const styles = { root: { margin: 0, marginTop: -1, marginLeft: inset ? 72 : 0, height: 1, border: 'none', backgroundColor: baseTheme.palette.borderColor, }, }; return ( <hr {...other} style={prepareStyles(Object.assign(styles.root, style))} /> ); }; Divider.muiName = 'Divider'; Divider.propTypes = { /** * If true, the `Divider` will be indented. */ inset: PropTypes.bool, /** * Override the inline-styles of the root element. */ style: PropTypes.object, }; Divider.defaultProps = { inset: false, }; Divider.contextTypes = { muiTheme: PropTypes.object.isRequired, }; export default Divider;
spec/components/layout.js
rahultaglr/taglr-toolbox
import React from 'react'; import { AppBar, Checkbox, Dropdown, IconButton, RadioGroup, RadioButton } from '../../components'; import { Layout, NavDrawer, Panel, Sidebar } from '../../components'; const dummyText = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.'; const drawerItems = dummyText.split(/\s/).map(function (word, index) { return (<li key={index}>{word}</li>); }); const sidebarWidths = [ { value: 4, label: '4 incr' }, { value: 5, label: '5 incr' }, { value: 6, label: '6 incr' }, { value: 7, label: '7 incr' }, { value: 8, label: '8 incr' }, { value: 9, label: '9 incr' }, { value: 10, label: '10 incr' }, { value: 25, label: '25%'}, { value: 33, label: '33%'}, { value: 50, label: '50%'}, { value: 66, label: '66%'}, { value: 75, label: '75%'} ]; class LayoutTest extends React.Component { state = { permanentAt: 'lg', drawerOpen: false, drawerPinned: false, sidebarPinned: false, sidebarWidth: 5, loremIpsums: 1 }; toggleDrawer = (event) => { event.stopPropagation(); this.setState({ drawerOpen: !this.state.drawerOpen }); }; toggleDrawerPinned = () => { this.setState({ drawerPinned: !this.state.drawerPinned }); }; changeDrawerPermanentAt = (value) => { this.setState({ permanentAt: value }); }; toggleSidebar = (value) => { this.setState({ sidebarPinned: (value === true) }); }; changeSidebarWidth = (value) => { this.setState({ sidebarWidth: value }); }; fewer = (event) => { event.preventDefault(); this.setState({ loremIpsums: Math.max(0, this.state.loremIpsums - 1) }); }; more = (event) => { event.preventDefault(); this.setState({ loremIpsums: this.state.loremIpsums + 1 }); }; render () { const rng = Array.from(new Array(this.state.loremIpsums), (x, i) => i); return ( <section> <h5>Layout</h5> <div style={{ width: '100%', height: '60rem', margin: '1.8rem 0' }}> <Layout> <NavDrawer active={this.state.drawerOpen} pinned={this.state.drawerPinned} permanentAt={this.state.permanentAt} onOverlayClick={this.toggleDrawer}> <AppBar title='Drawer'/> <ul style={{ listStyle: 'none', overflowY: 'auto', flex: 1, padding: '1.6rem' }}> {drawerItems} </ul> </NavDrawer> <Panel> <AppBar leftIcon='menu' onLeftIconClick={this.toggleDrawer}/> <div style={{ flex: 1, overflowY: 'auto' }}> <div style={{ display: 'flex', flexDirection: 'row' }}> <section style={{ margin: '1.8rem'}}> <h5>NavDrawer State</h5> <p>Drawer becomes permanent when window is....</p> <RadioGroup name='permanentAt' value={this.state.permanentAt} onChange={this.changeDrawerPermanentAt}> <RadioButton label='Small' value='sm'/> <RadioButton label='Medium' value='md' /> <RadioButton label='Large' value='lg' /> <RadioButton label='Extra Large' value='xl' /> <RadioButton label='Never' value={undefined} /> </RadioGroup> <Checkbox label='Pin drawer' checked={this.state.drawerPinned} onChange={this.toggleDrawerPinned} /> </section> <section style={{ margin: '1.8rem'}}> <h5>Sidebar State</h5> <RadioGroup name='sidebarPinned' value={this.state.sidebarPinned} onChange={this.toggleSidebar}> <RadioButton label='Pinned' value /> <RadioButton label='Unpinned' value={false} /> </RadioGroup> <h5>Sidebar Width</h5> <Dropdown auto onChange={this.changeSidebarWidth} source={sidebarWidths} value={this.state.sidebarWidth} /> </section> </div> <section style={{ margin: '1.8rem' }}> <h5>Scrollable Content</h5> <p> The center pane should scroll independently from the sides. Show [<a href='#' onClick={this.fewer}>-</a>] {`${this.state.loremIpsums}`} [<a href='#' onClick={this.more}>+</a>] paragraph(s) below this one. </p> {rng.map((x, i) => <p key={i}>{dummyText}</p>)} </section> </div> </Panel> <Sidebar pinned={this.state.sidebarPinned} width={Number(this.state.sidebarWidth)}> <div><IconButton icon='close' onClick={this.toggleSidebar}/></div> <div style={{ flex: 1, margin: '1.8rem' }}> <h5>Sidebar</h5> <p> Sidebar content should be secondary to the main content on a page. </p> <p> The width of the sidebar can be set either in <em>increments</em> (where 1 increment = height of the app bar) or in percentages. </p> <p> As per the spec, the right sidebar expands to cover the entire screen at small screen sizes. </p> </div> </Sidebar> </Layout> </div> </section> ); } } export default LayoutTest;
app/components/HomeComponents/TransactionTable.js
hlynn93/basic_ims
import React, { Component } from 'react'; import { Table, Icon, Button, Container } from 'semantic-ui-react'; class TransactionTable extends Component { props: { transactions: [], items: [], onDelete: () => void, onOrder: () => void } render() { const { transactions, items, onOrder, onDelete } = this.props; const entries = transactions.map((t, index) => ( <Table.Row key={index}> <Table.Cell textAlign="center">{index}</Table.Cell> <Table.Cell textAlign="center">{items.find(item => item.id === t.itemId).title}</Table.Cell> <Table.Cell textAlign="center">{t.quantity}</Table.Cell> <Table.Cell textAlign="center">{t.price}</Table.Cell> <Table.Cell textAlign="center"> <Icon size="large" color="red" name="remove" onClick={onDelete.bind(null, index)} /> </Table.Cell> </Table.Row> )); return ( <div> <Table singleLine> <Table.Header> <Table.Row> <Table.HeaderCell collapsing textAlign="center">ID</Table.HeaderCell> <Table.HeaderCell textAlign="center">Name</Table.HeaderCell> <Table.HeaderCell textAlign="center">Quantity</Table.HeaderCell> <Table.HeaderCell textAlign="center">Price</Table.HeaderCell> <Table.HeaderCell textAlign="center">Remove</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> {entries} </Table.Body> </Table> <Container fluid> <Button floated="right" color="green" onClick={onOrder} disabled={transactions.length < 1} > <Icon name="add to cart" /> Order </Button> </Container> </div> ); } } export default TransactionTable;
javascript/containers/current-stock-page.js
kdoran/moriana-react
import React from 'react' import { connect } from 'react-redux' import { getItems } from 'store/items' import h from 'utils/helpers' import {buildStockCardHref} from 'components/stockcard-link' const CurrentStockPage = class extends React.Component { state = { activeFilter: 'all', displayedItems: null } componentDidMount = () => { const { dbName, currentLocationName } = this.props.route this.props.getItems(dbName, currentLocationName) } filterOnClick = (event) => { event.preventDefault() const {filter} = event.target.dataset const {items} = this.props let displayedItems switch (filter) { case 'all': displayedItems = items break case 'positive': displayedItems = items.filter(i => i.value > 0) break case 'zero': displayedItems = items.filter(i => i.value === 0) break case 'quality': displayedItems = items.filter(i => i.value < 0) break } this.setState({ activeFilter: filter, displayedItems }) } stockLinkClicked = (event) => { const {item, category} = event.currentTarget.dataset window.location.href = buildStockCardHref(this.props.route.dbName, {item, category}) } render () { const filters = [ { name: 'All', key: 'all' }, { name: 'By Positive', key: 'positive' }, { name: 'By Zero', key: 'zero' }, { name: 'By Data Quality', key: 'quality' } ] const { items, loading } = this.props const { currentLocationName } = this.props.route let { activeFilter, displayedItems } = this.state displayedItems = displayedItems || items if (loading && items.length === 0) return (<div className='loader' />) return ( <div className='current-stock-page'> <h5>Current Stock at {currentLocationName}</h5> <div className='pull-right'> {filters.map((filter, i) => { const classes = (filter.key === activeFilter) ? 'disabled-link' : '' return ( <a href='#' key={i} onClick={this.filterOnClick} data-filter={filter.key} className={classes}> {filter.name} </a> ) })} </div> <table> <thead> <tr> <th>Item</th> <th>Category</th> <th>Total Value</th> </tr> </thead> <tbody> {displayedItems.map((row, i) => ( <tr key={i} data-item={row.item} data-category={row.category} onClick={this.stockLinkClicked}> <td>{row.item}</td> <td>{row.category}</td> <td>{h.num(row.value)}</td> </tr> ))} </tbody> </table> {!displayedItems.length && (<div className='text-center'>No items</div>)} </div> ) } } export default connect( state => state.items, { getItems } )(CurrentStockPage)
src/components/category_frequency_all.js
xuan6/admin_dashboard_local_dev
import React from 'react'; import ReactDOM from 'react-dom'; var SimpleTooltipStyle = require('react-d3-tooltip').SimpleTooltip; var BarTooltip = require('react-d3-tooltip').BarTooltip; //category by frequency const CategoryFreAll = ({data}) => { //activity trend by departments var generalChartData = data; var width = 800, height = 500, title = "Value", chartSeries = [ { field:'count', name:'Appreciation Count', color:'#A4D0EF' }]; var x = function(d) { return d.category; }, xScale = "ordinal", xLabel = "Values", yLabel = "Counts", yTicks = d3.format("d");//round to decimal int return( <BarTooltip title= {title} data= {generalChartData} width= {width} height= {height} chartSeries = {chartSeries} x= {x} xScale= {xScale} xLabel = {xLabel} yLabel = {yLabel} yTicks = {yTicks} showXGrid= {false} > <SimpleTooltipStyle/> </BarTooltip> ) }; export default CategoryFreAll;
src/components/SideMenu/index.js
PalmasLab/palmasplay
import React from 'react' import styles from './styles.css' const MenuSection = ({title, icon, children}) => ( <ul> <li className={styles.title}><strong>{title}</strong><i className={`fa fa-${icon}`}></i></li> {children} </ul> ) export const SideMenu = () => ( <div className={styles.sideMenu}> <MenuSection title="Menu"> <a href="#"><li><i className="fa fa-youtube-play"></i>What to watch</li></a> <a href="#"><li><i className="fa fa-user"></i>My Channel</li></a> <a href="#"><li><i className="fa fa-clock-o"></i>History</li></a> <a href="#"><li><i className="fa fa-play-circle-o"></i>Watch later</li></a> </MenuSection> <MenuSection title="Playlists" icon="cog"> <a href="#"><li><i className="fa fa-heart-o"></i>Liked Videos</li></a> <a href="#"><li><i className="fa fa-indent"></i>My Music</li></a> <a href="#"><li><i className="fa fa-indent"></i>Eminem</li></a> <a href="#"><li><i className="fa fa-indent"></i>David Guetta</li></a> </MenuSection> <MenuSection title="Playlists2" icon="heart"> <a href="#"><li><i className="fa fa-heart-o"></i>Liked Videos</li></a> <a href="#"><li><i className="fa fa-indent"></i>My Music</li></a> <a href="#"><li><i className="fa fa-indent"></i>Eminem</li></a> <a href="#"><li><i className="fa fa-indent"></i>David Guetta</li></a> </MenuSection> </div> )
src/components/numeric-input.js
bhongy/react-components
/** * A thin wrapper around HTMLInputElement that state as number type * rather than string - avoid ad-hoc string/number handling at use sites. * Handles precision and trailing period. See unit tests for the detail spec. * * TODO: handle formatting (could be tricky with change event value) * * @flow */ import React, { Component } from 'react'; import { omit } from 'lodash'; type Props = { initialValue?: ?number, onChange?: (obj: { value: ?number, name?: string }) => void, precision?: number, }; export type State = { inputValue: string, value: ?number, }; function handleInitialValue(value: ?number): State { if (typeof value === 'number' && Number.isFinite(value)) { return { value, inputValue: value.toString(), }; } return { value: null, inputValue: '', }; } export function truncateInputValueToPrecision(inputValue: string, precision?: number): string { if (typeof precision !== 'number' || precision % 1 !== 0 || precision < 0) { // handle invalid `precision` param // ? should throw instead ? return inputValue; } const [integer, decimals]: Array<string> = inputValue.split('.'); if (precision === 0 || typeof decimals === 'undefined') { return integer; } return [integer, decimals.slice(0, precision)].join('.'); } class NumericInput extends Component<Props, State> { constructor(props: Props): void { super(props); this.state = handleInitialValue(props.initialValue); } handleChange = (event: SyntheticInputEvent<HTMLInputElement>): void => { // create a copy of "name" value because React synthetic event is re-used // hence we cannot rely on the reference like `event.currentTarget.name` const { name, value: inputValue } = event.currentTarget; // bail early (do not change state) if input is invalid if (Number.isNaN(+inputValue)) { return; } // transformations assume that the inputValue can be safely converted // to float and without multiple periods (e.g. "01a" or "01.10.") // keep this after the "bail" check const newState: State = this.handlePrecision(inputValue); // do not `setState` if the new inputValue is the same as the current inputValue // after calling `this.handlePrecision` with the new inputValue if (newState === this.state) { return; } this.setState(newState, (): void => { const { onChange } = this.props; if (typeof onChange === 'function') { onChange({ value: this.state.value, name }); } }); }; handlePrecision = (inputValue: string): State => { const truncated: string = truncateInputValueToPrecision(inputValue, this.props.precision); if (this.state.inputValue === truncated) { return this.state; } return truncated === '' ? { value: null, inputValue: '' } : { value: +truncated, inputValue: truncated }; }; render() { const passThroughProps = omit(this.props, 'initialValue'); return ( <input {...passThroughProps} onChange={this.handleChange} value={this.state.inputValue} /> ); } } export default NumericInput;
pages/blog/test-article-one.js
fmarcos83/mdocs
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, { Component } from 'react'; export default class extends Component { render() { return ( <div> <h1>Test Article 1</h1> <p>Coming soon.</p> </div> ); } }
js/jqwidgets/demos/react/app/chart/dashboard/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxChart from '../../../jqwidgets-react/react_jqxchart.js'; class App extends React.Component { render() { let data1 = [ { text: 'Used', value: 55 }, { text: 'Available', value: 9 } ]; let data2 = [ { text: 'Used', value: 37 }, { text: 'Available', value: 63 } ]; let data3 = [ { text: 'Used', value: 89.3 }, { text: 'Available', value: 166.7 } ]; let data4 = [ { text: 'Used', value: 47 }, { text: 'Available', value: 53 } ]; let data5 = [ { hour: 0, latency: 235, requests: 3500 }, { hour: 1, latency: 231, requests: 3400 }, { hour: 2, latency: 217, requests: 3350 }, { hour: 3, latency: 215, requests: 3260 }, { hour: 4, latency: 225, requests: 3320 }, { hour: 5, latency: 235, requests: 3400 }, { hour: 6, latency: 239, requests: 3550 }, { hour: 7, latency: 255, requests: 4100 }, { hour: 8, latency: 251, requests: 4200 }, { hour: 9, latency: 259, requests: 4500 }, { hour: 10, latency: 265, requests: 4560 }, { hour: 11, latency: 257, requests: 4500 }, { hour: 12, latency: 265, requests: 4490 }, { hour: 13, latency: 261, requests: 4400 }, { hour: 14, latency: 258, requests: 4350 }, { hour: 15, latency: 257, requests: 4340 }, { hour: 16, latency: 255, requests: 4200 }, { hour: 17, latency: 245, requests: 4050 }, { hour: 18, latency: 241, requests: 4020 }, { hour: 19, latency: 239, requests: 3900 }, { hour: 20, latency: 237, requests: 3810 }, { hour: 21, latency: 236, requests: 3720 }, { hour: 22, latency: 235, requests: 3610 }, { hour: 23, latency: 239, requests: 3550 }, ]; let padding = { left: 5, top: 5, right: 5, bottom: 5 }; let titlePadding = { left: 5, top: 5, right: 5, bottom: 5 }; let seriesGroups = [ { type: 'donut', useGradientColors: false, series: [ { showLabels: false, enableSelection: true, displayText: 'text', dataField: 'value', labelRadius: 120, initialAngle: 90, radius: 60, innerRadius: 50, centerOffset: 0 } ] } ]; let counter = 0; let drawBefore = (renderer, rect) => { let value; if (counter === 0) { value = data1[0].value; } else if (counter === 1) { value = data2[0].value; } else if (counter === 2) { value = data3[0].value; } else if (counter === 3) { value = data4[0].value; } let sz = renderer.measureText(value, 0, { 'class': 'chart-inner-text' }); renderer.text( value, rect.x + (rect.width - sz.width) / 2, rect.y + rect.height / 2, 0, 0, 0, { 'class': 'chart-inner-text' } ); counter++; }; let xAxis = { dataField: 'hour', displayText: 'Hour', }; let latencyThreshold = 260; let seriesGroups2 = [ { type: 'column', valueAxis: { title: { text: 'Request Latency [ms]<br>' }, position: 'left' }, toolTipFormatSettings: { sufix: ' ms' }, series: [ { dataField: 'latency', displayText: 'Request latency', colorFunction: (value, itemIndex, serie, group) => { return (value > latencyThreshold) ? '#CC1133' : '#55CC55'; } } ], bands: [ { minValue: latencyThreshold, maxValue: latencyThreshold, lineWidth: 1, color: 'red' } ] }, { type: 'spline', valueAxis: { title: { text: 'Get Requests per second' }, position: 'right' }, toolTipFormatSettings: { sufix: ' req/s' }, series: [ { dataField: 'requests', displayText: 'Get requests', lineColor: '#343F9B', lineWidth: 2 } ] }, ]; return ( <div> <JqxChart ref='myChart1' style={{ width: 400, height: 180, float: 'left' }} title={'Cluster capacity'} description={''} colorScheme={'scheme05'} showLegend={false} enableAnimations={true} padding={padding} showToolTips={true} titlePadding={titlePadding} source={data1} backgroundColor={'#FAFAFA'} seriesGroups={seriesGroups} drawBefore={drawBefore} /> <JqxChart ref='myChart2' style={{ width: 400, height: 180, float: 'left' }} title={'Avg. CPU %'} description={''} colorScheme={'scheme05'} showLegend={false} enableAnimations={true} padding={padding} showToolTips={true} titlePadding={titlePadding} source={data2} backgroundColor={'#FAFAFA'} seriesGroups={seriesGroups} drawBefore={drawBefore} /> <JqxChart ref='myChart3' style={{ width: 400, height: 180, float: 'left' }} title={'Storage capacity [TB]'} description={''} colorScheme={'scheme05'} showLegend={false} enableAnimations={true} padding={padding} showToolTips={true} titlePadding={titlePadding} source={data3} backgroundColor={'#FAFAFA'} seriesGroups={seriesGroups} drawBefore={drawBefore} /> <JqxChart ref='myChart4' style={{ width: 400, height: 180, float: 'left' }} title={'Network utilization %'} description={''} colorScheme={'scheme05'} showLegend={false} enableAnimations={true} padding={padding} showToolTips={true} titlePadding={titlePadding} source={data4} backgroundColor={'#FAFAFA'} seriesGroups={seriesGroups} drawBefore={drawBefore} /> <JqxChart style={{ width: 800, height: 300 }} title={'Get request per second & response latencies'} description={'(Aggregated values for the last 24h)'} showLegend={false} enableAnimations={true} padding={padding} backgroundColor={'#FAFAFA'} titlePadding={titlePadding} source={data5} xAxis={xAxis} showBorderLine={true} seriesGroups={seriesGroups2} colorScheme={'scheme05'} /> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
app/boards/motec-d153/components/warnings.js
fermio/motorsport-display
import React from 'react'; import _ from 'lodash'; import { EngineWarnings } from '../../constants'; const Warnings = React.createClass({ propTypes: { warnings: React.PropTypes.array }, getDefaultProps: function() { return { warnings: [] } }, shouldComponentUpdate: function(nextProps, nextState) { return this.props.warnings != nextProps.warnings; }, render: function() { let warnings = []; if (_.indexOf(this.props.warnings, EngineWarnings.PIT_SPEED_LIMITER) != -1) { warnings.push( <div key="pit-speed-limiter" id="pit-speed-limiter" className="column"> Pit Speed Limiter </div> ); } if (_.indexOf(this.props.warnings, EngineWarnings.REV_LIMITER_ACTIVE) != -1) { warnings.push( <div key="rev-limiter" id="rev-limiter" className="column"> Rev Limiter Active </div> ); } if (_.indexOf(this.props.warnings, EngineWarnings.WATER_TEMP_WARNING) != -1) { warnings.push( <div key="water-temp" id="water-temp" className="column"> Engine Hot </div> ); } if (_.indexOf(this.props.warnings, EngineWarnings.FUEL_PRESSURE_WARNING) != -1) { warnings.push( <div key="fuel-pressure" id="fuel-pressure" className="column"> Fuel Pressure Low </div> ); } if (_.indexOf(this.props.warnings, EngineWarnings.OIL_PRESSURE_WARNING) != -1) { warnings.push( <div key="oil-pressure" id="oil-pressure" className="column"> Oil Pressue Low </div> ); } if (_.indexOf(this.props.warnings, EngineWarnings.ENGINE_STALLED) != -1) { warnings.push( <div key="engine-stalled" id="engine-stalled" className="column"> Engine Stalled </div> ); } return ( <div id="engine-warnings" className="row"> {warnings} </div> ); } }); export default Warnings;
packages/@lyra/vision/src/containers/LoadingContainer.js
VegaPublish/vega-studio
import React from 'react' import PropTypes from 'prop-types' import request from '../util/request' // Yeah, inheritance and all that. Deal with it. class LoadingContainer extends React.PureComponent { constructor() { super() if (!this.getSubscriptions) { throw new Error( `${ this.constructor.name } extended LoadingContainer but did not define a getSubscriptions() method` ) } this.subscriptions = [] this.state = {} } componentDidMount() { const subs = this.getSubscriptions() const stateKeys = (this.stateKeys = Object.keys(subs)) this.subscriptions = stateKeys.reduce((target, key) => { target.push(request(this, subs[key], key)) return target }, []) } hasAllData() { return ( this.stateKeys && this.stateKeys.every(key => this.state[key] !== undefined) ) } componentWillUnmount() { while (this.subscriptions.length) { this.subscriptions.pop().unsubscribe() } } } LoadingContainer.contextTypes = { client: PropTypes.shape({fetch: PropTypes.func}).isRequired } export default LoadingContainer
webapp/app/components/Spinner/index.js
EIP-SAM/SAM-Solution-Node-js
// // Spinner components to display during ajax requests // Props: // color: optional, choose the spinner's color // size: optional, choose the spinner's size // className: optional, add your own css here, to center the component etc... // Example: // import Spinner from 'components/Spinner'; // ... // <Spinner color="#ff0000" size={200} className={styles.newStyleSpinner} /> // import React from 'react'; import styles from './styles.css'; /* eslint-disable react/prefer-stateless-function */ export default class Spinner extends React.Component { static defaultProps = { color: '#3498db', size: 120, className: '', } render() { const width = 16 * (this.props.size / 120); const newStyle = { borderTopColor: this.props.color, width: this.props.size, height: this.props.size, borderWidth: width, borderTopWidth: width, }; return ( <div className={[styles.spinner, this.props.className].join(' ')} style={newStyle} /> ); } } Spinner.propTypes = { color: React.PropTypes.string, size: React.PropTypes.number, className: React.PropTypes.string, };
fields/types/datetime/DatetimeField.js
xyzteam2016/keystone
import DateInput from '../../components/DateInput'; import Field from '../Field'; import moment from 'moment'; import React from 'react'; import { Button, FormField, FormInput, FormNote, InputGroup } from 'elemental'; module.exports = Field.create({ displayName: 'DatetimeField', statics: { type: 'Datetime', }, focusTargetRef: 'dateInput', // default input formats dateInputFormat: 'YYYY-MM-DD', timeInputFormat: 'h:mm:ss a', tzOffsetInputFormat: 'Z', // parse formats (duplicated from lib/fieldTypes/datetime.js) parseFormats: ['YYYY-MM-DD', 'YYYY-MM-DD h:m:s a', 'YYYY-MM-DD h:m a', 'YYYY-MM-DD H:m:s', 'YYYY-MM-DD H:m'], getInitialState () { return { dateValue: this.props.value && this.moment(this.props.value).format(this.dateInputFormat), timeValue: this.props.value && this.moment(this.props.value).format(this.timeInputFormat), tzOffsetValue: this.props.value ? this.moment(this.props.value).format(this.tzOffsetInputFormat) : this.moment().format(this.tzOffsetInputFormat), }; }, getDefaultProps () { return { formatString: 'Do MMM YYYY, h:mm:ss a', }; }, moment () { if (this.props.isUTC) return moment.utc.apply(moment, arguments); else return moment.apply(undefined, arguments); }, // TODO: Move isValid() so we can share with server-side code isValid (value) { return this.moment(value, this.parseFormats).isValid(); }, // TODO: Move format() so we can share with server-side code format (value, format) { format = format || this.dateInputFormat + ' ' + this.timeInputFormat; return value ? this.moment(value).format(format) : ''; }, handleChange (dateValue, timeValue, tzOffsetValue) { var value = dateValue + ' ' + timeValue; var datetimeFormat = this.dateInputFormat + ' ' + this.timeInputFormat; // if the change included a timezone offset, include that in the calculation (so NOW works correctly during DST changes) if (typeof tzOffsetValue !== 'undefined') { value += ' ' + tzOffsetValue; datetimeFormat += ' ' + this.tzOffsetInputFormat; } // if not, calculate the timezone offset based on the date (respect different DST values) else { this.setState({ tzOffsetValue: this.moment(value, datetimeFormat).format(this.tzOffsetInputFormat) }); } this.props.onChange({ path: this.props.path, value: this.isValid(value) ? this.moment(value, datetimeFormat).toISOString() : null, }); }, dateChanged ({ value }) { this.setState({ dateValue: value }); this.handleChange(value, this.state.timeValue); }, timeChanged (evt) { this.setState({ timeValue: evt.target.value }); this.handleChange(this.state.dateValue, evt.target.value); }, setNow () { var dateValue = this.moment().format(this.dateInputFormat); var timeValue = this.moment().format(this.timeInputFormat); var tzOffsetValue = this.moment().format(this.tzOffsetInputFormat); this.setState({ dateValue: dateValue, timeValue: timeValue, tzOffsetValue: tzOffsetValue, }); this.handleChange(dateValue, timeValue, tzOffsetValue); }, renderNote () { if (!this.props.note) return null; return <FormNote note={this.props.note} />; }, renderUI () { var input; if (this.shouldRenderField()) { input = ( <InputGroup> <InputGroup.Section grow> <DateInput ref="dateInput" name={this.props.paths.date} value={this.state.dateValue} format={this.dateInputFormat} onChange={this.dateChanged} /> </InputGroup.Section> <InputGroup.Section grow> <FormInput name={this.props.paths.time} value={this.state.timeValue} placeholder="HH:MM:SS am/pm" onChange={this.timeChanged} autoComplete="off" /> </InputGroup.Section> <InputGroup.Section> <Button onClick={this.setNow}>Now</Button> </InputGroup.Section> <input type="hidden" name={this.props.paths.tzOffset} value={this.state.tzOffsetValue} /> </InputGroup> ); } else { input = <FormInput noedit>{this.format(this.props.value, this.props.formatString)}</FormInput>; } return ( <FormField label={this.props.label} className="field-type-datetime" htmlFor={this.props.path}> {input} {this.renderNote()} </FormField> ); }, });
src/routes/mypolls/index.js
binyuace/vote
import React from 'react'; import Layout from '../../components/Layout'; async function action({ fetch, store }) { const resp = await fetch('/api/polls', { method: 'GET', }); const data = await resp.json(); const state = store.getState(); if (!data) throw new Error('Failed to load the polls feed.'); const myPolls = data .filter(arr => arr.creatorId === (state.user ? state.user.id : null)) .reverse() .map(arr => <h1 key={arr._id}> <a href={`/poll/${arr._id}`}> {arr.title} </a> </h1>, ); return { chunks: ['about'], title: 'My Polls', component: ( <Layout> {myPolls} </Layout> ), }; } export default action;
app/components/TagsForm/index.js
54vanya/ru-for-you-front
/** * * TagsInput * */ import React from 'react'; import styled from 'styled-components'; import Input from 'components/Input'; import Button from 'components/Button'; const AddButtonWrapper = styled.div` position:relative; float: right; input{ height:42px; border-bottom-left-radius:0; border-top-left-radius:0; font-size:20px; padding: 0 1em; } margin-left:-4px; `; const InputWrapper = styled.div` overflow: hidden; `; const TagsForm = ({ value, onChange, onSubmitForm }) => ( <form onSubmit={onSubmitForm}> <AddButtonWrapper> <Button inputValue="GO" /> </AddButtonWrapper> <InputWrapper> <Input id="username" type="text" value={value} onChange={onChange} /> </InputWrapper> </form> ) ; TagsForm.propTypes = { value: React.PropTypes.string, onChange: React.PropTypes.func.isRequired, onSubmitForm: React.PropTypes.func.isRequired, }; export default TagsForm;
src/svg-icons/av/repeat.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvRepeat = (props) => ( <SvgIcon {...props}> <path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z"/> </SvgIcon> ); AvRepeat = pure(AvRepeat); AvRepeat.displayName = 'AvRepeat'; AvRepeat.muiName = 'SvgIcon'; export default AvRepeat;
docs/app/Examples/elements/Button/Groups/index.js
vageeshb/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const ButtonGroupsExamples = () => ( <ExampleSection title='Groups'> <ComponentExample title='Group' description='Buttons can exist together as a group.' examplePath='elements/Button/Groups/ButtonExampleGroup' /> <ComponentExample title='Icon Group' description='Button groups can show groups of icons.' examplePath='elements/Button/Groups/ButtonExampleGroupIcon' /> </ExampleSection> ) export default ButtonGroupsExamples
vgdb-frontend/src/components/nav/NavItem.js
mattruston/idb
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import './NavItem.css'; /* Link or Text item on the nav */ class NavItem extends Component { static defaultProps = { bold: false } render() { return ( /* Probably needs to be a router-link or something */ <Link className="nav-item" to={this.props.link}> <div className={"nav-link " + (this.props.bold ? 'nav-link-bold' : '')}> {this.props.text} </div> </Link> ); } } export default NavItem;
addons/storyshots/stories/directly_required/Button.js
enjoylife/storybook
import PropTypes from 'prop-types'; import React from 'react'; const buttonStyles = { border: '1px solid #eee', borderRadius: 3, backgroundColor: '#FFFFFF', cursor: 'pointer', fontSize: 15, padding: '3px 10px', margin: 10, }; const Button = ({ children, onClick }) => <button style={buttonStyles} onClick={onClick}> {children} </button>; Button.defaultProps = { onClick: null, }; Button.propTypes = { children: PropTypes.string.isRequired, onClick: PropTypes.func, }; export default Button;
src/containers/Admin/Chats/Chats.js
EncontrAR/backoffice
import React, { Component } from 'react'; import ContactList from '../../../components/admin/conversations/contactList'; import chatActions from '../../../redux/chat/actions'; import { connect } from 'react-redux'; const { indexAllConversations } = chatActions; class Chats extends Component { render() { return ( <ContactList conversations={ this.props.conversations } total_pages={ this.props.total_pages } total_count={ this.props.total_count } loadConversations={ (page, itemsPerPage) => { this.props.indexAllConversations(page, itemsPerPage) }} /> ); } } function mapStateToProps(state) { const { conversations, total_pages, total_count } = state.Chat; return { conversations: conversations, total_pages: total_pages, total_count: total_count }; } export default connect(mapStateToProps, { indexAllConversations })(Chats);
src/js/components/App.js
MarcusWasTaken/ArmelloCards
import React from 'react' import Deck from '../containers/Deck' import DeckList from '../containers/DeckList' import Filters from '../containers/Filters' import 'css/app' const App = () => ( <div className="app clearfix"> <div className="main"> <DeckList /> <Deck /> </div> <aside className="aside"> <h1>Armello Cards</h1> <Filters /> {/*<h5>Options</h5>*/} </aside> </div> ) export default App
docs/src/pages/premium-themes/onepirate/modules/views/AppForm.js
lgollut/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import Container from '@material-ui/core/Container'; import Box from '@material-ui/core/Box'; import { withStyles } from '@material-ui/core/styles'; import Paper from '../components/Paper'; const styles = (theme) => ({ root: { display: 'flex', backgroundImage: 'url(/static/onepirate/appCurvyLines.png)', backgroundRepeat: 'no-repeat', }, paper: { padding: theme.spacing(4, 3), [theme.breakpoints.up('md')]: { padding: theme.spacing(8, 6), }, }, }); function AppForm(props) { const { children, classes } = props; return ( <div className={classes.root}> <Container maxWidth="sm"> <Box mt={7} mb={12}> <Paper className={classes.paper}>{children}</Paper> </Box> </Container> </div> ); } AppForm.propTypes = { children: PropTypes.node.isRequired, classes: PropTypes.object.isRequired, }; export default withStyles(styles)(AppForm);
react/features/conference/components/native/ConferenceTimerDisplay.js
bgrozev/jitsi-meet
// @flow import React from 'react'; import { Text } from 'react-native'; import styles from './styles'; /** * Returns native element to be rendered. * * @param {string} timerValue - String to display as time. * * @returns {ReactElement} */ export default function renderConferenceTimer(timerValue: string) { return ( <Text numberOfLines = { 4 } style = { styles.roomTimer }> { timerValue } </Text> ); }
app/components/Settings/ChannelSelector.js
TheCbac/MICA-Desktop
// @flow /* ********************************************************** * File: ChannelSelector.js * * Brief: React component for choosing which of the sensor * channels that are active. * * Authors: Craig Cheney * * 2017.09.12 CC - Document created * ********************************************************* */ import React, { Component } from 'react'; import { Col, ButtonToolbar, Row } from 'react-bootstrap'; import ToggleButtonGroup from 'react-bootstrap/lib/ToggleButtonGroup'; import ToggleButton from 'react-bootstrap/lib/ToggleButton'; import micaSensorParams from '../../utils/mica/micaSensorParams'; import type { idType } from '../../types/paramTypes'; import type { setSensorChannelsActionT } from '../../types/actionTypes'; type propsType = { /* parameters */ deviceId: idType, sensorId: idType, channels: channelsT, /* Functions */ setSensorChannels: ( deviceId: idType, sensorId: idType, newChannels: number[] ) => setSensorChannelsActionT }; type stateType = { channels: number[] }; /* Get the channels */ function channelIdsFromObj(Obj: channelsT): number[] { const channelIds = Object.keys(Obj); const valueArray = []; for (let i = 0; i < channelIds.length; i++) { const { active } = Obj[channelIds[i]]; if (active) { valueArray.push(parseInt(channelIds[i], 10)); } } return valueArray; } export default class ChannelSelector extends Component<propsType, stateType> { /* Constructor function */ constructor(props: propsType) { super(props); /* Set the default state */ this.state = { channels: channelIdsFromObj(props.channels) }; } /* Return the channels that are available */ getChannels() { const { channels } = this.props; const channelIds = Object.keys(channels); /* Create a button for each channel */ const buttonArray = []; const numChan = channelIds.length; for (let i = 0; i < numChan; i++) { const id = channelIds[i]; /* Create the button */ buttonArray.push(( <ToggleButton key={i.toString()} value={parseInt(id, 10)}> {channels[id].name} </ToggleButton> )); } return buttonArray; } /* Control the state */ onChange = (channels: number[]): void => { /* Update the state */ this.setState({ channels }); /* Update the stored channels */ const { deviceId, sensorId } = this.props; /* Get the channels from the props */ this.props.setSensorChannels(deviceId, sensorId, channels); } /* At least one channel warning */ channelWarning() { if (this.state.channels.length < 1) { const warningText = { color: 'red', fontStyle: 'italic' }; return ( <Col md={8} xs={8}> <span style={warningText}>At least one channel must be active</span> </Col> ); } } /* Render function */ render() { return ( <div> <ButtonToolbar> <Col md={4} xs={4}> <label htmlFor='dataChannels'>Data Channels:</label> </Col> {this.channelWarning()} <Row /> <Col md={12} xs={12}> <ToggleButtonGroup bsSize='small' type='checkbox' value={this.state.channels} onChange={this.onChange} > { this.getChannels() } </ToggleButtonGroup> </Col> </ButtonToolbar> </div> ); } } /* [] - END OF FILE */
webapp/app/components/Tr/index.js
EIP-SAM/SAM-Solution-Node-js
// // Component <tr></tr> // import React from 'react'; /* eslint-disable react/prefer-stateless-function */ export default class Tr extends React.Component { render() { const ComponentToRender = this.props.component; let content = null; content = this.props.items.map((item, index) => ( <ComponentToRender key={`item-${index}`} object={item} /> )); return ( <tr className={this.props.className}>{content}</tr> ); } } Tr.propTypes = { component: React.PropTypes.func.isRequired, className: React.PropTypes.string, items: React.PropTypes.arrayOf(React.PropTypes.any).isRequired, };
app/js/components/header.js
pauloelias/simple-webpack-react
import React from 'react'; export default class Header extends React.Component { render() { return ( <div> <p>This is the amazing <b>header</b>.</p> </div> ) }; }
react-router-webpack-code-splitting/src/app.js
LiuuY/code-splitting-demo
import React from 'react' import {BrowserRouter, Link, Route} from 'react-router-dom' // getComponent is a function that returns a promise for a component // It will not be called until the first mount function asyncComponent(getComponent) { return class AsyncComponent extends React.Component { static Component = null; state = { Component: AsyncComponent.Component }; componentWillMount() { if (!this.state.Component) { getComponent().then(Component => { AsyncComponent.Component = Component this.setState({ Component }) }) } } render() { const { Component } = this.state if (Component) { return <Component {...this.props} /> } return null } } } const Module1 = asyncComponent(() => System.import('./module1').then(module => module.default) ) const Module2 = asyncComponent(() => System.import('./module2').then(module => module.default) ) const App = () => <BrowserRouter> <div> <Link to="/module1">module1</Link> <br /> <Link to="/module2">module2</Link> <h1>Welcome</h1> <Route path="/" render={() => <div>Home</div>} /> <Route path="/module1" component={Module1} /> <Route path="/module2" component={Module2} /> </div> </BrowserRouter> export default App
js/components/loaders/ProgressBar.android.js
fahrulrizall/projectuts
import React, { Component } from 'react'; import ProgressBar from 'ProgressBarAndroid'; export default class SpinnerNB extends Component { render() { return ( <ProgressBar {...this.prepareRootProps()} styleAttr="Horizontal" indeterminate={false} progress={this.props.progress ? this.props.progress / 100 : 0.5} color={getColor()} /> ); } }
imports/components/Signup.js
adderpositive/chat-app
/*================================================ Signup ====== - is component for UI architecture of sign up @imports - react ================================================ */ // imports import React from 'react'; const Signup = ({ name, email, password, passwordRepeated, setName, setEmail, setPassword, setPasswordRepeated, hangleSignup }) => { return ( <div className="container log"> <h1>Sign Up</h1> <div className="row"> <label htmlFor="name">Name:</label> <input className="u-full-width" type="text" placeholder="Name" id="name" value={name} onChange={setName}/> </div> <div className="row"> <label htmlFor="email">E-mail:</label> <input className="u-full-width" type="email" placeholder="Email" id="email" value={email} onChange={setEmail} required /> </div> <div className="row"> <label htmlFor="password">Password:</label> <input className="u-full-width" type="password" placeholder="Password" id="password" value={password} onChange={setPassword}/> </div> <div className="row"> <label htmlFor="passwordRepeat">Repeat password:</label> <input className="u-full-width" type="password" placeholder="Repeat password" id="passwordRepeated" value={passwordRepeated} onChange={setPasswordRepeated}/> </div> <div className="row"> <button className="button button-primary u-full-width" onClick={hangleSignup}>Sign up</button> </div> </div> ) } // export export default Signup;
packages/mineral-ui-icons/src/IconLineWeight.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconLineWeight(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M3 17h18v-2H3v2zm0 3h18v-1H3v1zm0-7h18v-3H3v3zm0-9v4h18V4H3z"/> </g> </Icon> ); } IconLineWeight.displayName = 'IconLineWeight'; IconLineWeight.category = 'action';
src/svg-icons/av/stop.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvStop = (props) => ( <SvgIcon {...props}> <path d="M6 6h12v12H6z"/> </SvgIcon> ); AvStop = pure(AvStop); AvStop.displayName = 'AvStop'; AvStop.muiName = 'SvgIcon'; export default AvStop;
src/client/components/TrippianListItemRoundWidget/TrippianListItemRoundWidget.js
trippian/trippian
import log from '../../log' import React from 'react' import { Link } from 'react-router' const TrippianListItemRoundWidget = ({ name = 'Amanda . Sydney', id, picture = 'lorempixel.com/200/200/people/' }) => { return ( <div className="popular-trippians-item text-center"> <Link to={`trippian/${id}`}> <div className="circle-image"> <img src={picture} alt="" /> </div> <h4> {name} </h4> </Link> </div> ) } TrippianListItemRoundWidget .displayName = 'TrippianListItemRoundWidget' export default TrippianListItemRoundWidget
client/common/components/DropdownFilter.js
Haaarp/geo
import React from 'react'; import { SplitButton, MenuItem } from 'react-bootstrap'; /* * Props: * items: Array * title: String */ const DropdownFilter = (props) => ( <div className="guide-dropdown-wrap"> <SplitButton title={props.title} pullLeft className="guide-dropdown-custom"> {props.items ? props.items.map((el, index) => <MenuItem eventKey="{index}">{el}</MenuItem>) : null} </SplitButton> </div> ); export default DropdownFilter;
client/views/admin/settings/inputs/ActionSettingInput.js
VoiSmart/Rocket.Chat
import { Button, Field } from '@rocket.chat/fuselage'; import React from 'react'; import { useMethod } from '../../../../contexts/ServerContext'; import { useToastMessageDispatch } from '../../../../contexts/ToastMessagesContext'; import { useTranslation } from '../../../../contexts/TranslationContext'; function ActionSettingInput({ _id, actionText, value, disabled, sectionChanged }) { const t = useTranslation(); const dispatchToastMessage = useToastMessageDispatch(); const actionMethod = useMethod(value); const handleClick = async () => { try { const data = await actionMethod(); const args = [data.message].concat(data.params); dispatchToastMessage({ type: 'success', message: t(...args) }); } catch (error) { dispatchToastMessage({ type: 'error', message: error }); } }; return ( <> <Field.Row> <Button data-qa-setting-id={_id} children={t(actionText)} disabled={disabled || sectionChanged} primary onClick={handleClick} /> </Field.Row> {sectionChanged && <Field.Hint>{t('Save_to_enable_this_action')}</Field.Hint>} </> ); } export default ActionSettingInput;
src/components/search_bar.js
scepticulous/react-video-player
import React, { Component } from 'react'; // const SearchBar = () => { // return <input />; // }; class SearchBar extends Component{ constructor(props) { super(props); this.state = { term: '' }; } render = () => { return ( <div className="search-bar"> <input value={this.state.term} onChange={event => this.onInputChange(event.target.value) } /> </div> ); } onInputChange(term){ this.setState({term}); this.props.onSearchTermChange(term); } } export default SearchBar;
src/index.js
vladpolonskiy/news-feed-react-redux
import React from 'react'; import ReactDOM from 'react-dom'; import store from './store'; import {Provider} from 'react-redux'; import {Router, browserHistory} from 'react-router'; import {routes} from './routes'; ReactDOM.render( <Provider store={store}> <Router history={browserHistory} routes={routes} /> </Provider>, document.getElementById('root') );
src/layouts/ErrorPage/index.js
IntellectionStudio/intellection.kz
import React from 'react'; import Page from 'layouts/Page'; import styles from './index.css'; const STATUS_CODE_NOT_FOUND = 404; const ErrorPage = ({ error = STATUS_CODE_NOT_FOUND, errorText = 'Page Not Found', ...restProps }) => { const pageProps = Page.pickPageProps(restProps); return ( <Page {...{ ...pageProps, head: { ...pageProps.head, hero: 'https://farm8.staticflickr.com/7559/16101654539_bee5151340_k.jpg', }, }} > <div className={styles.container}> <div className={styles.oops}>{'😱 Oooops!'}</div> <div className={styles.text}> <p className={styles.title}> <strong>{error}</strong> {errorText} </p> {error === STATUS_CODE_NOT_FOUND && ( <div> {'It seems you found a broken link. '} {'Sorry about that. '} <br /> {'Do not hesitate to report this page 😁.'} </div> )} </div> </div> </Page> ); }; export default ErrorPage;
HomeScreen.js
bakin-bacon/app
import React, { Component } from 'react'; import { StyleSheet, View, Text, } from 'react-native'; import * as Colors from './Colors'; export class HomeScreen extends Component { static navigationOptions = { title: "Bakin' Bacon", }; render() { return ( <View style={styles.container}> <Text style={{ textAlign: 'center', color: Colors.primary }}>Home Bacon Screen</Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: Colors.backgroundColor, }, });
src/containers/About.js
u-wave/web
import React from 'react'; import UwaveContext from '../context/UwaveContext'; import Overlay from '../components/Overlay'; import About from '../components/About'; const { useContext, } = React; function AboutContainer(props) { const uwave = useContext(UwaveContext); const component = uwave.getAboutPageComponent() ?? null; return ( <Overlay direction="top"> <About {...props} hasAboutPage={!!component} render={component} /> </Overlay> ); } export default AboutContainer;
app/components/Footer/index.js
jdelatorreitrs/react-boilerplate
import React from 'react'; import { FormattedMessage } from 'react-intl'; import A from 'components/A'; import LocaleToggle from 'containers/LocaleToggle'; import Wrapper from './Wrapper'; import messages from './messages'; function Footer() { return ( <Wrapper> <section> <FormattedMessage {...messages.licenseMessage} /> </section> <section> <LocaleToggle /> </section> <section> <FormattedMessage {...messages.authorMessage} values={{ author: <A href="https://twitter.com/mxstbr">Max Stoiber</A>, }} /> </section> </Wrapper> ); } export default Footer;
examples/PopoverExample.js
instea/react-native-popup-menu
import { Menu, MenuProvider, MenuOptions, MenuTrigger, renderers, } from 'react-native-popup-menu'; import { Text, View, StyleSheet } from 'react-native'; import React from 'react'; const { Popover } = renderers const MyPopover = () => ( <Menu renderer={Popover} rendererProps={{ preferredPlacement: 'bottom' }}> <MenuTrigger style={styles.menuTrigger} > <Text style={styles.triggerText}>{'\u263A'}</Text> </MenuTrigger> <MenuOptions style={styles.menuOptions}> <Text style={styles.contentText}>Hello world!</Text> </MenuOptions> </Menu> ) const Row = () => ( <View style={styles.row}> <MyPopover /> <MyPopover /> <MyPopover /> <MyPopover /> <MyPopover /> <MyPopover /> </View> ) const PopoverExample = () => ( <MenuProvider style={styles.container} customStyles={{ backdrop: styles.backdrop }}> <Row /> <Row /> <Row /> <Row /> <Row /> <Row /> <Row /> <Row /> </MenuProvider> ); const styles = StyleSheet.create({ container: { padding: 10, flexDirection: 'column', justifyContent: 'space-between', backgroundColor: 'rgba(0, 0, 0, 0.05)', }, row: { flexDirection: 'row', justifyContent: 'space-between', }, backdrop: { }, menuOptions: { padding: 50, }, menuTrigger: { padding: 5, }, triggerText: { fontSize: 20, }, contentText: { fontSize: 18, }, }) export default PopoverExample;
src/plugins/position/components/TableEnhancer.js
joellanciaux/Griddle
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from '../../../utils/griddleConnect'; import compose from 'recompose/compose'; import mapProps from 'recompose/mapProps'; import getContext from 'recompose/getContext'; import { setScrollPosition } from '../actions'; const Table = OriginalComponent => compose( getContext({ selectors: PropTypes.object, }), connect((state, props) => { const { tableHeightSelector, tableWidthSelector, rowHeightSelector } = props.selectors; return { TableHeight: tableHeightSelector(state), TableWidth: tableWidthSelector(state), RowHeight: rowHeightSelector(state), }; }, { setScrollPosition, } ), mapProps((props) => { const { selectors, ...restProps } = props; return restProps; }) )(class extends Component { constructor(props, context) { super(props, context); this.state = { scrollTop: 0 }; } render() { const { TableHeight, TableWidth } = this.props; const scrollStyle = { 'overflow': TableHeight && TableWidth ? 'scroll' : null, 'overflowY' : TableHeight && !TableWidth ? 'scroll' : null, 'overflowX' : !TableHeight && TableWidth ? 'scroll' : null, 'height': TableHeight ? TableHeight : null, 'width': TableWidth ? TableWidth : null, 'display': 'inline-block' }; return ( <div ref={(ref) => this._scrollable = ref} style={scrollStyle} onScroll={this._scroll}> <OriginalComponent {...this.props}/> </div> ); } _scroll = () => { const { setScrollPosition, RowHeight } = this.props; const { scrollTop } = this.state; if (this._scrollable && Math.abs(this._scrollable.scrollTop - scrollTop) >= RowHeight) { setScrollPosition( this._scrollable.scrollLeft, this._scrollable.scrollWidth, this._scrollable.clientWidth, this._scrollable.scrollTop, this._scrollable.scrollHeight, this._scrollable.clientHeight ); this.setState({ scrollTop: this._scrollable.scrollTop }); } } }); export default Table;
src/app/components/AudioEditor.js
skratchdot/audio-editor
import React, { Component } from 'react'; import { Row, Col, Jumbotron } from 'react-bootstrap'; import { connect } from 'react-redux'; import AudioPlayer from './AudioPlayer'; import WaveformAmplitude from './display/WaveformAmplitude'; import DisplayContainer from './DisplayContainer'; import DisplayMessage from './DisplayMessage'; import DisplayPlaybackPosition from './DisplayPlaybackPosition'; import MonoButtonGroup from './MonoButtonGroup'; import PlayBar from './PlayBar'; import PlaybackPositionSlider from './PlaybackPositionSlider'; import PlaybackRateBar from './PlaybackRateBar'; import PlaybackRateSlider from './PlaybackRateSlider'; import VolumeSlider from './VolumeSlider'; import ZoomBar from './ZoomBar'; import ZoomSlider from './ZoomSlider'; class AudioEditor extends Component { render() { const { buffer, mono, playbackType, playbackPosition, zoom } = this.props; const audioPlayer = playbackType === 0 ? '' : <AudioPlayer />; const zoomDisplay = []; if (mono || buffer.length === 0) { zoomDisplay.push( <WaveformAmplitude key="mono" type="mono" zoomLevel={1} start={zoom.start} end={zoom.end} /> ); } else { for (let i = 0; i < buffer.numberOfChannels; i++) { if (i > 0) { zoomDisplay.push( <div key={`spacer${i}`} style={{ height: 2, backgroundColor: '#aaa' }}>&nbsp;</div> ); } zoomDisplay.push( <WaveformAmplitude key={`channels.${i}`} type={`channels.${i}`} zoomLevel={1} start={zoom.start} end={zoom.end} /> ); } } return ( <div> {audioPlayer} <Row> <Col md={6}> <Jumbotron className="jumbo-control"> <PlayBar /> <VolumeSlider /> </Jumbotron> </Col> <Col md={6}> <Jumbotron className="jumbo-control"> <PlaybackRateBar /> <PlaybackRateSlider /> </Jumbotron> </Col> </Row> <Row> <Col md={12}> <DisplayContainer> <div style={{ height: 200, display: 'flex', flexDirection: 'column' }}> {zoomDisplay} </div> <DisplayPlaybackPosition min={zoom.start} max={zoom.end} /> <DisplayMessage showExtended={true} /> </DisplayContainer> <PlaybackPositionSlider min={zoom.start} max={zoom.end} /> <Row> <Col md={6}> <ZoomBar /> </Col> <Col md={6} style={{display: 'flex', justifyContent: 'flex-end'}}> <MonoButtonGroup /> </Col> </Row> </Col> </Row> <Row> <Col md={12}> <DisplayContainer> <WaveformAmplitude zoomLevel={1} start={0} end={buffer.length - 1} type="mono" height={50} /> <DisplayPlaybackPosition min={0} max={buffer.length - 1} /> <ZoomSlider /> <DisplayMessage /> </DisplayContainer> <PlaybackPositionSlider min={0} max={buffer.length - 1} /> <Row> <Col md={6}> <small>Position: {Math.round(playbackPosition.position)}</small> </Col> <Col md={6}> </Col> </Row> </Col> </Row> </div> ); } } export default connect(function (state) { return { buffer: state.buffer, mono: state.mono, muted: state.muted, playbackPosition: state.playbackPosition, playbackType: state.playbackType, volume: state.volume, zoom: state.zoom }; })(AudioEditor);
frontend/src/components/common/hoc/tableWithStateInUrl.js
unicef/un-partner-portal
// eslint-disable-next-line import React, { Component } from 'react'; import R from 'ramda'; import PropTypes from 'prop-types'; import { browserHistory as history, withRouter } from 'react-router'; import { connect } from 'react-redux'; import { updateOrder, calculatePaginatedPage, updatePageNumberSize, updatePageNumber, } from '../../../helpers/apiHelper'; class TableWithStateInUrl extends Component { constructor(props) { super(props); this.state = { page: props.pageNumber || 1, page_size: props.pageSize || 10 }; this.changeSorting = this.changeSorting.bind(this); this.changePageSize = this.changePageSize.bind(this); this.changePageNumber = this.changePageNumber.bind(this); // TODO - move default order to this component } componentWillReceiveProps(nextProps) { const { pathName, query = {} } = nextProps; if (!query.page || !query.page_size) { history.push({ pathname: pathName, query: R.merge(query, { page: this.state.page, page_size: this.state.page_size }), }); } } changePageSize(pageSize) { const { pageNumber, itemsCount, pathName, query } = this.props; updatePageNumberSize(calculatePaginatedPage(pageNumber, pageSize, itemsCount), pageSize, pathName, query); } changePageNumber(page) { const { pathName, query } = this.props; updatePageNumber(page, pathName, query); } changeSorting(sorting) { const { pathName, query } = this.props; if (sorting[0].columnName !== 'country_code' && sorting[0].columnName !== 'status') { const order = sorting[0].columnName === 'specializations' ? 'specializations__name' : sorting[0].columnName; this.setState({ sorting, }); const direction = sorting[0].direction === 'desc' ? '-' : ''; updateOrder(order, direction, pathName, query); } } render() { const { component: WrappedComponent, pageSize, pageNumber, ...other } = this.props; return (<WrappedComponent {...other} allowSorting sorting={this.state.sorting} changeSorting={this.changeSorting} changePageSize={this.changePageSize} changePageNumber={this.changePageNumber} pageSize={pageSize} pageNumber={pageNumber} />); } } TableWithStateInUrl.propTypes = { component: PropTypes.oneOfType([ PropTypes.element, PropTypes.func, ]), query: PropTypes.object, pathName: PropTypes.string, pageSize: PropTypes.number, pageNumber: PropTypes.number, itemsCount: PropTypes.number, }; const mapStateToProps = (state, { location: { pathname: pathName, query } = {}, }) => ({ pathName, query, pageSize: R.isNil(query.page_size) ? 0 : Number(query.page_size), pageNumber: R.isNil(query.page) ? 1 : Number(query.page), }); export default withRouter(connect(mapStateToProps, null)(TableWithStateInUrl));
admin/client/App/screens/Item/index.js
dvdcastro/keystone
/** * Item View * * This is the item view, it is rendered when users visit a page of a specific * item. This mainly renders the form to edit the item content in. */ import React from 'react'; import { Container, Spinner } from 'elemental'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import { listsByKey } from '../../../utils/lists'; import CreateForm from '../../shared/CreateForm'; import EditForm from './components/EditForm'; import EditFormHeader from './components/EditFormHeader'; import RelatedItemsList from './components/RelatedItemsList'; // import FlashMessages from '../../shared/FlashMessages'; import { selectItem, loadItemData, } from './actions'; import { selectList, } from '../List/actions'; var ItemView = React.createClass({ displayName: 'ItemView', contextTypes: { router: React.PropTypes.object.isRequired, }, getInitialState () { return { createIsOpen: false, }; }, componentDidMount () { // When we directly navigate to an item without coming from another client // side routed page before, we need to select the list before initializing the item this.props.dispatch(selectList(this.props.params.listId)); this.initializeItem(this.props.params.itemId); }, componentWillReceiveProps (nextProps) { // We've opened a new item from the client side routing, so initialize // again with the new item id if (nextProps.params.itemId !== this.props.params.itemId) { this.props.dispatch(selectList(nextProps.params.listId)); this.initializeItem(nextProps.params.itemId); } }, // Initialize an item initializeItem (itemId) { this.props.dispatch(selectItem(itemId)); this.props.dispatch(loadItemData()); }, // Called when a new item is created onCreate (item) { // Hide the create form this.setState({ createIsOpen: false, }); // Redirect to newly created item path const list = this.props.currentList; this.context.router.push(`${Keystone.adminPath}/${list.path}/${item.id}`); }, // Open and close the create new item modal toggleCreate (visible) { this.setState({ createIsOpen: visible, }); }, // Render this items relationships renderRelationships () { const { relationships } = this.props.currentList; const keys = Object.keys(relationships); if (!keys.length) return; return ( <div className="Relationships"> <Container> <h2>Relationships</h2> {keys.map(key => { const relationship = relationships[key]; const refList = listsByKey[relationship.ref]; return ( <RelatedItemsList key={relationship.path} list={this.props.currentList} refList={refList} relatedItemId={this.props.params.itemId} relationship={relationship} /> ); })} </Container> </div> ); }, // Handle errors handleError (error) { const detail = error.detail; if (detail) { // Item not found if (detail.name === 'CastError' && detail.path === '_id') { return ( <Container> <p>Item not found!</p> <Link to={`${Keystone.adminPath}/${this.props.routeParams.listId}`}> Go to list </Link> </Container> ); } } if (error.message) { // Server down + possibly other errors if (error.message === 'Internal XMLHttpRequest Error') { return ( <Container> <p>We encountered some network problems, please try refreshing!</p> </Container> ); } } return (<p>Error!</p>); }, render () { // If we don't have any data yet, show the loading indicator if (!this.props.ready) { return ( <div className="centered-loading-indicator" data-screen-id="item"> <Spinner size="md" /> </div> ); } // When we have the data, render the item view with it return ( <div data-screen-id="item"> {(this.props.error) ? this.handleError(this.props.error) : ( <div> <Container> <EditFormHeader list={this.props.currentList} data={this.props.data} toggleCreate={this.toggleCreate} /> <CreateForm list={this.props.currentList} isOpen={this.state.createIsOpen} onCancel={() => this.toggleCreate(false)} onCreate={(item) => this.onCreate(item)} /> <EditForm list={this.props.currentList} data={this.props.data} dispatch={this.props.dispatch} router={this.context.router} /> </Container> {this.renderRelationships()} </div> )} </div> ); }, }); module.exports = connect((state) => ({ data: state.item.data, loading: state.item.loading, ready: state.item.ready, error: state.item.error, currentList: state.lists.currentList, }))(ItemView);
src/svg-icons/editor/mode-comment.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorModeComment = (props) => ( <SvgIcon {...props}> <path d="M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18z"/> </SvgIcon> ); EditorModeComment = pure(EditorModeComment); EditorModeComment.displayName = 'EditorModeComment'; EditorModeComment.muiName = 'SvgIcon'; export default EditorModeComment;
docs/src/app/pages/components/Modal/ExampleModalCustomTitle.js
GetAmbassador/react-ions
import React from 'react' import Modal from 'react-ions/lib/components/Modal' import Header from 'react-ions/lib/components/Modal/Header' import Button from 'react-ions/lib/components/Button' class ExampleModalCustomTitle extends React.Component { constructor(props) { super(props) this.state = { open: false } } handleOpen = () => { this.setState({open: true}) } handleClose = () => { this.setState({open: false}) } handleSubmit = () => { this.setState({open: false}) } render() { const actions = [ <Button onClick={this.handleClose} optClass="inverted">Cancel</Button>, <Button onClick={this.handleSubmit}>Submit</Button> ] return ( <div> <Button onClick={this.handleOpen}>Open Modal</Button> <Modal title={ <Header handleClose={this.handleClose}> <h1>Custom Title</h1> </Header> } open={this.state.open} onRequestClose={this.handleClose} actions={actions} closeOnAction={true} > <p>The actions in this window were passed in as an array of React objects.</p> <p>This modal can only be closed by selecting one of the actions.</p> </Modal> </div> ) } } export default ExampleModalCustomTitle
docs/app/Examples/addons/Radio/States/index.js
Rohanhacker/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 RadioStatesExamples = () => ( <ExampleSection title='States'> <ComponentExample title='Checked' description='A radio can come pre-checked.' examplePath='addons/Radio/States/RadioExampleChecked' > <Message> Use{' '} <a href='https://facebook.github.io/react/docs/forms.html#default-value' target='_blank'> <code>defaultChecked</code> </a> {' '}as you normally would to set default form values. </Message> </ComponentExample> <ComponentExample title='Disabled' description='Radios can be disabled.' examplePath='addons/Radio/States/RadioExampleDisabled' /> <ComponentExample title='Read Only' description='Make the radio unable to be edited by the user.' examplePath='addons/Radio/States/RadioExampleReadOnly' /> <ComponentExample title='Remote Control' description='You can trigger events remotely.' examplePath='addons/Radio/States/RadioExampleRemoteControl' /> </ExampleSection> ) export default RadioStatesExamples
src/app/components/menuComponents/SettingsMenuItems.js
preeminence/react-redux-skeleton
import React from 'react'; import Settings from 'material-ui/svg-icons/action/settings'; import MenuListItem from './MenuListItem'; import appActions from '../../appActions'; class SettingsMenuItems extends React.Component { handleThemeChange() { this.props.dispatch(appActions.themeChanged()); } handleToggleSettingsClick() { this.props.dispatch(appActions.toggleSettings()); } render() { const menuItems = [ <MenuListItem key={1} toggle toggleText="Light Theme" toggleValue={this.props.values.lightTheme} onToggle={this.handleThemeChange.bind(this)} />, ]; return ( <div> <MenuListItem primaryText="Settings" leftIcon={<Settings />} open={this.props.values.settingsShow} nestedItems={menuItems} onClick={this.handleToggleSettingsClick.bind(this)} /> </div>); } } export default SettingsMenuItems;
examples/draft-0-10-0/tex/js/components/TeXEditorExample.js
tonygentilcore/draft-js
/** * Copyright (c) 2013-present, Facebook, Inc. All rights reserved. * * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; import Draft from 'draft-js'; import {Map} from 'immutable'; import React from 'react'; import TeXBlock from './TeXBlock'; import {content} from '../data/content'; import {insertTeXBlock} from '../modifiers/insertTeXBlock'; import {removeTeXBlock} from '../modifiers/removeTeXBlock'; var {Editor, EditorState, RichUtils} = Draft; export default class TeXEditorExample extends React.Component { constructor(props) { super(props); this.state = { editorState: EditorState.createWithContent(content), liveTeXEdits: Map(), }; this._blockRenderer = (block) => { if (block.getType() === 'atomic') { return { component: TeXBlock, editable: false, props: { onStartEdit: (blockKey) => { var {liveTeXEdits} = this.state; this.setState({liveTeXEdits: liveTeXEdits.set(blockKey, true)}); }, onFinishEdit: (blockKey, newContentState) => { var {liveTeXEdits} = this.state; this.setState({ liveTeXEdits: liveTeXEdits.remove(blockKey), editorState:EditorState.createWithContent(newContentState), }); }, onRemove: (blockKey) => this._removeTeX(blockKey), }, }; } return null; }; this._focus = () => this.refs.editor.focus(); this._onChange = (editorState) => this.setState({editorState}); this._handleKeyCommand = command => { var {editorState} = this.state; var newState = RichUtils.handleKeyCommand(editorState, command); if (newState) { this._onChange(newState); return true; } return false; }; this._removeTeX = (blockKey) => { var {editorState, liveTeXEdits} = this.state; this.setState({ liveTeXEdits: liveTeXEdits.remove(blockKey), editorState: removeTeXBlock(editorState, blockKey), }); }; this._insertTeX = () => { this.setState({ liveTeXEdits: Map(), editorState: insertTeXBlock(this.state.editorState), }); }; } /** * While editing TeX, set the Draft editor to read-only. This allows us to * have a textarea within the DOM. */ render() { return ( <div className="TexEditor-container"> <div className="TeXEditor-root"> <div className="TeXEditor-editor" onClick={this._focus}> <Editor blockRendererFn={this._blockRenderer} editorState={this.state.editorState} handleKeyCommand={this._handleKeyCommand} onChange={this._onChange} placeholder="Start a document..." readOnly={this.state.liveTeXEdits.count()} ref="editor" spellCheck={true} /> </div> </div> <button onClick={this._insertTeX} className="TeXEditor-insert"> {'Insert new TeX'} </button> </div> ); } }
client/components/AltFooter/index.js
Elektro1776/Project_3
import React, { Component } from 'react'; import { Button } from 'react-toolbox/lib/button'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; class AltFooter extends Component { constructor() { super(); this.state = { }; } render() { const styles = { basic: { width: '100vw', background: '#545454', height: '50px', bottom: '0', position: 'fixed', color: 'white', textAlign: 'center', lineHeight: '44px', }, }; return ( <div style={styles.basic}> <p>&#9400;Copyright 2017 uTile</p> </div> ); } } export default AltFooter;
src/browser/users/UsersPage.js
reedlaw/read-it
// @flow import OnlineUsers from './OnlineUsers'; import React from 'react'; import linksMessages from '../../common/app/linksMessages'; import { Box, PageHeader } from '../../common/components'; import { Title } from '../components'; const UsersPage = () => ( <Box> <Title message={linksMessages.users} /> <PageHeader heading="Users" description="Online users" /> <OnlineUsers /> </Box> ); export default UsersPage;
src/toolbar/SearchField.js
prajapati-parth/react-bootstrap-table
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; class SearchField extends Component { getValue() { return ReactDOM.findDOMNode(this).value; } setValue(value) { ReactDOM.findDOMNode(this).value = value; } render() { const { className, defaultValue, placeholder, onKeyUp, ...rest } = this.props; return ( <input className={ `form-control ${className}` } type='text' defaultValue={ defaultValue } placeholder={ placeholder || SearchField.defaultProps.placeholder } onKeyUp={ onKeyUp } style={ { zIndex: 0 } } { ...rest }/> ); } } SearchField.propTypes = { className: PropTypes.string, defaultValue: PropTypes.string, placeholder: PropTypes.string, onKeyUp: PropTypes.func }; SearchField.defaultProps = { className: '', defaultValue: '', placeholder: 'Search', onKeyUp: undefined }; export default SearchField;
src/app/components/blocks/_copyright.js
maullerz/eve-react
import React from 'react' const _copyright = ({info}) => { return <div className='row'> <div className='col-md-12'> <div className='grayback t-small'> <div className="row"> <div className="col-md-9 col-first"> EVE Online and the EVE logo are the registered trademarks of CCP hf. All rights are reserved worldwide. All other trademarks are the property of their respective owners. EVE Online, the EVE logo, EVE and all associated logos and designs are the intellectual property of CCP hf. All artwork, screenshots, characters, vehicles, storylines, world facts or other recognizable features of the intellectual property relating to these trademarks are likewise the intellectual property of CCP hf. CCP hf. has granted permission to EVE-Prod to use EVE Online and all associated logos and designs for promotional and information purposes on its website but does not endorse, and is not in any way affiliated with, EVE-Prod. CCP is in no way responsible for the content on or functioning of this website, nor can it be liable for any damage arising from the use of this website. </div> <div className="col-md-3 col-last"> Version: <a target="_blank" href={info.repo_url}>{info.message}</a><br /> Online: <span className="txt-yellow">{info.eve_online}</span><br /> Latest Update: <span className="txt-lime">{info.updated_at}</span><br /> EVE Time: <span className="txt-lime">{info.eve_time}</span><br /> Have idea? <a target="_blank" href="https://github.com/mazahell/eve-react">Fork me on Github</a><br /> </div> </div> </div> </div> </div> } export default _copyright
electron/app/components/PlusButton.js
zindlerb/motif
import React from 'react'; import classname from 'classname'; function PlusButton(props) { return ( <i onClick={props.onClick} className={classnames("fa fa-plus-circle", props.className)} aria-hidden="true" /> ); } export default PlusButton;
src/lib/plugins/hostname.js
Hyperline/hyperline
import os from 'os' import React from 'react' import Component from 'hyper/component' import SvgIcon from '../utils/svg-icon' class PluginIcon extends Component { render() { return ( <SvgIcon> <g fill="none" fillRule="evenodd"> <g className="hostname-icon" transform="translate(1.000000, 1.000000)" > <path d="M2,0 L12,0 L12,8 L2,8 L2,0 Z M4,2 L10,2 L10,6 L4,6 L4,2 Z M5.5,11 L8.5,11 L8.5,14 L5.5,14 L5.5,11 Z M11,11 L14,11 L14,14 L11,14 L11,11 Z M0,11 L3,11 L3,14 L0,14 L0,11 Z M6.5,10 L7.5,10 L7.5,11 L6.5,11 L6.5,10 Z M12,10 L13,10 L13,11 L12,11 L12,10 Z M1,10 L2,10 L2,11 L1,11 L1,10 Z M1,9 L13,9 L13,10 L1,10 L1,9 Z M6.5,8 L7.5,8 L7.5,9 L6.5,9 L6.5,8 Z" /> </g> </g> <style jsx>{` .hostname-icon { fill: #fff; } `}</style> </SvgIcon> ) } } export default class HostName extends Component { static displayName() { return 'hostname' } render() { const hostname = os.hostname() const username = process.env.USER return ( <div className="wrapper"> <PluginIcon /> <span>{username}@</span> {hostname} <style jsx>{` .wrapper { display: flex; align-items: center; } `}</style> </div> ) } }
client/extensions/woocommerce/woocommerce-services/views/shipping-label/label-purchase-modal/packages-step/add-item.js
Automattic/woocommerce-services
/** @format */ /** * External dependencies */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { localize } from 'i18n-calypso'; import { includes, size, some } from 'lodash'; import { CheckboxControl } from '@wordpress/components'; /** * Internal dependencies */ import Dialog from 'components/dialog'; import FormLabel from 'components/forms/form-label'; import getPackageDescriptions from './get-package-descriptions'; import FormSectionHeading from 'components/forms/form-section-heading'; import { closeAddItem, setAddedItem, addItems, } from 'woocommerce/woocommerce-services/state/shipping-label/actions'; import { getShippingLabel } from 'woocommerce/woocommerce-services/state/shipping-label/selectors'; import { getAllPackageDefinitions } from 'woocommerce/woocommerce-services/state/packages/selectors'; const AddItemDialog = props => { const { siteId, orderId, showAddItemDialog, addedItems, openedPackageId, selected, all, translate, } = props; if ( ! showAddItemDialog ) { return null; } const packageLabels = getPackageDescriptions( selected, all, true ); const getPackageNameElement = pckgId => { return <span className="packages-step__dialog-package-name">{ packageLabels[ pckgId ] }</span>; }; const renderCheckbox = ( pckgId, itemIdx, item ) => { const itemLabel = packageLabels[ pckgId ] ? translate( '%(item)s from {{pckg/}}', { args: { item: item.name }, components: { pckg: getPackageNameElement( pckgId ) }, } ) : item; const onChange = ( state ) => { props.setAddedItem( orderId, siteId, pckgId, itemIdx, state ); } return ( <FormLabel key={ `${ pckgId }-${ itemIdx }` } className="packages-step__dialog-package-option" > <CheckboxControl label={ itemLabel } className="form-label packages-step__dialog-package-option" checked={ includes( addedItems[ pckgId ], itemIdx ) } onChange={ onChange } /> </FormLabel> ); }; const itemOptions = []; Object.keys( selected ).forEach( pckgId => { if ( pckgId === openedPackageId ) { return; } let itemIdx = 0; selected[ pckgId ].items.forEach( item => { itemOptions.push( renderCheckbox( pckgId, itemIdx, item ) ); itemIdx++; } ); } ); const onClose = () => props.closeAddItem( orderId, siteId ); const buttons = [ { action: 'close', label: translate( 'Close' ), onClick: onClose }, { action: 'add', label: translate( 'Add' ), isPrimary: true, disabled: ! some( addedItems, size ), onClick: () => props.addItems( orderId, siteId, openedPackageId ), }, ]; return ( <Dialog isVisible={ showAddItemDialog } isFullScreen={ false } onClickOutside={ onClose } onClose={ onClose } buttons={ buttons } additionalClassNames="wcc-root woocommerce packages-step__dialog" > <FormSectionHeading>{ translate( 'Add item' ) }</FormSectionHeading> <div className="packages-step__dialog-body"> <p> { translate( 'Which items would you like to add to {{pckg/}}?', { components: { pckg: getPackageNameElement( openedPackageId ), }, } ) } </p> { itemOptions } </div> </Dialog> ); }; AddItemDialog.propTypes = { siteId: PropTypes.number.isRequired, orderId: PropTypes.number.isRequired, showAddItemDialog: PropTypes.bool.isRequired, addedItems: PropTypes.object, openedPackageId: PropTypes.string.isRequired, selected: PropTypes.object.isRequired, all: PropTypes.object.isRequired, closeAddItem: PropTypes.func.isRequired, setAddedItem: PropTypes.func.isRequired, addItems: PropTypes.func.isRequired, }; const mapStateToProps = ( state, { orderId, siteId } ) => { const shippingLabel = getShippingLabel( state, orderId, siteId ); return { showAddItemDialog: Boolean( shippingLabel.showAddItemDialog ), addedItems: shippingLabel.addedItems, openedPackageId: shippingLabel.openedPackageId, selected: shippingLabel.form.packages.selected, all: getAllPackageDefinitions( state, siteId ), }; }; const mapDispatchToProps = dispatch => { return bindActionCreators( { closeAddItem, setAddedItem, addItems }, dispatch ); }; export default connect( mapStateToProps, mapDispatchToProps )( localize( AddItemDialog ) );