path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
stories/card.stories.js
VulcanJS/Vulcan
import React from 'react'; import { storiesOf } from '@storybook/react'; import { dataSampleCollection } from './dataSample/dummyCollection'; import { Components } from 'meteor/vulcan:core'; /* Card */ const card = storiesOf('Core/Card', module); const cardProps = { collection: dataSampleCollection, document: { title: 'My title', url: 'https://vulcanjs.org', image: 'https://cl.ly/6906b7446a73/Screen%20Shot%202019-02-25%20at%2010.19.47.png', isTrue: false, answerToLife: 42, myObject: { foo: 12, bar: 'baz' }, now: new Date(), // component: ( // <label> // <input type="checkbox" /> My Checkbox // </label> // ), array: ['foo', 'bar'], }, }; card.add('Default', () => <Components.Card {...cardProps} />);
example/examples/MarkerTypes.js
palexs/react-native-maps
import React from 'react'; import { StyleSheet, View, Text, Dimensions, } from 'react-native'; import MapView from 'react-native-maps'; import flagBlueImg from './assets/flag-blue.png'; import flagPinkImg from './assets/flag-pink.png'; const { width, height } = Dimensions.get('window'); const ASPECT_RATIO = width / height; const LATITUDE = 37.78825; const LONGITUDE = -122.4324; const LATITUDE_DELTA = 0.0922; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; const SPACE = 0.01; class MarkerTypes extends React.Component { constructor(props) { super(props); this.state = { marker1: true, marker2: false, }; } render() { return ( <View style={styles.container}> <MapView provider={this.props.provider} style={styles.map} initialRegion={{ latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }} > <MapView.Marker onPress={() => this.setState({ marker1: !this.state.marker1 })} coordinate={{ latitude: LATITUDE + SPACE, longitude: LONGITUDE + SPACE, }} centerOffset={{ x: -18, y: -60 }} anchor={{ x: 0.69, y: 1 }} image={this.state.marker1 ? flagBlueImg : flagPinkImg} > <Text style={styles.marker}>X</Text> </MapView.Marker> <MapView.Marker onPress={() => this.setState({ marker2: !this.state.marker2 })} coordinate={{ latitude: LATITUDE - SPACE, longitude: LONGITUDE - SPACE, }} centerOffset={{ x: -42, y: -60 }} anchor={{ x: 0.84, y: 1 }} image={this.state.marker2 ? flagBlueImg : flagPinkImg} /> </MapView> </View> ); } } MarkerTypes.propTypes = { provider: MapView.ProviderPropType, }; const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, justifyContent: 'flex-end', alignItems: 'center', }, map: { ...StyleSheet.absoluteFillObject, }, marker: { marginLeft: 46, marginTop: 33, fontWeight: 'bold', }, }); module.exports = MarkerTypes;
spec/javascripts/jsx/gradebook-history/GradebookHistoryAppSpec.js
djbender/canvas-lms
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import {Provider} from 'react-redux' import {shallow} from 'enzyme' import SearchForm from 'jsx/gradebook-history/SearchForm' import SearchResults from 'jsx/gradebook-history/SearchResults' import GradebookHistoryApp from 'jsx/gradebook-history/GradebookHistoryApp' import GradebookHistoryStore from 'jsx/gradebook-history/store/GradebookHistoryStore' QUnit.module('GradebookHistoryApp has component', { setup() { this.wrapper = shallow(<GradebookHistoryApp />) }, teardown() { this.wrapper.unmount() } }) test('Provider with a store prop', function() { const provider = this.wrapper.find(Provider) equal(provider.length, 1) equal(provider.props().store, GradebookHistoryStore) }) test('Heading', function() { const heading = this.wrapper.find('h1') strictEqual(heading.length, 1) }) test('SearchForm', function() { const form = this.wrapper.find(SearchForm) strictEqual(form.length, 1) }) test('SearchResults', function() { const results = this.wrapper.find(SearchResults) strictEqual(results.length, 1) })
src/spa/dev/js/components/Feed.js
MoimHossain/netcore-microservice-tutorial
import React from 'react'; const Feed = () => ( <div className="ui feed"> <div className="event"> <div className="label"> <img src="https://semantic-ui.com/images/avatar/small/elliot.jpg"></img> </div> <div className="content"> <div className="summary"> <a className="user"> Elliot Fu </a> was invited into the project as an architect <div className="date"> 1 Hour Ago </div> </div> </div> </div> <div className="event"> <div className="label"> <img src="https://semantic-ui.com/images/avatar/small/helen.jpg"></img> </div> <div className="content"> <div className="summary"> <a>Helen Troy</a> added <a>2 new illustrations</a> <div className="date"> 4 days ago </div> </div> <div className="extra images"> <a><img src="https://i.ytimg.com/vi/ZuNbjjK_dK4/maxresdefault.jpg"></img></a> <a><img src="http://www.delivered.dhl.com/content/dam/delivered/master/issues/2017-1/images/issue-1-17-p31-delft-hyperloop-full-image.jpg"></img></a> </div> <div className="meta"> <a className="like"> <i className="like icon"></i> 1 Like </a> </div> </div> </div> <div className="event"> <div className="label"> <img src="https://semantic-ui.com/images/avatar/small/jenny.jpg"></img> </div> <div className="content"> <div className="summary"> <a className="user"> Jenny Hess </a> added <a>Design Document.docx</a> <div className="date"> 2 Days Ago </div> </div> <div className="meta"> <a className="like"> <i className="like icon"></i> 8 followers </a> </div> </div> </div> <div className="event"> <div className="label"> <img src="https://semantic-ui.com/images/avatar/small/joe.jpg"></img> </div> <div className="content"> <div className="summary"> <a>Joe Henderson</a> commented <div className="date"> 3 days ago </div> </div> <div className="extra text"> We're always circling back to where we'd we started, then starting all over again. Even if we don't run extra laps that day, we surely will come back for more of the same another day soon. </div> <div className="meta"> <a className="like"> <i className="like icon"></i> 5 participants </a> </div> </div> </div> <div className="event"> <div className="label"> <img src="https://semantic-ui.com/images/avatar/small/justen.jpg"></img> </div> <div className="content"> <div className="summary"> <a>Justen Kitsune</a> added <a>2 new revisions</a> <div className="date"> 4 days ago </div> </div> <div className="extra images"> <a><img src="https://semantic-ui.com/images/wireframe/image.png"></img></a> <a><img src="https://semantic-ui.com/images/wireframe/image.png"></img></a> </div> <div className="meta"> <a className="like"> <i className="like icon"></i> 41 participants </a> </div> </div> </div> </div> ); export default Feed;
src/App.js
ralmidani/react-my-reads
import React from 'react'; import './App.css'; import {getAll, update} from './BooksAPI'; import {Route} from 'react-router-dom'; import Search from './components/Search'; import BookShelves from './components/BookShelves'; class App extends React.Component { state = { books: [] } shelves = [ {apiTitle: 'currentlyReading', displayTitle: 'Currently Reading'}, {apiTitle: 'wantToRead', displayTitle: 'Want to Read'}, {apiTitle: 'read', displayTitle: 'Read'}, {apiTitle: 'none', displayTitle: 'None'} ] componentDidMount() { getAll().then(books => this.setState({books})); } moveBook = (book, shelf) => { update(book, shelf) .then(() => { book.shelf = shelf; const newState = this.state.books.filter((b) => b.id !== book.id) .concat(book); this.setState({books: newState}); }); } render() { return ( <div className="app"> <Route exact path="/" render={() => <BookShelves shelves={this.shelves} moveBook={this.moveBook} books={this.state.books} /> } /> <Route exact path="/search" render={() => <Search shelves={this.shelves} moveBook={this.moveBook} shelvedBooks={this.state.books} /> } /> </div> ); } } export default App
app/components/ConfigOptions.js
FermORG/FermionJS
// @flow import React, { Component } from 'react'; import styles from './photon.scss'; import coreStyles from './Core.scss'; import panelStyles from './Panels.scss'; import ColorPicker from './ColorPicker'; // returns renderable config Panel options. export default function ConfigOption(props) { const { activeComponent, propKey, value, action, deleter, actionHandler, onClick } = props; return ( <li className={`${styles['list-group-item']} ${panelStyles.list}`}> <strong>{`${propKey}`}</strong> <strong> : </strong> {addColorPicker(props)} <div className={`${panelStyles.deleteKey}`} onClick={() => { onClick(deleter, activeComponent, propKey); }} > X </div> </li> ); } function addColorPicker(props) { const { activeComponent, propKey, value, action, deleter, actionHandler, onClick } = props; if (propKey.indexOf('Color') === -1 && propKey.indexOf('color') === -1) { return ( <input className={`${panelStyles.editField}`} placeholder={`${value}`} onKeyPress={(event) => actionHandler(event, action, activeComponent, propKey)} /> ); } else { return (<ColorPicker color={value || '#f2f2f2'} activeComponent={activeComponent} onChange={(event) => actionHandler(event, action, activeComponent, propKey)} />); } }
src/components/App.js
rsimmons/immersion-player
import React, { Component } from 'react'; import { BrowserRouter as Router, Link, NavLink, Switch, Route, Redirect } from 'react-router-dom'; import { ScrollContext } from 'react-router-scroll-4'; import { extractAudioFromVideo, extractFrameImageFromVideo } from '../library'; import './App.css'; import WidthWrapper from './WidthWrapper.js'; import Player from './Player.js'; import Settings from './Settings.js'; import AddCollection from './AddCollection.js'; import ImportEpwing from './ImportEpwing.js'; const VideoListItem = (props) => { const { videoId, collection, name } = props; const hasSubs = collection.videos.get(videoId).subtitleTracks.size > 0; return ( <li className={'App-library-list-item ' + (hasSubs ? 'App-library-list-item-has-subs' : 'App-library-list-item-no-subs')}> <Link to={'/player/' + encodeURIComponent(collection.locator) + '/' + encodeURIComponent(videoId)}> {name} </Link> </li> ); }; // App class App extends Component { render() { const { mainState, actions } = this.props; if (mainState.modalLoadingMessage) { return <WidthWrapper><h1 className="header-font">{mainState.modalLoadingMessage}</h1></WidthWrapper>; } else { return ( <Router><ScrollContext> <Switch> <Route path="/player/:cloc/:vid" render={({ match, history }) => { const collectionLocator = decodeURIComponent(match.params.cloc); const videoId = decodeURIComponent(match.params.vid); return <Player video={mainState.collections.get(collectionLocator).videos.get(videoId)} onExit={() => { history.goBack(); }} onUpdatePlaybackPosition={(pos) => { actions.saveVideoPlaybackPosition(collectionLocator, videoId, pos); }} onNeedSubtitles={() => { actions.loadSubtitlesIfNeeded(collectionLocator, videoId); }} getSavedPlaybackPosition={() => { return actions.loadVideoPlaybackPosition(collectionLocator, videoId); }} onSetPreference={(pref, value) => { actions.setPreference(pref, value); }} preferences={mainState.preferences} sortFilterSubtitleTracksMap={actions.sortFilterSubtitleTracksMap} searchDictionaries={actions.searchDictionaries} onExtractAudio={(startTime, endTime) => extractAudioFromVideo(collectionLocator, videoId, startTime, endTime)} onExtractFrameImage={(time) => extractFrameImageFromVideo(collectionLocator, videoId, time)} ankiPrefs={mainState.preferences.anki} />; }}/> <Route path="/add_collection" render={({ history }) => { return <AddCollection onAdd={(name, dir) => { actions.addLocalCollection(name, dir); history.replace('/library'); }} onExit={() => { history.goBack(); }} />; }}/> <Route path="/import_epwing" render={({ history }) => { return <ImportEpwing onExit={() => { history.goBack(); }} onReloadDictionaries={actions.reloadDictionaries} />; }}/> <Route render={({ history }) => ( <WidthWrapper> <nav className="App-main-nav header-font"> <NavLink to={'/library'} activeClassName="selected">Library</NavLink> <NavLink to={'/settings'} activeClassName="selected">Settings</NavLink> </nav> <div className="App-below-main-nav"> <Switch> <Route path="/library/:cloc/:tname" render={({ match }) => { const collectionLocator = decodeURIComponent(match.params.cloc); const titleName = decodeURIComponent(match.params.tname); const collection = mainState.collections.get(collectionLocator); const title = collection.titles.find(t => t.name === titleName); // unindexed, but should be quick return ( <div> <div className="App-collection-header"> <h2 className="App-collection-header-title"><a href="/library" onClick={e => {e.preventDefault(); history.goBack();}} className="App-back-to-library-link">{collection.name}</a> / {title.name}</h2> </div> {title.parts.seasonEpisodes.length ? ( <ul> {title.parts.seasonEpisodes.map(se => ( <VideoListItem collection={collection} videoId={se.videoId} name={'Season ' + se.seasonNumber + ' Episode ' + se.episodeNumber} key={se.videoId} /> ))} </ul> ) : null} {title.parts.episodes.length ? ( <ul> {title.parts.episodes.map(ep => ( <VideoListItem collection={collection} videoId={ep.videoId} name={'Episode ' + ep.episodeNumber} key={ep.videoId} /> ))} </ul> ) : null} {title.parts.others.length ? ( <ul> {title.parts.others.map(other => ( <VideoListItem collection={collection} videoId={other.videoId} name={other.name} key={other.name} /> ))} </ul> ) : null} </div> ); }}/> <Route path="/library" render={() => (mainState.collections.size > 0) ? ( <ul> {mainState.collections.valueSeq().sort((a, b) => a.name.localeCompare(b.name)).map((collection) => ( <li className="App-collection" key={collection.locator}> <div className="App-collection-header"> <h2 className="App-collection-header-title">{collection.name} <span className="App-collection-header-buttons"> <button onClick={e => { e.preventDefault(); if (window.confirm('Are you sure you want to delete the collection "' + collection.name + '"?')) { actions.removeCollection(collection.locator); } }}>Delete</button>{' '} </span></h2> <div className="App-collection-id">{collection.locator}</div> </div> <ul> {collection.titles.map(title => title.series ? ( <li key={title.name} className="App-library-list-item"> <Link to={'/library/' + encodeURIComponent(collection.locator) + '/' + encodeURIComponent(title.name)}> {title.name} <span style={{color: 'grey'}}>[{title.parts.count}]</span> </Link> </li> ) : ( <VideoListItem collection={collection} videoId={title.videoId} name={title.name} key={title.name} /> ) )} </ul> </li> ))} </ul> ) : ( <div className="App-no-collections-message"> To get started, <Link to="/add_collection">Add A Collection</Link> to your library. </div> )}/> <Route path="/settings" render={({history}) => ( <Settings mainState={mainState} actions={actions} history={history} /> )}/> <Redirect to="/library"/> </Switch> </div> </WidthWrapper> )}/> </Switch> </ScrollContext></Router> ); } } } export default App;
web/src/content/projects/earning-insight/EarningInsightStories.js
ajmalafif/ajmalafif.com
import React from 'react' import Stories from 'react-insta-stories' import { getImage, GatsbyImage } from 'gatsby-plugin-image' import tw, { css, theme } from 'twin.macro' export const EarningInsightStories = props => { const figure1 = <GatsbyImage alt="Earning Insight exploration A" image={getImage(props.assets[0])} /> const figure2 = <GatsbyImage alt="Earning Insight exploration B" image={getImage(props.assets[1])} /> const figure3a = <GatsbyImage alt="Earning Insight exploration C1" image={getImage(props.assets[2])} /> const figure3b = <GatsbyImage alt="Earning Insight exploration C2" image={getImage(props.assets[3])} /> const stories = [ { content: props => ( <div style={{ background: 'var(--color-border)', height: '100%', width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', paddingTop: '2rem', paddingBottom: '2rem', }} > <figure css={{ width: '100%' }}> <img css={{ width: 320, maxWidth: 'min(320px, calc(100% - 32px))', margin: '0 auto', }} srcSet={figure1.props.image.images.sources[0].srcSet} src={figure1.props.image.images.fallback.src} alt={figure1.props.alt} /> <figcaption tw="font-sans" css={{ overflow: 'hidden', left: 0, bottom: 0, textAlign: 'center', width: '100% !important', fontWeight: 400, color: 'var(--text-primary) !important', fontSize: '0.75rem !important', padding: '0.5rem !important', margin: '0 !important', marginTop: '2rem !important', position: 'absolute !important', }} > Exploration A: Overlap driver‘s earning with average earnings for other drivers by default </figcaption> </figure> </div> ), }, { content: props => ( <div style={{ background: 'var(--color-border)', height: '100%', width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', }} > <figure css={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16, }} > <img css={{ width: 320, maxWidth: 'min(320px, calc(100% - 32px))', margin: '0 auto', }} srcSet={figure2.props.image.images.sources[0].srcSet} src={figure2.props.image.images.fallback.src} alt={figure2.props.alt} /> <figcaption tw="font-sans" css={{ overflow: 'hidden', left: 0, bottom: 0, textAlign: 'center', width: '100% !important', fontWeight: 400, color: 'var(--text-primary) !important', fontSize: '0.75rem !important', padding: '0.5rem !important', margin: '0 !important', marginTop: '2rem !important', position: 'absolute !important', }} > Exploration B: A toggle to show a range of weekly average earnings for all drivers </figcaption> </figure> </div> ), }, { content: props => ( <div style={{ background: 'var(--color-border)', height: '100%', width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', }} > <figure css={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16, }} > <img css={{ width: 320, maxWidth: 'min(320px, calc(50% - 32px))', }} srcSet={figure3a.props.image.images.sources[0].srcSet} src={figure3a.props.image.images.fallback.src} alt={figure3a.props.alt} /> <img css={{ width: 320, maxWidth: 'min(320px, calc(50% - 32px))', }} srcSet={figure3b.props.image.images.sources[0].srcSet} src={figure3b.props.image.images.fallback.src} alt={figure3b.props.alt} /> <figcaption tw="font-sans" css={{ overflow: 'hidden', left: 0, bottom: 0, textAlign: 'center', width: '100% !important', fontWeight: 400, color: 'var(--text-primary) !important', fontSize: '0.75rem !important', padding: '0.5rem !important', margin: '0 !important', marginTop: '2rem !important', position: 'absolute !important', }} > Exploration C: Show average earnings of other drivers on a separate tab </figcaption> </figure> </div> ), }, ] return ( <div className="fare-alert-exploration" tw="border-t border-b md:border my-4" css={{ borderColor: `${theme`borderColor.accent`}`, zIndex: 1, position: 'relative' }} > <Stories stories={stories} height={640} width="100%" defaultInterval={10240} loop={true} /> </div> ) } export default EarningInsightStories
client/containers/App/index.js
andreiconstantinescu/project-viper
import React from 'react' import { connect } from 'react-redux' import RandomNumber from 'components/RandomNumber' import RoundImage from 'components/RoundImage' import { Actions as GenerateNumberActions } from 'redux/RandomNumber.redux' import { Actions as SetMessageActions } from 'redux/Message.redux' import { Types as StarWarsTypes } from 'redux/StarWars.redux' import { starWars } from 'sagas/actions' import { random } from 'lodash' import { getTest, GetCharacter } from 'api' const App = props => { const { message, randomNumber, handleClick, getFoo, handleSW } = props return ( <div className='dt w-100'> <div className='dtc v-mid tc white ph3 ph4-l'> <RoundImage /> <RandomNumber number={randomNumber.value || 0}/> <button className='f6 link dim br2 ba ph3 pv2 mb2 dib dark-gray bg-transparent ma3 pointer' onClick={ handleClick } > Press Me! </button> <button className='f6 link dim br2 ba ph3 pv2 mb2 dib dark-gray bg-transparent ma3 pointer' onClick={ () => getFoo('TEST_PARAM') } > Test API Call </button> <button className='f6 link dim br2 ba ph3 pv2 mb2 dib dark-gray bg-transparent ma3 pointer' onClick={ () => handleSW() } > Star Wars Character </button> <h2 className='black-60'> { message.value } </h2> </div> </div> ) } const mapStateToProps = state => ({...state }) const mapDispatchToProps = dispatch => ({ handleClick: () => { dispatch(GenerateNumberActions.generate()) dispatch(SetMessageActions.setMessage( process.env.NODE_ENV !== 'production' ? 'Awesome! Now check Reactotron and press again 😜' : 'Aweomse! Generate another number!' )) }, async getFoo (param) { dispatch(SetMessageActions.setMessage((await getTest(param)).data)) }, async handleSW (id = random(1, 87)) { dispatch({ type: starWars, payload: id }) } }) export default connect(mapStateToProps, mapDispatchToProps)(App)
popup/src/scripts/components/search/HashtagSearchList.js
CaliAlec/ChromeIGStory
import React, { Component } from 'react'; import {connect} from 'react-redux'; import Tooltip from '@material-ui/core/Tooltip'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemText from '@material-ui/core/ListItemText'; import ListItemAvatar from '@material-ui/core/ListItemAvatar'; import Avatar from '@material-ui/core/Avatar'; import IconButton from '@material-ui/core/IconButton'; import DownloadIcon from '@material-ui/icons/GetApp'; import CircularProgress from '@material-ui/core/CircularProgress'; import InstagramApi from '../../../../../utils/InstagramApi'; import {fetchStory} from '../../../../../utils/Utils'; import {setCurrentStoryObject} from '../../utils/PopupUtils'; import AnalyticsUtil from '../../../../../utils/AnalyticsUtil'; class HashtagSearchList extends Component { constructor(props){ super(props); this.state = { selectedIndex: -1, downloadingIndex: -1, isDownloadingStory: false } } handleRequestChange (event, index) { var selectedResult = this.props.results[index]; fetchStory(selectedResult, false, (story) => { setCurrentStoryObject('USER_STORY', story); }); this.setState({ selectedIndex: index, }); AnalyticsUtil.track("Search List Item Clicked", { type: "hashtag", result: { id: selectedResult.id, name: selectedResult.name } }); } getMenuItem(index) { return ( <Tooltip title="Download" > <IconButton onClick={() => { if(!this.state.isDownloadingStory) { var selectedResult = this.props.results[index]; this.setState({ isDownloadingStory: true, downloadingIndex: index }); fetchStory(selectedResult, true, (story) => { this.setState({isDownloadingStory: false}); if(!story) { // show 'No Story Available' Snackbar message setCurrentStoryObject(null, null); } }); } }}> {(this.state.isDownloadingStory && this.state.downloadingIndex === index) ? <CircularProgress size={24}/> : <DownloadIcon />} </IconButton> </Tooltip> ); } render() { const hashtagSearchListData = this.props.results.map((hashtag, key) => { return ( <ListItem key={key} button selected={this.state.selectedIndex === key} onClick={event => this.handleRequestChange(event, key)} > <ListItemAvatar> <Avatar>#</Avatar> </ListItemAvatar> <ListItemText primary={hashtag.name} /> {this.getMenuItem(key)} </ListItem> ) }); return ( <List onChange={this.handleRequestChange.bind(this)}> {hashtagSearchListData} </List> ) } } export default HashtagSearchList;
app/containers/LocaleToggle/index.js
54vanya/ru-for-you-front
/* * * LanguageToggle * */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import Toggle from 'components/Toggle'; import Wrapper from './Wrapper'; import messages from './messages'; import { appLocales } from '../../i18n'; import { changeLocale } from '../LanguageProvider/actions'; import { selectLocale } from '../LanguageProvider/selectors'; export class LocaleToggle extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <Wrapper> <Toggle value={this.props.locale} values={appLocales} messages={messages} onToggle={this.props.onLocaleToggle} /> </Wrapper> ); } } LocaleToggle.propTypes = { onLocaleToggle: React.PropTypes.func, locale: React.PropTypes.string, }; const mapStateToProps = createSelector( selectLocale(), (locale) => ({ locale }) ); export function mapDispatchToProps(dispatch) { return { onLocaleToggle: (evt) => dispatch(changeLocale(evt.target.value)), dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(LocaleToggle);
src/screens/App/screens/About/index.js
savitri/savitri-web
import React from 'react'; export default class About extends React.Component { render() { return ( <div> <h2>About</h2> <p>About Savitri.</p> </div> ); } }
src/components/atoms/Atom/index.stories.js
SIB-Colombia/dataportal_v2_frontend
import React from 'react' import { storiesOf } from '@kadira/storybook' import Atom from '.' storiesOf('Atom', module) .add('default', () => ( <Atom>Hello</Atom> )) .add('reverse', () => ( <Atom reverse>Hello</Atom> ))
examples/with-firebase-functions/src/App.js
jaredpalmer/razzle
import './App.css'; import React from 'react'; const App = () => <div>Welcome to Razzle.</div>; export default App;
admin/client/App/screens/Item/components/FooterBar.js
matthieugayon/keystone
import React from 'react'; import blacklist from 'blacklist'; import assign from 'object-assign'; var FooterBar = React.createClass({ propTypes: { style: React.PropTypes.object, }, getDefaultProps () { return { style: {}, }; }, getInitialState () { return { position: 'relative', width: 'auto', height: 'auto', top: 0, }; }, componentDidMount () { // Bail in IE8 because React doesn't support the onScroll event in that browser // Conveniently (!) IE8 doesn't have window.getComputedStyle which we also use here if (!window.getComputedStyle) return; var footer = this.refs.footer; this.windowSize = this.getWindowSize(); var footerStyle = window.getComputedStyle(footer); this.footerSize = { x: footer.offsetWidth, y: footer.offsetHeight + parseInt(footerStyle.marginTop || '0'), }; window.addEventListener('scroll', this.recalcPosition, false); window.addEventListener('resize', this.recalcPosition, false); this.recalcPosition(); }, componentWillUnmount () { window.removeEventListener('scroll', this.recalcPosition, false); window.removeEventListener('resize', this.recalcPosition, false); }, getWindowSize () { return { x: window.innerWidth, y: window.innerHeight, }; }, recalcPosition () { var wrapper = this.refs.wrapper; this.footerSize.x = wrapper.offsetWidth; var offsetTop = 0; var offsetEl = wrapper; while (offsetEl) { offsetTop += offsetEl.offsetTop; offsetEl = offsetEl.offsetParent; } var maxY = offsetTop + this.footerSize.y; var viewY = window.scrollY + window.innerHeight; var newSize = this.getWindowSize(); var sizeChanged = (newSize.x !== this.windowSize.x || newSize.y !== this.windowSize.y); this.windowSize = newSize; var newState = { width: this.footerSize.x, height: this.footerSize.y, }; if (viewY > maxY && (sizeChanged || this.mode !== 'inline')) { this.mode = 'inline'; newState.top = 0; newState.position = 'absolute'; this.setState(newState); } else if (viewY <= maxY && (sizeChanged || this.mode !== 'fixed')) { this.mode = 'fixed'; newState.top = window.innerHeight - this.footerSize.y; newState.position = 'fixed'; this.setState(newState); } }, render () { var wrapperStyle = { height: this.state.height, marginTop: 60, position: 'relative', }; var footerProps = blacklist(this.props, 'children', 'style'); var footerStyle = assign({}, this.props.style, { position: this.state.position, top: this.state.top, width: this.state.width, height: this.state.height, }); return ( <div ref="wrapper" style={wrapperStyle}> <div ref="footer" style={footerStyle} {...footerProps}>{this.props.children}</div> </div> ); }, }); module.exports = FooterBar;
src/Tab/index.js
reactivers/react-mcw
/** * Created by muratguney on 28/03/2017. */ import React from 'react'; import PropTypes from 'prop-types'; import Button from '../Button' import WaveEffect from '../WaveEffect' import generateId from '../utils/generateId'; class Tabs extends React.Component { constructor(props) { super(props); this.state = {selected: props.defaultSelectedIndex || 0, id: ''}; } componentWillMount() { this.content = this.props.children[this.state.selected] ? this.props.children[this.state.selected].props.children : this.props.children.props.children; } changed = true; componentWillReceiveProps(nextProps){ if(nextProps.defaultSelectedIndex != this.props.defaultSelectedIndex && this.changed){ this.setState({selected: nextProps.defaultSelectedIndex}); this.changed = false } } render() { const {defaultSelectedIndex, tabContentStyle, tabStyle, style, light,indicatorStyle, indicatorColor, selectedBackgroundColor, selectedLabelColor, content, changeTab, index, selectedTab, unSelectedBackgroundColor, unSelectedLabelColor, label, children, ...otherProps} = this.props; return ( <div {...otherProps} style={{width: "100%", ...style}}> <div className="rmd-centered-item" style={{display: "flex", padding: "8px 0 8px 0", margin: "8px 0 8px 0", ...tabStyle}}> {React.Children.map(this.props.children, (child, index) => { return React.cloneElement(child, { selectedTab: this.state.selected, getId: (e) => this.id = e, key:index, changeTab: (e, content, id) => { this.setState({selected: e, id}, () => this.props.onChange && this.props.onChange(e)); this.content = content }, index: index, light:light, defaultSelectedIndex, tabContentStyle, selectedBackgroundColor, selectedLabelColor, unSelectedBackgroundColor, unSelectedLabelColor, }) })} </div> <Indicator selected={this.state.selected} {...this.props}/> <div style={{margin: 8, padding: 8, ...tabContentStyle}}>{this.content}</div> </div> ) } static propTypes = { selectedLabelColor: PropTypes.string, unSelectedLabelColor: PropTypes.string, selectedBackgroundColor: PropTypes.string, unSelectedBackgroundColor: PropTypes.string, indicatorColor: PropTypes.string, defaultSelectedIndex: PropTypes.number, style: PropTypes.object, tabContentStyle: PropTypes.object, indicatorStyle: PropTypes.object, tabStyle: PropTypes.object, fullWidth: PropTypes.bool, }; } class Tab extends React.Component { static propTypes = { label: PropTypes.any, style: PropTypes.object, onClick: PropTypes.func }; componentWillMount() { this.id = generateId(); window.id = this.id; } componentWillReceiveProps(nextProps){ if(this.props.children !== nextProps.children && nextProps.selectedTab === this.props.index) { nextProps.changeTab && nextProps.changeTab(this.props.index, nextProps.children, this.id) } } componentDidMount() { this.props.selectedTab === this.props.index && this.props.getId && this.props.getId(this.id); this.props.selectedTab == this.props.index && this.props.changeTab && this.props.changeTab(this.props.index, this.props.children, this.id) } isSelected() { return this.props.selectedTab == this.props.index } render() { this.props.selectedTab === this.props.index && this.props.getId && this.props.getId(this.id); const {style, selectedBackgroundColor, onClick,selectedLabelColor, changeTab, index, unSelectedBackgroundColor, unSelectedLabelColor, label,light, children} = this.props; return ( <WaveEffect light={light}> <Button id={this.id} style={{ width: "100%", color: this.isSelected() ? (selectedLabelColor || "white") : (unSelectedLabelColor || "white"), whiteSpace: "nowrap", textOverflow: "ellipsis", backgroundColor: this.isSelected() ? (selectedBackgroundColor || "") : (unSelectedBackgroundColor || ""), minHeight: 48, margin: 0, ...style }} onClick={(e) =>{ onClick && onClick(e) ; changeTab && changeTab(index, children, this.id)} } accent={this.isSelected()} primary={!selectedBackgroundColor} raised> {label} </Button> </WaveEffect> ) } } class Indicator extends React.Component { render() { return ( <div style={{ position: "relative", margin: 0, padding: 0, backgroundColor: this.props.indicatorColor || "white", transition: "0.4s", height: 3, top: -18, zIndex: 10, left: this.props.selected * (100 / this.props.children.length) + "%", width: 100 / this.props.children.length + "%", ...this.props.indicatorStyle }}/> ) } } export {Tabs, Tab}
src/routes.js
jhines2k7/react-starter-one
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import Router from 'react-routing/src/Router'; import http from './core/HttpClient'; import App from './components/App'; import ContentPage from './components/ContentPage'; import ContactPage from './components/ContactPage'; import LoginPage from './components/LoginPage'; import RegisterPage from './components/RegisterPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}>{component}</App>; }); on('/contact', async () => <ContactPage />); on('/login', async () => <LoginPage />); on('/register', async () => <RegisterPage />); on('*', async (state) => { const content = await http.get(`/api/content?path=${state.path}`); return content && <ContentPage {...content} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App> ); }); export default router;
gxa/src/main/javascript/bundles/differential-expression/src/DifferentialResults.js
gxa/atlas
import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-components' import URI from 'urijs' import EbiSpeciesIcon from 'react-ebi-species' import DisplayLevelsButton from './DisplayLevelsButton' import DifferentialDownloadButton from './DifferentialDownloadButton' import DifferentialFoldChangeCell from './DifferentialFoldChangeCell' import Legend from './legend/LegendDifferential' import ContrastTooltipLoader from './tooltip/ContrastTooltipLoader' const Header = styled.th` text-align: center; ` const Data = styled.td` text-align: center; ` const differentialResultRowDataPropTypes = { species: PropTypes.string.isRequired, kingdom: PropTypes.string.isRequired, experimentType: PropTypes.string.isRequired, numReplicates: PropTypes.number, regulation: PropTypes.string.isRequired, factors: PropTypes.arrayOf(PropTypes.string).isRequired, bioentityIdentifier: PropTypes.string.isRequired, bioentityName: PropTypes.string.isRequired, experimentAccession: PropTypes.string.isRequired, experimentName: PropTypes.string.isRequired, contrastId: PropTypes.string.isRequired, comparison: PropTypes.string.isRequired, foldChange: PropTypes.number.isRequired, colour: PropTypes.string.isRequired, id: PropTypes.string.isRequired, uri: PropTypes.string.isRequired } const DifferentialResultsRow = (props) => <tr> <DifferentialFoldChangeCell foldChange={props.foldChange} pValue={props.pValue} tStat={props.tStatistics} displayLevels={props.displayLevels} colour={props.colour} id={props.id}/> <Data style={{fontSize: `3rem`}}> <EbiSpeciesIcon species={props.species}/> </Data> <Data> <a href={URI(`genes/${props.bioentityIdentifier}`, props.atlasUrl).toString()}> {props.bioentityName || props.bioentityIdentifier} </a> </Data> <Data data-tip data-for={`${props.id}_contrast`}> <a href={URI(props.uri, props.atlasUrl)}> {props.comparison} </a> <ContrastTooltipLoader id={`${props.id}_contrast`} atlasUrl={props.atlasUrl} tooltipUrl={`rest/contrast-summary`} tooltipUrlParams={{ experimentAccession: props.experimentAccession, contrastId: props.contrastId, accessKey: props.accessKey }} /> </Data> <Data> {props.factors ? props.factors.toString().replace(/,/g, `, `) : ``} </Data> <Data> <a href={URI(`experiments/${props.experimentAccession}`, props.atlasUrl).toString()}> {props.experimentName} </a> </Data> </tr> DifferentialResultsRow.propTypes = { ...differentialResultRowDataPropTypes, atlasUrl: PropTypes.string.isRequired } class DifferentialResults extends React.Component { constructor(props) { super(props) this.state = { displayLevels: false, } this._toggleDisplayLevels = this._toggleDisplayLevels.bind(this) } _toggleDisplayLevels() { const newDisplayLevels = !this.state.displayLevels this.setState({ displayLevels: newDisplayLevels }) } render() { return ( <div className={`row column expanded`}> <div className={`row column expanded`}> <div className={`small-2 columns padding-left-none padding-right-none center`}> <Legend minDownLevel={this.props.minDownLevel} maxDownLevel={this.props.maxDownLevel} minUpLevel={this.props.minUpLevel} maxUpLevel={this.props.maxUpLevel} /> </div> <div className={`small-2 columns padding-left-none padding-right-none margin-left-large text-center`}> <DisplayLevelsButton onClick={this._toggleDisplayLevels} displayLevels={this.state.displayLevels} /> </div> <div className={`small-2 columns padding-left-none padding-right-none margin-left-large text-right`}> <DifferentialDownloadButton results={this.props.results} /> </div> </div> <div className={`row column expanded`}> <table className={`gxaDifferentialResultsTable`}> <thead> <tr> <Header style={{width: `10%`}}>Log<sub>2</sub>-fold change</Header> <Header style={{width: `5%`}}>Species</Header> <Header style={{width: `5%`}}>Gene name</Header> <Header style={{width: `30%`}}>Comparison</Header> <Header style={{width: `15%`}}>Experimental variables</Header> <Header style={{width: `35%`}}>Experiment name</Header> </tr> </thead> <tbody> { this.props.results.map(diffResult => <DifferentialResultsRow key = {diffResult.id} displayLevels = {this.state.displayLevels} atlasUrl = {this.props.atlasUrl} {...diffResult} />) } </tbody> </table> </div> </div> ) } } DifferentialResults.propTypes = { results: PropTypes.arrayOf(PropTypes.shape( differentialResultRowDataPropTypes )).isRequired, maxDownLevel: PropTypes.number, minDownLevel: PropTypes.number, minUpLevel: PropTypes.number, maxUpLevel: PropTypes.number, atlasUrl: PropTypes.string.isRequired } DifferentialResults.defaultProps = { maxDownLevel: Number.NEGATIVE_INFINITY, minDownLevel: 0, minUpLevel: 0, maxUpLevel: Number.POSITIVE_INFINITY, } export default DifferentialResults
src/App.js
PaulMill/myline_life
import React, { Component } from 'react'; import './App.css'; import NavBar from './components/navBar/NavBar.component' import axios from 'axios' import logo from './logo.svg' // import { browserHistory } from 'react-router' class App extends Component { constructor(props) { super(props) this.state = { isLoggedIn: false, userId: 0, userName: '', url: '' } this.setUserState = this.setUserState.bind(this) } setUserState(newstate){ this.setState(newstate) } componentWillMount(){ axios.get('/api/tokens') .then((res) => { if (!res.data) { return } return this.setState(res.data) }) .then(() => { return }) .catch(err => { console.error(err); }) } render() { const { isLoggedIn, userId, userName, url } = this.state const styleTextH1 = {textAlign: 'center', color: '#919999', fontSize: '4rem', fontWeight: 'bold', fontFamily: 'Oswald'} const styleTextH0 = {textAlign: 'center', color: '#b84818', fontSize: '5.7rem', fontWeight: 'bold', fontFamily: 'Oswald', marginTop: "6%"} return ( <div> <NavBar login={isLoggedIn} url={url} name={userName} id={userId}/> { this.props.children ? React.cloneElement(this.props.children, {url, isLoggedIn, userId, userName, setUserState: this.setUserState}) : null } {this.state.isLoggedIn ? <div></div> : <main> <div className="container" style={{marginTop: '5%'}}> <div className="row justify-content-md-center"> <div className="col-md-8 col-sm-12"> <div style={{textAlign: "center"}}> <img src={logo} className="App-logo" alt="logo" style={{marginBottom: "4%", fill: "#b84818"}} /> </div> <h1 style={styleTextH1}></h1> <h1 style={styleTextH1}></h1> <h1 style={styleTextH0}>{`{ thebook.photos }`}</h1> <div style={{marginTop: "8%"}}> <h3 style={{fontStyle: 'italic', textAlign: 'center', color: "#C4CFCF", fontWeight: 'bold'}}>Organize, Share, & Manage</h3> <h3 style={{fontStyle: 'italic', textAlign: 'center', color: "#C4CFCF", fontWeight: 'bold'}}>All of Your Photos in One Place</h3><br /> </div> </div> </div> </div> <video className="videoWelcomePage" poster="./bground/bgr.jpg" autoPlay="true" loop> <source src="./bground/bgr.mp4" type="video/mp4" />Your browser does not support the video tag. I suggest you upgrade your browser. <source src="./bground/bgr.webm" type="video/webm" />Your browser does not support the video tag. I suggest you upgrade your browser. </video> </main> } </div> ) } } export default App;
geonode/contrib/monitoring/frontend/src/index.js
timlinux/geonode
import React from 'react'; import { render } from 'react-dom'; import Root from './containers/root'; import injectTapEventPlugin from 'react-tap-event-plugin'; // Needed for onTouchTap // http://stackoverflow.com/a/34015469/988941 injectTapEventPlugin(); const spinner = document.getElementById('spinner'); spinner.style.display = 'none'; render( <Root />, document.getElementById('monitoring') );
pootle/static/js/admin/duedates/components/DueDateContainer.js
evernote/zing
/* * Copyright (C) Zing contributors. * * This file is a part of the Zing project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import React from 'react'; import DueDateAPI from 'api/DueDateAPI'; import DueDateWidget from './DueDateWidget'; class DueDateContainer extends React.Component { constructor(props) { super(props); const { initialDueDate } = props; this.state = { id: initialDueDate.id, isOpen: false, dueOn: initialDueDate.due_on, pootlePath: initialDueDate.pootle_path, }; } handleRemove(id) { DueDateAPI.remove(id).then(() => this.setState( { id: null, dueOn: 0, isOpen: false, }, this.handlePostUpdate ) ); } handleUpdate(isoDate) { const { id } = this.state; let promise; if (id) { promise = DueDateAPI.update(id, isoDate); } else { promise = DueDateAPI.add(this.state.pootlePath, isoDate); } promise.then((dueDate) => { this.setState( () => ({ id: dueDate.id, dueOn: dueDate.due_on, isOpen: false, }), this.handlePostUpdate ); }); } handlePostUpdate() { // FIXME: dirty but okayish for now PTL.stats.refreshTasks(); } handleToggle() { this.setState((prevState) => ({ isOpen: !prevState.isOpen, })); } render() { return ( <DueDateWidget dueOn={this.state.dueOn} id={this.state.id} isOpen={this.state.isOpen} onRemove={(id) => this.handleRemove(id)} onToggle={() => this.handleToggle()} onUpdate={(isoDate) => this.handleUpdate(isoDate)} /> ); } } DueDateContainer.propTypes = { initialDueDate: React.PropTypes.shape({ id: React.PropTypes.number, due_on: React.PropTypes.number, pootle_path: React.PropTypes.string, }), }; DueDateContainer.defaultProps = { initialDueDate: {}, }; export default DueDateContainer;
src/components/common/detailsList/DetailsListItem.js
zainxyz/react-reads
import isEmpty from 'lodash/isEmpty'; import PropTypes from 'prop-types'; import React from 'react'; /** * Render a single details list item * @param {string} options.label The label for the list item * @param {string} options.value The value for the list item * @param {Object} options The props for the DetailsListItem component * @return {JSX} */ const DetailsListItem = ({ label, value, }) => (!isEmpty(value) ? ( <li className="details-list__item"> { !isEmpty(label) && <p>{label}</p> } <p>{value}</p> </li> ) : null ); DetailsListItem.propTypes = { label: PropTypes.string, value: PropTypes.string, }; DetailsListItem.defaultProps = { label: '', value: '', }; export default DetailsListItem;
src/components/widget/RawWidget.js
metasfresh/metasfresh-webui-frontend
import Moment from 'moment'; import React, { Component } from 'react'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import { connect } from 'react-redux'; import classnames from 'classnames'; import { List as ImmutableList } from 'immutable'; import { RawWidgetPropTypes, RawWidgetDefaultProps } from './PropTypes'; import { getClassNames, generateMomentObj } from './RawWidgetHelpers'; import { allowShortcut, disableShortcut } from '../../actions/WindowActions'; import { DATE_FORMAT, TIME_FORMAT, DATE_TIMEZONE_FORMAT, DATE_FIELD_FORMATS, } from '../../constants/Constants'; import ActionButton from './ActionButton'; import Attributes from './Attributes/Attributes'; import Checkbox from './Checkbox'; import DatePicker from './DatePicker'; import DatetimeRange from './DatetimeRange'; import DevicesWidget from './Devices/DevicesWidget'; import Image from './Image'; import Tooltips from '../tooltips/Tooltips'; import Labels from './Labels'; import Link from './Link'; import CharacterLimitInfo from './CharacterLimitInfo'; import List from './List/List'; import Lookup from './Lookup/Lookup'; /** * @file Class based component. * @module RawWidget * @extends Component */ export class RawWidget extends Component { constructor(props) { super(props); const { widgetData } = props; let cachedValue = undefined; if (widgetData && widgetData[0]) { if (widgetData[0].value !== undefined) { cachedValue = widgetData[0].value; } else if ( widgetData[0].status && widgetData[0].status.value !== undefined ) { cachedValue = widgetData[0].status.value; } } this.state = { isEdited: false, cachedValue, errorPopup: false, tooltipToggled: false, clearedFieldWarning: false, }; this.getClassNames = getClassNames.bind(this); this.generateMomentObj = generateMomentObj.bind(this); } componentDidMount() { const { autoFocus, textSelected } = this.props; const { rawWidget } = this; if (rawWidget && autoFocus) { rawWidget.focus(); } if (textSelected) { rawWidget.select(); } } /** * Re-rendering conditions by widgetType this to prevent unnecessary re-renders * Performance boost */ shouldComponentUpdate(nextProps) { switch (this.props.widgetType) { case 'YesNo': return nextProps.widgetData[0].value !== this.props.widgetData[0].value; default: return true; } } /** * @method focus * @summary Function used specifically for list widgets. It blocks outside clicks, which are * then enabled again in handleBlur. This is to avoid closing the list as it's a separate * DOM element outside of it's parent's tree. */ focus = () => { const { handleFocus, disableOnClickOutside } = this.props; const { rawWidget } = this; if (rawWidget && rawWidget.focus) { rawWidget.focus(); } disableOnClickOutside && disableOnClickOutside(); handleFocus && handleFocus(); }; /** * @method handleFocus * @summary ToDo: Describe the method. * @param {*} e */ handleFocus = () => { const { dispatch, handleFocus, listenOnKeysFalse } = this.props; dispatch(disableShortcut()); listenOnKeysFalse && listenOnKeysFalse(); setTimeout(() => { this.setState( { isEdited: true, }, () => { handleFocus && handleFocus(); } ); }, 0); }; /** * @method handleBlurBlur * @summary ToDo: Describe the method. * @param {*} widgetField * @param {*} value * @param {*} id */ handleBlur = (widgetField, value, id) => { const { dispatch, handleBlur, listenOnKeysTrue, enableOnClickOutside, } = this.props; this.setState( { isEdited: false, }, () => { enableOnClickOutside && enableOnClickOutside(); dispatch(allowShortcut()); handleBlur && handleBlur(this.willPatch(widgetField, value)); listenOnKeysTrue && listenOnKeysTrue(); if (widgetField) { this.handlePatch(widgetField, value, id); } } ); }; /** * @method updateTypedCharacters * @summary updates in the state the number of charactes typed * @param {typedText} string */ updateTypedCharacters = (typedText) => { const { fieldName } = this.props; let existingCharsTyped = { ...this.state.charsTyped }; existingCharsTyped[fieldName] = typedText.length; this.setState({ charsTyped: existingCharsTyped }); return true; }; /** * @method handleKeyDown * @summary key handler for the widgets. For number fields we're suppressing up/down * arrows to enable table row navigation * @param {*} e * @param {*} property * @param {*} value */ handleKeyDown = (e, property, value) => { const { lastFormField, widgetType, closeTableField } = this.props; const { key } = e; this.updateTypedCharacters(e.target.value); // for number fields submit them automatically on up/down arrow pressed and blur the field const NumberWidgets = ImmutableList([ 'Integer', 'Amount', 'Quantity', 'Number', 'CostPrice', ]); if ( (key === 'ArrowUp' || key === 'ArrowDown') && NumberWidgets.includes(widgetType) ) { closeTableField(); e.preventDefault(); this.handleBlur(); return this.handlePatch(property, value, null, null, true); } if ((key === 'Enter' || key === 'Tab') && !e.shiftKey) { if (key === 'Enter' && !lastFormField) { e.preventDefault(); } return this.handlePatch(property, value); } }; /** * @method willPatch * @summary Checks if the value has actually changed between what was cached before. * @param {*} property * @param {*} value * @param {*} valueTo */ willPatch = (property, value, valueTo) => { const { widgetData } = this.props; const { cachedValue } = this.state; // if there's no widget value, then nothing could've changed. Unless // it's a widget for actions (think ActionButton) const isValue = widgetData[0].value !== undefined || (widgetData[0].status && widgetData[0].status.value !== undefined); let fieldData = widgetData.find((widget) => widget.field === property); if (!fieldData) { fieldData = widgetData[0]; } let allowPatching = (isValue && (JSON.stringify(fieldData.value) != JSON.stringify(value) || JSON.stringify(fieldData.valueTo) != JSON.stringify(valueTo))) || JSON.stringify(cachedValue) != JSON.stringify(value) || // clear field that had it's cachedValue nulled before (cachedValue === null && value === null); if (cachedValue === undefined && !value) { allowPatching = false; } return allowPatching; }; /** * @method handlePatch * @summary Method for handling the actual patching from the widget(input), which in turn * calls the parent method (usually from MasterWidget) if the requirements are met * (value changed and patching is not in progress). `isForce` will be used for Datepicker * Datepicker is checking the cached value in datepicker component itself * and send a patch request only if date is changed * @param {*} property * @param {*} value * @param {*} id * @param {*} valueTo * @param {*} isForce */ handlePatch = (property, value, id, valueTo, isForce) => { const { handlePatch, inProgress, widgetType, maxLength } = this.props; const willPatch = this.willPatch(property, value, valueTo); if (widgetType === 'LongText' || widgetType === 'Text') { value = value.substring(0, maxLength); this.updateTypedCharacters(value); } // Do patch only when value is not equal state // or cache is set and it is not equal value if ((isForce || willPatch) && handlePatch && !inProgress) { if (widgetType === 'ZonedDateTime' && Moment.isMoment(value)) { value = Moment(value).format(DATE_TIMEZONE_FORMAT); } this.setState({ cachedValue: value, clearedFieldWarning: false, }); return handlePatch(property, value, id, valueTo); } return Promise.resolve(null); }; /** * @method handleProcess * @summary ToDo: Describe the method. */ handleProcess = () => { const { handleProcess, buttonProcessId, tabId, rowId, dataId, windowType, caption, } = this.props; handleProcess && handleProcess(caption, buttonProcessId, tabId, rowId, dataId, windowType); }; /** * @method handleErrorPopup * @summary ToDo: Describe the method. * @param {*} value */ handleErrorPopup = (value) => { this.setState({ errorPopup: value, }); }; /** * @method clearFieldWarning * @summary ToDo: Describe the method. * @param {*} warning */ clearFieldWarning = (warning) => { if (warning) { this.setState({ clearedFieldWarning: true, }); } }; /** * @method toggleTooltip * @summary ToDo: Describe the method. * @param {*} show */ toggleTooltip = (show) => { this.setState({ tooltipToggled: show, }); }; /** * @method renderErrorPopup * @summary ToDo: Describe the method. * @param {*} reason */ renderErrorPopup = (reason) => { return ( <div className="input-error-popup">{reason ? reason : 'Input error'}</div> ); }; /** * @method renderWidget * @summary ToDo: Describe the method. */ renderWidget = () => { const { handleChange, updated, modalVisible, isModal, filterWidget, filterId, id, range, onHide, handleBackdropLock, subentity, widgetType, subentityId, dropdownOpenCallback, autoFocus, fullScreen, //@TODO Looks like `fields` and `widgetData` are the very same thing 99.9% of the time. fields, windowType, dataId, type, widgetData, rowId, tabId, docId, activeTab, icon, gridAlign, entity, onShow, caption, viewId, data, listenOnKeys, listenOnKeysFalse, closeTableField, handleZoomInto, attribute, allowShowPassword, onBlurWidget, defaultValue, isOpenDatePicker, dateFormat, initialFocus, timeZone, fieldName, maxLength, } = this.props; let widgetValue = data != null ? data : widgetData[0].value; const { isEdited, charsTyped } = this.state; // TODO: API SHOULD RETURN THE SAME PROPERTIES FOR FILTERS const widgetField = filterWidget ? fields[0].parameterName : fields[0].field; const readonly = widgetData[0].readonly; let tabIndex = this.props.tabIndex; if (widgetValue === null) { widgetValue = ''; } if (fullScreen || readonly || (modalVisible && !isModal)) { tabIndex = -1; } // TODO: this logic should be removed and adapted below after widgetType === 'MultiListValue' is added const isMultiselect = widgetData[0].widgetType === 'List' && widgetData[0].multiListValue ? true : false; // TODO: ^^^^^^^^^^^^^ const widgetProperties = { ref: (c) => (this.rawWidget = c), //autocomplete=new-password did not work in chrome for non password fields anymore, //switched to autocomplete=off instead autoComplete: 'off', className: 'input-field js-input-field', value: widgetValue, defaultValue, placeholder: fields[0].emptyText, disabled: readonly, onFocus: this.handleFocus, tabIndex: tabIndex, onChange: (e) => handleChange && this.updateTypedCharacters(e.target.value) && handleChange(widgetField, e.target.value), onBlur: (e) => this.handleBlur(widgetField, e.target.value, id), onKeyDown: (e) => this.handleKeyDown(e, widgetField, e.target.value, widgetType), title: widgetValue, id, }; const showErrorBorder = charsTyped && charsTyped[fieldName] > maxLength; let selectedValue = widgetData[0].value ? widgetData[0].value : widgetData[0].defaultValue; switch (widgetType) { case 'Date': if (range) { // TODO: Watch out! The datetimerange widget as exception, // is non-controlled input! For further usage, needs // upgrade. return ( <DatetimeRange onChange={(value, valueTo) => this.handlePatch( widgetField, value ? Moment(value).format(DATE_FORMAT) : null, null, valueTo ? Moment(valueTo).format(DATE_FORMAT) : null ) } field={widgetField} mandatory={widgetData[0].mandatory} validStatus={widgetData[0].validStatus} value={widgetData[0].value} valueTo={widgetData[0].valueTo} {...{ tabIndex, onShow, onHide, timeZone, }} /> ); } else { return ( <div className={this.getClassNames({ icon: true })}> <DatePicker key={1} field={widgetField} timeFormat={false} dateFormat={dateFormat || true} inputProps={{ placeholder: fields[0].emptyText, disabled: readonly, tabIndex: tabIndex, }} value={widgetValue || widgetData[0].value} onChange={(date) => handleChange(widgetField, date)} patch={(date) => this.handlePatch( widgetField, this.generateMomentObj(date, DATE_FORMAT), null, null, true ) } handleChange={handleChange} {...{ handleBackdropLock, isOpenDatePicker, timeZone, }} /> </div> ); } case 'ZonedDateTime': return ( <div className={this.getClassNames({ icon: true })}> <DatePicker key={1} field={widgetField} timeFormat={true} dateFormat={dateFormat || true} hasTimeZone={true} inputProps={{ placeholder: fields[0].emptyText, disabled: readonly, tabIndex: tabIndex, }} value={widgetValue || widgetData[0].value} onChange={(date) => handleChange(widgetField, date)} patch={(date) => this.handlePatch( widgetField, this.generateMomentObj(date, DATE_TIMEZONE_FORMAT), null, null, true ) } handleChange={handleChange} {...{ handleBackdropLock, isOpenDatePicker, timeZone, }} /> </div> ); case 'Time': return ( <div className={this.getClassNames({ icon: true })}> <DatePicker field={widgetField} timeFormat={TIME_FORMAT} dateFormat={false} inputProps={{ placeholder: fields[0].emptyText, disabled: readonly, tabIndex: tabIndex, }} value={widgetValue} onChange={(date) => handleChange(widgetField, date)} patch={(date) => this.handlePatch( widgetField, this.generateMomentObj(date, TIME_FORMAT), null, null, true ) } tabIndex={tabIndex} handleChange={handleChange} handleBackdropLock={handleBackdropLock} /> </div> ); case 'Timestamp': return ( <div className={this.getClassNames({ icon: true })}> <DatePicker field={widgetField} timeFormat={false} dateFormat={DATE_FIELD_FORMATS[widgetType]} inputProps={{ placeholder: fields[0].emptyText, disabled: readonly, tabIndex: tabIndex, }} value={widgetValue} onChange={(date) => handleChange(widgetField, date)} patch={(date) => this.handlePatch( widgetField, this.generateMomentObj(date, `x`), null, null, true ) } tabIndex={tabIndex} handleChange={handleChange} handleBackdropLock={handleBackdropLock} /> </div> ); case 'DateRange': { return ( <DatetimeRange onChange={(value, valueTo) => { const val = Moment(value).format(DATE_FORMAT); const valTo = Moment(valueTo).format(DATE_FORMAT); this.handlePatch(widgetField, { ...(val && { value: val }), ...(valTo && { valueTo: valTo }), }); }} mandatory={widgetData[0].mandatory} validStatus={widgetData[0].validStatus} onShow={onShow} onHide={onHide} value={widgetData[0].value} valueTo={widgetData[0].valueTo} tabIndex={tabIndex} /> ); } case 'Lookup': return ( <Lookup {...{ attribute, }} entity={entity} subentity={subentity} subentityId={subentityId} recent={[]} dataId={dataId} properties={fields} windowType={windowType} widgetData={widgetData} placeholder={ this.props.emptyText ? this.props.emptyText : this.props.fields[0].emptyText } readonly={readonly} mandatory={widgetData[0].mandatory} rank={type} align={gridAlign} isModal={isModal} updated={updated} filterWidget={filterWidget} filterId={filterId} parameterName={fields[0].parameterName} selected={widgetValue} tabId={tabId} rowId={rowId} tabIndex={tabIndex} viewId={viewId} autoFocus={autoFocus} initialFocus={initialFocus} forceFullWidth={this.props.forceFullWidth} forceHeight={this.props.forceHeight} validStatus={widgetData[0].validStatus} newRecordCaption={fields[0].newRecordCaption} newRecordWindowId={fields[0].newRecordWindowId} listenOnKeys={listenOnKeys} listenOnKeysFalse={listenOnKeysFalse} closeTableField={closeTableField} onFocus={this.focus} onBlur={this.handleBlur} onChange={this.handlePatch} onBlurWidget={onBlurWidget} onClickOutside={this.props.onClickOutside} /> ); case 'List': return ( <List {...{ attribute, }} widgetField={widgetField} dataId={dataId} entity={entity} subentity={subentity} subentityId={subentityId} defaultValue={fields[0].emptyText} selected={selectedValue} properties={fields[0]} readonly={readonly} mandatory={widgetData[0].mandatory} windowType={windowType} rowId={rowId} tabId={tabId} onFocus={this.focus} onBlur={this.handleBlur} onChange={this.handlePatch} align={gridAlign} updated={updated} filterWidget={filterWidget} filterId={filterId} parameterName={fields[0].parameterName} emptyText={fields[0].emptyText} tabIndex={tabIndex} viewId={viewId} autoFocus={autoFocus} validStatus={widgetData[0].validStatus} isMultiselect={isMultiselect} /> ); case 'MultiListValue': return ( <List {...{ attribute, }} widgetField={widgetField} dataId={dataId} entity={entity} subentity={subentity} subentityId={subentityId} defaultValue={fields[0].emptyText} selected={widgetData[0].value || null} properties={fields[0]} readonly={readonly} mandatory={widgetData[0].mandatory} windowType={windowType} rowId={rowId} tabId={tabId} onFocus={this.focus} onBlur={this.handleBlur} onChange={this.handlePatch} align={gridAlign} updated={updated} filterWidget={filterWidget} filterId={filterId} parameterName={fields[0].parameterName} emptyText={fields[0].emptyText} tabIndex={tabIndex} viewId={viewId} autoFocus={autoFocus} validStatus={widgetData[0].validStatus} isMultiselect={true} /> ); case 'Link': return ( <Link getClassNames={() => this.getClassNames({ icon: true })} {...{ isEdited, widgetProperties, icon, widgetData, tabIndex, fullScreen, }} /> ); case 'Text': return ( <div> <div className={classnames( this.getClassNames({ icon: true, }), { 'input-focused': isEdited, }, { 'border-danger': showErrorBorder, } )} > <input {...widgetProperties} type="text" /> {icon && <i className="meta-icon-edit input-icon-right" />} </div> {charsTyped && charsTyped[fieldName] >= 0 && ( <CharacterLimitInfo charsTyped={charsTyped[fieldName]} maxLength={maxLength} /> )} </div> ); case 'LongText': return ( <div> <div className={classnames( this.getClassNames({ icon: false, forcedPrimary: true, }), { 'input-focused': isEdited, }, { 'border-danger': showErrorBorder, } )} > <textarea {...widgetProperties} /> </div> {charsTyped && charsTyped[fieldName] >= 0 && ( <CharacterLimitInfo charsTyped={charsTyped[fieldName]} maxLength={maxLength} /> )} </div> ); case 'Password': return ( <div className="input-inner-container"> <div className={classnames( this.getClassNames({ icon: true, }), { 'input-focused': isEdited, } )} > <input {...widgetProperties} type="password" ref={(c) => (this.rawWidget = c)} /> {icon && <i className="meta-icon-edit input-icon-right" />} </div> {allowShowPassword && ( <div onMouseDown={() => { this.rawWidget.type = 'text'; }} onMouseUp={() => { this.rawWidget.type = 'password'; }} className="btn btn-icon btn-meta-outline-secondary btn-inline pointer btn-distance-rev btn-sm" > <i className="meta-icon-show" /> </div> )} </div> ); case 'Integer': case 'Amount': case 'Quantity': return ( <div className={classnames(this.getClassNames(), 'number-field', { 'input-focused': isEdited, })} > <input {...widgetProperties} type="number" min={0} precision={widgetField === 'CableLength' ? 2 : 1} step={subentity === 'quickInput' ? 0.1 : 1} /> </div> ); case 'Number': case 'CostPrice': return ( <div className={classnames(this.getClassNames(), 'number-field', { 'input-focused': isEdited, })} > <input {...widgetProperties} type="number" /> </div> ); case 'YesNo': return ( <Checkbox {...{ widgetData, disabled: readonly, fullScreen, tabIndex, widgetField, id, filterWidget, }} handlePatch={this.handlePatch} /> ); case 'Switch': return ( <label className={classnames('input-switch', { 'input-disabled': readonly, 'input-mandatory': widgetData[0].mandatory && widgetData[0].value.length === 0, 'input-error': widgetData[0].validStatus && !widgetData[0].validStatus.valid, 'input-table': rowId && !isModal, })} tabIndex={tabIndex} ref={(c) => (this.rawWidget = c)} onKeyDown={(e) => { e.key === ' ' && this.handlePatch(widgetField, !widgetData[0].value, id); }} > <input type="checkbox" checked={widgetData[0].value} disabled={readonly} tabIndex="-1" onChange={(e) => this.handlePatch(widgetField, e.target.checked, id) } /> <div className="input-slider" /> </label> ); case 'Label': return ( <div className={classnames('tag tag-warning ', { [`text-${gridAlign}`]: gridAlign, })} tabIndex={tabIndex} ref={(c) => (this.rawWidget = c)} > {widgetData[0].value} </div> ); case 'Button': return ( <button className={ 'btn btn-sm btn-meta-primary ' + (gridAlign ? 'text-' + gridAlign + ' ' : '') + (readonly ? 'tag-disabled disabled ' : '') } onClick={() => this.handlePatch(widgetField)} tabIndex={tabIndex} ref={(c) => (this.rawWidget = c)} > {widgetData[0].value && widgetData[0].value[Object.keys(widgetData[0].value)[0]]} </button> ); case 'ProcessButton': return ( <button className={ 'btn btn-sm btn-meta-primary ' + (gridAlign ? 'text-' + gridAlign + ' ' : '') + (readonly ? 'tag-disabled disabled ' : '') } onClick={this.handleProcess} tabIndex={tabIndex} ref={(c) => (this.rawWidget = c)} > {caption} </button> ); case 'ActionButton': return ( <ActionButton data={widgetData[0]} windowType={windowType} fields={fields} dataId={dataId} docId={docId} activeTab={activeTab} onChange={(option) => this.handlePatch(fields[1].field, option)} tabIndex={tabIndex} dropdownOpenCallback={dropdownOpenCallback} ref={(c) => (this.rawWidget = c)} /> ); case 'ProductAttributes': return ( <Attributes entity={entity} attributeType="pattribute" fields={fields} dataId={dataId} widgetData={widgetData[0]} docType={windowType} tabId={tabId} rowId={rowId} viewId={viewId} onFocus={this.handleFocus} onBlur={this.handleBlur} fieldName={widgetField} handleBackdropLock={handleBackdropLock} patch={(option) => this.handlePatch(widgetField, option)} tabIndex={tabIndex} autoFocus={autoFocus} readonly={readonly} /> ); case 'Address': return ( <Attributes attributeType="address" entity={entity} fields={fields} dataId={dataId} widgetData={widgetData[0]} docType={windowType} tabId={tabId} rowId={rowId} fieldName={widgetField} handleBackdropLock={handleBackdropLock} patch={(option) => this.handlePatch(widgetField, option)} tabIndex={tabIndex} autoFocus={autoFocus} readonly={readonly} isModal={isModal} /> ); case 'Image': return ( <Image fields={fields} data={widgetData[0]} handlePatch={this.handlePatch} readonly={readonly} /> ); case 'ZoomIntoButton': return ( <button className={ 'btn btn-sm btn-meta-primary ' + (gridAlign ? 'text-' + gridAlign + ' ' : '') + (readonly ? 'tag-disabled disabled ' : '') } onClick={() => handleZoomInto(fields[0].field)} tabIndex={tabIndex} ref={(c) => (this.rawWidget = c)} > {caption} </button> ); case 'Labels': { let values = []; const entry = widgetData[0]; if (entry && entry.value && Array.isArray(entry.value.values)) { values = entry.value.values; } return ( <Labels name={widgetField} entity={entity} subentity={subentity} subentityId={subentityId} windowType={windowType} viewId={viewId} selected={values} className={this.getClassNames()} onChange={(value) => this.handlePatch(widgetField, { values: value, }) } tabIndex={tabIndex} /> ); } default: return false; } }; render() { const { caption, description, captionElement, fields, type, noLabel, widgetData, rowId, isModal, handlePatch, widgetType, handleZoomInto, dataEntry, subentity, fieldFormGroupClass, fieldLabelClass, fieldInputClass, } = this.props; const { errorPopup, clearedFieldWarning, tooltipToggled, isEdited, } = this.state; const widgetBody = this.renderWidget(); const { validStatus, warning } = widgetData[0]; const quickInput = subentity === 'quickInput'; // We have to hardcode that exception in case of having // wrong two line rendered one line widgets const oneLineException = ['Switch', 'YesNo', 'Label', 'Button'].indexOf(widgetType) > -1; // Unsupported widget type if (!widgetBody) { // eslint-disable-next-line no-console console.warn( 'The %c' + widgetType, 'font-weight:bold;', 'is unsupported type of widget.' ); return false; } // No display value or not displayed if (!widgetData[0].displayed || widgetData[0].displayed !== true) { return false; } const valueDescription = widgetData[0].value && widgetData[0].value.description ? widgetData[0].value.description : null; const widgetFieldsName = fields .map((field) => 'form-field-' + field.field) .join(' '); let labelClass; let fieldClass; let formGroupClass = ''; if (quickInput) { labelClass = fieldLabelClass; fieldClass = fieldInputClass; formGroupClass = fieldFormGroupClass; } else { labelClass = dataEntry ? 'col-sm-5' : ''; if (!labelClass) { labelClass = type === 'primary' && !oneLineException ? 'col-sm-12 panel-title' : type === 'primaryLongLabels' ? 'col-sm-6' : 'col-sm-3'; } fieldClass = dataEntry ? 'col-sm-7' : ''; if (!fieldClass) { fieldClass = ((type === 'primary' || noLabel) && !oneLineException ? 'col-sm-12 ' : type === 'primaryLongLabels' ? 'col-sm-6' : 'col-sm-9 ') + (fields[0].devices ? 'form-group-flex' : ''); } } const labelProps = {}; if (!noLabel && caption && fields[0].supportZoomInto) { labelProps.onClick = () => handleZoomInto(fields[0].field); } return ( <div className={classnames( 'form-group', formGroupClass, { 'form-group-table': rowId && !isModal, }, widgetFieldsName )} > <div className="row"> {captionElement || null} {!noLabel && caption && ( <label className={classnames('form-control-label', labelClass, { 'input-zoom': quickInput && fields[0].supportZoomInto, 'zoom-into': fields[0].supportZoomInto, })} title={description || caption} {...labelProps} > {caption} </label> )} <div className={fieldClass} onMouseEnter={() => this.handleErrorPopup(true)} onMouseLeave={() => this.handleErrorPopup(false)} > {!clearedFieldWarning && warning && ( <div className={classnames('field-warning', { 'field-warning-message': warning, 'field-error-message': warning && warning.error, })} onMouseEnter={() => this.toggleTooltip(true)} onMouseLeave={() => this.toggleTooltip(false)} > <span>{warning.caption}</span> <i className="meta-icon-close-alt" onClick={() => this.clearFieldWarning(warning)} /> {warning.message && tooltipToggled && ( <Tooltips action={warning.message} type="" /> )} </div> )} <div className={classnames('input-body-container', { focused: isEdited, })} title={valueDescription} > <ReactCSSTransitionGroup transitionName="fade" transitionEnterTimeout={200} transitionLeaveTimeout={200} > {errorPopup && validStatus && !validStatus.valid && !validStatus.initialValue && this.renderErrorPopup(validStatus.reason)} </ReactCSSTransitionGroup> {widgetBody} </div> {fields[0].devices && !widgetData[0].readonly && ( <DevicesWidget devices={fields[0].devices} tabIndex={1} handleChange={(value) => handlePatch && handlePatch(fields[0].field, value) } /> )} </div> </div> </div> ); } } RawWidget.propTypes = RawWidgetPropTypes; RawWidget.defaultProps = RawWidgetDefaultProps; export default connect((state) => ({ modalVisible: state.windowHandler.modal.visible, timeZone: state.appHandler.me.timeZone, }))(RawWidget);
src/components/Header/Header.js
sjackson212/A6DotCom
import React from 'react'; import root from 'window-or-global'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Header.css'; import Link from '../Link'; import Navigation from '../Navigation'; import logoUrl from './A6-logo.svg'; class Header extends React.Component { render() { let pathname = ''; if (root && root.window && root.window.location) { pathname = root.window.location.pathname; } return ( <div className={s.root}> <div className={s.container}> <Link className={s.brand} to="/"> <img src={logoUrl} className={s.logo} alt="React" /> </Link> <Navigation pathname={pathname} /> </div> </div> ); } } export default withStyles(s)(Header);
src/modules/search/components/WorksSearchTermButton/WorksSearchTermButton.js
CtrHellenicStudies/Commentary
import React from 'react'; import { withRouter } from 'react-router'; import PropTypes from 'prop-types'; import FontIcon from 'material-ui/FontIcon'; import qs from 'qs-lite'; import autoBind from 'react-autobind'; // lib import { parseValueUrn } from '../../../cts/lib/parseUrn'; import serializeUrn from '../../../cts/lib/serializeUrn'; import defaultWorksEditions from '../../../comments/lib/defaultWorksEditions'; import getCurrentSubdomain from '../../../../lib/getCurrentSubdomain'; class WorksSearchTermButton extends React.Component { constructor(props) { super(props); autoBind(this); } handleChangeTextLocationWorksButton(key, value) { const queryParams = qs.parse(window.location.search.replace('?', '')); const subdomain = getCurrentSubdomain(); let urn = value; let works = []; let refsDecls = []; if (defaultWorksEditions[subdomain] && defaultWorksEditions[subdomain].works) { works = defaultWorksEditions[subdomain].works; works.forEach(work => { if (urn.indexOf(work.urn) === 0) { refsDecls = work.refsDecls; } }); } const parsedUrn = parseValueUrn(urn); parsedUrn.passage = [new Array(refsDecls.length).fill(1)]; // update route const urlParams = qs.stringify(queryParams); this.props.history.push(`/commentary/${serializeUrn(parsedUrn)}/?${urlParams}`); } render() { const { label, value, active } = this.props; return ( <li> <button className={`search-term-button ${(active) ? 'search-term-button--active' : ''}`} onClick={this.handleChangeTextLocationWorksButton.bind(this, 'works', value)} > <span className="search-term-button-label"> {label} </span> <FontIcon className="mdi mdi-plus-circle-outline search-term-button-icon" /> </button> </li> ); } } WorksSearchTermButton.propTypes = { label: PropTypes.string.isRequired, value: PropTypes.any.isRequired, // eslint-disable-line react/forbid-prop-types active: PropTypes.bool, }; WorksSearchTermButton.defaultProps = { active: false, }; export default withRouter(WorksSearchTermButton);
pootle/static/js/admin/components/Project/ProjectController.js
claudep/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import React from 'react'; import Search from '../Search'; import ProjectAdd from './ProjectAdd'; import ProjectEdit from './ProjectEdit'; const ProjectController = React.createClass({ propTypes: { items: React.PropTypes.object.isRequired, model: React.PropTypes.func.isRequired, onAdd: React.PropTypes.func.isRequired, onCancel: React.PropTypes.func.isRequired, onDelete: React.PropTypes.func.isRequired, onSearch: React.PropTypes.func.isRequired, onSelectItem: React.PropTypes.func.isRequired, onSuccess: React.PropTypes.func.isRequired, searchQuery: React.PropTypes.string.isRequired, selectedItem: React.PropTypes.object, view: React.PropTypes.string.isRequired, }, render() { const viewsMap = { add: ( <ProjectAdd model={this.props.model} collection={this.props.items} onSuccess={this.props.onSuccess} onCancel={this.props.onCancel} /> ), edit: ( <ProjectEdit model={this.props.selectedItem} collection={this.props.items} onAdd={this.props.onAdd} onSuccess={this.props.onSuccess} onDelete={this.props.onDelete} /> ), }; const args = { count: this.props.items.count, }; let msg; if (this.props.searchQuery) { msg = ngettext('%(count)s project matches your query.', '%(count)s projects match your query.', args.count); } else { msg = ngettext( 'There is %(count)s project.', 'There are %(count)s projects. Below are the most recently added ones.', args.count ); } const resultsCaption = interpolate(msg, args, true); return ( <div className="admin-app-projects"> <div className="module first"> <Search fields={['index', 'code', 'fullname', 'disabled']} onSearch={this.props.onSearch} onSelectItem={this.props.onSelectItem} items={this.props.items} selectedItem={this.props.selectedItem} searchLabel={gettext('Search Projects')} searchPlaceholder={gettext('Find project by name, code')} resultsCaption={resultsCaption} searchQuery={this.props.searchQuery} /> </div> <div className="module admin-content"> {viewsMap[this.props.view]} </div> </div> ); }, }); export default ProjectController;
src/CollapsibleMixin.js
zerkms/react-bootstrap
import React from 'react'; import TransitionEvents from './utils/TransitionEvents'; import deprecationWarning from './utils/deprecationWarning'; let warned = false; const CollapsibleMixin = { propTypes: { defaultExpanded: React.PropTypes.bool, expanded: React.PropTypes.bool }, getInitialState(){ let defaultExpanded = this.props.defaultExpanded != null ? this.props.defaultExpanded : this.props.expanded != null ? this.props.expanded : false; return { expanded: defaultExpanded, collapsing: false }; }, componentWillMount(){ if ( !warned ){ deprecationWarning('CollapsibleMixin', 'Collapse Component'); warned = true; } }, componentWillUpdate(nextProps, nextState){ let willExpanded = nextProps.expanded != null ? nextProps.expanded : nextState.expanded; if (willExpanded === this.isExpanded()) { return; } // if the expanded state is being toggled, ensure node has a dimension value // this is needed for the animation to work and needs to be set before // the collapsing class is applied (after collapsing is applied the in class // is removed and the node's dimension will be wrong) let node = this.getCollapsibleDOMNode(); let dimension = this.dimension(); let value = '0'; if(!willExpanded){ value = this.getCollapsibleDimensionValue(); } node.style[dimension] = value + 'px'; this._afterWillUpdate(); }, componentDidUpdate(prevProps, prevState){ // check if expanded is being toggled; if so, set collapsing this._checkToggleCollapsing(prevProps, prevState); // check if collapsing was turned on; if so, start animation this._checkStartAnimation(); }, // helps enable test stubs _afterWillUpdate(){ }, _checkStartAnimation(){ if(!this.state.collapsing) { return; } let node = this.getCollapsibleDOMNode(); let dimension = this.dimension(); let value = this.getCollapsibleDimensionValue(); // setting the dimension here starts the transition animation let result; if(this.isExpanded()) { result = value + 'px'; } else { result = '0px'; } node.style[dimension] = result; }, _checkToggleCollapsing(prevProps, prevState){ let wasExpanded = prevProps.expanded != null ? prevProps.expanded : prevState.expanded; let isExpanded = this.isExpanded(); if(wasExpanded !== isExpanded){ if(wasExpanded) { this._handleCollapse(); } else { this._handleExpand(); } } }, _handleExpand(){ let node = this.getCollapsibleDOMNode(); let dimension = this.dimension(); let complete = () => { this._removeEndEventListener(node, complete); // remove dimension value - this ensures the collapsible item can grow // in dimension after initial display (such as an image loading) node.style[dimension] = ''; this.setState({ collapsing:false }); }; this._addEndEventListener(node, complete); this.setState({ collapsing: true }); }, _handleCollapse(){ let node = this.getCollapsibleDOMNode(); let complete = () => { this._removeEndEventListener(node, complete); this.setState({ collapsing: false }); }; this._addEndEventListener(node, complete); this.setState({ collapsing: true }); }, // helps enable test stubs _addEndEventListener(node, complete){ TransitionEvents.addEndEventListener(node, complete); }, // helps enable test stubs _removeEndEventListener(node, complete){ TransitionEvents.removeEndEventListener(node, complete); }, dimension(){ return (typeof this.getCollapsibleDimension === 'function') ? this.getCollapsibleDimension() : 'height'; }, isExpanded(){ return this.props.expanded != null ? this.props.expanded : this.state.expanded; }, getCollapsibleClassSet(className) { let classes = {}; if (typeof className === 'string') { className.split(' ').forEach(subClasses => { if (subClasses) { classes[subClasses] = true; } }); } classes.collapsing = this.state.collapsing; classes.collapse = !this.state.collapsing; classes.in = this.isExpanded() && !this.state.collapsing; return classes; } }; export default CollapsibleMixin;
dashboard/app/components/app.js
benjaminjt/polyatomic
import React, { Component } from 'react'; import Hello from './hello'; class App extends Component { render() { return ( <div> <Hello /> </div> ); } } export default App
src/client/assets/js/nodes/datastores/plug/node.js
me-box/databox-sdk
import React from 'react'; import Textfield from 'components/form/Textfield'; import Select from 'components/form/Select'; import Cell from 'components/Cell'; import Cells from 'components/Cells'; class Node extends React.Component { render() { const {selected,values,updateNode} = this.props; const nameprops = { id: "name", value: this.props.values.name || "", onChange: (property, event)=>{ this.props.updateNode(property, event.target.value); }, } const typeprops = { options: [ {name: 'power', value: 'power'}, {name: 'voltage', value: 'voltage'}, {name: 'current', value: 'current'}, {name: 'on/off', value: 'power-state'}, ], onSelect: (event)=>{ this.props.updateNode("subtype", event.target.value); this.props.updateOutputSchema(event.target.value); }, style: {width: '100%'}, value: this.props.values.subtype || "", } const typeinput = <div className="centered"> <Select {...typeprops}/> </div> const nameinput = <div className="centered"> <Textfield {...nameprops}/> </div> return <div> <Cells> <Cell title={"name"} content={nameinput}/> <Cell title={"type"} content={typeinput}/> </Cells> </div> } }
react-app/src/components/ParentHome.js
floodfx/gma-village
import React from 'react'; import { Link } from 'react-router'; const ParentHome = ({user}) => ( <div> <div className="pv3 ph4 gma-orange-border"> <h1 className="lh-title f1 serif gma-orange">Welcome {user.first_name}!</h1> <p className="lh-copy f3"> We are looking forward to supporting you with you child care needs. </p> <h3 className="f3 serif gma-orange">Actions</h3> <ul className="lh-copy f3"> <li><Link to="/gma/list">Search for Gmas</Link></li> <li><Link to="/profile">Edit your profile</Link></li> <li><Link to="/careNeed/create">Post a Care Need</Link></li> </ul> </div> </div> ) export default ParentHome
packages/material-ui-icons/src/SpeakerNotesOff.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let SpeakerNotesOff = props => <SvgIcon {...props}> <path d="M10.54 11l-.54-.54L7.54 8 6 6.46 2.38 2.84 1.27 1.73 0 3l2.01 2.01L2 22l4-4h9l5.73 5.73L22 22.46 17.54 18l-7-7zM8 14H6v-2h2v2zm-2-3V9l2 2H6zm14-9H4.08L10 7.92V6h8v2h-7.92l1 1H18v2h-4.92l6.99 6.99C21.14 17.95 22 17.08 22 16V4c0-1.1-.9-2-2-2z" /> </SvgIcon>; SpeakerNotesOff = pure(SpeakerNotesOff); SpeakerNotesOff.muiName = 'SvgIcon'; export default SpeakerNotesOff;
client/src/components/dashboard/Profile/Preferences/common/RepoContainer.js
FCC-Alumni/alumni-network
import { connectScreenSize } from 'react-screen-size'; import { mapScreenSizeToProps } from '../../../Community/UserCard'; import propTypes from 'prop-types'; import React from 'react'; import repoHosts from '../../../../../assets/dropdowns/repoHosts'; import RepoInput from './RepoInput'; import RepoListItem from './RepoListItem'; import styled from 'styled-components'; import { Dimmer, Loader, Segment } from 'semantic-ui-react'; import { indexOf, isEmpty } from 'lodash'; import { searchGithubCommits, validateOtherRepos as validateOther, validateGithubRepo as validateRepo } from '../../../../../actions/repoValidations'; /* TODO: 1) Refactor addItem() code - UPDATE - at least partially done */ export const Container = styled.div` margin: 16px 0 !important; `; class RepoContainer extends React.Component { state = { error: {}, icon: 'github', isLoading: false, item: '', items_list: [], label: 'https://github.com/' } componentWillMount() { const items = this.props.prePopulateList; if (items.length > 0) { this.setState({ items_list: items }); } } componentDidMount() { document.addEventListener('keydown', this.handleKeyPress); } componentWillUnmount() { document.removeEventListener('keydown', this.handleKeyPress); } addItem = () => { this.setState({ isLoading: true }); const { item, items_list, label } = this.state; const [ namespace, repo ] = item.split('/'); // check if nothing entered if (!item) { this.setState({ isLoading: false }); return; } // check if format is valid: NAMESPACE/REPO if (!this.isFormatValid(repo)) { return; } // check if item already exists on list if (this.repoAlreadyAdded(item, items_list, label)) { return; } // HANDLE GITLAB: if (label === 'https://gitlab.com/' && this.isValidGitlabNaming(item, namespace, repo)) { this.validateOtherRepos('GitLab'); } // HANDLE BITBUCKET: if (label === 'https://bitbucket.org/' && this.isValidBitbucketNaming(item, repo)) { this.validateOtherRepos('BitBucket'); } // HANDLE GITHUB: if (label === 'https://github.com/' && this.isValidGithubNaming(item, namespace, repo)) { this.validateGithubRepos(); } } editItem = (item) => { const items_list = this.spliceList(item); this.setState({ item: item.item, items_list }); } handleChange = (e) => { this.setState({ error: '', item: e.target.value }); } handleKeyPress = (e) => { if (e.keyCode === 13) { this.addItem(); } } handleLabelChange = (e) => { let icon; if (e.target.innerText === 'https://github.com/') icon = 'github' if (e.target.innerText === 'https://gitlab.com/') icon = 'gitlab' if (e.target.innerText === 'https://bitbucket.org/') icon = 'bitbucket' this.setState({ icon, label: e.target.innerText }); } isFormatValid = (repo) => { if (!repo) { this.setState({ error: { header: `Invalid entry. Plese enter a valid repo in the format: namespace/repo.`, }, isLoading: false, item: '', }); return false; } return true; } isValidBitbucketNaming = (item, repo) => { if ( (repo.length === 1 && /^\./.test(repo)) || !/[\d\w-]+\/[\d\w-.]+\/?/.test(item) ) { this.setState({ error: { header: 'Please enter a valid BitBucket repository path: namespace/repo', namespace: `Namespace: This value must contain only ASCII letters, numbers, dashes and underscores.`, repo: `Repo: This value must contain only ASCII letters, numbers, dashes, underscores and periods.`, }, isLoading: false, item: '', }); return false; } else { return true; } } isValidGitlabNaming = (item, namespace, repo) => { if ( /(^-)|(\.((git)|(atom))?$)/.test(repo) || /(^-)|(\.((git)|(atom))?$)/.test(namespace) || !/[\d\w-.]+\/[\d\w-.]+\/?/.test(item) ) { this.setState({ error: { header: 'Please enter a valid GitLab repository path: namespace/repo', namespace: `Repo: This value can only contain letters, digits, '_', '-' and '.'. Cannot start with '-' or end in '.', '.git' or '.atom'`, repo: `Namespace: This value can only contain letters, digits, '_', '-' and '.'. Cannot start with '-' or end in '.', '.git' or '.atom'`, }, isLoading: false, item: '' }); return false; } else { return true; } } isValidGithubNaming = (item, namespace, repo) => { if ( // GitHub naming conventions: /^\./.test(repo) === '.' || /^-|--|-$/.test(namespace) || !/[\d\w-.]+\/[\d\w-]+\/?/.test(item) ) { this.setState({ error: { header: 'Please enter a valid GitHub repository path: namespace/repo', namespace: `Namespace: This value may only contain alphanumeric characters or single hyphens, and cannot begin or end with a hyphen.`, repo: `Repo: This value may only contain alphanumeric characters, periods, and hyphens, and cannot begin with a period.`, }, isLoading: false, item: '' }); return false; } return true; } removeItem = (item) => { const items_list = this.spliceList(item); this.setState({ items_list }, () => this.props.saveChanges(items_list)); } repoAlreadyAdded = (item, items_list, label) => { for (var obj of items_list) { if (obj.item.toLowerCase() === item.toLowerCase() && obj.label === label) { this.setState({ error: { header: 'You have already added this repo to your list!', }, isLoading: false, item: '' }); return true; } } return false; } spliceList = (item) => { const { items_list } = this.state; const index = indexOf(items_list, item); items_list.splice(index, 1); return items_list; } validateGithubRepos = () => { const { username } = this.props; const { item, items_list, label } = this.state; const [ namespace, repo ] = item.split('/'); validateRepo(namespace, repo, username) .then((res) => { const contributors = res.contributorsList; let isContributor = false; // first check if user is listed as contributor // if yes, setState & continue for (var contributor of contributors) { if (contributor.author.login === username) { isContributor = true; items_list.push({item, label}); this.setState({ isLoading: false, item: '', items_list, }, () => this.props.saveChanges(items_list)); } } // if user is not listed, repo may have > 100 contributors... // then search commit history of repo for commits by user. // prefer to use both checks, becuase this one is in "preview", // github warns changes could happen at any time with no notice. if (!isContributor) { searchGithubCommits(namespace, repo, username) .then((res) => { const commits = res.data.items; if (commits.length > 0) { isContributor = true; items_list.push({item, label}); this.setState({ isLoading: false, item: '', items_list, }, () => this.props.saveChanges(items_list)); } }) .catch((err) => { console.warn('There was a problem with GitHub\'s API: ' + err.message); }); } // if user/repo does not pass either check, reject with error if (!isContributor) { this.setState({ error: { header: 'You must be a contributor to the repo you would like to collaborate on.', }, isLoading: false, item: '', }); } }) // this should catch on the first axios.get request if repo does not exist // also handle mystery problem here (hopefully) .catch((err) => { err = 'contributors[Symbol.iterator]'; if (/\[Symbol.iterator\]/.test(err)) { this.setState({ error: { header: 'There was a problem with GitHub\'s API, please try again.', }, isLoading: false, item: '', }); } else { this.setState({ error: { header: 'Repository is private or invalid. Please enter a public, valid GitHub repo.', }, isLoading: false, item: '', }); } }); } validateOtherRepos = (hostSite) => { const { item, items_list, label } = this.state; const hostUrl = hostSite === 'BitBucket' ? 'https://bitbucket.org/' : 'https://gitlab.com/'; validateOther(item, hostUrl).then((res) => { if (res) { items_list.push({item, label}); this.setState({ isLoading: false, item: '', items_list, }, () => this.props.saveChanges(items_list)); } else { this.setState({ error: { header: `Repository is private or invalid. Please enter a public, valid ${hostSite} repo.`, }, isLoading: false, item: '', }); } }) .catch(err => { this.setState({ error: { header: `Our bad, it seems like we really messed this one up! Try again soon.`, }, isLoading: false, item: '', }); }); } render() { const { isMobile } = this.props.screen; const { item, isLoading, icon, error } = this.state; const listItems = this.state.items_list.map((el, i) => { var key = i + el.item.slice(0,3); return ( <RepoListItem editItem={() => this.editItem(el)} el={el} index={key} key={key} removeItem={() => this.removeItem(el)} /> ); }); return ( <Container> <RepoInput addItem={this.addItem} error={error} handleChange={this.handleChange} handleDropdownChange={this.handleLabelChange} icon={icon} isMobile={isMobile} item={item} repoHosts={repoHosts} /> <Segment basic style={{ marginTop: 5, minHeight: 50, padding: 0 }}> <Dimmer active={isLoading && true} inverted> <Loader /> </Dimmer> <div className="ui middle aligned divided selection list" style={{ margin: 0 }}> {listItems} </div> </Segment> { !isEmpty(error) && error.repo && error.namespace && <div className="ui error message"> <div className="header">{error.header}</div> <ul className="list"> <li>{error.namespace}</li> <li>{error.repo}</li> </ul> </div> } </Container> ); } } RepoContainer.propTypes = { prePopulateList: propTypes.array, saveChanges: propTypes.func.isRequired, username: propTypes.string.isRequired, } RepoContainer.defaultProps = { prePopulateList: [] } export default connectScreenSize(mapScreenSizeToProps)(RepoContainer);
techCurriculum/ui/solutions/2.7/src/index.js
jennybkim/engineeringessentials
/** * Copyright 2017 Goldman Sachs. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import '../stylesheet.css'; ReactDOM.render( <App />, document.getElementById('root') );
packages/material-ui-icons/src/Battery80TwoTone.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V9h10V5.33z" /><path d="M7 9v11.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V9H7z" /></React.Fragment> , 'Battery80TwoTone');
lib/ActionSheetIOS.js
beefe/react-native-actionsheet
/** * Wrap ActionSheetIOS Api as a component. * @see http://facebook.github.io/react-native/docs/actionsheetios.html */ import React from 'react' import { ActionSheetIOS } from 'react-native' import optionsSchema from './options' class ActionSheet extends React.Component { // shold not update whenever, because nothing rendered shouldComponentUpdate () { return false } show () { const props = this.props const options = {} optionsSchema.forEach((name) => { const value = props[name] if (typeof value !== 'undefined') { options[name] = value } }) const callback = options.onPress delete options.onPress ActionSheetIOS.showActionSheetWithOptions(options, callback) } // need not render anything render () { return null } } export default ActionSheet
src/components/KFPNavbar.js
KidsFirstProject/KidsFirstProject.github.io
import React from 'react'; import { Navbar, Nav, NavDropdown, Container } from 'react-bootstrap'; import { Link } from 'react-router-dom'; import { LinkContainer } from 'react-router-bootstrap'; import logo from '../assets/images/logo.png'; import './KFPNavbar.css'; const { Brand, Toggle, Collapse } = Navbar; const KFPNavbar = () => ( <Navbar expand="lg" collapseOnSelect sticky="top" className="navbar-custom" variant="dark" > <Container> <Brand> <Link to="/"> <img className="navbar-logo" alt="Kids First Project Logo" src={logo} /> </Link> </Brand> <Toggle aria-controls="basic-navbar-nav" /> <Collapse className="justify-content-end"> <Nav className="ml-auto"> <LinkContainer to="/about"> <Nav.Link>About</Nav.Link> </LinkContainer> <LinkContainer to="/team"> <Nav.Link>Our Team</Nav.Link> </LinkContainer> <LinkContainer to="/advocacy"> <Nav.Link>Advocacy</Nav.Link> </LinkContainer> <NavDropdown title="Programs"> <LinkContainer to="/programs/inshelter"> <NavDropdown.Item>In-Shelter Services</NavDropdown.Item> </LinkContainer> <LinkContainer to="/programs/scholarship"> <NavDropdown.Item>Scholarship Program</NavDropdown.Item> </LinkContainer> </NavDropdown> <NavDropdown title="Get Involved"> <LinkContainer to="/events"> <NavDropdown.Item>Event Calendar</NavDropdown.Item> </LinkContainer> <LinkContainer to="/volunteer"> <NavDropdown.Item>Volunteer</NavDropdown.Item> </LinkContainer> <LinkContainer to="/chapters"> <NavDropdown.Item>Chapters</NavDropdown.Item> </LinkContainer> </NavDropdown> <LinkContainer to="/blog"> <Nav.Link>Blog</Nav.Link> </LinkContainer> <LinkContainer to="/donate"> <Nav.Link>Donate</Nav.Link> </LinkContainer> <LinkContainer to="/contact"> <Nav.Link>Contact Us</Nav.Link> </LinkContainer> </Nav> </Collapse> </Container> </Navbar> ); export default KFPNavbar;
actor-apps/app-web/src/app/components/dialog/TypingSection.react.js
winiceo/actor-platform
import React from 'react'; import { PureRenderMixin } from 'react/addons'; import classNames from 'classnames'; import DialogStore from 'stores/DialogStore'; export default React.createClass({ mixins: [PureRenderMixin], getInitialState() { return { typing: null, show: false }; }, componentDidMount() { DialogStore.addTypingListener(this.onTypingChange); }, componentWillUnmount() { DialogStore.removeTypingListener(this.onTypingChange); }, onTypingChange() { const typing = DialogStore.getSelectedDialogTyping(); if (typing === null) { this.setState({show: false}); } else { this.setState({typing: typing, show: true}); } }, render() { const typing = this.state.typing; const show = this.state.show; const typingClassName = classNames('typing', { 'typing--hidden': show === false }); return ( <div className={typingClassName}> <div className="typing-indicator"><i></i><i></i><i></i></div> <span>{typing}</span> </div> ); } });
RN HotUpdate/SmartHomeII/SmartHome/Community/Community.js
HarrisLee/React-Native-Express
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { StyleSheet, Text, View, Navigator, Platform, WebView, } from 'react-native'; const DEFAULT_URL_COMMUNITY = 'https://sale.suning.com/znjj2/sns/1/sns.html?source=smart'; export default class Community extends Component { constructor(props) { super(props); this.state = { }; } requestShould(request){ console.log(request.url); var url = request.url.indexOf('jsbridge:'); if (url >= 0) { console.log('has contain jsbridge '+ url); return false; } return true; } render() { return (<View style={styles.container}> <WebView style={styles.webView} source={{uri:DEFAULT_URL_COMMUNITY}} startInLoadingState={true} javaScriptEnabled={false} onLoad={()=>alert('加载成功')} onShouldStartLoadWithRequest ={(request)=>this.requestShould(request)}> </WebView> </View> ); } } const styles = StyleSheet.create({ container:{ backgroundColor: '#ffffff', flex: 1 }, webView:{ flex:1, backgroundColor:'#ffffff', } });
js/src/modals/AddContract/types.js
BSDStudios/parity
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import React from 'react'; import { FormattedMessage } from 'react-intl'; import { eip20, wallet } from '~/contracts/abi'; const ABI_TYPES = [ { description: ( <FormattedMessage id='addContract.abiType.token.description' defaultMessage='A standard {erc20} token' values={ { erc20: ( <a href='https://github.com/ethereum/EIPs/issues/20' target='_blank'> <FormattedMessage id='addContract.abiType.token.erc20' defaultMessage='ERC 20' /> </a> ) } } /> ), label: ( <FormattedMessage id='addContract.abiType.token.label' defaultMessage='Token' /> ), readOnly: true, type: 'token', value: JSON.stringify(eip20) }, { description: ( <FormattedMessage id='addContract.abiType.multisigWallet.description' defaultMessage='Ethereum Multisig contract {link}' values={ { link: ( <a href='https://github.com/ethereum/dapp-bin/blob/master/wallet/wallet.sol' target='_blank'> <FormattedMessage id='addContract.abiType.multisigWallet.link' defaultMessage='see contract code' /> </a> ) } } /> ), label: ( <FormattedMessage id='addContract.abiType.multisigWallet.label' defaultMessage='Multisig Wallet' /> ), readOnly: true, type: 'multisig', value: JSON.stringify(wallet) }, { description: ( <FormattedMessage id='addContract.abiType.custom.description' defaultMessage='Contract created from custom ABI' /> ), label: ( <FormattedMessage id='addContract.abiType.custom.label' defaultMessage='Custom Contract' /> ), type: 'custom', value: '' } ]; export { ABI_TYPES };
website-prototyping-tools/RelayPlayground.js
almasakchabayev/relay
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ /* eslint-disable no-unused-vars, no-eval */ import './RelayPlayground.css'; import 'codemirror/mode/javascript/javascript'; import Codemirror from 'react-codemirror'; import React from 'react'; import ReactDOM from 'react/lib/ReactDOM'; import Relay from 'react-relay'; window.Relay = Relay; import RelayLocalSchema from 'relay-local-schema'; import babel from 'babel-core/browser'; import babelRelayPlaygroundPlugin from './babelRelayPlaygroundPlugin'; import debounce from 'lodash.debounce'; import defer from 'lodash.defer'; import errorCatcher from 'babel-plugin-react-error-catcher/error-catcher'; import errorCatcherPlugin from 'babel-plugin-react-error-catcher'; import evalSchema from './evalSchema'; import getBabelRelayPlugin from 'babel-relay-plugin'; import {introspectionQuery} from 'graphql/utilities'; import {graphql} from 'graphql'; var {PropTypes} = React; const CODE_EDITOR_OPTIONS = { extraKeys: { Tab(cm) { // Insert spaces when the tab key is pressed var spaces = Array(cm.getOption('indentUnit') + 1).join(' '); cm.replaceSelection(spaces); }, }, indentWithTabs: false, lineNumbers: true, mode: 'javascript', tabSize: 2, theme: 'solarized light', }; const ERROR_TYPES = { graphql: 'GraphQL Validation', query: 'Query', runtime: 'Runtime', schema: 'Schema', syntax: 'Syntax', }; const RENDER_STEP_EXAMPLE_CODE = `ReactDOM.render( <Relay.RootContainer Component={MyRelayContainer} route={new MyHomeRoute()} />, mountNode );`; function errorFromGraphQLResultAndQuery(errors, request) { var queryString = request.getQueryString(); var variables = request.getVariables(); var errorText = ` ${errors.map(e => e.message).join('\n')} Query: ${queryString} `; if (variables) { errorText += `Variables: ${JSON.stringify(variables)}`; } return {stack: errorText.trim()}; } class PlaygroundRenderer extends React.Component { componentDidMount() { this._container = document.createElement('div'); this.refs.mountPoint.appendChild(this._container); this._updateTimeoutId = defer(this._update); } componentDidUpdate(prevProps) { if (this._updateTimeoutId != null) { clearTimeout(this._updateTimeoutId); } this._updateTimeoutId = defer(this._update); } componentWillUnmount() { if (this._updateTimeoutId != null) { clearTimeout(this._updateTimeoutId); } try { ReactDOM.unmountComponentAtNode(this._container); } catch (e) {} } _update = () => { ReactDOM.render(React.Children.only(this.props.children), this._container); } render() { return <div ref="mountPoint" />; } } export default class RelayPlayground extends React.Component { static defaultProps = { autoExecute: false, }; static propTypes = { autoExecute: PropTypes.bool.isRequired, initialAppSource: PropTypes.string, initialSchemaSource: PropTypes.string, onAppSourceChange: PropTypes.func, onSchemaSourceChange: PropTypes.func, }; state = { appElement: null, appSource: this.props.initialAppSource, busy: false, editTarget: 'app', error: null, schemaSource: this.props.initialSchemaSource, shouldExecuteCode: this.props.autoExecute, }; componentDidMount() { // Hijack console.warn to collect GraphQL validation warnings (we hope) this._originalConsoleWarn = console.warn; var collectedWarnings = []; console.warn = (...args) => { collectedWarnings.push([Date.now(), args]); this._originalConsoleWarn.apply(console, args); }; // Hijack window.onerror to catch any stray fatals this._originalWindowOnerror = window.onerror; window.onerror = (message, url, lineNumber, something, error) => { // GraphQL validation warnings are followed closely by a thrown exception. // Console warnings that appear too far before this exception are probably // not related to GraphQL. Throw those out. if (/GraphQL validation error/.test(message)) { var recentWarnings = collectedWarnings .filter(([createdAt, args]) => Date.now() - createdAt <= 500) .reduce((memo, [createdAt, args]) => memo.concat(args), []); this.setState({ error: {stack: recentWarnings.join('\n')}, errorType: ERROR_TYPES.graphql, }); } else { this.setState({error, errorType: ERROR_TYPES.runtime}); } collectedWarnings = []; return false; }; if (this.state.shouldExecuteCode) { this._updateSchema(this.state.schemaSource, this.state.appSource); } } componentDidUpdate(prevProps, prevState) { var recentlyEnabledCodeExecution = !prevState.shouldExecuteCode && this.state.shouldExecuteCode; var appChanged = this.state.appSource !== prevState.appSource; var schemaChanged = this.state.schemaSource !== prevState.schemaSource; if ( this.state.shouldExecuteCode && (recentlyEnabledCodeExecution || appChanged || schemaChanged) ) { this.setState({busy: true}); this._handleSourceCodeChange( this.state.appSource, recentlyEnabledCodeExecution || schemaChanged ? this.state.schemaSource : null, ); } } componentWillUnmount() { clearTimeout(this._errorReporterTimeout); clearTimeout(this._warningScrubberTimeout); this._handleSourceCodeChange.cancel(); console.warn = this._originalConsoleWarn; window.onerror = this._originalWindowOnerror; } _handleExecuteClick = () => { this.setState({shouldExecuteCode: true}); } _handleSourceCodeChange = debounce((appSource, schemaSource) => { if (schemaSource != null) { this._updateSchema(schemaSource, appSource); } else { this._updateApp(appSource); } }, 300, {trailing: true}) _updateApp = (appSource) => { clearTimeout(this._errorReporterTimeout); // We're running in a browser. Create a require() shim to catch any imports. var require = (path) => { switch (path) { // The errorCatcherPlugin injects a series of import statements into the // program body. Return locally bound variables in these three cases: case '//error-catcher.js': return (React, filename, displayName, reporter) => { // When it fatals, render an empty <span /> in place of the app. return errorCatcher(React, filename, <span />, reporter); }; case 'react': return React; case 'reporterProxy': return (error, instance, filename, displayName) => { this._errorReporterTimeout = defer( this.setState.bind(this), {error, errorType: ERROR_TYPES.runtime} ); }; default: throw new Error(`Cannot find module "${path}"`); } }; try { var {code} = babel.transform(appSource, { filename: 'RelayPlayground', plugins : [ babelRelayPlaygroundPlugin, this._babelRelayPlugin, errorCatcherPlugin('reporterProxy'), ], retainLines: true, sourceMaps: 'inline', stage: 0, }); var result = eval(code); if ( React.isValidElement(result) && result.type.name === 'RelayRootContainer' ) { this.setState({ appElement: React.cloneElement(result, {forceFetch: true}), }); } else { this.setState({ appElement: ( <div> <h2> Render a Relay.RootContainer into <code>mountNode</code> to get started. </h2> <p> Example: </p> <pre>{RENDER_STEP_EXAMPLE_CODE}</pre> </div> ), }); } this.setState({error: null}); } catch (error) { this.setState({error, errorType: ERROR_TYPES.syntax}); } this.setState({busy: false}); } _updateCode = (newSource) => { var sourceStorageKey = `${this.state.editTarget}Source`; this.setState({[sourceStorageKey]: newSource}); if (this.state.editTarget === 'app' && this.props.onAppSourceChange) { this.props.onAppSourceChange(newSource); } if (this.state.editTarget === 'schema' && this.props.onSchemaSourceChange) { this.props.onSchemaSourceChange(newSource); } } _updateEditTarget = (editTarget) => { this.setState({editTarget}); } _updateSchema = (schemaSource, appSource) => { try { var Schema = evalSchema(schemaSource); } catch (error) { this.setState({error, errorType: ERROR_TYPES.schema}); return; } graphql(Schema, introspectionQuery).then((result) => { if ( this.state.schemaSource !== schemaSource || this.state.appSource !== appSource ) { // This version of the code is stale. Bail out. return; } this._babelRelayPlugin = getBabelRelayPlugin(result.data); Relay.injectNetworkLayer( new RelayLocalSchema.NetworkLayer({ schema: Schema, onError: (errors, request) => { this.setState({ error: errorFromGraphQLResultAndQuery(errors, request), errorType: ERROR_TYPES.query, }); }, }) ); this._updateApp(appSource); }); } renderApp() { if (!this.state.shouldExecuteCode) { return ( <div className="rpExecutionGuard"> <div className="rpExecutionGuardMessage"> <h2>For your security, this playground did not auto-execute</h2> <p> Clicking <strong>execute</strong> will run the code in the two tabs to the left. </p> <button onClick={this._handleExecuteClick}>Execute</button> </div> </div> ); } else if (this.state.error) { return ( <div className="rpError"> <h1>{this.state.errorType} Error</h1> <pre className="rpErrorStack">{this.state.error.stack}</pre> </div> ); } else if (this.state.appElement) { return <PlaygroundRenderer>{this.state.appElement}</PlaygroundRenderer>; } return null; } render() { var sourceCode = this.state.editTarget === 'schema' ? this.state.schemaSource : this.state.appSource; return ( <div className="rpShell"> <section className="rpCodeEditor"> <nav className="rpCodeEditorNav"> <button className={this.state.editTarget === 'app' && 'rpButtonActive'} onClick={this._updateEditTarget.bind(this, 'app')}> Code </button> <button className={this.state.editTarget === 'schema' && 'rpButtonActive'} onClick={this._updateEditTarget.bind(this, 'schema')}> Schema </button> </nav> {/* What is going on with the choice of key in Codemirror? * https://github.com/JedWatson/react-codemirror/issues/12 */} <Codemirror key={`${this.state.editTarget}-${this.state.shouldExecuteCode}`} onChange={this._updateCode} options={{ ...CODE_EDITOR_OPTIONS, readOnly: !this.state.shouldExecuteCode, }} value={sourceCode} /> </section> <section className="rpResult"> <h1 className="rpResultHeader"> Relay Playground <span className={ 'rpActivity' + (this.state.busy ? ' rpActivityBusy' : '') } /> </h1> <div className="rpResultOutput"> {this.renderApp()} </div> </section> </div> ); } }
src/components/app.js
JairoHernandez/WeatherApp
import React, { Component } from 'react'; import SearchBar from '../containers/search_bar'; import WeatherList from '../containers/weather_list'; export default class App extends Component { render() { return ( <div> <SearchBar /> <WeatherList /> </div> ); } }
src/mobile/public/components/ProfileCarousel/index.js
Perslu/rerebrace
import React from 'react'; import NukaCarousel from 'nuka-carousel' import R from 'ramda'; import './styles.css'; const profileToProfileListItem = profile => { return <img key={profile.email} src={profile.picture.large}/> }; const log = text => what => { console.log(text, what); return what; }; const objectToList = obj => { const getObjectContent = (key) => obj[key]; return R.map(getObjectContent, R.keys(obj)); }; const ProfileCarousel = (props) => { return ( <div className="ProfileCarousel"> <NukaCarousel cellSpacing={20} slidesToShow={4} decorators={[]} framePadding="20px" > {R.compose(log('profiles for carousel'), R.map(profileToProfileListItem), R.take(10), objectToList)(props.items)} </NukaCarousel> </div> ) } export default ProfileCarousel
src/components/App.js
jonscottclark/mlb-scoreboard
import React, { Component } from 'react'; import { RouteHandler } from 'react-router'; import Header from './Header.js'; import Scoreboard from './Scoreboard.js'; class App extends Component { constructor(props) { super(props); } render() { return ( <div> <Header /> <RouteHandler params={this.props.params} /> </div> ); } } export default App;
app/javascript/mastodon/features/direct_timeline/components/conversation.js
pointlessone/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import StatusContainer from '../../../containers/status_container'; export default class Conversation extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { conversationId: PropTypes.string.isRequired, accounts: ImmutablePropTypes.list.isRequired, lastStatusId: PropTypes.string, unread:PropTypes.bool.isRequired, onMoveUp: PropTypes.func, onMoveDown: PropTypes.func, markRead: PropTypes.func.isRequired, }; handleClick = () => { if (!this.context.router) { return; } const { lastStatusId, unread, markRead } = this.props; if (unread) { markRead(); } this.context.router.history.push(`/statuses/${lastStatusId}`); } handleHotkeyMoveUp = () => { this.props.onMoveUp(this.props.conversationId); } handleHotkeyMoveDown = () => { this.props.onMoveDown(this.props.conversationId); } render () { const { accounts, lastStatusId, unread } = this.props; if (lastStatusId === null) { return null; } return ( <StatusContainer id={lastStatusId} unread={unread} otherAccounts={accounts} onMoveUp={this.handleHotkeyMoveUp} onMoveDown={this.handleHotkeyMoveDown} onClick={this.handleClick} /> ); } }
blueocean-material-icons/src/js/components/svg-icons/device/dvr.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const DeviceDvr = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.1-.9-2-2-2zm0 14H3V5h18v12zm-2-9H8v2h11V8zm0 4H8v2h11v-2zM7 8H5v2h2V8zm0 4H5v2h2v-2z"/> </SvgIcon> ); DeviceDvr.displayName = 'DeviceDvr'; DeviceDvr.muiName = 'SvgIcon'; export default DeviceDvr;
stories/decorators/CenterDecorator.js
suranartnc/react-universal-starter-kit
import React from 'react' const style = { display: 'flex', justifyContent: 'center', alignItems: 'center', height: 'calc(100vh - 16px)' } export default (story) => ( <div style={style}> {story()} </div> )
src/components/Login/login.js
ChronoBank/ChronoWAVES
import React from 'react'; import {connect} from 'react-redux'; import {Paper, RaisedButton, TextField} from 'material-ui'; import styles from './styles'; import {loginSuccessAction} from '../../redux/userActions'; import {blockchain} from '../../blockchain'; class Login extends React.Component { constructor(props) { super(props); this.onInputChange = this.onInputChange.bind(this); this.state = {address: ''}; } /** * This event handler calculates address from current seed */ onInputChange(e) { const currentSeed = e.target.value; const address = blockchain.createAccount(currentSeed).address; this.setState({address: address, seed: currentSeed}); } render() { return ( <div style={styles.loginContainer}> <Paper style={styles.paper}> <TextField floatingLabelText="SEED" type="password" fullWidth={true} onChange={this.onInputChange}/> <p className="mono">{this.state.address}</p> <RaisedButton label="Login" primary={true} fullWidth={true} onTouchTap={() => { this.props.onLoginClick(this.state.seed); }} style={styles.loginBtn}/> </Paper> </div>); } } const mapDispatchToProps = (dispatch, ownProps) => { return { onLoginClick: (seed) => { dispatch(loginSuccessAction(seed)); } } }; export default connect(null, mapDispatchToProps)(Login);
examples/js/remote/remote-store-search.js
neelvadgama-hailo/react-bootstrap-table
import React from 'react'; import RemoteSearch from './remote-search'; function getProducts() { const products = []; const startId = products.length; for (let i = 0; i < 12; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: Math.floor((Math.random() * 2000) + 1) }); } return products; } export default class RemoteStoreSearch extends React.Component { constructor(props) { super(props); this.products = getProducts(); this.state = { data: this.products }; } onSearchChange(searchText, colInfos, multiColumnSearch) { const text = searchText.trim(); if (text === '') { this.setState({ data: this.products }); return; } let searchTextArray = []; if (multiColumnSearch) { searchTextArray = text.split(' '); } else { searchTextArray.push(text); } const data = this.products.filter((product) => { const keys = Object.keys(product); let valid = false; for (let i = 0, keysLength = keys.length; i < keysLength; i++) { const key = keys[i]; if (colInfos[key] && product[key]) { const { format, filterFormatted, formatExtraData, searchable, hidden } = colInfos[key]; let targetVal = product[key]; if (!hidden && searchable) { if (filterFormatted && format) { targetVal = format(targetVal, product, formatExtraData); } for (let j = 0, textLength = searchTextArray.length; j < textLength; j++) { const filterVal = searchTextArray[j].toLowerCase(); if (targetVal.toString().toLowerCase().indexOf(filterVal) !== -1) { valid = true; break; } } } } } return valid; }); this.setState({ data: data }); } render() { return ( <RemoteSearch onSearchChange={ this.onSearchChange.bind(this) } { ...this.state } /> ); } }
src/svg-icons/action/visibility.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionVisibility = (props) => ( <SvgIcon {...props}> <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/> </SvgIcon> ); ActionVisibility = pure(ActionVisibility); ActionVisibility.displayName = 'ActionVisibility'; ActionVisibility.muiName = 'SvgIcon'; export default ActionVisibility;
packages/material-ui-icons/src/ZoomIn.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let ZoomIn = 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>; ZoomIn = pure(ZoomIn); ZoomIn.muiName = 'SvgIcon'; export default ZoomIn;
app/javascript/mastodon/features/account/components/header.js
honpya/taketodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import IconButton from '../../../components/icon_button'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { autoPlayGif, me } from '../../../initial_state'; import classNames from 'classnames'; const messages = defineMessages({ unfollow: { id: 'account.unfollow', defaultMessage: 'Unfollow' }, follow: { id: 'account.follow', defaultMessage: 'Follow' }, requested: { id: 'account.requested', defaultMessage: 'Awaiting approval. Click to cancel follow request' }, unblock: { id: 'account.unblock', defaultMessage: 'Unblock @{name}' }, }); class Avatar extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, }; state = { isHovered: false, }; handleMouseOver = () => { if (this.state.isHovered) return; this.setState({ isHovered: true }); } handleMouseOut = () => { if (!this.state.isHovered) return; this.setState({ isHovered: false }); } render () { const { account } = this.props; const { isHovered } = this.state; return ( <Motion defaultStyle={{ radius: 90 }} style={{ radius: spring(isHovered ? 30 : 90, { stiffness: 180, damping: 12 }) }}> {({ radius }) => ( <a href={account.get('url')} className='account__header__avatar' role='presentation' target='_blank' rel='noopener' style={{ borderRadius: `${radius}px`, backgroundImage: `url(${autoPlayGif || isHovered ? account.get('avatar') : account.get('avatar_static')})` }} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} onFocus={this.handleMouseOver} onBlur={this.handleMouseOut} > <span style={{ display: 'none' }}>{account.get('acct')}</span> </a> )} </Motion> ); } } @injectIntl export default class Header extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map, onFollow: PropTypes.func.isRequired, onBlock: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { account, intl } = this.props; if (!account) { return null; } let info = ''; let mutingInfo = ''; let actionBtn = ''; let lockedIcon = ''; if (me !== account.get('id') && account.getIn(['relationship', 'followed_by'])) { info = <span className='account--follows-info'><FormattedMessage id='account.follows_you' defaultMessage='Follows you' /></span>; } else if (me !== account.get('id') && account.getIn(['relationship', 'blocking'])) { info = <span className='account--follows-info'><FormattedMessage id='account.blocked' defaultMessage='Blocked' /></span>; } if (me !== account.get('id') && account.getIn(['relationship', 'muting'])) { mutingInfo = <span className='account--muting-info'><FormattedMessage id='account.muted' defaultMessage='Muted' /></span>; } else if (me !== account.get('id') && account.getIn(['relationship', 'domain_blocking'])) { mutingInfo = <span className='account--muting-info'><FormattedMessage id='account.domain_blocked' defaultMessage='Domain hidden' /></span>; } if (me !== account.get('id')) { if (account.getIn(['relationship', 'requested'])) { actionBtn = ( <div className='account--action-button'> <IconButton size={26} active icon='hourglass' title={intl.formatMessage(messages.requested)} onClick={this.props.onFollow} /> </div> ); } else if (!account.getIn(['relationship', 'blocking'])) { actionBtn = ( <div className='account--action-button'> <IconButton size={26} icon={account.getIn(['relationship', 'following']) ? 'user-times' : 'user-plus'} active={account.getIn(['relationship', 'following'])} title={intl.formatMessage(account.getIn(['relationship', 'following']) ? messages.unfollow : messages.follow)} onClick={this.props.onFollow} /> </div> ); } else if (account.getIn(['relationship', 'blocking'])) { actionBtn = ( <div className='account--action-button'> <IconButton size={26} icon='unlock-alt' title={intl.formatMessage(messages.unblock, { name: account.get('username') })} onClick={this.props.onBlock} /> </div> ); } } if (account.get('moved') && !account.getIn(['relationship', 'following'])) { actionBtn = ''; } if (account.get('locked')) { lockedIcon = <i className='fa fa-lock' />; } const content = { __html: account.get('note_emojified') }; const displayNameHtml = { __html: account.get('display_name_html') }; return ( <div className={classNames('account__header', { inactive: !!account.get('moved') })} style={{ backgroundImage: `url(${account.get('header')})` }}> <div> <Avatar account={account} /> <span className='account__header__display-name' dangerouslySetInnerHTML={displayNameHtml} /> <span className='account__header__username'>@{account.get('acct')} {lockedIcon}</span> <div className='account__header__content' dangerouslySetInnerHTML={content} /> {info} {mutingInfo} {actionBtn} </div> </div> ); } }
src/hoc/with-xpath-validation.js
InseeFr/Pogues
/* eslint-disable react/prop-types */ import React from 'react'; import { validateXpath } from '../../jison'; /** * High order component * * @param ComponentToWrap * @returns <div><ComponentToWrap props.meta.warning=validateXPath(input.value) /></div> */ const withXPathValidation = ComponentToWrap => props => { const xPathIsInvalid = validateXpath(props.input.value); let childProps; if (xPathIsInvalid) { const warningsMessage = ( <div> {xPathIsInvalid.split('\n').map(m => ( <div key={m}>{m}</div> ))} </div> ); childProps = { ...props, meta: { ...props.meta, error: warningsMessage } }; } else { childProps = props; } return ( <div> <ComponentToWrap {...childProps} /> </div> ); }; // Don't use hoc directly in render, define them outside export default withXPathValidation;
2017/Cati/React/apresentacao2/projeto1/react-notes/src/components/Board.js
LorhanSohaky/UFSCar
import React from 'react'; import Note from './Note'; const Board=({notes,handleUpdate})=>( <div id="columns"> {notes.map((note,index)=>{ return <Note note={note} id={index} handleUpdate={handleUpdate}/> })} </div> ) export default Board;
app/react-app/src/index.js
spara/atsea-sample-shop-app
import React from 'react' import { render } from 'react-dom' import { createStore, applyMiddleware } from 'redux' import { Provider } from 'react-redux' import { Router, Route, hashHistory } from 'react-router' import { createLogger } from 'redux-logger' import thunkMiddleware from 'redux-thunk' import promiseMiddleware from 'redux-promise-middleware' import reducer from './reducers' import { fetchAllDummyItems, } from './actions' import App from './containers/App' import getMuiTheme from 'material-ui/styles/getMuiTheme' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import CheckoutContainer from './containers/CheckoutContainer' const middleware = [ thunkMiddleware, promiseMiddleware({ promiseTypeSuffixes: ['REQ', 'ACK', 'ERR'], }), ]; if (process.env.NODE_ENV !== 'production') { middleware.push(createLogger()); } const store = createStore( reducer, applyMiddleware(...middleware), ) const muiTheme = getMuiTheme({ textField: { focusColor: '#9fa5a8', }, }) store.dispatch(fetchAllDummyItems()) render( <Provider store={store}> <MuiThemeProvider muiTheme={muiTheme}> <Router history={hashHistory}> <Route path="/" component={App}/> <Route path="checkout" component={CheckoutContainer} /> </Router> </MuiThemeProvider> </Provider>, document.getElementById('root') )
wrappers/yaml.js
alonsogodinez/AlamedaWebPageGatsby
import React from 'react' import yaml from 'js-yaml' import Helmet from 'react-helmet' import { config } from 'config' module.exports = React.createClass({ propTypes () { return { route: React.PropTypes.object, } }, render () { const data = this.props.route.page.data return ( <div> <Helmet title={`${config.siteTitle} | ${data.title}`} /> <h1>{data.title}</h1> <p>Raw view of yaml file</p> <pre dangerouslySetInnerHTML={{ __html: yaml.safeDump(data) }} /> </div> ) }, })
src/interface/report/Results/Timeline/Casts.js
yajinni/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import { Trans } from '@lingui/macro'; import Tooltip from 'interface/Tooltip'; import { formatDuration } from 'common/format'; import Icon from 'interface/Icon'; import SpellLink from 'interface/SpellLink'; import CASTS_THAT_ARENT_CASTS from 'parser/core/CASTS_THAT_ARENT_CASTS'; import { EventType } from 'parser/core/Events'; import './Casts.scss'; const ICON_WIDTH = 22; class Casts extends React.PureComponent { static propTypes = { start: PropTypes.number.isRequired, secondWidth: PropTypes.number.isRequired, parser: PropTypes.shape({ eventHistory: PropTypes.arrayOf(PropTypes.shape({ type: PropTypes.string.isRequired, })).isRequired, toPlayer: PropTypes.func.isRequired, byPlayer: PropTypes.func.isRequired, }).isRequired, }; constructor() { super(); this.renderEvent = this.renderEvent.bind(this); } getOffsetLeft(timestamp) { return (timestamp - this.props.start) / 1000 * this.props.secondWidth; } isApplicableCastEvent(event) { const parser = this.props.parser; if (!parser.byPlayer(event)) { // Ignore pet/boss casts return false; } const spellId = event.ability.guid; if (CASTS_THAT_ARENT_CASTS.includes(spellId)) { return false; } return true; } renderEvent(event) { switch (event.type) { case EventType.Cast: if (this.isApplicableCastEvent(event)) { return this.renderCast(event); } else { return null; } case EventType.BeginChannel: if (this.isApplicableCastEvent(event)) { return this.renderBeginChannel(event); } else { return null; } case EventType.EndChannel: return this.renderChannel(event); case EventType.GlobalCooldown: return this.renderGlobalCooldown(event); default: return null; } } _lastLowered = null; _level = 0; _maxLevel = 0; renderCast(event) { if (event.channel) { // If a spell has a channel event, it has a cast time/is channeled and we already rendered it in the `beginchannel` event return null; } let className = ''; const left = this.getOffsetLeft(event.timestamp); // Hoist abilities off the GCD below the main timeline-bar const lower = !event.globalCooldown; let level = 0; if (lower) { className += ' lower'; // Avoid overlapping icons const margin = left - this._lastLowered; if (this._lastLowered && margin < ICON_WIDTH) { this._level += 1; level = this._level; this._maxLevel = Math.max(this._maxLevel, level); } else { this._level = 0; } this._lastLowered = left; } let castReason; const meta = event.meta; if (meta) { if (meta.isInefficientCast) { className += ' inefficient'; castReason = meta.inefficientCastReason; } else if (meta.isEnhancedCast) { className += ' enhanced'; castReason = meta.enhancedCastReason; } } return this.renderIcon(event, { className, style: { '--level': level > 0 ? level : undefined, }, children: lower ? ( <div className="time-indicator" /> ) : undefined, tooltip: castReason, }); } renderBeginChannel(event) { let className = ''; let castReason; if (event.isCancelled) { className += ' cancelled'; castReason = <Trans id="interface.report.results.timeline.casts.neverFinished">Cast never finished.</Trans>; } // If the beginchannel has a meta prop use that. // If it doesn't, look inside the trigger (which should be a begincast). // If the trigger doesn't have a meta prop, and it's a begincast event, use the cast event's instead. We need to do this since often we can only determine if something was a bad cast on cast finish, e.g. if a player should only cast something while a buff is up on finish. // Using the cast event's meta works here since the timeline is only ever called when parsing has finished, so it doesn't matter that it's not chronological. // This is kind of an ugly hack, but it's the only way to render an icon on the beginchannel event while allowing maintainers to mark the cast events bad. We could have forced everyone to modify meta on the beginchannel/begincast event instead, but that would be inconvenient and unexpected with no real gain. const meta = event.meta || (event.trigger && event.trigger.meta) || (event.trigger && event.trigger.type === EventType.BeginCast && event.trigger.castEvent && event.trigger.castEvent.meta); if (meta) { if (meta.isInefficientCast) { className += ' inefficient'; castReason = meta.inefficientCastReason; } else if (meta.isEnhancedCast) { className += ' enhanced'; castReason = meta.enhancedCastReason; } } return this.renderIcon(event, { className, tooltip: castReason, }); } renderIcon(event, { className = '', style = {}, children, tooltip } = {}) { const left = this.getOffsetLeft(event.timestamp); const linkIcon = children => ( <SpellLink id={event.ability.guid} icon={false} className={`cast ${className}`} style={{ left, ...style, }} > {children} </SpellLink> ); const icon = ( <> <Icon icon={event.ability.abilityIcon.replace('.jpg', '')} alt={event.ability.name} /> {children} </> ); return ( <React.Fragment // It's possible this complains about "encountered two children with the same key". This is probably caused by fabricating a channel event at a cast time. If you can fix it by removing one of the events that would be great, otherwise you may just have to ignore this as while it's showing a warning, deduplicting the icons is correct behavior. key={`cast-${left}-${event.ability.guid}`} > {tooltip ? ( <Tooltip content={tooltip}> <div className={`cast ${className}`} style={{ left, ...style }}> {icon} </div> </Tooltip> ) : linkIcon(icon)} </React.Fragment> ); } renderChannel(event) { const start = this.props.start; const left = this.getOffsetLeft(event.start); const fightDuration = (event.start - start) / 1000; return ( <Tooltip key={`channel-${left}-${event.ability.guid}`} content={( <Trans id="interface.report.results.timeline.casts.tooltip.xSecChannelByAbility"> {formatDuration(fightDuration, 3)}: {(event.duration / 1000).toFixed(2)}s channel by {event.ability.name} </Trans> )} > <div className="channel" style={{ left, width: event.duration / 1000 * this.props.secondWidth, }} /> </Tooltip> ); } renderGlobalCooldown(event) { const start = this.props.start; const left = this.getOffsetLeft(event.timestamp); const fightDuration = (event.timestamp - start) / 1000; return ( <Tooltip key={`gcd-${left}-${event.ability.guid}`} content={( <Trans id="interface.report.results.timeline.casts.tooltip.xSecGCDByAbility"> {formatDuration(fightDuration, 3)}: {(event.duration / 1000).toFixed(2)}s Global Cooldown by {event.ability.name} </Trans> )} > <div className="gcd" style={{ left, width: event.duration / 1000 * this.props.secondWidth, }} /> </Tooltip> ); } render() { const { parser } = this.props; const content = parser.eventHistory.map(this.renderEvent); return ( <div className="casts" style={{ '--levels': this._maxLevel + 1 }}> {content} </div> ); } } export default Casts;
app/jsx/developer_keys/NewKeyTrigger.js
djbender/canvas-lms
/* * Copyright (C) 2018 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import {Flex, View} from '@instructure/ui-layout' import {Menu} from '@instructure/ui-menu' import {Button} from '@instructure/ui-buttons' import {ScreenReaderContent} from '@instructure/ui-a11y' import {IconPlusLine} from '@instructure/ui-icons' import I18n from 'i18n!react_developer_keys' import React from 'react' import PropTypes from 'prop-types' export default class DeveloperKeyModalTrigger extends React.Component { showCreateDeveloperKey = () => { this.props.store.dispatch(this.props.actions.developerKeysModalOpen('api')) } showCreateLtiKey = () => { this.props.store.dispatch(this.props.actions.ltiKeysSetLtiKey(true)) this.props.store.dispatch(this.props.actions.developerKeysModalOpen('lti')) } developerKeyMenuItem(title, onClick) { return ( <Menu.Item onClick={onClick} type="button"> <Flex> <Flex.Item padding="0 x-small 0 0" margin="0 0 xxx-small 0"> <IconPlusLine /> </Flex.Item> <Flex.Item> <ScreenReaderContent>{I18n.t('Create an')}</ScreenReaderContent> {title} </Flex.Item> </Flex> </Menu.Item> ) } triggerButton() { return ( <Button variant="primary" buttonRef={this.props.setAddKeyButtonRef} icon={IconPlusLine}> <ScreenReaderContent>{I18n.t('Create a')}</ScreenReaderContent> {I18n.t('Developer Key')} </Button> ) } developerKeyTrigger() { return ( <Menu placement="bottom" trigger={this.triggerButton()} shouldHideOnSelect> {this.developerKeyMenuItem(I18n.t('API Key'), this.showCreateDeveloperKey)} {this.developerKeyMenuItem(I18n.t('LTI Key'), this.showCreateLtiKey)} </Menu> ) } render() { return ( <View as="div" margin="0 0 small 0" padding="none" textAlign="end"> {this.developerKeyTrigger()} </View> ) } } DeveloperKeyModalTrigger.propTypes = { store: PropTypes.shape({ dispatch: PropTypes.func.isRequired }).isRequired, actions: PropTypes.shape({ developerKeysModalOpen: PropTypes.func.isRequired, ltiKeysSetLtiKey: PropTypes.func.isRequired }).isRequired, setAddKeyButtonRef: PropTypes.func.isRequired }
integration/azure/authentication/ms-identity-v2/implicit-grant/ClientApp/src/containers/WorkflowGenProfileContainer.js
advantys/workflowgen-templates
import React, { Component } from 'react'; import WorkflowGenProfileComponent from '../components/WorkflowGenProfileComponent'; import { GraphQLContext, GQLFactory } from '../models/GraphQL'; class WorkflowGenProfileContainer extends Component { constructor (props) { super(props); this.state = { error: null, user: { userName: null } }; } async componentDidUpdate (prevProps, prevState) { const { state: { user: { userName }, error }, context: graphqlClient } = this; if (graphqlClient && !error && (!userName || userName !== prevState.user.userName)) { try { var data = await graphqlClient.request(GQLFactory.viewerProfile); } catch (error) { this.setState({ error }); return; } this.setState({ user: data.viewer }); } } render () { const { user, error } = this.state; return <WorkflowGenProfileComponent error={error} user={user.userName ? user : undefined} />; } } WorkflowGenProfileContainer.contextType = GraphQLContext; export default WorkflowGenProfileContainer;
stories/menu/index.js
lanyuechen/dh-component
import React from 'react'; import { storiesOf, action, linkTo } from '@kadira/storybook'; import MenuDemo from './menu' import withReadme from 'storybook-readme/with-readme'; const options = { inline: true, propTables: false } storiesOf('Menu 导航', module) .addWithInfo('默认列表', () => ( <div> <MenuDemo /> </div> ), options)
src/js/components/routes/Game.react.js
teamUndefined/creativity
import React from 'react'; import Canvas from './Canvas.react.js'; import Chat from '../partials/Chat.react'; import UserStore from '../../stores/UserStore'; import { Paper, Avatar } from 'material-ui'; var Game = React.createClass({ componentDidMount() { this.props.socket.on('err', function() { window.location = "/"; }); notie.alert(2, 'Welcome to the room!', 3); }, render() { return ( <div className="mdl-grid mb-l"> <div className="mdl-cell mdl-cell--1-col mdl-cell--0-col-phone"></div> <Paper zDepth={1} className="content-container mdl-cell mdl-cell--10-col mdl-cell--12-col-phone"> <div className="mdl-grid"> <div className="mdl-cell mdl-cell--12-col team-container"> <div className="mdl-grid"> <div className="mdl-cell mdl-cell--6-col us-players text-center "> <Avatar src={"https://graph.facebook.com/" + this.props.userDetails.facebook_uid + "/picture"} /> </div> <div className="mdl-cell mdl-cell--6-col them-players text-center "> </div> </div> </div> <div className="mdl-cell mdl-cell--4-col mdl-cell--12-col-phone chat-container"> <Chat socket={this.props.socket} /> </div> <div className="mdl-cell mdl-cell--8-col mdl-cell--12-col-phone canvas-section"> <Canvas socket={this.props.socket} /> </div> </div> </Paper> </div> ); } }); export default Game;
app/demos/CandleStick.js
chunghe/React-Native-Stock-Chart
import React, { Component } from 'react'; import { TouchableOpacity, View, Text, Dimensions, ScrollView, StyleSheet } from 'react-native'; import Svg, { G, Text as SvgText, Rect, Path } from 'react-native-svg'; import * as d3Scale from 'd3-scale'; import T from '../components/T'; const deviceWidth = Dimensions.get('window').width; const barMargin = 1; // 1 on each side const defaultStockChartHeight = 200; const barWidth = 5; class CandleStick extends Component { constructor(props) { super(props); this.state = { data: {}, showGridline: false }; } componentDidMount() { this.getStockQuotes(); } getStockQuotes = () => { const d = new Date(); const today = new Date(`${d.getFullYear()}/${d.getMonth() + 1}/${d.getDate()}`).getTime(); const from = today + 86400 * 1000; const to = from - 86400 * 30 * 1000 * 3; // 3 month ago const url = `http://m.cnyes.com/api/v1/charting/history?symbol=tse:2330&from=${Math.floor(from / 1000)}&to=${Math.floor(to / 1000)}&resolution=D`; fetch(url) .then(rsp => rsp.json()) .then(data => { this.setState({ data, current: 0 }); }); } getLinearScale(domain, range, isTime = false) { return (isTime ? d3Scale.scaleTime() : d3Scale.scaleLinear()).domain(domain).range(range); } getItemByIndex = (i) => { const { c, h, l, o, t, v, s } = this.state.data; return { c: c[i], h: h[i], l: l[i], o: o[i], t: new Date(t[i] * 1000), v: v[i], s, color: o[i] <= c[i] ? 'rgb(210, 72, 62)' : 'rgb(28, 193, 135)' }; } setCurrentItem = (i) => { if (i <= this.state.data.o.length - 1) { this.setState({ current: i }); } } handlePress = (e) => { const { locationX } = e.nativeEvent; // console.log({locationX, locationY}); const current = Math.floor((deviceWidth - locationX) / (barWidth + 2 * barMargin)); this.setCurrentItem(current); } toggleGridline = () => { this.setState({ showGridline: !this.state.showGridline }); } render() { const { current } = this.state; const { c, h, l, o, t, s } = this.state.data; if (s === undefined) { return null; } const highestPrice = Math.max(...h); const lowestPrice = Math.min(...l); const priceScale = this.getLinearScale([lowestPrice, highestPrice], [0, defaultStockChartHeight].reverse()); return ( <ScrollView style={styles.container}> <T heading>CandleStick chart</T> <Text>{`時間: ${new Date(t[current] * 1000)}`}</Text> <View style={{ flexDirection: 'row' }}> <Text style={{ flex: 1 }}>{`收盤: ${c[current]}`}</Text> <Text style={{ flex: 1 }}>{`開盤: ${o[current]}`}</Text> <Text style={{ flex: 1 }}>{`最高: ${h[current]}`}</Text> <Text style={{ flex: 1 }}>{`最低: ${l[current]}`}</Text> </View> <Svg height={defaultStockChartHeight} width={deviceWidth} > <G onPress={this.handlePress}> <Rect x="0" y="0" height={defaultStockChartHeight} width={deviceWidth} fill="#efefef" /> { t.map((_, i) => { const item = this.getItemByIndex(i); const [scaleO, scaleC, yTop, yBottom] = [item.o, item.c, item.h, item.l].map(priceScale); // deviceWidth divided columns each has (barWidth + 2) width // leave 1 as the padding on each side // const x = deviceWidth - i * (barWidth + 2) - barWidth; const x = deviceWidth - barWidth * (i + 1) - barMargin * (2 * i + 1); const barHeight = Math.max(Math.abs(scaleO - scaleC), 1); // if open === close, make sure chartHigh = 1 return ( <G key={i} > <Rect x={x} y={Math.min(scaleO, scaleC)} fill={item.color} height={barHeight} width={barWidth} /> <Path stroke={item.color} d={`M${x + barWidth / 2} ${yTop} ${x + barWidth / 2} ${yBottom}`} strokeWidth="1" /> {current === i && <Path stroke="#666" d={`M${x + barWidth / 2} 0 ${x + barWidth / 2} ${defaultStockChartHeight}`} strokeWidth="0.5" /> } {current === i && <Path stroke="#666" d={`M0 ${scaleC} ${deviceWidth} ${scaleC}`} strokeWidth="0.5" /> } </G> ); }, this) } { this.state.showGridline && priceScale.ticks(10).map((p, i) => { return ( <G key={i}> <SvgText fill="#999" textAnchor="end" x={deviceWidth - 5} y={priceScale(p) - 6} fontSize="10" > {`${p}`} </SvgText> <Path d={`M0 ${priceScale(p)} ${deviceWidth - 25} ${priceScale(p)}`} stroke="#ddd" strokeWidth="1" /> </G> ); }) } </G> </Svg> <View style={{ padding: 15, flexDirection: 'row' }}> <TouchableOpacity style={styles.button} onPress={this.toggleGridline}> <Text>toggle grid line</Text> </TouchableOpacity> </View> </ScrollView> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff' }, button: { borderWidth: 1, borderColor: '#666', borderStyle: 'solid', padding: 10, marginRight: 10 } }); export default CandleStick;
client/modules/User/components/LogInDialog/LoginDialog.js
XuHaoJun/tiamat
import React from 'react'; import PropTypes from 'prop-types'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import Button from '@material-ui/core/Button'; import LogInForm from '../LogInForm'; class LoginDialog extends React.Component { static propTypes = { open: PropTypes.bool, onRequestClose: PropTypes.func, loginFormProps: PropTypes.object, }; static defaultProps = { open: false, loginFormProps: {}, }; setFormRef = form => { if (form) { if (form.getWrappedInstance) { this.form = form.getWrappedInstance(); } else { this.form = form; } } else { this.form = form; } }; handleClose = () => { if (this.props.onRequestClose) { this.props.onRequestClose(); } }; handleLogin = () => { if (this.form) { if (this.form.login) { this.form.login(); } } }; render() { const { open } = this.props; let { loginFormProps } = this.props; loginFormProps = loginFormProps || {}; return ( <Dialog disableBackdropClick open={open} onClose={this.handleClose}> <DialogContent> <div style={{ height: '100%', display: 'flex', justifyContent: 'center', }} > <LogInForm ref={this.setFormRef} {...loginFormProps} /> </div> </DialogContent> <DialogActions> <Button color="primary" onClick={this.handleClose}> 取消 </Button> <Button color="primary" keyboardFocused={true} onClick={this.handleLogin}> 登入 </Button> </DialogActions> </Dialog> ); } } export default LoginDialog;
src/components/Combatant.js
kristyjy/battleplan
import React from 'react'; import { ListGroupItem, Badge, ButtonGroup, Button, Tooltip, Input } from 'reactstrap'; import './Combatant.scss'; import classNames from 'classnames'; class Combatant extends React.Component { constructor(props, context) { super(props, context); this.updateInitiative = this.updateInitiative.bind(this); this.toggleIsKO = this.toggleIsKO.bind(this); this.toggleIsDead = this.toggleIsDead.bind(this); this.toggle = this.toggle.bind(this); this.state = { tooltipOpen: false }; } updateInitiative(e) { if (e && e.target.value !== "") { const updatedCombatant = { ...this.props.combatant, 'initiative': parseInt(e.target.value) }; this.props.actions.updateCombatant(updatedCombatant); this.props.actions.sortCombatants(); } } toggleIsKO() { const updatedCombatant = { ...this.props.combatant, 'isKO': !this.props.combatant.isKO, 'isDead': false }; this.props.actions.updateCombatant(updatedCombatant); this.props.actions.sortCombatants(); } toggleIsDead() { const updatedCombatant = { ...this.props.combatant, 'isKO': false, 'isDead': !this.props.combatant.isDead }; this.props.actions.updateCombatant(updatedCombatant); this.props.actions.sortCombatants(); } toggle() { this.setState({ tooltipOpen: !this.state.tooltipOpen, }); } render() { const {combatant, isCurrentTurn} = this.props; const classes = classNames({ 'combatant': true, 'justify-content-between': true, 'currentTurn': isCurrentTurn, 'combatant-dead': combatant.isDead, 'combatant-ko': combatant.isKO }); const koBtnClasses = classNames({ "ko-toggle": true, "ko-toggle-on": combatant.isKO }); const deadBtnClasses = classNames({ "dead-toggle": true, "dead-toggle-on": combatant.isDead }); return ( <ListGroupItem className={classes}> <Badge pill id={"initiativeBadge"+combatant.id}>{combatant.initiative}</Badge> <Tooltip placement="right" isOpen={this.state.tooltipOpen} autohide={false} target={"initiativeBadge"+combatant.id} toggle={this.toggle}> <Input type="number" name={"initiativeInput"+combatant.id} id={"initiativeInput"+combatant.id} defaultValue={combatant.initiative} onChange={this.updateInitiative}/> </Tooltip> {combatant.name} <ButtonGroup size="sm"> <Button className={koBtnClasses} onClick={() => { this.toggleIsKO(); }}>KO</Button> <Button className={deadBtnClasses} onClick={() => { this.toggleIsDead(); }}>Dead</Button> </ButtonGroup> </ListGroupItem> ); } } Combatant.propTypes = { combatant : React.PropTypes.object.isRequired, isCurrentTurn : React.PropTypes.bool, actions : React.PropTypes.object.isRequired }; export default Combatant;
src/components/AudioDetails/components/AudioDetails.js
altarit/cloudpolis-react
import React from 'react' import PropTypes from 'prop-types' import Draggable from 'react-draggable' import {Link} from 'react-router-dom' import Input from '../../Input' import './AudioDetails.scss' import {requestLyrics, updateLyrics} from "../modules/audioDetails" export class AudioDetails extends React.Component { static propTypes = { isPlaying: PropTypes.bool.isRequired, mobile: PropTypes.bool.isRequired, isInfoEditMode: PropTypes.bool.isRequired, isLirycsEditMode: PropTypes.bool.isRequired, sidebar: PropTypes.bool.isRequired, track: PropTypes.object.isRequired, lyrics: PropTypes.string.isRequired, enableInfoEditMode: PropTypes.func.isRequired, enableLyricsEditMode: PropTypes.func.isRequired, disableEditMode: PropTypes.func.isRequired, toggleAudioDetails: PropTypes.func.isRequired, nextTrack: PropTypes.func.isRequired, prevTrack: PropTypes.func.isRequired, play: PropTypes.func.isRequired, pause: PropTypes.func.isRequired, updateLyrics: PropTypes.func.isRequired, } eventLogger = (e, data) => { console.log('Event: ', e) console.log('Data: ', data) } onStart = () => { //this.setState({activeDrags: ++this.state.activeDrags}); } onStop = () => { //this.setState({activeDrags: --this.state.activeDrags}); } onDrag = () => { //this.setState({activeDrags: --this.state.activeDrags}); } changeFilter = (newValue) => { this.props.getTracksByQuery(newValue) } renderEditMode = () => { return ( <div> <div> Title: <Input onChange={this.changeFilter} delay={300}/> </div> <div> Artist: </div> <div> Album: </div> <div> Compilation: </div> </div> ) } copyTrackLink = () => { } enableEditMode = () => { } disableEditMode = () => { } saveTrackInfo = () => { let text = this.refs.detailsLyrics.value console.log(text) this.props.updateLyrics(this.props.track.id, text) } renderViewMode = (editMode) => { return ( <div className='audio-details-info_main'> <div> {/*<button onClick={this.copyTrackLink}>Copy link</button>*/} {!this.props.isInfoEditMode && !this.props.isLirycsEditMode ? ( <label>{/*<button onClick={this.props.enableInfoEditMode}>Edit Tags</button>*/}</label> ) : ( <button onClick={this.props.disableEditMode}>Cancel</button> )} {!this.props.isInfoEditMode && !this.props.isLirycsEditMode ? ( <button onClick={this.props.enableLyricsEditMode}>Edit Lirycs</button> ) : ( <button onClick={this.saveTrackInfo}>Save</button> )} </div> <div className='audio-details-info_row'> <label className='audio-details-info_label'>Title:</label> <div className='audio-details-info_content'> {this.props.track.title} </div> </div> <div className='audio-details-info_row'> <label className='audio-details-info_label'> Artist: </label> <div className='audio-details-info_content'> {this.props.track.artist} </div> </div> <div className='audio-details-info_row'> <label className='audio-details-info_label'> Album: </label> <div className='audio-details-info_content'> {this.props.track.album} </div> </div> <div className='audio-details-info_row'> <label className='audio-details-info_label'>Location:</label> <div className='audio-details-info_content'> <Link to={`/music/libraries/${this.props.track.library}/${this.props.track.compilation}`}> {this.props.track.compilation ? `/${this.props.track.library}/${this.props.track.compilation}` : null} </Link> </div> </div> </div> ) } render() { return ( <Draggable handle='.handle' defaultPosition={{x: 50, y: -450}} position={null} onStart={this.onStart} onDrag={this.onDrag} onStop={this.onStart}> {!this.props.isDetailsOpen ? ( <div className='audio-details-popup dropdown dropdown-menu show'> <div className='audio-details-header'> <div className='handle audio-details-draggable'>Now playing...</div> <div className='handle audio-details-close' onClick={this.props.toggleAudioDetails}> <i className=' fa fa-fw fa-times'></i> </div> </div> <div className='audio-details-info'> {this.renderViewMode(this.props.isInfoEditMode)} <div className='audio-details-info_cover'></div> </div> <div className='audio-details_lyrics'> <div>Lyrics:</div> <div className='audio-details_lyrics-text'> {this.props.isLirycsEditMode ? ( <textarea defaultValue={this.props.lyrics} ref='detailsLyrics'></textarea> ) : this.props.lyrics !== '<none>' ? ( <pre style={{height: '180px'}}>{this.props.lyrics}</pre> ) : 'Loading'} </div> </div> </div> ) : (<div></div>)} </Draggable> ) } } export default AudioDetails
geonode/monitoring/frontend/src/index.js
mcldev/geonode
import React from 'react'; import { render } from 'react-dom'; import Root from './containers/root'; import injectTapEventPlugin from 'react-tap-event-plugin'; // Needed for onTouchTap // http://stackoverflow.com/a/34015469/988941 injectTapEventPlugin(); const spinner = document.getElementById('spinner'); spinner.style.display = 'none'; render( <Root />, document.getElementById('monitoring') );
demo/component/ComposedChart.js
thoqbk/recharts
import React from 'react'; import { ResponsiveContainer, ComposedChart, Line, Bar, Area, XAxis, YAxis, ReferenceLine, ReferenceDot, Tooltip, Legend, CartesianGrid, Brush } from 'recharts'; const data = [ { name: 'Page A', uv: 590, pv: 800, amt: 1400 }, { name: 'Page B', uv: 868, pv: 967, amt: 1506 }, { name: 'Page C', uv: 1397, pv: 1098, amt: 989 }, { name: 'Page D', uv: 1480, pv: 1200, amt: 1228 }, { name: 'Page E', uv: 1520, pv: 1108, amt: 1100 }, { name: 'Page F', uv: 1400, pv: 680, amt: 1700 }, ]; export default React.createClass({ displayName: 'ComposedChartDemo', render () { return ( <div className="line-charts"> <p>A simple ComposedChart of Line, Bar, Area</p> <div className="composed-chart-wrapper"> <ResponsiveContainer width="100%" height={300}> <ComposedChart width={800} height={400} data={data} margin={{ top: 20, right: 20, bottom: 5, left: 20 }}> <XAxis dataKey="name" /> <YAxis /> <Tooltip /> <Legend layout="vertical" align="right" verticalAlign="middle"/> <CartesianGrid stroke="#f5f5f5" /> <Area type="monotone" dataKey='amt' fill="#8884d8" stroke="#8884d8" /> <Line type="monotone" dataKey="uv" stroke="#ff7300" /> <Bar dataKey="pv" barSize={20} fill="#413ea0" /> <Brush/> </ComposedChart> </ResponsiveContainer> </div> <p>A simple ComposedChart of Line, Bar</p> <div className="composed-chart-wrapper"> <ComposedChart width={800} height={400} data={data} margin={{ top: 20, right: 20, bottom: 20, left: 20 }}> <XAxis dataKey="name"/> <YAxis /> <Tooltip /> <Legend /> <CartesianGrid stroke="#f5f5f5" /> <Bar dataKey="pv" barSize={20} fill="#413ea0" /> <Line type="monotone" dataKey="pv" stroke="#ff7300" /> </ComposedChart> </div> <p>A vertical ComposedChart of Line, Bar</p> <div className="composed-chart-wrapper"> <ComposedChart width={800} height={400} data={data} layout="vertical" margin={{ top: 20, right: 20, bottom: 20, left: 20 }}> <XAxis type="number" /> <YAxis type="category" dataKey="name" /> <Tooltip /> <Legend /> <CartesianGrid stroke="#f5f5f5" /> <Area dataKey="amt" fill="#8884d8" stroke="#8884d8" /> <Bar dataKey="pv" barSize={20} fill="#413ea0" /> <Line dataKey="uv" stroke="#ff7300" /> </ComposedChart> </div> </div> ); } });
src/EdgeShapes.js
dunnock/react-sigma
// @flow import React from 'react' import '../sigma/edges' type Props = { default?: Sigma$Edge$Shapes, sigma?: Sigma }; /** EdgeShapes component, interface for customEdgeShapes sigma plugin. It supposes that sigma graph is already in place, therefore component should not be mounted until graph is available. It can be used within Sigma component if graph is preloaded, or within loader component, like LoadJSON. Note! this Component requires "canvas" renderer to work. To assign a shape renderer to an edge, simply set edge.type='shape-name' e.g. edge.type='dotted'. ``` <Sigma renderer="canvas" graph={{nodes:["id0", "id1"], edges:[{id:"e0",source:"id0",target:"id1"}]}}> <EdgeShapes default="dotted"/> </Sigma> ``` Supported shapes ``` type Sigma$Edge$Shapes = "line" | "arrow" | "curve" | "curvedArrow" | "dashed" | "dotted" | "parallel" | "tapered"; ``` See [plugin page](https://github.com/jacomyal/sigma.js/tree/master/plugins/sigma.renderers.customEdgeShapes) for more datails on implementation. @param {string} default set default sigma edge to be applied to edges where type is not set **/ class EdgeShapes extends React.Component<Props> { constructor(props: Props) { super(props) if(this.props.sigma && this.props.default) this.props.sigma.settings({defaultEdgeType:this.props.default}) } render = () => null } export default EdgeShapes;
app/javascript/mastodon/features/explore/components/story.js
maa123/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Blurhash from 'mastodon/components/blurhash'; import { accountsCountRenderer } from 'mastodon/components/hashtag'; import ShortNumber from 'mastodon/components/short_number'; import Skeleton from 'mastodon/components/skeleton'; import classNames from 'classnames'; export default class Story extends React.PureComponent { static propTypes = { url: PropTypes.string, title: PropTypes.string, publisher: PropTypes.string, sharedTimes: PropTypes.number, thumbnail: PropTypes.string, blurhash: PropTypes.string, }; state = { thumbnailLoaded: false, }; handleImageLoad = () => this.setState({ thumbnailLoaded: true }); render () { const { url, title, publisher, sharedTimes, thumbnail, blurhash } = this.props; const { thumbnailLoaded } = this.state; return ( <a className='story' href={url} target='blank' rel='noopener'> <div className='story__details'> <div className='story__details__publisher'>{publisher ? publisher : <Skeleton width={50} />}</div> <div className='story__details__title'>{title ? title : <Skeleton />}</div> <div className='story__details__shared'>{typeof sharedTimes === 'number' ? <ShortNumber value={sharedTimes} renderer={accountsCountRenderer} /> : <Skeleton width={100} />}</div> </div> <div className='story__thumbnail'> {thumbnail ? ( <React.Fragment> <div className={classNames('story__thumbnail__preview', { 'story__thumbnail__preview--hidden': thumbnailLoaded })}><Blurhash hash={blurhash} /></div> <img src={thumbnail} onLoad={this.handleImageLoad} alt='' role='presentation' /> </React.Fragment> ) : <Skeleton />} </div> </a> ); } }
app/javascript/mastodon/components/avatar.js
masto-donte-com-br/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { autoPlayGif } from '../initial_state'; export default class Avatar extends React.PureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, size: PropTypes.number.isRequired, style: PropTypes.object, inline: PropTypes.bool, animate: PropTypes.bool, }; static defaultProps = { animate: autoPlayGif, size: 20, inline: false, }; state = { hovering: false, }; handleMouseEnter = () => { if (this.props.animate) return; this.setState({ hovering: true }); } handleMouseLeave = () => { if (this.props.animate) return; this.setState({ hovering: false }); } render () { const { account, size, animate, inline } = this.props; const { hovering } = this.state; const src = account.get('avatar'); const staticSrc = account.get('avatar_static'); let className = 'account__avatar'; if (inline) { className = className + ' account__avatar-inline'; } const style = { ...this.props.style, width: `${size}px`, height: `${size}px`, backgroundSize: `${size}px ${size}px`, }; if (hovering || animate) { style.backgroundImage = `url(${src})`; } else { style.backgroundImage = `url(${staticSrc})`; } return ( <div className={className} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} style={style} /> ); } }
test/test_helper.js
LucasCaixeta/ReduxBlog
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
js/components/Header/5.js
LetsBuildSomething/vmag_mobile
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Container, Header, Title, Content, Button, Icon, Left, Right, Body, Text } from 'native-base'; import { Actions } from 'react-native-router-flux'; import { actions } from 'react-native-navigation-redux-helpers'; import { openDrawer } from '../../actions/drawer'; import styles from './styles'; const { popRoute, } = actions; class Header5 extends Component { // eslint-disable-line static propTypes = { openDrawer: React.PropTypes.func, popRoute: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } popRoute() { this.props.popRoute(this.props.navigation.key); } render() { return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={() => Actions.pop()}> <Icon name="arrow-back" /> <Text>Back</Text> </Button> </Left> <Body> <Title>Header</Title> </Body> <Right> <Button transparent onPress={() => Actions.pop()}> <Text>Cancel</Text> </Button> </Right> </Header> <Content padder> <Text> Header With Icon & Text Button </Text> </Content> </Container> ); } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), popRoute: key => dispatch(popRoute(key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(Header5);
node_modules/react-router/es6/RoutingContext.js
tousif101/YouTube-Clone-React
import React from 'react'; import RouterContext from './RouterContext'; import warning from './routerWarning'; var RoutingContext = React.createClass({ displayName: 'RoutingContext', componentWillMount: function componentWillMount() { process.env.NODE_ENV !== 'production' ? warning(false, '`RoutingContext` has been renamed to `RouterContext`. Please use `import { RouterContext } from \'react-router\'`. http://tiny.cc/router-routercontext') : void 0; }, render: function render() { return React.createElement(RouterContext, this.props); } }); export default RoutingContext;
app/components/LoadingIndicator/index.js
joegattnet/joegatt.net-client
import React from 'react'; import Circle from './Circle'; import Wrapper from './Wrapper'; const LoadingIndicator = () => ( <Wrapper> <Circle /> <Circle rotate={30} delay={-1.1} /> <Circle rotate={60} delay={-1} /> <Circle rotate={90} delay={-0.9} /> <Circle rotate={120} delay={-0.8} /> <Circle rotate={150} delay={-0.7} /> <Circle rotate={180} delay={-0.6} /> <Circle rotate={210} delay={-0.5} /> <Circle rotate={240} delay={-0.4} /> <Circle rotate={270} delay={-0.3} /> <Circle rotate={300} delay={-0.2} /> <Circle rotate={330} delay={-0.1} /> </Wrapper> ); export default LoadingIndicator;
src/footer/ReactGridFooter.js
josebalius/react-grid
import React from 'react'; import ReactGridFooterStatus from './ReactGridFooterStatus'; import ReactGridFooterPagination from './ReactGridFooterPagination'; class ReactGridFooter extends React.Component { render() { return ( <div className="row"> <div className="col-md-6"> <ReactGridFooterStatus {...this.props} /> </div> <div className="col-md-6"> <ReactGridFooterPagination {...this.props} /> </div> </div> ) } } module.exports = ReactGridFooter;
src/svg-icons/places/free-breakfast.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesFreeBreakfast = (props) => ( <SvgIcon {...props}> <path d="M20 3H4v10c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.11 0 2-.9 2-2V5c0-1.11-.89-2-2-2zm0 5h-2V5h2v3zM4 19h16v2H4z"/> </SvgIcon> ); PlacesFreeBreakfast = pure(PlacesFreeBreakfast); PlacesFreeBreakfast.displayName = 'PlacesFreeBreakfast'; PlacesFreeBreakfast.muiName = 'SvgIcon'; export default PlacesFreeBreakfast;
js/components/QuestionTypes/CompleteForm.js
ecohealthalliance/GoodQuestion
import React from 'react'; import { Text, View, } from 'react-native'; import Styles from '../../styles/Styles'; import Color from '../../styles/Color'; import Button from 'apsl-react-native-button'; import Icon from 'react-native-vector-icons/FontAwesome'; const CompleteForm = React.createClass({ getInitialState() { return { buttonText: 'Submit', }; }, componentWillMount() { if (this.props.nextForm) { this.setState({ buttonText: 'Submit and continue', }); } }, componentWillReceiveProps(nextProps) { if (nextProps.buttonText) { this.setState({ buttonText: 'Submit and continue', }); } }, submitProxyHandler() { this.setState({ buttonText: 'Saving...', }, () => { this.props.submit(); }); }, render() { return ( <View style={Styles.question.block}> <View style={[Styles.question.header, Styles.question.headerComplete]} > <Icon name='check-circle' size={70} color={Color.primary} style={Styles.question.headerCompleteIcon}/> <View style={Styles.question.headerCompleteView}> <Text style={Styles.question.headerCompleteViewText}> Form Complete </Text> </View> </View> <Button onPress={this.submitProxyHandler} style={[Styles.form.primaryButton, {marginTop: 30}]} textStyle={Styles.form.primaryButtonText}> {this.state.buttonText} </Button> </View> ); }, }); module.exports = CompleteForm;
examples/NavigationPlayground/js/SimpleStack.js
half-shell/react-navigation
/** * @flow */ import React from 'react'; import { Button, ScrollView, } from 'react-native'; import { StackNavigator, } from 'react-navigation'; import SampleText from './SampleText'; const MyNavScreen = ({ navigation, banner }) => ( <ScrollView> <SampleText>{banner}</SampleText> <Button onPress={() => navigation.navigate('Profile', { name: 'Jane' })} title="Go to a profile screen" /> <Button onPress={() => navigation.navigate('Photos', { name: 'Jane' })} title="Go to a photos screen" /> <Button onPress={() => navigation.goBack(null)} title="Go back" /> </ScrollView> ); const MyHomeScreen = ({ navigation }) => ( <MyNavScreen banner="Home Screen" navigation={navigation} /> ); MyHomeScreen.navigationOptions = { title: 'Welcome', }; const MyPhotosScreen = ({ navigation }) => ( <MyNavScreen banner={`${navigation.state.params.name}'s Photos`} navigation={navigation} /> ); MyPhotosScreen.navigationOptions = { title: 'Photos', }; const MyProfileScreen = ({ navigation }) => ( <MyNavScreen banner={ `${navigation.state.params.mode === 'edit' ? 'Now Editing ' : '' }${navigation.state.params.name}'s Profile` } navigation={navigation} /> ); MyProfileScreen.navigationOptions = { header: ({ state, setParams }) => ({ title: `${state.params.name}'s Profile!`, // Render a button on the right side of the header. // When pressed switches the screen to edit mode. right: ( <Button title={state.params.mode === 'edit' ? 'Done' : 'Edit'} onPress={() => setParams({ mode: state.params.mode === 'edit' ? '' : 'edit' })} /> ), }), }; const SimpleStack = StackNavigator({ Home: { screen: MyHomeScreen, }, Profile: { path: 'people/:name', screen: MyProfileScreen, }, Photos: { path: 'photos/:name', screen: MyPhotosScreen, }, }); export default SimpleStack;
example/examples/BugMarkerWontUpdate.js
hzdg/react-native-maps
import React from 'react'; import { StyleSheet, View, Text, Dimensions, TouchableOpacity, } from 'react-native'; import MapView from 'react-native-maps'; import MyLocationMapMarker from './MyLocationMapMarker'; const { width, height } = Dimensions.get('window'); const ASPECT_RATIO = width / height; const LATITUDE = 37.78825; const LONGITUDE = -122.4324; const LATITUDE_DELTA = 0.0922; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; class BugMarkerWontUpdate extends React.Component { constructor(props) { super(props); this.state = { region: { latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }, coordinate: { latitude: LATITUDE, longitude: LONGITUDE, }, amount: 0, enableHack: false, }; } increment() { this.setState({ amount: this.state.amount + 10 }); } decrement() { this.setState({ amount: this.state.amount - 10 }); } toggleHack() { this.setState({ enableHack: !this.state.enableHack }); } render() { return ( <View style={styles.container}> <MapView provider={this.props.provider} style={styles.map} initialRegion={this.state.region} > <MyLocationMapMarker coordinate={this.state.coordinate} heading={this.state.amount} enableHack={this.state.enableHack} /> </MapView> <View style={styles.buttonContainer}> <TouchableOpacity onPress={() => this.toggleHack()} style={[styles.bubble, styles.button, styles.hackButton]} > <Text style={{ fontSize: 12, fontWeight: 'bold' }}> {this.state.enableHack ? 'Disable Hack' : 'Enable Hack'} </Text> </TouchableOpacity> </View> <View style={styles.buttonContainer}> <TouchableOpacity onPress={() => this.decrement()} style={[styles.bubble, styles.button]} > <Text style={{ fontSize: 20, fontWeight: 'bold' }}>-</Text> </TouchableOpacity> <TouchableOpacity onPress={() => this.increment()} style={[styles.bubble, styles.button]} > <Text style={{ fontSize: 20, fontWeight: 'bold' }}>+</Text> </TouchableOpacity> </View> </View> ); } } BugMarkerWontUpdate.propTypes = { provider: MapView.ProviderPropType, }; const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, justifyContent: 'flex-end', alignItems: 'center', }, map: { ...StyleSheet.absoluteFillObject, }, bubble: { backgroundColor: 'rgba(255,255,255,0.7)', paddingHorizontal: 18, paddingVertical: 12, borderRadius: 20, }, latlng: { width: 200, alignItems: 'stretch', }, button: { width: 80, paddingHorizontal: 12, alignItems: 'center', marginHorizontal: 10, }, hackButton: { width: 200, }, buttonContainer: { flexDirection: 'row', marginVertical: 20, backgroundColor: 'transparent', }, }); module.exports = BugMarkerWontUpdate;
packages/ringcentral-widgets-docs/src/app/pages/Components/ActiveCallDialPad/Demo.js
ringcentral/ringcentral-js-widget
import React from 'react'; // eslint-disable-next-line import ActiveCallDialPad from 'ringcentral-widgets/components/ActiveCallDialPad'; const props = {}; props.onChange = () => null; props.hiddenDialPad = () => null; props.onHangup = () => null; props.currentLocale = 'en-US'; /** * A example of `ActiveCallDialPad` */ const ActiveCallDialPadDemo = () => ( <div style={{ position: 'relative', height: '500px', width: '300px', border: '1px solid #f3f3f3', }} > <ActiveCallDialPad {...props} /> </div> ); export default ActiveCallDialPadDemo;
example/src/DeepLink.js
PlexChat/mobx-navigation
import React from 'react'; import { Button, Text, View } from 'react-native'; import { observer } from 'mobx-react' import { scene } from '../..'; import UniqueScene from './Unique'; @scene('SceneOne') class SceneOne extends React.Component { static navConfig = { tabAffinity: '3', navBarVisible: true, }; render() { return ( <View> <Text> One </Text> </View> ); } } @scene('SceneTwo') class SceneTwo extends React.Component { static navConfig = { navBarVisible: true, }; render() { return ( <View> <Text> Two </Text> </View> ); } } @scene('DeepLink') @observer export default class DeepLink extends React.Component { static navConfig = { cardStyle: { backgroundColor: 'red', }, navBarVisible: true, tabBarVisible: true, }; onPress = () => { const navState = this.props.navState; navState.multistep([ () => navState.push('SceneOne'), () => navState.push('SceneTwo'), ]); } onPress2 = () => { this.props.navState.push('UniqueScene', { text: 'From tab 4' }); } render() { return ( <View> <Button title='Deeplink to two' onPress={this.onPress} /> <Button title='Link to unique' onPress={this.onPress2} /> </View> ) } }
src/components/containers/shen-wen-suo-trading-particulars-container.js
HuangXingBin/goldenEast
import React from 'react'; import { Button, AutoComplete ,DatePicker } from 'antd'; import './user-list-container.css'; import UserListTable from '../views/trading-particulars-list'; import { connect } from 'react-redux'; import store from '../../store'; import { updateChuanShangBoardMarketSearch } from '../../actions/app-interaction-actions'; import { getChuanShangBoardMarketData } from '../../api/app-interaction-api'; const RangePicker = DatePicker.RangePicker; var ChuanShangBoardMarketContainer = React.createClass({ getInitialState() { let updateMarketSearch; let name= 2; switch (name) { case 1: updateMarketSearch=updateChuanShangBoardMarketSearch; break; case 2: updateMarketSearch=updateChuanShangBoardMarketSearch; break; default: updateMarketSearch=updateChuanShangBoardMarketSearch; }; return { updateMarketSearch2:updateMarketSearch, } }, componentWillMount(){ const user_sn = this.props.params.userSn; console.log('user_sn', user_sn) this.setState({ user_sn: user_sn }) }, componentDidMount() { const user_sn = this.state.user_sn; getChuanShangBoardMarketData({sn:user_sn}); }, componentWillUnmount(){ //清理搜索条件 store.dispatch(updateChuanShangBoardMarketSearch({ 'search[find]' : '', 'search[d_begin]' : '', 'search[d_end]' : '', 'page' : 1 })); }, submitSearch() { getChuanShangBoardMarketData(this.props.searchState); }, onDateChange(dates, dateStrings) { store.dispatch(this.state.updateMarketSearch2({ 'search[d_begin]' : dateStrings[0], 'search[d_end]' : dateStrings[1], 'page' : 1 })); // 启动搜索 this.submitSearch(); }, onPageChange(page) { store.dispatch(updateChuanShangBoardMarketSearch({ page : page })); // 启动搜索 this.submitSearch(); }, render(){ const { data } = this.props.dataState; console.log('dataSource', data); return ( <div> <div className="data-picker-bar"> <label>交易时间:</label> <RangePicker style={{ width: '200px' }} onChange={this.onDateChange} /> </div> <UserListTable defaultPageSize={12} total={data.total} currentPage={data.this_page} dataSource={data} onPageChange={this.onPageChange} /> </div> ) } }); const mapStateToProps = function (store) { return { dataState : store.chuanShangBoardMarketState.dataState, searchState : store.chuanShangBoardMarketState.searchState } }; export default connect(mapStateToProps)(ChuanShangBoardMarketContainer);
packages/arwes/src/Puffs/sandbox.js
romelperez/prhone-ui
import React from 'react'; import Puffs from './index'; export default () => ( <Puffs> <div style={{ width: '100%', height: 500 }} /> </Puffs> );
frontend/src/Settings/ImportLists/ImportLists/AddImportListModalContentConnector.js
Radarr/Radarr
import _ from 'lodash'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { fetchImportListSchema, selectImportListSchema } from 'Store/Actions/settingsActions'; import AddImportListModalContent from './AddImportListModalContent'; function createMapStateToProps() { return createSelector( (state) => state.settings.importLists, (importLists) => { const { isSchemaFetching, isSchemaPopulated, schemaError, schema } = importLists; const listGroups = _.chain(schema) .sortBy((o) => o.listOrder) .groupBy('listType') .value(); return { isSchemaFetching, isSchemaPopulated, schemaError, listGroups }; } ); } const mapDispatchToProps = { fetchImportListSchema, selectImportListSchema }; class AddImportListModalContentConnector extends Component { // // Lifecycle componentDidMount() { this.props.fetchImportListSchema(); } // // Listeners onImportListSelect = ({ implementation, name }) => { this.props.selectImportListSchema({ implementation, presetName: name }); this.props.onModalClose({ importListSelected: true }); }; // // Render render() { return ( <AddImportListModalContent {...this.props} onImportListSelect={this.onImportListSelect} /> ); } } AddImportListModalContentConnector.propTypes = { fetchImportListSchema: PropTypes.func.isRequired, selectImportListSchema: PropTypes.func.isRequired, onModalClose: PropTypes.func.isRequired }; export default connect(createMapStateToProps, mapDispatchToProps)(AddImportListModalContentConnector);
client/src/components/LoadingSpinner/LoadingSpinner.js
jnns/wagtail
import React from 'react'; import { STRINGS } from '../../config/wagtailConfig'; import Icon from '../../components/Icon/Icon'; /** * A loading indicator with a text label next to it. */ const LoadingSpinner = () => ( <span> <Icon name="spinner" className="c-spinner" /> {` ${STRINGS.LOADING}`} </span> ); export default LoadingSpinner;
framework-examples/react/src/index.js
pgbross/material-components-web
/** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-disable */ import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
src/client/index.js
cyrillegin/Aquaponics
import React from 'react'; import ReactDOM from 'react-dom'; import App from './routes/App'; document.querySelector('.loader').parentElement.removeChild(document.querySelector('.loader')); ReactDOM.render( <App />, document.getElementById('root'), // eslint-disable-line );
src/BoardContainer.js
svangordon/react-chessdiagram
/* MIT License Copyright (c) 2016 Judd Niemann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import React, { Component } from 'react'; import Board from './board.js'; import Piece from './piece.js'; import standardPieceDefinitions from './pieceDefinitions.js'; import Chess from 'chess.js'; /** BoardContainer : handles user input and draws a chess diagram consisting of * a board and pieces, using svg graphics */ class BoardContainer extends Component { constructor(props) { super(props); this.defaultOptions = { validateMoves: true, showLegalMoves: true }; this.options = Object.assign(this.defaultOptions, props.options); this.state = { selectedSquare: null, selectedPieceType: null, dragX: 0, dragY: 0, isDragging: false, left: 0, top: 0, width: 0, height: 0, }; } // Lifecycle events //// componentDidMount() { this._getClientPos(); // add DOM events addEventListener('resize', this._onResize.bind(this)); // resize event not provided by React events; use DOM version addEventListener('scroll', this._onScroll.bind(this)); } componentWillUnmount() { removeEventListener('resize', this._onResize.bind(this)); removeEventListener('scroll', this._onScroll.bind(this)); } componentWillReceiveProps (nextProps) { console.log('receiving props') if ( /* changes which have an effect on coordinates */ nextProps.squareSize !== this.props.squareSize || nextProps.ranks !== this.props.ranks || nextProps.files !== this.props.files ) { let evt = new Event('resize'); dispatchEvent(evt); // synthetically trigger resize event. (Can't get coords in here, because component not rendered yet ...) } } // event handling //// // DOM events _onResize() { this._getClientPos(); } _onScroll() { this._getClientPos(); } // react events _onMouseDown(evt) { // react event evt.preventDefault(); let x = evt.clientX - this.state.left; let y = evt.clientY - this.state.top; this._grab(x,y); } _onTouchStart(evt) { evt.preventDefault(); let x = evt.touches[0].clientX - this.state.left; let y = evt.touches[0].clientY - this.state.top; this._grab(x,y); } _onMouseMove(evt) { evt.preventDefault(); let x = evt.clientX - this.state.left; let y = evt.clientY - this.state.top; this._move(x,y); } _onTouchMove(evt) { evt.preventDefault(); let x = evt.touches[0].clientX - this.state.left; let y = evt.touches[0].clientY - this.state.top; this._move(x,y); } _onMouseUp(evt) { evt.preventDefault(); let x = evt.clientX - this.state.left; let y = evt.clientY - this.state.top; this._release(x,y); } _onTouchEnd(evt) { evt.preventDefault(); /* // Note: android doesn't populate touches array on touchend let x = evt.touches[0].clientX - this.state.left; let y = evt.touches[0].clientY - this.state.top; */ let [x,y] = [this.state.dragX, this.state.dragY]; this._release(x,y); } // coordinate conversion functions //// _squareToCoords(square) { // convert a square name (eg 'e4') to coordinates if(this.props.flip) { let x = this.props.squareSize * (this.props.files - (square.toLowerCase().charCodeAt(0)-97)); let y = (Number(square.slice(1))-1) * this.props.squareSize; return [x,y]; } else { let x = this.props.squareSize * (1 + square.toLowerCase().charCodeAt(0)-97); let y = (this.props.ranks-Number(square.slice(1))) * this.props.squareSize; return [x,y]; } } _fileRankToCoords(file, rank) { // convert zero-based file and rank values to coordinates if(this.props.flip) { let x = this.props.squareSize * (this.props.files - file); let y = this.props.squareSize * rank; return [x,y]; } else { let x = this.props.squareSize * (1 + file); let y = this.props.squareSize * (this.props.ranks - rank -1); return [x,y]; } } _coordsToSquare(x,y) { // convert coordinates to square name (eg e4) if(this.props.flip) { let file = String.fromCharCode(97 + this.props.files - x / this.props.squareSize + 1); let rank = 1 + Math.floor(y / this.props.squareSize); return file + rank; } else { let file = String.fromCharCode(97 + x / this.props.squareSize - 1); let rank = 1 + Math.floor((this.props.ranks * this.props.squareSize - y) / this.props.squareSize); return file + rank; } } // private actions _grab(x,y) { let boardW = this.props.squareSize * (1+this.props.files); let boardH = this.props.squareSize * (this.props.ranks); if(x < this.props.squareSize || x > boardW || y < 0 || y > boardH) { //outside the board ... return false; } let selectedSquare = this._coordsToSquare(x,y); let selectedPiece = this._getPieceAtSquare(selectedSquare); if (!this.state.selectedSquare || this.state.selectedSquare === selectedSquare) { this.setState({ selectedSquare: selectedSquare, selectedPieceType: selectedPiece ? selectedPiece.pieceType : null, dragX: selectedPiece ? selectedPiece.x + this.props.squareSize / 2: this.state.dragX, dragY: selectedPiece ? selectedPiece.y + this.props.squareSize / 2: this.state.dragY, isDragging: true }); } if(this.props.onSelectSquare) { this.props.onSelectSquare(selectedSquare); } } _move(x, y) { if(this.state.isDragging) { this.setState({dragX: x, dragY: y}); } } _release(x,y) { this.setState({isDragging: false}); let finalSquare = this._coordsToSquare(x,y); if(finalSquare !== this.state.selectedSquare) { if(this.props.onMovePiece) { // call the callback fn this.props.onMovePiece(this.state.selectedPieceType, this.state.selectedSquare, finalSquare); } this.setState({selectedSquare: null}); } } // self-enquiry //// _getClientPos() { let rect = this.refs.client.getBoundingClientRect(); this.setState({left: rect.left, top: rect.top, width: rect.width, height: rect.height}); } _getPieces() { if(!this.props.pieces) return []; return this.props.pieces.map((pieceString) => { let [pieceType, square ] = pieceString.split('@',2); // split 'piece@square' into pieceType, square if(!square) return {pieceType: 'invalid', square: 'none', x: 0,y: 0}; // guard against nonsense input let [x,y] = this._squareToCoords(square); if (isNaN(y)) return {pieceType: 'invalid', square: 'none', x: 0,y: 0}; // invalid y-coordinate return {pieceType: pieceType, square: square.toLowerCase(), x: x, y: y}; }); } _getPiecesFromFEN() { let fields = this.props.fen.split(" ", 6); const pieceDefinitions = Object.assign(standardPieceDefinitions, this.props.pieceDefinitions); const pieceChars = new RegExp('[' + Object.keys(pieceDefinitions).join('').replace('-', '\\-') + ']'); const splitFen = fields[0].replace(/(\d+|\w|\/)(?!$)/g, '$1,').split(','); return splitFen .reduce((accum, c) => { if(pieceChars.test(c)) { let [x,y] = this._fileRankToCoords(accum.file, accum.rank); let square = String.fromCharCode(97 + accum.file) + (accum.rank + 1).toString(); accum.pieces.push({pieceType: c, square: square, x: x, y: y}); accum.file++; } else if (c === "/") { accum.rank -= 1; accum.file = 0; } else if(Number.isInteger(parseInt(c))) { accum.file += Number(c); } return accum; }, { rank: this.props.ranks-1, file: 0, pieces: [] }) .pieces; } _getPieceAtSquare(square) { let pieces = this.props.fen ? this._getPiecesFromFEN() : this._getPieces(); return pieces.filter(pieceLocation => pieceLocation.square === square)[0]; } // render function render() { // TODO: Allow user-defined highlight colors let pieces = this.props.fen ? this._getPiecesFromFEN() : this._getPieces(); const pieceDefinitions = Object.assign(standardPieceDefinitions, this.props.pieceDefinitions); const highlights = {}; if (this.state.selectedSquare) { highlights[this.state.selectedSquare] = 'yellow'; } // let highlights = this.state.selectedSquare ? {this.state.selectedSquare: 'yellow'} : {}; if (this.options.showLegalMoves && this.props.allowedMoves[this.state.selectedSquare]) { this.props.allowedMoves[this.state.selectedSquare].forEach(square => { highlights[square] = 'red'; }); } return ( <svg ref={"client"} style={{display: 'inline-block'}} height={this.props.height === "auto" ? (1 + this.props.ranks) * this.props.squareSize : this.props.height} onMouseDown={this._onMouseDown.bind(this)} onMouseMove={this._onMouseMove.bind(this)} onTouchEnd={this._onTouchEnd.bind(this)} onTouchMove={this._onTouchMove.bind(this)} onTouchStart={this._onTouchStart.bind(this)} onMouseUp={this._onMouseUp.bind(this)} width={this.props.width === "auto" ? (1 + this.props.files) * this.props.squareSize : this.props.width} > <Board darkSquareColor={this.props.darkSquareColor} files={this.props.files} flip={!!this.props.flip} highlights={highlights} lightSquareColor={this.props.lightSquareColor} ranks={this.props.ranks} selectedSquare={this.state.selectedSquare} squareSize={this.props.squareSize} /> {pieces.map((piece, i) => <Piece x={this.state.isDragging && piece.square === this.state.selectedSquare ? this.state.dragX - this.props.squareSize / 2 : piece.x} y={this.state.isDragging && piece.square === this.state.selectedSquare ? this.state.dragY - this.props.squareSize / 2 : piece.y} key={i} pieceType={piece.pieceType} squareSize={this.props.squareSize} drawPiece={pieceDefinitions[piece.pieceType]} /> )} </svg> ); } } BoardContainer.propTypes = { /** Dictionary of legal moves, to be supplied by server*/ allowedMoves: React.PropTypes.object, darkSquareColor: React.PropTypes.string, /** Chess position in FEN format (Forsyth-Edwards Notation). eg "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" */ fen: React.PropTypes.string, files: React.PropTypes.number, /** if true, rotates the board so that Black pawns are moving up, and White pawns are moving down the board */ flip: React.PropTypes.bool, /** height of main svg container in pixels. If setting this manually, it should be at least 9 * squareSize to fit board AND labels*/ height: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, ]), lightSquareColor: React.PropTypes.string, /** callback function which is called when user moves a piece. Passes pieceType, initialSquare, finalSquare as parameters to callback */ onMovePiece: React.PropTypes.func, /** callback function which is called when user clicks on a square. Passes name of square as parameter to callback */ onSelectSquare: React.PropTypes.func, /** array of pieces at particular squares (alternative to fen) eg ['P@f2','P@g2','P@h2','K@g1']. * This format may be more suitable for unconventional board dimensions, for which standard FEN would not work. * Note: If both FEN and pieces props are present, FEN will take precedence */ pieces: React.PropTypes.array, /** Optional associative array containing non-standard chess characters*/ pieceDefinitions: React.PropTypes.object, ranks: React.PropTypes.number, squareSize: React.PropTypes.number, /** width of main svg container in pixels. If setting this manually, it should be at least 9 * squareSize to fit board AND labels*/ width: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, ]), }; BoardContainer.defaultProps = { allowedMoves: {}, darkSquareColor: "#005EBB", height: 'auto', files: 8, flip: false, lightSquareColor: "#2492FF", pieceDefinitions: {}, ranks: 8, squareSize: 45, width: 'auto', }; export default BoardContainer;
packages/components/src/VirtualizedList/CellTitle/CellTitleInput.component.js
Talend/ui
import PropTypes from 'prop-types'; import React from 'react'; import keycode from 'keycode'; import theme from './CellTitle.scss'; /** * Title input mode. * - It initializes the input value * - It adds handlers on form submit, ESC (cancel) and blur (submit) events */ export default class CellTitleInput extends React.Component { constructor(props) { super(props); this.onBlur = this.onBlur.bind(this); this.onKeyUp = this.onKeyUp.bind(this); this.onSubmit = this.onSubmit.bind(this); } componentDidMount() { this.titleInput.value = this.props.cellData; } onKeyUp(event) { if (event.keyCode === keycode('escape')) { this.props.onEditCancel(event, this.props.rowData); } } onBlur(event) { this.onSubmit(event); } onSubmit(event) { event.preventDefault(); this.props.onEditSubmit(event, { value: this.titleInput.value, model: this.props.rowData, }); } render() { return ( <form onSubmit={this.onSubmit} className={theme['edit-form']}> <label aria-hidden="true" hidden className="sr-only" htmlFor={this.props.id}> {this.props.label || 'title'} </label> <input id={this.props.id} ref={input => { this.titleInput = input; }} onBlur={this.onBlur} onKeyUp={this.onKeyUp} autoFocus /> </form> ); } } CellTitleInput.propTypes = { /** The id prefix. */ id: PropTypes.string, /** The input value. */ cellData: PropTypes.string.isRequired, /** The cancel callback on ESC keydown. */ onEditCancel: PropTypes.func.isRequired, /** The submit callback on ENTER keydown or blur. */ onEditSubmit: PropTypes.func.isRequired, /** The collection item. */ rowData: PropTypes.object, // eslint-disable-line react/forbid-prop-types /** The input label. */ label: PropTypes.string, };
ui/js/components/Text.js
ericsoderberg/pbc-web
import React from 'react'; import PropTypes from 'prop-types'; import Markdown from 'markdown-to-jsx'; const Text = (props) => { const { backgroundColor, className, text } = props; const classes = ['text']; if (className) { classes.push(className); } const textContent = text || props.children || ''; // strip out inline HTML let contents = <Markdown>{textContent.replace(/(<([^>]+)>)/ig, '')}</Markdown>; if (backgroundColor) { contents = ( <div className="text-contents" style={{ backgroundColor }}> {contents} </div> ); } return ( <div className={classes.join(' ')}> {contents} </div> ); }; Text.propTypes = { backgroundColor: PropTypes.string, children: PropTypes.any, className: PropTypes.string, text: PropTypes.string, }; Text.defaultProps = { backgroundColor: undefined, children: undefined, className: undefined, text: undefined, }; export default Text;
index.android.js
ravicpn/ReactNativeAppStoreClient
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ 'use strict'; import React, { Component } from 'react'; import { AppRegistry, View, } from 'react-native'; import AppStore from './components/views/AppStore' class ReactNativeAppStoreClient extends Component { render() { return ( <AppStore/> ); } } AppRegistry.registerComponent('ReactNativeAppStoreClient', () => ReactNativeAppStoreClient);
src/components/PayoutAddress/PayoutAddress.js
deluxe-pig/cloud-farmer
// PayoutAddress.js import React, { Component } from 'react'; import styles from './PayoutAddress.css'; import { Link } from 'react-router'; export default class PayoutAddress extends Component { render() { return ( <div> <div className={styles.payoutContainer}> <h1> Payout Address: </h1> <p className={styles.payoutAddress}> HqjXkj7X9oiQUxroqjkO19KXqjklx </p> <button className={styles.changePayoutAddress}> Change Payout Address </button> </div> </div> ); } }
demo/components/datepicker/DatePickerDemo.js
ctco/rosemary-ui
import React from 'react'; import {DatePicker, Button, MonthPicker, Input, IconInput} from '../../../src'; import DemoWithSnippet from '../../layout/DemoWithSnippet'; export default class DatePickerDemo extends React.Component { constructor(props) { super(props); this.state = { controlledValue: '01.01.2015', hi: '22.03.2015', datePickerWithChild: '22.03.2015' }; } render() { return ( <div> <DemoWithSnippet> <div> <span className="date-picker-demo__simple-example-text"> The selected date is:</span> <DatePicker className="btn--inline"> <Button className="btn-link btn--inline"/> </DatePicker> </div> </DemoWithSnippet> <br/> <br/> <h2>Date picker can be controlled</h2> <Input type="text" value={this.state.controlledValue} onChange={(value) => this.setState({controlledValue: value})}/> <DemoWithSnippet> <DatePicker value={this.state.controlledValue} format="DD.MM.YYYY" onChange={(value) => this.setState({controlledValue: value})}> <Button className="btn-link"/> </DatePicker> </DemoWithSnippet> <br/> <br/> <h2>Date Picker with Input</h2> <DatePicker value={this.state.hi} format="DD.MM.YYYY" onChange={(value) => this.setState({ hi: value })} > <Input type="text" /> </DatePicker> <br/> <br/> <h2>Date Picker with Input And Icoon</h2> <DatePicker value={this.state.datePickerWithChild} format="DD.MM.YYYY" onChange={(value) => this.setState({ datePickerWithChild: value })} > <IconInput iconClassName="im icon-calendar icon--xs" position="right" readOnly/> </DatePicker> <br/> <br/> <h2>Dates can be limited</h2> <DemoWithSnippet> <DatePicker format="DD.MM.YYYY" minDate="01.10.2015" maxDate="31.03.2017"> <Button className="btn-link"/> </DatePicker> </DemoWithSnippet> <h2>Month picker:</h2> <MonthPicker> <Button className="btn-link"/> </MonthPicker> <br/> <br/> <MonthPicker> <IconInput iconClassName="im icon-calendar-from" position="right" readOnly/> </MonthPicker> </div> ); } }
public/systemjs/app/pages/component/generic.js
snowkeeper/keystonejs-site
import React from 'react'; /** * A generic container * expects a html prop * */ class Generic extends React.Component { constructor(props) { super(props) this.displayName = 'Generic ' this.state = { html: props.html || props.response } this.props = props }, componentWillReceiveProps(props) { this.setState(props) }, render() { return !this.state.html ? <span /> : <div dangerouslySetInnerHTML={{ __html: this.state.html }} /> } } return Generic
packages/arwes/src/Heading/Heading.js
romelperez/ui
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; export default function Heading(props) { const { theme, classes, node, className, children, ...etc } = props; const cls = cx(classes.root, className); return React.createElement(node, { className: cls, ...etc }, children); } Heading.propTypes = { theme: PropTypes.any.isRequired, classes: PropTypes.any.isRequired, /** * The heading node e.g. h1, h2... */ node: PropTypes.oneOf(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) }; Heading.defaultProps = { node: 'h1' };
client/my-sites/invites/controller.js
mmmavis/mofo-calypso
/** * External Dependencies */ import ReactDom from 'react-dom'; import React from 'react'; import store from 'store'; import page from 'page'; /** * Internal Dependencies */ import i18n from 'lib/mixins/i18n'; import titleActions from 'lib/screen-title/actions'; import InviteAccept from 'my-sites/invites/invite-accept'; import { setSection } from 'state/ui/actions'; import { renderWithReduxStore } from 'lib/react-helpers'; import { acceptedNotice, getRedirectAfterAccept } from 'my-sites/invites/utils'; import { successNotice } from 'state/notices/actions'; export function acceptInvite( context ) { titleActions.setTitle( i18n.translate( 'Accept Invite', { textOnly: true } ) ); ReactDom.unmountComponentAtNode( document.getElementById( 'secondary' ) ); context.store.dispatch( setSection( null, { hasSidebar: false } ) ); renderWithReduxStore( React.createElement( InviteAccept, { siteId: context.params.site_id, inviteKey: context.params.invitation_key, activationKey: context.params.activation_key, authKey: context.params.auth_key } ), document.getElementById( 'primary' ), context.store ); } export function inviteNotices( context, next ) { const acceptedInvite = store.get( 'invite_accepted' ); if ( acceptedInvite ) { store.remove( 'invite_accepted' ); context.store.dispatch( successNotice( ... acceptedNotice( acceptedInvite ) ) ); page( getRedirectAfterAccept( acceptedInvite ) ); } else { next(); } }
src/components/SelectionPills/SelectionPill/SelectionPill.js
instacart/Snacks
import React from 'react' import Radium from '@instacart/radium' import PropTypes from 'prop-types' import { themePropTypes } from '../../../styles/themer/utils' import withTheme from '../../../styles/themer/withTheme' import { getStyles } from './styles' const NoOp = () => {} // eslint-disable-line no-empty-function // As of HTML5, id must consist of at least one character and no spaces const textToID = text => { return `selection_pill_${text.split(' ').join('_')}` } class SelectionPill extends React.PureComponent { static propTypes = { /** Unique identifier for the pill. Default to text input if not provided. */ id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** Any additional props to add to the list element (e.g. data attributes). */ listElementAttributes: PropTypes.object, /** Any additional props to add to the checkbox element (e.g. data attributes). */ elementAttributes: PropTypes.object, /** Flag determining if component selected state is controlled by parent through props or internal state */ parentControlledState: PropTypes.bool, /** Determines wether or not selected styles are applied and start is a selected state */ isSelected: PropTypes.bool, /** Determines Whether or not the pill is disabled. */ isDisabled: PropTypes.bool, /** Callback function called after pill click * @param {SyntheticEvent} event The react `SyntheticEvent` * @param {props} object All the props passed to the component */ onClick: PropTypes.func, /** Callback function called after pill gained focus * @param {SyntheticEvent} event The react `SyntheticEvent` * @param {props} object All the props passed to the component */ onFocus: PropTypes.func, /** Callback function called after pill has lost focus * @param {SyntheticEvent} event The react `SyntheticEvent` * @param {props} object All the props passed to the component */ onBlur: PropTypes.func, /** Snacks theme attributes provided by Themer */ snacksTheme: themePropTypes, /** Required text to appear inside pill */ text: PropTypes.string.isRequired, /** Optional style overrides for button and its states */ style: PropTypes.shape({ button: PropTypes.object, disabledStyle: PropTypes.object, selectedStyle: PropTypes.object, focusedStyle: PropTypes.object, }), /** Aria overrides for accessibility (i.e. use if label is not descriptive enough for screen readers) */ aria: PropTypes.shape({ label: PropTypes.string, }), } static defaultProps = { elementAttributes: {}, isSelected: false, parentControlledState: false, onClick: NoOp, onFocus: NoOp, onBlur: NoOp, style: {}, aria: {}, } state = { isSelected: this.props.isSelected, isFocused: false, } handleChange = event => { const { onClick } = this.props const { isSelected } = this.state this.setState({ isSelected: !isSelected }) onClick(event, { ...this.props, isSelected: !isSelected }) } toggleFocus = () => { const { isFocused } = this.state this.setState({ isFocused: !isFocused }) } handleFocus = event => { this.toggleFocus() this.props.onFocus(event, { ...this.props, isFocused: !this.state.isFocused }) } handleBlur = event => { this.toggleFocus() this.props.onBlur(event, { ...this.props, isFocused: !this.state.isFocused }) } renderInputBtn({ selected, inputId }) { const { aria, isDisabled } = this.props const componentStyles = getStyles() return ( <div style={componentStyles.checkBoxOverrideStyle}> <input id={inputId} type="checkbox" onChange={this.handleChange} checked={selected} disabled={isDisabled} aria-label={aria.label} onBlur={this.handleBlur} onFocus={this.handleFocus} /> </div> ) } render() { const { id, snacksTheme, text, style, isDisabled, parentControlledState } = this.props const { isFocused } = this.state const { primaryForeground } = snacksTheme.colors const inputId = id || textToID(text) const selected = parentControlledState ? this.props.isSelected : this.state.isSelected const componentStyles = getStyles({ isSelected: selected, isFocused, isDisabled, primaryForeground, externalStyles: style, }) return ( <li style={componentStyles.listElement} {...this.props.listElementAttributes}> {this.renderInputBtn({ selected, inputId })} <label htmlFor={inputId} style={componentStyles.labelButton}> {text} </label> </li> ) } } export default withTheme(Radium(SelectionPill))
src/svg-icons/maps/directions-railway.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsDirectionsRailway = (props) => ( <SvgIcon {...props}> <path d="M4 15.5C4 17.43 5.57 19 7.5 19L6 20.5v.5h12v-.5L16.5 19c1.93 0 3.5-1.57 3.5-3.5V5c0-3.5-3.58-4-8-4s-8 .5-8 4v10.5zm8 1.5c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm6-7H6V5h12v5z"/> </SvgIcon> ); MapsDirectionsRailway = pure(MapsDirectionsRailway); MapsDirectionsRailway.displayName = 'MapsDirectionsRailway'; export default MapsDirectionsRailway;
packages/wix-style-react/src/CalendarPanel/test/CalendarPanel.visual.js
wix/wix-style-react
import React from 'react'; import { storiesOf } from '@storybook/react'; import CalendarPanel from '../CalendarPanel'; const tests = [ { describe: 'CalendarPanel', its: [ { it: 'no presets', props: { presets: [], value: new Date(1990, 3, 29), footer: false, }, }, { it: 'with presets', props: { presets: [ { id: 1, value: 'a day', selectedDays: new Date(2018, 1, 1) }, { id: 2, value: 'a range', selectedDays: { from: new Date(2018, 1, 1), to: new Date(2018, 2, 1), }, }, ], value: new Date(1990, 3, 29), footer: false, }, }, ], }, ]; tests.forEach(({ describe, its }) => { its.forEach(({ it, props }) => { storiesOf(`CalendarPanel${describe ? '/' + describe : ''}`, module).add( it, () => <CalendarPanel {...props} />, ); }); });
generators/app/templates/src/core/container/RetrieveExample.js
fobbyal/generator-scalable-react-redux
import React from 'react' import { connect } from 'react-redux' import { Button, Container } from 'semantic-ui-react' import R from 'ramda' import { retrieveDummyData } from '../actions' import { getDummyData } from '../selectors' import { fromNullable, Just, Nothing } from 'data.maybe' import styled from 'styled-components' const Msg = styled.p` font-size: 1.4em font-weight: bold; color: #555; ` const RetrieveExample = ({ data, retrieveDummyData }) => ( <Container > <h2 className="ui huge header"> Retrieve data using redux + fetch </h2> <Msg>This page demostarts how to retrieve and display data from a json restful webservcie api</Msg> <div> <Button onClick={() => retrieveDummyData()} primary > Click to Retrieve from server </Button> </div> { fromNullable(data) .chain(d => R.isEmpty(d) ? Nothing() : Just(d)) .map(d => ( <pre><code> {JSON.stringify(data)} </code></pre> )).getOrElse(<div>Data not yet retrieved </div>) } </Container> ) const mapStateToProps = state => ({ data: getDummyData(state) }) const mapDispatchToProps = ({ retrieveDummyData }) export default connect(mapStateToProps, mapDispatchToProps)(RetrieveExample)
examples/src/components/CustomComponents.js
serkanozer/react-select
import React from 'react'; import createClass from 'create-react-class'; import PropTypes from 'prop-types'; import Select from 'react-select'; import Gravatar from 'react-gravatar'; const USERS = require('../data/users'); const GRAVATAR_SIZE = 15; const GravatarOption = createClass({ propTypes: { children: PropTypes.node, className: PropTypes.string, isDisabled: PropTypes.bool, isFocused: PropTypes.bool, isSelected: PropTypes.bool, onFocus: PropTypes.func, onSelect: PropTypes.func, option: PropTypes.object.isRequired, }, handleMouseDown (event) { event.preventDefault(); event.stopPropagation(); this.props.onSelect(this.props.option, event); }, handleMouseEnter (event) { this.props.onFocus(this.props.option, event); }, handleMouseMove (event) { if (this.props.isFocused) return; this.props.onFocus(this.props.option, event); }, render () { let gravatarStyle = { borderRadius: 3, display: 'inline-block', marginRight: 10, position: 'relative', top: -2, verticalAlign: 'middle', }; return ( <div className={this.props.className} onMouseDown={this.handleMouseDown} onMouseEnter={this.handleMouseEnter} onMouseMove={this.handleMouseMove} title={this.props.option.title}> <Gravatar email={this.props.option.email} size={GRAVATAR_SIZE} style={gravatarStyle} /> {this.props.children} </div> ); } }); const GravatarValue = createClass({ propTypes: { children: PropTypes.node, placeholder: PropTypes.string, value: PropTypes.object }, render () { var gravatarStyle = { borderRadius: 3, display: 'inline-block', marginRight: 10, position: 'relative', top: -2, verticalAlign: 'middle', }; return ( <div className="Select-value" title={this.props.value.title}> <span className="Select-value-label"> <Gravatar email={this.props.value.email} size={GRAVATAR_SIZE} style={gravatarStyle} /> {this.props.children} </span> </div> ); } }); const UsersField = createClass({ propTypes: { hint: PropTypes.string, label: PropTypes.string, }, getInitialState () { return {}; }, setValue (value) { this.setState({ value }); }, render () { var placeholder = <span>&#9786; Select User</span>; return ( <div className="section"> <h3 className="section-heading">{this.props.label} <a href="https://github.com/JedWatson/react-select/tree/master/examples/src/components/CustomComponents.js">(Source)</a></h3> <Select arrowRenderer={arrowRenderer} onChange={this.setValue} optionComponent={GravatarOption} options={USERS} placeholder={placeholder} value={this.state.value} valueComponent={GravatarValue} /> <div className="hint"> This example implements custom Option and Value components to render a Gravatar image for each user based on their email. It also demonstrates rendering HTML elements as the placeholder. </div> </div> ); } }); function arrowRenderer () { return ( <span>+</span> ); } module.exports = UsersField;