path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
Realization/frontend/czechidm-core/src/components/advanced/ModalProgressBar/ModalProgressBar.js
bcvsolutions/CzechIdMng
import React from 'react'; import PropTypes from 'prop-types'; // import * as Basic from '../../basic'; import ProgressBar from '../ProgressBar/ProgressBar'; /** * Progressbar in modal window. * * @author Radek Tomiška */ export default function ModalProgressBar(props) { const { rendered, showLoading, show, counter, count, text } = props; // if (!rendered) { return null; } // return ( <Basic.Modal show={ show } showLoading={ showLoading } bsSize="large" backdrop="static"> <Basic.Modal.Header text={ text }/> <Basic.Modal.Body> <ProgressBar max={ count } now={ counter } rendered={ !showLoading }/> </Basic.Modal.Body> </Basic.Modal> ); } ModalProgressBar.propTypes = { ...Basic.AbstractContextComponent.propTypes, /** * ProgressBar is shown */ show: PropTypes.bool, /** * Main title - modal header text */ text: PropTypes.string, /** * Current processed counter */ counter: PropTypes.number, /** * Size / maximum */ count: PropTypes.number }; ModalProgressBar.defaultProps = { ...Basic.AbstractContextComponent.defaultProps, show: false, counter: 0, count: 0, text: 'Probíhá zpracování' // TODO: locale };
packages/reactor-tests/src/tests/SenchaTestHooks.js
markbrocato/extjs-reactor
import React from 'react'; import { Button } from '@extjs/ext-react'; export default function SenchaTestHooks() { return <Button text="Target" itemId="target"/> }
src/index.js
tolylya/octoberry
/* eslint-disable import/default */ import React from 'react'; import { render } from 'react-dom'; import { browserHistory } from 'react-router'; import { AppContainer } from 'react-hot-loader'; import Root from './components/Root'; import configureStore from './store/configureStore'; require('./favicon.ico'); // Tell webpack to load favicon.ico import './styles/styles.scss'; // Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page. import { syncHistoryWithStore } from 'react-router-redux'; const store = configureStore(); // Create an enhanced history that syncs navigation events with the store const history = syncHistoryWithStore(browserHistory, store); render( <AppContainer> <Root store={store} history={history} /> </AppContainer>, document.getElementById('app') ); if (module.hot) { module.hot.accept('./components/Root', () => { const NewRoot = require('./components/Root').default; render( <AppContainer> <NewRoot store={store} history={history} /> </AppContainer>, document.getElementById('app') ); }); }
src/main/js/my-app/src/components/NotFound.js
myapos/ClientManagerSpringBoot
import React from 'react'; const NotFound = () => <div> The page that you requested has not found </div>; NotFound.contextTypes = { router: React.PropTypes.object.isRequired, }; export default NotFound;
src/index.js
Maachi/Admin-FrontEnd
import React from 'react'; import { Router, Route, browserHistory } from 'react-router'; import { render } from 'react-dom'; import Login from './pages/Login'; import Dashboard from './pages/Dashboard'; import CreateProcess from './pages/CreateProcess'; import './static/sass/main.scss'; render(( <Router history={browserHistory}> <Route path="/" component={Login}/> <Route path="/:firm/dashboard" component={Dashboard}/> <Route path="/:firm/create/process" component={CreateProcess}/> </Router> ), document.getElementById('gestion-app'));
imports/ui/components/form/remove-giveaway-dialog.js
irvinlim/free4all
import React from 'react'; import ConfirmDialog from '../../layouts/confirm-dialog'; const RemoveGiveawayDialog = (props) => ( <ConfirmDialog title="Are you sure?" {...props}> Are you sure you would like to remove this giveaway? </ConfirmDialog> ); export default RemoveGiveawayDialog;
AirFront/point/profile.js
sunshinezxf/Airburg
import React from 'react'; import { NavBar, Button, List, WhiteSpace, WingBlank, InputItem, Toast, } from 'antd-mobile'; const Item = List.Item; var profile = {id: '', name: '', phone: '', point: '123'}; export const PointCenter = React.createClass({ getDefaultProps(){ return {profile:profile} }, render(){ const {profile}=this.props; return ( <div> <NavBar iconName="" mode="light">我的积分</NavBar> <WhiteSpace/> <Item> <div className="bigTile" style={{height:'30vh'}}> <p>当前积分</p> {profile.point} </div> </Item> <WhiteSpace size="lg"/> <Item> <div className="bigTile" style={{height:'40vh'}}> 积分商城建设中<br/><br/> 敬请期待 </div> </Item> </div> ); } });
src/containers/NotFound/NotFound.js
martinrp/reduxgitresume
import React from 'react'; export default function NotFound() { return ( <div className="container"> <h1>Doh! 404!</h1> <p>These are <em>not</em> the droids you are looking for!</p> </div> ); }
src/components/Statement.js
lukebelliveau/aclu-matchers
import React from 'react'; import { StyleSheet, css } from 'aphrodite'; const styles = StyleSheet.create({ wrapperStyle: { padding: '50px', paddingTop: 0, '@media (max-width: 740px)': { padding: '0px', } }, body: { borderBottom: '2px solid #eee', borderTop: '2px solid #eee', paddingTop: 25, paddingBottom: 60, margin: '0 auto', marginTop: 40, maxWidth: 1024, '@media (max-width: 740px)': { padding: '15px', width: '90%' } }, h2: { textAlign: 'left', margin: '30px 0' }, p: { textAlign: 'left', marginTop: 30, marginBottom: 0 }, strong: { textAlign: 'left', display: 'block', marginTop: 30, fontSize: 18, '@media (max-width: 740px)': { fontSize: 14, } }, quote: { borderLeft: '5px solid #96989B' } }); export default () => ( <div className={css(styles.wrapperStyle)}> <div className={css(styles.body)}> <h2 className={css(styles.h2)}>Why donate?</h2> <blockquote className={css(styles.quote)}> <p> Extreme vetting is just a euphemism for discrimination against Muslims. Identifying specific countries with Muslim majorities and carving out exceptions for minority religions flies in the face of the constitutional principle that bans the government from either favoring or discriminating against particular religions. Any effort to discriminate against Muslims and favor other religions runs afoul of the First Amendment. </p> <footer> - Anthony D. Romero, Executive Director, American Civil Liberties Union </footer> </blockquote> <strong className={css(styles.strong)}>We wholeheartedly agree with this statement - and we're not alone.</strong> <p className={css(styles.p)}> People around the nation have offered to match our donations to the ACLU; all they need from us is a tweet with the donation receipt. Among others, we have matched donations with Ajay Chopra, Sia, and Jesse Tyler. </p> </div> </div> );
example/superchatExample/App.js
super-chat/react-native-superchat
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { Chat } from 'react-native-superchat'; import messages from './data/messages' import { Platform, StyleSheet, Text, View } from 'react-native'; export default class App extends Component { state = { messages: messages } constructor(props) { super(props); this.handleOnSend = this.handleOnSend.bind(this); } render() { return ( <Chat messages={this.state.messages} user={{id: 1}} onSend={this.handleOnSend} /> ); } handleOnSend(msg) { this.setState({messages: this.state.messages.concat(msg)}, () => { const response = { text: 'OK', messageId: (new Date()).getTime(), user: { ...msg.user, id: 2} }; setTimeout(() => { this.setState({messages: this.state.messages.concat(response)}); }, 1000); }); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });
pkg/interface/chat/src/js/components/lib/welcome.js
jfranklin9000/urbit
import React, { Component } from 'react'; export class Welcome extends Component { constructor() { super(); this.state = { show: true } this.disableWelcome = this.disableWelcome.bind(this); } disableWelcome() { this.setState({ show: false }); localStorage.setItem("urbit-chat:wasWelcomed", JSON.stringify(true)); } render() { let wasWelcomed = localStorage.getItem("urbit-chat:wasWelcomed"); if (wasWelcomed === null) { localStorage.setItem("urbit-chat:wasWelcomed", JSON.stringify(false)); return wasWelcomed = false; } else { wasWelcomed = JSON.parse(wasWelcomed); } let inbox = !!this.props.inbox ? this.props.inbox : {}; return ((!wasWelcomed && this.state.show) && (inbox.length !== 0)) ? ( <div className="ma4 pa2 bg-welcome-green bg-gray1-d white-d"> <p className="f8 lh-copy">Chats are instant, linear modes of conversation. Many chats can be bundled under one group.</p> <p className="f8 pt2 dib pointer bb" onClick={(() => this.disableWelcome())}> Close this </p> </div> ) : <div/> } } export default Welcome
www/containers/BlogsPage.js
DremyGit/dremy-blog
import React from 'react'; import Helmet from 'react-helmet'; import { connect } from 'react-redux'; import BlogItem from '../components/BlogPanel/BlogItem'; import BlogListTitle from '../components/BlogPanel/BlogListTitle'; import Pager from '../components/Pager/Pager'; import config from '../config'; import { fetchBlogListIfNeed, } from '../actions/blog'; import { dispatchFetch } from '../helpers/fetchUtils'; import Loading from '../components/Loading/Loading'; @connect(state => ({ blogEntities: state.getIn(['blog', 'entities']), isBlogListFetched: state.getIn(['blog', 'isFetched']), categoryEntities: state.getIn(['category', 'entities']), tagEntities: state.getIn(['tag', 'entities']), })) export default class BlogPage extends React.Component { static fetches = [ fetchBlogListIfNeed, ]; componentDidMount() { dispatchFetch(BlogPage.fetches, this.props); } render() { const { blogEntities, isBlogListFetched, categoryEntities, tagEntities, params, location, } = this.props; if (!isBlogListFetched) { return <Loading />; } const pathArr = location.pathname.split('/'); const pageType = pathArr[1]; let filtedBlogs; let title; let baseUrl = pageType; if (pageType === 'category') { filtedBlogs = blogEntities.filter(blog => blog.get('category') === params.categoryName); title = `分类「${categoryEntities.getIn([params.categoryName, 'name'])}」`; baseUrl += `/${pathArr[2]}`; } else if (pageType === 'tag') { filtedBlogs = blogEntities.filter(blog => blog.get('tags').includes(params.tagName)); title = `标签「${tagEntities.getIn([params.tagName, 'name'])}」`; baseUrl += `/${pathArr[2]}`; } else if (pageType === 'archive') { filtedBlogs = blogEntities.filter(blog => new Date(blog.get('create_at')).getFullYear() === +params.year); title = `${+params.year} 年`; baseUrl += `/${pathArr[2]}`; } else if (pageType === 'search') { const words = new RegExp(params.words, 'i'); filtedBlogs = blogEntities.filter(blog => blog.get('title').search(words) !== -1 || blog.getIn(['html', 'summary']).replace(/<*.?>/g, '').search(words) !== -1); title = `搜索「${params.words}」`; baseUrl += `/${pathArr[2]}`; } else { filtedBlogs = blogEntities; } const page = +params.pageNum || 1; const size = config.blogItemPerPage; const showBlogs = filtedBlogs .sort((a, b) => { if (a.get('create_at') < b.get('create_at')) return 1; if (a.get('create_at') > b.get('create_at')) return -1; return 0; }) .valueSeq() .skip((page - 1) * size) .take(size); return ( <div> <Helmet title={`${title || '首页'} Dremy_博客`} meta={[ { name: 'description', content: 'Dremy_博客 博客列表' }, ]} /> { title && <BlogListTitle title={title} count={filtedBlogs.size} /> } <div> {showBlogs.map(blog => <BlogItem key={blog.get('code')} blog={blog} category={categoryEntities.get(blog.get('category'))} tags={blog.get('tags').map(tag => tagEntities.get(tag))} />, ).toArray()} </div> <Pager totalNum={filtedBlogs.size} currentPage={page} perPage={config.blogItemPerPage} showPage={config.showPageNum} baseUrl={`/${baseUrl || 'blog'}`} /> </div> ); } }
05_ES6/Code/fork-es6/app/components/StorePane.js
joacoleonelli/react-zerotohero
import React from 'react'; import Store from './Store'; import autoBind from 'react-autobind'; class StorePane extends React.Component { constructor(props) { super(props); autoBind(this); } renderStore(store){ return <Store key={store} index={store} details={this.props.stores[store]} />; } render() { return ( <div id="stores-pane" className="column"> <h1>Stores & Ovens</h1> <ul> {Object.keys(this.props.stores).map(this.renderStore)} </ul> </div> ) } }; export default StorePane;
src/GoalInfoNavigation/index.js
christianalfoni/ducky-components
import React from 'react'; import PropTypes from 'prop-types'; import Wrapper from '../Wrapper'; import Typography from '../Typography'; import IconAvaWrapper from '../IconAvaWrapper'; import styles from './styles.css'; function GoalInfoNavigation(props) { return ( <Wrapper className={styles.outerWrapper} size={"short"} > <IconAvaWrapper className={props.currentSlide === 1 ? styles.iconInactive : styles.iconActive} icon={'icon-keyboard_arrow_left'} onClick={props.handleLeftClick} /> <Typography className={styles.typo} type={"caption2Normal"} > {props.currentSlide}{" / "}{props.slideCount} </Typography> <IconAvaWrapper className={props.currentSlide === props.slideCount ? styles.iconInactive : styles.iconActive} icon={'icon-keyboard_arrow_right'} onClick={props.handleRightClick} /> </Wrapper> ); } GoalInfoNavigation.propTypes = { currentSlide: PropTypes.number, handleLeftClick: PropTypes.func, handleRightClick: PropTypes.func, slideCount: PropTypes.number }; export default GoalInfoNavigation;
app/components/PreSplash/PreSplash.js
heptaman/Voluncheering
import React, { Component } from 'react'; import PropTypes from 'prop-types' import { View, Text, StyleSheet, TouchableOpacity, Animated } from 'react-native' import { connect } from 'react-redux' import { colors, fontSizes } from '~/styles' import { logout } from '~/actions/auth' class PreSplash extends Component { state = { rotation: new Animated.Value(0) } handleCancel = () => { this.props.dispatch(logout()) } componentDidMount() { this.interval = setInterval(() => { Animated.sequence([ Animated.timing(this.state.rotation, {toValue: -1, duration: 150}), Animated.timing(this.state.rotation, {toValue: 1, duration: 150}), Animated.timing(this.state.rotation, {toValue: 0, duration: 250}) ]).start() }, 1000) } componentWillUnmount() { window.clearInterval(this.interval) } getTransform() { return { transform: [{ rotate: this.state.rotation.interpolate({ inputRange: [-1, 1], outputRange: ['-20deg', '20deg'] }) }] } } render() { return ( <View style={styles.container}> <Animated.Image style={[styles.image, this.getTransform()]} source={require('../../images/logo.gif')} /> <Text style={styles.message}>We are logging you in...</Text> {/* <View style={styles.buttonContainer}> <TouchableOpacity onPress={this.handleCancel} style={styles.cancelButton}> <Text style={styles.cancelText}>Cancel</Text> </TouchableOpacity> </View> */} </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: colors.white, alignItems: 'center', justifyContent: 'center' }, image: { resizeMode: 'contain', height: 300 }, message: { marginTop: 32, fontSize: fontSizes.secondary, }, buttonContainer: { marginTop: 48, width: '100%', alignItems: 'center' }, cancelButton: { height: 40, width: 240, backgroundColor: colors.red, alignItems: 'center', borderRadius: 8, padding: 10, }, cancelText: { color: colors.background, fontSize: fontSizes.secondary, }, }) export default connect()(PreSplash)
electronApp/node_modules/react-element-to-jsx-string/AnonymousStatelessComponent.js
eyang414/superFriend
import React from 'react'; export default function(props) { let {children} = props; // eslint-disable-line react/prop-types return <div>{children}</div>; }
docs/app/Examples/modules/Modal/Types/index.js
mohammed88/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' import { Message } from 'semantic-ui-react' const ModalExamples = () => ( <ExampleSection title='Types'> <ComponentExample title='Modal' description='A standard modal.' examplePath='modules/Modal/Types/ModalExampleModal' /> <ComponentExample title='Basic' description='A modal can reduce its complexity.' examplePath='modules/Modal/Types/ModalExampleBasic' /> <ComponentExample title='Scrolling Modal' description={[ 'When your modal content exceeds the height of the browser the scrollable area will automatically', 'expand to include just enough space for scrolling, without scrolling the page below.', ].join(' ')} examplePath='modules/Modal/Types/ModalExampleScrolling' > <Message warning> <code>&lt;Modal.Content image /&gt;</code> requires an image with wrapped markup: <code>&lt;Image wrapped /&gt; </code> </Message> </ComponentExample> <ComponentExample title='Multiple Modals' description='Multiple modals can be displayed on top of one another.' examplePath='modules/Modal/Types/ModalExampleMultiple' /> <ComponentExample title='Controlled' description='A modal can be a controlled component' examplePath='modules/Modal/Types/ModalExampleControlled' /> </ExampleSection> ) export default ModalExamples
packages/material-ui-icons/src/SpeakerNotes.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM8 14H6v-2h2v2zm0-3H6V9h2v2zm0-3H6V6h2v2zm7 6h-5v-2h5v2zm3-3h-8V9h8v2zm0-3h-8V6h8v2z" /></g> , 'SpeakerNotes');
website/core/WebPlayer.js
skevy/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule WebPlayer */ 'use strict'; var Prism = require('Prism'); var React = require('React'); var WEB_PLAYER_VERSION = '1.2.6'; /** * Use the WebPlayer by including a ```ReactNativeWebPlayer``` block in markdown. * * Optionally, include url parameters directly after the block's language. For * the complete list of url parameters, see: https://github.com/dabbott/react-native-web-player * * E.g. * ```ReactNativeWebPlayer?platform=android * import React from 'react'; * import { AppRegistry, Text } from 'react-native'; * * const App = () => <Text>Hello World!</Text>; * * AppRegistry.registerComponent('MyApp', () => App); * ``` */ var WebPlayer = React.createClass({ parseParams: function(paramString) { var params = {}; if (paramString) { var pairs = paramString.split('&'); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split('='); params[pair[0]] = pair[1]; } } return params; }, render: function() { var hash = `#code=${encodeURIComponent(this.props.children)}`; if (this.props.params) { hash += `&${this.props.params}`; } return ( <div className={'web-player'}> <Prism>{this.props.children}</Prism> <iframe style={{marginTop: 4}} width="880" height={this.parseParams(this.props.params).platform === 'android' ? '425' : '420'} data-src={`//cdn.rawgit.com/dabbott/react-native-web-player/gh-v${WEB_PLAYER_VERSION}/index.html${hash}`} frameBorder="0" /> </div> ); }, }); module.exports = WebPlayer;
client-web/client-web/src/components/ListViewProperty.js
ppsari/final
import React from 'react' import { Link } from 'react-router-dom' import axios from 'axios' import prettyMoney from '../helpers/prettyMoney' const api = 'https://api.room360.ga/api' class ListViewProperty extends React.Component { constructor(props){ super(props) this.state={ properties:[] } } render () { return ( <div className="ListViewProperty"> {this.state.properties.map((prp,index)=>{ console.log(prp); return <div className="media m-t-20 shadow" key={index}> <div className="media-left" style={{minHeight: 124}}> <div style={{width: 120, height: 160, overflow: 'hidden'}}> <img style={{height: '100%'}} src={prp.image} alt="64x64" /> </div> </div> <div className="media-body padding-15"> <h5 className="extra-bold">{prp.name}</h5> <span className="lnr lnr-map-marker m-r-5 green"></span><span>{prp.city}</span> | <span className="lnr lnr-home m-r-5 m-l-5 green"></span><span> For {prp.status}</span><br/> <small className="excerpt italic">Price : {prettyMoney(prp.price.amount)}</small><br/> <small className="excerpt italic">Posted At : {prp.createdDate.split('T')[0]}</small> </div> <div className="media-right padding-15"> <div className="pull-right"> <Link to={`/dashboard/property/detail/${prp.status}/${prp._id}`}> <button type="submit" className="btn-round m-t-0 p-l-20 p-r-20 p-t-5 p-b-5 btn-primary btn-same"> <small>See Detail</small> </button> </Link> <Link to={`/dashboard/property/add-room/${prp.status}/${prp._id}`}> <button type="submit" className="btn-round m-t-0 p-l-20 p-r-20 p-t-5 p-b-5 btn-line btn-same"> <small>Add Room</small> </button> </Link> <button type="submit" className="btn-round m-t-0 p-l-20 p-r-20 p-t-5 p-b-5 btn-danger btn-same" onClick={()=>this.deleteProp(prp.status,prp._id,index)}> <small>Delete Room</small> </button> </div> </div> </div> })} </div> ) } deleteProp(status,id,index){ if(window.confirm(`Are you sure you want to delete this property?`)){ const token = JSON.parse(localStorage.getItem('token')).token if(status === 'rent'){ axios.delete(api+`/propertyRent/${id}`,{headers:{token: token}}) .then(response=>{ this.state.properties.splice(index,1) this.setState({ properties: this.state.properties }) }) } else{ axios.delete(api+`/propertySell/${id}`,{headers:{token: token}}) .then(response=>{ this.state.properties.splice(index,1) this.setState({ properties: this.state.properties }) }) } } else { return false } } componentDidMount(){ let token = JSON.parse(localStorage.getItem(`token`)).token axios.get(api+`/propertyRent/owner`,{headers:{token:token}}) .then(pr=>{ if(pr.data.length > 0){ this.setState({ properties: this.state.properties.concat(pr.data) }) } }) axios.get(api+`/propertySell/owner`,{headers:{token:token}}) .then(ps=>{ if(ps.data.length > 0){ this.setState({ properties: this.state.properties.concat(ps.data) }) } }) } } export default ListViewProperty
app/components/map-canvas.js
laynemcnish/walksafely-react
import React from 'react'; import PureComponent from 'react-pure-render/component'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { ActionCreators } from '../actions'; const { initMap } = ActionCreators; export class MapCanvas extends PureComponent { constructor(props) { super(props); } render () { return ( <div> <h1>Map Canvas</h1> </div> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ initMap }, dispatch); } export default connect(undefined, mapDispatchToProps)(MapCanvas);
old_examples/dyno/app.js
mzabriskie/react-tabs
import React from 'react'; import { render } from 'react-dom'; import Modal from 'react-modal'; import { Tab, Tabs, TabList, TabPanel } from '../../src/index'; import '../../style/react-tabs.css'; Modal.setAppElement(document.getElementById('example')); class App extends React.Component { constructor(props) { super(props); this.state = { isModalOpen: false, selectedIndex: -1, tabs: [ { label: 'Foo', content: 'This is foo' }, { label: 'Bar', content: 'This is bar' }, { label: 'Baz', content: 'This is baz' }, { label: 'Zap', content: 'This is zap' }, ], }; } openModal = () => { this.setState({ isModalOpen: true, }); } closeModal = () => { this.setState({ isModalOpen: false, }); } addTab = () => { const label = this.refs.label.value; const content = this.refs.content.value; this.setState({ tabs: [ ...this.state.tabs, { label, content }, ], selectedIndex: this.state.tabs.length, }); this.closeModal(); } removeTab = (index) => { this.setState({ tabs: this.state.tabs.filter((tab, i) => i !== index), selectedIndex: Math.max(this.state.selectedIndex - 1, 0), }); } render() { return ( <div style={{ padding: 50 }}> <p> <button onClick={this.openModal}>+ Add</button> </p> <Tabs selectedIndex={this.state.selectedIndex} onSelect={selectedIndex => this.setState({ selectedIndex })} > <TabList> {this.state.tabs.map((tab, i) => ( <Tab key={i}> {tab.label} <a href="#" onClick={() => this.removeTab(i)}>✕</a> </Tab> ))} </TabList> {this.state.tabs.map((tab, i) => <TabPanel key={i}>{tab.content}</TabPanel>)} </Tabs> <Modal isOpen={this.state.isModalOpen} onRequestClose={this.closeModal} style={{ width: 400, height: 350, margin: '0 auto' }} contentLabel="tabs" > <h2>Add a Tab</h2> <label htmlFor="label">Label:</label><br /> <input id="label" type="text" ref="label" /><br /><br /> <label htmlFor="content">Content:</label><br /> <textarea id="content" ref="content" rows="10" cols="50" /><br /><br /> <button onClick={this.addTab}>OK</button>{' '} <button onClick={this.closeModal}>Cancel</button> </Modal> </div> ); } } render(<App />, document.getElementById('example'));
app/assets/scripts/main.js
thadk/oc-map
'use strict'; import 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import MapWidget from './views/map-widget'; import TableWidget from './views/table-widget'; window.OC_MAP = { initMapWidget: containerEl => { render(( <MapWidget /> ), containerEl); }, initTableWidget: containerEl => { render(( <TableWidget /> ), containerEl); } };
js/components/ClinicTab.js
tausifmuzaffar/bisApp
import React, { Component } from 'react'; import { connect } from 'react-redux'; var moment = require('moment'); import { actions } from 'react-native-navigation-redux-helpers'; import { Image, WebView, AsyncStorage, Linking } from 'react-native'; import { Container, Header, Subtitle, Title, Content, H2, Button, Footer, FooterTab,Card, CardItem, Text, Body, Left, Right, Icon, Segment, Spinner, Separator, List, ListItem, Toast } from 'native-base'; import { Actions } from 'react-native-router-flux'; import PrayerTimes from './PrayerTimes'; import JummahTimes from './JummahTimes'; import { openDrawer } from '../actions/drawer'; import { Col, Row, Grid } from 'react-native-easy-grid'; import styles from './styles'; const { popRoute, } = actions; class ClinicTab extends Component { constructor(props) { super(props); this.state = { schedule: {}, }; } getAnnouncement(){ fetch("http://rcca.aleemstudio.com/MobileSupport/Get6MonthSchedule") .then((response) => response.json()) .then((responseJson) => { this.setState({schedule: responseJson}); }) .done(); } componentWillMount() { this.getAnnouncement(); } render() { function replaceAll(str, find, replace) { return str.replace(new RegExp(find, 'g'), replace); } function cleanString(javaString){ let output; output = replaceAll(javaString, "\r\n", ''); output = replaceAll(output, "\n", ''); output = replaceAll(output, "\r", ''); output = replaceAll(output, "&nbsp;", ' '); return output; } var sche = this.state.schedule; if(sche !== {}){ return ( <Content style={{ backgroundColor: '#F5F5F5' }} > <CardItem style={{ backgroundColor: '#9575CD' }}> <Text style={{ color: '#FFF', fontSize: 16 }}>For appointments call </Text> <Text style={{ color: '#FFF', fontSize: 16, textDecorationLine: 'underline'}} onPress={() => Linking.openURL('tel:2058794247')}>(205) 879 - 4247</Text> <Text style={{ color: '#FFF', fontSize: 16 }}> option 4</Text> </CardItem> {Object.keys(sche).map(function(key,i) { return( <Content key={i}> {((sche[key].doc1 !== null)||(sche[key].nur1 !== null)|| (sche[key].doc1 !== null))&&(moment(key)>=moment()) ? <Content> <Separator bordered noTopBorder> <Text style={{fontSize: 14}}>{moment(key).format('MMMM D, YYYY')}</Text> </Separator> <ListItem> <Text style={{fontSize: 15, fontWeight: 'bold'}}>Doctor{sche[key].doc2 !== null ? '(s)' : ''}:</Text> <Text style={{fontSize: 15}}> {sche[key].doc1}{sche[key].doc2 !== null ? ',' : ''} {sche[key].doc2}</Text> </ListItem> <ListItem> <Text style={{fontSize: 15, fontWeight: 'bold'}}>Nurse{sche[key].nur2 !== null ? '(s)' : ''}:</Text> <Text style={{fontSize: 15}}> {sche[key].nur1}{sche[key].nur2 !== null ? ',' : ''} {sche[key].nur2}</Text> </ListItem> <ListItem> <Text style={{fontSize: 15, fontWeight: 'bold'}}>Volunteer{sche[key].vol2 !== null ? '(s)' : ''}:</Text> <Text style={{fontSize: 15}}> {sche[key].vol1}{sche[key].vol2 !== null ? ',' : ''} {sche[key].vol2}</Text> </ListItem> </Content> : <Content></Content>} </Content> ); })} </Content> ); } else { return (<Spinner color="blue" />); } } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), popRoute: key => dispatch(popRoute(key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(ClinicTab);
packages/bonde-admin-canary/src/scenes/Auth/scenes/ResetPassword/InvalidToken.spec.js
ourcities/rebu-client
import test from 'ava' import React from 'react' import { shallow } from 'enzyme' import { Trans } from 'react-i18next' import { Title } from 'bonde-styleguide' import Link, { ButtonLink } from 'components/Link' import InvalidToken from './InvalidToken' test.beforeEach(t => { const i18n = key => key t.context.node = shallow(<InvalidToken t={i18n} />) }) test('should render header infos', t => { const { node } = t.context const title = node.find(Title.H2) const subtitle = node.find(Title.H4).at(0) t.is(title.props().children, 'resetPassword.invalidToken.title') t.is(subtitle.props().children, 'resetPassword.invalidToken.subtitle') }) test('should render a link to forget password', t => { const { node } = t.context const description = node.find(Title.H4).at(1) const trans = description.find(Trans) const link = trans.find(Link) t.is(link.props().to, '/auth/forget-password') t.is(trans.props().i18nKey, 'resetPassword.invalidToken.resendToken') }) test('should render a link to login', t => { const { node } = t.context const link = node.find(ButtonLink) t.is(link.props().to, '/auth/login') t.is(link.props().children, 'resetPassword.invalidToken.goBackLogin') })
fields/types/location/LocationColumn.js
pr1ntr/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; const SUB_FIELDS = ['street1', 'suburb', 'state', 'postcode', 'country']; var LocationColumn = React.createClass({ displayName: 'LocationColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; if (!value || !Object.keys(value).length) return null; const output = []; SUB_FIELDS.map((i) => { if (value[i]) { output.push(value[i]); } }); return ( <ItemsTableValue field={this.props.col.type} title={output.join(', ')}> {output.join(', ')} </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = LocationColumn;
RNDemo/RNComment/node_modules/react-navigation/src/navigators/DrawerNavigator.js
995996812/Web
/* @flow */ import React from 'react'; import { Dimensions, Platform } from 'react-native'; import createNavigator from './createNavigator'; import createNavigationContainer from '../createNavigationContainer'; import TabRouter from '../routers/TabRouter'; import DrawerScreen from '../views/Drawer/DrawerScreen'; import DrawerView from '../views/Drawer/DrawerView'; import DrawerItems from '../views/Drawer/DrawerNavigatorItems'; import NavigatorTypes from './NavigatorTypes'; import type { DrawerViewConfig } from '../views/Drawer/DrawerView'; import type { NavigationRouteConfigMap, NavigationTabRouterConfig, } from '../TypeDefinition'; export type DrawerNavigatorConfig = { containerConfig?: void, } & NavigationTabRouterConfig & DrawerViewConfig; const DefaultDrawerConfig = { /* * Default drawer width is screen width - header width * https://material.io/guidelines/patterns/navigation-drawer.html */ drawerWidth: Dimensions.get('window').width - (Platform.OS === 'android' ? 56 : 64), contentComponent: DrawerItems, drawerPosition: 'left', }; const DrawerNavigator = ( routeConfigs: NavigationRouteConfigMap, config: DrawerNavigatorConfig ) => { const mergedConfig = { ...DefaultDrawerConfig, ...config }; const { containerConfig, drawerWidth, contentComponent, contentOptions, drawerPosition, ...tabsConfig } = mergedConfig; const contentRouter = TabRouter(routeConfigs, tabsConfig); const drawerRouter = TabRouter( { DrawerClose: { screen: createNavigator( contentRouter, routeConfigs, config, NavigatorTypes.DRAWER )((props: *) => <DrawerScreen {...props} />), }, DrawerOpen: { screen: () => null, }, }, { initialRouteName: 'DrawerClose', } ); const navigator = createNavigator( drawerRouter, routeConfigs, config, NavigatorTypes.DRAWER )((props: *) => ( <DrawerView {...props} drawerWidth={drawerWidth} contentComponent={contentComponent} contentOptions={contentOptions} drawerPosition={drawerPosition} /> )); return createNavigationContainer(navigator, containerConfig); }; export default DrawerNavigator;
src/components/GlobalSearchResults.js
FiviumAustralia/RNSH-Pilot
import React, { Component } from 'react'; import { Link } from 'react-router'; import SearchResultRow from 'components/SearchResultRow'; import GlobalSearchFilters from 'components/GlobalSearchFilters'; import styles from './GlobalSearchResults.scss'; export default class GlobalSearchResults extends Component { render () { if (this.props.searchResultsVisibility === 'expanded') { var patientList = () => { return this.props.results.map((p) => { return ( <SearchResultRow key={p.id} patient={p}/> ); }); }; return ( <div className={styles['gs-result-container']}> <GlobalSearchFilters toggleTumorFilter={this.props.toggleTumorFilter} tumorFilter={this.props.tumorFilter} mainClass='gs-result-filters' selectedClass='gs-tumor-filter-selected' /> <div className={styles['gs-results']}> <div className={styles['chrome-workaround']}> <ul className={styles['gs-patient-search-results']}> {patientList()} </ul> </div> </div> <div className={styles['gs-results-footer']}> <Link className={styles['gs-advanced-search']} to={`/`} >Advanced Search</Link> </div> </div> ); } else { return null; } }; }; GlobalSearchResults.propTypes = { searchResultsVisibility: React.PropTypes.string, toggleTumorFilter: React.PropTypes.func.isRequired, results: React.PropTypes.array, tumorFilter: React.PropTypes.string, styles: React.PropTypes.object, };
src/containers/todo_item_detail.js
vijayviji/react-native-redux-todoapp
import React, { Component } from 'react'; import TodoItemDetailComp from '../components/todo_item_detail' import { MarkTodo } from '../action_creators'; import { TodoStates } from '../constants'; export default class TodoItemDetail extends Component { constructor(props) { super(props); } componentDidMount() { this.unsubscribe = this.props.store.subscribe(() => { this.forceUpdate(); }); } componentWillUnmount() { this.unsubscribe(); } render() { const todo = this._getTodo(this.props.id, this.props.store.getState().todos); return ( <TodoItemDetailComp todo = { todo } onMarkStateClicked = {() => { const next_todo_state = (todo.state === TodoStates.ACTIVE) ? TodoStates.COMPLETED : TodoStates.ACTIVE; this._markState(todo.id, next_todo_state); }} /> ); } _getTodo(id, todos) { return todos.filter(item => { if (id === item.id) { return item; } })[0]; } _markState(id, todo_state) { this.props.store.dispatch( MarkTodo(id, todo_state) ); } }
demo/sections/Example/Prop.js
joshq00/react-mdl
import React from 'react'; import Code from './Code'; function getJSON( value ) { const json = JSON.stringify( value, 0, 2 ); return json.replace( /"([^"]+)":/g, '$1:' ).trim(); } const Prop = ( props ) => { let { attr, value } = props; attr = ` ${ attr }`; if ( value === true ) { return <span>{ attr }</span>; } if ( React.isValidElement( value ) ) { return <span>{ attr }={`{ `}<Code el={ value } style={{ marginLeft: '1em' }} />{` }`}</span>; } switch ( typeof value ) { case 'string': value = `"${ value }"`; break; case 'object': // value = `{${ getJSON( value ) }}`; value = <span style={{ whiteSpace: 'pre' }}>{`{`}{ getJSON( value ) }{`}`}</span>; break; case 'function': value = `{ this._${ props.attr } }`; break; case 'boolean': case 'number': default: value = `{ ${ value } }`; } return <span>{ attr }={ value }</span>; }; Prop.propTypes = { attr: React.PropTypes.string, value: React.PropTypes.any }; export default Prop;
src/components/groups/Edit.js
dhruv-kumar-jha/productivity-frontend
'use strict'; import React, { Component } from 'react'; import { browserHistory } from 'react-router'; import { Modal, Spin, Icon, message, Button, Form, Input } from 'antd'; import ModalHeader from 'app/components/productivity/modal/Header'; const FormItem = Form.Item; import { graphql } from 'react-apollo'; import UpdateGroupMutation from 'app/graphql/mutations/groups/Update'; import GetAllGroupsQuery from 'app/graphql/queries/groups/All'; import Loading from 'app/components/common/Loading'; import _ from 'lodash'; import update from 'immutability-helper'; class EditGroup extends Component { constructor(props) { super(props); this.state = { processing: false, }; this.handleFormSubmit = this.handleFormSubmit.bind(this); this.resetForm = this.resetForm.bind(this); } handleCancel() { browserHistory.push('/settings/groups'); } handleFormSubmit(e) { e.preventDefault(); this.props.form.validateFields( (err, fields) => { if ( ! err ) { const group = _.find( this.props.data.groups, { id: this.props.params.id } ); if ( fields.name === group.name && fields.description === group.description ) { return message.warning('Please make changes first before updating.'); } this.setState({ processing: true }); this.props.mutate({ variables: { id: group.id, name: fields.name, description: fields.description, }, optimisticResponse: { __typename: 'Mutation', updateGroup: { __typename: 'Group', id: group.id, name: fields.name, description: fields.description, status: group.status, }, }, // updateQueries: { // AllGroups: (previousResult, { mutationResult }) => { // const updateGroup = mutationResult.data.updateGroup; // const groupIndex = _.findIndex( previousResult.groups, { id: group.id } ); // const updated = update(previousResult, { // groups: { // $splice: [[ groupIndex, 1, updateGroup ]] // }, // }); // return updated; // } // }, }) .then( res => { this.setState({ processing: false }); message.success('Group details has been successfully updated.'); }) .catch( res => { if ( res.graphQLErrors ) { const errors = res.graphQLErrors.map( error => error.message ); } }); } }); } resetForm() { this.props.form.resetFields(); } render() { if ( this.props.data.loading ) { return <Loading /> } const { groups } = this.props.data; const group = _.find( groups, { id: this.props.params.id } ); const { getFieldDecorator } = this.props.form; return ( <Modal wrapClassName="modal__primary" visible={ true } maskClosable={ false } onCancel={ this.handleCancel } footer={[]} > <Spin spinning={ this.state.processing } size="large" tip="Updating group, Please wait..." > <ModalHeader title={ <div><span>Update Group:</span> { group.name }</div> } subtitle="Change the details below and click on Update to save changes.." editable={ false } icon="plus-square-o" /> <div className="container"> <div className="content full"> <Form layout="vertical" onSubmit={ this.handleFormSubmit }> <FormItem label="Group Name" hasFeedback> { getFieldDecorator('name', { rules: [{ required: true, message: 'Please enter group name' }], initialValue: group.name, })( <Input placeholder="Group Name" autoComplete="off" autoFocus={true} /> ) } </FormItem> <FormItem label="Group Description" hasFeedback > { getFieldDecorator('description', { initialValue: group.description, })( <Input type="textarea" placeholder="Group Description" autosize={{ minRows: 3, maxRows: 6 }} /> ) } </FormItem> <FormItem className="m-b-0"> <Button type="primary" size="default" icon="check" htmlType="submit">Update Group</Button> <Button type="ghost" size="default" icon="reload" onClick={ this.resetForm } className="m-l-10">Reset</Button> </FormItem> </Form> </div> </div> </Spin> </Modal> ); } } EditGroup = Form.create()(EditGroup); export default graphql(GetAllGroupsQuery)( graphql(UpdateGroupMutation, { name: 'mutate' })(EditGroup) );
app/javascript/mastodon/features/favourites/index.js
hyuki0000/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import LoadingIndicator from '../../components/loading_indicator'; import { fetchFavourites } from '../../actions/interactions'; import { ScrollContainer } from 'react-router-scroll'; import AccountContainer from '../../containers/account_container'; import Column from '../ui/components/column'; import ColumnBackButton from '../../components/column_back_button'; import ImmutablePureComponent from 'react-immutable-pure-component'; const mapStateToProps = (state, props) => ({ accountIds: state.getIn(['user_lists', 'favourited_by', Number(props.params.statusId)]), }); @connect(mapStateToProps) export default class Favourites extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, accountIds: ImmutablePropTypes.list, }; componentWillMount () { this.props.dispatch(fetchFavourites(Number(this.props.params.statusId))); } componentWillReceiveProps (nextProps) { if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) { this.props.dispatch(fetchFavourites(Number(nextProps.params.statusId))); } } render () { const { accountIds } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } return ( <Column> <ColumnBackButton /> <ScrollContainer scrollKey='favourites'> <div className='scrollable'> {accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)} </div> </ScrollContainer> </Column> ); } }
RNApp/app/components/GenericTextInput/GenericTextInput.js
abhaytalreja/react-native-telescope
import React from 'react'; import { View, TextInput } from 'react-native'; import styles from './styles'; const GenericTextInput = (props) => { return ( <View> {props.borderTop ? <View style={styles.divider} /> : null} <TextInput style={styles.input} autoCapitalize="none" autoCorrect={false} {...props} /> </View> ); }; GenericTextInput.propTypes = { borderTop: React.PropTypes.bool, }; export default GenericTextInput;
tests/components/circular-grid-lines-tests.js
Apercu/react-vis
import test from 'tape'; import React from 'react'; import {mount} from 'enzyme'; import CircularGridLines from 'plot/circular-grid-lines'; import {testRenderWithProps, GENERIC_XYPLOT_SERIES_PROPS} from '../test-utils'; import FauxRadialScatterplot from '../../showcase/plot/faux-radial-scatterplot'; testRenderWithProps(CircularGridLines, GENERIC_XYPLOT_SERIES_PROPS); test('CircularGridLines: Showcase Example - FauxRadialScatterplot', t => { const $ = mount(<FauxRadialScatterplot />); t.equal($.text(), '-3-2-10123-3-2-10123', 'should find the right text content'); t.equal($.find('.rv-xy-plot__circular-grid-lines__line').length, 7, 'should find the right number of circles'); t.end(); });
src/InfoPanel.js
honmanyau/muup-story
import React, { Component } from 'react'; import './GameController.css'; class InfoPanel extends React.Component { render() { let player = this.props.player; let HPPercentage = player.hp / player.mhp * 100; const HPBarFillWidth = { width: HPPercentage + "%" }; return( <div className="GameController-infoPanel"> <div className="GameController-infoPanelLabel">{this.props.floor}<small>F</small></div> <div className="GameController-infoPanelLabel"><small>Lv</small>{player.level}</div> <div className="GameController-infoPanelLabel"> <small>HP</small>{player.hp}/{player.mhp} <div className="GameController-infoPanelLabel-HPBar"> <div className="GameController-infoPanelLabel-HPBarFill" style={HPBarFillWidth}></div> </div> </div> <div className="GameController-infoPanelLabel"> <small>ATK</small>{player.attack} <div className="GameController-extraSmallText">{player.weapon}</div> </div> </div> ); } }; export default InfoPanel
assets/jqwidgets/demos/react/app/grid/bindingtoremotedata/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxGrid from '../../../jqwidgets-react/react_jqxgrid.js'; class App extends React.Component { render() { let source = { datatype: 'jsonp', datafields: [ { name: 'countryName', type: 'string' }, { name: 'name', type: 'string' }, { name: 'population', type: 'float' }, { name: 'continentCode', type: 'string' } ], url: 'http://api.geonames.org/searchJSON' }; let dataAdapter = new $.jqx.dataAdapter(source, { formatData: (data) => { $.extend(data, { featureClass: 'P', style: 'full', maxRows: 50, username: 'jqwidgets' }); return data; } } ); let columns = [ { text: 'Country Name', datafield: 'countryName', width: 200 }, { text: 'City', datafield: 'name', width: 170 }, { text: 'Population', datafield: 'population', cellsformat: 'f', width: 170 }, { text: 'Continent Code', datafield: 'continentCode', minwidth: 110 } ]; return ( <div style={{ fontSize: 13, fontFamily: 'Verdana', float: 'left' }}> <JqxGrid width={850} source={dataAdapter} columnsresize={true} columns={columns} /> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
client/modules/App/components/DevTools.js
tranphong001/BIGVN
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-w" > <LogMonitor /> </DockMonitor> );
source/server/routes/main/index.js
ericelliott/universal-react-boilerplate
import React from 'react'; import { match } from 'react-router'; import renderLayout from 'server/render-layout'; import render from 'server/render'; import settings from 'server/settings'; import configureStore from 'shared/configure-store'; import createRoutes from 'shared/routes'; const store = configureStore(); const routes = createRoutes(React); const initialState = store.getState(); export default (req, res) => { match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { if (error) { res.status(500).send(error.message); } else if (redirectLocation) { res.redirect(302, redirectLocation.pathname + redirectLocation.search); } else if (renderProps) { const rootMarkup = render(React)(renderProps, store); res.status(200).send(renderLayout({ settings, rootMarkup, initialState })); } else { res.status(404).send('Not found'); } }); };
src/demo/field.js
react-entanglement/react-entanglement
import React from 'react' export default function Field({ value, onChange }) { return <input onChange={e => onChange(e.target.value)} value={value} /> }
_experiment/react-fetch-github-repo/v1-external-fetch-file/src/Repo.js
David-Castelli/react-testing
// Render of single element import React from 'react'; import {render} from 'react-dom'; // Single element const Repo = ({repo, item}) => <article> <div className='article-content'> {item} <a href={repo.url}> <h3 className='title'>{repo.name}</h3> </a> <p className='description'>{repo.description}</p> <span className='created_at'>{repo.created_at}</span> <span className='updated_at'>{repo.updated_at}</span> <br/> <span className='open_issues'>{repo.open_issues}</span> <span className='watchers'>{repo.watchers}</span> <p className='language'>{repo.language}</p> </div> </article> export default Repo;
src/js/ui/components/entryListFilter.js
hiddentao/heartnotes
import _ from 'lodash'; import React from 'react'; import { connectRedux } from '../helpers/decorators'; import Loading from './loading'; var Component = React.createClass({ propTypes: { searchKeyword: React.PropTypes.string, }, getDefaultProps: function() { return { searchKeyword: null, }; }, getInitialState: function() { return { keyword: null, }; }, render: function() { let filter = null, summary = null; let searchIndexing = this.props.data.diary.searchIndexing; if (!searchIndexing.success) { filter = ( <Loading text="Rebuilding search..." /> ); } else { let filterText = null; let keyword = this.state.keyword; filter = ( <input ref="input" value={keyword} type="text" placeholder="Search..." onChange={this._onChange} /> ); if (keyword) { summary = ( <span className="filter-summary">Filter by: {keyword}</span> ); } } return ( <div className="entry-list-filter"> {filter} {summary} </div> ); }, componentWillReceiveProps: function(newProps) { if (newProps.searchKeyword !== this.state.keyword) { this.setState({ keyword: newProps.searchKeyword }); } }, _onChange: function(e) { let keyword = e.currentTarget.value; this.setState({ keyword: keyword, }); this.props.actions.search(keyword); }, }); module.exports = connectRedux([ 'search' ])(Component);
node_modules/react-bootstrap/es/Well.js
geng890518/editor-ui
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, bsSizes, getClassSet, splitBsProps } from './utils/bootstrapUtils'; import { Size } from './utils/StyleConfig'; var Well = function (_React$Component) { _inherits(Well, _React$Component); function Well() { _classCallCheck(this, Well); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Well.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('div', _extends({}, elementProps, { className: classNames(className, classes) })); }; return Well; }(React.Component); export default bsClass('well', bsSizes([Size.LARGE, Size.SMALL], Well));
app/components/layout/newProject/imageUploader.js
communicode-source/communicode
import React from 'react'; import styles from './../../../assets/css/pages/createProject.scss'; class ImageUpload extends React.Component { constructor() { super(); this.state = {file: '', imagePreviewUrl: ''}; } _handleSubmit(e) { e.preventDefault(); } _handleImageChange(e) { e.preventDefault(); const reader = new FileReader(); const file = e.target.files[0]; reader.onloadend = () => { this.setState({ file: file, imagePreviewUrl: reader.result }); }; reader.readAsDataURL(file); } render() { let {imagePreviewUrl} = this.state; let $imagePreview = null; if (imagePreviewUrl) { $imagePreview = (<img className={styles.cover} src={imagePreviewUrl} />); } else { $imagePreview = (<div>Please select an Image for Preview</div>); } return ( <div className={styles.question}> <h4>Cover Photo:</h4> <form onSubmit={this._handleSubmit.bind(this)}> <label className={styles.fileUploaderLabel} htmlFor="file">Choose a file <input id="file" name="file" type="file" onChange={(e)=>this._handleImageChange(e)} className={styles.fileUploadInput} /> </label> </form> <div> {$imagePreview} </div> {imagePreviewUrl !== '' && <button onClick={this._handleSubmit.bind(this)}>Upload Image</button>} </div> ); } } export default ImageUpload;
src/svg-icons/hardware/phonelink-off.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwarePhonelinkOff = (props) => ( <SvgIcon {...props}> <path d="M22 6V4H6.82l2 2H22zM1.92 1.65L.65 2.92l1.82 1.82C2.18 5.08 2 5.52 2 6v11H0v3h17.73l2.35 2.35 1.27-1.27L3.89 3.62 1.92 1.65zM4 6.27L14.73 17H4V6.27zM23 8h-6c-.55 0-1 .45-1 1v4.18l2 2V10h4v7h-2.18l3 3H23c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1z"/> </SvgIcon> ); HardwarePhonelinkOff = pure(HardwarePhonelinkOff); HardwarePhonelinkOff.displayName = 'HardwarePhonelinkOff'; HardwarePhonelinkOff.muiName = 'SvgIcon'; export default HardwarePhonelinkOff;
frontend/src/routes/Home/components/HomeView.js
qurben/mopidy-jukebox
import React from 'react' import DuckImage from '../assets/Duck.jpg' import classes from './HomeView.scss' export const HomeView = () => ( <div> <h4>Welcome!</h4> <img alt='This is a duck, because Redux!' className={classes.duck} src={DuckImage} /> </div> ) export default HomeView
docs/src/app/components/pages/components/Snackbar/ExampleTwice.js
skarnecki/material-ui
import React from 'react'; import Snackbar from 'material-ui/Snackbar'; import RaisedButton from 'material-ui/RaisedButton'; export default class SnackbarExampleTwice extends React.Component { constructor(props) { super(props); this.state = { message: 'Event 1 added to your calendar', open: false, }; this.timer = undefined; } componentWillUnMount() { clearTimeout(this.timer); } handleTouchTap = () => { this.setState({ open: true, }); this.timer = setTimeout(() => { this.setState({ message: `Event ${Math.round(Math.random() * 100)} added to your calendar`, }); }, 1500); }; handleRequestClose = () => { this.setState({ open: false, }); }; render() { return ( <div> <RaisedButton onTouchTap={this.handleTouchTap} label="Add to my calendar two times" /> <Snackbar open={this.state.open} message={this.state.message} action="undo" autoHideDuration={3000} onRequestClose={this.handleRequestClose} /> </div> ); } }
src/action-button.js
lonord/react-marked-editor
import React, { Component } from 'react'; import propTypes from 'prop-types'; class ActionButton extends Component { render() { const styles = { wrapper: { height: this.props.height, width: this.props.width }, btn: { height: this.props.height - 2, width: this.props.width - 2, lineHeight: (this.props.width - 2) + 'px' } } return ( <div style={styles.wrapper} className="wrapper" title={this.props.title}> <div className={this.props.isSelect ? 'btn btn-select' : 'btn'} style={styles.btn} onClick={this.props.onClick}> {this.props.text ? <i className={`fa ${this.props.iconClass ? 'fa-' + this.props.iconClass : ''} text-btn`}>{this.props.text}</i> : <i className={`fa ${this.props.iconClass ? 'fa-' + this.props.iconClass : ''}`}></i>} </div> <style jsx>{` .wrapper { cursor: pointer; } .btn { border-radius: 3px; border: 1px solid transparent; text-align: center; color: #777; } .btn:hover { border: 1px solid #eee; background: #fafafa; } .btn-select { border: 1px solid #eee; background: #f0f0f0; } .text-btn { font-weight: bold; } `}</style> </div> ); } } ActionButton.propTypes = { text: propTypes.string, iconClass: propTypes.string, width: propTypes.number, height: propTypes.number, onClick: propTypes.func, title: propTypes.string, isSelect: propTypes.bool }; ActionButton.defaultProps = { iconClass: '', width: 24, height: 24, isSelect: false } export default ActionButton;
app/components/FileList.js
zoo1/fil
import _ from 'underscore'; import React from 'react'; import {connect} from 'react-redux'; import classNames from 'classnames'; import {createFile, deleteFile, renameFile, openFile} from 'actions/files'; class FileRenameForm extends React.Component { constructor(props) { super(props); this.state = { path: props.path }; } componentDidMount() { React.findDOMNode(this.refs.fileName).select(); } onSubmit(event) { event.preventDefault(); this.props.onRename(this.state.path); } handleChange(event) { this.setState({ path: event.target.value }); } render() { const block = this.props.block + "__rename-form"; return ( <form className={block} onSubmit={this.onSubmit.bind(this)}> <input className={block + "__input"} value={this.state.path} ref="fileName" onChange={this.handleChange.bind(this)} /> </form> ); } } class FileItem extends React.Component { constructor(props) { super(props); this.state = { rename: props.rename }; } handleFileRename(event) { const {files, dispatch} = this.props; this.setState({rename: true}); event.preventDefault(); } handleClick(event) { const {path} = this.props; this.props.onOpenFile(path); event.preventDefault(); } renameFile(newPath) { const {dispatch} = this.props; dispatch(renameFile(this.props.path, newPath)); dispatch(openFile(newPath)); this.setState({rename: false}); } handleRemove() { const {path, dispatch, files} = this.props; dispatch(deleteFile(path)); } render() { const {path, current, block} = this.props; const isCurrent = path == current; return ( <li className={classNames({ [block + "__item"]: true, [block + "__item--current"]: isCurrent })}> <a href="#" onDoubleClick={this.handleFileRename.bind(this)} onClick={this.handleClick.bind(this)}> {this.state.rename && ( <FileRenameForm block={block} path={path} onRename={this.renameFile.bind(this)} /> )} {!this.state.rename && path} </a> {isCurrent && ( <button onClick={this.handleRemove.bind(this)} className={block + "__remove-button"}> {String.fromCharCode(10799)} </button> )} </li> ); } } class FileList extends React.Component { constructor() { super(); this.state = { renamingPath: null }; } handleNewFileButtonClick(event) { const {files, dispatch} = this.props; const files = _.keys(files).filter(name => name.startsWith(file)).length let fileName = 'module.py'; if(files !== 0) fileName = 'module' + files + '.py'; dispatch(createFile(fileName)) this.setState({renamingPath: fileName}); event.preventDefault(); } render() { const {files, current, dispatch} = this.props; const block = "file-list"; return ( <ul className={block}> {_.keys(files).map( (path) => <FileItem key={path} block={block} path={path} rename={this.state.renamingPath === path} {...this.props} /> )} <li className={classNames(block + "__item", block + "__item--new")}> <a onClick={this.handleNewFileButtonClick.bind(this)} href="#" >+</a> </li> </ul> ); } } function select(state) { return { files: state.files }; } export default connect(select)(FileList);
src/components/AddClient/components/ClientRole/StaffRole.js
TheModevShop/craft-app
import React from 'react'; import _ from 'lodash'; import Radio from 'components/uiElements/Radio/Radio'; import './staff-role.less'; class StaffRole extends React.Component { constructor(...args) { super(...args); this.state = {}; } render() { return ( <div className="staff-role-wrapper"> <section> <Radio value={'agent-restricted'} name={'agent-restricted'} active={this.props.permission} onChangeRadio={this.props.onPermissionsUpdated.bind(this)}> <span> <h4 className="bold">Restricted</h4> <h5 className="darkGray">Restricted Cannot manage their calendar (others must book appointments on their behalf). No access to Appointments Dashboard and Appointments App.</h5> </span> </Radio> <Radio value={'agent-self'} name={'agent-self'} active={this.props.permission} onChangeRadio={this.props.onPermissionsUpdated.bind(this)}> <span> <h4 className="bold">Self Access <span className="regular">- Ideal for single staff member.</span></h4> <h5 className="darkGray">View, accept and decline their own appointments and view their own calendars.</h5> </span> </Radio> <Radio value={'agent-staff'} name={'agent-staff'} active={this.props.permission} onChangeRadio={this.props.onPermissionsUpdated.bind(this)}> <span> <h4 className="bold">All Staff Access <span className="regular">- Ideal for the front desk.</span></h4> <h5 className="darkGray">Restricted Cannot manage their calendar (others must book appointments on their behalf). No access to Appointments Dashboard and Appointments App.</h5> </span> </Radio> <Radio value={'resource-admin'} name={'resource-admin'} active={this.props.permission} onChangeRadio={this.props.onPermissionsUpdated.bind(this)}> <span> <h4 className="bold">Full Access <span className="regular">- Ideal for partners.</span></h4> <h5 className="darkGray">Access to everything.</h5> </span> </Radio> </section> <section></section> <section></section> </div> ); } } StaffRole.propTypes = {}; export default StaffRole;
src/components/top-menu/switch.js
Lokiedu/libertysoil-site
/* This file is a part of libertysoil.org website Copyright (C) 2017 Loki Education (Social Enterprise) 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 React from 'react'; import WelcomeGuestTopMessage from './welcome-guest'; import WelcomeUserTopMessage from './welcome-user'; import WelcomeFirstLoginTopMessage from './welcome-first-login'; export default class TopMessageSwitch extends React.Component { static displayName = 'TopMessageSwitch'; shouldComponentUpdate(nextProps) { return nextProps !== this.props; } render() { const { message, ...props } = this.props; switch (message[1].get('message')) { case 'welcome-guest': return ( <WelcomeGuestTopMessage {...props} /> ); case 'welcome-user': return ( <WelcomeUserTopMessage {...props} /> ); case 'welcome-first-login': return ( <WelcomeFirstLoginTopMessage {...props} /> ); default: return false; } } }
packages/mineral-ui-icons/src/IconWbIridescent.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconWbIridescent(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M5 14.5h14v-6H5v6zM11 .55V3.5h2V.55h-2zm8.04 2.5l-1.79 1.79 1.41 1.41 1.8-1.79-1.42-1.41zM13 22.45V19.5h-2v2.95h2zm7.45-3.91l-1.8-1.79-1.41 1.41 1.79 1.8 1.42-1.42zM3.55 4.46l1.79 1.79 1.41-1.41-1.79-1.79-1.41 1.41zm1.41 15.49l1.79-1.8-1.41-1.41-1.79 1.79 1.41 1.42z"/> </g> </Icon> ); } IconWbIridescent.displayName = 'IconWbIridescent'; IconWbIridescent.category = 'image';
frontend/app_v2/src/components/WidgetArea/WidgetAreaContainer.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' // FPCC import WidgetAreaData from 'components/WidgetArea/WidgetAreaData' import Widget from 'components/Widget' import LazyLoader from 'components/LazyLoader' function WidgetAreaContainer({ id }) { const { widgets } = WidgetAreaData({ id }) return ( <section> {widgets?.length > 0 && widgets.map((widget, index) => { return ( <LazyLoader key={`${widget?.uid ? widget?.uid : 'widget'}_${index}`}> <Widget.Container widgetType={widget?.type} data={widget} /> </LazyLoader> ) })} </section> ) } // PROPTYPES const { string } = PropTypes WidgetAreaContainer.propTypes = { id: string, // The id of the 'widgetAware' document } export default WidgetAreaContainer
js/components/AlertBar.js
msldiarra/signals-ui
import React from 'react'; export default class AlertBar extends React.Component { render() { let progressBarClass = (this.props.tank.fillingrate > 50) ? "progress-bar progress-bar-success" : (this.props.tank.fillingrate > 30) ? "progress-bar progress-bar-warning": "progress-bar progress-bar-danger"; return (<div> <a className="black" href="#"> <div> <div> <h5><i className="fa fa-filter"></i> {this.props.tank.tank} (<b>{this.props.tank.liquidtype}</b>) dans la station de <b>{this.props.tank.station}</b> </h5> </div> <div className="progress"> <div className={progressBarClass} role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style={{width:this.props.tank.fillingrate + '%'}}> <span>{this.props.tank.fillingrate}%</span> </div> </div> </div> </a> </div>); } }
packages/material-ui-icons/src/CompareArrows.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M9.01 14H2v2h7.01v3L13 15l-3.99-4v3zm5.98-1v-3H22V8h-7.01V5L11 9l3.99 4z" /></g> , 'CompareArrows');
components/Layout/Layout.js
tbescherer/TrumpAnxietyHotline
import {connect} from 'react-redux'; import React from 'react'; import Header from './Header'; import s from './Layout.css'; import store from '../../core/store.js'; class Layout extends React.Component { constructor(props) { super(props); } componentDidMount() { window.componentHandler.upgradeElement(this.root); } componentWillUnmount() { window.componentHandler.downgradeElements(this.root); } render() { return ( <div className="mdl-layout mdl-js-layout mdl-layout--fixed-header" ref={node => (this.root = node)}> <div className="mdl-layout__inner-container"> <Header> <span className="mdl-layout-title" onClick={() => {window.location.href=window.location.origin}} style={{cursor: 'pointer'}}>Trump Anxiety Hotline</span> <div className="mdl-layout-spacer"></div> </Header> <div className="mdl-layout__drawer"> <span className="mdl-layout-title" style={{cursor: 'pointer'}} onClick={() => {window.location.href=window.location.origin}}>Home</span> <nav className="mdl-navigation" style={{cursor: 'pointer'}}> <div className="mdl-navigation__link" onClick={() => {window.location.href="/messages"}}>Start A Conversation</div> <div className="mdl-navigation__link" onClick={() => {window.location.href="/analytics"}}>Analytics</div> <div className="mdl-navigation__link" onClick={() => {window.location.href="/links"}}>Quick Links</div> <div className="mdl-navigation__link" onClick={() => {window.location.href="/about"}}>About</div> <div className="mdl-navigation__link" onClick={() => {window.location.href="http://www.zazzle.com/trumpanxietyhotline"}}>Buy a Hat</div> </nav> </div> <main className="mdl-layout__content"> <div className={s.content} {...this.props} /> </main> </div> </div> ); } } export default Layout;
frontend/teg-web-ui/src/common/topNavigation/StaticTopNavigation.js
tegh/tegh-daemon
import React from 'react' import { Link } from 'react-router-dom' import classnames from 'classnames' import Typography from '@mui/material/Typography' import Hidden from '@mui/material/Hidden' import IconButton from '@mui/material/IconButton' import MenuIcon from '@mui/icons-material/Menu' import useStyle from './TopNavigationStyles' import WordMark from '../WordMark' import UserProfileMenu from './UserProfileMenu' const StaticTopNavigation = ({ title = () => <WordMark/>, onMenuButtonClick, className, avatar = localStorage.getItem('avatar'), }) => { const classes = useStyle() const hasMenu = onMenuButtonClick != null return ( <div className={className}> <div className={classnames( classes.mainMenu, hasMenu && classes.withMenu, )} > <Hidden mdDown={!hasMenu} mdUp> <IconButton className={classes.buttonClass} aria-label="Menu" onClick={onMenuButtonClick} size="large"> <MenuIcon /> </IconButton> </Hidden> <Typography variant="h4" className={classes.title} component={React.forwardRef((props, ref) => ( <Link to="/" innerRef={ref} {...props} /> ))} > {title()} </Typography> <div className={classes.userProfileMenu} > <UserProfileMenu avatar={avatar}/> </div> </div> </div> ); } export default StaticTopNavigation
client/src/App.js
teenoh/Hello-Books
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } } export default App;
docs/app/Examples/views/Statistic/Types/StatisticExampleBottomLabel.js
mohammed88/Semantic-UI-React
import React from 'react' import { Statistic } from 'semantic-ui-react' const StatisticExampleBottomLabel = () => ( <div> <Statistic> <Statistic.Value>5,550</Statistic.Value> <Statistic.Label>Downloads</Statistic.Label> </Statistic> <Statistic value='5,500' label='Downloads' /> </div> ) export default StatisticExampleBottomLabel
node_modules/antd/es/button/button.js
yhx0634/foodshopfront
import _extends from 'babel-runtime/helpers/extends'; import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; var __rest = this && this.__rest || function (s, e) { var t = {}; for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; }if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; }return t; }; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import omit from 'omit.js'; import Icon from '../icon'; var rxTwoCNChar = /^[\u4e00-\u9fa5]{2}$/; var isTwoCNChar = rxTwoCNChar.test.bind(rxTwoCNChar); function isString(str) { return typeof str === 'string'; } // Insert one space between two chinese characters automatically. function insertSpace(child, needInserted) { // Check the child if is undefined or null. if (child == null) { return; } var SPACE = needInserted ? ' ' : ''; // strictNullChecks oops. if (typeof child !== 'string' && typeof child !== 'number' && isString(child.type) && isTwoCNChar(child.props.children)) { return React.cloneElement(child, {}, child.props.children.split('').join(SPACE)); } if (typeof child === 'string') { if (isTwoCNChar(child)) { child = child.split('').join(SPACE); } return React.createElement( 'span', null, child ); } return child; } var Button = function (_React$Component) { _inherits(Button, _React$Component); function Button(props) { _classCallCheck(this, Button); var _this = _possibleConstructorReturn(this, (Button.__proto__ || Object.getPrototypeOf(Button)).call(this, props)); _this.handleClick = function (e) { // Add click effect _this.setState({ clicked: true }); clearTimeout(_this.timeout); _this.timeout = setTimeout(function () { return _this.setState({ clicked: false }); }, 500); var onClick = _this.props.onClick; if (onClick) { onClick(e); } }; _this.state = { loading: props.loading }; return _this; } _createClass(Button, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var _this2 = this; var currentLoading = this.props.loading; var loading = nextProps.loading; if (currentLoading) { clearTimeout(this.delayTimeout); } if (typeof loading !== 'boolean' && loading && loading.delay) { this.delayTimeout = setTimeout(function () { return _this2.setState({ loading: loading }); }, loading.delay); } else { this.setState({ loading: loading }); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { if (this.timeout) { clearTimeout(this.timeout); } if (this.delayTimeout) { clearTimeout(this.delayTimeout); } } }, { key: 'render', value: function render() { var _classNames; var _a = this.props, type = _a.type, shape = _a.shape, _a$size = _a.size, size = _a$size === undefined ? '' : _a$size, className = _a.className, htmlType = _a.htmlType, children = _a.children, icon = _a.icon, prefixCls = _a.prefixCls, ghost = _a.ghost, others = __rest(_a, ["type", "shape", "size", "className", "htmlType", "children", "icon", "prefixCls", "ghost"]);var _state = this.state, loading = _state.loading, clicked = _state.clicked; // large => lg // small => sm var sizeCls = ''; switch (size) { case 'large': sizeCls = 'lg'; break; case 'small': sizeCls = 'sm'; default: break; } var classes = classNames(prefixCls, className, (_classNames = {}, _defineProperty(_classNames, prefixCls + '-' + type, type), _defineProperty(_classNames, prefixCls + '-' + shape, shape), _defineProperty(_classNames, prefixCls + '-' + sizeCls, sizeCls), _defineProperty(_classNames, prefixCls + '-icon-only', !children && icon && !loading), _defineProperty(_classNames, prefixCls + '-loading', loading), _defineProperty(_classNames, prefixCls + '-clicked', clicked), _defineProperty(_classNames, prefixCls + '-background-ghost', ghost), _classNames)); var iconType = loading ? 'loading' : icon; var iconNode = iconType ? React.createElement(Icon, { type: iconType }) : null; var needInserted = React.Children.count(children) === 1 && (!iconType || iconType === 'loading'); var kids = React.Children.map(children, function (child) { return insertSpace(child, needInserted); }); return React.createElement( 'button', _extends({}, omit(others, ['loading', 'clicked']), { type: htmlType || 'button', className: classes, onClick: this.handleClick }), iconNode, kids ); } }]); return Button; }(React.Component); export default Button; Button.__ANT_BUTTON = true; Button.defaultProps = { prefixCls: 'ant-btn', loading: false, clicked: false, ghost: false }; Button.propTypes = { type: PropTypes.string, shape: PropTypes.oneOf(['circle', 'circle-outline']), size: PropTypes.oneOf(['large', 'default', 'small']), htmlType: PropTypes.oneOf(['submit', 'button', 'reset']), onClick: PropTypes.func, loading: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]), className: PropTypes.string, icon: PropTypes.string };
.history/src/components/GKM/Category_20170624164531.js
oded-soffrin/gkm_viewer
import React from 'react'; import _ from 'lodash' const Category = ({ category }) => { const items = _.map(category.items, (i) => (<div style={{ display: 'inline-block', padding: '10px' }}>{i.text}</div>)) console.log(items); return ( <div> <div> {category.type}: {category.text} </div> <div>Items:</div> {items} </div> ) }; /* Item.propTypes = { }; */ export default Category
app/components/Slider.js
firewenda/testwebsite
import React from 'react'; import Slider from 'react-slick'; class SimpleSlider extends React.Component{ render(){ let settings = { dots: true, infinite: true, speed: 500, slidesToShow: 1, slidesToScroll: 1, autoplay: true, }; return ( <div className='slide-carousel'> <Slider {...settings}> <div><img src='/img/banner/banner1.jpg' /></div> <div><img src='/img/banner/banner2.jpg' /></div> <div><img src='/img/banner/banner3.jpg' /></div> </Slider> </div> ); } } export default SimpleSlider;
src/js/Containers/NewsContainer.js
RoyalSix/Eagle-Connect
/** * @file This is the container for the actual component * This file should handle the business logic of the component * There should be no styling/css properties in this file * In this way we can have a separation of concerns handle * will allow for easier testing * {@link https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0} */ import React, { Component } from 'react'; //These are required for react to work import { connect } from 'react-redux' /** * This allows us to get access to the store from the state we pass * {@see mapStateToProps} */ import { ListView } from 'react-native'; //This is the component that we will need to create a List ListView //type of datasource to feed to the component //{@link https://facebook.github.io/react-native/docs/listview.html} import News from '../Components/News'; //This is the actual component that contains styling to be rendered class NewsContainer extends Component { render() { //React render function to be called everytime there is new props var listSource = new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, sectionHeaderHasChanged: (s1, s2) => s1 !== s2 }); var dataSource = listSource.cloneWithRows(this.props.news); /* * This is going to be the data that will be sent to the child component * this.props.chapels is defined in chapelActions and is getting fetched in app container * From the action it goes to the reducer by the tyoe name RECEIVE_CHAPEL_LOAD * and then merged in the store * This is a standard redux flow Action -> Reducer -> Container (this file) -> Component (Chapel.js) */ return ( <News dataSource={dataSource}/> ) } } const mapStateToProps = (state) => { return { ...state.newsReducer } /** * This function allows us to take whatever is in the store of our choosing (chapelReducer) * And send it the this containers props {@see this.props.chapel in render function} * This will take everything from the state in {@see chapelReducer} */ } export default connect(mapStateToProps)(NewsContainer)
packages/react/src/views/Server.js
wq/wq.app
import React from 'react'; import { useRenderContext } from '../hooks'; const HTML = '@@HTML'; export default function Server() { const html = useRenderContext()[HTML]; return ( <> <p>This renderer does not (yet) support server-rendered HTML.</p> <pre> <code>{html}</code> </pre> </> ); }
src/frontend/components/EventView.js
Bernie-2016/ground-control
import React from 'react' import Relay from 'react-relay' import {BernieText} from './styles/bernie-css' import {Paper, Styles} from 'material-ui' import EventPreview from './EventPreview' import EventInvalid from './EventInvalid' import yup from 'yup' import MuiThemeProvider from 'material-ui/lib/MuiThemeProvider' import {BernieTheme} from './styles/bernie-theme' const publicEventsRootUrl = 'https://secure.berniesanders.com/page/event/detail/' class EventView extends React.Component { styles = { pageContainer: { margin: '0 auto', padding: '1rem', maxWidth: 1100 } } render() { if (!this.props.event) return <EventInvalid /> let event_type_name = 'volunteer event' if(this.props.event.eventType.name.toLowerCase().indexOf('phone bank') > -1){ event_type_name = 'phone bank party' } else if(this.props.event.eventType.name.toLowerCase().indexOf('barnstorm') > -1){ event_type_name = 'Barnstorm event' } return ( <MuiThemeProvider muiTheme={Styles.getMuiTheme(BernieTheme)}> <div style={this.styles.pageContainer}> <p style={BernieText.secondaryTitle}>Event Details:</p> <EventPreview event={this.props.event} /> </div> </MuiThemeProvider> ) } } export default Relay.createContainer(EventView, { fragments: { event: () => Relay.QL` fragment on Event { attendeesCount attendeeVolunteerMessage attendeeVolunteerShow capacity contactPhone createDate description duration eventIdObfuscated eventType { id name } flagApproval host { id firstName lastName } hostReceiveRsvpEmails id isSearchable isOfficial latitude localTimezone localUTCOffset longitude name publicPhone rsvpEmailReminderHours rsvpUseReminderEmail startDate venueAddr1 venueAddr2 venueCity venueCountry venueDirections venueName venueState venueZip } ` } })
client/views/directory/ChannelsTab.js
VoiSmart/Rocket.Chat
import React from 'react'; import NotAuthorizedPage from '../../components/NotAuthorizedPage'; import { usePermission } from '../../contexts/AuthorizationContext'; import ChannelsTable from './ChannelsTable'; function ChannelsTab(props) { const canViewPublicRooms = usePermission('view-c-room'); if (canViewPublicRooms) { return <ChannelsTable {...props} />; } return <NotAuthorizedPage />; } export default ChannelsTab;
app/components/H3/index.js
rajeshbhatt/shopping-cart-redux
import React from 'react'; function H3(props) { return ( <h3 {...props} /> ); } export default H3;
src/Parser/Druid/Guardian/Modules/Features/FrenziedRegenGoEProcs.js
hasseboulen/WoWAnalyzer
import React from 'react'; import { formatPercentage } from 'common/format'; import SpellIcon from 'common/SpellIcon'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; import SPELLS from 'common/SPELLS'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import GuardianOfElune from './GuardianOfElune'; class FrenziedRegenGoEProcs extends Analyzer { static dependencies = { combatants: Combatants, guardianOfElune: GuardianOfElune, }; on_initialized() { this.active = this.combatants.selected.hasTalent(SPELLS.GUARDIAN_OF_ELUNE_TALENT.id); } statistic() { const nonGoEFRegen = this.guardianOfElune.nonGoEFRegen; const GoEFRegen = this.guardianOfElune.GoEFRegen; if ((nonGoEFRegen + GoEFRegen) === 0) { return null; } return ( <StatisticBox icon={<SpellIcon id={SPELLS.FRENZIED_REGENERATION.id} />} value={`${formatPercentage(nonGoEFRegen / (nonGoEFRegen + GoEFRegen))}%`} label="Unbuffed Frenzied Regen" tooltip={`You cast <b>${nonGoEFRegen + GoEFRegen}</b> total ${SPELLS.FRENZIED_REGENERATION.name} and <b> ${GoEFRegen}</b> were buffed by 20%.`} /> ); } statisticOrder = STATISTIC_ORDER.CORE(8); } export default FrenziedRegenGoEProcs;
frontend/src/Settings/CustomFormats/CustomFormats/Specifications/AddSpecificationModalContentConnector.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { fetchCustomFormatSpecificationSchema, selectCustomFormatSpecificationSchema } from 'Store/Actions/settingsActions'; import AddSpecificationModalContent from './AddSpecificationModalContent'; function createMapStateToProps() { return createSelector( (state) => state.settings.customFormatSpecifications, (specifications) => { const { isSchemaFetching, isSchemaPopulated, schemaError, schema } = specifications; return { isSchemaFetching, isSchemaPopulated, schemaError, schema }; } ); } const mapDispatchToProps = { fetchCustomFormatSpecificationSchema, selectCustomFormatSpecificationSchema }; class AddSpecificationModalContentConnector extends Component { // // Lifecycle componentDidMount() { this.props.fetchCustomFormatSpecificationSchema(); } // // Listeners onSpecificationSelect = ({ implementation, name }) => { this.props.selectCustomFormatSpecificationSchema({ implementation, presetName: name }); this.props.onModalClose({ specificationSelected: true }); } // // Render render() { return ( <AddSpecificationModalContent {...this.props} onSpecificationSelect={this.onSpecificationSelect} /> ); } } AddSpecificationModalContentConnector.propTypes = { fetchCustomFormatSpecificationSchema: PropTypes.func.isRequired, selectCustomFormatSpecificationSchema: PropTypes.func.isRequired, onModalClose: PropTypes.func.isRequired }; export default connect(createMapStateToProps, mapDispatchToProps)(AddSpecificationModalContentConnector);
src/js/views/UserArea/UserArea.js
TheoZimm/SaltyDashboard
import React from 'react'; import {AuthorizedComponent} from 'react-router-role-authorization'; import routes from '../../routes'; class UserArea extends AuthorizedComponent { constructor(props) { super(props); // Get user role from localStorage(session) and define allowed roles this.userRoles = [JSON.parse(localStorage.getItem('user')).role]; this.notAuthorizedPath = '/unauthorized'; } // Send props to routes // This define where to routes redirect depending user roles render() { return ( <div> <routes {...this.props}/> </div> ); }; } ; export default UserArea;
src/svg-icons/editor/space-bar.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorSpaceBar = (props) => ( <SvgIcon {...props}> <path d="M18 9v4H6V9H4v6h16V9z"/> </SvgIcon> ); EditorSpaceBar = pure(EditorSpaceBar); EditorSpaceBar.displayName = 'EditorSpaceBar'; export default EditorSpaceBar;
src/screens/main/main.screen.js
Barylskyigb/simple-debts-react-native
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { View, Text, FlatList, Image, RefreshControl, TouchableWithoutFeedback, ActivityIndicator } from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; import IonIcon from 'react-native-vector-icons/Ionicons'; import Debt from '../../components/Debt/Debt.presenter'; import debtScreenStyles from '../debt/debt.styles'; import styles from './main.styles'; import * as colors from '../../utils/colors'; import TouchableArea from '../../components/TouchableArea/TouchableArea'; import AddPopup from './AddPopup/AddPopup'; import AddConfirmationPopup from './AddConfirmationPopup/AddConfirmationPopup.presenter'; import HeaderButton from '../../components/HeaderButton/HeaderButton'; import * as firebase from 'react-native-firebase'; export default class MainScreen extends Component { static navigationOptions = ({ navigation }) => { const { params = {} } = navigation.state; const { signOut } = params; return { headerLeft: ( <HeaderButton onPress={signOut}> <IonIcon name="ios-log-out" size={22} color={colors.white} /> </HeaderButton> ), headerRight: ( <View style={styles.popupButtonWrapper}> <TouchableArea onPress={params.toggleAddPopup} borderless style={styles.popupButton} > <Icon name="plus" size={20} color="white" /> </TouchableArea> </View> ), headerTransparent: true }; }; static propTypes = { user: PropTypes.object.isRequired, navigation: PropTypes.object.isRequired, fetchDebts: PropTypes.func.isRequired, debts: PropTypes.array.isRequired, uploadPushToken: PropTypes.func.isRequired, signOut: PropTypes.func.isRequired }; state = { refreshing: false, loading: false, popupVisible: false, userToAdd: {} }; componentDidMount() { const { navigation } = this.props; navigation.setParams({ toggleAddPopup: this.toggleAddPopup, signOut: this.signOut }); navigation.addListener('didFocus', this.onFocus); this.requestPushNotificationsPermissions(); // if app was in background this.onNotificationOpened = firebase .notifications() .onNotificationOpened(this.handleOpenedNotification); } componentWillUnmount() { // remove the callback this.onNotificationOpened(); } requestPushNotificationsPermissions = async () => { const { uploadPushToken } = this.props; const enabled = await firebase.messaging().hasPermission(); if (enabled) { console.log("we've got push permissions"); } else { try { console.log('requesting permission'); await firebase.messaging().requestPermission(); } catch (error) { console.log('permissions rejected :('); } } const fcmToken = await firebase.messaging().getToken(); if (fcmToken) { uploadPushToken(fcmToken); } else { console.log('could not get push token from firebase'); } }; handleOpenedNotification = ({ notification }) => { if (notification && notification.data.debtsId) { this.goToDebt(notification.data.debtsId); } }; onFocus = async () => { const { fetchDebts } = this.props; this.setState({ loading: true }); await fetchDebts(); this.setState({ loading: false }); }; signOut = () => this.props.signOut(); onRefresh = async () => { this.setState({ refreshing: true }); await this.props.fetchDebts(); this.setState({ refreshing: false }); }; goToDebt = debtId => { const { navigation } = this.props; navigation.navigate('DebtScreen', { debtId }); }; toggleAddPopup = () => this.setState(prevState => ({ popupVisible: !prevState.popupVisible })); toggleConfirmationPopup = () => this.setState(prevState => ({ confirmationPopupVisible: !prevState.confirmationPopupVisible })); renderEmptyPlaceholder = () => { const { loading } = this.state; return loading ? ( <ActivityIndicator size="large" style={debtScreenStyles.spinner} /> ) : ( <TouchableWithoutFeedback> <View style={styles.placeholderContainer}> <IonIcon name="ios-paper" size={40} color={colors.black} /> <Text style={styles.placeholderText}> There are no records yet. Tap '+' to add one! </Text> </View> </TouchableWithoutFeedback> ); }; renderAddPopup = () => ( <AddPopup isVisible={this.state.popupVisible} onBackdropPress={this.toggleAddPopup} onUserSelected={userToAdd => { this.setState({ userToAdd }); this.toggleAddPopup(); setTimeout(this.toggleConfirmationPopup, 700); }} /> ); renderAddConfirmationPopup = () => ( <AddConfirmationPopup isVisible={this.state.confirmationPopupVisible} onBackdropPress={this.toggleConfirmationPopup} onClose={this.toggleConfirmationPopup} onConfirmation={debtId => { this.toggleConfirmationPopup(); this.props.navigation.navigate('DebtScreen', { debtId }); }} user={this.state.userToAdd} /> ); renderSummary = () => { const { user } = this.props; return ( <View style={styles.summaryContainer}> <Image source={{ uri: user.picture }} style={styles.summaryAvatar} /> <Text style={styles.summaryText}>{user.name}</Text> </View> ); }; render() { const { debts } = this.props; const { refreshing } = this.state; return ( <View style={styles.container}> {this.renderAddPopup()} {this.renderSummary()} {this.renderAddConfirmationPopup()} <View style={styles.listContainer}> <FlatList data={debts} renderItem={({ item }) => ( <Debt debt={item} onPress={() => this.goToDebt(item.id)} /> )} keyExtractor={item => item.id} ListEmptyComponent={this.renderEmptyPlaceholder} refreshControl={ <RefreshControl refreshing={refreshing} onRefresh={this.onRefresh} colors={['gray']} tintColor="gray" /> } /> </View> </View> ); } }
creditcardsimulation_redux_hooks/src/index.js
balaSpyrus/code
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import rootReducer from './reducers'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; const store = createStore(rootReducer); ReactDOM.render( <Provider store={store}> <App /> </Provider> , document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
packages/cf-builder-table/example/basic/component.js
manatarms/cf-ui
import React from 'react'; import { connect } from 'react-redux'; import { TableBuilder, tableReducer, tableActions } from 'cf-builder-table'; import { TableCell } from 'cf-component-table'; import { Button as ButtonUnstyled, ButtonTheme } from 'cf-component-button'; import { applyTheme } from 'cf-style-container'; const Button = applyTheme(ButtonUnstyled, ButtonTheme); const EXAMPLE_TABLE = 'EXAMPLE_TABLE'; class BuilderTable extends React.Component { constructor(props) { super(props); this.state = { data: [ { id: '1', name: 'James', coolness: 1 }, { id: '2', name: 'David', coolness: -1 } ] }; this.handleClick = this.handleClick.bind(this); } handleClick(id) { this.setState( { data: this.state.data.map(item => { return item.id === id ? { ...item, coolness: item.id === '1' ? Infinity : -Infinity } : item; }) }, () => { this.props.dispatch( tableActions.flashRow(EXAMPLE_TABLE, id, 'success') ); } ); } render() { return ( <TableBuilder tableName={EXAMPLE_TABLE} rows={this.state.data.map(item => { return { id: item.id, cells: item }; })} columns={[ { label: 'Name', cell: cells => { return ( <TableCell key="name"> {cells.name} </TableCell> ); } }, { label: 'Coolness', cell: cells => { return ( <TableCell key="coolness"> {cells.coolness.toString()} </TableCell> ); } }, { label: 'Update', cell: cells => { return ( <TableCell key="actions"> <Button type="default" onClick={this.handleClick.bind(null, cells.id)} > Update </Button> </TableCell> ); } } ]} /> ); } } export default connect(() => ({}))(BuilderTable);
react/features/base/media/components/native/Video.js
bgrozev/jitsi-meet
// @flow import React, { Component } from 'react'; import { RTCView } from 'react-native-webrtc'; import { Pressable } from '../../../react'; import styles from './styles'; import VideoTransform from './VideoTransform'; /** * The type of the React {@code Component} props of {@link Video}. */ type Props = { mirror: boolean, onPlaying: Function, /** * Callback to invoke when the {@code Video} is clicked/pressed. */ onPress: Function, stream: Object, /** * Similarly to the CSS property z-index, specifies the z-order of this * Video in the stacking space of all Videos. When Videos overlap, * zOrder determines which one covers the other. A Video with a larger * zOrder generally covers a Video with a lower one. * * Non-overlapping Videos may safely share a z-order (because one does * not have to cover the other). * * The support for zOrder is platform-dependent and/or * implementation-specific. Thus, specifying a value for zOrder is to be * thought of as giving a hint rather than as imposing a requirement. * For example, video renderers such as Video are commonly implemented * using OpenGL and OpenGL views may have different numbers of layers in * their stacking space. Android has three: a layer bellow the window * (aka default), a layer bellow the window again but above the previous * layer (aka media overlay), and above the window. Consequently, it is * advisable to limit the number of utilized layers in the stacking * space to the minimum sufficient for the desired display. For example, * a video call application usually needs a maximum of two zOrder * values: 0 for the remote video(s) which appear in the background, and * 1 for the local video(s) which appear above the remote video(s). */ zOrder: number, /** * Indicates whether zooming (pinch to zoom and/or drag) is enabled. */ zoomEnabled: boolean }; /** * The React Native {@link Component} which is similar to Web's * {@code HTMLVideoElement} and wraps around react-native-webrtc's * {@link RTCView}. */ export default class Video extends Component<Props> { /** * React Component method that executes once component is mounted. * * @inheritdoc */ componentDidMount() { // RTCView currently does not support media events, so just fire // onPlaying callback when <RTCView> is rendered. const { onPlaying } = this.props; onPlaying && onPlaying(); } /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement|null} */ render() { const { onPress, stream, zoomEnabled } = this.props; if (stream) { // RTCView const style = styles.video; const objectFit = zoomEnabled ? 'contain' : (style && style.objectFit) || 'cover'; const rtcView = ( <RTCView mirror = { this.props.mirror } objectFit = { objectFit } streamURL = { stream.toURL() } style = { style } zOrder = { this.props.zOrder } /> ); // VideoTransform implements "pinch to zoom". As part of "pinch to // zoom", it implements onPress, of course. if (zoomEnabled) { return ( <VideoTransform enabled = { zoomEnabled } onPress = { onPress } streamId = { stream.id } style = { style }> { rtcView } </VideoTransform> ); } // XXX Unfortunately, VideoTransform implements a custom press // detection which has been observed to be very picky about the // precision of the press unlike the builtin/default/standard press // detection which is forgiving to imperceptible movements while // pressing. It's not acceptable to be so picky, especially when // "pinch to zoom" is not enabled. return ( <Pressable onPress = { onPress }> { rtcView } </Pressable> ); } // RTCView has peculiarities which may or may not be platform specific. // For example, it doesn't accept an empty streamURL. If the execution // reached here, it means that we explicitly chose to not initialize an // RTCView as a way of dealing with its idiosyncrasies. return null; } }
collect-webapp/frontend/src/datamanagement/components/recordeditor/fields/CompositeAttributeFormItem.js
openforis/collect
import React from 'react' import { Col, Label, Row } from 'reactstrap' const CompositeAttributeFormItem = ({ field, label, inputField, labelWidth = 50 }) => { const widthPx = `${labelWidth}px` return ( <Row key={field}> <Col style={{ width: widthPx, maxWidth: widthPx }}> <Label>{label}</Label> </Col> <Col>{inputField}</Col> </Row> ) } export default CompositeAttributeFormItem
app/containers/LanguageProvider/index.js
oualid-mazouz/fbchallenge
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { IntlProvider } from 'react-intl'; import { makeSelectLocale } from './selectors'; export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}> {React.Children.only(this.props.children)} </IntlProvider> ); } } LanguageProvider.propTypes = { locale: React.PropTypes.string, messages: React.PropTypes.object, children: React.PropTypes.element.isRequired, }; const mapStateToProps = createSelector( makeSelectLocale(), (locale) => ({ locale }) ); function mapDispatchToProps(dispatch) { return { dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(LanguageProvider);
src/Icons/Cancel.js
hasseboulen/WoWAnalyzer
import React from 'react'; // https://thenounproject.com/search/?q=circled%20cross&i=1144421 // Created by johartcamp from the Noun Project const Icon = ({ ...other }) => ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" {...other}> <path d="M 50 5 C 25.18272 5 5 25.1827 5 50 C 5 74.8173 25.18272 95 50 95 C 74.81728 95 95 74.8173 95 50 C 95 25.1827 74.81728 5 50 5 z M 50 11 C 71.57464 11 89 28.42534 89 50 C 89 71.5746 71.57464 89 50 89 C 28.42536 89 11 71.5746 11 50 C 11 28.42534 28.42536 11 50 11 z M 31.65625 28.96875 A 3.0003 3.0003 0 0 0 29.875 34.09375 L 45.75 50 L 29.875 65.875 A 3.0003 3.0003 0 1 0 34.125 70.09375 L 50 54.21875 L 65.875 70.09375 A 3.0003 3.0003 0 1 0 70.125 65.875 L 54.25 50 L 70.125 34.09375 A 3.0003 3.0003 0 0 0 67.65625 28.96875 A 3.0003 3.0003 0 0 0 65.875 29.875 L 50 45.75 L 34.125 29.875 A 3.0003 3.0003 0 0 0 31.65625 28.96875 z " /> </svg> ); export default Icon;
frontends/xcms/app/index.js
suryakencana/niimanga
require('es6-shim'); require('./styles.css'); require("font-awesome-webpack"); require('bootstrap-table/dist/bootstrap-table.css'); require('bootstrap-table/dist/bootstrap-table.js'); import React from 'react'; import Router from 'utils/router'; import { Provider } from 'react-redux'; import configureStore from './store'; import fetchData from './utils/fetchData'; import rehydrate from './utils/rehydrate'; import { EventEmitter } from 'events'; const store = configureStore(); var loadingEvents = new EventEmitter(); var token = rehydrate(); var renderState = { element: document.getElementById('app-container'), Handler: null, routerState: null }; var render = () => { var { element, Handler, routerState } = renderState; loadingEvents.emit('start'); fetchData(token, routerState).then((data) => { loadingEvents.emit('end'); React.render( <Provider store={store}> { () => <Handler routerState={routerState} data={data} token={token} loadingEvents={loadingEvents} />} </Provider> , element); }); }; Router.run((Handler, state) => { renderState.Handler = Handler; renderState.routerState = state; render(); });
lib/cli/generators/REACT_NATIVE/template/storybook/stories/index.js
shilman/storybook
import React from 'react'; import { Text } from 'react-native'; import { storiesOf } from '@storybook/react-native'; import { action } from '@storybook/addon-actions'; import { linkTo } from '@storybook/addon-links'; import Button from './Button'; import CenterView from './CenterView'; import Welcome from './Welcome'; storiesOf('Welcome', module).add('to Storybook', () => <Welcome showApp={linkTo('Button')} />); storiesOf('Button', module) .addDecorator(getStory => <CenterView>{getStory()}</CenterView>) .add('with text', () => ( <Button onPress={action('clicked-text')}> <Text>Hello Button</Text> </Button> )) .add('with some emoji', () => ( <Button onPress={action('clicked-emoji')}> <Text>😀 😎 👍 💯</Text> </Button> ));
fields/types/relationship/RelationshipField.js
ligson/keystone
import _ from 'underscore'; import Field from '../Field'; import React from 'react'; import Select from 'react-select'; import superagent from 'superagent'; import { Button, FormInput } from 'elemental'; module.exports = Field.create({ displayName: 'RelationshipField', shouldCollapse () { // many:true relationships have an Array for a value // so need to check length instead if (this.props.many) { return this.props.collapse && !this.props.value.length; } return this.props.collapse && !this.props.value; }, getInitialState () { return { ready: this.props.value ? false : true, simpleValue: this.props.value, expandedValues: null }; }, componentDidMount () { this.loadValues(this.props.value); }, componentWillReceiveProps (newProps) { if (newProps.value !== this.state.simpleValue) { this.setState({ ready: false, simpleValue: newProps.value, expandedValues: null }); this.loadValues(newProps.value); } }, loadValues (input) { var expandedValues = []; var inputs = _.compact([].concat(input)); var self = this; var finish = function () { self.setState({ ready: true, expandedValues: expandedValues }); }; if (!inputs.length) return finish(); var callbackCount = 0; _.each(inputs, function(input) { expandedValues.push({ value: input }); superagent .get('/keystone/api/' + self.props.refList.path + '/' + input + '?simple') .set('Accept', 'application/json') .end(function (err, res) { if (err) throw err; var value = res.body; _.findWhere(expandedValues, { value: value.id }).label = value.name; callbackCount++; if (callbackCount === inputs.length) { finish(); } }); }); }, buildFilters () { var filters = {}; _.each(this.props.filters, function(value, key) { if(_.isString(value) && value[0] == ':') {//eslint-disable-line eqeqeq var fieldName = value.slice(1); var val = this.props.values[fieldName]; if (val) { filters[key] = val; return; } // check if filtering by id and item was already saved if (fieldName === ':_id' && Keystone.item) { filters[key] = Keystone.item.id; return; } } else { filters[key] = value; } }, this); var parts = []; _.each(filters, function (val, key) { parts.push('filters[' + key + ']=' + encodeURIComponent(val)); }); return parts.join('&'); }, buildOptionQuery (input) { return 'context=relationship&q=' + input + '&list=' + Keystone.list.path + '&field=' + this.props.path + '&' + this.buildFilters(); }, getOptions (input, callback) { superagent .get('/keystone/api/' + this.props.refList.path + '/autocomplete?' + this.buildOptionQuery(input)) .set('Accept', 'application/json') .end(function (err, res) { if (err) throw err; var data = res.body; callback(null, { options: data.items.map(function (item) { return { value: item.id, label: item.name }; }), complete: data.total === data.items.length }); }); }, renderLoadingUI () { return <div className='help-block'>loading...</div>; }, updateValue (simpleValue, expandedValues) { this.setState({ simpleValue: simpleValue, expandedValues: expandedValues }); this.props.onChange({ path: this.props.path, value: this.props.many ? _.pluck(expandedValues, 'value') : simpleValue }); }, renderValue () { if (!this.state.ready) { return this.renderLoadingUI(); } // Todo: this is only a temporary fix, remodel if (this.state.expandedValues && this.state.expandedValues.length) { var body = []; _.each(this.state.expandedValues, function (item, i) { body.push(<FormInput key={i} noedit href={'/keystone/' + this.props.refList.path + '/' + item.value}>{item.label}</FormInput>); }, this); return body; } else { return <FormInput noedit>not set)</FormInput>; } }, renderField () { if (!this.state.ready) { return this.renderLoadingUI(); } let button = (!this.props.many && this.props.value) ? ( <Button key="relational-button" type="link" href={'/keystone/' + this.props.refList.path + '/' + this.props.value} className='keystone-relational-button' title={'Go to "' + this.state.expandedValues[0].label + '"'}> <span className="octicon octicon-file-symlink-file" /> </Button> ) : null; return ( <div style={{ position: 'relative' }}> <Select key="relationship-select" multi={this.props.many} onChange={this.updateValue} name={this.props.path} asyncOptions={this.getOptions} value={this.state.expandedValues} /> {button} </div> ); } });
webapp-src/src/MainScreen/FullScreen.js
babelouest/taliesin
import React, { Component } from 'react'; import { Row, Col, Image, ButtonGroup, Button, MenuItem, DropdownButton } from 'react-bootstrap'; import FontAwesome from 'react-fontawesome'; import StateStore from '../lib/StateStore'; import i18n from '../lib/i18n'; class FullScreen extends Component { constructor(props) { super(props); this.state = { stream: StateStore.getState().profile.stream, media: StateStore.getState().profile.mediaNow, mediaNext: StateStore.getState().profile.mediaNext, jukeboxIndex: StateStore.getState().profile.jukeboxIndex, currentPlayer: StateStore.getState().profile.currentPlayer, show: StateStore.getState().showFullScreen, title: "", titleNext: "", imgBlob: false, status: StateStore.getState().profile.currentPlayerStatus, repeat: StateStore.getState().profile.currentPlayerRepeat, random: StateStore.getState().profile.currentPlayerRandom, volume: StateStore.getState().profile.currentPlayerVolume, playerSwitch: StateStore.getState().profile.currentPlayerSwitch }; StateStore.subscribe(() => { if (this._ismounted) { if (StateStore.getState().lastAction === "loadStream") { this.setState({stream: StateStore.getState().profile.stream}, () => {this.loadMedia();}); } else if (StateStore.getState().lastAction === "setJukeboxIndex") { this.setState({jukeboxIndex: StateStore.getState().profile.jukeboxIndex}, () => {this.loadMedia();}); } else if (StateStore.getState().lastAction === "setMediaNow") { this.setState({media: StateStore.getState().profile.mediaNow,}, () => {this.loadMedia();}); } else if (StateStore.getState().lastAction === "setMediaNext") { this.setState({mediaNext: StateStore.getState().profile.mediaNext}, () => {this.loadMedia();}); } else if (StateStore.getState().lastAction === "setCurrentPlayerStatus") { this.setState({ status: StateStore.getState().profile.currentPlayerStatus, repeat: StateStore.getState().profile.currentPlayerRepeat, random: StateStore.getState().profile.currentPlayerRandom, volume: StateStore.getState().profile.currentPlayerVolume, playerSwitch: StateStore.getState().profile.currentPlayerSwitch }); } else if (StateStore.getState().lastAction === "showFullScreen") { this.setState({ stream: StateStore.getState().profile.stream, media: StateStore.getState().profile.mediaNow, mediaNext: StateStore.getState().profile.mediaNext, jukeboxIndex: StateStore.getState().profile.jukeboxIndex, show: StateStore.getState().showFullScreen, title: "", titleNext: "", imgBlob: false, status: StateStore.getState().profile.currentPlayerStatus, repeat: StateStore.getState().profile.currentPlayerRepeat, random: StateStore.getState().profile.currentPlayerRandom, volume: StateStore.getState().profile.currentPlayerVolume, playerSwitch: StateStore.getState().profile.currentPlayerSwitch }, () => {this.loadMedia();}); } else if (StateStore.getState().lastAction === "loadStream" || StateStore.getState().lastAction === "loadStreamAndPlay") { this.setState({stream: StateStore.getState().profile.stream}, () => {this.loadMedia();}); } else if (StateStore.getState().lastAction === "setJukeboxSwitch") { this.setState({playerSwitch: StateStore.getState().profile.currentPlayerSwitch}); } } }); this.loadMedia = this.loadMedia.bind(this); this.buildTitle = this.buildTitle.bind(this); this.buildTitleNext = this.buildTitleNext.bind(this); this.handleClose = this.handleClose.bind(this); this.getMediaCover = this.getMediaCover.bind(this); this.handleSelectArtist = this.handleSelectArtist.bind(this); this.handleSelectAlbum = this.handleSelectAlbum.bind(this); this.handleSelectYear = this.handleSelectYear.bind(this); this.handleSelectGenre = this.handleSelectGenre.bind(this); this.handlePlayerAction = this.handlePlayerAction.bind(this); this.handleChangeVolume = this.handleChangeVolume.bind(this); this.handleSelectFolder = this.handleSelectFolder.bind(this); this.getMediaFolder = this.getMediaFolder.bind(this); this.loadMedia(); } componentWillReceiveProps(nextProps) { this.setState({ stream: StateStore.getState().profile.stream, media: StateStore.getState().profile.mediaNow, mediaNext: StateStore.getState().profile.mediaNext, jukeboxIndex: StateStore.getState().profile.jukeboxIndex, show: StateStore.getState().showFullScreen, title: "", titleNext: "", imgBlob: false, status: StateStore.getState().profile.currentPlayerStatus, repeat: StateStore.getState().profile.currentPlayerRepeat, random: StateStore.getState().profile.currentPlayerRandom, volume: StateStore.getState().profile.currentPlayerVolume, playerSwitch: StateStore.getState().profile.currentPlayerSwitch }, () => { this.loadMedia(); }); } componentWillUnmount() { this._ismounted = false; } componentDidMount() { this._ismounted = true; } loadMedia() { if (this._ismounted) { this.setState({title: this.buildTitle(), titleNext: this.buildTitleNext()}); this.getMediaCover(); this.getMediaFolder(); } } buildTitle() { var title = ""; if (!!this.state.media && !!this.state.media.tags) { if (this.state.jukeboxIndex > -1 && !this.state.stream.webradio) { title += ((this.state.jukeboxIndex+1)<10?"0"+(this.state.jukeboxIndex+1):(this.state.jukeboxIndex+1)) + "/" + (this.state.stream.elements<10?"0"+this.state.stream.elements:this.state.stream.elements) + " - "; } if (!!this.state.media.tags && !!this.state.media.tags.title) { title += this.state.media.tags.title; } else { title += this.state.media.name.replace(/\.[^/.]+$/, ""); } } return title; } buildTitleNext() { var title = ""; if (!!this.state.mediaNext && !!this.state.mediaNext.tags) { if (this.state.mediaNext.tags.artist) { title += this.state.mediaNext.tags.artist + " - "; } if (this.state.jukeboxIndex > -1 && !this.state.stream.webradio) { title += ((this.state.jukeboxIndex+1)<10?"0"+(this.state.jukeboxIndex+1):(this.state.jukeboxIndex+1)) + "/" + (this.state.stream.elements<10?"0"+this.state.stream.elements:this.state.stream.elements) + " - "; } if (!!this.state.mediaNext.tags && !!this.state.mediaNext.tags.title) { title += this.state.mediaNext.tags.title; } else { title += this.state.mediaNext.name.replace(/\.[^/.]+$/, ""); } } return title; } handleClose() { StateStore.dispatch({type: "showFullScreen", show: false}); } handleSelectArtist(value) { StateStore.dispatch({type: "showFullScreen", show: false}); StateStore.dispatch({type: "setCurrentBrowse", browse: "category"}); StateStore.dispatch({type: "setCurrentDataSource", currentDataSource: StateStore.getState().dataSourceList.find((ds) => {return ds.name === this.state.media.data_source})}); StateStore.dispatch({type: "setCurrentCategory", category: "artist", categoryValue: value}); } getMediaFolder() { var media = this.state.media; if (media) { if (media.path) { if (media.path.lastIndexOf("/") > -1) { media.folder = media.path.substring(0, media.path.lastIndexOf("/")); } else { media.folder = ""; } this.setState({media: media}); } else { media.folder = ""; this.setState({media: media}); } } } handleSelectAlbum(value) { StateStore.dispatch({type: "showFullScreen", show: false}); StateStore.dispatch({type: "setCurrentBrowse", browse: "category"}); StateStore.dispatch({type: "setCurrentDataSource", currentDataSource: StateStore.getState().dataSourceList.find((ds) => {return ds.name === this.state.media.data_source})}); StateStore.dispatch({type: "setCurrentCategory", category: "album", categoryValue: value}); } handleSelectYear(value) { StateStore.dispatch({type: "showFullScreen", show: false}); StateStore.dispatch({type: "setCurrentBrowse", browse: "category"}); StateStore.dispatch({type: "setCurrentDataSource", currentDataSource: StateStore.getState().dataSourceList.find((ds) => {return ds.name === this.state.media.data_source})}); StateStore.dispatch({type: "setCurrentCategory", category: "year", categoryValue: value}); } handleSelectGenre(value) { StateStore.dispatch({type: "showFullScreen", show: false}); StateStore.dispatch({type: "setCurrentBrowse", browse: "category"}); StateStore.dispatch({type: "setCurrentDataSource", currentDataSource: StateStore.getState().dataSourceList.find((ds) => {return ds.name === this.state.media.data_source})}); StateStore.dispatch({type: "setCurrentCategory", category: "genre", categoryValue: value}); } handlePlayerAction(action) { StateStore.dispatch({type: "setPlayerAction", action: action}); } handleChangeVolume(deltaVolume) { var volume = this.state.volume + deltaVolume; if (volume < 0) volume = 0; if (volume > 100) volume = 100; if (this._ismounted) { this.setState({volume: (volume)}, () => { StateStore.dispatch({type: "setPlayerAction", action: "volume", parameter: (deltaVolume)}); }); } } handleSelectFolder(value) { StateStore.dispatch({type: "showFullScreen", show: false}); StateStore.dispatch({type: "setCurrentDataSource", currentDataSource: StateStore.getState().dataSourceList.find((ds) => {return ds.name === this.state.media.data_source})}); StateStore.dispatch({type: "setCurrentBrowse", browse: "path"}); StateStore.dispatch({type: "setCurrentPath", path: value}); } getMediaCover() { if (!!this.state.media && this.state.show && this._ismounted) { StateStore.getState().APIManager.taliesinApiRequest("GET", "/data_source/" + encodeURIComponent(this.state.media.data_source) + "/browse/path/" + encodeURI(this.state.media.path).replace(/#/g, "%23").replace(/\+/g, "%2B") + "?cover&base64") .then((result) => { this.setState({imgBlob: result}); }) .fail(() => { this.setState({imgBlob: false}); }); } } render() { var mediaImage, metadata = [], separator, playButton, playButtonLarge, switchButton, switchButtonXs; if (this.state.imgBlob) { mediaImage = <Image src={"data:image/jpeg;base64," + this.state.imgBlob} className="cover-image-full center-block" responsive />; } else { mediaImage = <Image src="images/generic-album.png" className="cover-image-full center-block" responsive />; } if (this.state.status === "stop") { playButton = <Button title={i18n.t("common.play")} onClick={() => {this.handlePlayerAction("play")}}> <FontAwesome name={"play"} /> </Button>; playButtonLarge = <Button bsSize="large" title={i18n.t("common.play")} onClick={() => {this.handlePlayerAction("play")}}> <FontAwesome name={"play"} /> </Button>; } else if (this.state.status === "pause") { playButton = <Button title={i18n.t("common.play")} onClick={() => {this.handlePlayerAction("pause")}}> <FontAwesome name={"play"} /> </Button>; playButtonLarge = <Button bsSize="large" title={i18n.t("common.play")} onClick={() => {this.handlePlayerAction("pause")}}> <FontAwesome name={"play"} /> </Button>; } else if (!this.state.stream.webradio) { playButton = <Button title={i18n.t("common.pause")} onClick={() => {this.handlePlayerAction("pause")}}> <FontAwesome name={"pause"} /> </Button>; playButtonLarge = <Button bsSize="large" title={i18n.t("common.pause")} onClick={() => {this.handlePlayerAction("pause")}}> <FontAwesome name={"pause"} /> </Button>; } else { playButton = <Button title={i18n.t("common.play")} disabled={true}> <FontAwesome name={"play"} /> </Button>; playButtonLarge = <Button bsSize="large" title={i18n.t("common.play")} disabled={true}> <FontAwesome name={"play"} /> </Button>; } if (this.state.media) { if (this.state.media.tags.title) { metadata.push( <Row key={0}> <Col xs={6} className="text-right"> <label className="text-fullscreen">{i18n.t("common.title")}</label> </Col> <Col xs={6}> <span className="text-fullscreen">{this.state.media.tags.title}</span> </Col> </Row>); } var dm = Math.floor(this.state.media.duration/60000); if (dm < 10) { dm = "0" + dm; } var ds = Math.floor(this.state.media.duration/1000)%60; if (ds < 10) { ds = "0" + ds; } metadata.push( <Row key={1}> <Col xs={6} className="text-right"> <label className="text-fullscreen">{i18n.t("common.duration")}</label> </Col> <Col xs={6}> <span className="text-fullscreen">{dm}:{ds}</span> </Col> </Row>); if (this.state.media.tags.artist) { metadata.push( <Row key={2}> <Col xs={6} className="text-right"> <label className="text-fullscreen">{i18n.t("common.artist")}</label> </Col> <Col xs={6}> <span><a role="button" className="anchor-fullscreen" onClick={() => {this.handleSelectArtist(this.state.media.tags.artist)}}>{this.state.media.tags.artist}</a></span> </Col> </Row>); } if (this.state.media.tags.album) { metadata.push( <Row key={3}> <Col xs={6} className="text-right"> <label className="text-fullscreen">{i18n.t("common.album")}</label> </Col> <Col xs={6}> <span><a role="button" className="anchor-fullscreen" onClick={() => {this.handleSelectAlbum(this.state.media.tags.album)}}>{this.state.media.tags.album}</a></span> </Col> </Row>); } if (this.state.media.tags.date) { metadata.push( <Row key={4}> <Col xs={6} className="text-right"> <label className="text-fullscreen">{i18n.t("common.date")}</label> </Col> <Col xs={6}> <span><a role="button" className="anchor-fullscreen" onClick={() => {this.handleSelectYear(this.state.media.tags.date)}}>{this.state.media.tags.date.substring(0, 4)}</a></span> </Col> </Row>); } if (this.state.media.tags.genre) { metadata.push( <Row key={5}> <Col xs={6} className="text-right"> <label className="text-fullscreen">{i18n.t("common.genre")}</label> </Col> <Col xs={6}> <span><a role="button" className="anchor-fullscreen" onClick={() => {this.handleSelectGenre(this.state.media.tags.genre)}}>{this.state.media.tags.genre}</a></span> </Col> </Row>); } if (this.state.media.tags.copyright) { metadata.push( <Row key={5}> <Col xs={6} className="text-right"> <label className="text-fullscreen">{i18n.t("common.copyright")}</label> </Col> <Col xs={6}> <span>{this.state.media.tags.copyright}</span> </Col> </Row>); } metadata.push( <Row key={6}> <Col xs={6} className="text-right"> <label className="text-fullscreen">{i18n.t("common.open_folder")}</label> </Col> <Col xs={6}> <span><a role="button" className="anchor-fullscreen" onClick={() => {this.handleSelectFolder(this.state.media.folder)}}>{this.state.media.data_source + "/" + this.state.media.folder}</a></span> </Col> </Row> ); if (this.state.titleNext) { metadata.push( <Row key={7}> <Col xs={6} className="text-right"> <label className="text-fullscreen">{i18n.t("common.title_next")}</label> </Col> <Col xs={6}> <span className="text-fullscreen">{this.state.titleNext}</span> </Col> </Row>); } } if (StateStore.getState().profile.currentPlayer.type === "carleon") { switchButton = <Button title={i18n.t("player.switch")} onClick={() => {this.handlePlayerAction("switch")}} className={(this.state.playerSwitch)?"btn-primary":""}> <FontAwesome name={"power-off"} /> </Button> switchButtonXs = <Button bsSize="large" title={i18n.t("player.switch")} onClick={() => {this.handlePlayerAction("switch")}} className={(this.state.playerSwitch)?"btn-primary":""}> <FontAwesome name={"power-off"} /> </Button> } return ( <div className={"fullscreen" + (!this.state.show?" hidden":"")} > <div className="media-background-fullscreen" style={{backgroundImage:this.state.imgBlob?"url(data:image/png;base64,"+this.state.imgBlob+")":"" }}> </div> <Row style={{marginTop: "10px"}}> <Col md={12} className="text-center"> <div className="text-fullscreen">{this.state.title}</div> </Col> </Row> <Row style={{marginTop: "10px"}}> <Col md={12} className="text-center hidden-sm hidden-xs"> <ButtonGroup> <Button title={i18n.t("common.previous")} onClick={() => {this.handlePlayerAction("previous")}}> <FontAwesome name={"fast-backward"} /> </Button> <Button title={i18n.t("common.stop")} onClick={() => {this.handlePlayerAction("stop")}}> <FontAwesome name={"stop"} /> </Button> {playButton} <Button title={i18n.t("common.next")} onClick={() => {this.handlePlayerAction("next")}}> <FontAwesome name={"fast-forward"} /> </Button> <Button title={i18n.t("common.repeat")} onClick={() => {this.handlePlayerAction("repeat")}} className={(this.state.repeat&&!this.state.stream.webradio)?"btn-primary":""} disabled={this.state.stream.webradio}> <FontAwesome name={"repeat"} /> </Button> <Button title={i18n.t("common.random")} onClick={() => {this.handlePlayerAction("random")}} className={(this.state.random&&!this.state.stream.webradio)?"btn-primary":""} disabled={this.state.stream.webradio}> <FontAwesome name={"random"} /> </Button> <DropdownButton title={<FontAwesome name={"volume-up"} />} pullRight id="dropdown-volume"> <MenuItem eventKey="1" className="text-center" onClick={() => {this.handleChangeVolume(5)}}>{i18n.t("common.volume_plus_5")}</MenuItem> <MenuItem eventKey="1" className="text-center" onClick={() => {this.handleChangeVolume(1)}}>{i18n.t("common.volume_plus_1")}</MenuItem> <MenuItem className="text-center">{i18n.t("common.volume_current")} {this.state.volume} %</MenuItem> <MenuItem eventKey="1" className="text-center" onClick={() => {this.handleChangeVolume(-1)}}>{i18n.t("common.volume_minus_1")}</MenuItem> <MenuItem eventKey="1" className="text-center" onClick={() => {this.handleChangeVolume(-5)}}>{i18n.t("common.volume_minus_5")}</MenuItem> </DropdownButton> {switchButton} </ButtonGroup> </Col> <Col md={12} className="text-center visible-sm visible-xs"> <ButtonGroup> <Button bsSize="large" title={i18n.t("common.previous")} onClick={() => {this.handlePlayerAction("previous")}}> <FontAwesome name={"fast-backward"} /> </Button> <Button bsSize="large" title={i18n.t("common.stop")} onClick={() => {this.handlePlayerAction("stop")}}> <FontAwesome name={"stop"} /> </Button> {playButtonLarge} <Button bsSize="large" title={i18n.t("common.next")} onClick={() => {this.handlePlayerAction("next")}}> <FontAwesome name={"fast-forward"} /> </Button> <DropdownButton bsSize="large" title={<FontAwesome name={"volume-up"} />} pullRight id="dropdown-volume"> <MenuItem eventKey="1" className="text-center" onClick={() => {this.handleChangeVolume(5)}}>{i18n.t("common.volume_plus_5")}</MenuItem> <MenuItem eventKey="1" className="text-center" onClick={() => {this.handleChangeVolume(1)}}>{i18n.t("common.volume_plus_1")}</MenuItem> <MenuItem className="text-center">{i18n.t("common.volume_current")} {this.state.volume} %</MenuItem> <MenuItem eventKey="1" className="text-center" onClick={() => {this.handleChangeVolume(-1)}}>{i18n.t("common.volume_minus_1")}</MenuItem> <MenuItem eventKey="1" className="text-center" onClick={() => {this.handleChangeVolume(-5)}}>{i18n.t("common.volume_minus_5")}</MenuItem> </DropdownButton> {switchButtonXs} </ButtonGroup> </Col> </Row> <Row style={{marginTop: "10px"}}> <Col md={12}> {mediaImage} </Col> </Row> {separator} {metadata} <Row style={{marginTop: "10px"}}> <Col md={12} className="text-center"> <Button onClick={this.handleClose} className="btn btn-success"> {i18n.t("common.close")} </Button> </Col> </Row> </div> ); } } export default FullScreen;
app/javascript/mastodon/features/account_timeline/index.js
kirakiratter/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { fetchAccount } from '../../actions/accounts'; import { expandAccountFeaturedTimeline, expandAccountTimeline } from '../../actions/timelines'; import StatusList from '../../components/status_list'; import LoadingIndicator from '../../components/loading_indicator'; import Column from '../ui/components/column'; import HeaderContainer from './containers/header_container'; import ColumnBackButton from '../../components/column_back_button'; import { List as ImmutableList } from 'immutable'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { FormattedMessage } from 'react-intl'; import { fetchAccountIdentityProofs } from '../../actions/identity_proofs'; import MissingIndicator from 'mastodon/components/missing_indicator'; const emptyList = ImmutableList(); const mapStateToProps = (state, { params: { accountId }, withReplies = false }) => { const path = withReplies ? `${accountId}:with_replies` : accountId; return { isAccount: !!state.getIn(['accounts', accountId]), statusIds: state.getIn(['timelines', `account:${path}`, 'items'], emptyList), featuredStatusIds: withReplies ? ImmutableList() : state.getIn(['timelines', `account:${accountId}:pinned`, 'items'], emptyList), isLoading: state.getIn(['timelines', `account:${path}`, 'isLoading']), hasMore: state.getIn(['timelines', `account:${path}`, 'hasMore']), blockedBy: state.getIn(['relationships', accountId, 'blocked_by'], false), }; }; export default @connect(mapStateToProps) class AccountTimeline extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, statusIds: ImmutablePropTypes.list, featuredStatusIds: ImmutablePropTypes.list, isLoading: PropTypes.bool, hasMore: PropTypes.bool, withReplies: PropTypes.bool, blockedBy: PropTypes.bool, isAccount: PropTypes.bool, multiColumn: PropTypes.bool, }; componentWillMount () { const { params: { accountId }, withReplies } = this.props; this.props.dispatch(fetchAccount(accountId)); this.props.dispatch(fetchAccountIdentityProofs(accountId)); if (!withReplies) { this.props.dispatch(expandAccountFeaturedTimeline(accountId)); } this.props.dispatch(expandAccountTimeline(accountId, { withReplies })); } componentWillReceiveProps (nextProps) { if ((nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) || nextProps.withReplies !== this.props.withReplies) { this.props.dispatch(fetchAccount(nextProps.params.accountId)); this.props.dispatch(fetchAccountIdentityProofs(nextProps.params.accountId)); if (!nextProps.withReplies) { this.props.dispatch(expandAccountFeaturedTimeline(nextProps.params.accountId)); } this.props.dispatch(expandAccountTimeline(nextProps.params.accountId, { withReplies: nextProps.params.withReplies })); } } handleLoadMore = maxId => { this.props.dispatch(expandAccountTimeline(this.props.params.accountId, { maxId, withReplies: this.props.withReplies })); } render () { const { shouldUpdateScroll, statusIds, featuredStatusIds, isLoading, hasMore, blockedBy, isAccount, multiColumn } = this.props; if (!isAccount) { return ( <Column> <ColumnBackButton multiColumn={multiColumn} /> <MissingIndicator /> </Column> ); } if (!statusIds && isLoading) { return ( <Column> <LoadingIndicator /> </Column> ); } const emptyMessage = blockedBy ? <FormattedMessage id='empty_column.account_unavailable' defaultMessage='Profile unavailable' /> : <FormattedMessage id='empty_column.account_timeline' defaultMessage='No toots here!' />; return ( <Column> <ColumnBackButton multiColumn={multiColumn} /> <StatusList prepend={<HeaderContainer accountId={this.props.params.accountId} />} alwaysPrepend scrollKey='account_timeline' statusIds={blockedBy ? emptyList : statusIds} featuredStatusIds={featuredStatusIds} isLoading={isLoading} hasMore={hasMore} onLoadMore={this.handleLoadMore} shouldUpdateScroll={shouldUpdateScroll} emptyMessage={emptyMessage} bindToDocument={!multiColumn} timelineId='account' /> </Column> ); } }
sonar-flow-plugin/src/main/js/components/FlowIssuesList.js
I8C/sonar-flow-plugin
import React from 'react'; import FlowIssueItem from './FlowIssueItem.js' import {findIssues} from '../functions/sonar_api.js' export default class FlowIssuesList extends React.PureComponent { constructor(props) { super(props); // this.props.projectKey // this.props.selectedIssue // this.props.onSelection this.state = { issues: [], components: [] }; this.handleSelection = this.handleSelection.bind(this); } componentDidMount() { findIssues(this.props.projectKey).then( (response) => { this.setState({ issues: response.issues, components: response.components }); } ); } handleSelection(issue) { this.props.onSelection(issue); } render() { let issueItems = []; let lastComponent=undefined; this.state.issues.forEach(issue => { issue.id=issue.key; issueItems.push( <div> {issue.component!=lastComponent?<div className="concise-issue-component note text-ellipsis">{issue.component.replace(/.*:(.+?\/)(.+)(\/.+?\/.+)/,"$1...$3")}</div>:""} <FlowIssueItem {...issue} onSelection={this.handleSelection} isSelected={this.props.selectedIssue.id==issue.id}/> </div> ); lastComponent=issue.component; }); return ( <div className="search-navigator-facets-list"> <div>{issueItems}</div> </div> ); } }
src/index.js
grishanin/moviepilot-trending
import React from 'react'; import App from './App'; require('./css/main.less'); React.render(<App />, document.getElementById('root'));
tests/react_modules/es6class-proptypes-callsite.js
facebook/flow
/* @flow */ import React from 'react'; import Hello from './es6class-proptypes-module'; import type {Node} from 'react'; class HelloLocal extends React.Component<{name: string}> { defaultProps = {}; propTypes = { name: React.PropTypes.string.isRequired, }; render(): Node { return <div>{this.props.name}</div>; } } class Callsite extends React.Component<{}> { render(): Node { return ( <div> <Hello /> <HelloLocal /> </div> ); } } module.exports = Callsite;
app/components/views/videoTabs/VideoList.js
MutatedBread/binary-academy-rn
import React, { Component } from 'react'; import { View } from 'react-native'; import { List, Content, Container, ListItem, Left, Right, Body, Button, Thumbnail, Text, Icon } from 'native-base'; import Loading from './Loading.js' import LoadingMoreVideoSpinner from './LoadingMoreVideoSpinner.js' import VideoItem from './VideoItem.js' var YoutubeFetch = require('./../../YoutubeAPI/YoutubeFetch.js'); var YoutubeFetchStatus = require('./../../YoutubeAPI/YoutubeFetchStatus.js'); export default class VideoList extends Component { constructor(props) { super(props); this.youtubeFetch = new YoutubeFetch(this.props.playlistId); } async componentWillMount() { await this.loadVideos(YoutubeFetchStatus.NEW); } loadVideos = async (status) => { if(status === YoutubeFetchStatus.NEXT_PAGE) this.props.loadingFunction(true); var vids = this.props.videoArrayStore; let json = await this.youtubeFetch.getPlaylistDetails(status); for(var i = 0; i < await json.items.length; i++) { if(json.items[i].snippet.thumbnails) { vids.push({ title: json.items[i].snippet.title, medium_img_url: json.items[i].snippet.thumbnails.medium.url, videoId: json.items[i].snippet.resourceId.videoId }); } } this.props.videoArrayUpdateFunction(await vids); if(status === YoutubeFetchStatus.NEXT_PAGE) this.props.loadingFunction(false); this.forceUpdate(); } render() { return ( <Container> <Container> { (this.props.videoArrayStore.length > 0) ? <List dataArray={this.props.videoArrayStore} renderRow={(video) => <VideoItem onPress={this.props.viewVideo} video={video}/> } renderFooter={() => <ListItem center> { this.props.isLoading ? <Icon name="ios-more" /> : this.youtubeFetch.hasNextPage() ? <Button binary onPress={() => this.loadVideos(YoutubeFetchStatus.NEXT_PAGE)}> <Text> More Videos </Text> </Button> : null } </ListItem> } > </List> : <Loading /> } </Container> { (this.props.isLoading) ? <LoadingMoreVideoSpinner /> : null } </Container> ); }'' }
app/static/src/diagnostic/EquipmentForm_modules/AditionalEqupmentParameters_modules/TransformerParams.js
SnowBeaver/Vision
import React from 'react'; import FormControl from 'react-bootstrap/lib/FormControl'; import FormGroup from 'react-bootstrap/lib/FormGroup'; import ControlLabel from 'react-bootstrap/lib/ControlLabel'; import {findDOMNode} from 'react-dom'; import {hashHistory} from 'react-router'; import {Link} from 'react-router'; import Checkbox from 'react-bootstrap/lib/Checkbox'; import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger'; import Tooltip from 'react-bootstrap/lib/Tooltip'; import HelpBlock from 'react-bootstrap/lib/HelpBlock'; const TextField = React.createClass({ _onChange: function (e) { this.props.onChange(e); }, render: function () { let tooltip = <Tooltip id={this.props.label}>{this.props.label}</Tooltip>; var label = (this.props.label != null) ? this.props.label : ""; var name = (this.props.name != null) ? this.props.name : ""; var type = (this.props["data-type"] != null) ? this.props["data-type"]: undefined; var len = (this.props["data-len"] != null) ? this.props["data-len"]: undefined; var choice = (this.props["data-choice"] != null) ? this.props["data-choice"]: undefined; var validationState = (this.props.errors[name]) ? 'error' : null; var error = this.props.errors[name]; var value = (this.props["value"] != null) ? this.props["value"]: ""; return ( <OverlayTrigger overlay={tooltip} placement="top"> <FormGroup validationState={validationState}> <ControlLabel>{label}</ControlLabel> <FormControl type="text" placeholder={label} name={name} data-type={type} data-len={len} data-choice={choice} onChange={this._onChange} value={value} /> <HelpBlock className="warning">{error}</HelpBlock> <FormControl.Feedback /> </FormGroup> </OverlayTrigger> ); } }); var SelectField = React.createClass({ handleChange: function (e) { this.props.onChange(e); }, getInitialState: function () { return { items: [], isVisible: false, value: -1 }; }, isVisible: function () { return this.state.isVisible; }, componentDidMount: function () { var source = '/api/v1.0/' + this.props.source + '/'; this.serverRequest = $.authorizedGet(source, function (result) { this.setState({items: (result['result'])}); }.bind(this), 'json'); }, componentWillUnmount: function () { this.serverRequest.abort(); }, setVisible: function () { this.state.isVisible = true; }, render: function () { var label = (this.props.label != null) ? this.props.label : ""; var value = (this.props.value != null) ? this.props.value : ""; var name = (this.props.name != null) ? this.props.name : ""; var validationState = (this.props.errors[name]) ? 'error' : null; var error = this.props.errors[name]; var required = this.props.required ? this.props.required : null; var menuItems = []; for (var key in this.state.items) { menuItems.push(<option key={this.state.items[key].id} value={this.state.items[key].id}>{`${this.state.items[key].name ? this.state.items[key].name : this.state.items[key].model}`}</option>); } return ( <FormGroup validationState={validationState}> <ControlLabel>{label}</ControlLabel> <FormControl componentClass="select" onChange={this.handleChange} value={value} name={name} required={required} > <option value="">{required ? this.props.label + " *" : this.props.label}</option>); {menuItems} </FormControl> <HelpBlock className="warning">{error}</HelpBlock> </FormGroup> ); } }); var BushSerialSelectField = React.createClass({ handleChange: function (event, index, value) { this.setState({ value: event.target.value }); }, getInitialState: function () { return { items: [], isVisible: false, value: -1 }; }, isVisible: function () { return this.state.isVisible; }, componentDidMount: function () { var source = '/api/v1.0/' + this.props.source + '/'; this.serverRequest = $.authorizedGet(source, function (result) { this.setState({items: (result['result'])}); }.bind(this), 'json'); }, componentWillUnmount: function () { this.serverRequest.abort(); }, setVisible: function () { this.state.isVisible = true; }, render: function () { var label = (this.props.label != null) ? this.props.label : ""; var value = (this.props.value != null) ? this.props.value : ""; var name = (this.props.name != null) ? this.props.name : ""; var validationState = (this.props.errors[name]) ? 'error' : null; var error = this.props.errors[name]; var menuItems = []; for (var key in this.state.items) { menuItems.push(<option key={this.state.items[key].id} value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>); } return ( <FormGroup validationState={validationState}> <FormControl componentClass="select" onChange={this.handleChange} defaultValue={value} name={name} > <option>{this.props.label}</option>); {menuItems} </FormControl> <HelpBlock className="warning">{error}</HelpBlock> </FormGroup> ); } }); var TransformerParams = React.createClass({ getInitialState: function () { return { 'phase_number':'', 'threephase':'', 'fluid_volume':'', 'fluid_type_id':'', 'fluid_level_id':'', 'gassensor_id':'', 'bushing_serial1_id':'', 'bushing_serial2_id':'', 'bushing_serial3_id':'', 'bushing_serial4_id':'', 'bushing_serial5_id':'', 'bushing_serial6_id':'', 'bushing_serial7_id':'', 'bushing_serial8_id':'', 'bushing_serial9_id':'', 'bushing_serial10_id':'', 'bushing_serial11_id':'', 'bushing_serial12_id':'', 'mvaforced11':'', 'mvaforced12':'', 'mvaforced13':'', 'mvaforced14':'', 'imp_base1':'', 'imp_base2':'', 'impbasedmva3':'', 'impbasedmva4':'', 'mvaforced21':'', 'mvaforced22':'', 'mvaforced23':'', 'mvaforced24':'', 'mvaactual':'', 'mvaractual':'', 'mwreserve':'', 'mvareserve':'', 'mwultime':'', 'mvarultime':'', 'ratio_tag1':'', 'ratio_tag2':'', 'ratio_tag3':'', 'ratio_tag4':'', 'static_shield1':'', 'static_shield2':'', 'ratio_tag5':'', 'ratio_tag6':'', 'ratio_tag7':'', 'ratio_tag8':'', 'static_shield3':'', 'static_shield4':'', 'bushing_neutral1':'', 'bushing_neutral2':'', 'bushing_neutral3':'', 'bushing_neutral4':'', 'windings':'', 'winding_metal1':'', 'winding_metal2':'', 'winding_metal3':'', 'winding_metal4':'', 'primary_winding_connection':'', 'secondary_winding_connection':'', 'tertiary_winding_connection':'', 'quaternary_winding_connection':'', 'based_transformer_power':'', 'autotransformer':'', 'bil1':'', 'bil2':'', 'ltc1':'', 'ltc2':'', 'first_cooling_stage_power':'', 'second_cooling_stage_power':'', 'bil3':'', 'bil4':'', 'ltc3':'', 'third_cooling_stage_power':'', 'temperature_rise':'', 'cooling_rating':'', 'primary_tension':'', 'secondary_tension':'', 'tertiary_tension':'', 'impedance1':'', 'impedance2':'', 'impedance3':'', 'impedance4':'', 'formula_ratio1':'', 'formula_ratio2':'', 'formula_ratio3':'', 'sealed':'', 'welded_cover':'','id':'', 'errors': {} } }, handleChange: function(e){ var state = this.state; if (e.target.type == "checkbox"){ state[e.target.name] = e.target.checked; } else state[e.target.name] = e.target.value; this.setState(state); }, load:function() { this.setState(this.props.equipment_item) }, render: function () { var errors = (Object.keys(this.state.errors).length) ? this.state.errors : this.props.errors; return ( <div> <div className="row"> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Phase Number" name="phase_number" value={this.state.phase_number} errors={errors} data-choice={['1', '3', '6']}/> </div> <div className="col-md-2"> <Checkbox name="threephase" checked={this.state.threephase} onChange={this.handleChange}><b>Three Phase</b></Checkbox> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Fluid Volume" name="fluid_volume" value={this.state.fluid_volume} errors={errors} data-type="float"/> </div> {/* <div className="col-md-2"> <SelectField source="fluid_type" label="Fluid Type" value={this.state.fluid_type_id} errors={errors} name="fluid_type_id" required={(this.props.edited)}/> </div> */} {/*<div className="col-md-2"> <SelectField source="fluid_level" label="Fluid Level" value={this.state.fluid_level_id} errors={errors} name="fluid_level_id"/> </div>*/} <div className="col-md-2"> <SelectField onChange={this.handleChange} source="gas_sensor" label="Gas Sensor" value={this.state.gassensor_id} errors={errors} name="gassensor_id" required={(this.props.edited)}/> </div> </div> {/*<div className="row"> <div className="col-md-2"> <BushSerialSelectField source="bushing" label="Bushing Serial 1" value={this.state.bushing_serial1_id} errors={errors} name="bushing_serial1_id"/> </div> <div className="col-md-2"> <BushSerialSelectField source="bushing" label="Bushing Serial 2" value={this.state.bushing_serial2_id} errors={errors} name="bushing_serial2_id"/> </div> <div className="col-md-2"> <BushSerialSelectField source="bushing" label="Bushing Serial 3" value={this.state.bushing_serial3_id} errors={errors} name="bushing_serial3_id"/> </div> <div className="col-md-2"> <BushSerialSelectField source="bushing" label="Bushing Serial 4" value={this.state.bushing_serial4} errors={errors} name="bushing_serial4_id"/> </div> <div className="col-md-2"> <BushSerialSelectField source="bushing" label="Bushing Serial 5" value={this.state.bushing_serial5_id} errors={errors} name="bushing_serial5_id"/> </div> <div className="col-md-2"> <BushSerialSelectField source="bushing" label="Bushing Serial 1" value={this.state.bushing_serial6_id} errors={errors} name="bushing_serial6_id"/> </div> </div> <div className="row"> <div className="col-md-2"> <BushSerialSelectField source="bushing" label="Bushing Serial 7" value={this.state.bushing_serial7} errors={errors} name="bushing_serial7_id"/> </div> <div className="col-md-2"> <BushSerialSelectField source="bushing" label="Bushing Serial 8" value={this.state.bushing_serial8_id} errors={errors} name="bushing_serial8_id"/> </div> <div className="col-md-2"> <BushSerialSelectField source="bushing" label="Bushing Serial 9" value={this.state.bushing_serial9_id} errors={errors} name="bushing_serial9_id"/> </div> <div className="col-md-2"> <BushSerialSelectField source="bushing" label="Bushing Serial 10" value={this.state.bushing_serial10_id} errors={errors} name="bushing_serial10_id"/> </div> <div className="col-md-2"> <BushSerialSelectField source="bushing" label="Bushing Serial 11" value={this.state.bushing_serial11_id} errors={errors} name="bushing_serial11_id"/> </div> <div className="col-md-2"> <BushSerialSelectField source="bushing" label="Bushing Serial 12" value={this.state.bushing_serial12_id} errors={errors} name="bushing_serial12_id"/> </div> </div> */} <div className="row"> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Mva Forced 11" name="mvaforced11" value={this.state.mvaforced11} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Mva Forced 12" name="mvaforced12" value={this.state.mvaforced12} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Mva Forced 13" name="mvaforced13" value={this.state.mvaforced13} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Mva Forced 14" name="mvaforced14" value={this.state.mvaforced14} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Base Impedance 1" name="imp_base1" value={this.state.imp_base1} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Base Impedance 2" name="imp_base2" value={this.state.imp_base2} errors={errors} data-type="float"/> </div> </div> <div className="row"> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Mva Forced 21" name="mvaforced21" value={this.state.mvaforced21} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Mva Forced 22" name="mvaforced22" value={this.state.mvaforced22} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Mva Forced 23" name="mvaforced23" value={this.state.mvaforced23} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Mva Forced 24" name="mvaforced24" value={this.state.mvaforced24} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Base Impedance 3" name="impbasedmva3" value={this.state.impbasedmva3} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Base Impedance 4" name="impbasedmva4" value={this.state.impbasedmva4} errors={errors} data-type="float"/> </div> </div> <div className="row"> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Mva Actual" name="mvaactual" value={this.state.mvaactual} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Mvar Actual" name="mvaractual" value={this.state.mvaractual} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Reserve Mw" name="mwreserve" value={this.state.mwreserve} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Reserve Mva" name="mvarreserve" value={this.state.mvarreserve} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Ultime Mw" name="mwultime" value={this.state.mwultime} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Ultime Mvar" name="mvarultime" value={this.state.mvarultime} errors={errors} data-type="float"/> </div> </div> <div className="row"> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Ratio Tag 1" name="ratio_tag1" value={this.state.ratio_tag1} errors={errors} data-len="20"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Ratio Tag 2" name="ratio_tag2" value={this.state.ratio_tag2} errors={errors} data-len="20"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Ratio Tag 3" name="ratio_tag3" value={this.state.ratio_tag3} errors={errors} data-len="20"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Ratio Tag 4" name="ratio_tag4" value={this.state.ratio_tag4} errors={errors} data-len="20"/> </div> <div className="col-md-2"> <Checkbox name="static_shield1" checked={this.state.static_shield1} onChange={this.handleChange}><b>Static Shield 1</b></Checkbox> </div> <div className="col-md-2"> <Checkbox name="static_shield2" checked={this.state.static_shield2} onChange={this.handleChange}><b>Static Shield 2</b></Checkbox> </div> </div> <div className="row"> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Ratio Tag 5" name="ratio_tag5" value={this.state.ratio_tag5} errors={errors} data-len="20"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Ratio Tag 6" name="ratio_tag6" value={this.state.ratio_tag6} errors={errors} data-len="20"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Ratio Tag 7" name="ratio_tag7" value={this.state.ratio_tag7} errors={errors} data-len="20"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Ratio Tag 8" name="ratio_tag8" value={this.state.ratio_tag8} errors={errors} data-len="20"/> </div> <div className="col-md-2"> <Checkbox name="static_shield3" checked={this.state.static_shield3} onChange={this.handleChange}><b>Static Shield 3</b></Checkbox> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Static Shield 4" name="static_shield4" value={this.state.static_shield4} errors={errors} data-type="float"/> </div> </div> <div className="row"> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Bushing Neutral 1" name="bushing_neutral1" value={this.state.bushing_neutral1} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Bushing Neutral 2" name="bushing_neutral2" value={this.state.bushing_neutral2} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Bushing Neutral 3" name="bushing_neutral3" value={this.state.bushing_neutral3} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Bushing Neutral 4" name="bushing_neutral4" value={this.state.bushing_neutral4} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Windings" name="windings" value={this.state.windings} errors={errors} data-type="int"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Winding Metal 1" name="winding_metal1" value={this.state.winding_metal1} errors={errors} data-type="int"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Winding Metal 2" name="winding_metal2" value={this.state.winding_metal2} errors={errors} data-type="int"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Winding Metal 3" name="winding_metal3" value={this.state.winding_metal3} errors={errors} data-type="int"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Winding Metal 4" name="winding_metal4" value={this.state.winding_metal4} errors={errors} data-type="int"/> </div> </div> <div className="row"> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Primary Winding Connection" name="primary_winding_connection" value={this.state.primary_winding_connection} errors={errors} data-type="int"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Secondary Winding Connection" name="secondary_winding_connection" value={this.state.secondary_winding_connection} errors={errors} data-type="int"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Tertiary Winding Connection" name="tertiary_winding_connection" value={this.state.tertiary_winding_connection} errors={errors} data-type="int"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Quaternary Winding Connection" name="quaternary_winding_connection" value={this.state.quaternary_winding_connection} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Based Power" name="based_transformer_power" value={this.state.based_transformer_power} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <Checkbox name="autotransformer" checked={this.state.autotransformer} onChange={this.handleChange}><b>Autotransformer</b></Checkbox> </div> </div> <div className="row"> <div className="col-md-2"> <TextField onChange={this.handleChange} label="BIL 1" name="bil1" value={this.state.bil1} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="BIL 2" name="bil2" value={this.state.bil2} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Ltc 1" name="ltc1" value={this.state.ltc1} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Ltc 2" name="ltc2" value={this.state.ltc2} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="First Cooling Stage Power" name="first_cooling_stage_power" value={this.state.first_cooling_stage_power} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Second Cooling Stage Power" name="second_cooling_stage_power" value={this.state.second_cooling_stage_power} errors={errors} data-type="float"/> </div> </div> <div className="row"> <div className="col-md-2"> <TextField onChange={this.handleChange} label="BIL 3" name="bil3" value={this.state.bil3} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="BIL 4" name="bil4" value={this.state.bil4} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Ltc 3" name="ltc3" value={this.state.ltc3} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Third colling stage power" name="third_cooling_stage_power" value={this.state.third_cooling_stage_power} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Temperature Rise" name="temperature_rise" value={this.state.temperature_rise} errors={errors} data-type="int"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Cooling Rating" name="cooling_rating" value={this.state.cooling_rating} errors={errors} data-type="int"/> </div> </div> <div className="row"> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Primary Tension" name="primary_tension" value={this.state.primary_tension} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Secondary Tension" name="secondary_tension" value={this.state.secondary_tension} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Tertiary Tension" name="tertiary_tension" value={this.state.tertiary_tension} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Impedance 1" name="impedance1" value={this.state.impedance1} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Impedance 2" name="impedance2" value={this.state.impedance2} errors={errors} data-type="float"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Impedance 3" name="impedance3" value={this.state.impedance3} errors={errors} data-type="float"/> </div> </div> <div className="row"> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Formula Ratio 1" name="formula_ratio" value={this.state.formula_ratio} errors={errors} data-type="int"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Formula Ratio 2" name="formula_ratio2" value={this.state.formula_ratio2} errors={errors} data-type="int"/> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Formula Ratio 3" name="formula_ratio3" value={this.state.formula_ratio3} errors={errors} data-type="float"/> </div> <div className="col-md-2 "> <Checkbox name="sealed" checked={this.state.sealed} onChange={this.handleChange}><b>Sealed</b></Checkbox> </div> <div className="col-md-2"> <Checkbox name="welded_cover" checked={this.state.welded_cover} onChange={this.handleChange}><b>Welded Cover</b></Checkbox> </div> <div className="col-md-2"> <TextField onChange={this.handleChange} label="Impedance 4" name="impedance4" value={this.state.impedance4} errors={errors} data-type="float"/> </div> </div> </div> ) } }); export default TransformerParams;
node_modules/@expo/vector-icons/createIconSet.js
RahulDesai92/PHR
import React from 'react'; import { Text } from 'react-native'; import { Font } from 'expo'; import createIconSet from './vendor/react-native-vector-icons/lib/create-icon-set'; import createIconButtonComponent from './vendor/react-native-vector-icons/lib/icon-button'; export default function(glyphMap, fontName, expoAssetId) { const expoFontName = Font.style(fontName, { ignoreWarning: true, }).fontFamily; const font = { [fontName]: expoAssetId }; const RNVIconComponent = createIconSet(glyphMap, expoFontName); class Icon extends React.Component { static propTypes = RNVIconComponent.propTypes; static defaultProps = RNVIconComponent.defaultProps; state = { fontIsLoaded: Font.isLoaded(fontName), }; async componentWillMount() { this._mounted = true; if (!this.state.fontIsLoaded) { await Font.loadAsync(font); this._mounted && this.setState({ fontIsLoaded: true }); } } componentWillUnmount() { this._mounted = false; } setNativeProps(props) { if (this._icon) { this._icon.setNativeProps(props); } } render() { if (!this.state.fontIsLoaded) { return <Text />; } return ( <RNVIconComponent ref={view => { this._icon = view; }} {...this.props} /> ); } } Icon.Button = createIconButtonComponent(Icon); Icon.glyphMap = glyphMap; Icon.font = font; return Icon; }
src/components/Main.js
Royzx/gallery-by-react
require('normalize.css/normalize.css'); require('styles/App.scss'); import React from 'react'; import ReactDOM from 'react-dom'; //获取图片相关数据 var imageDatas = require('../data/imageDatas.json'); //利用自执行函数,将图片名信息转成图片URL路径信息 imageDatas = (function getImageURL(imageDataArr){ for(let i = 0,j=imageDataArr.length;i<j;i++){ let singleImageData = imageDataArr[i]; singleImageData.imageURL = require('../images/'+singleImageData.fileName); imageDataArr[i] = singleImageData; } return imageDataArr; })(imageDatas); /** * 取范围内的随机值 * @param {*} low * @param {*} high */ function getRangeRandom(low,high) { return Math.ceil(Math.random() * (high - low)) + low; } /** * 取0-30度角 */ function get30DegRandom() { return ((Math.random() > 0.5 ? '': '-') + Math.ceil(Math.random() * 30)); } /**控制按钮组件 */ class ControllerUnit extends React.Component { handleClick(e) { //如果点击的是当前正在选中态的按钮,则翻转你图片,否则将对应的图片居中 if (this.props.arrange.isCenter) { this.props.inverse(); } else { this.props.center(); } e.preventDefault(); e.stopPropagation(); } render() { var controllerUnitClassName = 'controller-unit'; //如果对应的是居中的图片,显示控制按钮居中态 if (this.props.arrange.isCenter) { controllerUnitClassName += ' is-center'; //如果对应的是翻转图片,显示控制按钮翻转态 if (this.props.arrange.inverse) { controllerUnitClassName += ' is-inverse'; } } return ( <span className={controllerUnitClassName} onClick={this.handleClick.bind(this)}></span> ); } } /**单个图片组件 */ class ImgFigure extends React.Component { handleClick(e) { if(this.props.arrange.isCenter) { this.props.inverse(); } else { this.props.center(); } e.stopPropagation(); e.preventDefault(); } render() { var styleObj = {}; //如果props属性中指定了这张图片的位置,则使用 if (this.props.arrange.pos) { styleObj = this.props.arrange.pos; } if(this.props.arrange.rotate) { (['Moz','ms','Webkit','']).forEach(function(value){ styleObj[value + 'Transform'] = 'rotate(' + this.props.arrange.rotate + 'deg)'; }.bind(this)); } if(this.props.arrange.isCenter) { styleObj.zIndex = 11; } var imgFigureClassName = 'img-figure'; imgFigureClassName += this.props.arrange.inverse ? ' is-inverse': ''; return( <figure className={imgFigureClassName} style={styleObj} onClick={this.handleClick.bind(this)}> <img src={this.props.data.imageURL} alt={this.props.data.title}/> <figcaption> <h2 className="img-title">{this.props.data.title}</h2> <div className='img-back' onClick={this.handleClick.bind(this)}> <p>{this.props.data.desc}</p> </div> </figcaption> </figure> ); } } class AppComponent extends React.Component { /** * 翻转图片 * @param {*} index 传入当前被执行inverse操作的图片信息数组的index值 * @return {function} 这是一个闭包函数,其中return中一个真正待被执行的函数 */ inverse(index) { return (function(){ var imgsArrangeArr = this.state.imgsArrangeArr; imgsArrangeArr[index].inverse = !imgsArrangeArr[index].inverse; this.setState({ imgsArrangeArr: imgsArrangeArr }); }.bind(this)); } /** * 利用arrange函数,居中对应index的图片 * @param {*} index 需要背景中的图片对应的图片信息数组的index值 * @return {Function} */ center(index) { return function() { this.rearrange(index); }.bind(this); } /** * 重新布局所有图片 * @param {*} centerIndex 指定居中排布哪个卡片 */ rearrange(centerIndex) { var imgsArrangeArr = this.state.imgsArrangeArr, //获取图片位置信息数组 Constant = this.Constant, //获取定位位置对象 centerPos = Constant.centerPos, //获取居中位置信息 hPosRange = Constant.hPosRange, //获取水平位置信息 h_leftSecX = hPosRange.leftSecX, //获取左侧X位置信息 h_rightSecX = hPosRange.rightSecX, //获取右侧X位置信息 h_y = hPosRange.h_y, //获取y位置信息 vPosRange = Constant.vPosRange, //获取顶部位置信息 v_x = vPosRange.v_x, //获取顶部X位置信息 v_y = vPosRange.v_y; //获取顶部Y位置信息 //获取居中图片index并居中处理 var imgsArrangeArrCenter = imgsArrangeArr.splice(centerIndex,1); imgsArrangeArrCenter = { pos: centerPos, rotate: 0, isCenter: true }; //获取顶部图片index并处理 var topImgNum= Math.ceil(Math.random() * 2), topIndex = 0, imgsArrangeArrTop = []; if(topImgNum) { topIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum + 1)); imgsArrangeArrTop = imgsArrangeArr.splice(topIndex,topImgNum); imgsArrangeArrTop.forEach(function(value,index) { imgsArrangeArrTop[index] = { pos: { left: getRangeRandom(v_x[0], v_x[1]), top: getRangeRandom(v_y[0], v_y[1]) }, rotate: get30DegRandom() }; }); } //获取水平方向上的图片信息并处理 var k = Math.ceil(imgsArrangeArr.length / 2); for(var i = 0; i < imgsArrangeArr.length; i++) { if(i < k) { imgsArrangeArr[i] = { pos: { left: getRangeRandom(h_leftSecX[0], h_leftSecX[1]), top: getRangeRandom(h_y[0], h_y[1]) }, rotate: get30DegRandom(), isCenter:false } } else { imgsArrangeArr[i] = { pos: { left: getRangeRandom(h_rightSecX[0], h_rightSecX[1]), top: getRangeRandom(h_y[0], h_y[1]) }, rotate: get30DegRandom(), isCenter:false } } } //将去除的数组元素修改之后放回去 if(imgsArrangeArr && imgsArrangeArrTop) { for(var i = topImgNum-1;i >= 0 ; i--) { imgsArrangeArr.splice(topIndex,0,imgsArrangeArrTop[i]); } } //中间图片 imgsArrangeArr.splice(centerIndex,0,imgsArrangeArrCenter); this.setState({ imgsArrangeArr: imgsArrangeArr }) } constructor(props) { super(props); this.state = {imgsArrangeArr:[]}; /*** 位置范围常量*/ this.Constant = { centerPos:{ left:0, top:0 }, hPosRange:{ //水平方向取值范围 leftSecX:[0,0], rightSecX:[0,0], h_y:[0,0] }, vPosRange:{ //垂直方向取值范围 v_x:[0,0], v_y:[0,0] } }; } componentDidMount(){ /**舞台的宽高以及半宽和半高 */ var stageDOM = ReactDOM.findDOMNode(this.refs.stage), stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW = Math.ceil(stageW / 2), halfStageH = Math.ceil(stageH / 2); /**图片的宽高以及半宽和半高 */ var imgDOM = ReactDOM.findDOMNode(this.refs.imgFigure0), imgW = imgDOM.scrollWidth, imgH = imgDOM.scrollHeight, halfImgW = Math.ceil(imgW / 2), halfImgH = Math.ceil(imgH / 2); this.Constant.centerPos = { left:halfStageW - halfImgW, top:halfStageH - halfImgH }; /**水平方向上左右两侧图片的范围start */ /** 左*/ this.Constant.hPosRange.leftSecX[0] = -halfImgW; this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3; /**右 */ this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW; this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW; /**垂直 */ this.Constant.hPosRange.h_y[0] = - halfImgH; this.Constant.hPosRange.h_y[1] = stageH - halfImgH; /**水平方向上左右两侧图片的范围start */ /**垂直方向上顶部图片范围start */ this.Constant.vPosRange.v_x[0] = halfStageW - imgW; this.Constant.vPosRange.v_x[1] = halfStageW; this.Constant.vPosRange.v_y[0] = -halfImgH; this.Constant.vPosRange.v_y[1] = halfStageH - halfImgH * 3; /**垂直方向上顶部图片范围end */ /**默认居中第一张图片 */ this.rearrange(0); } render() { var controllerUnits = [], ImgFigures = []; imageDatas.map(function(value,index) { if(!this.state.imgsArrangeArr[index]) { this.state.imgsArrangeArr[index] = { pos: { left:0, top:0 }, rotate: 0, inverse:false, isCenter:false } } ImgFigures.push(<ImgFigure data={value} ref={'imgFigure'+index} arrange={this.state.imgsArrangeArr[index]} key={index} inverse={this.inverse(index)} center={this.center(index)}/>); controllerUnits.push(<ControllerUnit arrange={this.state.imgsArrangeArr[index]} key={index} inverse={this.inverse(index)} center={this.center(index)}/>) }.bind(this)); return ( <section className="stage" ref="stage"> <section className="img-sec"> {ImgFigures} </section> <nav className="controller-nav"> {controllerUnits} </nav> </section> ); } } AppComponent.defaultProps = { }; export default AppComponent;
src/svg-icons/navigation/arrow-drop-down-circle.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationArrowDropDownCircle = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 12l-4-4h8l-4 4z"/> </SvgIcon> ); NavigationArrowDropDownCircle = pure(NavigationArrowDropDownCircle); NavigationArrowDropDownCircle.displayName = 'NavigationArrowDropDownCircle'; NavigationArrowDropDownCircle.muiName = 'SvgIcon'; export default NavigationArrowDropDownCircle;
fixtures/dom/src/components/fixtures/input-change-events/RadioGroupFixture.js
brigand/react
import React from 'react'; import Fixture from '../../Fixture'; class RadioGroupFixture extends React.Component { constructor(props, context) { super(props, context); this.state = { changeCount: 0, }; } handleChange = () => { this.setState(({changeCount}) => { return { changeCount: changeCount + 1, }; }); }; handleReset = () => { this.setState({ changeCount: 0, }); }; render() { const {changeCount} = this.state; const color = changeCount === 2 ? 'green' : 'red'; return ( <Fixture> <label> <input defaultChecked name="foo" type="radio" onChange={this.handleChange} /> Radio 1 </label> <label> <input name="foo" type="radio" onChange={this.handleChange} /> Radio 2 </label> {' '} <p style={{color}}> <code>onChange</code>{' calls: '}<strong>{changeCount}</strong> </p> <button onClick={this.handleReset}>Reset count</button> </Fixture> ); } } export default RadioGroupFixture;
fields/types/geopoint/GeoPointColumn.js
Adam14Four/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var GeoPointColumn = React.createClass({ displayName: 'GeoPointColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; if (!value || !value.length) return null; const formattedValue = `${value[1]}, ${value[0]}`; const formattedTitle = `Lat: ${value[1]} Lng: ${value[0]}`; return ( <ItemsTableValue title={formattedTitle} field={this.props.col.type}> {formattedValue} </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = GeoPointColumn;
src/Interpolate.js
mengmenglv/react-bootstrap
// https://www.npmjs.org/package/react-interpolate-component // TODO: Drop this in favor of es6 string interpolation import React from 'react'; import ValidComponentChildren from './utils/ValidComponentChildren'; const REGEXP = /\%\((.+?)\)s/; const Interpolate = React.createClass({ displayName: 'Interpolate', propTypes: { component: React.PropTypes.node, format: React.PropTypes.string, unsafe: React.PropTypes.bool }, getDefaultProps() { return { component: 'span', unsafe: false }; }, render() { let format = (ValidComponentChildren.hasValidComponent(this.props.children) || (typeof this.props.children === 'string')) ? this.props.children : this.props.format; let parent = this.props.component; let unsafe = this.props.unsafe === true; let props = {...this.props}; delete props.children; delete props.format; delete props.component; delete props.unsafe; if (unsafe) { let content = format.split(REGEXP).reduce(function(memo, match, index) { let html; if (index % 2 === 0) { html = match; } else { html = props[match]; delete props[match]; } if (React.isValidElement(html)) { throw new Error('cannot interpolate a React component into unsafe text'); } memo += html; return memo; }, ''); props.dangerouslySetInnerHTML = { __html: content }; return React.createElement(parent, props); } else { let kids = format.split(REGEXP).reduce(function(memo, match, index) { let child; if (index % 2 === 0) { if (match.length === 0) { return memo; } child = match; } else { child = props[match]; delete props[match]; } memo.push(child); return memo; }, []); return React.createElement(parent, props, kids); } } }); export default Interpolate;
docs/src/sections/OverlaySection.js
Terminux/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function OverlaySection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="custom-overlays">Custom overlays</Anchor> <small>Overlay</small> </h2> <p> The <code>OverlayTrigger</code> component is great for most use cases, but as a higher level abstraction it can lack the flexibility needed to build more nuanced or custom behaviors into your Overlay components. For these cases it can be helpful to forgo the trigger and use the <code>Overlay</code> component directly. </p> <ReactPlayground codeText={Samples.Overlay}/> <h4><Anchor id="custom-overlays-overlay">Use Overlay instead of Tooltip and Popover</Anchor></h4> <p> You don't need to use the provided <code>Tooltip</code> or <code>Popover</code> components. Creating custom overlays is as easy as wrapping some markup in an <code>Overlay</code> component </p> <ReactPlayground codeText={Samples.OverlayCustom} /> <h3><Anchor id="custom-overlays-props">Props</Anchor></h3> <PropTable component="Overlay"/> </div> ); }
examples/todomvc/index.js
STRML/redux
import React from 'react'; import App from './containers/App'; import 'todomvc-app-css/index.css'; React.render( <App />, document.getElementById('root') );
src/routes.js
NathanBWaters/website
import React from 'react'; import {IndexRoute, Route} from 'react-router'; import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth'; import { TheRunners, ProjectDashboard, Outfitr, GoAlgo, JumpstartGUI, Website } from 'components'; import { App, Chat, Home, Widgets, About, Login, LoginSuccess, Survey, NotFound, ProjectsMain, } from 'containers'; export default (store) => { const requireLogin = (nextState, replace, cb) => { function checkAuth() { const { auth: { user }} = store.getState(); if (!user) { // oops, not logged in, so can't be here! replace('/'); } cb(); } if (!isAuthLoaded(store.getState())) { store.dispatch(loadAuth()).then(checkAuth); } else { checkAuth(); } }; /** * Please keep routes in alphabetical order */ return ( <Route path="/" component={App}> { /* Home (main) route */ } <IndexRoute component={Home}/> { /* Routes requiring login */ } <Route onEnter={requireLogin}> <Route path="chat" component={Chat}/> <Route path="loginSuccess" component={LoginSuccess}/> </Route> { /* Routes */ } <Route path="about" component={About}/> <Route path="login" component={Login}/> <Route path="projects" component={ProjectsMain} > <IndexRoute component={ProjectDashboard}/> <Route path="the_runners" component={TheRunners}/> <Route path="outfitr" component={Outfitr}/> <Route path="go_algo" component={GoAlgo}/> <Route path="jumpstart_gui" component={JumpstartGUI}/> <Route path="personal_website" component={Website}/> </Route> <Route path="survey" component={Survey}/> <Route path="widgets" component={Widgets}/> { /* Catch all route */ } <Route path="*" component={NotFound} status={404} /> </Route> ); };
app/renderInBrowser.js
theseushu/runcai
import React from 'react'; import ReactDOM from 'react-dom'; import { match, applyRouterMiddleware, Router } from 'react-router'; import { useScroll } from 'react-router-scroll'; import AppRoot from 'containers/AppRoot'; import FullScreenGallery from 'modules/fullScreenGallery'; import MapDialog from 'modules/mapDialog'; import { actions as mapActions } from 'api/map'; import { currentUserSelector } from 'modules/data/ducks/selectors'; import { actions as profileActions } from 'api/profile'; export default function renderInBrowser({ messages, store, routes, history, api }) { match({ history, routes }, (error, redirectLocation, renderProps) => { ReactDOM.render( <AppRoot store={store} messages={messages}> <Router {...renderProps} render={ // Scroll to top when going to a new page, imitating default browser behaviour applyRouterMiddleware(useScroll()) } /> </AppRoot>, document.getElementById('app'), () => { const ssStyles = document.getElementById('server-side-styles'); ssStyles.parentNode.removeChild(ssStyles); }, ); const tokenExists = api.tokenExists(); // token exists means there's sessionToken in cookies. // if currentUser is not null,(which means store state is populated from ssr) we do nothing // otherwise, fetch user's profile if (tokenExists) { const currentUser = currentUserSelector(store.getState()); if (!currentUser) { store.dispatch(profileActions.fetch()); } } store.dispatch(mapActions.getCurrentLocation()); }); if (process.env.browser) { // todo switch to standard client detection const galleryEl = document.createElement('div'); galleryEl.setAttribute('id', '_fullScreenGallery_'); document.body.appendChild(galleryEl); ReactDOM.render( <AppRoot store={store} messages={messages}> <FullScreenGallery /> </AppRoot>, galleryEl ); const mapDialogEl = document.createElement('div'); mapDialogEl.setAttribute('id', '_map_dialog_'); document.body.appendChild(mapDialogEl); ReactDOM.render( <AppRoot store={store} messages={messages}> <MapDialog /> </AppRoot>, mapDialogEl ); if (process.env.NODE_ENV !== 'production') { if (localStorage) { localStorage.debug = 'funongweb*,funongbackend*,funongcommon*'; } if (!document.getElementById('_dev_tools_')) { System.import('./DevTools').then((DevToolsModule) => { const DevTools = DevToolsModule.default; const devToolsEl = document.createElement('div'); devToolsEl.setAttribute('id', '_dev_tools_'); document.body.appendChild(devToolsEl); ReactDOM.render( <DevTools store={store} /> , devToolsEl ); }); } } } }
packages/cf-component-progress/src/Progress.js
mdno/mdno.github.io
import React from 'react'; import PropTypes from 'prop-types'; import Link from 'cf-component-link'; import { createComponent } from 'cf-style-container'; import { clearFix } from 'polished'; const styles = () => ({ position: 'relative' }); const Bar = createComponent( ({ theme }) => ({ display: 'block', width: '100%', appearance: 'none', '&::-webkit-progress-bar': { backgroundColor: theme.bodyBackground, color: theme.bodyBackground }, '&::-webkit-progress-value': { backgroundColor: theme.color.marine, color: theme.color.marine, transition: 'width 500ms ease' }, /* Mozilla uses progress-bar as the value */ '&::-moz-progress-bar': { backgroundColor: theme.color.marine, color: theme.color.marine } }), 'progress', ['max', 'value'] ); const Items = createComponent( () => ({ listStyle: 'none', ...clearFix(), margin: 0, padding: 0 }), 'ol' ); const Item = createComponent( ({ theme, width, disabled, active }) => { let color = theme.colorGray; if (disabled) { color = theme.colorGrayLight; } else if (active) { color = theme.color.marine; } return { width: 'auto', float: 'none', height: 'auto', padding: 0, paddingTop: '7.5px', color, fontSize: '0.86667em', textAlign: 'center', cursor: disabled ? 'default' : 'pointer', display: active ? 'list-item' : 'none', '&::before': { content: 'none' }, tablet: { width, float: 'left', display: 'list-item' }, '& > .cf-link': { display: 'block', color: 'inherit', cursor: 'pointer' } }; }, 'li', ['key', 'width', 'disabled', 'active'] ); class Progress extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(step) { if (step.id !== this.props.active) { this.props.onChange(step.id); } } render() { const { className, steps, active } = this.props; const max = steps.length; const itemWidth = (1 / max * 100).toFixed(4) + '%'; let value; const items = steps.map((step, index) => { const isActive = step.id === active; if (isActive) { value = index + 1; } return ( <Item key={step.id} width={itemWidth} disabled={step.disabled} active={isActive} > <Link onClick={this.handleClick.bind(null, step)} disabled={step.disabled} > {step.label} </Link> </Item> ); }); return ( <div className={className}> <Bar max={max} value={value} /> <Items> {items} </Items> </div> ); } } Progress.propTypes = { active: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, steps: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string.isRequired, label: PropTypes.string.isRequired, disabled: PropTypes.bool.isRequired }) ).isRequired, className: PropTypes.string }; Progress.defaultProps = { steps: [] }; export default createComponent(styles, Progress);
src/components/theme-legacy/form/instructions/target-state.js
MoveOnOrg/mop-frontend
import React from 'react' const TargetState = () => ( <div> <h4>Targeting Your Governor or State Legislature</h4> <p>If you choose <strong>The entire State House</strong>, then your petition signers will be asked to sign a petition addressed to their individual representative in the state house of representatives.</p> <p>If you choose <strong>The entire State Senate</strong>, then your petition signers will be asked to sign a petition addressed to their individual representative in the state senate.</p> <p>If you choose <strong>Governor of State</strong>, your petition signatures will be addressed to your state&rsquo;s governor.</p> <p>If your petition should be addressed to <strong>a specific legislator</strong>, type his or her name in the text area. Be sure to check the spelling and use the individual&rsquo;s proper title.</p> </div> ) export default TargetState
src/screens/search/components/DestinationSearch/DestinationSearch.js
vio-lets/Larkyo-Client
import React from 'react'; // import './PeopleSearch.css'; export default class DestinationSearch extends React.Component { constructor() { super(); this.state = {} } render() { return( <div className="destinationSearchContainer"> <h2>Destination search is coming soon</h2> </div> ) } }