path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/components/icons/ErrorIcon.js
maximgatilin/weathernow
import React from 'react'; export default function ErrorIcon() { return ( <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="currentColor"> <path d="M24.406 22.747c0.091-0.147 0.099-0.331 0.022-0.485l-7.982-15.963c-0.17-0.338-0.723-0.338-0.893 0l-7.982 15.963c-0.077 0.155-0.069 0.338 0.022 0.485s0.251 0.236 0.425 0.236h15.963c0.173 0 0.333-0.090 0.425-0.236zM16 20.49c-0.275 0-0.499-0.224-0.499-0.499s0.223-0.499 0.499-0.499 0.499 0.224 0.499 0.499-0.224 0.499-0.499 0.499zM16.499 17.995c0 0.275-0.223 0.499-0.499 0.499s-0.499-0.224-0.499-0.499v-5.487c0-0.275 0.223-0.499 0.499-0.499s0.499 0.223 0.499 0.499v5.487z"></path> <path d="M16 1.533c-8.252 0-14.966 6.714-14.966 14.966 0 4.588 2.114 8.782 5.809 11.588l-0.737 1.105c-0.096 0.144-0.111 0.327-0.038 0.484s0.22 0.266 0.392 0.287l3.991 0.499c0.021 0.003 0.041 0.004 0.062 0.004 0.166 0 0.322-0.082 0.415-0.222 0.105-0.157 0.112-0.36 0.018-0.524l-1.995-3.492c-0.086-0.15-0.243-0.245-0.416-0.251-0.171-0.012-0.337 0.078-0.432 0.222l-0.704 1.057c-3.414-2.616-5.366-6.506-5.366-10.757 0-7.702 6.266-13.968 13.968-13.968s13.968 6.266 13.968 13.968c0 5.463-3.214 10.456-8.188 12.72-0.251 0.114-0.362 0.41-0.247 0.66 0.084 0.184 0.265 0.292 0.454 0.292 0.069 0 0.139-0.014 0.206-0.045 5.33-2.425 8.773-7.775 8.773-13.628 0-8.252-6.714-14.966-14.966-14.966z"></path> </svg> ) }
modules/IndexRoute.js
jamiehill/react-router
import React from 'react' import invariant from 'invariant' import warning from 'warning' import { createRouteFromReactElement } from './RouteUtils' import { component, components, falsy } from './PropTypes' const { bool, func } = React.PropTypes /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ const IndexRoute = React.createClass({ statics: { createRouteFromReactElement(element, parentRoute) { if (parentRoute) { parentRoute.indexRoute = createRouteFromReactElement(element) } else { warning( false, 'An <IndexRoute> does not make sense at the root of your route config' ) } } }, propTypes: { path: falsy, ignoreScrollBehavior: bool, component, components, getComponents: func }, render() { invariant( false, '<IndexRoute> elements are for router configuration only and should not be rendered' ) } }) export default IndexRoute
src/components/TutReqList/ListItem.js
MattMcFarland/tw-client
import React from 'react'; import moment from 'moment'; export const ListItem = ( props ) => ( <section className="tut-request-item"> <table className="listitem-table"> <tbody> <tr> <td className="listitem-vote"> <div className="listitem-vote-inner"> <div className="vote"> <button data-tipsy={props.userVote === 1 ? 'Remove vote' : 'Vote up' } className="tipsy tipsy--n up" data-id={props.id} disabled={props.lockVote} onClick={props.onVoteUp}> <span className={props.userVote === 1 ? "icon ion-chevron-up active" : "icon ion-chevron-up"} /> </button> <span className="score">{props.score}</span> <button data-tipsy={props.userVote === -1 ? 'Remove vote' : 'Vote down' } className="tipsy tipsy--s down" data-id={props.id} disabled={props.lockVote} onClick={props.onVoteDown}> <span className={props.userVote === -1 ? "icon ion-chevron-down active" : "icon ion-chevron-down"} /> </button> </div> </div> </td> <td className="listitem-content"> <div className="listitem-content-inner"> <p style={{margin: '0', paddingTop: '4px', lineHeight:'1'}}><a href={"/tutorial-request/" + props.permalink}>{props.title}</a></p> <a style={{fontSize: '12px', color: '#999'}} href={"/tutorial-request/" + props.permalink}> <span>{props.comments.length} Comments</span> <span> & </span> <span style={{fontSize: '12px', color: '#999'}}>{props.solutions.length} Tutorials</span> </a> <ul className="tags"> {props.tags.map((tag, index) => <li key={index} className={tag.is_pending ? "pending tag" : "approved tag"} title={tag.is_pending ? "This tag is pending approval by moderators and may be removed" : "Tutorial request tagged with" + tag.name} >{tag.name}</li> )} </ul> </div> </td> <td className="listitem-meta"> <div className="listitem-meta-inner"> <div className="user"> <div className="body"> <div className="meta"> {props.authorAvatar ? <div className="avatar-container"><img className="avatar" src={props.authorAvatar} alt="Avatar" /></div> : ''} <div className="user-name"><a href={props.authorUrl}>{props.authorName}</a></div> <div className="timestamp"><span style={{fontSize: '12px', color: '#999'}}><a href={"/tutorial-request/" + props.permalink}>{moment(props.created_at).fromNow()}</a></span></div> </div> </div> </div> </div> </td> </tr> </tbody> </table> <div className="divider"/> </section> );
definitions/npm/styled-components_v2.x.x/flow_v0.42.x-v0.52.x/test_styled-components_v2.x.x.js
mkscrg/flow-typed
// @flow import {renderToString} from 'react-dom/server' import styled, { ThemeProvider, withTheme, keyframes, ServerStyleSheet, StyleSheetManager } from 'styled-components' import React from 'react' import type { Theme, Interpolation, // Temporary ReactComponentFunctional, ReactComponentClass, ReactComponentStyled, ReactComponentStyledTaggedTemplateLiteral, ReactComponentUnion, ReactComponentIntersection, } from 'styled-components' const TitleTaggedTemplateLiteral: ReactComponentStyledTaggedTemplateLiteral<{}> = styled.h1; const TitleStyled: ReactComponentStyled<*> = styled.h1` font-size: 1.5em; `; const TitleGeneric: ReactComponentIntersection<*> = styled.h1` font-size: 1.5em; `; const TitleFunctional: ReactComponentFunctional<*> = styled.h1` font-size: 1.5em; `; const TitleClass: ReactComponentClass<*> = styled.h1` font-size: 1.5em; `; declare var needsReactComponentFunctional: ReactComponentFunctional<*> => void declare var needsReactComponentClass: ReactComponentClass<*> => void needsReactComponentFunctional(TitleStyled) needsReactComponentClass(TitleStyled) const ExtendedTitle: ReactComponentIntersection<*> = styled(TitleStyled)` font-size: 2em; `; const Wrapper: ReactComponentIntersection<*> = styled.section` padding: 4em; background: ${({theme}) => theme.background}; `; // ---- EXTEND ---- const Attrs0ReactComponent: ReactComponentStyled<*> = styled.div.extend``; const Attrs0ExtendReactComponent: ReactComponentIntersection<*> = Attrs0ReactComponent.extend``; const Attrs0SyledComponent: ReactComponentStyledTaggedTemplateLiteral<*> = styled.div; const Attrs0ExtendStyledComponent: ReactComponentIntersection<*> = Attrs0SyledComponent.extend``; // ---- ATTRIBUTES ---- const Attrs1: ReactComponentStyledTaggedTemplateLiteral<*> = styled.section.attrs({ testProp: 'foo' }); // $ExpectError const Attrs1Error: ReactComponentStyledTaggedTemplateLiteral<*> = styled.section.attrs({ testProp: 'foo' })``; declare var needsString: string => void needsReactComponentFunctional(styled.section.attrs({})``) needsReactComponentClass(styled.section.attrs({})``) // $ExpectError needsString(styled.section.attrs({})``) const Attrs2: ReactComponentStyledTaggedTemplateLiteral<*> = styled.section .attrs({ testProp1: 'foo' }) .attrs({ testProp2: 'bar' }); const Attrs3Styled: ReactComponentStyled<*> = styled.section.attrs({ testProp: 'foo' })` background-color: red; `; const Attrs3Generic: ReactComponentIntersection<*> = styled.section.attrs({ testProp: 'foo' })` background-color: red; `; const Attrs3Functional: ReactComponentFunctional<*> = styled.section.attrs({ testProp: 'foo' })` background-color: red; `; const Attrs3Class: ReactComponentClass<*> = styled.section.attrs({ testProp: 'foo' })` background-color: red; `; const theme: Theme = { background: "papayawhip" }; // ---- WithComponent ---- const withComponent1: ReactComponentStyled<*> = styled.div.withComponent('a'); const withComponent2: ReactComponentStyled<*> = styled.div.withComponent(withComponent1); const withComponent3: ReactComponentStyled<*> = styled.div.withComponent(Attrs3Class); // $ExpectError const withComponentError1: ReactComponentStyled<*> = styled.div.withComponent(0); // $ExpectError const withComponentError2: ReactComponentStyled<*> = styled.div.withComponent('NotHere'); // ---- WithTheme ---- const Component: ReactComponentFunctional<{ theme: Theme }> = ({ theme }) => ( <ThemeProvider theme={theme}> <Wrapper> <TitleStyled>Hello World, this is my first styled component!</TitleStyled> </Wrapper> </ThemeProvider> ); const ComponentWithTheme: ReactComponentFunctional<{}> = withTheme(Component); const Component2: ReactComponentFunctional<{}> = () => ( <ThemeProvider theme={outerTheme => outerTheme}> <Wrapper> <TitleStyled>Hello World, this is my first styled component!</TitleStyled> </Wrapper> </ThemeProvider> ); const OpacityKeyFrame: string = keyframes` 0% { opacity: 0; } 100% { opacity: 1; } `; // $ExpectError const NoExistingElementWrapper = styled.nonexisting` padding: 4em; background: papayawhip; `; const num: 9 = 9 // $ExpectError const NoExistingComponentWrapper = styled()` padding: 4em; background: papayawhip; `; // $ExpectError const NumberWrapper = styled(num)` padding: 4em; background: papayawhip; `; const sheet = new ServerStyleSheet() const html = renderToString(sheet.collectStyles(<ComponentWithTheme />)) const css = sheet.getStyleTags() const sheet2 = new ServerStyleSheet() const html2 = renderToString( <StyleSheetManager sheet={sheet}> <ComponentWithTheme /> </StyleSheetManager> ) const css2 = sheet.getStyleTags() const css3 = sheet.getStyleElement() // ---- COMPONENT CLASS TESTS ---- class NeedsThemeReactClass extends React.Component { props: { foo: string, theme: Theme } render() { return <div />; } } class ReactClass extends React.Component { props: { foo: string } render() { return <div />; } } const StyledClass: ReactComponentClass<{ foo: string, theme: Theme }> = styled(NeedsThemeReactClass)` color: red; `; const NeedsFoo1Class: ReactComponentClass<{ foo: string }, { theme: Theme }> = withTheme(NeedsThemeReactClass); // $ExpectError const NeedsFoo0ClassError: ReactComponentClass<{ foo: string }> = withTheme(ReactClass); // $ExpectError const NeedsFoo1ClassError: ReactComponentClass<{ foo: string }> = withTheme(NeedsFoo1Class); // $ExpectError const NeedsFoo1ErrorClass: ReactComponentClass<{ foo: number }> = withTheme(NeedsThemeReactClass); // $ExpectError const NeedsFoo2ErrorClass: ReactComponentClass<{ foo: string }, { theme: string }> = withTheme(NeedsThemeReactClass); // $ExpectError const NeedsFoo3ErrorClass: ReactComponentClass<{ foo: string, theme: Theme }> = withTheme(NeedsFoo1Class); // $ExpectError const NeedsFoo4ErrorClass: ReactComponentClass<{ foo: number }> = withTheme(NeedsFoo1Class); // $ExpectError const NeedsFoo5ErrorClass: ReactComponentClass<{ foo: string, theme: string }> = withTheme(NeedsFoo1Class); // ---- INTERPOLATION TESTS ---- const interpolation: Array<Interpolation> = styled.css` background-color: red; `; // $ExpectError const interpolationError: Array<Interpolation | boolean> = styled.css` background-color: red; `; // ---- DEFAULT COMPONENT TESTS ---- const defaultComponent: ReactComponentIntersection<{}> = styled.div` background-color: red; `; // $ExpectError const defaultComponentError: {} => string = styled.div` background-color: red; `; // ---- FUNCTIONAL COMPONENT TESTS ---- const FunctionalComponent: ReactComponentFunctional<{ foo: string, theme: Theme }> = props => <div />; const NeedsFoo1: ReactComponentFunctional<{ foo: string, theme: Theme }> = styled(FunctionalComponent)` background-color: red; `; // $ExpectError const NeedsFoo1Error: ReactComponentFunctional<{ foo: number }> = styled(FunctionalComponent)` background-color: red; `; const NeedsFoo2: ReactComponentFunctional<{ foo: string, theme: Theme }> = styled(NeedsFoo1)` background-color: red; `; // $ExpectError const NeedsFoo2Error: ReactComponentFunctional<{ foo: number }> = styled(NeedsFoo1)` background-color: red; `; // ---- FUNCTIONAL COMPONENT TESTS (withTheme)---- const NeedsFoo1Functional: ReactComponentFunctional<{ foo: string }> = withTheme(FunctionalComponent); const NeedsFoo2Functional: ReactComponentFunctional<{ foo: string }> = withTheme(NeedsFoo1Functional); // $ExpectError const NeedsFoo1ErrorFunctional: ReactComponentFunctional<{ foo: number }> = withTheme(FunctionalComponent); // $ExpectError const NeedsFoo2ErrorFunctional: ReactComponentFunctional<{ foo: string }, { theme: string }> = withTheme(FunctionalComponent); // $ExpectError const NeedsFoo3ErrorFunctional: ReactComponentFunctional<{ foo: number, theme: Theme }> = withTheme(FunctionalComponent); // $ExpectError const NeedsFoo4ErrorFunctional: ReactComponentFunctional<{ foo: number }> = withTheme(NeedsFoo1Functional); // $ExpectError const NeedsFoo5ErrorFunctional: ReactComponentFunctional<{ foo: string }, { theme: string }> = withTheme(NeedsFoo1Functional); // $ExpectError const NeedsFoo6ErrorFunctional: ReactComponentFunctional<{ foo: number }, { theme: Theme }> = withTheme(NeedsFoo1Functional);
app/demos/BasicLineChart.js
chunghe/React-Native-Stock-Chart
import React, { Component } from 'react'; import { ScrollView, StyleSheet } from 'react-native'; import { VictoryLine, } from 'victory-chart-native'; import T from '../components/T'; import data from '../data'; class BasicLineChart extends Component { render() { const { ticks } = data; return ( <ScrollView style={styles.container}> <T heading>Draw basic line chart using VictoryLine</T> <VictoryLine data={ticks} x={(d) => d.time} y={'price'} /> </ScrollView> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff' }, }); export default BasicLineChart;
src/modules/player/Player.js
paramsinghvc/harp
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import Slider from 'material-ui/Slider'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import bindThis from '../../shared/bindThis'; import { setVolume, setAudio, playAudio, pauseAudio, togglePlayPause, setAudioDuration, setCurrentPosition, playNextAudio, playPrevAudio, clearPlayerQueue } from './PlayerActions'; require('./Player.scss'); const styles = { volumeSlider: { height: 110, position: 'absolute', top: -106, left: 5, background: 'rgba(0, 0, 0, 0.42)', padding: 10, paddingTop: 15, borderRadius: 3, display: 'none' } } @connect((state) => { return { player: state.player } }, (dispatch) => { return bindActionCreators({ setVolume, setAudio, playAudio, pauseAudio, togglePlayPause, setAudioDuration, setCurrentPosition, playNextAudio, playPrevAudio, clearPlayerQueue }, dispatch) }) export default class Player extends Component { constructor(props) { super(props); } componentDidMount() { this.audioElem = ReactDOM.findDOMNode(this.refs.audioElem); this.audioElem.addEventListener('ended', function(e) { this.endAudio(); }.bind(this), false); this.audioElem.addEventListener('abort', function() { this.props.pauseAudio(); this.props.setCurrentPosition(0); this.audioElem.currentTime = 0; }.bind(this)); this.audioElem.addEventListener('loadeddata', function() { this.audioElem.play(); this.props.playAudio(); }.bind(this)); this.audioElem.addEventListener('durationchange', function(e) { console.log(this.audioElem.duration); this.props.setAudioDuration(this.audioElem.duration); }.bind(this), false); this.audioElem.addEventListener('timeupdate', function(e) { !this.audioElem.ended && this.props.setCurrentPosition(this.audioElem.currentTime); }.bind(this), false); } @bindThis getVolumeClass(volume) { let vClass = ''; if (volume > 0) if (volume > 3) vClass = 'up'; else vClass = 'down'; else vClass = 'off'; return `material-icons volume ${vClass}`; } @bindThis playPauseAudio() { this.props.togglePlayPause(); } endAudio() { this.props.pauseAudio(); this.props.setCurrentPosition(0); this.audioElem.currentTime = 0; this.props.playNextAudio(); } @bindThis changeVolume(vol) { this.props.setVolume(vol); this.setAudioElementVolume(vol); } @bindThis toggleMuteVolume(currentVolume) { if (currentVolume > 0) { this.props.setVolume(0); this.setAudioElementVolume(0); } else { this.props.setVolume(3); this.setAudioElementVolume(3); } } @bindThis setAudioElementVolume(vol) { let volume = (1 / 5) * vol; this.audioElem.volume = volume; } @bindThis seekAudioToPosition(e, pos) { this.audioElem.currentTime = pos; } @bindThis playPauseStateCheck(isPlaying) { if (this.audioElem) { if (isPlaying && this.audioElem.paused) { this.audioElem.play(); } if (!isPlaying && !this.audioElem.paused) { this.audioElem.pause(); } } } @bindThis playNext() { this.props.playNextAudio(); } @bindThis playPrevious() { this.props.playPrevAudio(); } render() { this.playPauseStateCheck(this.props.player.get('isPlaying')); return ( <section id="s-player"> <div className="audio-info" tabIndex="0" aria-label="playing audio information"> <p className="audio-name" tabIndex="0" aria-label="Audio Name" id="audio-name" aria-describedby="audio-name">{this.props.player.getIn(['audioInfo', 'name'])}</p> <p className="audio-artists" tabIndex="0" aria-label="Artists Names" aria-describedby="audio-artists" id="audio-artists">{this.props.player.getIn(['audioInfo', 'artists'])}</p> </div> <div className="audio-controls" tabIndex="0" aria-label="Player Controls"> <audio id="audio-elem" ref="audioElem" src={this.props.player.getIn(['audioInfo', 'url'])} aria-hidden="true"/> <section className={this.props.player.getIn(['audioInfo', 'url']) ? 'seek-controls' : 'seek-controls disabled'}> <i className="material-icons prev" onClick={this.playPrevious} tabIndex="0" aria-label="Play Previous Track">&#xE045;</i> <i className={this.props.player.get('isPlaying') ? `material-icons pause-btn`: `material-icons play-btn`} onClick={this.playPauseAudio} onKeyPress={(e) => { if(e.which == 13) this.playPauseAudio(); }} aria-label={this.props.player.get('isPlaying') ? `Pause Track`: `Play Track`} tabIndex="0"></i> <i className="material-icons next" tabIndex="0" aria-label="Play Next Track" onClick={this.playNext}>&#xE044;</i> </section> <Slider style={{width: '100%'}} sliderStyle={{marginTop: 5}} max={this.props.player.get('audioDuration')} min={0} value={this.props.player.get('currentPosition')} onChange={this.seekAudioToPosition} aria-valuemax={this.props.player.get('audioDuration')} aria-valuemin={0} aria-valuenow={this.props.player.get('currentPosition')} role="slider" disabled={!!!this.props.player.getIn(['audioInfo', 'url'])} aria-label="Player Progress Slider" aria-live="polite" aria-atomic="true" /> </div> <div className="audio-volume"> <i className="material-icons clear-queue" title="Clear Queue" onClick={this.props.clearPlayerQueue}>&#xE0B8;</i> <div className="vol-slider-holder"> <i className={this.getVolumeClass(this.props.player.get('volume'))} onClick={() => {this.toggleMuteVolume(this.props.player.get('volume'))}}></i> <Slider style={styles.volumeSlider} id="vol-slider" sliderStyle={{marginTop: 0, marginBottom: 0}} axis="y" value={this.props.player.get('volume')} min={0} max={5} onChange={(e, volume) => {this.changeVolume(volume)}} aria-valuemax={5} aria-valuemin={0} aria-valuenow={this.props.player.get('volume')} role="slider" tabIndex="0" aria-label="Player Volume Control" /> </div> </div> </section> ) } }
templates/rubix/rubix-bootstrap/src/AlertLink.js
jeffthemaximum/jeffline
import React from 'react'; import classNames from 'classnames'; export default class AlertLink extends React.Component { render() { let props = { ...this.props }; props.className = classNames('alert-link', props.className); return ( <a {...props} /> ); } }
src/components/keyboard-shortcut.js
tddbin/tddbin-frontend
import React from 'react'; export default class KeyboardShortcut extends React.Component { render() { const {printableKeys, helpText} = this.props.shortcut; return ( <div> <span className="shortcut">{printableKeys} </span> {helpText} </div> ); } }
examples/router/src/Echo.js
jaysoo/react-transact
import React from 'react' import { connect } from 'react-redux' import { transact, taskCreator } from 'react-transact' import { scan } from 'ramda' const say = taskCreator('ERROR', 'ECHO', (what) => what) const repeat = taskCreator('ERROR', 'ECHO', (what) => { return `${what} ${what}` }) const delay = (ms) => (x) => new Promise((res) => { setTimeout(() => res(x), ms) }) const Echo = transact((state, props) => ( scan( (acc, task) => { return acc.chain(task).map(delay(500)) }, say(props.params.what), [ repeat, repeat, repeat, repeat, repeat ] ) ))( connect(state => ({ what: state.what }) )(({ what}) => ( <div className="content"> { what} </div> ))) Echo.displayName = 'Echo' export default Echo
docs/src/app/components/pages/components/List/ExampleSettings.js
kasra-co/material-ui
import React from 'react'; import MobileTearSheet from '../../../MobileTearSheet'; import {List, ListItem} from 'material-ui/List'; import Subheader from 'material-ui/Subheader'; import Divider from 'material-ui/Divider'; import Checkbox from 'material-ui/Checkbox'; import Toggle from 'material-ui/Toggle'; const styles = { root: { display: 'flex', flexWrap: 'wrap', }, }; const ListExampleSettings = () => ( <div style={styles.root}> <MobileTearSheet> <List> <Subheader>General</Subheader> <ListItem primaryText="Profile photo" secondaryText="Change your Google+ profile photo" /> <ListItem primaryText="Show your status" secondaryText="Your status is visible to everyone you use with" /> </List> <Divider /> <List> <Subheader>Hangout Notifications</Subheader> <ListItem leftCheckbox={<Checkbox />} primaryText="Notifications" secondaryText="Allow notifications" /> <ListItem leftCheckbox={<Checkbox />} primaryText="Sounds" secondaryText="Hangouts message" /> <ListItem leftCheckbox={<Checkbox />} primaryText="Video sounds" secondaryText="Hangouts video call" /> </List> </MobileTearSheet> <MobileTearSheet> <List> <ListItem primaryText="When calls and notifications arrive" secondaryText="Always interrupt" /> </List> <Divider /> <List> <Subheader>Priority Interruptions</Subheader> <ListItem primaryText="Events and reminders" rightToggle={<Toggle />} /> <ListItem primaryText="Calls" rightToggle={<Toggle />} /> <ListItem primaryText="Messages" rightToggle={<Toggle />} /> </List> <Divider /> <List> <Subheader>Hangout Notifications</Subheader> <ListItem primaryText="Notifications" leftCheckbox={<Checkbox />} /> <ListItem primaryText="Sounds" leftCheckbox={<Checkbox />} /> <ListItem primaryText="Video sounds" leftCheckbox={<Checkbox />} /> </List> </MobileTearSheet> </div> ); export default ListExampleSettings;
examples/real-world/containers/Root.js
lightsinthesky/redux
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import { Router, Route } from 'react-router'; import configureStore from '../store/configureStore'; import App from './App'; import UserPage from './UserPage'; import RepoPage from './RepoPage'; const store = configureStore(); export default class Root extends Component { render() { return ( <div> <Provider store={store}> {() => <Router history={this.props.history}> <Route path='/' component={App}> <Route path='/:login/:name' component={RepoPage} /> <Route path='/:login' component={UserPage} /> </Route> </Router> } </Provider> </div> ); } }
src/App.js
lslima91/React-PostCSS-Playground
import React, { Component } from 'react'; // import {main, section, sec} from './css/style.styl' import {main, section, sec} from './css/style.css' const Responsive = () =>( <div className={section}> <div className={sec}>1</div> <div className={sec}>2</div> <div className={sec}>3</div> <div className={sec}>4</div> <div className={sec}>5</div> <div className={sec}>6</div> </div> ) const Offset = ({}) => ( // {/*<!-- Offset -->*/} <div className={section}> <div className={sec}>1</div> <div className={sec}>2</div> </div> ) const Nesting = ({}) => ( // {/*<!-- Nesting -->*/} <div className={section}> <div className={sec}>a</div> <div className={sec}>a</div> <div className={sec}> <div className={sec}>b</div> <div className={sec}>b</div> </div> </div> ) const Alignment = () => ( // {/*<!-- Alignment -->*/} <div className={section}> <div className={sec}>1</div> </div> ) const Cycle = () => ( // {/*<!-- Cycle -->*/} <div className={section}> <div className={sec}> 1 - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem rem nam dolore repellendus provident, voluptas necessitatibus vel cupiditate delectus, doloremque incidunt accusantium quia! Nisi molestiae totam natus, in assumenda accusantium. </div> <div className={sec}> 2 - Lorem ipsum dolor sit amet. </div> <div className={sec}> 3 - Lorem ipsum dolor sit amet, consectetur adipisicing elit. At sunt harum ut rerum id quae voluptas velit iusto quasi distinctio. </div> <div className={sec}> 4 - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Similique, sequi? </div> <div className={sec}> 5 - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime nisi deserunt, dolorem accusamus sint ipsam dolor quae ab animi assumenda architecto placeat possimus fugit doloribus vel, corporis amet aliquam maiores! </div> <div className={sec}> 6 - Lorem ipsum dolor sit amet, consectetur adipisicing elit. </div> </div> ) const Vgrid = () => ( // {/*<!-- Vertical Grid -->*/} <div className={section}> <div className={sec}>1</div> <div className={sec}>2</div> <div className={sec}>3</div> </div> ) const Wafflegrid = () => ( // {/*<!-- Waffle Grid -->*/} <div className={section}> <div className={sec}>1</div> <div className={sec}>2</div> <div className={sec}>3</div> <div className={sec}>4</div> <div className={sec}>5</div> <div className={sec}>6</div> <div className={sec}>7</div> <div className={sec}>8</div> <div className={sec}>9</div> <div className={sec}>10</div> <div className={sec}>11</div> <div className={sec}>12</div> <div className={sec}>13</div> <div className={sec}>14</div> <div className={sec}>15</div> </div> ) const Varstyles = () => ( // {/*<!-- Varying Sizes -->*/} <div className={section}> <div className={sec}>1</div> <div className={sec}>2</div> </div> ) const Sordering = () => ( <div className={section}> {/*<!-- Source Ordering -->*/} <div className={sec}>1</div> <div className={sec}>2</div> </div> ) export class App extends Component { render() { return ( <div> <Responsive /> <Offset/> <Nesting /> <Alignment/> <Cycle/> <Vgrid/> <Wafflegrid /> <Varstyles /> <Sordering />*/} </div> ); } }
dva/wd2/src/routes/User/Modify/ModifyPwdPage.js
imuntil/React
import React from 'react' import { connect } from 'dva' import { List, Toast } from 'antd-mobile' import QueueAnim from 'rc-queue-anim' import Form from '@/components/Common/Form' import InputItem from '@/components/Form/InputItem' import UInput from '@/components/Form/UInput' import { modifyPwd } from '@/services' import { delay } from '@/utils/cts' import './ModifyPage.scss' const Item = List.Item const mapStateToProps = state => { return { user: state.user } } @connect(mapStateToProps) export default class ModifyPwdPage extends Form { state = { submitted: false, nPwd: '' } handleChange = ({ name, value, $valid: { valid } }) => { this.form[name] = { value, valid } name === 'nPwd' && this.setState({ nPwd: value }) } handle = async () => { if (!this.formValid) return const { oPwd, nPwd } = this.form if (oPwd.value === nPwd.value) { Toast.info('新密码不能和原密码一样', 1.5) return } const { user: { phone }, history } = this.props Toast.loading('', 100) const { fail, err } = await modifyPwd({ nPwd: nPwd.value, oPwd: oPwd.value, phone }) if (err) { Toast.info('出错了,请稍后重试', 2) return } if (fail) { Toast.info(fail.msg, 2) return } Toast.success('操作成功', 1.5) await delay(800) history.push('/user') } render() { const { submitted, nPwd } = this.state return ( <div className="container modify-pwd-sl92w"> <div className="am-list"> <QueueAnim className="am-list-body"> <Item key={0}> <p className="list-item flex"> <span>手机号</span> <span className="gray">135****6765</span> </p> </Item> <InputItem key={1} label="登陆密码" mode="left" className="bb no-bt wider-label" noColon > <UInput name="oPwd" type="password" reg="password" onInputChange={this.handleChange} shake={submitted} placeholder="填写当前登录密码" required /> </InputItem> <Item key={2}> <p className="list-item gray">请重新设置登录密码</p> </Item> <InputItem key={3} label="设置新密码" mode="left" className="no-bt wider-label" noColon > <UInput name="nPwd" type="password" reg="password" onInputChange={this.handleChange} shake={submitted} placeholder="6-20位字母、数字组合" required /> </InputItem> <InputItem key={4} label="确认新密码" mode="left" className="wider-label" noColon > <UInput name="confirm" type="password" reg="password" onInputChange={this.handleChange} shake={submitted} confirm={nPwd} placeholder="再次填写密码" required /> </InputItem> <p className="form-btn-box" key={5}> <a onClick={this.handleClick} href="javascript:;" className="form-btn" > 保存 </a> </p> </QueueAnim> </div> </div> ) } }
client/components/games/index.js
wordupapp/wordup
import React from 'react'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import { Table, Header, Grid, Container, Icon, Button, Label } from 'semantic-ui-react'; import styles from './styles'; const Games = props => { const { level } = props; const seed = Math.floor(Math.random() * 100); const games = [ { key: 0, name: 'Synonym Matching', ref: 'synonyms', icon: 'cloud' }, { key: 1, name: 'Definitions', ref: `definitions/${seed}`, icon: 'telegram' }, { key: 2, name: 'Examples', ref: 'fill-it-in', icon: 'bookmark' }, { key: 3, name: 'Chat Chat', ref: '', icon: 'wechat' }, { key: 5, name: 'Word School', ref: '', icon: 'pencil' }, { key: 6, name: 'Under Contruction', ref: '', icon: 'cogs' }, ]; const gameButtons = games.map(game => ( <Grid.Column key={game.key} style={styles.buttonCol}> <Button icon as={Link} to={`/games/${game.ref}`} style={styles.gameButton}> <Container style={styles.gameContainer}> <Icon style={styles.gameIcon} name={game.icon} size="massive" /> <Header as="h3" style={styles.gameLabel}> {game.name} </Header> </Container> </Button> </Grid.Column> )); const userLevelBlock = ( <Container style={styles.rightContainerTop}> <Header as="h2" style={styles.subTitle}> {'Your level: '} <Label circular color="red" style={styles.levelNumber}> {level} </Label> </Header> <Container style={styles.levelContainer}> <Icon style={styles.levelIcon} name={'trophy'} /> </Container> </Container> ); // TODO: fake datat for now! const topScoresArr = [ { rank: 1, score: 140, userName: 'Louis', userLevel: 9, userImage: 'https://raw.githubusercontent.com/Ashwinvalento/cartoon-avatar/master/lib/images/male/67.png', }, { rank: 2, score: 135, userName: 'Maggie', userLevel: 7, userImage: 'https://raw.githubusercontent.com/Ashwinvalento/cartoon-avatar/master/lib/images/female/98.png', }, { rank: 3, score: 100, userName: 'Tyler', userLevel: 8, userImage: 'https://raw.githubusercontent.com/Ashwinvalento/cartoon-avatar/master/lib/images/male/128.png', }, { rank: 4, score: 99, userName: 'Eva', userLevel: 8, userImage: 'https://raw.githubusercontent.com/Ashwinvalento/cartoon-avatar/master/lib/images/female/103.png', }, { rank: 5, score: 98, userName: 'Mabelle', userLevel: 6, userImage: ' https://raw.githubusercontent.com/Ashwinvalento/cartoon-avatar/master/lib/images/female/30.png', }, ] const topScoreTableRows = topScoresArr.map(score => ( <Table.Row key={score.rank}> <Table.Cell>{score.rank}</Table.Cell> <Table.Cell>{score.score}</Table.Cell> <Table.Cell> <Label image> <img src={score.userImage} alt={score.userName} /> {score.userName} </Label> </Table.Cell> <Table.Cell>{score.userLevel}</Table.Cell> </Table.Row> )) return ( <Container style={styles.all}> <Grid container stackable stretched relaxed style={styles.container}> <Grid.Row> <Grid.Column width={11}> <Container style={styles.leftContainer}> <Header as="h1" style={styles.title}> Playground </Header> <Grid columns={3} doubling style={styles.gameGroup}> {gameButtons} </Grid> </Container> </Grid.Column> <Grid.Column floated="right" width={5}> <Grid.Row > {userLevelBlock} </Grid.Row> <Grid.Row> <Container style={styles.rightContainerBot}> <Header as="h2" style={styles.subTitle}>Top scores</Header> <Table color="red"> <Table.Header> <Table.Row> <Table.HeaderCell>Rank</Table.HeaderCell> <Table.HeaderCell>Score</Table.HeaderCell> <Table.HeaderCell style={styles.userCol}>User</Table.HeaderCell> <Table.HeaderCell>Level</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> {topScoreTableRows} </Table.Body> </Table> </Container> </Grid.Row> </Grid.Column> </Grid.Row> </Grid> </Container> ); }; /** * CONTAINER */ const mapState = state => { return { level: state.userLevel, }; }; export default connect(mapState)(Games);
src/components/AuthenticatedRoutes.js
codefordenver/encorelink
import PropTypes from 'prop-types'; import React from 'react'; import { withRouter } from 'react-router'; function AuthenticatedRoutes({ isAppInitialized, isLoggedIn, children, router, location }) { if (!isAppInitialized) { return <div>Loading...</div>; } else if (!isLoggedIn) { router.replace({ pathname: '/login', state: { nextPathname: location.pathname } }); } return children; } AuthenticatedRoutes.propTypes = { children: PropTypes.node.isRequired, isAppInitialized: PropTypes.bool.isRequired, isLoggedIn: PropTypes.bool.isRequired, router: PropTypes.shape({ replace: PropTypes.func.isRequired }), location: PropTypes.shape({ state: PropTypes.shape({ pathname: PropTypes.string }) }).isRequired }; export default withRouter(AuthenticatedRoutes);
webpack/stores/TodoStore.js
ihenvyr/react_redux_boilerplate
import React, { Component } from 'react'; import { createStore, applyMiddleware, combineReducers, compose } from 'redux'; import thunk from 'redux-thunk'; import * as TodoReducers from './TodoReducers'; let finalCreateStore; if (dev_tools) { var reduxDevtools = require('redux-devtools'); var devTools = reduxDevtools.devTools; var persistState = reduxDevtools.persistState; var reduxDevtoolsLibReact = require('redux-devtools/lib/react'); var DevTools = reduxDevtoolsLibReact.DevTools; var DebugPanel = reduxDevtoolsLibReact.DebugPanel; var LogMonitor = reduxDevtoolsLibReact.LogMonitor; finalCreateStore = compose( applyMiddleware(thunk), devTools(), persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)) )(createStore); } else { finalCreateStore = compose( applyMiddleware(thunk) )(createStore); } const reducer = combineReducers(TodoReducers); const store = finalCreateStore(reducer); export default store;
src/App.js
steve-sarcinella/stevensarcinella.com
import React, { Component } from 'react'; import { ThemeProvider } from 'styled-components' import WeatherWatchContainer from './containers/WeatherWatchContainer'; import './App.css'; const theme = { primary: '#6699CC;' }; // <ThemeProvider theme={theme}> // <div className="app"> // </div> // </ThemeProvider> class App extends Component { render() { return ( <WeatherWatchContainer> OMG ITS THE WEATHER </WeatherWatchContainer> ); } } export default App;
src/scenes/App/scenes/Home/components/ActivityTopList/index.js
jsza/tempus-website
import React from 'react' import cx from 'classnames' import {mapScreenshot, formatTime, prettyZoneName} from 'root/utils/TempusUtils' import {Link} from 'react-router-dom' import Table from 'react-bootstrap/lib/Table' import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger' import TimeAgo from 'react-timeago' import SteamAvatar from 'root/components/SteamAvatar' export default class ActivityTopList extends React.Component { render() { const items = this.props.data.map((i) => { const rank = i.get('rank') const pi = i.get('player_info') const mi = i.get('map_info') const zi = i.get('zone_info') const ri = i.get('record_info') const iconClasses = cx( { 'tf-icon': true , 'mini': true , 'soldier': ri.get('class') === 3 , 'demoman': ri.get('class') === 4 }) return ( <tr> <td className="shrink"> <span className={iconClasses} /> {' '} <OverlayTrigger animation={false} placement="bottom" overlay={<div className="app-tooltip"><img width="160" className="img-thumbnail" src={mapScreenshot(mi.get('name'), '160p')} /></div>}> <Link to={`/maps/${mi.get('name')}`}> {mi.get('name') + ( zi.get('type') !== 'map' ? '/' + prettyZoneName(zi.get('type'), zi.get('zoneindex')) : '' )} </Link> </OverlayTrigger> </td> <td className="shrink"> <strong className="activity-duration"> #{rank} </strong> </td> <td className="shrink"> <span className="activity-player-container"> <span style={{marginRight: '6px'}}> <SteamAvatar steamID={pi.get('steamid')} size="mini" /> </span> <Link to={`/players/${pi.get('id')}`}> {pi.get('name')} </Link> </span> </td> <td className="expand"> <span className="pull-right text-muted"> <TimeAgo date={ri.get('date') * 1000} /> </span> </td> </tr> ) }) return( <Table className="activity-table"> <tbody> {items} </tbody> </Table> ) } }
src/parser/shaman/restoration/CombatLogParser.js
sMteX/WoWAnalyzer
import React from 'react'; import Panel from 'interface/others/Panel'; import RestorationShamanSpreadsheet from 'interface/others/RestorationShamanSpreadsheet'; import Feeding from 'interface/others/Feeding'; import CoreCombatLogParser from 'parser/core/CombatLogParser'; import HealingEfficiencyDetails from 'parser/core/healingEfficiency/HealingEfficiencyDetails'; import ManaTracker from 'parser/core/healingEfficiency/ManaTracker'; import LowHealthHealing from 'parser/shared/modules/features/LowHealthHealing'; import ManaLevelChart from 'parser/shared/modules/resources/mana/ManaLevelChart'; import ManaUsageChart from 'parser/shared/modules/resources/mana/ManaUsageChart'; import HealingEfficiencyTracker from './modules/core/HealingEfficiencyTracker'; import Abilities from './modules/Abilities'; import HealingDone from './modules/core/HealingDone'; import ShamanAbilityTracker from './modules/core/ShamanAbilityTracker'; import HealingRainLocation from './modules/core/HealingRainLocation'; import MasteryEffectiveness from './modules/features/MasteryEffectiveness'; import AlwaysBeCasting from './modules/features/AlwaysBeCasting'; import CooldownThroughputTracker from './modules/features/CooldownThroughputTracker'; import Checklist from './modules/features/checklist/Module'; import SpellUsable from './modules/features/SpellUsable'; import StatValues from './modules/features/StatValues'; import TidalWaves from './modules/features/TidalWaves'; import CastBehavior from './modules/features/CastBehavior'; // Talents import TalentStatisticBox from './modules/talents/TalentStatisticBox'; import Torrent from './modules/talents/Torrent'; import UnleashLife from './modules/talents/UnleashLife'; import Deluge from './modules/talents/Deluge'; import Undulation from './modules/talents/Undulation'; import FlashFlood from './modules/talents/FlashFlood'; import EarthShield from './modules/talents/EarthShield'; import AncestralVigor from './modules/talents/AncestralVigor'; import EarthenWallTotem from './modules/talents/EarthenWallTotem'; import Downpour from './modules/talents/Downpour'; import CloudburstTotem from './modules/talents/CloudburstTotem'; import Ascendance from './modules/talents/Ascendance'; import Wellspring from './modules/talents/Wellspring'; import HighTide from './modules/talents/HighTide'; import NaturesGuardian from './modules/talents/NaturesGuardian'; // Spells import ChainHeal from './modules/spells/ChainHeal'; import HealingSurge from './modules/spells/HealingSurge'; import HealingRain from './modules/spells/HealingRain'; import HealingWave from './modules/spells/HealingWave'; import LavaSurge from './modules/spells/LavaSurge'; import Resurgence from './modules/spells/Resurgence'; //Azerite import BaseHealerAzerite from './modules/azerite/BaseHealerAzerite'; import SwellingStream from './modules/azerite/SwellingStream'; import SoothingWaters from './modules/azerite/SoothingWaters'; import OverflowingShores from './modules/azerite/OverflowingShores'; import SpoutingSpirits from './modules/azerite/SpoutingSpirits'; import SurgingTides from './modules/azerite/SurgingTides'; // Shared import SpiritWolf from '../shared/talents/SpiritWolf'; import StaticCharge from '../shared/talents/StaticCharge'; import AstralShift from '../shared/spells/AstralShift'; import PackSpirit from '../shared/azerite/PackSpirit'; import SereneSpirit from '../shared/azerite/SereneSpirit'; import SynapseShock from '../shared/azerite/SynapseShock'; import IgneousPotential from '../shared/azerite/IgneousPotential'; import CloudburstNormalizer from './normalizers/CloudburstNormalizer'; import { ABILITIES_AFFECTED_BY_HEALING_INCREASES } from './constants'; class CombatLogParser extends CoreCombatLogParser { static abilitiesAffectedByHealingIncreases = ABILITIES_AFFECTED_BY_HEALING_INCREASES; static specModules = { // Override the ability tracker so we also get stats for Tidal Waves and beacon healing abilityTracker: ShamanAbilityTracker, lowHealthHealing: LowHealthHealing, healingDone: HealingDone, abilities: Abilities, healingRainLocation: HealingRainLocation, manaTracker: ManaTracker, hpmDetails: HealingEfficiencyDetails, hpmTracker: HealingEfficiencyTracker, // Generic healer things manaLevelChart: ManaLevelChart, manaUsageChart: ManaUsageChart, // Features alwaysBeCasting: AlwaysBeCasting, masteryEffectiveness: MasteryEffectiveness, cooldownThroughputTracker: CooldownThroughputTracker, tidalWaves: TidalWaves, castBehavior: CastBehavior, checklist: Checklist, spellUsable: SpellUsable, statValues: StatValues, // Talents: torrent: Torrent, unleashLife: UnleashLife, undulation: Undulation, deluge: Deluge, flashFlood: FlashFlood, earthShield: EarthShield, ancestralVigor: AncestralVigor, earthenWallTotem: EarthenWallTotem, downpour: Downpour, cloudburstTotem: CloudburstTotem, ascendance: Ascendance, wellspring: Wellspring, highTide: HighTide, naturesGuardian: NaturesGuardian, talentStatisticBox: TalentStatisticBox, // Spells: chainHeal: ChainHeal, healingSurge: HealingSurge, healingRain: HealingRain, healingWave: HealingWave, lavaSurge: LavaSurge, resurgence: Resurgence, // Azerite baseHealerAzerite: BaseHealerAzerite, swellingStream: SwellingStream, soothingWaters: SoothingWaters, overflowingShores: OverflowingShores, spoutingSpirits: SpoutingSpirits, surgingTides: SurgingTides, synapseShock: SynapseShock, igneousPotential: IgneousPotential, // Shared: spiritWolf: SpiritWolf, staticCharge: StaticCharge, astralShift: AstralShift, packSpirit: PackSpirit, sereneSpirit: SereneSpirit, // Normalizers: cloudburstNormalizer: CloudburstNormalizer, }; generateResults(...args) { const results = super.generateResults(...args); results.tabs = [ ...results.tabs, { title: 'Player Log Data', url: 'player-log-data', render: () => ( <Panel style={{ padding: '15px 22px 15px 15px' }}> <RestorationShamanSpreadsheet parser={this} /> </Panel> ), }, { title: 'Feeding', url: 'feeding', render: () => ( <Panel style={{ padding: 0 }}> <Feeding cooldownThroughputTracker={this.getModule(CooldownThroughputTracker)} /> </Panel> ), }, ]; return results; } } export default CombatLogParser;
src/svg-icons/av/surround-sound.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSurroundSound = (props) => ( <SvgIcon {...props}> <path d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM7.76 16.24l-1.41 1.41C4.78 16.1 4 14.05 4 12c0-2.05.78-4.1 2.34-5.66l1.41 1.41C6.59 8.93 6 10.46 6 12s.59 3.07 1.76 4.24zM12 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm5.66 1.66l-1.41-1.41C17.41 15.07 18 13.54 18 12s-.59-3.07-1.76-4.24l1.41-1.41C19.22 7.9 20 9.95 20 12c0 2.05-.78 4.1-2.34 5.66zM12 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/> </SvgIcon> ); AvSurroundSound = pure(AvSurroundSound); AvSurroundSound.displayName = 'AvSurroundSound'; AvSurroundSound.muiName = 'SvgIcon'; export default AvSurroundSound;
app/javascript/mda_viewer/components/riek/src/RIEStatefulBase.js
relf/WhatsOpt
import React from 'react'; import ReactDOM from 'react-dom'; import RIEBase from './RIEBase'; const debug = require('debug')('RIEStatefulBase'); export default class RIEStatefulBase extends RIEBase { constructor(props) { super(props); this.myRef = React.createRef(); } startEditing = () => { debug('startEditing') this.props.beforeStart ? this.props.beforeStart() : null; if (this.props.isDisabled) return; this.setState({ editing: true }); this.props.afterStart ? this.props.afterStart() : null; }; finishEditing = () => { debug('finishEditing') this.props.beforeFinish ? this.props.beforeFinish() : null; let inputElem = ReactDOM.findDOMNode(this.myRef.current); let newValue = inputElem.value; const result = this.doValidations(newValue); if (result && this.props.value !== newValue) { this.commit(newValue); } if (!result && this.props.handleValidationFail) { this.props.handleValidationFail(result, newValue, () => this.cancelEditing()); } else { this.cancelEditing(); } this.props.afterFinish ? this.props.afterFinish() : null; }; cancelEditing = () => { debug('cancelEditing') this.setState({ editing: false, invalid: false }); }; keyDown = (event) => { debug('keyDown(${event.keyCode})') if (event.keyCode === 13) { this.finishEditing() } // Enter else if (event.keyCode === 27) { this.cancelEditing() } // Escape }; textChanged = (event) => { debug('textChanged(${event.target.value})') this.doValidations(event.target.value.trim()); }; componentDidUpdate = (prevProps, prevState) => { debug(`componentDidUpdate(${JSON.stringify(prevProps)}, ${JSON.stringify(prevState)})`) var inputElem = ReactDOM.findDOMNode(this.myRef.current); if (this.state.editing && !prevState.editing) { debug('entering edit mode') inputElem.focus(); this.selectInputText(inputElem); } else if (this.state.editing && prevProps.text != this.props.text) { debug('not editing && text not equal previous props -- finishing editing') this.finishEditing(); } }; renderEditingComponent = () => { debug('renderEditingComponent()') return <input disabled={this.state.loading} className={this.makeClassString()} defaultValue={this.props.value} onInput={this.textChanged} onBlur={this.elementBlur} ref={this.myRef} onKeyDown={this.keyDown} {...this.props.editProps} />; }; renderNormalComponent = () => { debug('renderNormalComponent') return <span tabIndex="0" className={this.makeClassString()} onFocus={this.startEditing} onClick={this.startEditing} ref={this.myRef} {...this.props.defaultProps}>{this.state.newValue || this.props.value}</span>; }; elementBlur = (event) => { debug(`elementBlur(${event})`) this.finishEditing(); }; elementClick = (event) => { debug(`elementClick(${event})`) this.startEditing(); event.target.element.focus(); }; render = () => { debug('render()') if (this.state.editing) { return this.renderEditingComponent(); } else { return this.renderNormalComponent(); } }; }
examples/huge-apps/routes/Course/components/Nav.js
darul75/react-router
import React from 'react'; import { Link } from 'react-router'; import AnnouncementsRoute from '../routes/Announcements'; import AssignmentsRoute from '../routes/Assignments'; import GradesRoute from '../routes/Grades'; const styles = {}; styles.nav = { borderBottom: '1px solid #aaa' }; styles.link = { display: 'inline-block', padding: 10, textDecoration: 'none', }; styles.activeLink = Object.assign({}, styles.link, { //color: 'red' }); class Nav extends React.Component { render () { var { course } = this.props; var pages = [ ['announcements', 'Announcements'], ['assignments', 'Assignments'], ['grades', 'Grades'], ]; return ( <nav style={styles.nav}> {pages.map((page, index) => ( <Link key={page[0]} activeStyle={index === 0 ? Object.assign({}, styles.activeLink, { paddingLeft: 0 }) : styles.activeLink} style={index === 0 ? Object.assign({}, styles.link, { paddingLeft: 0 }) : styles.link } to={`/course/${course.id}/${page[0]}`} >{page[1]}</Link> ))} </nav> ); } } export default Nav;
src/components/PersonList.stories.js
janimattiellonen/fgr
import React from 'react'; import { storiesOf, action } from '@kadira/storybook'; import PersonList from './PersonList'; import { generatePerson, random } from '../utils/random'; const randoms = Array.from('tussi').map(generatePerson()); const oldWomen = Array.from('vanhoinaisii').map(generatePerson( person => ({ ...person, gender: 'f', age: random.integer(75, 100), }) )); storiesOf('PersonList', module) .add('Random persons', () => ( <PersonList persons={randoms} /> )) .add('Old women', () => ( <PersonList persons={oldWomen} /> )) ;
pnpm-offline/.pnpm-store-offline/1/registry.npmjs.org/react-bootstrap/0.31.0/es/Row.js
JamieMason/npm-cache-benchmark
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'div' }; var Row = function (_React$Component) { _inherits(Row, _React$Component); function Row() { _classCallCheck(this, Row); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Row.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return Row; }(React.Component); Row.propTypes = propTypes; Row.defaultProps = defaultProps; export default bsClass('row', Row);
fields/types/text/TextColumn.js
pr1ntr/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var TextColumn = React.createClass({ displayName: 'TextColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, linkTo: React.PropTypes.string, }, getValue () { // cropping text is important for textarea, which uses this column const value = this.props.data.fields[this.props.col.path]; return value ? value.substr(0, 100) : null; }, render () { const value = this.getValue(); const empty = !value && this.props.linkTo ? true : false; const className = this.props.col.field.monospace ? 'ItemList__value--monospace' : undefined; return ( <ItemsTableCell> <ItemsTableValue className={className} href={this.props.linkTo} empty={empty} padded interior field={this.props.col.type}> {value} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = TextColumn;
es/index.js
localvore-today/react-validator
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import { find, isArray } from 'lodash'; import validator from './validator'; export default function withFormValidations(WrappedComponent, inputs, redux, validations) { return function (_React$Component) { _inherits(_class2, _React$Component); function _class2() { var _temp, _this, _ret; _classCallCheck(this, _class2); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = { inputs: inputs.map(function (i) { i.validations = new validator(i.rules, redux, validations); return i; }) }, _this._addInputs = function (inputs) { if (!isArray(inputs)) inputs = [inputs]; _this.setState({ inputs: _this.state.inputs.concat(inputs.map(function (i) { i.validations = new validator(i.rules, redux, validations, i.value); return i; })) }); }, _this._field = function (name) { return find(_this.state.inputs, function (i) { return i.label === name; }); }, _this._syncPasswordMatchValidator = function (input) { _this.setState({ inputs: _this.state.inputs.map(function (i) { if (i.label === 'confirmPassword') { i.validations._rules.map(function (r) { if (r.rule === 'match') { r.args = input.validations.val; } return r; }); } return i; }) }); }, _this._onChange = function (input, value) { input.validations.val = value; if (input.label === 'password') { _this._syncPasswordMatchValidator(input); } _this.setState({ inputs: _this.state.inputs.map(function (i) { if (i.label === input.label) i = input; return i; }) }); }, _this._valid = function (inputs) { var errors = []; if (inputs && !isArray(inputs)) { inputs = [inputs]; } _this.setState({ inputs: _this.state.inputs.map(function (i) { if (inputs && inputs.indexOf(i) >= 0) { i.validations.checkRules(); } else if (!inputs) { i.validations.checkRules(); } return i; }) }); inputs ? errors = _this.state.inputs.filter(function (i) { return inputs.indexOf(i) >= 0 && i.validations.errors.length > 0; }) : errors = _this.state.inputs.filter(function (i) { return i.validations.errors.length > 0; }); return errors.length < 1; }, _this._reset = function () { _this.setState({ inputs: _this.state.inputs.map(function (i) { i.validations.reset(); return i; }) }); }, _this._resetInputs = function () { _this.setState({ inputs: _this.state.inputs.map(function (i) { i.validations.val = ''; return i; }) }); }, _temp), _possibleConstructorReturn(_this, _ret); } _class2.prototype.render = function render() { return React.createElement(WrappedComponent, _extends({}, this.props, { addInputs: this._addInputs, field: this._field, inputs: this.state.inputs, onChange: this._onChange, reset: this._reset, resetInputs: this._resetInputs, valid: this._valid })); }; return _class2; }(React.Component); }
examples/index.js
6174/slate
import React from 'react' import ReactDOM from 'react-dom' import { HashRouter, NavLink, Route, Redirect, Switch } from 'react-router-dom' import CheckLists from './check-lists' import CodeHighlighting from './code-highlighting' import Embeds from './embeds' import Emojis from './emojis' import ForcedLayout from './forced-layout' import HoveringMenu from './hovering-menu' import HugeDocument from './huge-document' import Images from './images' import Links from './links' import MarkdownPreview from './markdown-preview' import MarkdownShortcuts from './markdown-shortcuts' import PasteHtml from './paste-html' import PlainText from './plain-text' import Plugins from './plugins' import RTL from './rtl' import ReadOnly from './read-only' import RichText from './rich-text' import SearchHighlighting from './search-highlighting' import SyncingOperations from './syncing-operations' import Tables from './tables' /** * Examples. * * @type {Array} */ const EXAMPLES = [ ['Rich Text', RichText, '/rich-text'], ['Plain Text', PlainText, '/plain-text'], ['Hovering Menu', HoveringMenu, '/hovering-menu'], ['Links', Links, '/links'], ['Images', Images, '/images'], ['Embeds', Embeds, '/embeds'], ['Emojis', Emojis, '/emojis'], ['Markdown Preview', MarkdownPreview, '/markdown-preview'], ['Markdown Shortcuts', MarkdownShortcuts, '/markdown-shortcuts'], ['Check Lists', CheckLists, '/check-lists'], ['Code Highlighting', CodeHighlighting, '/code-highlighting'], ['Tables', Tables, '/tables'], ['Paste HTML', PasteHtml, '/paste-html'], ['Search Highlighting', SearchHighlighting, '/search-highlighting'], ['Syncing Operations', SyncingOperations, '/syncing-operations'], ['Read-only', ReadOnly, '/read-only'], ['RTL', RTL, '/rtl'], ['Plugins', Plugins, '/plugins'], ['Forced Layout', ForcedLayout, '/forced-layout'], ['Huge Document', HugeDocument, '/huge-document'], ] /** * App. * * @type {Component} */ class App extends React.Component { state = { error: null, info: null, } componentDidCatch(error, info) { this.setState({ error, info }) } render() { return ( <div className="app"> <div className="nav"> <span className="nav-title">Slate Examples</span> <div className="nav-links"> <a className="nav-link" href="https://github.com/ianstormtaylor/slate">GitHub</a> <a className="nav-link" href="https://docs.slatejs.org/">Docs</a> </div> </div> <div className="tabs"> {EXAMPLES.map(([ name, Component, path ]) => ( <NavLink key={path} to={path} className="tab"activeClassName="active"> {name} </NavLink> ))} </div> {this.state.error ? this.renderError() : this.renderExample()} </div> ) } renderExample() { return ( <div className="example"> <Switch> {EXAMPLES.map(([ name, Component, path ]) => ( <Route key={path} path={path} component={Component} /> ))} <Redirect from="/" to="/rich-text" /> </Switch> </div> ) } renderError() { return ( <div className="error"> <p> An error was thrown by one of the example's React components! </p> <pre className="info"> <code> {this.state.error.stack} {'\n'} {this.state.info.componentStack} </code> </pre> </div> ) } } /** * Router. * * @type {Element} router */ const router = <HashRouter><App /></HashRouter> /** * Mount the router. */ const root = document.body.querySelector('main') ReactDOM.render(router, root)
assets/javascripts/kitten/components/graphics/icons/cross-circle-icon/index.js
KissKissBankBank/kitten
import React from 'react' import PropTypes from 'prop-types' import COLORS from '../../../../constants/colors-config' import { computeFromRatio } from '../../../../helpers/utils/ratio' import deprecated from 'prop-types-extra/lib/deprecated' import classNames from 'classnames' const DEFAULT_WIDTH = 20 const DEFAULT_HEIGHT = 20 export const CrossCircleIcon = ({ color, bgColor, circleColor, crossColor, width, height, title, className, ...props }) => { const computed = computeFromRatio({ defaultWidth: DEFAULT_WIDTH, defaultHeight: DEFAULT_HEIGHT, width, height, }) return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width={computed.width} height={computed.height} className={classNames('k-ColorSvg', className)} {...props} > {title && <title>{title}</title>} <circle fill={bgColor || circleColor} cx="10" cy="10" r="10" /> <path fill={color || crossColor} d="M11.414 10l2.122-2.12-1.415-1.416L10 8.586 7.88 6.464 6.463 7.88 8.586 10l-2.122 2.12 1.415 1.416L10 11.414l2.12 2.122 1.416-1.415L11.414 10z" /> </svg> ) } CrossCircleIcon.prototype = { bgColor: PropTypes.string, color: PropTypes.string, circleColor: deprecated( PropTypes.string, '`circleColor` is deprecated. Please use `bgColor` instead.', ), crossColor: deprecated( PropTypes.string, '`crossColor` is deprecated. Please use `color` instead.', ), title: PropTypes.string, width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), } CrossCircleIcon.defaultProps = { bgColor: COLORS.background1, color: COLORS.font1, }
src/eventDiagram/Consumers.js
camjackson/rr-docs-spike
import React from 'react'; import { services } from '../data'; const consumersOf = eventType => ( Object.keys(services).reduce((consumers, serviceName) => ( services[serviceName].consumes.includes(eventType) ? consumers.concat(serviceName) : consumers ), []) ); const Consumers = ({ eventType }) => ( <div> <h3>Consumers:</h3> <ul> {consumersOf(eventType).map(consumer => ( <li key={consumer}>{consumer}</li> ))} </ul> </div> ); export default Consumers;
packages/playground/stories/Select.story.js
appearhere/bloom
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { withKnobs, boolean } from '@storybook/addon-knobs'; import { Select, Option } from '@appearhere/bloom'; const icons = [ 'appearhere-brackets', 'automatic-payments', 'calendar-insight', 'chart-arrow', 'play-c', 'chevron-right', 'tick-c', 'tick-starred', 'travel-idea', 'vip-entrance', 'card-list', 'account', 'appearhere', 'arrow', 'bogroll', 'book', 'calendar', 'camera', 'chatting', 'chevron', 'clock', 'comment', 'cross', 'dollar', 'download', 'facebook', 'filter', 'globe', 'heart', 'location', 'manage', 'map', 'menu,', 'minus', 'notification', 'percentage', 'pinterest', 'play', 'plus', 'radio', 'search', 'shield', 'signature', 'star', 'store', 'teamwork', 'tick', 'ticket', 'twitter', ] const stories = storiesOf('FormComponents', module); stories.addDecorator(withKnobs); stories .add('Select', () => ( <Select name="icon" onChange={action('onChange')} onFocus={action('onFocus')} onBlur={action('onBlur')} error={boolean('Errored', false) ? 'Something went wrong' : ''} multiple={boolean('Multiple', false)} > {icons.map(option => ( <Option key={option} value={option}> {option} </Option> ))} </Select> )) .add('Select w/high priority', () => ( <Select name="icon" onChange={action('onChange')} onFocus={action('onFocus')} onBlur={action('onBlur')} error={boolean('Errored', false) ? 'Something went wrong' : ''} multiple={boolean('Multiple', false)} priority="high" > {icons.map(option => ( <Option key={option} value={option}> {option} </Option> ))} </Select> ));
src/routes/Home/components/HomeView.js
febobo/react-redux-start
import React from 'react' import reactDom from 'react-dom' import DuckImage from '../assets/Duck.jpg' import classes from './HomeView.scss' import {i18n} from '../../../util/i18n' import Adv from '../../../components/Adv' import code from '../../../static/images/code.jpg' import ad1 from '../../../static/images/ad1.jpg' import ad2 from '../../../static/images/ad2.jpg' import Lottery from '../../../components/Lottery' import Geetest from '../../../components/Geetest' import GoogleAdv from '../../../components/GoogleAdv' import GoogleAdv2 from '../../../components/GoogleAdv2' import GoogleAdv4 from '../../../components/GoogleAdv4' import BtcHomeTopAdv from '../../../components/Advs/BtcHomeTopAdv' import AutoHomeTopLeftAdv from '../../../components/Advs/AutoHomeTopLeftAdv' // import AutoHomeTopRightAdv from '../../../components/Advs/AutoHomeTopRightAdv' import CoinadAdv from '../../../components/CoinadAdv' import geetest from 'geetest-proxy'; import config from '../../../BaseConfig' export class HomeView extends React.Component { renderAdvProps(advProps){ const defaultProps = { style : {display:"inline-block",width:"970px",height:"90px"}, client : 'ca-pub-5722932343401905', slot : 1843492278, advBoxStyle : { paddingTop:"22px", textAlign : "center"} } return Object.assign({},defaultProps,advProps) } render (){ return ( <div> { config.show_home_top_adv ? <GoogleAdv4 {...this.renderAdvProps({slot:3422043073})} /> :null } { config.show_btc_home_top_adv ? <BtcHomeTopAdv {...this.renderAdvProps({slot:8465861479})} /> :null } { config.show_auto_home_top_adv ? <div style={{width:'1000px',margin:'0 auto',overflow:'hidden',padding:'0 20px'}}> <div style={{float:'left'}}> <AutoHomeTopLeftAdv {...this.renderAdvProps({ style : {display:"inline-block",width:"468px",height:"60px"}, client : 'ca-pub-5722932343401905', slot : 3046293077, advBoxStyle : { paddingTop:"22px", textAlign : "center"} })} /> </div> <div style={{float:'right',paddingTop : '22px'}}> <center> <div> <iframe scrolling="no" src="//coinad.com/ads/show/show.php?a=4XD7CSC96NFAP&b=3Y7FCLUKXK5ZR" style={{overflow:"hidden",width:"468px",height:"60px"}} frameborder="0"></iframe> </div> </center> </div> </div> :null } <Geetest {...this.props}/> { config.show_google_adv ? <GoogleAdv2 {...this.renderAdvProps({ slot:1843492278, advBoxStyle : { paddingTop:"25px", textAlign : "center" , width : "996px" , margin:"0 auto"} })} /> :null } <div className={classes.luckMain}> <div className={classes.mainBlock}> <div className={classes.dynamicTitle}><img src="images/dynamicIco.png" /><span><b>{i18n.t('common.dynamic')}</b></span> </div> <Lottery isDynamic={true} style={{marginTop:'20px'}}/> <div className={classes.ad}> <div className={classes.ad1}> { config.show_coinad_adv ? <center> <div> <iframe scrolling="no" src="https://coinad.com/ads/show/show.php?a=4XD7CSC96NFAP&b=JQB17YW307U7Y" style={{overflow:"hidden",width:"300px",height:"250px"}} frameborder="0"></iframe> </div> </center> :null } { config.show_auto_home_content_right_adv ? <center> <div> <iframe scrolling="no" src="https://coinad.com/ads/show/show.php?a=4XD7CSC96NFAP&b=JQB17YW307U7Y" style={{overflow:"hidden",width:"300px",height:"250px"}} frameborder="0"></iframe> </div> </center> :null } { config.show_moon_adv ? <center> <div> <iframe src="coinmedia.co/new_code_site13705.js" scrolling="no" frameborder="0" width="300px" height="250px"></iframe> </div> </center> :null } </div> <div className={classes.ad1}> { config.show_coinad_adv ? <center> <div> <iframe scrolling="no" src="https://coinad.com/ads/show/show.php?a=4XD7CSC96NFAP&b=JQB17YW307U7Y" style={{overflow:"hidden",width:"300px",height:"250px"}} frameborder="0"></iframe> </div> </center> :null } { config.show_auto_home_content_right_adv ? <center> <div> <iframe scrolling="no" src="https://coinad.com/ads/show/show.php?a=4XD7CSC96NFAP&b=JQB17YW307U7Y" style={{overflow:"hidden",width:"300px",height:"250px"}} frameborder="0"></iframe> </div> </center> :null } { config.show_moon_adv ? <center> <div> <iframe src="//coinmedia.co/new_code_site13705.js" scrolling="no" frameborder="0" width="300px" height="250px"></iframe> </div> </center> :null } </div> </div> </div> </div> <div className={classes.adv}> { config.show_coinad_adv ? <center> <div> <iframe scrolling="no" src="//coinad.com/ads/show/show.php?a=4XD7CSC96NFAP&b=CQE94BMJIJCKA" style={{overflow:"hidden",width:"728px",height:"90px"}} frameborder="0"></iframe> </div> </center> :null } { config.show_auto_home_content_right_adv ? <center> <div> <iframe scrolling="no" src="https://coinad.com/ads/show/show.php?a=4XD7CSC96NFAP&b=CQE94BMJIJCKA" style={{overflow:"hidden",width:"728px",height:"90px"}} frameborder="0"></iframe> </div> </center> :null } { config.show_moon_adv ? <center> <div> <iframe src="//coinmedia.co/new_code_site13704.js" scrolling="no" frameborder="0" width="728px" height="120px"></iframe> </div> </center> :null } </div> </div> ) } } export default HomeView;
node_modules/react-router/es/withRouter.js
SpatialMap/SpatialMapDev
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; import invariant from 'invariant'; import React from 'react'; import hoistStatics from 'hoist-non-react-statics'; import { ContextSubscriber } from './ContextUtils'; import { routerShape } from './PropTypes'; function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } export default function withRouter(WrappedComponent, options) { var withRef = options && options.withRef; var WithRouter = React.createClass({ displayName: 'WithRouter', mixins: [ContextSubscriber('router')], contextTypes: { router: routerShape }, propTypes: { router: routerShape }, getWrappedInstance: function getWrappedInstance() { !withRef ? process.env.NODE_ENV !== 'production' ? invariant(false, 'To access the wrapped instance, you need to specify ' + '`{ withRef: true }` as the second argument of the withRouter() call.') : invariant(false) : void 0; return this.wrappedInstance; }, render: function render() { var _this = this; var router = this.props.router || this.context.router; var params = router.params, location = router.location, routes = router.routes; var props = _extends({}, this.props, { router: router, params: params, location: location, routes: routes }); if (withRef) { props.ref = function (c) { _this.wrappedInstance = c; }; } return React.createElement(WrappedComponent, props); } }); WithRouter.displayName = 'withRouter(' + getDisplayName(WrappedComponent) + ')'; WithRouter.WrappedComponent = WrappedComponent; return hoistStatics(WithRouter, WrappedComponent); }
app/components/Threads/AddNew.js
Bullseyed/Bullseye
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Row, Col, Collapsible, CollapsibleItem, Input, Button, Modal, Icon } from 'react-materialize'; import axios from 'axios'; import { postThread } from '../../reducers/thread-reducer' import { Link } from 'react-router-dom' import AddNewThreadModal from './AddNewThreadModal' const AddNew = (props) => { return ( <Modal header='Propose a Business' trigger= { props.bullseye.length ? <Button large waves='light'><i className='material-icons left'>add_location</i>Propose a Business</Button> : <Button large disabled waves='light'><i className='material-icons left'>add_location</i>Propose a Business</Button> }> <AddNewThreadModal /> </Modal> ); } const mapStateToProps = ({bullseye}) => ({ bullseye }); export default connect(mapStateToProps, null)(AddNew);
src/components/Blocks/Cta/index.js
StudentRND/www
import React from 'react' import { graphql } from 'gatsby' import SmartLink from '../../Ui/SmartLink' import './index.sass' export default ({ text, ctaText, ctaLocation, ...props }) => ( <div className="cta-block"> <SmartLink to={ctaLocation}> <h2>{text}</h2> <span className="link">{ctaText}</span> </SmartLink> </div> ); export const query = graphql` fragment CtaBlockItems on ContentfulLayoutBlockCta { text ctaText ctaLocation } `;
docs/src/app/components/pages/components/IconMenu/ExampleScrollable.js
nathanmarks/material-ui
import React from 'react'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import IconButton from 'material-ui/IconButton/IconButton'; import MapsPlace from 'material-ui/svg-icons/maps/place'; const IconMenuExampleScrollable = () => ( <IconMenu iconButtonElement={<IconButton><MapsPlace /></IconButton>} anchorOrigin={{horizontal: 'left', vertical: 'top'}} targetOrigin={{horizontal: 'left', vertical: 'top'}} maxHeight={272} > <MenuItem value="AL" primaryText="Alabama" /> <MenuItem value="AK" primaryText="Alaska" /> <MenuItem value="AZ" primaryText="Arizona" /> <MenuItem value="AR" primaryText="Arkansas" /> <MenuItem value="CA" primaryText="California" /> <MenuItem value="CO" primaryText="Colorado" /> <MenuItem value="CT" primaryText="Connecticut" /> <MenuItem value="DE" primaryText="Delaware" /> <MenuItem value="DC" primaryText="District Of Columbia" /> <MenuItem value="FL" primaryText="Florida" /> <MenuItem value="GA" primaryText="Georgia" /> <MenuItem value="HI" primaryText="Hawaii" /> <MenuItem value="ID" primaryText="Idaho" /> <MenuItem value="IL" primaryText="Illinois" /> <MenuItem value="IN" primaryText="Indiana" /> <MenuItem value="IA" primaryText="Iowa" /> <MenuItem value="KS" primaryText="Kansas" /> <MenuItem value="KY" primaryText="Kentucky" /> <MenuItem value="LA" primaryText="Louisiana" /> <MenuItem value="ME" primaryText="Maine" /> <MenuItem value="MD" primaryText="Maryland" /> <MenuItem value="MA" primaryText="Massachusetts" /> <MenuItem value="MI" primaryText="Michigan" /> <MenuItem value="MN" primaryText="Minnesota" /> <MenuItem value="MS" primaryText="Mississippi" /> <MenuItem value="MO" primaryText="Missouri" /> <MenuItem value="MT" primaryText="Montana" /> <MenuItem value="NE" primaryText="Nebraska" /> <MenuItem value="NV" primaryText="Nevada" /> <MenuItem value="NH" primaryText="New Hampshire" /> <MenuItem value="NJ" primaryText="New Jersey" /> <MenuItem value="NM" primaryText="New Mexico" /> <MenuItem value="NY" primaryText="New York" /> <MenuItem value="NC" primaryText="North Carolina" /> <MenuItem value="ND" primaryText="North Dakota" /> <MenuItem value="OH" primaryText="Ohio" /> <MenuItem value="OK" primaryText="Oklahoma" /> <MenuItem value="OR" primaryText="Oregon" /> <MenuItem value="PA" primaryText="Pennsylvania" /> <MenuItem value="RI" primaryText="Rhode Island" /> <MenuItem value="SC" primaryText="South Carolina" /> <MenuItem value="SD" primaryText="South Dakota" /> <MenuItem value="TN" primaryText="Tennessee" /> <MenuItem value="TX" primaryText="Texas" /> <MenuItem value="UT" primaryText="Utah" /> <MenuItem value="VT" primaryText="Vermont" /> <MenuItem value="VA" primaryText="Virginia" /> <MenuItem value="WA" primaryText="Washington" /> <MenuItem value="WV" primaryText="West Virginia" /> <MenuItem value="WI" primaryText="Wisconsin" /> <MenuItem value="WY" primaryText="Wyoming" /> </IconMenu> ); export default IconMenuExampleScrollable;
src/icons/SignalWifi2BarLockIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class SignalWifi2BarLockIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path opacity=".3" d="M41 19c.7 0 1.4.1 2.1.2l4.2-5.2c-.9-.7-9.9-8-23.3-8S1.6 13.3.7 14L24 43l7-8.7V29c0-5.5 4.5-10 10-10z"/><path d="M46 32v-3c0-2.8-2.2-5-5-5s-5 2.2-5 5v3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2v-8c0-1.1-.9-2-2-2zm-2 0h-6v-3c0-1.7 1.3-3 3-3s3 1.3 3 3v3zM9.6 25L24 43l7-8.7V29c0-2.6 1-5 2.7-6.8C31.2 21 27.9 20 24 20c-8.2 0-13.7 4.5-14.4 5z"/></svg>;} };
assets/javascripts/kitten/components/action/button-group/stories.js
KissKissBankBank/kitten
import React from 'react' import { ButtonGroup } from './index' import { DocsPage } from 'storybook/docs-page' export default { title: 'Action/ButtonGroup', component: ButtonGroup, parameters: { docs: { page: () => <DocsPage filepath={__filename} importString="ButtonGroup" />, }, }, decorators: [ story => ( <div className="story-Container story-Grid story-Grid--large"> {story()} </div> ), ], argTypes: {}, args: {}, } export const Default = args => ( <ButtonGroup aria-label="Button label" {...args}> <ButtonGroup.Button>Button1</ButtonGroup.Button> <ButtonGroup.Button active modifier="helium"> Button2 </ButtonGroup.Button> <ButtonGroup.Button>Button3</ButtonGroup.Button> </ButtonGroup> )
examples/realtime/app.js
jjmulenex/sdk
/* global MAPBOX_API_KEY */ /** Realtime data example. */ import {createStore, combineReducers, applyMiddleware} from 'redux'; import thunkMiddleware from 'redux-thunk'; import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import RendererSwitch from '../rendererswitch'; import SdkZoomControl from '@boundlessgeo/sdk/components/map/zoom-control'; import SdkMapReducer from '@boundlessgeo/sdk/reducers/map'; import SdkMapboxReducer from '@boundlessgeo/sdk/reducers/mapbox'; import * as mapActions from '@boundlessgeo/sdk/actions/map'; import * as mapboxActions from '@boundlessgeo/sdk/actions/mapbox'; // This will have webpack include all of the SDK styles. import '@boundlessgeo/sdk/stylesheet/sdk.scss'; /* eslint-disable no-underscore-dangle */ const store = createStore(combineReducers({ map: SdkMapReducer, mapbox: SdkMapboxReducer, }), window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), applyMiddleware(thunkMiddleware)); function main() { const baseUrl = 'https://api.mapbox.com/styles/v1/mapbox/bright-v8'; store.dispatch(mapboxActions.configure({baseUrl, accessToken: MAPBOX_API_KEY})); // Start with a reasonable global view of the map. store.dispatch(mapActions.setView([-93, 45], 2)); // set the sprite so we can use icon-image store.dispatch(mapActions.setSprite('mapbox://sprites/mapbox/bright-v8')); // add the OSM source store.dispatch(mapActions.addOsmSource('osm')); // and an OSM layer. store.dispatch(mapActions.addLayer({ id: 'osm', source: 'osm', type: 'raster', })); const url = 'https://wanderdrone.appspot.com/'; // add our drone source store.dispatch(mapActions.addSource('drone', {type: 'geojson', data: url})); // add our drone layer with an icon-image from the sprite store.dispatch(mapActions.addLayer({ id: 'drone', type: 'symbol', source: 'drone', layout: { 'icon-image': 'rocket-15' } })); // update the data every 2 seconds window.setInterval(function() { store.dispatch(mapActions.updateSource('drone', {data: url})); }, 2000); // place the map on the page. ReactDOM.render(<Provider store={store}> <RendererSwitch> <SdkZoomControl /> </RendererSwitch> </Provider>, document.getElementById('map')); } main();
src/components/icons/ArrowForward.js
austinknight/ui-components
import React from 'react'; export default function ArrowForward(props) { return ( <svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" > {props.title && <title>{props.title}</title>} <path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z" /> </svg> ); }
src/class/popup/Button.js
MrMamen/traktflix
import PropTypes from 'prop-types'; import React from 'react'; import ErrorBoundary from '../ErrorBoundary'; class Button extends React.Component { constructor(props) { super(props); } handleClick() { browser.tabs.create({url: this.props.url, active: true}); } render() { return ( <ErrorBoundary> <button onClick={this.handleClick.bind(this)} className='mdl-button mdl-js-button mdl-button--raised mdl-button--colored mdl-js-ripple-effect'> {this.props.text} </button> </ErrorBoundary> ); } } Button.propTypes = { text: PropTypes.string.isRequired, url: PropTypes.string.isRequired }; export default Button;
src/Parser/VengeanceDemonHunter/Modules/Statistics/Spells/SigilOfFlame.js
mwwscott0/WoWAnalyzer
import React from 'react'; import Module from 'Parser/Core/Module'; import AbilityTracker from 'Parser/Core/Modules/AbilityTracker'; import Enemies from 'Parser/Core/Modules/Enemies'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage, formatThousands, formatDuration } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; class SigilOfFlame extends Module { static dependencies = { abilityTracker: AbilityTracker, enemies: Enemies, }; statistic() { const sigilOfFlameUptime = this.enemies.getBuffUptime(SPELLS.SIGIL_OF_FLAME_DEBUFF.id); const sigilOfFlameUptimePercentage = sigilOfFlameUptime / this.owner.fightDuration; const sigilOfFlameDamage = this.abilityTracker.getAbility(SPELLS.SIGIL_OF_FLAME_DEBUFF.id).damageEffective; return ( <StatisticBox icon={<SpellIcon id={SPELLS.SIGIL_OF_FLAME.id} />} value={`${formatPercentage(sigilOfFlameUptimePercentage)}%`} label="Sigil of Flame Uptime" tooltip={`The Sigil of Flame total damage was ${formatThousands(sigilOfFlameDamage)}.<br/>The Sigil of Flame total uptime was ${formatDuration(sigilOfFlameUptime / 1000)}.`} /> ); } statisticOrder = STATISTIC_ORDER.CORE(9); } export default SigilOfFlame;
packages/cf-component-card/src/CardToolbar.js
jroyal/cf-ui
import React from 'react'; import PropTypes from 'prop-types'; import { createComponent } from 'cf-style-container'; const styles = ({ theme }) => ({ borderTop: `1px solid ${theme.colorGrayLight}`, minHeight: '2.96666rem', '&:first-child': { borderTop: 'initial' }, '&::after': { content: "''", display: 'table', clear: 'both' } }); const Links = createComponent( () => ({ float: 'right' }), 'div', ['role'] ); const CardToolbar = ({ className, controls, links }) => ( <div className={className}> <div>{controls}</div> <Links role="tablist"> {links} </Links> </div> ); CardToolbar.propTypes = { className: PropTypes.string, controls: PropTypes.any, links: PropTypes.any }; export default createComponent(styles, CardToolbar);
src/js/components/nodes/registerNodes/NodesFileUpload.js
knowncitizen/tripleo-ui
/** * Copyright 2017 Red Hat Inc. * * 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 { Button } from 'react-bootstrap'; import { injectIntl, defineMessages, FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import React from 'react'; const messages = defineMessages({ invalidJson: { id: 'RegisterNodesDialog.invalidJson', defaultMessage: 'Invalid JSON' }, csvUnsupported: { id: 'RegisterNodesDialog.csvUnsupported', defaultMessage: 'CSV Upload Unsupported' }, selectedFileUnsupported: { id: 'RegisterNodesDialog.selectedFileUnsupported', defaultMessage: 'The selected file format is not supported yet.' }, unsupportedFileFormat: { id: 'RegisterNodesDialog.unsupportedFileFormat', defaultMessage: 'Unsupported File Format' }, provideCsvOrInstackenvJson: { id: 'RegisterNodesDialog.provideCsvOrInstackenvJson', defaultMessage: 'Please provide a CSV file or instackenv.json.' }, uploadFromFile: { id: 'RegisterNodesDialog.uploadFromFile', defaultMessage: 'Upload From File' } }); class NodesFileUpload extends React.Component { addNodesFromInstackenvJSON(fileContents) { const { addNode, intl: { formatMessage }, notify } = this.props; try { const nodes = JSON.parse(fileContents).nodes; nodes.map(node => addNode(node)); } catch (e) { notify({ title: formatMessage(messages.invalidJson), message: e.toString() }); } } uploadFromFile(event) { const { intl: { formatMessage }, notify } = this.props; const file = event.target.files[0]; const reader = new FileReader(); reader.onload = (f => e => { if (file.name.match(/(\.json)$/)) { this.addNodesFromInstackenvJSON(e.target.result); } else if (file.name.match(/(\.csv)$/)) { // TODO(jtomasek): add CSV file support // this.addNodesFromCSV(e.target.result); notify({ title: formatMessage(messages.csvUnsupported), message: formatMessage(messages.selectedFileUnsupported) }); } else { notify({ title: formatMessage(messages.unsupportedFileFormat), message: formatMessage(messages.provideCsvOrInstackenvJson) }); } })(file); reader.readAsText(file); this.refs.regNodesUploadFileForm.reset(); } render() { return ( <Button onClick={() => this.refs.regNodesUploadFileInput.click()}> <FormattedMessage {...messages.uploadFromFile} /> <form ref="regNodesUploadFileForm"> <input style={{ display: 'none' }} ref="regNodesUploadFileInput" id="regNodesUploadFileInput" type="file" accept="text/json" onChange={this.uploadFromFile.bind(this)} /> </form> </Button> ); } } NodesFileUpload.propTypes = { addNode: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, notify: PropTypes.func.isRequired }; export default injectIntl(NodesFileUpload);
packages/ringcentral-widgets-docs/src/app/pages/Components/ConferenceAlert/Demo.js
ringcentral/ringcentral-js-widget
import React from 'react'; // eslint-disable-next-line import ConferenceAlert from 'ringcentral-widgets/components/AlertRenderer/ConferenceAlert'; const props = {}; props.currentLocale = 'en-US'; props.message = { message: 'test string', }; /** * A example of `ConferenceAlert` */ const ConferenceAlertDemo = () => <ConferenceAlert {...props} />; export default ConferenceAlertDemo;
example/src/app.js
johnnycx127/react-geosuggest-baidu
import React from 'react'; import ReactDOM from 'react-dom'; import Geosuggest from '../../src/Geosuggest'; var App = React.createClass({ // eslint-disable-line /** * Render the example app * @return {Function} React render function */ render: function() { return ( // eslint-disable-line <div> <Geosuggest onFocus={this.onFocus} onBlur={this.onBlur} onChange={this.onChange} onSuggestSelect={this.onSuggestSelect} region="北京市" radius="20" /> </div> ); }, /** * When the input receives focus */ onFocus: function() { console.log('onFocus'); // eslint-disable-line }, /** * When the input loses focus * @param {String} value The user input */ onBlur: function(value) { console.log('onBlur', value); // eslint-disable-line }, /** * When the input got changed * @param {String} value The new value */ onChange: function(value) { console.log('input changes to :' + value); // eslint-disable-line }, /** * When a suggest got selected * @param {Object} suggest The suggest */ onSuggestSelect: function(suggest) { console.log(suggest); // eslint-disable-line } }); ReactDOM.render(<App />, document.getElementById('app')); // eslint-disable-line
resources/js/Admin/Faq.js
DoSomething/northstar
import React from 'react'; import Layout from './components/Layout'; import NoteCard from '../components/Card/NoteCard'; const Faq = () => ( <article className="base-12-grid pb-20 pt-8"> <h1 className="col-span-full font-bold mb-10 text-2xl uppercase">FAQ</h1> <div className="col-span-6"> {/* DS Admin Info Section */} <section> <h2 id="what-is-dosomething-admin" className="font-bold mb-6 text-lg"> What is DoSomething Admin? </h2> <p className=""> DoSomething Admin (formerly Northstar Admin) is an internal tool where staff and interns review and view more information about campaign actions. It is the tool you should use when looking for content for a sponsor, decks, media, etc! </p> <p className="mt-4"> Additionally, DoSomething Admin is the source of truth for all member activity (signups, posts, impact) and campaign/action metadata. Member activity from DoSomething Admin is sent to Looker and powers all campaign dashboards. </p> </section> {/* Common Terms Definition Section */} <section className="mt-12"> <h2 id="can-I-get-some-defintions" className="font-bold mb-6 text-lg"> Can I get some definitions? </h2> <p> We know there's a lot of terms flying around, so below you can find some definitions for some of the most common terms you will here. </p> <dl className="mt-8"> <dt className="font-bold text-purple-500">Signup</dt> <dd className="mt-2"> A signup is created in two ways. The first way is when a user signs up for a campaign. The second way is when a user completes an action that automatically creates the sign up. For example, on the ungated Prom Map experience, if the user signs the petition or submits a story, when the post is submitted, a signup is also made at the same time. Text posts over SMS are another example of when the signup is created at the same time as the post. </dd> <dt className="font-bold mt-8 text-purple-500">Why participated</dt> <dd className="mt-2"> The "why participated" is the reason a user submits explaining why they took action in the campaign. A user can only have one "why participated" for the campaign, which means that while a user may submit multiple posts for a campaign, they only have one "why participated." The rationale behind this was that they're saying why they participated in the overall campaign, not why they decided to take and upload that photo or tip. If a user submits a new "why participated" their previous "why participated" is replaced with this new submission. </dd> <dt className="font-bold mt-8 text-purple-500">Post</dt> <dd> A post is created every time a user submits proof that they took action on a campaign. A user can submit multiple posts for one campaign. For example, a user signs up for Teens for Jeans and submits 5 photos. The user has 1 signup, 5 posts, and 1 reportback. We have many different types of posts, including: text posts, photo posts, call posts, and voter registration posts. </dd> <dt className="font-bold mt-8 text-purple-500">Quantity</dt> <dd> This is the total number of X a user did (i.e. how many items collected). There is one quantity for a member for a given campaign. If on the first submission they tell us they did 50 and then in the second submission they tell us 200, their total quantity is 250. We know both the quantity per submission and the total quantity for the campaign. </dd> <dt className="font-bold mt-8 text-purple-500">Reportback</dt> <dd> This is an internal term. If a member submits proof of their action (a post), they have reported back. If a member sends in multiple proofs of their action (posts), this is still just one reportback. </dd> </dl> <p> Here's a visualization of how things get into the system and are structured: </p> <img src="https://images.ctfassets.net/81iqaqpfd8fy/6hAMqF2PfcFX9p2GICR87F/c73dc36d02d74839bc814488d789d84e/Rogue_RB_Flow_Diagram.jpg" alt="Reportback flow diagram" /> </section> {/* About Tags Section */} <section className="mt-12"> <h2 id="why-are-tags-important" className="font-bold mb-6 text-lg"> Why are tags important? </h2> <p> They're important because they allow admins to search for posts that fit a certain criteria and they allow us to identify trends, i.e., a lot of people are putting in unrealistic quantities or aren't completing the action which could be a result of unclear website instructions. </p> </section> {/* Tags Definition Section */} <section className="mt-12"> <h2 id="what-do-the-different-tags-mean" className="font-bold mb-6 text-lg" > What do the different tags mean? </h2> <p> After selecting a status (<strong>Approve</strong> or{' '} <strong>Reject</strong>), you are able to apply tags. All of these tags were created from campaign, marketing or business development requests. </p> <p className="mt-4"> <b> It's important to add tags as you're reviewing because other people can filter by tags on the Campaign Filtering page to find what they're looking for! </b> </p> <p className="mt-4"> When you tag something as "Good for X" it will show up in the #badass-members Slack channel. </p> <dl className="mt-8"> <dt className="font-bold mt-8 text-purple-500">Good Submission</dt> <dd className="mt-2"> <span>Use this if the overall submission is good.</span> <NoteCard className="bg-gray-200 mt-4 italic" type="information"> <p> Note: we are running a test starting in June 2019 where users who are opted into the badge experiment will get a "Staff Fave" badge in their user profile if their submission has been tagged "Good Submission." You don't need to do anything special for this as this will happen automatically in the experiment. </p> </NoteCard> </dd> <dt className="font-bold mt-8 text-purple-500">Good Quote</dt> <dd className="mt-2">Use this if the text is good.</dd> <dt className="font-bold mt-8 text-purple-500">Hide in Gallery</dt> <dd className="mt-2"> <span> Hides submission from the gallery, does NOT exclude the impact. </span> <div> <p> Sometimes the submission will accurately reflect the CTA and have a realistic impact, but you might not want to show it in the public, web gallery! Use the 'Hide in Gallery' for various reasons, including: </p> <ul className=""> <li> The submission is not clear but you want to count the impact. </li> <li> The submission does not fully reflect the CTA but you want to count the impact. </li> <li> You want to count the impact, but the caption may include language or personal information about a user (i.e. email address) that shouldn't be shown in the public gallery. </li> </ul> </div> </dd> <dt className="font-bold mt-8 text-purple-500">Good for Sponsor</dt> <dd className="mt-2"> Use this if the submission meets any asks the sponsor has made. For example, if Company A wants to see people outside only, you can use this tag on submissions where people are outside. </dd> <dt className="font-bold mt-8 text-purple-500"> Good for Storytelling </dt> <dd className="mt-2"> A tag request from the Impact team - these are submissions that show good impact and member activity. The Impact team will use this tag when looking for things for the Gala or other decks. This is overall a better submission than what you would tag as "Good Submission." You will likely use this one sparingly. </dd> <dt className="font-bold mt-8 text-purple-500">Irrelevant</dt> <dd className="mt-2"> Use this if the submission has nothing to do with the campaign (i.e. a cat photo for Teens for Jeans). </dd> <dt className="font-bold mt-8 text-purple-500">Inappropriate</dt> <dd className="mt-2"> Use this if there is inappropriate content (i.e. middle finger in the background of the image). If you're Accepting the submission, remember to use "Hide in Gallery" so that it doesn't show up in the public web gallery. </dd> <dt className="font-bold mt-8 text-purple-500"> Unrealistic Quantity </dt> <dd className="mt-2"> Use this if someone has put a ridiculously high number in the quantity field (i.e. they said they created 1 million Love Letters and it’s a selfie). You can tag as unrealistic quantity, but you'd still want to update the quantity to correct it! </dd> <dt className="font-bold mt-8 text-purple-500">Test</dt> <dd className="mt-2"> Use this if it’s a DS individual who’s submitting tests. (i.e., the quote or caption says "test" or the member email is{' '} <span className="font-mono text-gray-700">@dosomething.org</span> or{' '} <span className="font-mono text-gray-700">@test.com</span>). </dd> <dt className="font-bold mt-8 text-purple-500">Incomplete Action</dt> <dd className="mt-2"> Use this if someone didn’t complete the action. </dd> <dt className="font-bold mt-8 text-purple-500">Bulk</dt> <dd className="mt-2"> This is used when a developer automatically bulk approves submissions. This has happened in the past for text post campaigns. </dd> <dt className="font-bold mt-8 text-purple-500">Good for Brand</dt> <dd className="mt-2"> Use this if the submission clearly highlights a brand or brands. </dd> <dt className="font-bold mt-8 text-purple-500">Group Photo:</dt> <dd className="mt-2">Use this if it's a group photo.</dd> <dt className="font-bold mt-8 text-purple-500">Social</dt> <dd className="mt-2"> Use this if submission is a screenshot of a guide/checklist shared on social media. </dd> </dl> </section> <hr className="border-0 bg-gray-300 h-px my-12" /> {/* Questions */} <p id="got-questions"> <i> Got questions that aren't answered here or in the documentation linked above? Please ask in the{' '} <a href="https://dosomething.slack.com/archives/C09ANFQLA" className="text-blurple-500 hover:text-blurple-200 hover:underline" target="_blank" > #help-product </a>{' '} channel! </i> </p> </div> {/* Table Of Contents Links */} <aside className="col-span-4 col-start-8"> <div className="sticky" style={{ top: '20px' }}> <h2 className="text-gray-500 text-sm uppercase">On this page</h2> <ul className="mt-4"> <li> <a href="#what-is-dosomething-admin" className="hover:text-blurple-500 hover:underline" > What is DoSomething Admin? </a> </li> <li className="mt-2"> <a href="#can-I-get-some-defintions" className="hover:text-blurple-500 hover:underline" > Can I get some definitions? </a> </li> <li className="mt-2"> <a href="#why-are-tags-important" className="hover:text-blurple-500 hover:underline" > Why are tags important? </a> </li> <li className="mt-2"> <a href="#what-do-the-different-tags-mean" className="hover:text-blurple-500 hover:underline" > What do the different tags mean? </a> </li> <li className="mt-2"> <a href="#got-questions" className="hover:text-blurple-500 hover:underline" > Got questions? </a> </li> </ul> </div> </aside> </article> ); Faq.layout = page => <Layout children={page} title="FAQ" />; export default Faq;
src/Toolbox.js
colinmorris/SongSim
import React, { Component } from 'react'; import Clipboard from 'clipboard'; import './Toolbox.css'; import config from './config.js'; import {MODE, MODE_TOOLTIPS} from './constants.js'; // TODO: is this really the orthodox way to do this? :/ new Clipboard('#perma'); /** * Contains a bunch of controls for stuff like: * - setting matrix coloring mode * - whether to ignore singletons * - saving svg file * - sharing/permalinks * Separating this stuff into a component separate from Songsim involves some * spooky action at a distance, but I think it's worth it to simplify Songsim, * particularly its render method. */ class Toolbox extends Component { renderModeRadio = (mode_key) => { var mode = MODE[mode_key]; var tt = MODE_TOOLTIPS[mode_key]; // TODO: Really when we get a change to state.verse, we should see if // the new verse is custom && mode is color_title, and if so, we should // automatically switch to a different mode. But bleh. var disabled = (mode === MODE.color_title && (!this.props.verse || !this.props.verse.title)); var divCname = disabled ? "radio-inline disabled" : "radio-inline"; return ( <label title={tt} key={mode} className={divCname}> <input type="radio" disabled={disabled} checked={this.props.mode === mode} value={mode} onChange={(e) => { this.props.onStateChange({mode: e.target.value}) }} name="mode" /> {mode} </label> ); } renderSingletonRadios = () => { var singstop = [this.props.ignoreSingletons, this.props.ignore_stopwords]; var modes = [ {label: 'show all', ss: [false, false]}, {label: 'ignore all', ss: [true, false]}, {label: 'ignore stopwords', ss: [false, true], tt: 'Show single-word matches, unless they\'re common words like "the" or "and"'}, ]; var radios = []; for (let mode of modes) { radios.push(( <label className="radio-inline" key={mode.label} title={mode.tt}> <input type="radio" checked={singstop[0] === mode.ss[0] && singstop[1] === mode.ss[1]} value={mode.ss} onChange={(e) => { this.props.onStateChange({ignore_singletons: mode.ss[0], ignore_stopwords: mode.ss[1]}); }} /> {mode.label} </label> )); } return ( <fieldset> <legend title="How to treat individual squares floating off the main diagonal"> Single-word matches </legend> {radios} </fieldset> ); } renderMobileCheckbox = () => { return ( <label className="checkbox-inline" title="(Janky) UI intended for small screens" > <input type="checkbox" checked={this.props.mobile} onChange={(e) => { this.props.onStateChange({mobile: e.target.checked}); }} /> Mobile mode </label> ); } renderSave = () => { if (!this.props.mobile && this.props.verse && config.exportSVGEnabled && this.props.exportSVG) { return ( <button className="btn" onClick={this.props.exportSVG} title="Save matrix as SVG file" > <span className="glyphicon glyphicon-save" /> </button> ); } } renderPermalink = () => { if (this.props.mobile || !(this.props.verse && this.props.verse.isCustom() && !this.props.verse.isBlank())) { return; } var perma = this.props.verse.get_permalink(this.props.router); if (perma) { return ( <label className="form-inline"> Permalink: <input type="text" readOnly={true} value={perma} /> <button id="perma" className="btn" data-clipboard-text={perma}> <span className="glyphicon glyphicon-copy" title="copy" /> </button> </label> ); } else { return ( <button className="btn" onClick={this.props.onShare} title="Generate a shareable permalink for this song" > Permalink </button> ); } } render() { var moderadios = Object.keys(MODE).map(this.renderModeRadio); var kls = this.props.mobile ? "" : "form-horizontal"; kls += ' toolbox'; kls = 'form-horizontal toolbox'; //kls = 'row toolbox'; var radioKls = 'col-xs-12 col-md-6 col-lg-4'; return ( <div className={kls}> <div className={radioKls}> <fieldset> <legend> Color Mode </legend> {moderadios} </fieldset> </div> <div className={radioKls}> {this.renderSingletonRadios()} </div> <div className='col-xs-5 col-md-4 col-lg-2'> {this.renderMobileCheckbox()} </div> <div className='col-xs-3 col-md-2 col-lg-1'> {this.renderSave()} </div> <div className='col-xs-8 col-md-6'> {this.renderPermalink()} </div> </div> ); } } Toolbox.propTypes = { verse: React.PropTypes.object, } export default Toolbox;
src/svg-icons/action/bug-report.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionBugReport = (props) => ( <SvgIcon {...props}> <path d="M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z"/> </SvgIcon> ); ActionBugReport = pure(ActionBugReport); ActionBugReport.displayName = 'ActionBugReport'; ActionBugReport.muiName = 'SvgIcon'; export default ActionBugReport;
src/routes/chart/barChart/index.js
tigaly/antd-admin
import React from 'react' import PropTypes from 'prop-types' import { Row, Col, Card, Button } from 'antd' import Container from '../Container' import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, } from 'recharts' const data = [ { name: 'Page A', uv: 4000, pv: 2400, amt: 2400, }, { name: 'Page B', uv: 3000, pv: 1398, amt: 2210, }, { name: 'Page C', uv: 2000, pv: 9800, amt: 2290, }, { name: 'Page D', uv: 2780, pv: 3908, amt: 2000, }, { name: 'Page E', uv: 1890, pv: 4800, amt: 2181, }, { name: 'Page F', uv: 2390, pv: 3800, amt: 2500, }, { name: 'Page G', uv: 3490, pv: 4300, amt: 2100, }, ] const mixData = [ { name: 'Page A', uv: 4000, female: 2400, male: 2400, }, { name: 'Page B', uv: 3000, female: 1398, male: 2210, }, { name: 'Page C', uv: 2000, female: 9800, male: 2290, }, { name: 'Page D', uv: 2780, female: 3908, male: 2000, }, { name: 'Page E', uv: 1890, female: 4800, male: 2181, }, { name: 'Page F', uv: 2390, female: 3800, male: 2500, }, { name: 'Page G', uv: 3490, female: 4300, male: 2100, }, ] const colProps = { lg: 12, md: 24, } const SimpleBarChart = () => ( <Container> <BarChart data={data} margin={{ top: 5, right: 30, left: 20, bottom: 5, }}> <XAxis dataKey="name" /> <YAxis /> <CartesianGrid strokeDasharray="3 3" /> <Tooltip /> <Legend /> <Bar dataKey="pv" fill="#8884d8" /> <Bar dataKey="uv" fill="#82ca9d" /> </BarChart> </Container> ) const StackedBarChart = () => ( <Container> <BarChart data={data} margin={{ top: 20, right: 30, left: 20, bottom: 5, }}> <XAxis dataKey="name" /> <YAxis /> <CartesianGrid strokeDasharray="3 3" /> <Tooltip /> <Legend /> <Bar dataKey="pv" stackId="a" fill="#8884d8" /> <Bar dataKey="uv" stackId="a" fill="#82ca9d" /> </BarChart> </Container> ) const MixBarChart = () => ( <Container> <BarChart data={mixData} margin={{ top: 20, right: 30, left: 20, bottom: 5, }}> <XAxis dataKey="name" /> <YAxis /> <CartesianGrid strokeDasharray="3 3" /> <Tooltip /> <Legend /> <Bar dataKey="female" stackId="a" fill="#8884d8" /> <Bar dataKey="male" stackId="a" fill="#82ca9d" /> <Bar dataKey="uv" fill="#ffc658" /> </BarChart> </Container> ) // CustomShapeBarChart const getPath = (x, y, width, height) => { return `M${x},${y + height} C${x + width / 3},${y + height} ${x + width / 2},${y + height / 3} ${x + width / 2}, ${y} C${x + width / 2},${y + height / 3} ${x + 2 * width / 3},${y + height} ${x + width}, ${y + height} Z` } const TriangleBar = (props) => { const { fill, x, y, width, height } = props return <path d={getPath(x, y, width, height)} stroke="none" fill={fill} /> } TriangleBar.propTypes = { fill: PropTypes.string, x: PropTypes.number, y: PropTypes.number, width: PropTypes.number, height: PropTypes.number, } const CustomShapeBarChart = () => ( <Container> <BarChart data={mixData} margin={{ top: 20, right: 30, left: 20, bottom: 5, }}> <XAxis dataKey="name" /> <YAxis /> <CartesianGrid strokeDasharray="3 3" /> <Bar dataKey="female" fill="#8884d8" shape={< TriangleBar />} label /> </BarChart> </Container> ) const EditorPage = () => ( <div className="content-inner"> <Button type="primary" size="large" style={{ position: 'absolute', right: 0, top: -48, }}> <a href="http://recharts.org/#/en-US/examples/TinyBarChart" target="blank">Show More</a> </Button> <Row gutter={32}> <Col {...colProps}> <Card title="SimpleBarChart"> <SimpleBarChart /> </Card> </Col> <Col {...colProps}> <Card title="StackedBarChart"> <StackedBarChart /> </Card> </Col> <Col {...colProps}> <Card title="MixBarChart"> <MixBarChart /> </Card> </Col> <Col {...colProps}> <Card title="CustomShapeBarChart"> <CustomShapeBarChart /> </Card> </Col> </Row> </div> ) export default EditorPage
src/components/nit-list/index.js
WHCIBoys/nitpik-web
import React from 'react'; import Nit from './nit'; import * as C from '../../constants'; import * as I from 'immutable'; function NitList({ nitList }) { return ( <div> <h2 data-testid="home-heading" className="center caps" style={{color: C.grey500}} id="qa-counter-heading">Nits</h2> <div className="flex flex-wrap"> { nitList.map((nit, i) => { return <Nit key={i} content={nit.get('content')}/>; }) } </div> </div> ); } NitList.propTypes = { nitList: React.PropTypes.instanceOf(I.List), isVisible: React.PropTypes.bool, }; export default NitList;
src/components/notebook.js
OpenChemistry/mongochemclient
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Iframe from 'react-iframe' import { Typography, withStyles } from '@material-ui/core'; import PageHead from './page-head'; import PageBody from './page-body'; const styles = () => ({ iframe: { border: 0, left: 0, position: 'absolute', top: 0, width:'100%', height:'100%' }, container: { overflow: 'hidden', position: 'relative', paddingTop: '100%' } }); class Notebook extends Component { render = () => { const { fileId, classes } = this.props; const baseUrl = `${window.location.origin}/api/v1`; return ( <div> <PageHead> <Typography color="inherit" gutterBottom variant="display1"> Notebook </Typography> </PageHead> <PageBody> <div className={classes.container}> <Iframe id='iframe' url={`${baseUrl}/notebooks/${fileId}/html`} className={classes.iframe}/> </div> </PageBody> </div> ); } } Notebook.propTypes = { fileId: PropTypes.string } Notebook.defaultProps = { fileId: null, } export default withStyles(styles)(Notebook)
pkg/ui/src/i18n/help-text/index.js
matt-deboer/kuill
import React from 'react' import IconButton from 'material-ui/IconButton' import IconHelp from 'material-ui/svg-icons/action/help-outline' import en from './en' var localeMap = {en: en} async function textForLocale(locale) { if (locale in localeMap) { return localeMap[locale] } else { // code-split loading of locales let resolvedLocale = await import(`./${locale}`).catch(error => { return 'en' }).then(helpText => { localeMap[locale] = helpText return locale }) // return locale from the map return localeMap[resolvedLocale] } } const styles = { button: { padding: 0, height: 18, width: 18, }, icon: { color: 'rgba(180,180,180,0.5)', height: 20, width: 20, } } export default class HelpText extends React.Component { constructor(props) { super(props) this.state = { open: false, } } componentDidMount = () => { let { textId } = this.props textForLocale(this.props.locale).then(locale => { this.setState({ text: locale[textId] }) }) } render() { let { textId, style, iconStyle, orientation } = this.props let normalizedId = `help-text-contents--${textId}` let hintPosition = orientation || 'top' return ( <div style={{...style}}> <IconButton style={{...styles.button}} iconStyle={{...styles.icon, ...iconStyle}} data-rh={`#${normalizedId}`} data-rh-at={hintPosition}> <IconHelp /> </IconButton> <div id={normalizedId} style={{display: 'none'}}> <div className={'help-text-contents'} style={{maxWidth: '300px'}}> {this.state.text} </div> </div> </div> ) } }
src/svg-icons/hardware/laptop-mac.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareLaptopMac = (props) => ( <SvgIcon {...props}> <path d="M20 18c1.1 0 1.99-.9 1.99-2L22 5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2H0c0 1.1.9 2 2 2h20c1.1 0 2-.9 2-2h-4zM4 5h16v11H4V5zm8 14c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z"/> </SvgIcon> ); HardwareLaptopMac = pure(HardwareLaptopMac); HardwareLaptopMac.displayName = 'HardwareLaptopMac'; HardwareLaptopMac.muiName = 'SvgIcon'; export default HardwareLaptopMac;
src/svg-icons/action/settings-overscan.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsOverscan = (props) => ( <SvgIcon {...props}> <path d="M12.01 5.5L10 8h4l-1.99-2.5zM18 10v4l2.5-1.99L18 10zM6 10l-2.5 2.01L6 14v-4zm8 6h-4l2.01 2.5L14 16zm7-13H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16.01H3V4.99h18v14.02z"/> </SvgIcon> ); ActionSettingsOverscan = pure(ActionSettingsOverscan); ActionSettingsOverscan.displayName = 'ActionSettingsOverscan'; ActionSettingsOverscan.muiName = 'SvgIcon'; export default ActionSettingsOverscan;
src/frontend/react/components/Nav.js
FakeYou/voerr
import React from 'react'; import connectToStores from 'alt/utils/connectToStores'; import ClassNames from 'classnames'; import { Link } from 'react-router'; import { contains } from 'lodash'; import LoginStore from 'flux/stores/LoginStore'; import LoginActions from 'flux/actions/LoginActions'; import 'assets/style/nav'; @connectToStores export default class Nav extends React.Component { static getStores(props) { return [LoginStore]; } static getPropsFromStores(props) { return LoginStore.getState(); } constructor() { super(); this.state = { showSearch: false, navOpen: false }; } onClickHamburger() { this.setState({ navOpen: !this.state.navOpen }); } onLogout() { LoginActions.requestLogout(); } componentWillMount() { } render() { let ulClasses = ClassNames({ open: this.state.navOpen }); let links; if(this.props.user) { let price = (this.props.user.credit / 100).toFixed(2).replace('.', ','); links = [ <li key="account"><Link to='/account'>{this.props.user.name}</Link></li>, <li key="credit" className="highlight">&euro;{price}</li>, <li key="split" className="highlight hidden">|</li>, <li key="logout"><a href='#' onClick={this.onLogout.bind(this)}>Uitloggen</a></li> ]; } else { links = [ <li key="login"><Link to='/inloggen'>Inloggen</Link></li>, <li key="register"><Link to='/registeren'>Registeren</Link></li>, <li key="how"><a href='#'>Hoe het werkt</a></li> ]; } return ( <div className="nav"> <h1><Link to="/">voerr</Link></h1> <nav onClick={this.onClickHamburger.bind(this)}> <ul className={ulClasses}> <li className="header"><h2>voerr</h2></li> {links} </ul> </nav> </div> ); } }
client/src/index.js
mozillaSv/TweetGeoViz
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import routes from './routes.js'; import store from './stores/appStore.js'; // <--- dispatch init actions HERE ReactDOM.render( <Provider store={store}> {routes} </Provider>, document.getElementById('app') );
App/Containers/YakViewContainer.js
bretth18/bison
// This is our redux wrapper for the YakView component. // it injects the state and dispatch functions via props. 'use strict'; import { View } from 'react-native'; import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import YakView from '../Components/YakView'; import * as YakActions from '../Actions/addYak'; import * as YakViewActions from '../Actions/addComment'; class YakViewContainer extends Component { render() { return ( <YakView {...this.props} /> ); } } function mapStateToProps(state) { return { commentList: state.yakView.commentList, // score: state.yakView.yakScore, }; } function mapDispatchToProps(dispatch) { return bindActionCreators(YakViewActions, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(YakViewContainer);
src/RelativeSize.js
dunnock/react-sigma
// @flow import React from 'react' import '../sigma/plugins.relativeSize' type Props = { initialSize: number, sigma?: sigma }; /** RelativeSize component, interface for RelativeSize 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 NeoCypher. Sets nodes sizes corresponding its degree. @param {number} initialSize start size for every node, will be multiplied by Math.sqrt(node.degree) **/ class RelativeSize extends React.Component<Props> { constructor(props: Props) { super(props) sigma.plugins.relativeSize(this.props.sigma, this.props.initialSize) } render = () => null } export default RelativeSize;
client/src/app/views/userProfile.js
jhuntoo/starhackit
import _ from 'lodash'; import React from 'react'; import Reflux from 'reflux'; import { History } from 'react-router'; import userActions from 'actions/user'; import userProfileStore from 'stores/userProfile'; import authStore from 'stores/auth'; import UserAvatar from 'components/userAvatar'; import MarkedDisplay from 'components/markedDisplay'; import Spinner from 'components/spinner'; export default React.createClass( { statics: { willTransitionTo: function ( transition, params ) { userActions.getProfile( params.id ); } }, mixins: [ History, Reflux.connect( userProfileStore, 'user' ) ], getInitialState() { return { display: { addFriend: true } }; }, render() { return ( <div id="user-profile"> { this.renderLoading() } { this.renderUserProfile() } </div> ); }, renderUserProfile() { let user = this.state.user; if ( this.pageIsForUser() ) { return ( <div className="user-profile"> <legend>{ user.name } Public Profile</legend> <div className="profile-avatar"> <UserAvatar user={ user } /> </div> { user.about && <div className="compact"> <MarkedDisplay content={ user.about } /> </div> } </div> ); } }, renderLoading() { if ( !(this.pageIsForUser()) ) { return <Spinner />; } }, pageIsForUser() { let requested = Number( this.getParams().id ); let got = Number( _.get( this.state.user, 'id' ) ); return requested === got; }, isNotMe() { return !(authStore.isMyId( _.get( this.state.user, 'id' ) )); }, notifySent() { $.bootstrapGrowl( `Friend Request Sent to ${this.state.user.name}`, { type: 'warning', delay: 5000 } ); }, showError( e ) { if ( e.status === 422 ) { $.bootstrapGrowl( `Friend Request has already been sent to ${this.state.user.name}`, { type: 'danger', delay: 5000 } ); } else { $.bootstrapGrowl( 'Unknown error has occurred. Please contact us on our Facebook Page or sub-Reddit; links are in the home page', { type: 'danger', delay: 5000 } ); } } } );
src/svg-icons/device/gps-off.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceGpsOff = (props) => ( <SvgIcon {...props}> <path d="M20.94 11c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06c-1.13.12-2.19.46-3.16.97l1.5 1.5C10.16 5.19 11.06 5 12 5c3.87 0 7 3.13 7 7 0 .94-.19 1.84-.52 2.65l1.5 1.5c.5-.96.84-2.02.97-3.15H23v-2h-2.06zM3 4.27l2.04 2.04C3.97 7.62 3.25 9.23 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c1.77-.2 3.38-.91 4.69-1.98L19.73 21 21 19.73 4.27 3 3 4.27zm13.27 13.27C15.09 18.45 13.61 19 12 19c-3.87 0-7-3.13-7-7 0-1.61.55-3.09 1.46-4.27l9.81 9.81z"/> </SvgIcon> ); DeviceGpsOff = pure(DeviceGpsOff); DeviceGpsOff.displayName = 'DeviceGpsOff'; DeviceGpsOff.muiName = 'SvgIcon'; export default DeviceGpsOff;
src/app.js
Kikonejacob/nodeApp
import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component { render() { return <h1>Hi, {this.props.name}!</h1>; } } ReactDOM.render( <App name="stranger"/>, document.querySelector('.react-root') );
src/decorators/withViewport.js
nobesnickr/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from '../../node_modules/fbjs/lib/ExecutionEnvironment'; let EE; let viewport = {width: 1366, height: 768}; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = {width: window.innerWidth, height: window.innerHeight}; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on('resize', this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport}/>; } handleResize(value) { this.setState({viewport: value}); } }; } export default withViewport;
source/components/I18nString.react.js
BeethovensWerkstatt/VideApp
import React from 'react'; import PropTypes from 'prop-types'; var langfile = require('../i18n/i18n.json'); const I18nString = ({ lang, content, tooltip }) => { if(typeof content !== 'undefined' && typeof tooltip !== 'undefined') { if(!langfile.hasOwnProperty(content)) { const tip = 'Unable to retrieve content from "' + content + '" in i18n.json'; return <span className="i18n error" title={tip}>ERROR (i18n)</span>; } if(!langfile.hasOwnProperty(tooltip)) { const tip = 'Unable to retrieve tooltip from "' + tooltip + '" in i18n.json'; return <span className="i18n error" title={tip}>ERROR (i18n)</span>; } const contentString = langfile[content][lang]; const tooltipString = langfile[tooltip][lang]; return <span className="i18n" title={tooltipString}>{contentString}</span>; } else if(typeof content !== 'undefined') { if(!langfile.hasOwnProperty(content)) { const tip = 'Unable to retrieve content from "' + content + '" in i18n.json'; return <span className="i18n error" title={tip}>ERROR (i18n)</span>; } const contentString = langfile[content][lang]; return <span className="i18n">{contentString}</span>; } //fallback return <span className="i18n error" title="The content to be translated has not been specified.">ERROR (i18n)</span>; }; I18nString.propTypes = { lang: PropTypes.string.isRequired, content: PropTypes.string, tooltip: PropTypes.string }; export default I18nString;
demo/public/component/Popover.js
ev-ui/ev-ui
import React from 'react' import {render} from 'react-dom' import styled,{keyframes} from 'styled-components' import Ripple from '../plugin/evolify/ripple.jsx' const swiftIn=keyframes` 0%{ transform:scale(0); } 70%{ transform:scale(1.1); } 100%{ transform:scale(1); } `; const swiftOut=keyframes` 0%{ transform:scale(1); } 30%{ transform:scale(1.1); } 100%{ transform:scale(0); } `; const Root=styled.div` position:fixed; display:none; outline:none; transform-origin:top left; &.swift-in{ animation:${swiftIn} .5s forwards; } &.swift-out{ animation:${swiftOut} .5s forwards; } `; export default class ContextMenu extends React.Component{ onBlur(){ this.Root.classList.add('swift-out'); setTimeout(()=>{ this.Root.classList.remove('swift-out'); this.props.onHide(); },499) } componentDidUpdate(){ if(this.props.visible){ this.Root.focus(); } } mapPropsToMenu(menu,sub){ return( <ul className={'menu'+(sub?' subMenu':'')}> { menu.map((menuItem,index)=>( <li className='ripple' key={index}><Ripple className="menu-item" onClick={this.onClick.bind(this,menuItem.action)}>{menuItem.text}&nbsp;&nbsp;&nbsp;&nbsp;{menuItem.subMenu && menuItem.subMenu.length>0?'>':''}</Ripple> { menuItem.subMenu && menuItem.subMenu.length>0?this.mapPropsToMenu(menuItem.subMenu,true) :'' } </li> )) } </ul> ) } render(){ let menu = this.props.menu||[]; return( <Root id='root' className={this.props.visible?'swift-in':''} style={{display:this.props.visible?'inherit':'',left:this.props.left+'px',top:this.props.top+'px'}} tabIndex='-1' innerRef={root=>{this.Root=root}} onBlur={this.onBlur.bind(this)} > {this.props.content} </Root> ) } }
components/CustomChart.js
jepz20/coffee_tracker
import React from 'react'; import { connect } from 'react-redux'; import * as actions from '../actions'; import { Line, Bar, Pie } from 'react-chartjs'; import Loader from './Loader'; const possibleColors = [ { color: '#F7464A', highlight: '#FF5A5E', }, { color: '#46BFBD', highlight: '#5AD3D1', }, { color: '#FDB45C', highlight: '#FFC870', }, { color: '#949FB1', highlight: '#A8B3C5', }, { color: '#4D5360', highlight: '#616774', }, ]; const CustomChart = props => { const options = { responsive: true, scales: { xAxes: [ { type: 'linear', position: 'bottom', }, ], }, }; const customStyle = { fillColor: 'rgba(108, 200, 193,0.7)', pointColor: 'rgba(93, 64, 55,1)', pointStrokeColor: '#fff', }; let chart; const { data, chartType, title, loading } = props; if (!data) { chart = <div>No Data</div>; }; let type = chartType ? chartType : 'bar'; if (type == 'pie') { data.forEach((item, index) => item = (item = Object.assign(item, possibleColors[index]))); } else { data.datasets.forEach(item => item = (item = Object.assign(item, customStyle))); } if (loading === 0) { chart = <Loader />; } else { switch (type) { case 'line': chart = <Line data={data} options={options}/>; break; case 'bar': chart = <Bar data={data} options={options}/>; break; case 'pie': chart = <Pie data={data} options={options}/>; break; default: chart = <Bar data={data} options={options}/>; break; } }; return ( <div> <h4 className="graphs__title">{ title }</h4> { chart } </div> ); }; export default CustomChart;
src/parser/hunter/survival/modules/spells/SerpentSting.js
sMteX/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import { formatNumber, formatPercentage } from 'common/format'; import StatisticBox from 'interface/others/StatisticBox'; import SpellIcon from 'common/SpellIcon'; import Enemies from 'parser/shared/modules/Enemies'; import SpellLink from 'common/SpellLink'; import ItemDamageDone from 'interface/others/ItemDamageDone'; import StatTracker from 'parser/shared/modules/StatTracker'; import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER'; import StatisticListBoxItem from 'interface/others/StatisticListBoxItem'; import { SERPENT_STING_SV_BASE_DURATION, SERPENT_STING_SV_PANDEMIC } from 'parser/hunter/survival/constants'; /** * Fire a shot that poisons your target, causing them to take (15% of Attack power) Nature damage instantly and an additional (60% of Attack power) Nature damage over 12/(1+haste) sec. * * Example log: https://www.warcraftlogs.com/reports/pNJbYdLrMW2ynKGa#fight=3&type=damage-done&source=16&translate=true */ class SerpentSting extends Analyzer { static dependencies = { enemies: Enemies, statTracker: StatTracker, }; badRefresh = 0; timesRefreshed = 0; casts = 0; bonusDamage = 0; serpentStingTargets = []; accumulatedTimeBetweenRefresh = 0; accumulatedPercentRemainingOnRefresh = 0; hasVV = false; hasBoP = false; uptimeRequired = 0.95; constructor(...args) { super(...args); this.hasBoP = this.selectedCombatant.hasTalent(SPELLS.BIRDS_OF_PREY_TALENT.id); } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.SERPENT_STING_SV.id) { return; } this.casts++; if (this.selectedCombatant.hasBuff(SPELLS.VIPERS_VENOM_BUFF.id)) { this.hasVV = true; } } on_byPlayer_damage(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.SERPENT_STING_SV.id) { return; } this.bonusDamage += event.amount + (event.absorbed || 0); } on_byPlayer_applydebuff(event) { const spellId = event.ability.guid; let targetInstance = event.targetInstance; if (spellId !== SPELLS.SERPENT_STING_SV.id) { return; } if (targetInstance === undefined) { targetInstance = 1; } const hastedSerpentStingDuration = SERPENT_STING_SV_BASE_DURATION / (1 + this.statTracker.currentHastePercentage); const serpentStingTarget = { targetID: event.targetID, targetInstance: targetInstance, timestamp: event.timestamp, serpentStingDuration: hastedSerpentStingDuration }; this.serpentStingTargets.push(serpentStingTarget); this.hasVV = false; } on_byPlayer_removedebuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.SERPENT_STING_SV.id) { return; } for (let i = 0; i < this.serpentStingTargets.length; i++) { if (event.timestamp - this.serpentStingTargets[i].timestamp > this.serpentStingTargets[i].serpentStingDuration) { this.serpentStingTargets.splice(i, 1); } } } on_byPlayer_refreshdebuff(event) { const spellId = event.ability.guid; let targetInstance = event.targetInstance; if (spellId !== SPELLS.SERPENT_STING_SV.id) { return; } for (let i = 0; i < this.serpentStingTargets.length; i++) { if (event.timestamp - this.serpentStingTargets[i].timestamp > this.serpentStingTargets[i].serpentStingDuration) { this.serpentStingTargets.splice(i, 1); } } if (this.serpentStingTargets.length === 0) { return; } this.timesRefreshed++; if (targetInstance === undefined) { targetInstance = 1; } const hastedSerpentStingDuration = SERPENT_STING_SV_BASE_DURATION / (1 + this.statTracker.currentHastePercentage); const serpentStingTarget = { targetID: event.targetID, targetInstance: targetInstance, timestamp: event.timestamp }; for (let i = 0; i <= this.serpentStingTargets.length - 1; i++) { if (this.serpentStingTargets[i].targetID === serpentStingTarget.targetID && this.serpentStingTargets[i].targetInstance === serpentStingTarget.targetInstance) { const timeRemaining = this.serpentStingTargets[i].serpentStingDuration - (event.timestamp - this.serpentStingTargets[i].timestamp); if (timeRemaining > (hastedSerpentStingDuration * SERPENT_STING_SV_PANDEMIC) && !this.hasVV) { this.badRefresh++; } const pandemicSerpentStingDuration = Math.min(hastedSerpentStingDuration * SERPENT_STING_SV_PANDEMIC, timeRemaining) + hastedSerpentStingDuration; if (!this.hasVV) { this.accumulatedTimeBetweenRefresh += this.serpentStingTargets[i].serpentStingDuration - timeRemaining; this.accumulatedPercentRemainingOnRefresh += timeRemaining / this.serpentStingTargets[i].serpentStingDuration; } this.serpentStingTargets[i].timestamp = event.timestamp; this.serpentStingTargets[i].serpentStingDuration = pandemicSerpentStingDuration; this.hasVV = false; } } } get averageTimeBetweenRefresh() { const avgTime = (this.accumulatedTimeBetweenRefresh / this.timesRefreshed) || 0; return (avgTime / 1000).toFixed(2); } get averagePercentRemainingOnRefresh() { return ((this.accumulatedPercentRemainingOnRefresh / this.timesRefreshed) || 0).toFixed(4); } get uptimePercentage() { return this.enemies.getBuffUptime(SPELLS.SERPENT_STING_SV.id) / this.owner.fightDuration; } get refreshingThreshold() { return { actual: this.badRefresh, isGreaterThan: { minor: 1, average: 3, major: 5, }, style: 'number', }; } get uptimeThreshold() { if (this.hasBoP && !this.hasVV) { return { actual: this.uptimePercentage, isGreaterThan: { minor: 0.35, average: 0.425, major: 0.50, }, style: 'percentage', }; } if (this.hasBoP && this.hasVV) { this.uptimeRequired -= 0.3; } return { actual: this.uptimePercentage, isLessThan: { minor: this.uptimeRequired, average: this.uptimeRequired - 0.05, major: this.uptimeRequired - 0.1, }, style: 'percentage', }; } suggestions(when) { if (this.hasBoP && !this.hasVV) { when(this.uptimeThreshold).addSuggestion((suggest, actual, recommended) => { return suggest(<>With <SpellLink id={SPELLS.BIRDS_OF_PREY_TALENT.id} /> talented and without <SpellLink id={SPELLS.VIPERS_VENOM_TALENT.id} /> talented, you don't want to cast <SpellLink id={SPELLS.SERPENT_STING_SV.id} /> during <SpellLink id={SPELLS.COORDINATED_ASSAULT.id} /> at all, which is a majority of the fight, as thus a low uptime of <SpellLink id={SPELLS.SERPENT_STING_SV.id} /> is better than a high uptime. </>) .icon(SPELLS.SERPENT_STING_SV.icon) .actual(`${formatPercentage(actual)}% Serpent Sting uptime`) .recommended(`<${formatPercentage(recommended)}% is recommended`); }); } else { when(this.uptimeThreshold).addSuggestion((suggest, actual, recommended) => { return suggest(<>Remember to maintain the <SpellLink id={SPELLS.SERPENT_STING_SV.id} /> on enemies, but don't refresh the debuff unless it has less than {formatPercentage(SERPENT_STING_SV_PANDEMIC)}% duration remaining {this.hasVV ? <>, or you have a <SpellLink id={SPELLS.VIPERS_VENOM_TALENT.id} /> buff</> : ''}. During <SpellLink id={SPELLS.COORDINATED_ASSAULT.id} />, you shouldn't be refreshing <SpellLink id={SPELLS.SERPENT_STING_SV.id} /> at all{this.hasVV ? <> unless there's less than 50% remaining of the debuff and you have <SpellLink id={SPELLS.VIPERS_VENOM_BUFF.id} /> active</> : ''}.</>) .icon(SPELLS.SERPENT_STING_SV.icon) .actual(`${formatPercentage(actual)}% Serpent Sting uptime`) .recommended(`>${formatPercentage(recommended)}% is recommended`); }); } when(this.refreshingThreshold).addSuggestion((suggest, actual, recommended) => { return suggest(<>It is not recommended to refresh <SpellLink id={SPELLS.SERPENT_STING_SV.id} /> earlier than when there is less than {formatPercentage(SERPENT_STING_SV_PANDEMIC)}% of the debuffs duration remaining unless you get a <SpellLink id={SPELLS.VIPERS_VENOM_TALENT.id} /> proc.</>) .icon(SPELLS.SERPENT_STING_SV.icon) .actual(`${actual} Serpent Sting cast(s) were cast too early`) .recommended(`<${recommended} is recommended`); }); } statistic() { return ( <StatisticBox position={STATISTIC_ORDER.CORE(19)} icon={<SpellIcon id={SPELLS.SERPENT_STING_SV.id} />} value={`${formatPercentage(this.uptimePercentage)}%`} label="Serpent Sting uptime" tooltip={( <ul> <li>You cast Serpent Sting a total of {this.casts} times. </li> <li>You refreshed the debuff {this.timesRefreshed} times. </li> <ul> <li>When you did refresh (without Viper's Venom up), it happened on average with {formatPercentage(this.averagePercentRemainingOnRefresh)}% or {this.averageTimeBetweenRefresh} seconds remaining on the debuff.</li> <li>You had {this.badRefresh} bad refreshes. This means refreshes with more than {formatPercentage(SERPENT_STING_SV_PANDEMIC)}% of the current debuff remaining and no Viper's Venom buff active.</li> </ul> <li>Serpent Sting dealt a total of {formatNumber(this.bonusDamage / this.owner.fightDuration * 1000)} DPS or {formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.bonusDamage))}% of your total damage.</li> </ul> )} /> ); } subStatistic() { return ( <StatisticListBoxItem title={<SpellLink id={SPELLS.SERPENT_STING_SV.id} />} value={<ItemDamageDone amount={this.bonusDamage} />} /> ); } } export default SerpentSting;
src/containers/weather_list.js
OatsAndSquats25/React-redux-weather-app
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Chart from '../components/chart'; import GoogleMap from '../components/google_map'; class WeatherList extends Component { renderWeather(cityData) { const name = cityData.city.name; const temps = cityData.list.map(weather => weather.main.temp); const pressures = cityData.list.map(weather => weather.main.pressure); const humidities = cityData.list.map(weather => weather.main.humidity); //const lon = cityData.city.coord.lon; //const lat = cityData.city.coord.lat; const { lon, lat } = cityData.city.coord; return ( <tr key={name}> <td><GoogleMap lon={lon} lat={lat} /></td> <td><Chart data={temps} color="orange" units="K" /></td> <td><Chart data={pressures} color="green" units="hPa" /></td> <td><Chart data={humidities} color="black" units="%" /></td> </tr> ); } render() { return ( <table className="table table-hover"> <thead> <tr> <th>City</th> <th>Temperature (K)</th> <th>Pressure (hPa)</th> <th>Humidity (%)</th> </tr> </thead> <tbody> {this.props.weather.map(this.renderWeather)} </tbody> </table> ); } } function mapStateToProps({ weather }) { return { weather }; } export default connect(mapStateToProps)(WeatherList);
node_modules/react-bootstrap/es/Popover.js
acalabano/get-committed
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import isRequiredForA11y from 'prop-types-extra/lib/isRequiredForA11y'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * An html id attribute, necessary for accessibility * @type {string} * @required */ id: isRequiredForA11y(PropTypes.oneOfType([PropTypes.string, PropTypes.number])), /** * Sets the direction the Popover is positioned towards. */ placement: PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Popover. */ positionTop: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * The "left" position value for the Popover. */ positionLeft: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * The "top" position value for the Popover arrow. */ arrowOffsetTop: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * The "left" position value for the Popover arrow. */ arrowOffsetLeft: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * Title content */ title: PropTypes.node }; var defaultProps = { placement: 'right' }; var Popover = function (_React$Component) { _inherits(Popover, _React$Component); function Popover() { _classCallCheck(this, Popover); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Popover.prototype.render = function render() { var _extends2; var _props = this.props, placement = _props.placement, positionTop = _props.positionTop, positionLeft = _props.positionLeft, arrowOffsetTop = _props.arrowOffsetTop, arrowOffsetLeft = _props.arrowOffsetLeft, title = _props.title, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'title', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2)); var outerStyle = _extends({ display: 'block', top: positionTop, left: positionLeft }, style); var arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft }; return React.createElement( 'div', _extends({}, elementProps, { role: 'tooltip', className: classNames(className, classes), style: outerStyle }), React.createElement('div', { className: 'arrow', style: arrowStyle }), title && React.createElement( 'h3', { className: prefix(bsProps, 'title') }, title ), React.createElement( 'div', { className: prefix(bsProps, 'content') }, children ) ); }; return Popover; }(React.Component); Popover.propTypes = propTypes; Popover.defaultProps = defaultProps; export default bsClass('popover', Popover);
fields/types/html/HtmlField.js
dvdcastro/keystone
import _ from 'lodash'; import Field from '../Field'; import React from 'react'; import tinymce from 'tinymce'; import { FormInput } from 'elemental'; /** * TODO: * - Remove dependency on underscore */ var lastId = 0; function getId () { return 'keystone-html-' + lastId++; } // Workaround for #2834 found here https://github.com/tinymce/tinymce/issues/794#issuecomment-203701329 function removeTinyMCEInstance (editor) { var oldLength = tinymce.editors.length; tinymce.remove(editor); if (oldLength === tinymce.editors.length) { tinymce.editors.remove(editor); } } module.exports = Field.create({ displayName: 'HtmlField', statics: { type: 'Html', }, getInitialState () { return { id: getId(), isFocused: false, }; }, initWysiwyg () { if (!this.props.wysiwyg) return; var self = this; var opts = this.getOptions(); opts.setup = function (editor) { self.editor = editor; editor.on('change', self.valueChanged); editor.on('focus', self.focusChanged.bind(self, true)); editor.on('blur', self.focusChanged.bind(self, false)); }; this._currentValue = this.props.value; tinymce.init(opts); }, componentDidUpdate (prevProps, prevState) { if (prevState.isCollapsed && !this.state.isCollapsed) { this.initWysiwyg(); } if (!_.isEqual(this.props.currentDependencies, prevProps.currentDependencies)) { if (_.isEqual(prevProps.dependsOn, prevProps.currentDependencies)) { var instance = tinymce.get(prevState.id); if (instance) { removeTinyMCEInstance(instance); } } if (_.isEqual(this.props.dependsOn, this.props.currentDependencies)) { this.initWysiwyg(); } } }, componentDidMount () { this.initWysiwyg(); }, componentWillReceiveProps (nextProps) { if (this.editor && this._currentValue !== nextProps.value) { this.editor.setContent(nextProps.value); } }, focusChanged (focused) { this.setState({ isFocused: focused, }); }, valueChanged (event) { var content; if (this.editor) { content = this.editor.getContent(); } else { content = event.target.value; } this._currentValue = content; this.props.onChange({ path: this.props.path, value: content, }); }, getOptions () { var plugins = ['code', 'link']; var options = Object.assign( {}, Keystone.wysiwyg.options, this.props.wysiwyg ); var toolbar = options.overrideToolbar ? '' : 'bold italic | alignleft aligncenter alignright | bullist numlist | outdent indent | removeformat | link '; var i; if (options.enableImages) { plugins.push('image'); toolbar += ' | image'; } if (options.enableCloudinaryUploads || options.enableS3Uploads) { plugins.push('uploadimage'); toolbar += options.enableImages ? ' uploadimage' : ' | uploadimage'; } if (options.additionalButtons) { var additionalButtons = options.additionalButtons.split(','); for (i = 0; i < additionalButtons.length; i++) { toolbar += (' | ' + additionalButtons[i]); } } if (options.additionalPlugins) { var additionalPlugins = options.additionalPlugins.split(','); for (i = 0; i < additionalPlugins.length; i++) { plugins.push(additionalPlugins[i]); } } if (options.importcss) { plugins.push('importcss'); var importcssOptions = { content_css: options.importcss, importcss_append: true, importcss_merge_classes: true, }; Object.assign(options.additionalOptions, importcssOptions); } if (!options.overrideToolbar) { toolbar += ' | code'; } var opts = { selector: '#' + this.state.id, toolbar: toolbar, plugins: plugins, menubar: options.menubar || false, skin: options.skin || 'keystone', }; if (this.shouldRenderField()) { opts.uploadimage_form_url = options.enableS3Uploads ? Keystone.adminPath + '/api/s3/upload' : Keystone.adminPath + '/api/cloudinary/upload'; } else { Object.assign(opts, { mode: 'textareas', readonly: true, menubar: false, toolbar: 'code', statusbar: false, }); } if (options.additionalOptions) { Object.assign(opts, options.additionalOptions); } return opts; }, getFieldClassName () { var className = this.props.wysiwyg ? 'wysiwyg' : 'code'; return className; }, renderField () { var className = this.state.isFocused ? 'is-focused' : ''; var style = { height: this.props.height, }; return ( <div className={className}> <FormInput multiline style={style} onChange={this.valueChanged} id={this.state.id} className={this.getFieldClassName()} name={this.getInputName(this.props.path)} value={this.props.value} /> </div> ); }, renderValue () { return <FormInput multiline noedit value={this.props.value} />; }, });
newclient/scripts/components/user/dashboard/dashboard/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ import styles from './style'; import classNames from 'classnames'; import React from 'react'; import {get} from 'lodash'; import {AppHeader} from '../../../app-header'; import {NewDisclosureButton} from '../new-disclosure-button'; import {DisclosureArchiveButton} from '../disclosure-archive-button'; import {ConfirmationMessage} from '../confirmation-message'; import DisclosureTable from '../disclosure-table'; import {ReviewTable} from '../review-table'; import {DisclosureStore} from '../../../../stores/disclosure-store'; import {TravelLogButton} from '../travel-log-button'; import {DisclosureActions} from '../../../../actions/disclosure-actions'; import { DISCLOSURE_TYPE, ROLES, DISCLOSURE_STATUS } from '../../../../../../coi-constants'; import AdminMenu from '../../../admin-menu'; import moment from 'moment'; function shouldUpdateStatus(noEntityConfigValue, disclosureSummaries) { if (!noEntityConfigValue) { return true; } const annualSummary = disclosureSummaries.find(summary => { return String(summary.type) === DISCLOSURE_TYPE.ANNUAL; }); if (annualSummary && annualSummary.entityCount === 0) { return false; } return true; } export class Dashboard extends React.Component { constructor() { super(); const storeState = DisclosureStore.getState(); this.state = { applicationState: storeState.applicationState, disclosureSummaries: storeState.disclosureSummariesForUser, projects: storeState.projects, annualDisclosure: storeState.annualDisclosure, toReview: storeState.disclosuresNeedingReview }; this.onChange = this.onChange.bind(this); } shouldComponentUpdate() { return true; } componentDidMount() { DisclosureStore.listen(this.onChange); DisclosureActions.loadDisclosureSummaries(); } componentWillUnmount() { DisclosureStore.unlisten(this.onChange); } onChange() { const storeState = DisclosureStore.getState(); this.setState({ applicationState: storeState.applicationState, disclosureSummaries: storeState.disclosureSummariesForUser, projects: storeState.projects, annualDisclosure: storeState.annualDisclosure, toReview: storeState.disclosuresNeedingReview }); } render() { const { disclosureSummaries, applicationState, projects, toReview } = this.state; const { userInfo, configState } = this.context; const isAdmin = userInfo && (userInfo.coiRole === ROLES.ADMIN); let confirmationMessage; if (this.state && applicationState && applicationState.confirmationShowing) { confirmationMessage = ( <ConfirmationMessage /> ); } let annualDisclosureEnabled; let manualDisclosureEnabled; let travelLogEnabled; configState.config.disclosureTypes.forEach(type => { switch (type.typeCd.toString()) { case DISCLOSURE_TYPE.ANNUAL: annualDisclosureEnabled = type.enabled === 1; break; case DISCLOSURE_TYPE.MANUAL: manualDisclosureEnabled = type.enabled === 1; break; case DISCLOSURE_TYPE.TRAVEL: travelLogEnabled = type.enabled === 1; break; } }); let annualDisclosureButton; if (annualDisclosureEnabled) { const annualDisclosure = disclosureSummaries.find(summary => { return summary.type.toString() === DISCLOSURE_TYPE.ANNUAL; }); if ( !annualDisclosure || annualDisclosure.status === DISCLOSURE_STATUS.IN_PROGRESS || annualDisclosure.status === DISCLOSURE_STATUS.UP_TO_DATE || annualDisclosure.status === DISCLOSURE_STATUS.UPDATE_REQUIRED ) { annualDisclosureButton = ( <div> <NewDisclosureButton type={DISCLOSURE_TYPE.ANNUAL} update={disclosureSummaries.length > 0} /> </div> ); } } let travelLogButton; if (travelLogEnabled) { travelLogButton = ( <div> <TravelLogButton /> </div> ); } let manualDisclosureButton; if (manualDisclosureEnabled) { manualDisclosureButton = ( <div> <NewDisclosureButton type={DISCLOSURE_TYPE.MANUAL} /> </div> ); } if (!configState.isLoaded) { return (<div />); } let adminMenu; if (isAdmin ) { adminMenu = ( <AdminMenu className={`${styles.override} ${styles.adminMenu}`} /> ); } const configValueOn = get( configState, 'config.general.disableNewProjectStatusUpdateWhenNoEntities', false ); let newProjectBanner; if ( Array.isArray(projects) && projects.some(project => project.new === 1) && shouldUpdateStatus(configValueOn, disclosureSummaries) ) { newProjectBanner = ( <div className={styles.infoBanner}> Your annual disclosure needs updates due to new projects to disclose. </div> ); } let expirationBanner; if (disclosureSummaries.length > 0) { const expirationDate = disclosureSummaries.find(summary => { return String(summary.type) === DISCLOSURE_TYPE.ANNUAL; }).expired_date; if (expirationDate) { const days = moment(expirationDate).diff(moment(new Date()), 'days'); expirationBanner = ( <div className={styles.expiresBanner}> <span style={{paddingTop: '5px'}}>Your disclosure expires in:</span> <span className={styles.days}>{days}</span> <span className={styles.daysLabel}>Days</span> </div> ); } } let banners; if (newProjectBanner || expirationBanner) { banners = ( <div> <div className={styles.bannerContainer}> {expirationBanner} {newProjectBanner} </div> </div> ); } let disclosureTableLabel; let reviewTableLabel; let reviewTable; if (userInfo.coiRole === ROLES.REVIEWER) { disclosureTableLabel = ( <div className={styles.disclosureTableLabel}>My Disclosures</div> ); reviewTableLabel = ( <div className={styles.reviewTableLabel}>Needs Review</div> ); reviewTable = ( <ReviewTable disclosures={toReview} /> ); } const classes = classNames( 'flexbox', 'column', {[styles.isAdmin]: isAdmin} ); return ( <div className={classes} style={{minHeight: '100%'}}> <AppHeader className={`${styles.override} ${styles.header}`} moduleName={'Conflict Of Interest'} /> <span className={`flexbox row fill ${styles.container} ${this.props.className}`}> <span className={styles.sidebar}> {adminMenu} {annualDisclosureButton} {travelLogButton} {manualDisclosureButton} <div> <DisclosureArchiveButton className={`${styles.override} ${styles.borderBottom}`} /> </div> </span> <span className={`fill ${styles.content}`}> <div className={styles.header2}> <h2 className={styles.heading}>MY COI DASHBOARD</h2> </div> {confirmationMessage} {banners} {disclosureTableLabel} <DisclosureTable disclosures={disclosureSummaries} /> {reviewTableLabel} {reviewTable} </span> </span> </div> ); } } Dashboard.contextTypes = { configState: React.PropTypes.object, userInfo: React.PropTypes.object };
client/src/layout/Dashboard.js
idoalit/slims.js
/** * @Author: Waris Agung Widodo <ido> * @Date: 2017-10-02T14:33:28+07:00 * @Email: ido.alit@gmail.com * @Filename: Dashboard.js * @Last modified by: ido * @Last modified time: 2017-10-03T11:50:20+07:00 */ import React from 'react'; import Card from '../components/Card'; export default class Dashboard extends React.Component { constructor() { super() this.state = {title: 0, newTitle: 0, item: 0, newItem: 0, loan: 0, lent: 0, extend: 0, overdue: 0} } componentDidMount(){ // get title fetch('/api/biblio/count/title') .then(res => res.json()) .then(data => this.setState({title: data.data})) // get new title fetch('/api/biblio/count/new-title') .then(res => res.json()) .then(data => this.setState({newTitle: data.data})) // get new title fetch('/api/biblio/count/item') .then(res => res.json()) .then(data => this.setState({item: data.data})) // get new title fetch('/api/biblio/count/new-item') .then(res => res.json()) .then(data => this.setState({newItem: data.data})) // get all loan transaction fetch('/api/loan/count') .then(res => res.json()) .then(data => this.setState({loan: data.data})) // get lent fetch('/api/loan/count/lent') .then(res => res.json()) .then(data => this.setState({lent: data.data})) // get renewed fetch('/api/loan/count/extend') .then(res => res.json()) .then(data => this.setState({extend: data.data})) // get overdue fetch('/api/loan/count/overdue') .then(res => res.json()) .then(data => this.setState({overdue: data.data})) } render(){ var numberWithCommas = function (x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } var data = { biblio : { color: 'orange -pink', title: 'Bibliographi', value: numberWithCommas(this.state.title), icon: 'book', sub: [ { label: 'new', value: numberWithCommas(this.state.newTitle), icon: 'long arrow up' } ] }, item : { color: 'deep-purple -blue', title: 'Items', value: numberWithCommas(this.state.item), icon: 'clone', sub: [ { label: 'new', value: numberWithCommas(this.state.newItem), icon: 'long arrow up' } ] }, loan : { color: 'green -blue', title: 'Loans', value: numberWithCommas(this.state.loan), icon: 'shopping basket', sub: [ { label: 'lent', value: numberWithCommas(this.state.lent), icon: 'long arrow up' }, { label: 'overdue', value: numberWithCommas(this.state.overdue), icon: 'wait' }, { label: 'extend', value: numberWithCommas(this.state.extend), icon: 'repeat' } ] }, } return( <div className="ui grid three column"> <div className="column"> <Card data={data.biblio} /> </div> <div className="column"> <Card data={data.item} /> </div> <div className="column"> <Card data={data.loan} /> </div> </div> ) } }
src/Pages/Cafes.js
LaurentEtienne/Kfe
import React, { Component } from 'react'; import CafeStore from '../Stores/Cafe'; let getState = () => { return { companyCafes: CafeStore.getCompanyCafes(), partnerCafes: CafeStore.getPartnerCafes() }; }; class Cafes extends Component { constructor(props) { super(props); this.state = getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { CafeStore.addChangeListener(this.onChange); CafeStore.provideCompanyCafes(); CafeStore.providePartnerCafes(); } componentWillUnmount() { CafeStore.removeChangeListener(this.onChange); } onChange() { this.setState(getState()); } render() { let createModel = (cafe) => { let model = { name: cafe.system.name, imageLink: "url(" + cafe.elements.photo.value[0].url + ")", street: cafe.elements.street.value, city: cafe.elements.city.value, zipCode: cafe.elements.zip_code.value, country: cafe.elements.country.value, state: cafe.elements.state.value, phone: cafe.elements.phone.value, }; model.dataAddress = model.city + ", " + model.street; model.countryWithState = model.country + (model.state ? ", " + model.state : ""); model.location = model.city + ", " + model.countryWithState; return model; }; let companyCafes = this.state.companyCafes.map(createModel).map((model, index) => { return ( <div className="col-md-6" key={index}> <div className="cafe-image-tile js-scroll-to-map" data-address={model.dataAddress}> <div className="cafe-image-tile-image-wrapper" style={{ backgroundImage: model.imageLink, backgroundSize: "cover", backgroundPosition: "right" }}> </div> <div className="cafe-image-tile-content"> <h3 className="cafe-image-tile-name">{model.name}</h3> <address className="cafe-tile-address"> <a name={model.name} className="cafe-tile-address-anchor"> {model.street}, {model.city}<br />{model.zipCode}, {model.countryWithState} </a> </address> <p>{model.phone}</p> </div> </div> </div> ); }); let models = this.state.partnerCafes.map(createModel); let locations = models.map((model) => model.location).reduce((result, location) => { if (result.indexOf(location) < 0) { result.push(location); } return result; }, []).sort(); let partnerCafes = locations.map((location, locationIndex) => { let locationPartnerCafes = models.filter((model) => model.location === location).map((model, modelIndex) => { return ( <p key={modelIndex}>{model.name}, {model.street}, {model.phone}</p> ); }); return ( <div key={locationIndex}> <h3>{location}</h3> {locationPartnerCafes} </div> ); }); return ( <div className="container"> <h2>Our cafes</h2> <div className="row"> {companyCafes} </div> <h2>Other places where you can drink our coffee</h2> <div className="row"> {partnerCafes} </div> </div> ); } } export default Cafes;
features/apimgt/org.wso2.carbon.apimgt.store.feature/src/main/resources/store/source/src/app/components/Shared/Confirm.js
thusithak/carbon-apimgt
import React from 'react' import Dialog, { DialogActions, DialogContent, DialogContentText, DialogTitle, } from 'material-ui/Dialog'; class Confirm extends React.Component{ constructor(props){ super(props); this.state( { open: false } ) } handleRequestClose(action){ this.setState({ open: false }); action === "ok" ? this.props.callback(true) : this.props.callback(false); } render(props){ return( <Dialog open={this.state.open} onRequestClose={this.handleRequestClose}> <DialogTitle> { props.title ? props.title : 'Please Confirm' } </DialogTitle> <DialogContent> <DialogContentText> { props.message ? props.message : 'Are you sure?' } </DialogContentText> </DialogContent> <DialogActions> <Button onClick={() => this.handleRequestClose("cancel")} color="primary"> { props.labelCancel ? props.labelCancel : 'Cancel'} </Button> <Button onClick={() => this.handleRequestClose("ok")} color="primary"> { props.labelOk ? props.labelOk : 'OK'} </Button> </DialogActions> </Dialog> ) } } export default Confirm;
src/components/lists/ConnectionListItem.js
whphhg/vcash-electron
import React from 'react' import { observer } from 'mobx-react' const ConnectionListItem = observer(({ t, connections, index }) => { const instance = connections.instances.get(connections.ids[index]) const { rpc } = instance.status const color = rpc === null ? '' : rpc === true ? 'green' : 'red' return ( <div className={ 'list-item' + (index % 2 === 0 ? ' even' : '') + (connections.viewingId === instance.id ? ' selected' : '') } onClick={() => connections.setViewing(instance.id)} > <div className="flex-sb"> <p style={{ fontWeight: '500' }}> {instance.type === 'local' ? '127.0.0.1' : instance.host}: {instance.type === 'local' ? instance.localPort : instance.port} </p> <p style={{ fontWeight: '400' }}> {instance.type === 'local' ? t('local') : 'SSH'} </p> </div> <div className="flex"> <i className={'material-icons md-16 ' + color}>power_settings_new</i> <p>{rpc === true ? t('connected') : t('disconnected')}</p> </div> </div> ) }) export default ConnectionListItem
src/main.js
cjordanball/cjbinfo
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import reduxThunk from 'redux-thunk'; import { BrowserRouter, Route } from 'react-router-dom'; import reducers from './reducers'; import Tracker from './hocs/ga_tracker'; import '../styles/styles.less'; import ActionTypes from './actions/types'; import App from './components/app'; const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore); const store = createStoreWithMiddleware(reducers); const token = localStorage.getItem('token'); if (token) { store.dispatch({ type: ActionTypes.AUTH_USER }); } ReactDOM.render( <Provider store={store}> <BrowserRouter> <Route component={Tracker(App)} /> </BrowserRouter> </Provider>, document.querySelector('#root'));
pkg/users/authorized-keys-panel.js
cockpit-project/cockpit
/* * This file is part of Cockpit. * * Copyright (C) 2020 Red Hat, Inc. * * Cockpit is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * Cockpit 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Cockpit; If not, see <http://www.gnu.org/licenses/>. */ import cockpit from 'cockpit'; import React from 'react'; import { useObject, useEvent } from 'hooks.js'; import { Button, TextArea } from '@patternfly/react-core'; import { show_modal_dialog } from "cockpit-components-dialog.jsx"; import { show_unexpected_error } from "./dialog-utils.js"; import * as authorized_keys from './authorized-keys.js'; const _ = cockpit.gettext; function AddAuthorizedKeyDialogBody({ state, change }) { const { text } = state; return ( <TextArea id="authorized-keys-text" placeholder={_("Paste the contents of your public SSH key file here")} className="form-control" value={text} onChange={value => change("text", value)} /> ); } function add_authorized_key_dialog(keys) { let dlg = null; const state = { text: "" }; function change(field, value) { state[field] = value; update(); } function update() { const props = { id: "add-authorized-key-dialog", title: _("Add public key"), body: <AddAuthorizedKeyDialogBody state={state} change={change} /> }; const footer = { actions: [ { caption: _("Add"), style: "primary", clicked: () => { return keys.add_key(state.text); } } ] }; if (!dlg) dlg = show_modal_dialog(props, footer); else { dlg.setProps(props); dlg.setFooterProps(footer); } } update(); } export function AuthorizedKeys({ name, home, allow_mods }) { const manager = useObject(() => authorized_keys.instance(name, home), manager => manager.close(), [name, home]); useEvent(manager, "changed"); function remove_key(raw) { manager.remove_key(raw).catch(show_unexpected_error); } const { state, keys } = manager; let key_items; if (state == "access-denied") { key_items = [ <li key={state} className="pf-c-data-list__item"> <div key={state} className="pf-c-data-list__item-row fingerprint"> <span>{_("You do not have permission to view the authorized public keys for this account.")}</span> </div> </li> ]; } else if (state == "failed") { key_items = [ <li key={state} className="pf-c-data-list__item"> <div key={state} className="pf-c-data-list__item-row fingerprint"> <span>{_("Failed to load authorized keys.")}</span> </div> </li> ]; } else if (state == "ready") { if (keys.length === 0) { key_items = [ <li key={state} className="pf-c-data-list__item"> <div key="empty" className="pf-c-data-list__item-row no-keys"> {_("There are no authorized public keys for this account.")} </div> </li> ]; } else { key_items = keys.map(k => <li key={k.raw} className="pf-c-data-list__item"> <div className="pf-c-data-list__item-row"> <div className="pf-c-data-list__item-content"> <div className="pf-c-data-list__cell comment"> { k.comment || <em>{_("Unnamed")}</em> } </div> <div className="pf-c-data-list__cell fingerprint"> { k.fp || <span>{_("Invalid key")}</span> } </div> </div> { allow_mods && <div className="pf-c-data-list__item-action"> <Button variant="secondary" onClick={() => remove_key(k.raw)} className="account-remove-key"> {_("Remove")} </Button> </div> } </div> </li>); } } else return null; return ( <div className="pf-c-card" id="account-authorized-keys"> <div className="pf-c-card__header"> <div className="pf-c-card__title"><h2>{_("Authorized public SSH keys")}</h2></div> { allow_mods && <Button onClick={() => add_authorized_key_dialog(manager)} id="authorized-key-add"> {_("Add key")} </Button>} </div> <div className="pf-c-card__body contains-list"> <ul className="pf-c-data-list pf-m-compact" id="account-authorized-keys-list"> { key_items } </ul> </div> </div> ); }
src/components/Order.js
hunt-genes/fasttrack
/* global window */ // Set state during browser rendring. This will cause a flicker, but we need it. /* eslint "react/no-did-mount-set-state": 0 */ import Dialog from 'material-ui/Dialog'; import RaisedButton from 'material-ui/RaisedButton'; import TextField from 'material-ui/TextField'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import moment from 'moment'; import React from 'react'; import Relay from 'react-relay'; import prefix from '../prefix'; import theme from '../theme'; import OrderVariablesMutation from '../mutations/orderVariables'; import OrderSnpTable from './OrderSnpTable'; import { validateEmail, validateProject } from '../lib/validations'; class Order extends React.Component { static propTypes = { location: React.PropTypes.object, relay: React.PropTypes.object, site: React.PropTypes.object, } static contextTypes = { relay: Relay.PropTypes.Environment, router: React.PropTypes.object.isRequired, } static childContextTypes = { muiTheme: React.PropTypes.object.isRequired, }; constructor(props) { super(props); this.muiTheme = getMuiTheme(theme); } state = { selected: new Map(), project: '', comment: '', email: '', ordered: false, emailValid: true, emailWritten: false, projectValid: true, projectWritten: false, downloadSnpsOpen: false, } getChildContext() { return { muiTheme: getMuiTheme(theme) }; } componentDidMount() { const selected = window.localStorage.getItem('orderSelected'); const email = window.localStorage.getItem('email'); const project = window.localStorage.getItem('project'); const comment = window.localStorage.getItem('comment'); const newState = {}; if (selected) { newState.selected = new Map(JSON.parse(selected)); } if (email) { newState.email = email; newState.emailWritten = true; } if (project) { newState.project = project; } if (comment) { newState.comment = comment; } this.setState(newState); } onSubmitOrder = (event) => { event.preventDefault(); this.setState({ ordered: true }); if (validateEmail(this.state.email) && this.state.project) { this.context.relay.commitUpdate(new OrderVariablesMutation({ email: this.state.email, project: this.state.project, comment: this.state.comment, snps: Array.from(this.state.selected.keys()), site: this.props.site, })); } } onChangeProject = (event, project) => { if (this.state.projectWritten) { this.setState({ project, projectValid: validateProject(project) }); } else { this.setState({ project }); } } onChangeComment = (event, comment) => { this.setState({ comment }); } onChangeEmail = (event, email) => { if (this.state.emailWritten) { this.setState({ email, emailValid: validateEmail(email) }); } else { this.setState({ email }); } } onBlurEmail = () => { this.setState({ emailWritten: true, emailValid: validateEmail(this.state.email) }); } onBlurProject = () => { this.setState({ projectWritten: true, projectValid: validateProject(this.state.project) }); } onClickBack = () => { this.context.router.goBack(); } onClickDone = () => { this.setState({ selected: new Map(), comment: '', ordered: false, }); window.localStorage.removeItem('orderSelected'); window.localStorage.removeItem('email'); window.localStorage.removeItem('project'); window.localStorage.removeItem('comment'); const query = this.props.location.query; this.context.router.push({ pathname: prefix, query, }); } onDownloadDialogClose = () => { this.setState({ downloadSnpsOpen: false }); } onDownloadClick = () => { // do not preventDefault here this.setState({ downloadSnpsOpen: false }); } openDownloadSnps = () => { this.setState({ downloadSnpsOpen: true }); } render() { const errorStyle = { color: theme.palette.errorColor, }; const warningStyle = { color: theme.palette.accent1Color, }; const snps = Array.from(this.state.selected.keys()); snps.sort((a, b) => { return b < a; }); const downloadActions = ( <form action={`${prefix}/snps`} method="POST"> <input type="hidden" name="snps" value={snps} /> <RaisedButton label="Download" type="submit" onClick={this.onDownloadClick} primary /> <RaisedButton label="Cancel" onTouchTap={this.onDownloadDialogClose} /> </form> ); const downloadDialog = ( <Dialog title="Download SNP list" open={this.state.downloadSnpsOpen} onRequestClose={this.onDownloadDialogClose} actions={downloadActions} actionContainerStyle={{ textAlign: 'inherit' }} autoScrollBodyContent > <p>This will download the list of SNPs as a csv file.</p> <p>Fields are separated by commas, individual traits and genes, by semicolons.</p> <p>Downloading a SNP-list-file will not be registered as an order. You must click the «Send»-button in order to effectuate your order.</p> </Dialog> ); const { emailValid, projectValid } = this.state; const { email } = this.props.site; return ( <section> <div style={{ maxWidth: 800, margin: '0 auto' }}> {this.state.ordered && this.props.site.order ? <div> {this.props.relay.hasOptimisticUpdate(this.props.site) ? <div> <h1>Please wait</h1> <p>Order is not confirmed yet</p> </div> : <div> <h1>Thank you for your order</h1> <p>Your order was sent {moment(this.props.site.order.createdAt).format('lll')}, and contains the following SNPs:</p> </div> } <OrderSnpTable snps={snps} results={this.state.selected} /> {downloadDialog} <RaisedButton onClick={this.openDownloadSnps} label="Download" /> <p>You will receive an email with a confirmation on submitted SNP-order to {this.props.site.order.email} shortly.</p> <p>Please contact us {email ? `at ${email} ` : '' } if there is something wrong with your order.</p> <RaisedButton label="Done" onClick={this.onClickDone} /> </div> : <div> {this.state.selected.size ? <div> <form onSubmit={this.onSubmitOrder}> <h1> You have selected {snps.length} SNPs to order from HUNT </h1> <p>Please use your HUNT case number (saksnummer) as identification. To order SNP-data from HUNT, you need a submitted and/or approved HUNT-application. Please refer to the HUNT website for details for application procedures, <a href="https://www.ntnu.no/hunt">www.ntnu.no/hunt</a>.</p> <div> <TextField id="project" floatingLabelText="Project / case number" onChange={this.onChangeProject} value={this.state.project} onBlur={this.onBlurProject} errorStyle={projectValid ? warningStyle : errorStyle } errorText={projectValid ? 'Format: 2017/123' : 'Invalid project number, it should be like 2017/123' } /> </div> <div> <TextField id="email" type="email" floatingLabelText="Email" onChange={this.onChangeEmail} onBlur={this.onBlurEmail} errorText={emailValid ? 'Your email, not to your PI or supervisor. We will use this for e-mail confirmation and later communications.' : 'Email is not valid, is it an @ntnu.no address?' } errorStyle={emailValid ? warningStyle : errorStyle} fullWidth value={this.state.email} /> </div> <div> <TextField id="comment" floatingLabelText="Comment" fullWidth multiLine onChange={this.onChangeComment} value={this.state.comment} /> </div> <div style={{ marginTop: '2rem' }}> <RaisedButton primary label="Send" type="submit" disabled={!emailValid || !projectValid} /> <RaisedButton label="Back" onClick={this.onClickBack} /> </div> <RaisedButton style={{ float: 'right', marginTop: '1rem' }} onClick={this.openDownloadSnps} label="Download" /> <h2>Please verify your SNP-order before submitting</h2> <OrderSnpTable snps={snps} results={this.state.selected} /> </form> {downloadDialog} </div> : <div> <h1 id="download">You have selected no SNPs yet</h1> <p> Please go back and select some SNPs, if you want to order variables from HUNT </p> <RaisedButton label="Back" onClick={this.onClickBack} /> </div> } </div> } </div> </section> ); } } export default Relay.createContainer(Order, { fragments: { site: () => { return Relay.QL` fragment on Site { id email order { id email snps createdAt } ${OrderVariablesMutation.getFragment('site')} }`; }, viewer: () => { return Relay.QL` fragment on User { id }`; }, }, });
src/svg-icons/action/hourglass-empty.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionHourglassEmpty = (props) => ( <SvgIcon {...props}> <path d="M6 2v6h.01L6 8.01 10 12l-4 4 .01.01H6V22h12v-5.99h-.01L18 16l-4-4 4-3.99-.01-.01H18V2H6zm10 14.5V20H8v-3.5l4-4 4 4zm-4-5l-4-4V4h8v3.5l-4 4z"/> </SvgIcon> ); ActionHourglassEmpty = pure(ActionHourglassEmpty); ActionHourglassEmpty.displayName = 'ActionHourglassEmpty'; export default ActionHourglassEmpty;
app/components/Notes/AddNote.js
luketlancaster/github-notetaker
import React from 'react'; class AddNote extends React.Component { handleSubmit() { var newNote = this.refs.note.getDOMNode().value; this.refs.note.getDOMNode().value = ''; this.props.addNote(newNote); } render() { return ( <div className="input-group"> <input type="text" className="form-control" ref="note" placeholder="Add New Note" /> <span className="input-group-btn"> <button className="btn btn-default" type="button" onClick={this.handleSubmit.bind(this)}>Submit</button> </span> </div> ) } } AddNote.propTypes = { username: React.PropTypes.string.isRequired, addNote: React.PropTypes.func.isRequired }; export default AddNote;
packages/material-ui-icons/src/Phonelink.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M4 6h18V4H4c-1.1 0-2 .9-2 2v11H0v3h14v-3H4V6zm19 2h-6c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h6c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1zm-1 9h-4v-7h4v7z" /></g> , 'Phonelink');
src/ReactReduxProject/examplePage/controller/entry.js
Terry-Su/MVVC
import React from 'react' import App from '../component/App' import controller from './index' // initialize controller.init(App)
examples/react-redux/src/components/ui/Content.js
rangle/redux-segment
import React from 'react'; const Content = ({ children, style = {}, isVisible }) => { return ( <div className={ `mt3 p1` } style={{ ...styles.base, style }}> { isVisible ? children : null } </div> ); }; const styles = { base: {}, }; export default Content;
src/containers/Base/Base.js
brendo/open-api-renderer
import React from 'react' import { configureAnchors } from 'react-scrollable-anchor' import DocumentTitle from 'react-document-title' import PropTypes from 'prop-types' import Page from '../../components/Page/Page' import Overlay from '../../components/Overlay/Overlay' import { getDefinition, parseDefinition, validateDefinition } from '../../lib/definitions' import lincolnLogo from '../../assets/lincoln-logo-white.svg' import { styles } from './Base.styles' @styles export default class Base extends React.PureComponent { state = { parserType: 'open-api-v3', definitionUrl: null, definition: null, parsedDefinition: null, loading: false, error: null } componentDidMount () { this.intialise() } intialise = async () => { const { parserType } = this.state const { definitionUrl, navSort, validate } = this.props if (!definitionUrl) { return true } if (definitionUrl === this.state.definitionUrl) { return false } await this.setDefinition({ definitionUrl, parserType, navSort, validate }) configureAnchors({ offset: -10, scrollDuration: 100 }) return true } setDefinition = async ({ definitionUrl, navSort, validate, parserType = this.state.parserType }) => { this.setState({ loading: !!definitionUrl, error: null }) try { const [ definition ] = await Promise.all([ getDefinition(definitionUrl), validate && validateDefinition(definitionUrl, parserType) ]) const parsedDefinition = await parseDefinition({ definition, parserType, navSort }) this.setState({ loading: false, definitionUrl, definition, parsedDefinition, parserType }) } catch (err) { return this.setState({ loading: false, error: err }) } } render () { const { location, classes } = this.props const { parsedDefinition: definition, definitionUrl, loading, error } = this.state let element if (loading) { element = <Loading {...{definitionUrl}} /> } else if (error) { element = <Failure {...{error}} /> } else { element = <Definition {...{ location, definition, definitionUrl }} /> } return ( <DocumentTitle title={definition ? definition.title : 'Lincoln Renderer'}> <div className={classes.base}> {element} </div> </DocumentTitle> ) } } Base.contextTypes = { router: PropTypes.object } Base.propTypes = { classes: PropTypes.object, location: PropTypes.object, definitionUrl: PropTypes.string, navSort: PropTypes.oneOfType([ PropTypes.string, PropTypes.bool ]), validate: PropTypes.bool } Base.defaultProps = { navSort: false, validate: false } const Definition = ({ definition, definitionUrl, location }) => !definition ? <Overlay> <img src={lincolnLogo} alt='' /> <h3>Render your Open API definition by adding the CORS-enabled URL above.</h3> <p>You can also set this with the <code>?url</code> query parameter.</p> </Overlay> : <Page definition={definition} location={location} specUrl={definitionUrl} /> Definition.propTypes = { definition: PropTypes.object, definitionUrl: PropTypes.string, location: PropTypes.object } const Failure = ({ error }) => <Overlay> <h3>Failed to load definition.</h3> <br /> <p>{error.message}</p> </Overlay> Failure.propTypes = { error: PropTypes.object } const Loading = ({ definitionUrl }) => <Overlay> <em>Loading <b>{definitionUrl}</b>...</em> </Overlay> Loading.propTypes = { definitionUrl: PropTypes.string }
src/views/Notes/NotesIndex.js
aplee29/online-notebook-app-client
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { NavLink } from 'react-router-dom'; import NoteCard from './NoteCard'; import { getNotes } from '../../redux/modules/Notes/actions'; class NotesIndex extends Component { componentDidMount() { const user_id = this.props.currentUser.id; const { token } = this.props; this.props.getNotes(user_id, token) } render() { const { notes } = this.props; return ( <div> {notes.length > 0 ? <p>* Click on a note to view full content *</p> : <p>* Create a <NavLink to="/notes/new">new note</NavLink> to get started *</p> } {notes.map(note => <NoteCard key={note.id} note={note} />)} </div> ) } } const mapStateToProps = (state) => { return { token: state.auth.token, currentUser: state.auth.currentUser, notes: state.notes.notesArr }; }; export default connect(mapStateToProps, { getNotes })(NotesIndex);
fields/types/password/PasswordFilter.js
michaelerobertsjr/keystone
import React from 'react'; import { SegmentedControl } from 'elemental'; const EXISTS_OPTIONS = [ { label: 'Is Set', value: true }, { label: 'Is NOT Set', value: false }, ]; function getDefaultValue () { return { exists: true, }; } var PasswordFilter = React.createClass({ propTypes: { filter: React.PropTypes.shape({ exists: React.PropTypes.oneOf(EXISTS_OPTIONS.map(i => i.value)), }), }, statics: { getDefaultValue: getDefaultValue, }, getDefaultProps () { return { filter: getDefaultValue(), }; }, toggleExists (value) { this.props.onChange({ exists: value }); }, render () { const { filter } = this.props; return <SegmentedControl equalWidthSegments options={EXISTS_OPTIONS} value={filter.exists} onChange={this.toggleExists} />; }, }); module.exports = PasswordFilter;
src/routes/Battle/components/BattleReady.js
eunvanz/handpokemon2
import React from 'react' import PropTypes from 'prop-types' import ContentContainer from 'components/ContentContainer' import Button from 'components/Button' import CenterMidContainer from 'components/CenterMidContainer' class BattleReady extends React.PureComponent { render () { const { onClickStart, auth, creditInfo, onClickDefense } = this.props const renderBody = () => { if (creditInfo.battleCredit > 0) { return ( <div> <h4>시합을 시작할 준비가 됐나?<br />시합이 시작된 이후에 도망친다면 패배처리되니 조심하라구.</h4> <Button text='시합시작!' onClick={onClickStart} icon='fa fa-gamepad' /> <Button className='m-l-5' text='수비배치' icon='fa fa-shield-check' color='orange' onClick={onClickDefense} /> </div> ) } else { return ( <div> <h4>시합 크레딧이 부족하군.<br />심심하면 교배나 진화를 통해 콜렉션을 강화해보는건 어때?</h4> <Button text='내 콜렉션' color='green' onClick={() => this.context.router(`/collection/${auth.uid}`)} /> <Button className='m-l-5' text='수비배치' icon='fa fa-shield-check' color='orange' onClick={onClickDefense} /> </div> ) } } return ( <ContentContainer title='시합준비' body={<CenterMidContainer bodyComponent={renderBody()} />} /> ) } } BattleReady.contextTypes = { router: PropTypes.object.isRequired } BattleReady.propTypes = { auth: PropTypes.object, onClickStart: PropTypes.func.isRequired, creditInfo: PropTypes.object.isRequired, onClickDefense: PropTypes.func.isRequired } export default BattleReady
demo/src/index.js
UnforbiddenYet/react-sleek-photo-gallery
import React from 'react'; import ReactDOM from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import Application from './application'; import styles from './styles.css'; const render = (Component) => { ReactDOM.render( <AppContainer> <Component/> </AppContainer>, document.getElementById('app') ); }; render(Application); // Hot Module Replacement API if (module.hot) { module.hot.accept('./application', () => { render(Application); }); }
src/server.js
CasualBot/learningReact
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import 'babel-core/polyfill'; import path from 'path'; import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Router from './routes'; import Html from './components/Html'; const server = global.server = express(); server.set('port', (process.env.PORT || 5000)); server.use(express.static(path.join(__dirname, 'public'))); // // Register API middleware // ----------------------------------------------------------------------------- server.use('/api/content', require('./api/content')); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- server.get('*', async (req, res, next) => { try { let statusCode = 200; const data = { title: '', description: '', css: '', body: '' }; const css = []; const context = { onInsertCss: value => css.push(value), onSetTitle: value => data.title = value, onSetMeta: (key, value) => data[key] = value, onPageNotFound: () => statusCode = 404, }; await Router.dispatch({ path: req.path, context }, (state, component) => { data.body = ReactDOM.renderToString(component); data.css = css.join(''); }); const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(statusCode).send('<!doctype html>\n' + html); } catch (err) { next(err); } }); // // Launch the server // ----------------------------------------------------------------------------- server.listen(server.get('port'), () => { /* eslint-disable no-console */ console.log('The server is running at http://localhost:' + server.get('port')); if (process.send) { process.send('online'); } });
src/svg-icons/alert/add-alert.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AlertAddAlert = (props) => ( <SvgIcon {...props}> <path d="M10.01 21.01c0 1.1.89 1.99 1.99 1.99s1.99-.89 1.99-1.99h-3.98zm8.87-4.19V11c0-3.25-2.25-5.97-5.29-6.69v-.72C13.59 2.71 12.88 2 12 2s-1.59.71-1.59 1.59v.72C7.37 5.03 5.12 7.75 5.12 11v5.82L3 18.94V20h18v-1.06l-2.12-2.12zM16 13.01h-3v3h-2v-3H8V11h3V8h2v3h3v2.01z"/> </SvgIcon> ); AlertAddAlert = pure(AlertAddAlert); AlertAddAlert.displayName = 'AlertAddAlert'; export default AlertAddAlert;
src/CommitTreePanel.js
cynicaldevil/gitrobotic
import React from 'react'; import LinearProgress from 'material-ui/LinearProgress'; import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card'; import CircleIcon from 'material-ui/svg-icons/av/fiber-manual-record'; import DiffPanel from './utils/DiffPanel'; import Git from 'nodegit'; var url = (() => { if (process.env.NODE_ENV === 'development') return require("file!./static/branchIcon.svg"); else return require("file?emitFile=false&name=[path]../../static/[name].[ext]!./static/branchIcon.svg"); })(); const constStyles = { fontFamily: `apple-system, BlinkMacSystemFont,"Segoe UI", Roboto,Helvetica,Arial,sans-serif, "Apple Color Emoji","Segoe UI Emoji", "Segoe UI Symbol"`, darkRed: '#b60a0a', grey: '#ededed', borderGrey: '#7e7e7e', yellow: '#b97005', }; class gitFunctions { static getCommits(repoPath, sha, that) { let pathToRepo = require('path').resolve(repoPath); Git.Repository.open(pathToRepo) .then(function(repo) { return repo.getCommit(sha); }) .then(function( commit ) { let history = commit.history( Git.Revwalk.SORT.Time); history.on("end", walk); history.start(); }) .done(); // function passed to history.on() listener to receive commits' info. // calls the setCommitState of App class to set new state let walk = (function(commitsArr){ let commits = []; commitsArr.forEach( function(commit) { commits.push({ sha: commit.sha(), author: commit.author().name(), email: commit.author().email(), date: commit.date().toString(), message: commit.message() }); }); //TODO: pass a promise object to the function and can the //history event listener from there that.returnRepo(commits); }).bind(that); } static getCommitDiff(sha, path) { return Git.Repository.open(require('path').resolve(path)) .then(function(repo) { return repo.getCommit(sha); }) .then(function(commit) { return commit.getDiff(); }); } } class Commit extends React.Component { constructor(props) { super(props); } handleOnClick = (commit) => { this.props.getCommitDiff(commit); // gitFunctions.getCommitDiff(commit.sha, this.props.repoPath); } render() { const styles={ span: { fontWeight: 500, }, commitDiv: { display: 'flex', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontFamily: '"Roboto", sans-serif', padding: 1, margin: 0, backgroundColor: '#FFFCF3', borderBottom: '2px solid #ffffff', color: constStyles.yellow, }, circleIcon: { minWidth: 13, maxWidth: 13, minHeight: 13, maxHeight: 13, }, message: { fontFamily: constStyles.fontFamily, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', padding: 2, margin: 4, fontSize: 15, }, sha: { fontSize: 12, fontFamily: 'monospace', }, sideBar: { position: 'relative', display: 'flex', alignItems: 'center', }, line: { position: 'absolute', left: '42%', width: 2, height: 90, backgroundColor: constStyles.yellow, } }; const commit = this.props.commit; return ( <div style={styles.commitDiv} onClick={() => { this.handleOnClick(commit) }} > <div style={styles.sideBar}> <div style={styles.line} /> <CircleIcon style={styles.circleIcon} color={constStyles.yellow}/> </div> <div style={styles.message} > <p style={{margin: 4}}>{commit.author}</p> {commit.sha?<span style={styles.sha}>{commit.sha.slice(0, 8)+' '}</span>:null} <span style={styles.span}>{commit.message}</span> </div> </div> ) } } class CommitInfo extends React.Component { constructor(props) { super(props); } render = () => { let commit = ''; if(this.props.commit) { commit = this.props.commit; } const styles= { main: { backgroundColor: '#fffdf8', fontFamily: constStyles.fontFamily, fontSize: 15, border: '2px solid'+ constStyles.yellow, borderBottom: '1px solid'+ constStyles.yellow, letterSpacing: -1, }, margin: { margin: 10, }, author: { margin: 7, fontSize: 32, fontWeight: 700, color: constStyles.yellow, }, message: { color: constStyles.yellow, fontSize: 20, }, dateSha: { color: constStyles.yellow, fontSize: 15, } }; return ( <div style={styles.main} > <div style={styles.margin} > <p style={styles.author} >{commit.author}</p> <p style={styles.message} >{commit.message}</p> <p style={styles.dateSha}> {commit.sha? <span style={{fontFamily: 'monospace', fontWeight: 700}} >{commit.sha.slice(0, 8)}</span> :null} <span >{' '+commit.date}</span> </p> </div> </div> ); } } class LoadingCommitInfo extends React.Component { constructor(props) { super(props); } render = () => { const styles={ main:{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', width: '65%', border: '2px solid'+ constStyles.yellow, color: constStyles.yellow, fontFamily: constStyles.fontFamily, fontSize: 40, fontWeight: 800, letterSpacing: -2, }, progressBar: { marginTop: 15, width: 200 } }; return ( <div style={styles.main} > Loading. Hang Tight! <LinearProgress color={constStyles.yellow} style={styles.progressBar} mode="indeterminate" /> </div> ); } } class CommitTree extends React.Component { constructor(props) { super(props); this.state = { commits: [], diffs: [], selected_commit: null, }; this.getCommitDiff = this.getCommitDiff.bind(this); } getCommitDiff = (commit) => { //for CommitInfo component this.setState({ selected_commit: commit }); gitFunctions.getCommitDiff(commit.sha, this.props.repo.path) .done((diffList) => { this.setState({ diffs: diffList, }); }); } returnRepo = (commits) => { this.setState({ commits : commits }); // to load the first commit's diff info by default this.getCommitDiff(commits[0]); } componentDidMount = () => { if(this.props.repo && this.props.branchRef.sha) { gitFunctions.getCommits(this.props.repo.path, this.props.branchRef.sha, this); } } componentWillReceiveProps = (newprops) => { if(newprops.repo && newprops.branchRef.sha) { this.setState({ selected_commit: null }); gitFunctions.getCommits(newprops.repo.path, newprops.branchRef.sha, this); } } render() { const styles={ commits: { border: '2px solid'+ constStyles.yellow, borderTop: '0px', borderRadius: '0px 0px 4px 4px', overflow: 'auto', height: 430, }, branchName: { color: constStyles.yellow, display: 'flex', fontFamily: constStyles.fontFamily, fontWeight: 500, fontSize: 20, backgroundColor: '#fff6dc', border: '2px solid'+ constStyles.yellow, borderBottom: '1px solid'+ constStyles.yellow, zIndex: 10, margin: 0, padding: 20, }, diffProps: { type: { color: constStyles.yellow, }, file: { color: constStyles.yellow, }, border: { color: constStyles.yellow, } } }; let rows=[]; this.state.commits.forEach((commit, index) => { rows.push(<Commit getCommitDiff={this.getCommitDiff} commit={commit} key={index} />); }); return ( <div style={{display: 'flex', overflow: 'auto', height: 500}} > <div style={{width: '35%'}}> <div style={styles.branchName}> <img style={{width: 15, height: 24}} src={url}></img> <div style={{width: 10}} /> <div style={{height: 24,}}>{' '+this.props.branchRef.name}</div> </div> <div style={styles.commits}> { rows } </div> </div> {this.state.selected_commit? <div style={{width: '65%', overflow: 'auto'}}> <CommitInfo commit={this.state.selected_commit} /> <div style={{overflow: 'auto', border: '2px solid'+constStyles.yellow}}> <DiffPanel diffs={this.state.diffs} diffStyle={styles.diffProps} /> </div> </div>: <LoadingCommitInfo />} </div> ) } } export default CommitTree;
react-ui/src/components/base/NavLink.js
MaGuangChen/resume-maguangchen
import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import * as actions from '../../actions/actions'; const NavLink = (props) => { const { login, dispatch } = props; const handleShowMenu = () => { dispatch(actions.showMenu(false)); } const handleShowLogin = () => { dispatch(actions.showLogin(true)); } const toContactMe = () => { dispatch(actions.showMenu(false)); } const removeCurrentUserId = () => { localStorage.removeItem('currentUserId'); localStorage.removeItem('currentUserAcount'); dispatch(actions.showMenu(false)); dispatch(actions.loginStatus(false)); dispatch(actions.showLogoutSussced(true)); } return ( <div className="navgation-bar_content"> <span onClick={handleShowMenu} className="navgation-bar_content_close"> X </span> { login.login && <div className="navgation-bar_content_link-block"> <Link className="navgation-bar_content_link" to="/user"> 前往您的帳戶管理頁面 </Link> <p onClick={removeCurrentUserId} className="navgation-bar_content_link"> 登出 Logout </p> </div> } { !login.login && <div className="navgation-bar_content_link-block"> <p onClick={handleShowLogin} className="navgation-bar_content_link" > 登入 Login </p> <a onClick={toContactMe} className="navgation-bar_content_link" href="#to-contact"> 創建帳號 Signup </a> </div> } </div> ); } export default connect()(NavLink);
examples/using-sqip/src/components/layout.js
mingaldrichgan/gatsby
import React from 'react' import PropTypes from 'prop-types' import Image from 'gatsby-image' import Polaroid from '../components/polaroid' import '../index.css' const Layout = ({ children, data }) => { const images = data.images.edges.map(image => ( <Polaroid image={image.node} key={image.node.name} /> )) const background = data.background.edges[0].node return ( <React.Fragment> <div style={{ position: `relative`, height: `66vw`, zIndex: 0, }} > <Image // Inject the sqip dataURI as base64 value fluid={{ ...background.childImageSharp.fluid, base64: background.childImageSharp.sqip.dataURI, }} alt={background.name} /> <div>{images}</div> </div> <div style={{ padding: `5vw` }}>{children}</div> </React.Fragment> ) } export default Layout Layout.propTypes = { children: PropTypes.node, data: PropTypes.object, }
imports/util/users.js
irvinlim/free4all
import { Meteor } from 'meteor/meteor'; import React from 'react'; import Avatar from 'material-ui/Avatar'; import { Link } from 'react-router'; import * as Colors from 'material-ui/styles/colors'; import { nl2br, propExistsDeep } from './helper'; import * as AvatarHelper from './avatar'; import * as IconsHelper from './icons'; const maybeGetUser = (userOrId) => { if (!userOrId) return null; if (userOrId._id) return userOrId; else return Meteor.users.findOne(userOrId); }; // Name export const getUserLink = (user, content=null, style={}) => { user = maybeGetUser(user); if (!user) return getFullName(user); if (!content) content = getFullName(user); return ( <Link to={`/profile/${user._id}`} style={ style }> { content } </Link> ); }; export const getFullName = (user) => { user = maybeGetUser(user); return propExistsDeep(user, ['profile', 'name']) ? user.profile.name : "Someone"; }; export const getFullNameWithLabelIfEqual = (user, user2, label) => { user = maybeGetUser(user); user2 = maybeGetUser(user2); const fullName = getFullName(user); if (user && user2 && user._id == user2._id) return <span>{ fullName } <span className="user-label">({ label })</span></span> else return <span>{ fullName }</span>; }; export const getFirstInitial = (user) => { user = maybeGetUser(user); return propExistsDeep(user, ['profile', 'name']) ? user.profile.name.charAt(0) : null; }; // Profile export const resolveGender = (gender) => { switch (gender.toLowerCase()) { case "male": return "Male"; case "female": return "Female"; default: return "Unspecified"; } }; export const getBio = (user) => { if (propExistsDeep(user, ['profile', 'bio'])) return nl2br(user.profile.bio); else return null; }; // Avatar const resolveFacebookAvatarSize = (size) => { if (size <= 50) return "small"; else if (size <= 100) return "normal"; else return "large"; }; export const getAvatarUrl = (user, size=64) => { user = maybeGetUser(user); if (!user) return ""; // Using native Cloudinary if (propExistsDeep(user, ['profile', 'avatarId'])) return AvatarHelper.getUrl(user.profile.avatarId, size); // Using Facebook Graph else if (propExistsDeep(user, ['services', 'facebook', 'id'])) return `https://graph.facebook.com/${user.services.facebook.id}/picture/?width=${size*2}&height=${size*2}`; // Using Google+ profile picture (provided on first login) else if (propExistsDeep(user, ['services', 'google', 'picture'])) return user.services.google.picture; // Using Gravatar else if (user.emails && user.emails.length) return Gravatar.imageUrl(user.emails[0].address, { size: size*2, default: 'mm', secure: true }); else return null; }; export const getAvatar = (user, size=64, style) => { const avatarUrl = getAvatarUrl(user, size); const firstInitial = getFirstInitial(user); if (avatarUrl) return <Avatar src={ avatarUrl } size={size} style={style} />; else if (firstInitial) return <Avatar backgroundColor="#097381" size={size} style={style}>{ firstInitial }</Avatar>; else return <Avatar backgroundColor={ Colors.grey700 } icon={ IconsHelper.materialIcon("person", _.extend({ color: Colors.grey50 }, style)) } />; }; // Authentication const hasService = (service) => (user) => propExistsDeep(user, ['services', service]); export const hasPasswordService = hasService('password'); export const hasFacebookService = hasService('facebook'); export const hasGoogleService = hasService('google'); export const hasIVLEService = hasService('ivle'); export const countServices = (user) => user ? Object.keys(user.services).filter(service => service != "resume").length : 0; // Admin-only methods export const adminGetFirstEmail = (user) => propExistsDeep(user, ['emails', 0, 'address']) ? user.emails[0].address : null; export const adminGetRegisteredDate = (user) => user && user.createdAt ? moment(user.createdAt).format('Do MMM YYYY') : null; export const adminGetLastLoginDate = (user) => { if (propExistsDeep(user, ['services', 'resume', 'loginTokens']) && user.services.resume.loginTokens.length) return moment(user.services.resume.loginTokens.reduce((p, x) => !p || x.when && moment(x.when).isAfter(p) ? x.when : p)).fromNow(); else return "Never"; };
components/Header.js
stevenctl/tweebot-ui
import React from 'react'; import cookie from 'react-cookie'; class Header extends React.Component{ constructor(){ super(); } componentWillMount(props){ this.props.doGetUserInfo(); } render(){ return ( <nav className="navbar navbar-inverse navbar-static-top"> <div className="container-fluid"> {/*Brand and toggle get grouped for better mobile display */} <div className="navbar-header"> <a className="navbar-brand" href="/">tweebot</a> {/* <ul className="navbar-service dropdown"> <a href="#" role="button">Menu</a> <ul className="dropdown-menu dropdown-menu-right"> <li><a href="#">Stuff</a></li> <li><a href="#">Other Stuff</a></li> <li><a href="#">Even More Stuff</a></li> </ul> </ul> */} </div> {/*Support and sign out links*/} <div className="collapse navbar-collapse"> <ul className="nav navbar-nav navbar-right navbar-account"> <li className="dropdown"> <a className="dropdown-toggle" data-toggle="dropdown" href="#" aria-expanded="false"> <i className="fa fa-user fa-fw"></i> <i className="fa fa-caret-down"></i> </a> <ul className="dropdown-menu dropdown-user"> <li><a href="#"><i className="fa fa-user fa-fw"></i> {this.props.userFullName}</a></li> <li><a href="#"><i className="fa fa-gear fa-fw"></i> Settings</a></li> <li className="divider"></li> <li onClick={this.props.doLogout.bind(this)}> <a href="#"><i className="fa fa-sign-out fa-fw"></i>Logout</a> </li> </ul> </li> </ul> </div> </div> </nav> ); } } export default Header;
docs/component.js
Means88/react-jsport
import React from 'react'; import { load } from '../dist/JSPort'; export class Component1 extends React.Component { componentDidMount() { this.changeText(); } componentDidUpdate() { this.changeText(); } changeText() { $('#hello').text('Changed by jQuery'); } render() { return ( <button id="hello" className="btn btn-default"> Bootstrap Button </button> ); } } class _Component2 extends React.Component { render() { return ( <div> Hello {this.props.text} {this.props.children} <span>{typeof _}</span> </div> ); } } export const Component2 = load('https://cdn.bootcss.com/lodash.js/4.17.4/lodash.min.js')(_Component2);
src/ReactBoilerplate/Scripts/server.js
pauldotknopf/react-dot-net
import React from 'react'; import ReactDOM from 'react-dom/server'; import Html from './helpers/Html'; import { match } from 'react-router'; import getRoutes from './routes'; import createHistory from 'react-router/lib/createMemoryHistory'; import RouterContext from 'react-router/lib/RouterContext'; import configureStore from './redux/configureStore'; import { Provider } from 'react-redux'; import isEmpty from 'utils/isEmpty'; export function renderView(callback, path, model, viewBag) { const history = createHistory(path); const store = configureStore(model, history); const result = { html: null, status: 404, redirect: null }; match( { history, routes: getRoutes(store), location: path }, (error, redirectLocation, renderProps) => { if (redirectLocation) { result.redirect = redirectLocation.pathname + redirectLocation.search; } else if (error) { result.status = 500; } else if (renderProps) { // if this is the NotFoundRoute, then return a 404 const isNotFound = renderProps.routes.filter((route) => route.status === 404).length > 0; result.status = isNotFound ? 404 : 200; const component = ( <Provider store={store}> <RouterContext {...renderProps} /> </Provider> ); if (!isEmpty(viewBag)) { // If the server provided anyhting in ASP.NET's ViewBag, hydrate it to the store/state. // The contents can be accessed on the client via `state.viewBag`. It exist for the initial // page load only, and will be cleared when navigating to another page on the client. store.dispatch({ type: '_HYDRATE_VIEWBAG', viewBag }); } result.html = ReactDOM.renderToString(<Html component={component} store={store} />); } else { result.status = 404; } }); callback(null, result); } export function renderPartialView(callback) { callback('TODO', null); }
src/Transition.js
azendoo/react-overlays
import React from 'react'; import transitionInfo from 'dom-helpers/transition/properties'; import addEventListener from 'dom-helpers/events/on'; import classnames from 'classnames'; let transitionEndEvent = transitionInfo.end; export const UNMOUNTED = 0; export const EXITED = 1; export const ENTERING = 2; export const ENTERED = 3; export const EXITING = 4; /** * The Transition component lets you define and run css transitions with a simple declarative api. * It works similar to React's own [CSSTransitionGroup](http://facebook.github.io/react/docs/animation.html#high-level-api-reactcsstransitiongroup) * but is specifically optimized for transitioning a single child "in" or "out". * * You don't even need to use class based css transitions if you don't want to (but it is easiest). * The extensive set of lifecyle callbacks means you have control over * the transitioning now at each step of the way. */ class Transition extends React.Component { constructor(props, context) { super(props, context); let initialStatus; if (props.in) { // Start enter transition in componentDidMount. initialStatus = props.transitionAppear ? EXITED : ENTERED; } else { initialStatus = props.unmountOnExit ? UNMOUNTED : EXITED; } this.state = {status: initialStatus}; this.nextCallback = null; } componentDidMount() { if (this.props.transitionAppear && this.props.in) { this.performEnter(this.props); } } componentWillReceiveProps(nextProps) { const status = this.state.status; if (nextProps.in) { if (status === EXITING) { this.performEnter(nextProps); } else if (this.props.unmountOnExit) { if (status === UNMOUNTED) { // Start enter transition in componentDidUpdate. this.setState({status: EXITED}); } } else if (status === EXITED) { this.performEnter(nextProps); } // Otherwise we're already entering or entered. } else { if (status === ENTERING || status === ENTERED) { this.performExit(nextProps); } // Otherwise we're already exited or exiting. } } componentDidUpdate() { if (this.props.unmountOnExit && this.state.status === EXITED) { // EXITED is always a transitional state to either ENTERING or UNMOUNTED // when using unmountOnExit. if (this.props.in) { this.performEnter(this.props); } else { this.setState({status: UNMOUNTED}); } } } componentWillUnmount() { this.cancelNextCallback(); } performEnter(props) { this.cancelNextCallback(); const node = React.findDOMNode(this); // Not this.props, because we might be about to receive new props. props.onEnter(node); this.safeSetState({status: ENTERING}, () => { this.props.onEntering(node); this.onTransitionEnd(node, () => { this.safeSetState({status: ENTERED}, () => { this.props.onEntered(node); }); }); }); } performExit(props) { this.cancelNextCallback(); const node = React.findDOMNode(this); // Not this.props, because we might be about to receive new props. props.onExit(node); this.safeSetState({status: EXITING}, () => { this.props.onExiting(node); this.onTransitionEnd(node, () => { this.safeSetState({status: EXITED}, () => { this.props.onExited(node); }); }); }); } cancelNextCallback() { if (this.nextCallback !== null) { this.nextCallback.cancel(); this.nextCallback = null; } } safeSetState(nextState, callback) { // This shouldn't be necessary, but there are weird race conditions with // setState callbacks and unmounting in testing, so always make sure that // we can cancel any pending setState callbacks after we unmount. this.setState(nextState, this.setNextCallback(callback)); } setNextCallback(callback) { let active = true; this.nextCallback = (event) => { if (active) { active = false; this.nextCallback = null; callback(event); } }; this.nextCallback.cancel = () => { active = false; }; return this.nextCallback; } onTransitionEnd(node, handler) { this.setNextCallback(handler); if (node) { addEventListener(node, transitionEndEvent, this.nextCallback); setTimeout(this.nextCallback, this.props.timeout); } else { setTimeout(this.nextCallback, 0); } } render() { const status = this.state.status; if (status === UNMOUNTED) { return null; } const {children, className, ...childProps} = this.props; Object.keys(Transition.propTypes).forEach(key => delete childProps[key]); let transitionClassName; if (status === EXITED) { transitionClassName = this.props.exitedClassName; } else if (status === ENTERING) { transitionClassName = this.props.enteringClassName; } else if (status === ENTERED) { transitionClassName = this.props.enteredClassName; } else if (status === EXITING) { transitionClassName = this.props.exitingClassName; } const child = React.Children.only(children); return React.cloneElement( child, { ...childProps, className: classnames( child.props.className, className, transitionClassName ) } ); } } Transition.propTypes = { /** * Show the component; triggers the enter or exit animation */ in: React.PropTypes.bool, /** * Unmount the component (remove it from the DOM) when it is not shown */ unmountOnExit: React.PropTypes.bool, /** * Run the enter animation when the component mounts, if it is initially * shown */ transitionAppear: React.PropTypes.bool, /** * A Timeout for the animation, in milliseconds, to ensure that a node doesn't * transition indefinately if the browser transitionEnd events are * canceled or interrupted. * * By default this is set to a high number (5 seconds) as a failsafe. You should consider * setting this to the duration of your animation (or a bit above it). */ timeout: React.PropTypes.number, /** * CSS class or classes applied when the component is exited */ exitedClassName: React.PropTypes.string, /** * CSS class or classes applied while the component is exiting */ exitingClassName: React.PropTypes.string, /** * CSS class or classes applied when the component is entered */ enteredClassName: React.PropTypes.string, /** * CSS class or classes applied while the component is entering */ enteringClassName: React.PropTypes.string, /** * Callback fired before the "entering" classes are applied */ onEnter: React.PropTypes.func, /** * Callback fired after the "entering" classes are applied */ onEntering: React.PropTypes.func, /** * Callback fired after the "enter" classes are applied */ onEntered: React.PropTypes.func, /** * Callback fired before the "exiting" classes are applied */ onExit: React.PropTypes.func, /** * Callback fired after the "exiting" classes are applied */ onExiting: React.PropTypes.func, /** * Callback fired after the "exited" classes are applied */ onExited: React.PropTypes.func }; // Name the function so it is clearer in the documentation function noop() {} Transition.displayName = 'Transition'; Transition.defaultProps = { in: false, unmountOnExit: false, transitionAppear: false, timeout: 5000, onEnter: noop, onEntering: noop, onEntered: noop, onExit: noop, onExiting: noop, onExited: noop }; export default Transition;
components/_entry/test.js
joeybaker/rachelandjoey
import test from 'tape' import React from 'react' import {addons} from 'react/addons' import Entry from './index.jsx' const {TestUtils} = addons const {Simulate, renderIntoDocument, isElement, createRenderer} = TestUtils const getReactNode = (dom, node) => TestUtils.findRenderedDOMComponentWithTag(dom, node) const getDOMNode = (dom, node) => getReactNode(dom, node).getDOMNode() const getDOMNodes = (dom, type) => TestUtils.scryRenderedDOMComponentsWithTag(dom, type) const getDOMNodeText = (dom, node) => getDOMNode(dom, node).textContent test('Entry: constructor', (t) => { const entry = React.createElement(Entry) t.ok( isElement(entry) , 'is a valid react component' ) t.end() }) // TODO: delete me. I'm just an example! test('Entry rendered DOM', (t) => { const name = 'Bert' const entry = React.createElement(Entry, {name}) const dom = renderIntoDocument(entry) t.equal( getDOMNodeText(dom, 'h1') , name , 'renders the `name` prop' ) t.end() })
src/components/Exercises.js
Greynight/Exercises
import React from 'react'; import SelectField from 'material-ui/SelectField'; import MenuItem from 'material-ui/MenuItem'; const Exercises = ({ exercises, value, handleExerciseChange }) => { return ( <SelectField fullWidth={true} floatingLabelText="Exercises" value={value} onChange={handleExerciseChange} > {exercises.map(exercise => <MenuItem key={exercise.id} value={exercise.id} primaryText={exercise.name} />)} </SelectField> ); }; export default Exercises;
app/components/Rectangle.js
amyrebecca/react-animation
import React from 'react' export default class Rectangle extends React.Component { constructor(props) { super(props); } componentDidMount() { var animator = function(){ this.forceUpdate() window.requestAnimationFrame(animator.bind(this)) } window.requestAnimationFrame(animator.bind(this)) } scaleX(val){ return Math.floor(val*this.props.dims.width/100.0) } scaleY(val){ return Math.floor(val*this.props.dims.height/100.0) } render() { var when = new Date().getTime() var offset = (when/100)%100 var two = 30+30*Math.cos(when/200) var color='hsla(150,80%,'+(20+40*(1+Math.sin(when/2000)))+'%,'+(1+Math.cos(when/300)/2.0)+')' return ( <rect height={this.scaleY(30)} width={this.scaleX(30)} x={Math.floor(1.3*this.scaleX(offset-15))} y={Math.floor(1.3*this.scaleY(two-15))} fill={color}/> ); } }