path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
client/index.js
jmeas/moolah
import 'babel-polyfill'; import React from 'react'; import {render} from 'react-dom'; import {Provider} from 'react-redux'; import { Router, Route, IndexRoute, browserHistory, Redirect, applyRouterMiddleware } from 'react-router'; import {useScroll} from 'react-router-scroll'; import FirstChild from './common/components/first-child'; import Categories from './categories/components/content'; import Account from './account/components/account'; import Transactions from './transactions/components/content'; import Layout from './common/components/layout'; import NotFound from './common/components/not-found'; import LandingPage from './meta/components/landing-page'; import About from './meta/components/about'; import Contact from './meta/components/contact'; import Privacy from './meta/components/privacy'; import Terms from './meta/components/terms'; import SignIn from './meta/components/sign-in'; import store from './state/store'; import generateAuthCheck from './common/utils/auth-check'; import {getYearMonthStringFromDate} from './transactions/utils/format-date'; if (process.NODE_ENV !== 'production') { window.store = store; } const authCheck = generateAuthCheck(store); function onIndexEnter(nextState, redirect) { if (authCheck.mustBeLoggedOut(nextState, redirect, false)) { return; } redirect('/transactions'); } // When we enter `/transactions/this-month`, we dynamically redirect them to a // URL with the current month and year in it. This way, the URL in the nav bar // can remain constant, even if the user keeps the app open as the dates change. function onTransactionsEnter(nextState, redirect) { if (!authCheck.mustBeLoggedIn(nextState, redirect)) { return; } const dateString = getYearMonthStringFromDate(new Date()); redirect(`/transactions/${dateString}`); } render(( <Provider store={store}> <Router history={browserHistory} render={applyRouterMiddleware(useScroll())}> <Route path="/" component={Layout}> <IndexRoute component={LandingPage} onEnter={onIndexEnter}/> <Route path="/transactions" component={FirstChild}> <IndexRoute onEnter={onTransactionsEnter}/> <Route path=":transactionDate" component={Transactions} onEnter={authCheck.mustBeLoggedIn}/> </Route> <Route path="/categories" component={Categories} onEnter={authCheck.mustBeLoggedIn}/> <Route path="/account" component={Account} onEnter={authCheck.mustBeLoggedIn}/> <Route path="/contact" component={Contact}/> <Route path="/privacy" component={Privacy}/> <Route path="/about" component={About}/> <Route path="/terms" component={Terms}/> <Route path="/login" component={SignIn} onEnter={authCheck.mustBeLoggedOut}/> <Route path="/join" component={SignIn} onEnter={authCheck.mustBeLoggedOut}/> <Redirect from="/dashboard" to="/"/> <Route path="*" component={NotFound}/> </Route> </Router> </Provider> ), document.querySelector('.app-container'));
examples/universal/client.js
dmin/redux
import 'babel-core/polyfill'; import React from 'react'; import configureStore from './store/configureStore'; import { Provider } from 'react-redux'; import App from './containers/App'; const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState); const rootElement = document.getElementById('app'); React.render( <Provider store={store}> {() => <App/>} </Provider>, rootElement );
src/App.js
jeetiss/madskillz
import React from 'react' import { connect } from 'react-redux' import { splitTime, exp } from './utils/time' import { injectGlobal } from 'styled-components' import { Cifer, Blat, Cont } from './components' injectGlobal` body { margin: 0; background-color: white; font-family: 'Roboto', sans-serif; } ` function Main ({ time }) { const vals = splitTime(time.now - time.from) const labels = exp(vals) return ( <Cont> <Cifer> { Object.keys(vals).map(key => <Blat key={key} value={vals[key]} label={labels[key]} /> )} </Cifer> </Cont> ) } const CMain = connect(store => store)(Main) export default CMain
client/modules/App/components/Landing/Button.js
aksm/refactored-palm-tree
import React from 'react'; import styles from '../../Landing.css'; import {browserHistory} from 'react-router'; class Button extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(route) { // e.preventDefault(); browserHistory.push(route); } render() { return ( <div id={styles.buttonfan}> <button onClick={() => this.handleClick('/viewer')} className={styles.btnDesign}>View A Show</button> <button onClick={() => this.handleClick('/talent')} className={styles.btnDesign}>Create A Show</button> <button onClick={() => this.handleClick('/about')} className={styles.btnDesign}>About</button> </div> ) } } module.exports = Button;
src/forms/output/GraphHolder.js
shp54/cliff-effects
import React, { Component } from 'react'; // CUSTOM COMPONENTS import { GraphTimeButtons } from '../../components/GraphTimeButtons'; class GraphHolder extends Component { constructor (props) { super(props); this.state = { activeID: 'Yearly' }; } onClick = (evnt) => { var id = evnt.target.id; this.setState({ activeID: id }); }; render () { const { activeID } = this.state, { Graph, client } = this.props, { current } = client, activePrograms = []; // The ids later used to access all program-specific data and functions // Only active programs are added if (current.hasSection8) { activePrograms.push('section8'); } if (current.hasSnap) { activePrograms.push('snap'); } return ( <div className='graph-holder'> <Graph className='client-graph' client={ client } timescale={ activeID } activePrograms={ activePrograms } /> <GraphTimeButtons activeID={ activeID } onClick={ this.onClick } /> </div> ); }; // End render() }; // End <GraphHolder> export { GraphHolder };
src/components/Cook/Cook.js
joyvuu-dave/comeals-ui-react
// rendered by Cooks import React from 'react' import classes from './Cook.scss' // Schema import type { ResidentsSchema } from '../../redux/modules/Residents' import type { BillSchema } from '../../redux/modules/bill' type Props = { ui: { select_disabled: boolean, input_disabled: boolean, error_message: { '1': string, '2': string, '3': string } }, bill: BillSchema, residents: ResidentsSchema, num: number, updateCook: Function, updateCost: Function }; export class Cook extends React.Component<void, Props, void> { constructor () { super() this.handleSelectChange = this.handleSelectChange.bind(this) this.handleInputChange = this.handleInputChange.bind(this) } handleSelectChange (e) { this.props.updateCook({resident_id: Number(e.target.value)}) if (Number(e.target.value) === -1) { this.props.updateCost({amount: ''}) } } handleInputChange (e) { this.props.updateCost({amount: e.target.value}) } renderOptions () { return this.props.residents.map((r) => <option key={r.id} value={r.id}>{r.name}</option> ) } render () { return ( <section> <select className={classes['cook-select']} disabled={this.props.ui.select_disabled} value={this.props.bill ? this.props.bill.resident_id : -1} onChange={this.handleSelectChange}> <option key={this.props.num * -10} value={-1}>{`Cook ${this.props.num}`}</option> {this.renderOptions()} </select> $<input className={classes['cook-input']} disabled={this.props.ui.input_disabled} type='string' placeholder='food cost' value={this.props.bill ? this.props.bill.amount : ''} onChange={this.handleInputChange} /> {' '} <span className={classes.alert}>{this.props.ui.error_message[this.props.num]}</span> </section> ) } } export default Cook
app/client/src/routes/manageCampaign/index.js
uprisecampaigns/uprise-app
import React from 'react'; import ManageCampaign from 'scenes/ManageCampaign'; import Layout from 'components/Layout'; import organizeCampaignPaths from 'routes/organizeCampaignPaths'; const path = organizeCampaignPaths({ path: '/organize/:slug', component: campaign => ( <Layout> <ManageCampaign campaignSlug={campaign.slug} /> </Layout> ), }); export default path;
src/icons/LandscapeIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class LandscapeIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M28 12l-7.5 10 5.7 7.6L23 32c-3.38-4.5-9-12-9-12L2 36h44L28 12z"/></svg>;} };
src/client.js
EmilNordling/poesk
import React from 'react' import ReactDom from 'react-dom' import { AppContainer } from 'react-hot-loader' import OfflinePluginRuntime from 'offline-plugin/runtime' import App from './components/App' import './manifest.json' import './assets/icon.png' import './assets/icon-192.png' import './assets/icon-512.png' const render = (Component) => { ReactDom.render( <AppContainer> <Component /> </AppContainer>, document.getElementById('app'), ) } render(App) // Reload react hot loader if (module.hot) { module.hot.accept('./components/App', () => { render(App) }) } // Install Service Worker if (process.env.NODE_ENV === 'production') { OfflinePluginRuntime.install() }
components/plugins/snack-embed.js
ccheever/expo-docs
import React from 'react' export default class SnackEmbed extends React.Component { componentDidMount() { var script = document.getElementById('snack') // inject script if it hasn't been loaded by a previous page if (!script) { script = document.createElement('script') script.src = 'https://snack.expo.io/embed.js' script.async = true script.id = 'snack' document.body.appendChild(script) script.addEventListener('load', () => { window.ExpoSnack.initialize() }) } if (window.ExpoSnack) { window.ExpoSnack.initialize() } } render() { // TODO: Handle `data-snack-sdk-version` somehow // maybe using `context`? // get snack data from snack id or from inline code var embedProps if (this.props.snackId) { embedProps = { 'data-snack-id': this.props.snackId } } else { let code = React.Children.toArray(this.props.children).join('').trim() embedProps = { 'data-snack-code': code } if (this.props.hasOwnProperty('name')) { embedProps['data-snack-name'] = this.props.name } if (this.props.hasOwnProperty('description')) { embedProps['data-snack-description'] = this.props.description } } // fill in default options for snack styling if (this.props.hasOwnProperty('platform')) { embedProps['data-snack-platform'] = this.props.platform } else { embedProps['data-snack-platform'] = 'ios' } if (this.props.hasOwnProperty('preview')) { embedProps['data-snack-preview'] = this.props.preview } else { embedProps['data-snack-preview'] = false } if (this.props.hasOwnProperty('theme')) { embedProps['data-snack-theme'] = this.props.theme } else { embedProps['data-snack-theme'] = 'light' } var embedStyle = {} if (this.props.hasOwnProperty('style')) { embedStyle = this.props.style } return ( <div {...embedProps} style={{ overflow: 'hidden', background: '#fafafa', borderWidth: 1, borderStyle: 'solid', height: 505, width: '100%', borderRadius: 4, borderColor: 'rgba(0,0,0,.16)', ...embedStyle }} /> ) } }
BuyDemo/Component/Shop/ZPShop.js
HAPENLY/ReactNative-Source-code-Demo
/** * Created by zhaopengsong on 2016/12/19. */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Platform, TouchableOpacity, Image, WebView } from 'react-native'; var Shop = React.createClass({ getInitialState(){ return{ detailUrl: 'http://i.meituan.com/topic/mingdian?ci=1&f=iphone&msid=48E2B810-805D-4821-9CDD-D5C9E01BC98A2015-07-02-16-25124&token=p19ukJltGhla4y5Jryb1jgCdKjsAAAAAsgAAADHFD3UYGxaY2FlFPQXQj2wCyCrhhn7VVB-KpG_U3-clHlvsLM8JRrnZK35y8UU3DQ&userid=10086&utm_campaign=AgroupBgroupD100Fab_chunceshishuju__a__a___b1junglehomepagecatesort__b__leftflow___ab_gxhceshi__nostrategy__leftflow___ab_gxhceshi0202__b__a___ab_pindaochangsha__a__leftflow___ab_xinkeceshi__b__leftflow___ab_gxtest__gd__leftflow___ab_waimaiwending__a__a___ab_gxh_82__nostrategy__leftflow___i_group_5_2_deallist_poitype__d__d___ab_b_food_57_purepoilist_extinfo__a__a___ab_pindaoshenyang__a__leftflow___ab_pindaoquxincelue0630__b__b1___a20141120nanning__m1__leftflow___ab_i_group_5_3_poidetaildeallist__a__b___ab_waimaizhanshi__b__b1___ab_i_group_5_5_onsite__b__b___ab_i_group_5_6_searchkuang__a__leftflowGhomepage_bargainmiddle_30311731&utm_content=4B8C0B46F5B0527D55EA292904FD7E12E48FB7BEA8DF50BFE7828AF7F20BB08D&utm_medium=iphone&utm_source=AppStore&utm_term=5.7&uuid=4B8C0B46F5B0527D55EA292904FD7E12E48FB7BEA8DF50BFE7828AF7F20BB08D&version_name=5.7&lat=23.12005&lng=113.3076' } }, render() { // alert(this.props.url); return ( <View style={styles.container}> {/*导航*/} {this.renderNavBar()} <WebView automaticallyAdjustContentInsets={true} source={{uri: this.state.detailUrl}} javaScriptEnabled={true} domStorageEnabled={true} decelerationRate="normal" startInLoadingState={true} /> </View> ); }, // 导航条 renderNavBar(){ return( <View style={styles.navOutViewStyle}> <TouchableOpacity onPress={()=>{this.props.navigator.pop()}} style={styles.leftViewStyle}> <Image source={{uri: 'icon_shop_local'}} style={styles.navImageStyle}/> </TouchableOpacity> <Text style={{color:'white', fontSize:16, fontWeight:'bold'}}>商家</Text> <TouchableOpacity onPress={()=>{alert('点了!')}} style={styles.rightViewStyle}> <Image source={{uri: 'icon_shop_search'}} style={styles.navImageStyle}/> </TouchableOpacity> </View> ) } }); const styles = StyleSheet.create({ container: { flex:1 }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, navImageStyle:{ width:Platform.OS == 'ios' ? 28: 24, height:Platform.OS == 'ios' ? 28: 24, }, leftViewStyle:{ // 绝对定位 position:'absolute', left:10, bottom:Platform.OS == 'ios' ? 15:13 }, rightViewStyle:{ // 绝对定位 position:'absolute', right:10, bottom:Platform.OS == 'ios' ? 15:13 }, navOutViewStyle:{ height: Platform.OS == 'ios' ? 64 : 44, backgroundColor:'rgba(255,96,0,1.0)', // 设置主轴的方向 flexDirection:'row', // 垂直居中 ---> 设置侧轴的对齐方式 alignItems:'center', // 主轴方向居中 justifyContent:'center' }, }); // 输出组件类 module.exports = Shop;
src/components/Transaction/Filter/AppliedFilters.js
ayastreb/money-tracker
import React from 'react'; import PropTypes from 'prop-types'; import { Label } from 'semantic-ui-react'; class AppliedFilters extends React.Component { removeAppliedAccount = accountId => () => { this.props.applyFilters({ accounts: this.props.appliedAccounts.filter(acc => acc !== accountId), tags: this.props.appliedTags }); }; removeAppliedTag = tag => () => { this.props.applyFilters({ accounts: this.props.appliedAccounts, tags: this.props.appliedTags.filter(t => t !== tag) }); }; render() { if ( this.props.appliedAccounts.length === 0 && this.props.appliedTags.length === 0 ) { return null; } return ( <div className="transactions-filters-applied"> {this.props.appliedAccounts.map(accountId => ( <Label key={accountId} content={this.props.accountNameMap[accountId]} icon="credit card" onRemove={this.removeAppliedAccount(accountId)} /> ))} {this.props.appliedTags.map(tag => ( <Label key={tag} content={tag} icon="tag" onRemove={this.removeAppliedTag(tag)} /> ))} </div> ); } } AppliedFilters.propTypes = { appliedTags: PropTypes.arrayOf(PropTypes.string), appliedAccounts: PropTypes.arrayOf(PropTypes.string), accountNameMap: PropTypes.object, applyFilters: PropTypes.func }; export default AppliedFilters;
modules/RouterContextMixin.js
apoco/react-router
import React from 'react'; import invariant from 'invariant'; import { stripLeadingSlashes, stringifyQuery } from './URLUtils'; var { func, object } = React.PropTypes; function pathnameIsActive(pathname, activePathname) { if (stripLeadingSlashes(activePathname).indexOf(stripLeadingSlashes(pathname)) === 0) return true; // This quick comparison satisfies most use cases. // TODO: Implement a more stringent comparison that checks // to see if the pathname matches any routes (and params) // in the currently active branch. return false; } function queryIsActive(query, activeQuery) { if (activeQuery == null) return query == null; if (query == null) return true; for (var p in query) if (query.hasOwnProperty(p) && String(query[p]) !== String(activeQuery[p])) return false; return true; } var RouterContextMixin = { propTypes: { stringifyQuery: func.isRequired }, getDefaultProps() { return { stringifyQuery }; }, childContextTypes: { router: object.isRequired }, getChildContext() { return { router: this }; }, /** * Returns a full URL path from the given pathname and query. */ makePath(pathname, query) { if (query) { if (typeof query !== 'string') query = this.props.stringifyQuery(query); if (query !== '') return pathname + '?' + query; } return pathname; }, /** * Returns a string that may safely be used to link to the given * pathname and query. */ makeHref(pathname, query) { var path = this.makePath(pathname, query); var { history } = this.props; if (history && history.makeHref) return history.makeHref(path); return path; }, /** * Pushes a new Location onto the history stack. */ transitionTo(pathname, query, state=null) { var { history } = this.props; invariant( history, 'Router#transitionTo is client-side only (needs history)' ); history.pushState(state, this.makePath(pathname, query)); }, /** * Replaces the current Location on the history stack. */ replaceWith(pathname, query, state=null) { var { history } = this.props; invariant( history, 'Router#replaceWith is client-side only (needs history)' ); history.replaceState(state, this.makePath(pathname, query)); }, /** * Navigates forward/backward n entries in the history stack. */ go(n) { var { history } = this.props; invariant( history, 'Router#go is client-side only (needs history)' ); history.go(n); }, /** * Navigates back one entry in the history stack. This is identical to * the user clicking the browser's back button. */ goBack() { this.go(-1); }, /** * Navigates forward one entry in the history stack. This is identical to * the user clicking the browser's forward button. */ goForward() { this.go(1); }, /** * Returns true if a <Link> to the given pathname/query combination is * currently active. */ isActive(pathname, query) { var { location } = this.state; if (location == null) return false; return pathnameIsActive(pathname, location.pathname) && queryIsActive(query, location.query); } }; export default RouterContextMixin;
src/About.js
hryanjones/kyakarun
import React from 'react'; const About = () => ( <div> <ul> <li> <a href='https://github.com/hryanjones/kyakarun/issues'>Report issues</a> </li> <li> Send feedback via <a href='https://twitter.com/hryanjones'>twitter</a> or <a href='mailto://hryanjones@gmail.com'>email</a> </li> <li> <a href='https://github.com/hryanjones/kyakarun'>Code</a> </li> </ul> <hr/> <h3>What is this?</h3> <p> <em>Kya Karun</em> is a simple web-app to help you decide what to do. You enter a number of activities and the amount of time they're good for, then you tell the app how much time you have and it'll suggest an activity randomly. </p> <h3>Where is my data stored?</h3> <p> Currently, this simple app stores everything in <a href='https://en.wikipedia.org/wiki/Web_storage#localStorage'>browser local storage</a>. </p> <h3>Why?</h3> <p> Every time I pulled out my phone I would waste time on Twitter, which wouldn't make me happy. In the vein of <a href='http://www.timewellspent.io/'>time well spent</a> I made this app to help me make better decisions with my time, steering me towards activities like studying Hindi, meditating, exercising, or reading a book, and ideally to a more fulfilled life. </p> <h3>Why is it called <em>Kya Karun</em>?</h3> <p> <em>Kya Karun</em> means "What should I do?" in Hindi. </p> </div> ); export default About;
src/index.js
shojil/bifapp
/** * Index - this is where everything * starts - but offloads to app.js * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ /* global __DEV__ */ import React from 'react'; import { applyMiddleware, compose, createStore } from 'redux'; import { connect, Provider } from 'react-redux'; import { createLogger } from 'redux-logger'; import thunk from 'redux-thunk'; import { Router } from 'react-native-router-flux'; // Consts and Libs import { AppStyles } from '@theme/'; import AppRoutes from '@navigation/'; import Analytics from '@lib/analytics'; // All redux reducers (rolled into one mega-reducer) import rootReducer from '@redux/index'; // Connect RNRF with Redux const RouterWithRedux = connect()(Router); // Load middleware let middleware = [ Analytics, thunk, // Allows action creators to return functions (not just plain objects) ]; if (__DEV__) { // Dev-only middleware middleware = [ ...middleware, createLogger(), // Logs state changes to the dev console ]; } // Init redux store (using the given reducer & middleware) const store = compose( applyMiddleware(...middleware), )(createStore)(rootReducer); /* Component ==================================================================== */ // Wrap App in Redux provider (makes Redux available to all sub-components) export default function AppContainer() { return ( <Provider store={store}> <RouterWithRedux scenes={AppRoutes} style={AppStyles.appContainer} /> </Provider> ); }
actor-apps/app-web/src/app/components/dialog/MessagesSection.react.js
daodaoliang/actor-platform
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ import _ from 'lodash'; import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; import { MessageContentTypes } from 'constants/ActorAppConstants'; import MessageActionCreators from 'actions/MessageActionCreators'; import VisibilityStore from 'stores/VisibilityStore'; import MessageItem from './messages/MessageItem.react'; const {addons: { PureRenderMixin }} = addons; let _delayed = []; let flushDelayed = () => { _.forEach(_delayed, (p) => { MessageActionCreators.setMessageShown(p.peer, p.message); }); _delayed = []; }; let flushDelayedDebounced = _.debounce(flushDelayed, 30, 100); let lastMessageDate = null, lastMessageSenderId = null; @ReactMixin.decorate(PureRenderMixin) class MessagesSection extends React.Component { static propTypes = { messages: React.PropTypes.array.isRequired, peer: React.PropTypes.object.isRequired }; constructor(props) { super(props); VisibilityStore.addChangeListener(this.onAppVisibilityChange); } componentWillUnmount() { VisibilityStore.removeChangeListener(this.onAppVisibilityChange); } getMessagesListItem = (message, index) => { let date = new Date(message.fullDate); const month = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; if (lastMessageDate === null) { lastMessageDate = new Date(message.fullDate); } const isFirstMessage = index === 0; const isNewDay = date.getDate() !== lastMessageDate.getDate(); const dateDivider = isNewDay ? <li className="date-divider">{month[date.getMonth()]} {date.getDate()}</li> : null; const isSameSender = message.sender.peer.id === lastMessageSenderId && !isFirstMessage && !isNewDay; const messageItem = ( <MessageItem key={message.sortKey} message={message} isNewDay={isNewDay} isSameSender={isSameSender} onVisibilityChange={this.onMessageVisibilityChange} peer={this.props.peer}/> ); lastMessageDate = new Date(message.fullDate); lastMessageSenderId = message.sender.peer.id; return [dateDivider, messageItem]; }; onAppVisibilityChange = () => { if (VisibilityStore.isVisible) { flushDelayed(); } }; onMessageVisibilityChange = (message, isVisible) => { if (isVisible) { _delayed.push({peer: this.props.peer, message: message}); if (VisibilityStore.isVisible) { flushDelayedDebounced(); } } }; render() { const messages = _.map(this.props.messages, this.getMessagesListItem); return ( <ul className="messages__list"> {messages} </ul> ); } } export default MessagesSection;
src/components/common/svg-icons/device/network-cell.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceNetworkCell = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M2 22h20V2z"/><path d="M17 7L2 22h15z"/> </SvgIcon> ); DeviceNetworkCell = pure(DeviceNetworkCell); DeviceNetworkCell.displayName = 'DeviceNetworkCell'; DeviceNetworkCell.muiName = 'SvgIcon'; export default DeviceNetworkCell;
src/client/main.js
Nord-HI/nord.is
import 'babel-polyfill' import React from 'react' import ReactDOM from 'react-dom' import { Router, browserHistory } from 'react-router' // Routes import Routes from 'client/common/components/Routes' // Base styling import 'client/common/base.css' // Render the router ReactDOM.render(( <Router history={browserHistory}> {Routes} </Router> ), document.getElementById('app'))
app/javascript/mastodon/components/gifv.js
tootsuite/mastodon
import React from 'react'; import PropTypes from 'prop-types'; export default class GIFV extends React.PureComponent { static propTypes = { src: PropTypes.string.isRequired, alt: PropTypes.string, width: PropTypes.number, height: PropTypes.number, onClick: PropTypes.func, }; state = { loading: true, }; handleLoadedData = () => { this.setState({ loading: false }); } componentWillReceiveProps (nextProps) { if (nextProps.src !== this.props.src) { this.setState({ loading: true }); } } handleClick = e => { const { onClick } = this.props; if (onClick) { e.stopPropagation(); onClick(); } } render () { const { src, width, height, alt } = this.props; const { loading } = this.state; return ( <div className='gifv' style={{ position: 'relative' }}> {loading && ( <canvas width={width} height={height} role='button' tabIndex='0' aria-label={alt} title={alt} onClick={this.handleClick} /> )} <video src={src} role='button' tabIndex='0' aria-label={alt} title={alt} muted loop autoPlay playsInline onClick={this.handleClick} onLoadedData={this.handleLoadedData} style={{ position: loading ? 'absolute' : 'static', top: 0, left: 0 }} /> </div> ); } }
node_modules/react-router/es6/IndexLink.js
geng890518/editor-ui
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; import React from 'react'; import Link from './Link'; /** * An <IndexLink> is used to link to an <IndexRoute>. */ var IndexLink = React.createClass({ displayName: 'IndexLink', render: function render() { return React.createElement(Link, _extends({}, this.props, { onlyActiveOnIndex: true })); } }); export default IndexLink;
src/SelectRowHeaderColumn.js
prince1809/react-grid
import React from 'react'; import classSet from 'classnames'; import Const from './Const'; class SelectRowHeaderColumn extends React.Component{ render(){ var thStyle = { width: 35 }; return( <th style={thStyle}> <div className="th-inner table-header-column"> {this.props.children} </div> </th> ) } }; export default SelectRowHeaderColumn;
src/authentication/signup/index.js
GrayTurtle/rocket-workshop
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { compose } from 'redux'; import { firebaseConnect, isLoaded, isEmpty } from 'react-redux-firebase'; import '../auth.css'; class Signup extends Component { static propTypes = { }; constructor(props) { super(props); this.state = { email: '', password: '', error: '' }; } componentWillReceiveProps(nextProps) { const { auth, history } = nextProps; if (auth.isLoaded && !auth.isEmpty) { history.push('/organizer/acm'); } } onChange = (value, type) => { this.setState({ [type]: value }); } onSignup = () => { const { email, password } = this.state; const { firebase } = this.props; firebase.createUser({ email, password }); } render() { const { email, password } = this.state; const { authError } = this.props; return ( <div className="auth-form"> {authError && <div className="auth-error">{authError.message}</div>} <input className="auth-field" type="text" value={email} onChange={({ target: { value }}) => this.onChange(value, 'email')}/> <input className="auth-field" type="password" value={password} onChange={({ target: { value }}) => this.onChange(value, 'password')} /> <div className="signup-button" onClick={this.onSignup}>Signup</div> </div> ); } } export default compose( firebaseConnect(), connect( ({ firebase: { auth, authError } }) => ({ auth, authError }) ) )(Signup);
packages/es-components/src/components/controls/buttons/ActionButton.js
jrios/es-components
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { useTheme } from '../../util/useTheme'; import Button from './Button'; const StyledButton = styled(Button)` .es-button__display { background-color: ${props => props.defaultStyle.bgColor}; box-shadow: 0 4px 0 0 ${props => props.defaultStyle.boxShadowColor}; color: ${props => props.defaultStyle.textColor}; transition: background-color 120ms linear, color 120ms linear; } &:hover .es-button__display { background-color: ${props => props.hoverStyle.bgColor}; box-shadow: 0 4px 0 0 ${props => props.hoverStyle.hoverBgColor}; color: ${props => props.hoverStyle.textColor}; } `; const ActionButton = React.forwardRef(function ActionButton(props, ref) { const { children, styleType, ...other } = props; const theme = useTheme(); const defaultStyle = theme.buttonStyles.button.variant.default; const hoverStyle = theme.buttonStyles.button.variant[styleType]; return ( <StyledButton ref={ref} defaultStyle={defaultStyle} hoverStyle={hoverStyle} styleType={styleType} type="button" {...other} > {children} </StyledButton> ); }); ActionButton.propTypes = { children: PropTypes.node.isRequired, /** Select the color style of the button, types come from theme buttonStyles.button */ styleType: PropTypes.string }; ActionButton.defaultProps = { styleType: 'primary' }; export default ActionButton;
packages/presentation/src/index.js
dfbaskin/react-higher-order-components
import React from 'react'; import ReactDOM from 'react-dom'; import 'normalize.css'; import './index.css'; import {App} from './app'; require('prismjs'); require('prismjs/themes/prism.css'); ReactDOM.render( <App />, document.getElementById('root') );
exercise-04-solution/src/components/PokemonPreview.js
learnapollo/pokedex-react
import React from 'react' import { Link } from 'react-router' export default class PokemonPreview extends React.Component { static propTypes = { pokemon: React.PropTypes.object, } render () { return ( <Link to={`/view/${this.props.pokemon.id}`} style={{ minWidth: 200 }} className='link dim grow mw4 bg-white ma2 pa3 shadow-1' > <img src={this.props.pokemon.url} alt={this.props.pokemon.name} /> <div className='gray tc'>{this.props.pokemon.name}</div> </Link> ) } }
lib/views/mount-settings.js
koding/kd-atom
'use babel' import { Emitter } from 'atom' import { View } from 'atom-space-pen-views' import React from 'react' import { render } from 'react-dom' import { find } from 'lodash' import MountsTable from './mounts-table' export default class MountSettings extends View { static content({ mounts }) { this.section({ class: 'machines-list-container' }) } initialize({ mounts, machines, options }) { this.emitter = new Emitter() this.options = options this.mounts = mounts.map(mount => ({ ...mount, machine: find(machines, { alias: mount.label }), })) } onClose() { this.options.onClose() } onReload() { this.options.onReload() } onOpen(mount) { this.options.onOpen({ mount }) } onNewWindow(mount) { this.options.onNewWindow({ mount }) } onUnmount(mount) { return this.options.onUnmount({ mount }) } onShowMachine(machine) { this.options.onShowMachine({ machine }) } onCopyId(machine, name, index) { return this.options.onCopyId(machine, name, index) } attached() { this.renderTable({ mounts: this.mounts }) } renderTable({ mounts }) { render( <MountsTable mounts={mounts} onClose={this.onClose.bind(this)} onReload={this.onReload.bind(this)} onOpen={this.onOpen.bind(this)} onNewWindow={this.onNewWindow.bind(this)} onUnmount={this.onUnmount.bind(this)} onShowMachine={this.onShowMachine.bind(this)} onCopyId={this.onCopyId.bind(this)} />, this.element ) } }
admin/client/App/screens/List/components/ItemsTable/ItemsTableRow.js
creynders/keystone
import React from 'react'; import classnames from 'classnames'; import ListControl from '../ListControl'; import { Columns } from 'FieldTypes'; import { DropTarget, DragSource } from 'react-dnd'; import { setDragBase, resetItems, reorderItems, setRowAlert, moveItem, } from '../../actions'; const ItemsRow = React.createClass({ propTypes: { columns: React.PropTypes.array, id: React.PropTypes.any, index: React.PropTypes.number, items: React.PropTypes.object, list: React.PropTypes.object, // Injected by React DnD: isDragging: React.PropTypes.bool, // eslint-disable-line react/sort-prop-types connectDragSource: React.PropTypes.func, // eslint-disable-line react/sort-prop-types connectDropTarget: React.PropTypes.func, // eslint-disable-line react/sort-prop-types connectDragPreview: React.PropTypes.func, // eslint-disable-line react/sort-prop-types }, renderRow (item) { const itemId = item.id; const rowClassname = classnames({ 'ItemList__row--dragging': this.props.isDragging, 'ItemList__row--selected': this.props.checkedItems[itemId], 'ItemList__row--manage': this.props.manageMode, 'ItemList__row--success': this.props.rowAlert.success === itemId, 'ItemList__row--failure': this.props.rowAlert.fail === itemId, }); // item fields var cells = this.props.columns.map((col, i) => { var ColumnType = Columns[col.type] || Columns.__unrecognised__; var linkTo = !i ? `${Keystone.adminPath}/${this.props.list.path}/${itemId}` : undefined; return <ColumnType key={col.path} list={this.props.list} col={col} data={item} linkTo={linkTo} />; }); // add sortable icon when applicable if (this.props.list.sortable) { cells.unshift(<ListControl key="_sort" type="sortable" dragSource={this.props.connectDragSource} />); } // add delete/check icon when applicable if (!this.props.list.nodelete) { cells.unshift(this.props.manageMode ? ( <ListControl key="_check" type="check" active={this.props.checkedItems[itemId]} /> ) : ( <ListControl key="_delete" onClick={(e) => this.props.deleteTableItem(item, e)} type="delete" /> )); } var addRow = (<tr key={'i' + item.id} onClick={this.props.manageMode ? (e) => this.props.checkTableItem(item, e) : null} className={rowClassname}>{cells}</tr>); if (this.props.list.sortable) { return ( // we could add a preview container/image // this.props.connectDragPreview(this.props.connectDropTarget(addRow)) this.props.connectDropTarget(addRow) ); } else { return (addRow); } }, render () { return this.renderRow(this.props.item); }, }); module.exports = exports = ItemsRow; // Expose Sortable /** * Implements drag source. */ const dragItem = { beginDrag (props) { const send = { ...props }; props.dispatch(setDragBase(props.item, props.index)); return { ...send }; }, endDrag (props, monitor, component) { if (!monitor.didDrop()) { props.dispatch(resetItems(props.id)); return; } const base = props.drag; const page = props.currentPage; const droppedOn = monitor.getDropResult(); // some drops provide the data for us in prevSortOrder const prevSortOrder = typeof droppedOn.prevSortOrder === 'number' ? droppedOn.prevSortOrder : props.sortOrder; // use a given newSortOrder prop or retrieve from the cloned items list let newSortOrder = typeof droppedOn.newSortOrder === 'number' ? droppedOn.newSortOrder : droppedOn.index; // self if (prevSortOrder === newSortOrder) { if (base.page !== page) { // we were dropped on ourself, but not on our original page if (droppedOn.index === 0) { // item is first in the list // save to the sortOrder of the 2nd item - 1 // newSortOrder = CurrentListStore.findClonedItemByIndex(1).sortOrder - 1; droppedOn.goToPage = Number(page) - 1; } else { // item is last in the list // save to the sortOrder of the 2nd to last item - 1 // newSortOrder = CurrentListStore.findClonedItemByIndex(droppedOn.index - 1).sortOrder + 1; droppedOn.goToPage = Number(page) + 1; } if (!newSortOrder || !droppedOn.goToPage) { // something is wrong so reset this.props.dispatch(resetItems(props.id)); return; } } else { props.dispatch(resetItems(props.id)); return; } } // dropped on a target // droppedOn.goToPage is an optional page override for dropping items on a new page target props.dispatch(reorderItems(props.item, prevSortOrder, newSortOrder, Number(droppedOn.goToPage))); }, }; /** * Implements drag target. */ const dropItem = { drop (props, monitor, component) { return { ...props }; }, hover (props, monitor, component) { // reset row alerts if (props.rowAlert.success || props.rowAlert.fail) { props.dispatch(setRowAlert({ reset: true, })); } const dragged = monitor.getItem().index; const over = props.index; // self if (dragged === over) { return; } props.dispatch(moveItem(dragged, over, props)); monitor.getItem().index = over; }, }; /** * Specifies the props to inject into your component. */ function dragProps (connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), connectDragPreview: connect.dragPreview(), }; } function dropProps (connect) { return { connectDropTarget: connect.dropTarget(), }; }; exports.Sortable = DragSource('item', dragItem, dragProps)(DropTarget('item', dropItem, dropProps)(ItemsRow));
src/Component/goodInfo.js
smay1227/wintershop
import React, { Component } from 'react'; import {Link} from 'react-router'; import '../Stylesheets/goodInfo.css'; export default class goodInfo extends Component { constructor(props) { super(props); this.state = { year: this.props.params.year, month: this.props.params.month, day: this.props.params.day, urlname: this.props.params.urlname } this.props.actions.fetchBlog({year: '2017', month: '1', day: '19', urlname: 'react_life'}) } render(){ let blog = this.props.results.blog; function renderhtml(){ return { __html: blog.content }; } return( <div> <nav className="navbar navbar-default navbar-fixed-top" role="navigation"> <div className="container-fluid"> <Link className="navbar-info-brand" to={'/goods'}>承易康源</Link> <div className="navbar-info-right"> <Link className="buy" to='/goodChoose'>购买</Link> </div> </div> </nav> <div className='container center-block info-content'> <div className="col-md-2 col-sm-12"></div> <div className="col-md-8 col-sm-12"> <div className='row'> <div className="panel panel-default"> <div className="panel-body blog"> <div dangerouslySetInnerHTML={renderhtml()}></div> </div> </div> </div> </div> </div> </div> ); } }
lib/ui/src/components/notifications/NotificationItem.stories.js
storybooks/storybook
import React from 'react'; import NotificationItem from './NotificationItem'; export default { component: NotificationItem, title: 'UI/Notifications/NotificationItem', decorators: [(storyFn) => <div style={{ width: '240px', margin: '1rem' }}>{storyFn()}</div>], excludeStories: /.*Data$/, }; const onClear = () => {}; const onDismissNotification = () => {}; const Template = (args) => <NotificationItem {...args} />; export const simpleData = { id: '1', onClear, content: { headline: 'Storybook cool!', }, }; export const simple = Template.bind({}); simple.args = { notification: simpleData, onDismissNotification, }; export const longHeadlineData = { id: '2', onClear, content: { headline: 'This is a long message that extends over two lines!', }, }; export const longHeadline = Template.bind({}); longHeadline.args = { notification: longHeadlineData, onDismissNotification, }; export const linkData = { id: '3', onClear, content: { headline: 'Storybook X.X is available! Download now »', }, link: '/some/path', }; export const link = Template.bind({}); link.args = { notification: linkData, onDismissNotification, }; export const linkIconWithColorData = { id: '4', onClear, content: { headline: 'Storybook with a smile!', }, icon: { name: 'facehappy', color: 'hotpink', }, link: '/some/path', }; export const linkIconWithColor = Template.bind({}); linkIconWithColor.args = { notification: linkIconWithColorData, onDismissNotification, }; export const linkIconWithColorSubHeadlineData = { id: '5', onClear, content: { headline: 'Storybook X.X is available with a smile! Download now »', subHeadline: 'This link also has a sub headline', }, icon: { name: 'facehappy', color: 'tomato', }, link: '/some/path', }; export const linkIconWithColorSubHeadline = Template.bind({}); linkIconWithColorSubHeadline.args = { notification: linkIconWithColorSubHeadlineData, onDismissNotification, }; export const bookIconData = { id: '6', onClear, content: { headline: 'Storybook has a book icon!', }, icon: { name: 'book', }, }; export const bookIcon = Template.bind({}); bookIcon.args = { notification: bookIconData, onDismissNotification, }; export const strongSubHeadlineData = { id: '7', onClear, content: { headline: 'Storybook has a book icon!', subHeadline: <strong>Strong subHeadline</strong>, }, icon: { name: 'book', }, }; export const strongSubHeadline = Template.bind({}); strongSubHeadline.args = { notification: strongSubHeadlineData, onDismissNotification, }; export const strongEmphasizedSubHeadlineData = { id: '8', onClear, content: { headline: 'Storybook cool!', subHeadline: ( <span> <em>Emphasized</em> normal <strong>strong Storybook!</strong> </span> ), }, icon: { name: 'book', }, }; export const strongEmphasizedSubHeadline = Template.bind({}); strongEmphasizedSubHeadline.args = { notification: strongEmphasizedSubHeadlineData, onDismissNotification, }; export const bookIconSubHeadlineData = { id: '9', onClear, content: { headline: 'Storybook has a book icon!', subHeadline: 'Find out more!', }, icon: { name: 'book', }, }; export const bookIconSubHeadline = Template.bind({}); bookIconSubHeadline.args = { notification: bookIconSubHeadlineData, onDismissNotification, }; export const bookIconLongSubHeadlineData = { id: '10', onClear, content: { headline: 'Storybook has a book icon!', subHeadline: 'Find out more! by clicking on on buttons and downloading some applications. Find out more! by clicking on buttons and downloading some applications', }, icon: { name: 'book', }, }; export const bookIconLongSubHeadline = Template.bind({}); bookIconLongSubHeadline.args = { notification: bookIconLongSubHeadlineData, onDismissNotification, }; export const accessibilityIconData = { id: '11', onClear, content: { headline: 'Storybook has a accessibility icon!', subHeadline: 'It is here!', }, icon: { name: 'accessibility', }, }; export const accessibilityIcon = Template.bind({}); accessibilityIcon.args = { notification: accessibilityIconData, onDismissNotification, }; export const accessibilityGoldIconData = { id: '12', onClear, content: { headline: 'Accessibility icon!', subHeadline: 'It is gold!', }, icon: { name: 'accessibility', color: 'gold', }, }; export const accessibilityGoldIcon = Template.bind({}); accessibilityGoldIcon.args = { notification: accessibilityGoldIconData, onDismissNotification, }; export const accessibilityGoldIconLongHeadLineNoSubHeadlineData = { id: '13', onClear, content: { headline: 'Storybook notifications has a accessibility icon it can be any color!', }, icon: { name: 'accessibility', color: 'gold', }, }; export const accessibilityGoldIconLongHeadLineNoSubHeadline = Template.bind({}); accessibilityGoldIconLongHeadLineNoSubHeadline.args = { notification: accessibilityGoldIconLongHeadLineNoSubHeadlineData, onDismissNotification, };
app/components/default-settings/RaceDistanceSetting.js
opensprints/opensprints-electron
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Select from './Select'; export default class RaceDistanceSetting extends Component { static propTypes = { defaultRaceSettings: PropTypes.object.isRequired, changeDefaultRaceSetting: PropTypes.func.isRequired } render() { const { defaultRaceSettings, changeDefaultRaceSetting } = this.props; return ( <div className="row"> <div className="input-group inline"> <label htmlFor="distance-input" className="group-heading text-uppercase"> Race Distance </label> <div className="input-group inline"> <div className="col-xs-4" style={{ padding: '3px 3px 3px 0' }} > <div style={{ position: 'relative' }}> <input id="distance-input" style={{ padding: '6px 10px' }} className="form-control context" type="text" value={defaultRaceSettings.raceDistance} onChange={(e) => { changeDefaultRaceSetting('raceDistance', parseInt(e.target.value.replace(/[^\d]/g, ''), 10) ); }} /> </div> </div> <div className="col-xs-4" style={{ padding: '3px 0 3px 2px' }} > <Select selectProps={{ style: { width: '130px' }, onChange: (e) => { changeDefaultRaceSetting('raceDistanceUnits', e.target.value); }, value: defaultRaceSettings.raceDistanceUnits }} > <option value="feet">feet</option> <option value="meters">meters</option> </Select> </div> </div> </div> </div> ); } }
src/svg-icons/device/location-disabled.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceLocationDisabled = (props) => ( <SvgIcon {...props}> <path d="M20.94 11c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06c-1.13.12-2.19.46-3.16.97l1.5 1.5C10.16 5.19 11.06 5 12 5c3.87 0 7 3.13 7 7 0 .94-.19 1.84-.52 2.65l1.5 1.5c.5-.96.84-2.02.97-3.15H23v-2h-2.06zM3 4.27l2.04 2.04C3.97 7.62 3.25 9.23 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c1.77-.2 3.38-.91 4.69-1.98L19.73 21 21 19.73 4.27 3 3 4.27zm13.27 13.27C15.09 18.45 13.61 19 12 19c-3.87 0-7-3.13-7-7 0-1.61.55-3.09 1.46-4.27l9.81 9.81z"/> </SvgIcon> ); DeviceLocationDisabled = pure(DeviceLocationDisabled); DeviceLocationDisabled.displayName = 'DeviceLocationDisabled'; DeviceLocationDisabled.muiName = 'SvgIcon'; export default DeviceLocationDisabled;
docs/build.js
pivotal-cf/react-bootstrap
/* eslint no-console: 0 */ import React from 'react'; import path from 'path'; import Router from 'react-router'; import routes from './src/Routes'; import Root from './src/Root'; import fsp from 'fs-promise'; import { copy } from '../tools/fs-utils'; import { exec } from '../tools/exec'; import metadata from './generate-metadata'; const repoRoot = path.resolve(__dirname, '../'); const docsBuilt = path.join(repoRoot, 'docs-built'); const license = path.join(repoRoot, 'LICENSE'); const readmeSrc = path.join(__dirname, 'README.docs.md'); const readmeDest = path.join(docsBuilt, 'README.md'); /** * Generates HTML code for `fileName` page. * * @param {string} fileName Path for Router.Route * @return {Promise} promise * @internal */ function generateHTML(fileName, propData) { return new Promise((resolve, reject) => { const urlSlug = fileName === 'index.html' ? '/' : `/${fileName}`; Router.run(routes, urlSlug, Handler => { let html = React.renderToString(React.createElement(Handler, { propData })); html = '<!doctype html>' + html; let write = fsp.writeFile(path.join(docsBuilt, fileName), html); resolve(write); }); }); } export default function BuildDocs({dev}) { console.log('Building: '.cyan + 'docs'.green + (dev ? ' [DEV]'.grey : '')); const devOption = dev ? '' : '-p'; return exec(`rimraf ${docsBuilt}`) .then(() => fsp.mkdir(docsBuilt)) .then(metadata) .then(propData => { let pagesGenerators = Root.getPages().map( page => generateHTML(page, propData)); return Promise.all(pagesGenerators.concat([ exec(`webpack --config webpack.docs.js --bail ${devOption}`), copy(license, docsBuilt), copy(readmeSrc, readmeDest) ])); }) .then(() => console.log('Built: '.cyan + 'docs'.green + (dev ? ' [DEV]'.grey : ''))); }
src/containers/QuizList/QuizList.js
AbhishekCode/quiz
import React, { Component } from 'react'; import { StyleSheet, css } from 'aphrodite'; import { connect } from 'react-redux'; import RaisedButton from 'material-ui/RaisedButton'; import {browserHistory} from 'react-router'; import CircularProgress from 'material-ui/CircularProgress'; import {List, ListItem} from 'material-ui/List'; import {routepath} from '../../utils/config'; const routePath = routepath(); import {loadQuizList, loadSelectedQuiz, loadQuizListFirebase, addQuiz} from '../../redux/reducers/quiz'; class QuizList extends Component { constructor(props) { super(props); this.props.dispatch(loadQuizListFirebase()); }; _selectQuiz = (index) => { this.props.dispatch(loadSelectedQuiz(this.props.quizList[index])); browserHistory.push(routePath+"quiz"); } _home = () => { browserHistory.push(routePath+"/home"); } render() { return ( <div className={css(styles.container)}> <RaisedButton label={"Home"} primary={true} style={nextButtonStyle} onClick={this._home} /> { !this.props.quizList && <CircularProgress /> } <List style={{width:'100%'}}> { this.props.quizList && this.props.quizList.map((quiz, index) => <ListItem style={{width:'100%'}} primaryText={quiz.name} secondaryText={'by '+quiz.user} onClick={()=>this._selectQuiz(index)} /> ) } </List> </div> ); } } const nextButtonStyle = { margin: 10 } const styles = StyleSheet.create({ container: { display: 'flex', flex: 1, width: '100%', flexDirection: 'column', justyfyContent: 'center', alignItems: 'center', padding: 10 } }); function mapStateToProps(state) { return { quizList: state.quiz.quizList || undefined }; } export default connect(mapStateToProps) (QuizList);
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentSimplifyTypeArgs/__tests__/fixtures/DefaultPropsInline.js
TiddoLangerak/flow
// @flow import React from 'react'; class MyComponent extends React.Component<{a: number, b: number, c: number}, Props> { static defaultProps: {a: number, b: number, c: number} = {a: 1, b: 2, c: 3}; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} } const expression = () => class extends React.Component<{a: number, b: number, c: number}, Props> { static defaultProps: {a: number, b: number, c: number} = {a: 1, b: 2, c: 3}; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} }
src/shared/components/component.js
tarkalabs/material-todo-jsc2016
import _ from 'lodash'; import React from 'react'; import appState from '../stores'; import shouldComponentUpdate from '../helpers/should_component_update'; export default function component(ParentComponent, paths) { return React.createClass({ displayName: 'component', shouldComponentUpdate: shouldComponentUpdate, render: function() { var isComputed = (pitem) => /^computed/i.test(pitem); var hasComputed = (path) => _.some(path, isComputed); var computedPaths = _.pickBy(paths, (path) => hasComputed(path)); var standardPaths = _.pickBy(paths, (path) => !hasComputed(path)); var props = _.reduce(standardPaths, ((memo, path, key) => { memo[key] = appState.cursor(path); return memo; }), {}); props = _.reduce(computedPaths, ((memo, path, key) => { path = path.map((pitem) => { if (isComputed(pitem)) { var keys = pitem.split(".").slice(2); var cursorKey = pitem.split(".")[1]; var ppath = memo[cursorKey].deref(); return _.isEmpty(keys) ? ppath : ppath.getIn(keys); } else { return pitem; } }); memo[key] = appState.cursor(path); return memo; }), props); return <ParentComponent {...this.props} {...props} />; } }); }
modules/Lifecycle.js
runlevelsix/react-router
import React from 'react' import invariant from 'invariant' const { object } = React.PropTypes /** * The Lifecycle mixin adds the routerWillLeave lifecycle method * to a component that may be used to cancel a transition or prompt * the user for confirmation. * * On standard transitions, routerWillLeave receives a single argument: the * location we're transitioning to. To cancel the transition, return false. * To prompt the user for confirmation, return a prompt message (string). * * routerWillLeave does not receive a location object during the beforeunload * event in web browsers (assuming you're using the useBeforeUnload history * enhancer). In this case, it is not possible for us to know the location * we're transitioning to so routerWillLeave must return a prompt message to * prevent the user from closing the tab. */ const Lifecycle = { propTypes: { // Route components receive the route object as a prop. route: object }, contextTypes: { history: object.isRequired, // Nested children receive the route as context, either // set by the route component using the RouteContext mixin // or by some other ancestor. route: object }, _getRoute() { const route = this.props.route || this.context.route invariant( route, 'The Lifecycle mixin needs to be used either on 1) a <Route component> or ' + '2) a descendant of a <Route component> that uses the RouteContext mixin' ) return route }, componentWillMount() { invariant( this.routerWillLeave, 'The Lifecycle mixin requires you to define a routerWillLeave method' ) this.context.history.registerRouteHook( this._getRoute(), this.routerWillLeave ) }, componentWillUnmount() { this.context.history.unregisterRouteHook( this._getRoute(), this.routerWillLeave ) } } export default Lifecycle
App/Components/NoNavbar.js
FAC7/anna-freud-hub
import React from 'react' import { View } from 'react-native' export default () => <View />
imports/ui/admin/components/.stories/menu.js
dououFullstack/atomic
import React from 'react'; import { storiesOf, action } from '@kadira/storybook'; import { setComposerStub } from 'react-komposer'; import Menu from '../menu.jsx'; storiesOf('admin.Menu', module) .add('default view', () => { return ( <Menu /> ); })
src/svg-icons/image/camera-alt.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCameraAlt = (props) => ( <SvgIcon {...props}> <circle cx="12" cy="12" r="3.2"/><path d="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/> </SvgIcon> ); ImageCameraAlt = pure(ImageCameraAlt); ImageCameraAlt.displayName = 'ImageCameraAlt'; export default ImageCameraAlt;
app/javascript/mastodon/components/missing_indicator.js
danhunsaker/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import illustration from 'mastodon/../images/elephant_ui_disappointed.svg'; import classNames from 'classnames'; const MissingIndicator = ({ fullPage }) => ( <div className={classNames('regeneration-indicator', { 'regeneration-indicator--without-header': fullPage })}> <div className='regeneration-indicator__figure'> <img src={illustration} alt='' /> </div> <div className='regeneration-indicator__label'> <FormattedMessage id='missing_indicator.label' tagName='strong' defaultMessage='Not found' /> <FormattedMessage id='missing_indicator.sublabel' defaultMessage='This resource could not be found' /> </div> </div> ); MissingIndicator.propTypes = { fullPage: PropTypes.bool, }; export default MissingIndicator;
src/styles/MuiThemeProvider.js
AndriusBil/material-ui
// @flow import React from 'react'; import PropTypes from 'prop-types'; import createBroadcast from 'brcast'; import themeListener, { CHANNEL } from './themeListener'; class MuiThemeProvider extends React.Component<Object> { constructor(props: Object, context: Object) { super(props, context); // Get the outer theme from the context, can be null this.outerTheme = themeListener.initial(context); // Propagate the theme so it can be accessed by the children this.broadcast.setState(this.mergeOuterLocalTheme(this.props.theme)); } getChildContext() { if (this.props.sheetsManager) { return { [CHANNEL]: this.broadcast, sheetsManager: this.props.sheetsManager, }; } return { [CHANNEL]: this.broadcast, }; } componentDidMount() { // Subscribe on the outer theme, if present this.unsubscribeId = themeListener.subscribe(this.context, outerTheme => { this.outerTheme = outerTheme; // Forward the parent theme update to the children this.broadcast.setState(this.mergeOuterLocalTheme(this.props.theme)); }); } componentWillReceiveProps(nextProps: Object) { // Propagate a local theme update if (this.props.theme !== nextProps.theme) { this.broadcast.setState(this.mergeOuterLocalTheme(nextProps.theme)); } } componentWillUnmount() { if (this.unsubscribeId !== null) { themeListener.unsubscribe(this.context, this.unsubscribeId); } } broadcast = createBroadcast(); unsubscribeId = null; // We are not using the React state in order to avoid unnecessary rerender. outerTheme = null; // Simple merge between the outer theme and the local theme mergeOuterLocalTheme(localTheme: Object) { // To support composition of theme. if (typeof localTheme === 'function') { return localTheme(this.outerTheme); } if (!this.outerTheme) { return localTheme; } return { ...this.outerTheme, ...localTheme }; } render() { return this.props.children; } } MuiThemeProvider.propTypes = { /** * You can only provide a single element. */ children: PropTypes.element.isRequired, /** * The sheetsManager is used in order to only inject once a style sheet in a page for * a given theme object. * You should provide on the server. */ sheetsManager: PropTypes.object, /** * A theme object. */ theme: PropTypes.oneOfType([PropTypes.object, PropTypes.func]).isRequired, }; MuiThemeProvider.childContextTypes = { ...themeListener.contextTypes, sheetsManager: PropTypes.object, }; MuiThemeProvider.contextTypes = themeListener.contextTypes; export default MuiThemeProvider;
src/components/App.js
donjar/learn-latex
import React from 'react'; import Question from './Question'; class App extends React.Component { render() { return ( <div className="App"> <div className="container"> <h1>Belajar LaTeX</h1> <Question description="Di forum olimpiade.org, kode LaTeX dibungkus dengan tanda dollar ($). Ayok tulis kode LaTeX pertama Anda! Coba tulis $2 + 3 = 5$." answer="$2 + 3 = 5$" /> </div> </div> ); } } export default App;
src/containers/Asians/Published/AdjudicatorSpeechScoreRange/AdjudicatorGivenScores.js
westoncolemanl/tabbr-web
import React from 'react' import { connect } from 'react-redux' import { TableCell, TableRow } from 'material-ui/Table' import _ from 'lodash' export default connect(mapStateToProps)(({ adjudicator, scoresGiven }) => { const score = _.sum(scoresGiven) / scoresGiven.length return ( <TableRow> <TableCell children={score.toFixed(2)} /> <TableCell children={`${adjudicator.firstName} ${adjudicator.lastName}`} /> {scoresGiven.sort().map((score, index) => <TableCell key={index} children={score} /> )} </TableRow> ) }) function mapStateToProps (state, ownProps) { return { rounds: Object.values(state.rounds.data), adjudicators: Object.values(state.adjudicators.data), ballots: Object.values(state.ballots.data) } }
src/index.js
dsandmark/redux-tech-demo
import React from 'react'; import ReactDOM from 'react-dom'; import { IndexRoute, Router, Route, browserHistory } from 'react-router' import { applyMiddleware, createStore } from 'redux' import { Provider } from 'react-redux' import createLogger from 'redux-logger' import rootReducer from './domain' import './index.css'; import App from './views/app/app.component'; import Welcome from './views/welcome/welcome.component' import PageNotFound from './views/page-not-found/page-not-found.component' import Conclusion from './views/1-conclusion/component' import FirstOverview from './views/2-first-overview/component' import FirstRecap from './views/3-first-recap/component' import ReactReduxConnection from './views/4-react-redux-connection/component' import ReactReduxFullFlow from './views/5-react-redux-full-flow/component' import ReduxUnidirectionalFlow from './views/6-redux-unidirectional-flow/component' import Switches from './views/7-switches/component' import Performance from './views/8-performance/component' import ReusableComponents from './views/9-reusable-components/component' import FinalRecap from './views/10-final-recap/component' import Thanks from './views/11-thanks/component' const logger = createLogger() const store = createStore( rootReducer, applyMiddleware(logger) ) ReactDOM.render( <Provider store={store}> <Router history={browserHistory}> <Route path='/' component={App}> <IndexRoute component={Welcome} /> <Route path='conclusion' component={Conclusion}/> <Route path='first-overview' component={FirstOverview}/> <Route path='first-recap' component={FirstRecap}/> <Route path='react-redux-connection' component={ReactReduxConnection}/> <Route path='react-redux-full-flow' component={ReactReduxFullFlow}/> <Route path='redux-unidirectional-flow' component={ReduxUnidirectionalFlow}/> <Route path='switches' component={Switches}/> <Route path='performance' component={Performance}/> <Route path='reusable-components' component={ReusableComponents}/> <Route path='final-recap' component={FinalRecap}/> <Route path='thanks' component={Thanks}/> </Route> <Route path="*" component={PageNotFound} /> </Router> </Provider>, document.getElementById('root') )
containers/page_new_paper.js
MonkingStand/MS-blog-site-v3.0
import React from 'react'; import ParagraphType from '../components/new_paper_paragraph_type'; import ParagraphKit from '../components/new_paper_paragraph_kit'; import InputArea from '../components/new_paper_input_area'; import SubmitContainer from '../components/new_paper_submit_container'; import ViewContent from '../components/new_paper_view_content'; import smoothScroll from '../modules/plugin_smooth_scroll'; class PageNewPaper extends React.Component { constructor() { super(); this.scrollToTop = this.scrollToTop.bind(this); this.state = { addedLink: { linkVal : '', linkTitle: '' }, selectedParagraphType: { name : 'normal', begin: '<p>', end : '</p>' }, contentList : [] }; }; scrollToTop() { smoothScroll('#topAnchor', 750); }; changeAddedLink(newLink) { this.setState({ addedLink: newLink }); }; changeParagraphType(newType) { this.setState({ selectedParagraphType: newType }); }; insertNewParagraph(content) { const selectedParagraphType = this.state.selectedParagraphType; const oldContentList = this.state.contentList.slice(0); const oldContentCloseTag = (oldContentList.length !== 0) ? oldContentList[oldContentList.length - 1] : ''; var newContentList; if (selectedParagraphType.name === 'title' || selectedParagraphType.name === 'normal' || selectedParagraphType.name === 'imgContainer') { newContentList = oldContentList.concat(content); } else { if (oldContentCloseTag !== selectedParagraphType.containerEnd || oldContentCloseTag == '<br>') { /* first time to add or content is <br> */ newContentList = oldContentList.concat(content); } else { oldContentList.pop(); newContentList = oldContentList.concat(content.slice(1)); } } this.setState({ contentList: newContentList }); }; deleteLatestParagraph() { const listCount = this.state.contentList.length; const newContentList = (listCount === 0) ? [] : this.state.contentList.slice(0, -1); this.setState({ contentList: newContentList }); }; render() { const css_id_newPaperPage = { padding: 0, margin : 0 }; return ( <div> {/* 遮罩层 */} <div className = "mask-container"></div> {/* 顶部锚点 */} <div id = "topAnchor"></div> {/* 【回到顶部】快捷键 */} <div id = "scrollBtn" onClick = { this.scrollToTop } > <img src = "./img/scroll-bg.png"/> </div> {/* 主体部分 */} <div id = "newPaperPage" style = { css_id_newPaperPage } className = "body-container" > <div className = "body-content row new-paper-container"> <div className = "col-xs-6"> {/* 段落类别选择 */} <ParagraphType changeParagraphType = { this.changeParagraphType.bind(this) }/> {/* 段落元件 */} <ParagraphKit insertNewParagraph = { this.insertNewParagraph.bind(this) } changeAddedLink = { this.changeAddedLink.bind(this) } /> </div> {/* 输入区域 */} <InputArea addedLink = { this.state.addedLink } selectedParagraphType = { this.state.selectedParagraphType } insertNewParagraph = { this.insertNewParagraph.bind(this) } changeAddedLink = { this.changeAddedLink.bind(this) } deleteLatestParagraph = { this.deleteLatestParagraph.bind(this) } /> {/* 提交文章保存 */} <SubmitContainer contentList = { this.state.contentList }/> {/* 预览区域 */} <ViewContent contentList = { this.state.contentList }/> </div> </div> </div> ); }; }; export default PageNewPaper;
src/svg-icons/av/videocam-off.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvVideocamOff = (props) => ( <SvgIcon {...props}> <path d="M21 6.5l-4 4V7c0-.55-.45-1-1-1H9.82L21 17.18V6.5zM3.27 2L2 3.27 4.73 6H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.21 0 .39-.08.54-.18L19.73 21 21 19.73 3.27 2z"/> </SvgIcon> ); AvVideocamOff = pure(AvVideocamOff); AvVideocamOff.displayName = 'AvVideocamOff'; AvVideocamOff.muiName = 'SvgIcon'; export default AvVideocamOff;
fields/types/color/ColorColumn.js
matthieugayon/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var ColorColumn = React.createClass({ displayName: 'ColorColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; if (!value) return null; const colorBoxStyle = { backgroundColor: value, borderRadius: 3, display: 'inline-block', height: 18, marginRight: 10, verticalAlign: 'middle', width: 18, }; return ( <ItemsTableValue truncate={false} field={this.props.col.type}> <div style={{ lineHeight: '18px' }}> <span style={colorBoxStyle} /> <span style={{ display: 'inline-block', verticalAlign: 'middle' }}>{value}</span> </div> </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = ColorColumn;
src/WriteboxInput.js
bdryanovski/react-native-writebox
/* @flow */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { View, Text, TextInput, Platform } from 'react-native'; import { LIGHT_GRAY_FONT_COLOR, GRAY_FONT_COLOR } from './constants' import styles from './styles' const INPUT_MAX_HEIGHT = 60 export default class WriteBoxInput extends Component { static propTypes = { onHeightChanged: PropTypes.func, onChange: PropTypes.func, onFocus: PropTypes.func, onBlur: PropTypes.func, autoFocus: PropTypes.bool, value: PropTypes.string, placeholder: PropTypes.string, inputLimit: PropTypes.number } static defaultProps = { onHeightChanged: () => {}, onChange: () => {}, onFocus: () => {}, onBlur: () => {}, autoFocus: false, value: '', placeholder: 'Type here ...', inputLimit: undefined } constructor(props) { super(props) this.state = { content: props.value || '', height: 0, } this._onContentSizeChange = this._onContentSizeChange.bind(this) this._onChange = this._onChange.bind(this) } componentWillReceiveProps(props) { if (props.autoFocus) { this._textInput.focus(); } this.setState({ content: props.value }); } _maxInputHeight(input) { return input >= INPUT_MAX_HEIGHT ? INPUT_MAX_HEIGHT : input } _onContentSizeChange(event) { let update = { height: this._maxInputHeight(event.nativeEvent.contentSize.height) } this.setState(update) this.props.onHeightChanged(update) } _onChange(event) { this.setState({ content: event.nativeEvent.text }) if (Platform.OS === 'android') { this._onContentSizeChange(event) } if (this.props.onChange) { this.props.onChange({ value: event.nativeEvent.text }); } } render() { let inputCounter let addFlex, addFlexSize /* * Add counter */ if (this.props.inputLimit) { addFlex = {flexDirection: 'row', alignItems: 'flex-end' } addFlexSize = { flex: .9 } let remainder = this.props.inputLimit - this.state.content.length if (remainder < -99) { remainder = -99 } const remainderColor = remainder > 5 ? GRAY_FONT_COLOR : 'red' inputCounter = ( <Text style={ [ styles.remainder, { color: remainderColor } ] }> { remainder } </Text> ) } return ( <View style={[ styles.content, addFlex ] }> <TextInput placeholder={ this.props.placeholder } placeholderTextColor={ LIGHT_GRAY_FONT_COLOR } autoFocus={ this.props.autoFocus } onFocus={ this.props.onFocus } onBlur={ this.props.onBlur } accessible={ true } accessibilityLabel={ this.props.placeholder } multiline={ true } returnKeyType="done" ref={(r) => { this._textInput = r; }} onContentSizeChange={ this._onContentSizeChange } disableFullscreenUI={ true } textBreakStrategy={ 'highQuality' } onChange={ this._onChange.bind(this) } underlineColorAndroid='transparent' enablesReturnKeyAutomatically={true} style={ [ styles.input, { height: this.state.height + 4}, addFlexSize ] } value={ this.state.content } /> { inputCounter } </View> ) } }
client/src/research/CountChart.js
mit-teaching-systems-lab/swipe-right-for-cs
import React from 'react'; import PropTypes from 'prop-types'; import { VictoryBar, VictoryChart, VictoryTheme, VictoryAxis, VictoryLabel, VictoryGroup } from 'victory'; // Horizontal bar chart showing counts by a string key class CountChart extends React.Component { render() { const {chartTitle, countMap} = this.props; const labels = Object.keys(countMap); const dataPoints = [0].concat(labels.map(label => countMap[label])); return ( <VictoryChart theme={VictoryTheme.material} padding={{ left: 90, top: 50, right: 90, bottom: 50 }} > <VictoryLabel text={chartTitle} x={225} y={30} textAnchor="middle"/> <VictoryAxis dependentAxis tickValues={labels.map((label, i) => i + 1)} tickFormat={labels}/> <VictoryAxis/> <VictoryGroup horizontal offset={1} colorScale={["#999"]} > <VictoryBar data={dataPoints} labels={data => data.y === 0 ? '' : data.y} /> </VictoryGroup> </VictoryChart> ); } } CountChart.propTypes = { countMap: PropTypes.object.isRequired, chartTitle: PropTypes.string.isRequired }; export default CountChart;
examples/real-world/index.js
fanhc019/redux
import 'babel-core/polyfill'; import React from 'react'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import { Provider } from 'react-redux'; import { Router, Route } from 'react-router'; import configureStore from './store/configureStore'; import App from './containers/App'; import UserPage from './containers/UserPage'; import RepoPage from './containers/RepoPage'; const history = createBrowserHistory(); const store = configureStore(); React.render( <Provider store={store}> {() => <Router history={history}> <Route path="/" component={App}> <Route path="/:login/:name" component={RepoPage} /> <Route path="/:login" component={UserPage} /> </Route> </Router> } </Provider>, document.getElementById('root') );
src/components/draggable/draggableView.stories.js
philpl/rxjs-diagrams
import React from 'react' import { storiesOf } from '@kadira/storybook' import { withKnobs, number, boolean } from '@kadira/storybook-addon-knobs'; import DraggableView from './draggableView' storiesOf('DraggableView', module) .addDecorator(withKnobs) .add('Default', () => ( <DraggableView width={number('Width', 500)} height={number('Height', 50)} emissions={[ { x: 5, d: 1 }, { x: 20, d: 2 }, { x: 35, d: 2 }, { x: 60, d: 1 }, { x: 70, d: 3 } ]} completion={80} end={80} /> ))
blueocean-material-icons/src/js/components/svg-icons/image/filter-vintage.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageFilterVintage = (props) => ( <SvgIcon {...props}> <path d="M18.7 12.4c-.28-.16-.57-.29-.86-.4.29-.11.58-.24.86-.4 1.92-1.11 2.99-3.12 3-5.19-1.79-1.03-4.07-1.11-6 0-.28.16-.54.35-.78.54.05-.31.08-.63.08-.95 0-2.22-1.21-4.15-3-5.19C10.21 1.85 9 3.78 9 6c0 .32.03.64.08.95-.24-.2-.5-.39-.78-.55-1.92-1.11-4.2-1.03-6 0 0 2.07 1.07 4.08 3 5.19.28.16.57.29.86.4-.29.11-.58.24-.86.4-1.92 1.11-2.99 3.12-3 5.19 1.79 1.03 4.07 1.11 6 0 .28-.16.54-.35.78-.54-.05.32-.08.64-.08.96 0 2.22 1.21 4.15 3 5.19 1.79-1.04 3-2.97 3-5.19 0-.32-.03-.64-.08-.95.24.2.5.38.78.54 1.92 1.11 4.2 1.03 6 0-.01-2.07-1.08-4.08-3-5.19zM12 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z"/> </SvgIcon> ); ImageFilterVintage.displayName = 'ImageFilterVintage'; ImageFilterVintage.muiName = 'SvgIcon'; export default ImageFilterVintage;
front/app/app/rh-components/rh-ContentArea.js
nudoru/React-Starter-2-app
import React from 'react'; class ContentArea extends React.Component { render() { return ( <div className="content-region"> <div className="page-container"> {this.props.children} </div> </div> ); } } export default ContentArea;
docs/exam/src/StaffDetail.js
Hellfire-zmcy/web
import React from 'react'; export default class StaffDetail extends React.Component{ handlerEdit(){ let item = {}; let editTabel = React.findDOMNode(this.refs.editTabel); let sex = editTabel.querySelector('#staffEditSex'); let id = editTabel.querySelector('#staffEditId'); item.name = editTabel.querySelector('#staffEditName').value.trim(); item.age = editTabel.querySelector('#staffEditAge').value.trim(); item.descrip = editTabel.querySelector('#staffEditDescrip').value.trim(); item.sex = sex.options[sex.selectedIndex].value; item.id = id.options[id.selectedIndex].value; item.key = this.props.staffDetail.key; /* *表单验证 */ if(item.name=='' || item.age=='' || item.descrip=='') { let tips = React.findDOMNode(this.refs.DtipsUnDone); tips.style.display = 'block'; setTimeout(function(){ tips.style.display = 'none'; }, 1000); return; } //非负整数 let numReg = /^\d+$/; if(!numReg.test(item.age) || parseInt(item.age)>150) { let tips = React.findDOMNode(this.refs.DtipsUnAge); tips.style.display = 'block'; setTimeout(function(){ tips.style.display = 'none'; }, 1000); return; } this.props.editDetail(item); //此处应在返回修改成功信息后确认 let tips = React.findDOMNode(this.refs.Dtips); tips.style.display = 'block'; setTimeout(function(){ tips.style.display = 'none'; }, 1000); } handlerClose(){ this.props.closeDetail(); } componentDidUpdate(){ if(this.props.staffDetail == null){} else { let selSex = React.findDOMNode(this.refs.selSex); for(let i=0; i<selSex.options.length; i++){ if(selSex.options[i].value == this.props.staffDetail.info.sex){ selSex.options[i].selected = 'selected'; break; } } let selId = React.findDOMNode(this.refs.selId); for(let i=0; i<selId.options.length; i++) { if(selId.options[i].value == this.props.staffDetail.info.id){ selId.options[i].selected = 'selected'; break; } } } } render(){ let staffDetail = this.props.staffDetail; if(!staffDetail) return null; return ( <div className="overLay"> <h4 style={{'text-align':'center'}}>点击'完成'保存修改,点击'关闭'放弃未保存修改并退出.</h4> <hr/> <table ref="editTabel"> <tbody> <tr> <th>姓名</th> <td><input id='staffEditName' type="text" defaultValue={staffDetail.info.name}></input></td> </tr> <tr> <th>年龄</th> <td><input id='staffEditAge' type="text" defaultValue={staffDetail.info.age}></input></td> </tr> <tr> <th>性别</th> <td> <select ref='selSex' id='staffEditSex'> <option value="男">男</option> <option value="女">女</option> </select> </td> </tr> <tr> <th>身份</th> <td> <select ref="selId" id='staffEditId'> <option value="主任">主任</option> <option value="老师">老师</option> <option value="学生">学生</option> <option value="实习">实习</option> </select> </td> </tr> <tr> <th>个人描述</th> <td><textarea id='staffEditDescrip' type="text" defaultValue={staffDetail.info.descrip}></textarea></td> </tr> </tbody> </table> <p ref='Dtips' className='tips'>修改成功</p> <p ref='DtipsUnDone' className='tips'>请录入完整的人员信息</p> <p ref='DtipsUnAge' className='tips'>请录入正确的年龄</p> <button onClick={this.handlerEdit.bind(this)}>完成</button> <button onClick={this.handlerClose.bind(this)}>关闭</button> </div> ); } }
src/components/Header/Header.js
panli-com/MyApp
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; import styles from './Header.css'; import withStyles from '../../decorators/withStyles'; import Link from '../Link'; import Navigation from '../Navigation'; @withStyles(styles) class Header extends Component { render() { return ( <div className="Header"> <div className="Header-container"> <a className="Header-brand" href="/" onClick={Link.handleClick}> <img className="Header-brandImg" src={require('./logo-small.png')} width="38" height="38" alt="React" /> <span className="Header-brandTxt">Panli</span> </a> <Navigation className="Header-nav" /> <div className="Header-banner"> <h1 className="Header-bannerTitle">及时沟通</h1> <p className="Header-bannerDesc">让沟通更舒畅!</p> </div> </div> </div> ); } } export default Header;
src/svg-icons/action/android.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAndroid = (props) => ( <SvgIcon {...props}> <path d="M6 18c0 .55.45 1 1 1h1v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V19h2v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V19h1c.55 0 1-.45 1-1V8H6v10zM3.5 8C2.67 8 2 8.67 2 9.5v7c0 .83.67 1.5 1.5 1.5S5 17.33 5 16.5v-7C5 8.67 4.33 8 3.5 8zm17 0c-.83 0-1.5.67-1.5 1.5v7c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5v-7c0-.83-.67-1.5-1.5-1.5zm-4.97-5.84l1.3-1.3c.2-.2.2-.51 0-.71-.2-.2-.51-.2-.71 0l-1.48 1.48C13.85 1.23 12.95 1 12 1c-.96 0-1.86.23-2.66.63L7.85.15c-.2-.2-.51-.2-.71 0-.2.2-.2.51 0 .71l1.31 1.31C6.97 3.26 6 5.01 6 7h12c0-1.99-.97-3.75-2.47-4.84zM10 5H9V4h1v1zm5 0h-1V4h1v1z"/> </SvgIcon> ); ActionAndroid = pure(ActionAndroid); ActionAndroid.displayName = 'ActionAndroid'; ActionAndroid.muiName = 'SvgIcon'; export default ActionAndroid;
docs/src/app/components/pages/components/Stepper/CustomStepConnector.js
hwo411/material-ui
import React from 'react'; import FlatButton from 'material-ui/FlatButton'; import RaisedButton from 'material-ui/RaisedButton'; import { Step, Stepper, StepLabel, } from 'material-ui/Stepper'; import ArrowForwardIcon from 'material-ui/svg-icons/navigation/arrow-forward'; /** * It is possible to specify your own step connector by passing an element to the `connector` * prop. If you want to remove the connector, pass `null` to the `connector` prop. */ class CustomStepConnector extends React.Component { constructor(props) { super(props); this.handleNext = this.handleNext.bind(this); this.handlePrev = this.handlePrev.bind(this); } state = { stepIndex: 0, }; getStepContent(stepIndex) { switch (stepIndex) { case 0: return ( <p> {'For each ad campaign that you create, you can control how much you\'re willing to ' + 'spend on clicks and conversions, which networks and geographical locations you want ' + 'your ads to show on, and more.'} </p> ); case 1: return ( <p> {'An ad group contains one or more ads which target a shared set of keywords.'} </p> ); case 2: return ( <p> {'Try out different ad text to see what brings in the most customers, and learn ' + 'how to enhance your ads using features like ad extensions. If you run into any ' + 'problems with your ads, find out how to tell if they\'re running and how to ' + 'resolve approval issues.'} </p> ); } } handleNext() { const {stepIndex} = this.state; if (stepIndex < 2) { this.setState({stepIndex: stepIndex + 1}); } } handlePrev() { const {stepIndex} = this.state; if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}); } } render() { const {stepIndex} = this.state; return ( <div style={{width: '100%', maxWidth: 700, margin: 'auto'}}> <Stepper activeStep={stepIndex} connector={<ArrowForwardIcon />}> <Step> <StepLabel>Select campaign settings</StepLabel> </Step> <Step> <StepLabel>Create an ad group</StepLabel> </Step> <Step> <StepLabel>Create an ad</StepLabel> </Step> </Stepper> {this.getStepContent(stepIndex)} <div style={{marginTop: 24, marginBottom: 12}}> <FlatButton label="Back" disabled={stepIndex === 0} onTouchTap={this.handlePrev} style={{marginRight: 12}} /> <RaisedButton label={stepIndex === 2 ? 'Finish' : 'Next'} primary={true} onTouchTap={this.handleNext} /> </div> </div> ); } } export default CustomStepConnector;
examples/with-material-ui-next/pages/_document.js
arunoda/next.js
import React from 'react' import Document, { Head, Main, NextScript } from 'next/document' import { getContext, setContext } from '../styles/context' export default class MyDocument extends Document { static async getInitialProps (ctx) { // Reset the context for handling a new request. setContext() const page = ctx.renderPage() // Get the context with the collected side effects. const context = getContext() return { ...page, styles: <style id='jss-server-side' dangerouslySetInnerHTML={{ __html: context.sheetsRegistry.toString() }} /> } } render () { const context = getContext() return ( <html lang='en'> <Head> <title>My page</title> <meta charSet='utf-8' /> {/* Use minimum-scale=1 to enable GPU rasterization */} <meta name='viewport' content={ 'user-scalable=0, initial-scale=1, maximum-scale=1, ' + 'minimum-scale=1, width=device-width, height=device-height' } /> {/* PWA primary color */} <meta name='theme-color' content={context.theme.palette.primary[500]} /> <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto:300,400,500' /> </Head> <body> <Main /> <NextScript /> </body> </html> ) } }
src/svg-icons/device/signal-cellular-4-bar.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellular4Bar = (props) => ( <SvgIcon {...props}> <path d="M2 22h20V2z"/> </SvgIcon> ); DeviceSignalCellular4Bar = pure(DeviceSignalCellular4Bar); DeviceSignalCellular4Bar.displayName = 'DeviceSignalCellular4Bar'; DeviceSignalCellular4Bar.muiName = 'SvgIcon'; export default DeviceSignalCellular4Bar;
app/pages/search/controls/PositionControl.js
fastmonkeys/respa-ui
import React from 'react'; import PropTypes from 'prop-types'; import { createSliderWithTooltip } from 'rc-slider'; import Slider from 'rc-slider/lib/Slider'; import injectT from '../../../i18n/injectT'; import CheckboxControl from './CheckboxControl'; const TooltipSlider = createSliderWithTooltip(Slider); class PositionControl extends React.Component { static propTypes = { geolocated: PropTypes.bool, onConfirm: PropTypes.func.isRequired, onPositionSwitch: PropTypes.func.isRequired, t: PropTypes.func.isRequired, value: PropTypes.number, }; constructor(props) { super(props); this.state = { distance: this.props.value || 21000, maxDistance: 20000, step: 1000, toggled: this.props.geolocated, }; } handleToggleChange = (value) => { this.setState({ toggled: value }); this.props.onPositionSwitch(); }; handleDistanceSliderChange = (value) => { this.setState({ distance: value }); }; handleConfirm = (value) => { if (value > this.state.maxDistance) { this.props.onConfirm(''); } else { this.props.onConfirm(value); } }; distanceFormatter = (value) => { if (value > this.state.maxDistance) { return this.props.t('PositionControl.noDistanceLimit'); } return `${value / 1000} km`; }; render() { const { t, geolocated } = this.props; return ( <div className="app-PositionControl"> <CheckboxControl id="geolocation-status" label={t('PositionControl.useDistance')} labelClassName="app-SearchControlsCheckbox__label" onConfirm={this.handleToggleChange} toggleClassName="app-SearchControlsCheckbox__toggle" value={geolocated} /> {this.state.toggled && ( <TooltipSlider className="app-PositionControl__distance_slider" disabled={!this.state.toggled} max={this.state.maxDistance + this.state.step} min={this.state.step} onAfterChange={this.handleConfirm} onChange={this.handleDistanceSliderChange} step={this.state.step} tipFormatter={this.distanceFormatter} tipProps={{ overlayClassName: 'app-PositionControl__distance_slider_tooltip' }} value={this.state.distance} /> )} {this.state.toggled && ( <div> {`${t('PositionControl.maxDistance')} : ${this.distanceFormatter(this.state.distance)}`} </div> )} </div> ); } } export default injectT(PositionControl);
js/components/MessageList.js
DevHse/ClubRoom
import React, { Component } from 'react'; import { ListView, Text, Row, Image, View, Subtitle, Caption, Heading } from '@shoutem/ui'; import moment from 'moment'; const Message = ({ msg }) => ( <Row> <Image styleName="small-avatar top" source={{ uri: msg.author.avatar }} /> <View styleName="vertical"> <View styleName="horizontal space-between"> <Subtitle>{msg.author.name}</Subtitle> <Caption>{moment(msg.time).from(Date.now())}</Caption> </View> <Text styleName="multiline">{msg.text}</Text> </View> </Row> ); const MessageList = ({ messages, onLayout }) => ( <ListView data={messages} autoHideHeader={true} renderRow={msg => <Message msg={msg} />} onLayout={onLayout} /> ); export default MessageList;
stories/panelWithAddButton.stories.js
JimBarrows/Bootstrap-React-Components
import {storiesOf} from '@storybook/react' import {action} from '@storybook/addon-actions' import React from 'react' import PanelBody from '../src/panels/PanelBody' import PanelWithAddButton from '../src/panels/PanelWithAddButton' storiesOf('Panels/Add Button', module) .addDecorator((story) => <div className="container"> {story()} </div>) .add('Basic', () => <PanelWithAddButton onAddClick={action('panel with add button clicked')} id={'basic'} title={'Panel with add Button'}> <PanelBody id={'heading'}> Panel with add button </PanelBody> </PanelWithAddButton>)
src/svg-icons/action/perm-phone-msg.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPermPhoneMsg = (props) => ( <SvgIcon {...props}> <path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.58l2.2-2.21c.28-.27.36-.66.25-1.01C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM12 3v10l3-3h6V3h-9z"/> </SvgIcon> ); ActionPermPhoneMsg = pure(ActionPermPhoneMsg); ActionPermPhoneMsg.displayName = 'ActionPermPhoneMsg'; ActionPermPhoneMsg.muiName = 'SvgIcon'; export default ActionPermPhoneMsg;
packages/slate-react/src/components/editor.js
AlbertHilb/slate
import Debug from 'debug' import Portal from 'react-portal' import React from 'react' import SlateTypes from 'slate-prop-types' import Types from 'prop-types' import logger from 'slate-dev-logger' import { Stack, State } from 'slate' import EVENT_HANDLERS from '../constants/event-handlers' import AfterPlugin from '../plugins/after' import BeforePlugin from '../plugins/before' import noop from '../utils/noop' /** * Debug. * * @type {Function} */ const debug = Debug('slate:editor') /** * Plugin-related properties of the editor. * * @type {Array} */ const PLUGINS_PROPS = [ ...EVENT_HANDLERS, 'placeholder', 'placeholderClassName', 'placeholderStyle', 'plugins', 'schema', ] /** * Editor. * * @type {Component} */ class Editor extends React.Component { /** * Property types. * * @type {Object} */ static propTypes = { autoCorrect: Types.bool, autoFocus: Types.bool, className: Types.string, onBeforeChange: Types.func, onChange: Types.func, placeholder: Types.any, placeholderClassName: Types.string, placeholderStyle: Types.object, plugins: Types.array, readOnly: Types.bool, role: Types.string, schema: Types.object, spellCheck: Types.bool, state: SlateTypes.state.isRequired, style: Types.object, tabIndex: Types.number, } /** * Default properties. * * @type {Object} */ static defaultProps = { autoFocus: false, autoCorrect: true, onChange: noop, plugins: [], readOnly: false, schema: {}, spellCheck: true, } /** * When constructed, create a new `Stack` and run `onBeforeChange`. * * @param {Object} props */ constructor(props) { super(props) this.state = {} this.tmp = {} // Create a new `Stack`, omitting the `onChange` property since that has // special significance on the editor itself. const plugins = resolvePlugins(props) const stack = Stack.create({ plugins }) this.state.stack = stack // Run `onBeforeChange` on the passed-in state because we need to ensure // that it is normalized, and queue the resulting change. const change = props.state.change() stack.handle('onBeforeChange', change, this) const { state } = change this.queueChange(change) this.cacheState(state) this.state.state = state // Create a bound event handler for each event. EVENT_HANDLERS.forEach((handler) => { this[handler] = (...args) => { this.onEvent(handler, ...args) } }) if (props.onDocumentChange) { logger.deprecate('0.22.10', 'The `onDocumentChange` prop is deprecated because it led to confusing UX issues, see https://github.com/ianstormtaylor/slate/issues/614#issuecomment-327868679') } if (props.onSelectionChange) { logger.deprecate('0.22.10', 'The `onSelectionChange` prop is deprecated because it led to confusing UX issues, see https://github.com/ianstormtaylor/slate/issues/614#issuecomment-327868679') } } /** * When the `props` are updated, create a new `Stack` if necessary and run * `onBeforeChange` to ensure the state is normalized. * * @param {Object} props */ componentWillReceiveProps = (props) => { let { stack } = this.state // If any plugin-related properties will change, create a new `Stack`. for (let i = 0; i < PLUGINS_PROPS.length; i++) { const prop = PLUGINS_PROPS[i] if (props[prop] == this.props[prop]) continue const plugins = resolvePlugins(props) stack = Stack.create({ plugins }) this.setState({ stack }) } // Run `onBeforeChange` on the passed-in state because we need to ensure // that it is normalized, and queue the resulting change. const change = props.state.change() stack.handle('onBeforeChange', change, this) const { state } = change this.queueChange(change) this.cacheState(state) this.setState({ state }) } /** * When the component first mounts, flush any temporary changes. */ componentDidMount = () => { this.flushChange() } /** * When the component updates, flush any temporary change. */ componentDidUpdate = () => { this.flushChange() } /** * Cache a `state` object to be able to compare against it later. * * @param {State} state */ cacheState = (state) => { this.tmp.document = state.document this.tmp.selection = state.selection } /** * Queue a `change` object, to be able to flush it later. This is required for * when a change needs to be applied to the state, but because of the React * lifecycle we can't apply that change immediately. So we cache it here and * later can call `this.flushChange()` to flush it. * * @param {Change} change */ queueChange = (change) => { if (change.operations.length) { debug('queueChange', { change }) this.tmp.change = change } } /** * Flush a temporarily stored `change` object, for when a change needed to be * made but couldn't because of React's lifecycle. */ flushChange = () => { const { change } = this.tmp if (change) { debug('flushChange', { change }) this.props.onChange(change) delete this.tmp.change } } /** * Programmatically blur the editor. */ blur = () => { this.change(c => c.blur()) } /** * Programmatically focus the editor. */ focus = () => { this.change(c => c.focus()) } /** * Get the editor's current schema. * * @return {Schema} */ getSchema = () => { return this.state.stack.schema } /** * Get the editor's current state. * * @return {State} */ getState = () => { return this.state.state } /** * Perform a change `fn` on the editor's current state. * * @param {Function} fn */ change = (fn) => { const { state } = this.state const change = state.change() fn(change) debug('change', { change }) this.onChange(change) } /** * On event. * * @param {String} handler * @param {Mixed} ...args */ onEvent = (handler, ...args) => { const { stack, state } = this.state const change = state.change() stack.handle(handler, change, this, ...args) this.onChange(change) } /** * On change. * * @param {Change} change */ onChange = (change) => { if (State.isState(change)) { throw new Error('As of slate@0.22.0 the `editor.onChange` method must be passed a `Change` object not a `State` object.') } const { stack } = this.state stack.handle('onBeforeChange', change, this) stack.handle('onChange', change, this) const { state } = change const { document, selection } = this.tmp const { onChange, onDocumentChange, onSelectionChange } = this.props if (state == this.state.state) return debug('onChange', { change }) onChange(change) if (onDocumentChange && state.document != document) onDocumentChange(state.document, change) if (onSelectionChange && state.selection != selection) onSelectionChange(state.selection, change) } /** * Render the editor. * * @return {Element} */ render() { const { props, state } = this const { stack } = state const children = stack .renderPortal(state.state, this) .map((child, i) => <Portal key={i} isOpened>{child}</Portal>) debug('render', { props, state }) const tree = stack.render(state.state, this, { ...props, children, }) return tree } } /** * Resolve an array of plugins from `props`. * * In addition to the plugins provided in `props.plugins`, this will create * two other plugins: * * - A plugin made from the top-level `props` themselves, which are placed at * the beginning of the stack. That way, you can add a `onKeyDown` handler, * and it will override all of the existing plugins. * * - A "core" functionality plugin that handles the most basic events in * Slate, like deleting characters, splitting blocks, etc. * * @param {Object} props * @return {Array} */ function resolvePlugins(props) { // eslint-disable-next-line no-unused-vars const { state, onChange, plugins = [], ...overridePlugin } = props const beforePlugin = BeforePlugin(props) const afterPlugin = AfterPlugin(props) return [ beforePlugin, overridePlugin, ...plugins, afterPlugin ] } /** * Mix in the property types for the event handlers. */ for (let i = 0; i < EVENT_HANDLERS.length; i++) { const property = EVENT_HANDLERS[i] Editor.propTypes[property] = Types.func } /** * Export. * * @type {Component} */ export default Editor
app/javascript/mastodon/features/compose/components/navigation_bar.js
dunn/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ActionBar from './action_bar'; import Avatar from '../../../components/avatar'; import Permalink from '../../../components/permalink'; import IconButton from '../../../components/icon_button'; import { FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; export default class NavigationBar extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, onLogout: PropTypes.func.isRequired, onClose: PropTypes.func, }; render () { return ( <div className='navigation-bar'> <Permalink href={this.props.account.get('url')} to={`/accounts/${this.props.account.get('id')}`}> <span style={{ display: 'none' }}>{this.props.account.get('acct')}</span> <Avatar account={this.props.account} size={48} /> </Permalink> <div className='navigation-bar__profile'> <Permalink href={this.props.account.get('url')} to={`/accounts/${this.props.account.get('id')}`}> <strong className='navigation-bar__profile-account'>@{this.props.account.get('acct')}</strong> </Permalink> <a href='/settings/profile' className='navigation-bar__profile-edit'><FormattedMessage id='navigation_bar.edit_profile' defaultMessage='Edit profile' /></a> </div> <div className='navigation-bar__actions'> <IconButton className='close' title='' icon='close' onClick={this.props.onClose} /> <ActionBar account={this.props.account} onLogout={this.props.onLogout} /> </div> </div> ); } }
src/components/RecipeCard/RecipeCard.js
DonHansDampf/whattoeat_website
import React from 'react' import { Card, CardImage, Heading, Text } from 'rebass' const RecipeCard = (props) => { return ( <div> <Card style={{ margin: 5 }}> <CardImage src={props.image} /> <Heading level={2} size={3} > {props.title} </Heading> <Text> {props.desc} </Text> </Card> </div> ) } RecipeCard.propTypes = { image: React.PropTypes.string.isRequired, title: React.PropTypes.string.isRequired, desc: React.PropTypes.string.isRequired } export default RecipeCard
jenkins-design-language/src/js/components/material-ui/svg-icons/notification/sync-problem.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const NotificationSyncProblem = (props) => ( <SvgIcon {...props}> <path d="M3 12c0 2.21.91 4.2 2.36 5.64L3 20h6v-6l-2.24 2.24C5.68 15.15 5 13.66 5 12c0-2.61 1.67-4.83 4-5.65V4.26C5.55 5.15 3 8.27 3 12zm8 5h2v-2h-2v2zM21 4h-6v6l2.24-2.24C18.32 8.85 19 10.34 19 12c0 2.61-1.67 4.83-4 5.65v2.09c3.45-.89 6-4.01 6-7.74 0-2.21-.91-4.2-2.36-5.64L21 4zm-10 9h2V7h-2v6z"/> </SvgIcon> ); NotificationSyncProblem.displayName = 'NotificationSyncProblem'; NotificationSyncProblem.muiName = 'SvgIcon'; export default NotificationSyncProblem;
client/views/Home/index.js
shastajs/boilerplate
import React from 'react' import { Link } from 'shasta-router' import { Component, PropTypes, connect } from 'shasta' import { Flex, Box } from 'reflexbox' import { Toolbar, NavItem, Space, Text, Container, Button, Panel, PanelHeader, PanelFooter } from 'rebass' import jif from 'jif' import actions from 'core/actions' import DocumentMeta from 'react-document-meta' import UserList from './UserList' import RepoList from './RepoList' import OrgList from './OrgList' import User from './User' @connect({ count: 'counter.count', me: 'me' }) export default class HomeView extends Component { static displayName = 'HomeView' static propTypes = { count: PropTypes.number.isRequired, me: PropTypes.map.isRequired, name: PropTypes.string.isRequired } static defaultProps = { name: 'tj' } render() { return ( <Flex align="center" column auto> <DocumentMeta title="Home" /> <Box col={12}> <Toolbar> <Space auto /> { jif(this.props.me.isEmpty() , () => <NavItem is={Link} to="/login"> Sign In </NavItem> , () => <NavItem href="/auth/logout"> Sign out </NavItem> ) } </Toolbar> </Box> <Box p={2} mobile={12} tablet={6} desktop={4}> <Panel rounded> <PanelHeader>Counter</PanelHeader> <Container> <Text>Current: {this.props.count}</Text> </Container> <PanelFooter> <Flex justify="space-between" auto wrap> <Button onClick={() => actions.counter.increment()}> Increment </Button> <Button onClick={() => actions.counter.decrement()}> Decrement </Button> <Button onClick={() => actions.counter.reset()}> Reset </Button> </Flex> </PanelFooter> </Panel> </Box> <Box p={2} mobile={12} tablet={6} desktop={4}> <User name={this.props.name} /> </Box> <Flex align="flex-start" auto> <Box p={2} mobile={12} tablet={4} desktop={4}> <OrgList name={this.props.name}/> </Box> <Box p={2} mobile={12} tablet={4} desktop={4}> <RepoList name={this.props.name}/> </Box> <Box p={2} mobile={12} tablet={4} desktop={4}> <UserList/> </Box> </Flex> <Flex align="center" auto> <Link to="/about">Go To About View</Link> </Flex> </Flex> ) } }
src/component/SectionTabs.js
bertrandmartel/caipy-dashboard
//react import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import AppBar from 'material-ui/AppBar'; import Tabs, { Tab } from 'material-ui/Tabs'; import EpgDataSet from './EpgDataSet.js'; import CaipyDataSet from './CaipyDataSet.js'; import TimelineContainer from './Timeline.js'; import TimelineIcon from 'material-ui-icons/Timeline'; import StorageIcon from 'material-ui-icons/Storage'; function TabContainer(props) { return <div style={{ }}>{props.children}</div>; } TabContainer.propTypes = { children: PropTypes.node.isRequired, }; const styles = theme => ({ root: { flexGrow: 1, marginTop: 0, backgroundColor: theme.palette.background.paper, }, tabRoot: { backgroundColor: theme.palette.background.paper, }, hidden : { display: 'none' } }); /** * Tab view showing the dataset & the timeline */ class SectionTabs extends Component { caipyDataSet = {}; epgDataSet = {}; constructor(props) { super(props); this.updatePage = this.updatePage.bind(this); this.playRolling = this.playRolling.bind(this); this.pauseRolling = this.pauseRolling.bind(this); } /** * Update selected page according to start date of selected item * * @param {Date} date start date of selected item * @param {String} channel channel tab to update */ updatePage(date, channel) { } playRolling() { this.props.onPlayRolling(); } pauseRolling() { this.props.onPauseRolling(); } state = { value: 0, updatePageDate: null, updateChannel: null }; handleChange = (event, value) => { this.setState({ value }); }; render() { const { classes } = this.props; const { value } = this.state; const profile = { tab1: (value === 0), tab2: (value === 1), tab3: (value === 2), } return (<div className={classes.root}> <AppBar position="static"> <Tabs value={value} onChange={this.handleChange} indicatorColor="accent" textColor="accent" className={classes.tabRoot} > <Tab icon={<TimelineIcon />} label="timeline" /> <Tab icon={<StorageIcon />} label="event dataset" /> <Tab icon={<StorageIcon />} label="EPG dataset" /> </Tabs> </AppBar> <div className={profile.tab1 ? "" : classes.hidden}> <TabContainer > <div className={this.props.ready ? "" : "hidden"}> <TimelineContainer key={this.props.items.channelName} channel={this.props.items.channelName} data={this.props.items} caipyData={this.props.caipyData} epgData={this.props.epgData} onUpdatePage={this.updatePage} options={this.props.options} actionType={this.props.actionType} settings={this.props.settings} onPlayRolling={this.playRolling} onPauseRolling={this.pauseRolling} onSetStartOverChart={this.props.onSetStartOverChart} keepCurrentWindow={this.props.keepCurrentWindow} onOpenFlowChart={this.props.onOpenFlowChart} onUpdateOptions={this.props.onUpdateOptions} overrideOptions={this.props.overrideOptions} startover={this.props.startover} /> </div> </TabContainer> </div> <div className={profile.tab2 ? "" : classes.hidden}> <TabContainer> <div className={this.props.ready ? "" : "hidden"}> { this.props.caipyData.map(function(value, index){ return ( <CaipyDataSet key={value.name} name={value.name} rows={value.rows} length={value.rows.length} perPage={50} ref={instance => { this.caipyDataSet[value.name] = instance; }} /> ); },this) } </div> </TabContainer> </div> <div className={profile.tab3 ? "" : classes.hidden}> <TabContainer> <div className={this.props.ready ? "" : "hidden"}> <EpgDataSet key={this.props.epgData.name} name={this.props.epgData.name} rows={this.props.epgData.rows} perPage={50} ref={instance => { this.epgDataSet[this.props.epgData.name] = instance; }} /> </div> </TabContainer> </div> </div>) } } SectionTabs.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(SectionTabs);
app/components/ProductItem/index.js
Luandro-com/repsparta-web-app
/** * * ProductItem * */ import React from 'react'; import Radium from 'radium'; import SelectField from 'material-ui/SelectField'; import MenuItem from 'material-ui/MenuItem'; import FlatButton from 'material-ui/FlatButton'; import styles from './styles.css'; const sty = { select: { background: '#fff', width: '75%', paddingLeft: 15, }, underline: { display: 'none', }, label: { color: '#0D1332', }, icon: { fill: '#0D1332', }, selectFull: { background: '#fff', width: '80%', padding: '31px 15px', borderRadius: 35, textAlign: 'center', }, labelFull: { top: -24, paddingRight: 88, color: '#0D1332', }, iconFull: { fill: '#0D1332', top: -18, width: 40, height: 40, }, counter: { borderRadius: 0, minWidth: 25, }, }; function ProductItem({ imgLoad, imgLoaded, escription, featured_src, id, type, stock_quantity, price_html, short_description, title, variations, inc, dec, change, selected, counter }) { const fullWidth = window.innerWidth > 1023; function createMarkup() { return { __html: price_html }; } return ( <div className={styles.wrapper}> <div className={styles.id}> <div className={imgLoaded ? styles.img : styles.placeHolder}> <img className={imgLoaded ? '' : styles.disabled} src={featured_src} onLoad={(e) => imgLoad(e)} alt={title} /> </div> <h4 className={styles.title}>{title}</h4> </div> <div className={styles.info}> {type === 'variable' && <SelectField value={selected} onChange={(e, index, value) => change(e, index, value)} iconStyle={fullWidth ? sty.iconFull : sty.icon} labelStyle={fullWidth ? sty.labelFull : sty.label} underlineStyle={sty.underline} style={fullWidth ? sty.selectFull : sty.select} > <MenuItem value={1} primaryText="República..." /> {variations.map((item, key) => <MenuItem value={item.attributes[0].option} key={key} primaryText={item.attributes[0].option} /> )} </SelectField> } {type === 'simple' && stock_quantity > 0 && <div className={styles.simple_container}> <div className={styles.simple_product}> {stock_quantity - counter} <span className={styles.restantes}>restantes</span> </div> </div> } {selected !== 1 && <div className={styles.stock}> { variations .filter((item) => item.attributes[0].option === selected) .map((res, key) => <span key={key} className={styles.stock_num}>{res.stock_quantity - counter}</span>) } <span className={styles.stock_text}>disponíveis</span> </div> } <div className={styles.counter}> <span className={styles.num}>{counter}</span> <div className={styles.buttons}> <FlatButton backgroundColor="#EC1D24" label="+" hoverColor="#fff" style={sty.counter} onTouchTap={inc} /> <FlatButton backgroundColor="#FFCA05" label="-" hoverColor="#fff" style={sty.counter} onTouchTap={dec} /> </div> </div> </div> <h3 className={styles.price} dangerouslySetInnerHTML={createMarkup()} /> </div> ); } export default Radium(ProductItem);
src/svg-icons/device/battery-50.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBattery50 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V13h10V5.33z"/><path d="M7 13v7.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V13H7z"/> </SvgIcon> ); DeviceBattery50 = pure(DeviceBattery50); DeviceBattery50.displayName = 'DeviceBattery50'; DeviceBattery50.muiName = 'SvgIcon'; export default DeviceBattery50;
tests/format/flow-repo/react/createElement_string.js
prettier/prettier
// @flow import React from 'react'; class Bar extends React.Component {} class Foo extends React.Component { render() { const Cmp = Math.random() < 0.5 ? 'div' : Bar; return (<Cmp/>); } }
common/routes/Posts/components/Clients.js
noentiger/react-portfolio
import React from 'react'; import { StyleSheet, css } from 'aphrodite'; import { Color } from '../../../style'; const styles = StyleSheet.create({ container: { margin: '4em auto', }, title: { color: Color.black, fontWeight: 900, fontSize: 56, maxWidth: 600, }, item: { color: Color.black, fontWeight: 300, display: 'inline-block', padding: '10px 5px', wordBreak: 'break-all', '@media (min-width: 320px) and (max-width: 1224px)': { fontSize: 21, }, '@media (min-width: 1224px)': { fontSize: 36, }, }, }); const Clients = () => ( <div className={css(styles.container)}> <h1 className={css(styles.title)}>{'Some of the clients I\'ve worked with'}</h1> { /* eslint-disable no-use-before-define */ clientList.map((client, i) => <h4 key={client.name} className={css(styles.item)}>{client.name} {i !== clientList.length - 1 && '/'}</h4>, ) /* eslint-enable no-use-before-define */ } </div> ); const clientList = [ { name: 'Arla', }, { name: 'Skånemejerier', }, { name: 'SATS Elixia', }, { name: 'Aller Media', }, { name: 'Apollo', }, { name: 'PwC', }, { name: 'C Sports', }, { name: 'Choice Hotels', }, { name: 'Blocket', }, { name: 'Hästens', }, { name: "McDonald's", }, { name: 'Intersport', }, { name: 'Opel', }, { name: 'Pepsi', }, { name: 'Dressmann', }, { name: 'SVT', }, { name: 'Tele2', }, { name: 'Aftenposten', }, { name: 'Pizza Hut', }, { name: 'Goldwell', }, { name: 'Svensk Fastighetsförmedling', }, { name: 'Trocadero', }, { name: 'Babyshop', }, { name: 'Happy Pancake', }, { name: 'Aunt Mabels', }, { name: 'First Hotels', }, { name: 'Proteinfabrikken', }, { name: 'Peppes Pizza', }, { name: 'Sparebank1', }, { name: 'Actic Träning', }, { name: 'Physio Control', }, { name: 'VG', }, { name: 'Norges Golfforbund', }, { name: 'Helsingborgs IF', }, { name: 'Eika', }, { name: 'Amesto', }, { name: 'Länsförsäkringar Stockholm', }, { name: 'Humac', }, { name: 'Yellow Pages', }, { name: 'Godfisk', }, { name: 'Radio P4', }, { name: 'Visit Sweden', }, { name: 'Stamina', }, ]; export default Clients;
src/components/Main.js
liyongfen/todoList
"use strict" import '../styles/main.css'; import 'antd/dist/antd.css'; import React from 'react'; import ReactDOM from 'react-dom'; import {connect} from 'react-redux'; import propTypes from 'prop-types'; import {Icon,notification,Row,Col,Modal} from 'antd'; import Header from './Header.js'; import Footer from './Footer.js'; import Todo from './Todo.js'; import TodoModel from './TodoModel.js'; import Search from './Search.js'; import TodoLeft from './TodoLeft.js'; import TimeUtils from "../core/utils/TimeUtils.js" import {loadInitialDatas,loadRemoveOneTodo,loadAddOneTodo,loadEditOneTodo,loadSearchTodos} from '../actions/mainaction'; var mapStateToProps= function(state){ return{ todoListDatas:state.todoListDatas, status:state.status } } class App extends React.Component{ constructor(props){ super(props); this.state = {data:{newKey:'',visible:false,title:0, todo:{id:0,title:'',status:'0',desc:'',type:'schedule',importance:'0'} } }; } _DelTodo(e,id){ loadRemoveOneTodo(this.props.dispatch,"",id); var title = "删除失败!"; if(this.props.status==1){ title = "删除成功!"; } const modal = Modal.success({ title: title }); setTimeout(() => modal.destroy(), 1000); } _EditTodo(e,todo){ this.state.data.todo = todo; this.state.data.visible = true; this.state.data.title = 0; this.setState({data:this.state.data}); } _EditModal(e,todo){ this.state.data.visible = false; this.setState({data:this.state.data}); loadEditOneTodo(this.props.dispatch,"",todo); var title = "修改失败!"; if(this.props.status==1){ title = "修改成功!"; } const modal = Modal.success({ title: title }); setTimeout(() => modal.destroy(), 1000); } _getAddModel(e){ this.state.data.title = 1; this.state.data.visible = true; this.state.data.newKey = TimeUtils.getCurrentTime('-'); this.state.data.todo = {id:0,title:'',desc:'',status:'0',type:'schedule',importance:'0',time:"2017-06-12 12:12:12"} this.setState({data:this.state.data}); } _AddTodo(e,addtodo){ this.state.data.visible = false; this.setState({data:this.state.data}); loadAddOneTodo(this.props.dispatch,"",addtodo); var title = "添加失败!"; if(this.props.status==1){ title = "添加成功!"; } const modal = Modal.success({ title: title }); setTimeout(() => modal.destroy(), 1000); } _SearchTodoLists(e,searchdata){ loadSearchTodos(this.props.dispatch,"",searchdata); } componentDidMount(){ loadInitialDatas(this.props.dispatch,""); } render(){ var {todoListDatas} = this.props; return ( <div className="content"> <Header /> <Search _getAddModel={this._getAddModel.bind(this)} _SearchTodoLists={this._SearchTodoLists.bind(this)}/> <div className="main"> <Row> <Col span={10}> <TodoLeft /> </Col> <Col span={14}> <Todo todoListDatas={todoListDatas} _DelTodo={this._DelTodo.bind(this)} _EditTodo={this._EditTodo.bind(this)} /> </Col> </Row> </div> <TodoModel data={this.state.data} _AddTodo={this._AddTodo.bind(this)} _EditModal={this._EditModal.bind(this)}/> <Footer /> </div> ); } } App.propTypes = { filterData:propTypes.array, status:propTypes.number } export default connect(mapStateToProps)(App);
examples/tex/js/components/TeXEditorExample.js
brookslyrette/draft-js
/** * Copyright (c) 2013-present, Facebook, Inc. All rights reserved. * * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; import Draft from 'draft-js'; import {Map} from 'immutable'; import React from 'react'; import TeXBlock from './TeXBlock'; import {content} from '../data/content'; import {insertTeXBlock} from '../modifiers/insertTeXBlock'; import {removeTeXBlock} from '../modifiers/removeTeXBlock'; var {ContentState, Editor, EditorState, RichUtils} = Draft; export default class TeXEditorExample extends React.Component { constructor(props) { super(props); const contentState = ContentState.createFromBlockArray(content); this.state = { editorState: EditorState.createWithContent(contentState), liveTeXEdits: Map(), }; this._blockRenderer = (block) => { if (block.getType() === 'atomic') { return { component: TeXBlock, editable: false, props: { onStartEdit: (blockKey) => { var {liveTeXEdits} = this.state; this.setState({liveTeXEdits: liveTeXEdits.set(blockKey, true)}); }, onFinishEdit: (blockKey) => { var {liveTeXEdits} = this.state; this.setState({liveTeXEdits: liveTeXEdits.remove(blockKey)}); }, onRemove: (blockKey) => this._removeTeX(blockKey), }, }; } return null; }; this._focus = () => this.refs.editor.focus(); this._onChange = (editorState) => this.setState({editorState}); this._handleKeyCommand = command => { var {editorState} = this.state; var newState = RichUtils.handleKeyCommand(editorState, command); if (newState) { this._onChange(newState); return true; } return false; }; this._removeTeX = (blockKey) => { var {editorState, liveTeXEdits} = this.state; this.setState({ liveTeXEdits: liveTeXEdits.remove(blockKey), editorState: removeTeXBlock(editorState, blockKey), }); }; this._insertTeX = () => { this.setState({ liveTeXEdits: Map(), editorState: insertTeXBlock(this.state.editorState), }); }; } /** * While editing TeX, set the Draft editor to read-only. This allows us to * have a textarea within the DOM. */ render() { return ( <div className="TexEditor-container"> <div className="TeXEditor-root"> <div className="TeXEditor-editor" onClick={this._focus}> <Editor blockRendererFn={this._blockRenderer} editorState={this.state.editorState} handleKeyCommand={this._handleKeyCommand} onChange={this._onChange} placeholder="Start a document..." readOnly={this.state.liveTeXEdits.count()} ref="editor" spellCheck={true} /> </div> </div> <button onClick={this._insertTeX} className="TeXEditor-insert"> {'Insert new TeX'} </button> </div> ); } }
src/components/Settings/Speech/Speech.component.js
amberleyromo/cboard
import React from 'react'; import { FormattedMessage } from 'react-intl'; import { withStyles } from 'material-ui/styles'; import Button from 'material-ui/Button'; import Paper from 'material-ui/Paper'; import List, { ListItem, ListItemText } from 'material-ui/List'; import Menu, { MenuItem } from 'material-ui/Menu'; import { LinearProgress } from 'material-ui/Progress'; import ArrowDownwardIcon from 'material-ui-icons/ArrowDownward'; import ArrowUpwardIcon from 'material-ui-icons/ArrowUpward'; import FastForwardIcon from 'material-ui-icons/FastForward'; import FastRewindIcon from 'material-ui-icons/FastRewind'; import FullScreenDialog from '../../FullScreenDialog'; import { MIN_PITCH, MAX_PITCH, INCREMENT_PITCH, MIN_RATE, MAX_RATE, INCREMENT_RATE } from './Speech.constants'; import messages from './Speech.messages'; const styles = theme => ({ container: { display: 'flex', position: 'relative', justifyContent: 'center' }, icon: { marginLeft: 3, marginRight: 3, width: 20 }, progress: { paddingLeft: 2, paddingRight: 2, maxWidth: '50%', minWidth: '20%', marginTop: 20 } }); const getProgressPercent = (value, min, max) => Math.round((value - min) / (max - min) * 100.0); const SpeechComponent = ({ anchorEl, classes, handleChangePitch, handleChangeRate, handleClickListItem, handleMenuItemClick, handleVoiceRequestClose, intl, langVoices, onRequestClose, open, pitch, rate, selectedVoiceIndex, voiceOpen, voiceURI }) => ( <div className="Speech"> <FullScreenDialog open={open} title={<FormattedMessage {...messages.speech} />} onRequestClose={onRequestClose} > <Paper> <List> <ListItem button divider aria-haspopup="true" aria-controls="voice-menu" aria-label="Voice" onClick={handleClickListItem} > <ListItemText primary={<FormattedMessage {...messages.voice} />} secondary={voiceURI} /> </ListItem> <ListItem divider aria-label={intl.formatMessage(messages.pitch)}> <ListItemText primary={<FormattedMessage {...messages.pitch} />} secondary={<FormattedMessage {...messages.pitchDescription} />} /> <div className={classes.container}> <Button color="primary" aria-label={intl.formatMessage(messages.lower)} disabled={pitch <= MIN_PITCH} onClick={() => handleChangePitch(pitch - INCREMENT_PITCH)} > <ArrowDownwardIcon className={classes.icon} /> </Button> <div className={classes.progress}> <LinearProgress variant="determinate" value={getProgressPercent(pitch, MIN_PITCH, MAX_PITCH)} /> </div> <Button color="primary" aria-label={intl.formatMessage(messages.higher)} disabled={pitch >= MAX_PITCH} onClick={() => handleChangePitch(pitch + INCREMENT_PITCH)} > <ArrowUpwardIcon className={classes.icon} /> </Button> </div> </ListItem> <ListItem aria-label={intl.formatMessage(messages.rate)}> <ListItemText primary={<FormattedMessage {...messages.rate} />} secondary={<FormattedMessage {...messages.rateDescription} />} /> <div className={classes.container}> <Button color="primary" aria-label={intl.formatMessage(messages.slower)} disabled={rate <= MIN_RATE} onClick={() => handleChangeRate(rate - INCREMENT_RATE)} > <FastRewindIcon className={classes.icon} /> </Button> <div className={classes.progress}> <LinearProgress variant="determinate" value={getProgressPercent(rate, MIN_RATE, MAX_RATE)} /> </div> <Button color="primary" aria-label={intl.formatMessage(messages.faster)} disabled={rate >= MAX_RATE} onClick={() => handleChangeRate(rate + INCREMENT_RATE)} > <FastForwardIcon className={classes.icon} /> </Button> </div> </ListItem> </List> </Paper> <Menu id="voice-menu" anchorEl={anchorEl} open={voiceOpen} onClose={handleVoiceRequestClose} > {langVoices.map((voice, index) => ( <MenuItem key={index} selected={index === selectedVoiceIndex} onClick={() => handleMenuItemClick(voice, index)} > {voice.name} </MenuItem> ))} </Menu> </FullScreenDialog> </div> ); export default withStyles(styles)(SpeechComponent);
src/containers/DevTools/DevTools.js
Anshul-HL/blitz-vihanga
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-Q"> <LogMonitor /> </DockMonitor> );
ReactTest/app/component/Popular.js
OlesiaBelmega/GoIT-Studing
import React from 'react'; import PropTypes from 'prop-types'; import api from '../ultils/api'; import Loading from './Loading' function SelectLanguage(props) { let languages = ['All', 'JavaScript', 'Ruby', 'Java', 'CSS', 'Python']; return ( <ul className="languages"> {languages.map((lang) => { return ( <li style={lang === props.selectedLanguage ? {color: '#d0021b'} : null} onClick={props.onSelect.bind(null, lang)} key={lang}> {lang} </li> ); })} </ul> ); } function RepoGrid(props) { return( <ul className="popular-list"> {props.repos.map((repo, index) => { return ( <li key={repo.name} className="popular-item"> <div className="popular-rank">#{index + 1}</div> <ul className="space-list-items"> <li> <img className="avatar" src={repo.owner.avatar_url} alt={`Avatar for ${repo.owner.login}`} /> </li> <li><a href={repo.html_url}>{repo.name}</a></li> <li>@{repo.owner.login}</li> <li>{repo.stargazers_count} stars</li> </ul> </li> ) })} </ul> ) } RepoGrid.popTypes = { repos: PropTypes.array.isRequired }; SelectLanguage.propTypes = { selectedLanguage: PropTypes.string.isRequired, onSelect: PropTypes.func.isRequired, }; class Popular extends React.Component { constructor(props) { super(props); this.state = { selectedLanguage: 'All', repos: null }; this.updateLanguage = this.updateLanguage.bind(this); }; componentDidMount() { this.updateLanguage(this.state.selectedLanguage) } updateLanguage(lang) { this.setState(function() { return { selectedLanguage: lang, repos: null }; }); api.fetchPopularRepos(lang) .then((repos) => { this.setState(() => { return { repos: repos } }) }) }; render() { return ( <div> <SelectLanguage selectedLanguage={this.state.selectedLanguage} onSelect={this.updateLanguage}/> {!this.state.repos ? <Loading /> : <RepoGrid repos={this.state.repos} />} </div> ); } } export default Popular;
Skins/VetoccitanT3/Js/React/react-tooltip-master/example/src/index.js
ENG-SYSTEMS/Kob-Eye
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
src/index.js
SteveHoggNZ/react-transform-boilerplate-tape-tests
import React from 'react'; import { render } from 'react-dom'; import { App } from './App'; import { NICE, SUPER_NICE, COUNTERS } from './colors'; render(<App counters={COUNTERS}/>, document.getElementById('root'));
src/containers/pages/welcome/sections/use-cases/create-deck.js
vFujin/HearthLounge
import React from 'react'; import CardInText from "../../../../../components/card/card-in-text"; import {Link} from "react-router-dom"; import Icon from "../../../../../components/icon"; const theramore = <CardInText label="Theramore" imgSrc="http://media.services.zam.com/v1/media/byName/hs/cards/enus/GVG_015.png" rarity="mage"/>; const jaina = <CardInText label="Jaina Proudmoore" imgSrc="http://media.services.zam.com/v1/media/byName/hs/cards/enus/HERO_08.png" rarity="mage"/>; const dreadlords = <CardInText label="Dreadlords" imgSrc="http://media.services.zam.com/v1/media/byName/hs/cards/enus/HERO_08.png" rarity="warlock"/>; const garrosh = <CardInText label="Garrosh Hellscream" imgSrc="http://media.services.zam.com/v1/media/byName/hs/cards/enus/HERO_01.png" rarity="warrior"/>; const pirate = <CardInText label="Pirate" imgSrc="http://media.services.zam.com/v1/media/byName/hs/cards/enus/CFM_325.png" rarity="common"/>; const iceblock = <CardInText label="Ice Block" imgSrc="http://media.services.zam.com/v1/media/byName/hs/cards/enus/EX1_295.png" rarity="karazhan"/>; const waterElemental = <CardInText label="water elementals" imgSrc="http://media.services.zam.com/v1/media/byName/hs/cards/enus/CS2_033.png" rarity="common"/>; const CaseCreateDeck = () => ( <div> <span className="hero mage in-text">Jaina Proudmoore</span> <p>Azeroth went silent. After sudden disappearance of {theramore} from the planet {jaina} went into full mad-mode. Even {dreadlords} weren't THAT angry at their madness peak.</p> <p>The amount of hate Mage had towards {garrosh} was inconceivable. The {pirate} Deck was so devastating every time she tried to face it with her Fatigue deck. {iceblock} was always late to the party.</p> <p>To the rescue came one of {jaina}'s {waterElemental} suggesting <Link to="/create-deck">HearthLounge's tool - the ultimate Deck Creation</Link>.</p> <p>With <Link to="/create-deck">HearthLounge's Deck Creation tool</Link> {jaina} discovered new possibilities and finally managed to defeat the big bully Warrior.</p> <p>Some say {garrosh} did nothing wrong to this day.</p> <Icon name="create-deck"/> </div> ); export default CaseCreateDeck;
src/popup/components/Card/index.js
victorvoid/fluany
/** * @fileOverview The card component to show and edit card(Front & Back) * @name index.js<Card> * @license GNU General Public License v3.0 */ import React from 'react' import PropTypes from 'prop-types' import * as translator from 'shared/constants/internacionalization' import CardEdit from './CardEdit' import TooltipCard from './TooltipCard' import isEmpty from 'ramda/src/isEmpty' import isNil from 'ramda/src/isNil' import { connect } from 'react-redux' import { isEditingCard, removeCard, allNoEditingCard } from 'actions/pack' import { changeCard } from 'actions/flags' import { getIndexThingById } from 'reducers/stateManipulate' import { getInLocal } from 'store/LocalStore' export const Card = ({ onChangeCard, onAllNoEditingCard, onEditingCard, onRemoveCard, packs, card, indexOfPack, packageid, cardEditing }) => { let listItem = '' const indexOfCard = getIndexThingById(packs[indexOfPack].cards, card.id) const handleClickCard = (e) => { onAllNoEditingCard(packageid) listItem.style.transform = `translateX(-${listItem.getBoundingClientRect().left - 25}px)` onEditingCard(!card.isEditing, 'isEditing', packageid, indexOfCard) onChangeCard({front: null, back: null}) } const handleRemoveCard = (e) => { e.stopPropagation() onRemoveCard(packageid, indexOfCard) } const handleSaveCard = (e) => { e.stopPropagation() // if is empty, you don't save it :( if ((isEmpty(cardEditing.front) || isEmpty(cardEditing.back)) || (card.isCreating && isNil(cardEditing.front) && isNil(cardEditing.back))) { return } if (!isNil(cardEditing.front)) { onEditingCard(cardEditing.front, 'front', packageid, indexOfCard) } if (!isNil(cardEditing.back)) { onEditingCard(cardEditing.back, 'back', packageid, indexOfCard) } handleClickCard() getInLocal('openInPackage').then(data => { // when is clicked in save when is selected text, close window to continue the navigation setTimeout(() => { window.close() }, 1500) }) } const handleCancelCard = (e) => { handleClickCard() if (card.isCreating && isEmpty(card.front) && isEmpty(card.back)) { onRemoveCard(packageid, indexOfCard) onEditingCard(false, 'isCreating', packageid, indexOfCard) } } const cardEditProps = { packs, indexOfPack, indexOfCard, packageid, cardEditing, onChangeCard } return ( <li className={`card-item ${card.isEditing ? 'isEditing' : 'no-editing'}`} ref={(e) => { listItem = e }}> <a href="#" onClick={handleClickCard}> <CardEdit {...cardEditProps} /> <div className={`card-item-block color-${card.colorID}`}> <button className='btn-delete' onClick={handleCancelCard}> <span>{translator.CARD_CANCEL}</span> </button> <button className='btn-save' onClick={handleSaveCard}> <svg className='save-icon'> <use xlinkHref='#icon-correct' /> </svg> <span>{translator.CARD_SAVE}</span> </button> <TooltipCard handleOnDelete={handleRemoveCard} color={card.colorID} back={card.back} /> <p className='card-item--flash card-item--count'>{translator.CARD_FRONT_LABEL}</p> <p className='card-item--count'>{ card.front }</p> </div> </a> </li> ) } const mapStateToProps = ( state ) => { return { cardEditing: state.flags.cardEditing } } function mapDispatchToProps(dispatch) { return { onChangeCard: (c) => dispatch(changeCard(c)), onAllNoEditingCard: (packid) => dispatch(allNoEditingCard(packid)), onEditingCard: (...props) => dispatch(isEditingCard(...props)), onRemoveCard: (...props) => dispatch(removeCard(...props)) } } const { func, number, array, object } = PropTypes /** * PropTypes * @property {Function} onChangeCard A function to handler the changes of the card * @property {Function} onAllNoEditingCard A action to close all cards that is being edited * @property {Function} onEditingCard A action to change a prop in card object (front, back, isEditing, etc) * @property {Function} onRemoveCard A action to remove a specific card * @property {Object} card All cards of specific package * @property {Array} packs All packages in store * @property {Number} indexOfPack The package position(index) * @property {Object} cardEditing The object of the card is being changed */ Card.propTypes = { onChangeCard: func.isRequired, onAllNoEditingCard: func.isRequired, onEditingCard: func.isRequired, onRemoveCard: func.isRequired, card: object.isRequired, packs: array.isRequired, indexOfPack: number.isRequired, cardEditing: object.isRequired } export default connect(mapStateToProps, mapDispatchToProps)(Card)
front-end/src/components/CommentCard/CommentCard.js
mkalpana/km-react-reddit-clone
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import './CommentCard.css'; import { VoteScore } from '../index'; import DisplayComment from './DisplayComment'; import EditCommentForm from './EditCommentForm'; class CommentCard extends Component { state = { showEditForm: false, }; render() { const { timestamp, body, author, voteScore, onUpVote, onDownVote, onEditComment, onDeleteComment, } = this.props; const { showEditForm } = this.state; return ( <div className="CommentCard-container"> <VoteScore score={voteScore} onUpVote={onUpVote} onDownVote={onDownVote} /> { showEditForm ? ( <EditCommentForm initialValues={{ author: author, body: body }} onSubmitSuccess={() => this.setState({ showEditForm: false })} onSubmit={onEditComment} /> ) : ( <DisplayComment timestamp={timestamp} body={body} author={author} onEdit={() => this.setState({ showEditForm: true })} onDelete={onDeleteComment} /> ) } </div> ); } } CommentCard.propTypes = { timestamp: PropTypes.number, body: PropTypes.string, author: PropTypes.string, category: PropTypes.string, voteScore: PropTypes.number, onUpVote: PropTypes.func, onDownVote: PropTypes.func, onDeleteComment: PropTypes.func, onEditComment: PropTypes.func, }; export default CommentCard;
examples/custom-menu/app.js
thomasboyt/react-autocomplete
import React from 'react' import Autocomplete from '../../lib/index' import { getStates, matchStateToTerm, sortStates, styles, fakeRequest } from '../utils' let App = React.createClass({ getInitialState () { return { unitedStates: getStates(), loading: false } }, render () { return ( <div> <h1>Custom Menu</h1> <p> While Autocomplete ships with a decent looking menu, you can control the look as well as the rendering of it. In this case we put headers for each letter of the alphabet. </p> <Autocomplete items={this.state.unitedStates} getItemValue={(item) => item.name} onSelect={() => this.setState({ unitedStates: [] }) } onChange={(event, value) => { this.setState({loading: true}) fakeRequest(value, (items) => { this.setState({ unitedStates: items, loading: false }) }) }} renderItem={(item, isHighlighted) => ( <div style={isHighlighted ? styles.highlightedItem : styles.item} key={item.abbr} id={item.abbr} >{item.name}</div> )} renderMenu={(items, value, style) => ( <div style={{...styles.menu, ...style}}> {value === '' ? ( <div style={{padding: 6}}>Type of the name of a United State</div> ) : this.state.loading ? ( <div style={{padding: 6}}>Loading...</div> ) : items.length === 0 ? ( <div style={{padding: 6}}>No matches for {value}</div> ) : this.renderItems(items)} </div> )} /> </div> ) }, renderItems (items) { console.log(items) return items.map((item, index) => { var text = item.props.children if (index === 0 || items[index - 1].props.children.charAt(0) !== text.charAt(0)) { var style = { background: '#eee', color: '#454545', padding: '2px 6px', fontWeight: 'bold' } return [<div style={style}>{text.charAt(0)}</div>, item] } else { return item } }) } }) React.render(<App/>, document.getElementById('container'))
src/components/ReportModals/FinancialTransactionsReportModal.js
folio-org/ui-users
import React from 'react'; import PropTypes from 'prop-types'; import moment from 'moment-timezone'; import { Field } from 'react-final-form'; import { isEmpty } from 'lodash'; import { FormattedMessage, injectIntl, } from 'react-intl'; import stripesFinalForm from '@folio/stripes/final-form'; import { Modal, Button, Row, Col, Datepicker, ModalFooter, MultiSelection, Select, } from '@folio/stripes/components'; import { DATE_FORMAT } from '../../constants'; import css from './ReportModal.css'; export const validate = (options) => { const errors = {}; const { startDate, endDate, feeFineOwner } = options; if (isEmpty(startDate) && isEmpty(endDate)) { errors.startDate = <FormattedMessage id="ui-users.reports.cash.drawer.report.startDate.error" />; } if (isEmpty(startDate) && !isEmpty(endDate)) { errors.startDate = <FormattedMessage id="ui-users.reports.cash.drawer.report.endDateWithoutStart.error" />; } if ((!isEmpty(startDate) && !isEmpty(endDate)) && (moment(startDate).isAfter(moment(endDate)))) { errors.endDate = <FormattedMessage id="ui-users.reports.cash.drawer.report.endDate.error" />; } if (!feeFineOwner) { errors.feeFineOwner = <FormattedMessage id="ui-users.reports.financial.trans.modal.owners.error" />; } return errors; }; const FinancialTransactionsReportModal = (props) => { const { valid } = props.form.getState(); const { values: { feeFineOwner: ownerValue = '' }, owners, } = props; const parseDate = (date) => (date ? moment.tz(date, props.timezone).format(DATE_FORMAT) : date); const formattedOwners = owners.map(({ id, owner }) => ({ value: id, label: owner, })); const selectedServicePoint = owners?.find(({ id }) => id === ownerValue) ?? {}; const formattedServicePoints = selectedServicePoint?.servicePointOwner?.map(({ value, label }) => ({ value, label, })) ?? []; const onChangeOwner = (feeFineOwner) => { const { form: { change } } = props; change('feeFineOwner', feeFineOwner); change('servicePoint', []); }; const footer = ( <ModalFooter> <Button disabled={!valid} marginBottom0 buttonStyle="primary" onClick={props.form.submit} > <FormattedMessage id="ui-users.saveAndClose" /> </Button> <Button marginBottom0 buttonStyle="default" onClick={props.onClose} > <FormattedMessage id="ui-users.cancel" /> </Button> </ModalFooter> ); return ( <Modal data-test-financial-transactions-report-modal id="financial-transactions-report-modal" size="small" footer={footer} dismissible open label={props.label} onClose={props.onClose} > <form className={css.content} onSubmit={props.handleSubmit} > <Row> <Col xs={6}> <Field label={<FormattedMessage id="ui-users.reports.refunds.modal.startDate" />} name="startDate" required component={Datepicker} autoFocus parse={parseDate} /> </Col> <Col xs={6}> <Field label={<FormattedMessage id="ui-users.reports.refunds.modal.endDate" />} name="endDate" component={Datepicker} parse={parseDate} /> </Col> <Col xs={12}> <Field data-test-financial-transactions-report-owner name="feeFineOwner" component={Select} label={<FormattedMessage id="ui-users.reports.financial.trans.modal.owners" />} placeholder={props.intl.formatMessage({ id: 'ui-users.reports.financial.trans.modal.owners.placeholder' })} dataOptions={formattedOwners} onChange={(e) => onChangeOwner(e.target.value)} required /> </Col> <Col xs={12}> <Field data-test-financial-transactions-report-servicePoint name="servicePoint" component={MultiSelection} label={<FormattedMessage id="ui-users.reports.financial.trans.modal.servicePoint" />} placeholder={props.intl.formatMessage({ id: 'ui-users.reports.financial.trans.modal.servicePoint.placeholder' })} dataOptions={formattedServicePoints} disabled={!ownerValue} /> </Col> </Row> </form> </Modal> ); }; FinancialTransactionsReportModal.propTypes = { form: PropTypes.object.isRequired, intl: PropTypes.object.isRequired, label: PropTypes.string.isRequired, owners: PropTypes.arrayOf(PropTypes.object).isRequired, onClose: PropTypes.func.isRequired, handleSubmit: PropTypes.func.isRequired, timezone: PropTypes.string.isRequired, values: PropTypes.object.isRequired, }; export default stripesFinalForm({ validate, subscription: { values: true }, })(injectIntl(FinancialTransactionsReportModal));
src/popover/SKBoundPopover.js
ShaneKing/sk-antd
import {Popover} from 'antd'; import PropTypes from 'prop-types'; import React from 'react'; import {Proxy0, SK} from 'sk-js'; import SKPopover from './SKPopover'; /** * @MustModelId */ export default class SKBoundPopover extends SKPopover { static SK_COMP_NAME = 'SKPopover'; static SK_EXTEND_COMP_NAME = 'SKBoundPopover'; static defaultProps = SK.extends(true, {}, SKPopover.defaultProps, { compTag: Popover }); static propTypes = SK.extends(true, {}, SKPopover.propTypes, { ssVisibleChange: PropTypes.func, }); constructor(...args) { super(...args); this.SK_COMP_NAME = SKBoundPopover.SK_COMP_NAME; this.SK_EXTEND_COMP_NAME = SKBoundPopover.SK_EXTEND_COMP_NAME; this.handleVisibleChange = (visible) => { if (this.props.ssVisibleChange && Proxy0._.isFunction(this.props.ssVisibleChange)) { this.props.ssVisibleChange(visible); } else { this.n2m(visible); } }; } render() { const {compTag: CompTag} = this.props; return ( <CompTag {...this.skTransProps2Self(CompTag)} onVisibleChange={this.handleVisibleChange} visible={this.m2n()} > {this.skTransProps2Child()} </CompTag> ); } }
src/index.js
jonniebigodes/freecodecampreactChallenges
import React from 'react'; import {render} from 'react-dom'; import {Router,Route,browserHistory} from 'react-router'; import App from './components/App'; import LeaderBoardContainer from './components/Challenges/Camper/CamperLeaderBoard'; import RecipesContainer from './components/Challenges/Recipes/Recipes'; import MarkDownContainer from './components/Challenges/MarkDownPreview/markDownPreview'; import GameofLifeContainer from './components/Challenges/GameOfLife/GameofLife'; import Bootstrap from 'bootstrap/dist/css/bootstrap.css'; render( <Router history={browserHistory}> <Route path="/" component={App} /> <Route path="/leaderboard" component={LeaderBoardContainer}/> <Route path="/recipes" component={RecipesContainer}/> <Route path="/markdown" component={MarkDownContainer}/> <Route path="/lifegame" component={GameofLifeContainer}/> </Router>, document.getElementById('root') );
application/index.js
ronanamsterdam/squaredcoffee
import React, { Component } from 'react'; import { StyleSheet, Text, View } from 'react-native'; import { Provider } from 'react-redux'; import App from './app'; import configureStore from './store'; export const store = configureStore(); export default class ApplicationRoot extends Component { render() { return ( <Provider store={store}> <App /> </Provider> ); } }
packages/wix-style-react/src/ToggleSwitch/docs/ControlledToggleSwitch.js
wix/wix-style-react
/* eslint-disable no-undef */ import React from 'react'; import { FormField, ToggleSwitch } from 'wix-style-react'; class ControlledToggleSwitch extends React.Component { state = { checked: false, }; render() { const { checked } = this.state; return ( <FormField id="formfieldToggleSwitchId" infoContent="I help you to fill info" label="Toggle" labelPlacement="right" stretchContent={false} required > <ToggleSwitch id="formfieldToggleSwitchId" checked={checked} onChange={e => this.setState({ checked: e.target.checked })} /> </FormField> ); } }
node_modules/case-sensitive-paths-webpack-plugin/demo/src/init.js
louisiaegerv/zephyr
import AppRoot from './AppRoot.component.js'; import React from 'react'; import ReactDOM from 'react-dom'; const app = { initialize() { ReactDOM.render(<AppRoot/>, document.getElementById('react-app-hook')); } }; app.initialize();
app/jsx/course_settings/components/UploadArea.js
venturehive/canvas-lms
/* * Copyright (C) 2016 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import I18n from 'i18n!course_images' import classnames from 'classnames' import htmlEscape from 'str/htmlEscape' class UploadArea extends React.Component { constructor (props) { super(props); this.handleFileChange = this.handleFileChange.bind(this); this.uploadFile = this.uploadFile.bind(this); } handleFileChange (e) { this.props.handleFileUpload(e, this.props.courseId); e.preventDefault(); e.stopPropagation(); } uploadFile () { this.refs.courseImagefileUpload.click(); } render () { return ( <div className="UploadArea"> <div className="UploadArea__Content"> <div className="UploadArea__Icon"> <i className="icon-upload" /> </div> <div className="UploadArea__Instructions"> <strong> {I18n.t('Drag and drop your image here or ')} <a tabIndex="0" role="button" href="#" onClick={this.uploadFile}> <span className="screenreader-only">{I18n.t('Browse your computer for a course image')}</span> <span aria-hidden="true">{I18n.t('browse your computer')}</span> </a> </strong> <input type="file" ref="courseImagefileUpload" name="fileUpload" className="FileUpload__Input" accept=".jpg, .jpeg, .gif, .png, image/png, image/jpeg, image/gif" aria-hidden="true" onChange={this.handleFileChange} /> </div> <div className="UploadArea__FileTypes"> {I18n.t('For best results crop image to 262px wide by 146px tall. JPG, PNG or GIF file types accepted')} </div> </div> </div> ); } } export default UploadArea
test/mochaTestHelper.js
vacuumlabs/este
import Bluebird from 'bluebird'; import chai, {assert, expect} from 'chai'; import React from 'react'; import sinon from 'sinon'; import sinonAsPromised from 'sinon-as-promised'; import sinonChai from 'sinon-chai'; import TestUtils from 'react-addons-test-utils'; chai.should(); chai.use(sinonChai); // Use Bluebird Promises inside of sinon stubs. // Bluebird has better error reporting for unhandled Promises. sinonAsPromised(Bluebird); export { assert, chai, expect, React, sinon, sinonChai, TestUtils };
packages/react-router/modules/Router.js
DelvarWorld/react-router
import warning from 'warning' import invariant from 'invariant' import React from 'react' import PropTypes from 'prop-types' /** * The public API for putting history on context. */ class Router extends React.Component { static propTypes = { history: PropTypes.object.isRequired, children: PropTypes.node } static contextTypes = { router: PropTypes.object } static childContextTypes = { router: PropTypes.object.isRequired } getChildContext() { return { router: { ...this.context.router, history: this.props.history, route: { location: this.props.history.location, match: this.state.match } } } } state = { match: this.computeMatch(this.props.history.location.pathname) } computeMatch(pathname) { return { path: '/', url: '/', params: {}, isExact: pathname === '/' } } componentWillMount() { const { children, history } = this.props invariant( children == null || React.Children.count(children) === 1, 'A <Router> may have only one child element' ) // Do this here so we can setState when a <Redirect> changes the // location in componentWillMount. This happens e.g. when doing // server rendering using a <StaticRouter>. this.unlisten = history.listen(() => { this.setState({ match: this.computeMatch(history.location.pathname) }) }) } componentWillReceiveProps(nextProps) { warning( this.props.history === nextProps.history, 'You cannot change <Router history>' ) } componentWillUnmount() { this.unlisten() } render() { const { children } = this.props return children ? React.Children.only(children) : null } } export default Router
src/js/app/main.js
marshallford/yet-another-react-boilerplate
import 'react-hot-loader/patch' import 'styles/main.scss' import React from 'react' import { render } from 'react-dom' import { AppContainer as HotLoader } from 'react-hot-loader' import App from 'app' const el = document.getElementById('app') render( <HotLoader> <App /> </HotLoader>, el ) if (module.hot) { module.hot.accept('app', () => { render( <HotLoader> <App /> </HotLoader>, el ) }) }
App/ComponenetsV2/NavigationContent.js
victoryforphil/GTMobile
import React, { Component } from 'react'; import { AppRegistry, PropTypes, ScrollView, StyleSheet, Text, TouchableOpacity, View, Alert, Navigator } from 'react-native'; import Icon from 'react-native-vector-icons/MaterialIcons'; import icons from 'react-native-vector-icons/EvilIcons'; import * as firebase from 'firebase'; import {GoogleSignin, GoogleSigninButton} from 'react-native-google-signin'; class NavigationContent extends Component { constructor(props) { super(props); var initList = [ { name: "Home", icon: "home", route: "Home" }, { name: "Events", icon: "date-range", route: "Events" }, { name: "Voting", icon: "check-circle", route: "Polls" }, { name: "Bell Schedule", icon: "alarm-on", route: "BellSchedule" }, { name: "Settings", icon: "settings", route: "Settings" } ] var listGroup = {groups: [{routes: initList}]} this.state = { id: "main", currentList: initList, listMap: listGroup }; } componentDidMount(){ var self = this; GoogleSignin.configure().then(function(){ GoogleSignin.currentUserAsync().then((user) => { console.log('USER', user); self.setState({user: user}); }).done(); }); } signIn(){ GoogleSignin.signIn() .then((user) => { this.setState({user: user}); }) .catch((err) => { console.log('WRONG SIGNIN', err); }) .done(); } signOut(){ GoogleSignin.signOut() .then(() => { GoogleSignin.currentUserAsync().then((user) => { console.log('USER', user); this.setState({user: user}); }).done(); }) .catch((err) => { }); } handlePress(selected) { if (selected.children) { var newList = this.state.listMap; newList.groups.push({routes: selected.children}); this.updateList(newList); } console.log(selected); if(selected.route){ this.props.onSelect(selected.route, selected.group); } } handleBack(){ var newList = this.state.listMap; newList.groups.pop(); this.updateList(newList); } updateList(newList){ if(newList.groups.length > 1){ this.setState({canBack: true}) }else{ this.setState({canBack: false}) } this.setState({ listMap: newList, currentList: newList.groups[newList.groups.length - 1].routes }); } signInRender(){ var self = this; if(self.state.user != null){ return ( <TouchableOpacity style={styles.button} onPress={()=>{self.signOut()}}> <Text style={{color: 'white'}}>Sign Out {self.state.user.name}</Text> </TouchableOpacity>) }else{ return(<GoogleSigninButton style={{width: 312, height: 64}} size={GoogleSigninButton.Size.Wide} color={GoogleSigninButton.Color.Light} onPress={self.signIn.bind(self)}/>) } } render(){ var self = this; var backButton = () =>{ if(this.state.canBack){ return( <TouchableOpacity style={styles.button} onPress={()=>{self.handleBack()}}> <Text style={styles.DrwrTex}><Icon name="arrow-back" size={30 } sytle={styles.icons} />Back</Text> </TouchableOpacity> ) } } if(this.state.currentList){ var sideBarItems = this.state.currentList.map(function(item,i) { return ( <TouchableOpacity key={i} style={styles.button} onPress={()=>{self.handlePress(item)}}> <Icon name={item.icon} size={30 } sytle={styles.icons} color={'#00CED1'}/> <Text style={styles.DrwrTex}>{item.name}</Text> </TouchableOpacity> ); }); } return( <ScrollView > {this.signInRender()} {backButton()} {sideBarItems} </ScrollView>) } } const styles = StyleSheet.create({ button: { borderWidth: .5, borderColor: 'black', padding: 25, flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }, backbutton: { borderWidth: .5, borderColor: 'black', padding: 15, flexDirection: 'row' }, newbutton: { borderWidth: .5, borderColor: 'black', padding: 25, flexDirection: 'row' }, icons: { color: '#00CED1', }, DrwrTex: { color: '#00CED1', fontSize: 18, marginLeft: 10, } }) export default NavigationContent
packages/ringcentral-widgets-docs/src/app/pages/Components/Eula/index.js
u9520107/ringcentral-js-widget
import React from 'react'; import { parse } from 'react-docgen'; import CodeExample from '../../../components/CodeExample'; import ComponentHeader from '../../../components/ComponentHeader'; import PropTypeDescription from '../../../components/PropTypeDescription'; import Demo from './Demo'; // eslint-disable-next-line import demoCode from '!raw-loader!./Demo'; // eslint-disable-next-line import componentCode from '!raw-loader!ringcentral-widgets/components/Eula'; const EulaPage = () => { const info = parse(componentCode); return ( <div> <ComponentHeader name="Eula" description={info.description} /> <CodeExample code={demoCode} title="Eula Example" > <Demo /> </CodeExample> <PropTypeDescription componentInfo={info} /> </div> ); }; export default EulaPage;
src/components/TemplateComponent.js
chimo/se-dir-frontend-react
'use strict'; import React from 'react'; import SiteNavigation from './SiteNavigationComponent'; import i18n from '../i18n'; require('es6-promise/auto'); var airbrakeJs = require('airbrake-js'); class TemplateComponent extends React.Component { getChildContext() { return { 'config': this.state.config, 'logger': this.state.logger }; } /** * Set the initial state */ constructor(props) { super(props); this.state = { config: {}, logger: { /* eslint-disable no-console */ notify: function(msg) { console.error(msg); } /* eslint-enable no-console */ } }; } /** * Get the configuration file * * @return A promise */ get_config() { return fetch('/config.json') .then(function(response) { if (!response.ok) { return Promise.reject(response.statusCode); } return response.json(); }) .catch(err => { // TODO: Handle error // eslint-disable-next-line no-console console.log('GOT ERR loading config' + err); }); } /** * Send errors to a logging system */ setup_error_logger(config) { var logger; logger = new airbrakeJs({ projectId: config.logger.api_key, projectKey: config.logger.api_key, reporter: 'xhr', host: config.logger.host }); return logger; } /** * Get/parse config data. * * Called by React after the initial render. */ componentDidMount() { var app = this; app .get_config() .then(function(config) { let logger = app.state.logger; // If we have a logger in the configs, set it up // otherwise it will default to the browser's console.error() if (config.logger) { logger = app.setup_error_logger(config); } let currentLocale = config.defaultLocale || 'en'; // If we have locales in the config, figure out which language to // display to the user based on the current url if (config.locales) { let currentUrl = window.location.href; for (let i = 0; i < config.locales.length; i += 1) { let locale = config.locales[i]; let pattern = new RegExp('^' + locale.prefix, 'i'); if (currentUrl.search(pattern) !== -1) { currentLocale = locale.locale; break; } } } i18n.changeLanguage(currentLocale); app.setState( { config: config, logger: logger } ); }) .catch(function(reason) { app.state.logger.notify(reason); }); } render() { /* Copy state information from this component to the child component's properties */ var childWithProps = React.cloneElement(this.props.children, this.state); return ( <div className='template-component'> {/* Every page will have the navigation component */} <SiteNavigation /> {/* The router will decide what to render here based on the URL we're at */} <main className='main'> {childWithProps} </main> </div> ); } } TemplateComponent.displayName = 'TemplateComponent'; TemplateComponent.childContextTypes = { 'config': React.PropTypes.object, 'logger': React.PropTypes.object }; export default TemplateComponent;
src/js/PurchasePage.js
merlox/dapp-transactions
import React from 'react' import Header from './Header' import './../stylus/index.styl' import './../stylus/purchasepage.styl' class PurchasePage extends React.Component { constructor(props) { super(props) } render(){ return ( <div style={{height: '100%'}}> <h1 className="purchase-title">Purchase Order</h1> <div className="purchase-box-container"> <div className="purchase-box"> <h2>Seller</h2> <img src={this.props.checkoutData.retailerImage} /> <p className="retailer-name">{this.props.checkoutData.retailerName}</p> <p className="retailer-address">{this.props.checkoutData.retailerAddress}</p> <p className="retailer-address">{this.props.checkoutData.retailerCity}</p> <p className="retailer-address">{this.props.checkoutData.retailerCode}</p> </div> <Box className="purchase-box" party="Sender" name="Company Name" address="Unit 24, The Henfield Business Park" city="Henfield" code="BN5 9SL" ledger="/ipfs/QmAkfhkHIWliuewnkhasfJoqiwhkfhShfkuashfsf/ledger" /> <Box className="purchase-box" party="Buyer" name="Firsname Lastname" address="71 Elmore" city="Swindon" code="SN3 3TN" ledger="/ipfs/QmAkfhkHIWliuewsdfsdfaerwqvzxcvhfzcvzvcsf/ledger" /> </div> <table className="purchase-table"> <thead> <tr> <td>Item Name</td> <td>Quantity</td> <td>Price</td> </tr> </thead> <tbody> <tr> <td>{this.props.checkoutData.itemName}</td> <td>{this.props.checkoutData.itemQuantity}</td> <td>{'$ ' + this.props.checkoutData.itemPrice}</td> </tr> <tr> <td></td> <td className="purchase-total-amount">Total Amount: </td> <td>{'$ ' + this.props.checkoutData.itemPrice * this.props.checkoutData.itemQuantity}</td> </tr> </tbody> </table> <div className="purchase-buttons-container"> <button className="purchase-decline-button" onClick={() => this.props.declineTransaction()} >Decline</button> <button className="purchase-accept-button" onClick={() => this.props.acceptTransaction()} >Accept and Sign</button> </div> </div> ) } } class Box extends React.Component { constructor(props){ super(props) } render(){ return ( <div className={this.props.className}> <h2>{this.props.party}</h2> <p className="retailer-name">{this.props.name}</p> <p className="retailer-address">{this.props.address}</p> <p className="retailer-address">{this.props.city}</p> <p className="retailer-address">{this.props.code}</p> <div className="horizontal-rule"></div> <p>Ledger address</p> <a href={"https://gateway.ipfs.io" + this.props.ledger}>{this.props.ledger}</a> </div> ) } } export default PurchasePage
src/game/problems/index.js
evinism/lambda-explorer
import React from 'react'; import InlineDefinition from '../inlineDefinitions/InlineDefinition'; import { equal, parseTerm as parse, leftmostOutermostRedex, toNormalForm, bReduce, getFreeVars, tokenize, renderExpression, renderAsChurchNumeral, renderAsChurchBoolean, } from '../../lib/lambda'; // interface for each should be roughly: /* { title: 'string', prompt: ReactElement, winCondition: computationData => bool } */ const safeEqual = (a, b) => (a && b) ? equal(a, b) : false; const t = parse('λab.a'); const f = parse('λab.b'); // (ast, [[arg, arg, result]]) => bool // should be able to handle non-boolean arguments too... function satisfiesTruthTable(ast, rules){ return rules.map( rule => { const mutable = [].concat(rule); const target = mutable.pop(); const ruleArgs = mutable; const testAst = ruleArgs.reduce((acc, cur) => ({ type: 'application', left: acc, right: cur, }), ast); try { const res = equal(target, toNormalForm(testAst)); return res; } catch (e) { console.log("Error in test: " + e); return false; } } ).reduce((a, b) => a && b, true); }; const Code = props => (<span className="code">{props.children}</span>); // just a dumb alias const Def = ({e, children}) => (<InlineDefinition entry={e}>{children}</InlineDefinition>); export default [ { title: 'Simple Variable', prompt: ( <div> <p>Let's get acquainted with some basic syntax. First, type <Code>a₁</Code>. Letters followed optionally by numbers represent variables in this REPL.</p> <p>In the actual lambda calculus, it's a bit broader, but we'll keep it simple right now.</p> </div> ), winCondition: ({ast}) => safeEqual(ast, parse('a₁')), }, // okay the first problem I actually care about { title: 'Application', prompt: ( <div> <p>You just wrote an expression which contains only the variable <Code>a₁</Code>, which is just a symbol, and not currently bound to anything. In the lambda calculus, variables can be bound to functions, and variables can be applied to one another.</p> <p>To apply the variable <Code>a₁</Code> to the variable <Code>b₁</Code>, type in <Code>a₁b₁</Code>. This represents calling the function <Code>a₁</Code> with <Code>b₁</Code> as an argument.</p> <p>Remember, the variable or function you're applying always goes <i>first</i></p> <p>Try applying one variable to another.</p> </div> ), winCondition: ({ast}) => { return safeEqual(ast, parse('a₁b₁')); }, }, { title: 'Upper Case Variables', prompt: ( <div> <p>Since lots of variables in the Lambda Calculus are single letters, there's often a semantic ambiguity when written down. For example, if I type in <Code>hi</Code>, do I mean one variable <Code>hi</Code>, or the variable <Code>h</Code> applied to variable <Code>i</Code>?</p> <p>For ease of use in this REPL, we'll make a small comprimise: upper case letters are interpreted as multi-letter variables, and lower case letters are interpreted as single-letter variables.</p> <p>Try typing <Code>MULT</Code>, and observe that it's interpreted as one variable, and NOT an application.</p> </div> ), winCondition: ({ast}) => safeEqual(ast, parse('MULT')), }, { title: 'Identity', prompt: ( <div> <p>Now we'll get into lambda abstractions. Lambda abstractions represent functions in the lambda calculus. A lambda abstraction takes the form <Code>λ [head] . [body]</Code> where <Code>[head]</Code> is the parameter of the function, and <Code>[body]</Code> is what the function resolves to.</p> <p>Let's write the identity function; a function which takes its argument, does nothing to it, and spits it back out. In the lambda calculus, that looks something like <Code>λa.a</Code></p> <p>as a reminder, you can type backslash (<Code>\</Code>) for λ</p> </div> ), winCondition: ({ast}) => { return safeEqual(ast, parse('λa.a')); }, }, { title: "Parentheses", prompt: ( <div> <p>Schweet! This takes one argument <Code>a</Code> and outputs that same argument! Now go ahead and wrap the whole thing in parentheses</p> </div> ), winCondition: ({text, ast}) => { return ( /^\s*\(.*\)\s*$/.test(text) && safeEqual(ast, parse('λa.a')) ); }, }, { title: "Baby's first β-reduction", prompt: ( <div> <p>Perfect! In the lambda calculus, you can always wrap <Def e={'expression'}>expressions</Def> in parentheses.</p> <p>Now in the same way that we can apply variables to other variables, we can apply lambda expressions to variables. Try applying your identity function to the variable <Code>b</Code>, by writing <Code>(λa.a)b</Code>.</p> <p>Don't worry if this doesn't make sense yet, we'll go a bit more in depth in the future.</p> </div> ), winCondition: ({ast}) => safeEqual(ast, parse('(λa.a)b')), }, { title: 'β-reduction function', prompt: ( <div> <p>Nice! What happened here is your identity function took <Code>b</Code> as the input and spit it right back out. The process of evaluating a function like this is called <i>beta reduction</i>.</p> <p>The result you're seeing here is in what's called <i>normal form</i>, which we'll also go through a little later.</p> <p>Just like we can evaluate functions with variables, we can also evaluate them with other functions! Try typing <Code>(λa.a)λb.b</Code></p> </div> ), winCondition: ({ast}) => safeEqual(ast, parse('(λa.a)λb.b')), }, { title: 'A primer on parsing', prompt: ( <div> <p>So we can perform beta reductions with other functions as the argument!</p> <p>With that, we've just introduced the main elements of the syntax of the lambda calculus:</p> <table><tbody> <tr><td>Variables</td><td><Code>a₁</Code></td></tr> <tr><td>Applying one expression to another</td><td><Code>a₁b₁</Code></td></tr> <tr><td>A lambda abstraction</td><td><Code>λx.y</Code></td></tr> <tr><td>Parentheses</td><td><Code>(λx.y)</Code></td></tr> </tbody></table> <p>We've also introduced a few ways in which these can be combined.</p> <table><tbody> <tr><td>Applying one lambda expression to a variable</td><td><Code>(λx.x)b₁</Code></td></tr> <tr><td>Applying one lambda expression to another</td><td><Code>(λa.a)λb.b</Code></td></tr> </tbody></table> <p>It's time to solidify our understanding of how these combine syntactically. Write any expression to continue.</p> </div> ), winCondition: () => true, }, { title: 'Left-associativity', prompt: ( <div> <p>Repeated <Def e='application'>applications</Def> in the lambda calculus are what is called <i>left-associative</i>. This means that repeated applications are evaluated from left to right.</p> <p>To make this clearer, if we were to explicity write out the parentheses for the expression <Code>abcd</Code>, we'd end up with <Code>((ab)c)d</Code>. That is, in the expression <Code>abcd</Code>, <Code>a</Code> will first be applied to <Code>b</Code>, then the result of <Code>ab</Code> will be applied to <Code>c</Code>, so on and so forth.</p> <p>Write out the parentheses explicitly for <Code>ijkmn</Code></p> </div> ), winCondition: ({text}) => { // Any of these are valid interpretations and we should be permissive rather // than enforcing dumb bullshit. return [ '(((ij)k)m)n', '((((ij)k)m)n)', '((((i)j)k)m)n', '(((((i)j)k)m)n)', ].includes(text.replace(/\s/g, '')); }, }, { title: 'Tightly Binding Lambdas', prompt: ( <div> <p><Def e='lambda_abstraction'>Lambda abstractions</Def> have higher prescedence than <Def e='application'>applications</Def>.</p> <p>This means that if we write the expression <Code>λx.yz</Code>, it would be parenthesized as <Code>λx.(yz)</Code> and NOT <Code>(λx.y)z</Code>.</p> <p>As a rule of thumb, the body of a lambda abstraction (i.e. the part of the lambda expression after the dot) extends all the way to the end of the expression unless parentheses tell it not to.</p> <p>Explicitly write the parentheses around <Code>λw.xyz</Code>, combining this new knowledge with what you learned in the last question around how applications are parenthesized.</p> <p>Solution: <span className='secret'>λw.((xy)z)</span></p> </div> ), winCondition: ({text}) => { return [ 'λw.((xy)z)', '(λw.((xy)z))', 'λw.(((x)y)z)', '(λw.(((x)y)z))', ].includes(text.replace(/\s/g, '')); }, }, { title: 'Applying Lambdas to Variables', prompt: ( <div> <p>So what if we DID want to apply a <Def e='lambda_abstraction'>lambda abstraction</Def> to a variable? We'd have to write it out a little more explicity, like we did back in problem 6.</p> <p>For example, if we wanted to apply the lambda abstraction <Code>λx.y</Code> to variable <Code>z</Code>, we'd write it out as <Code>(λx.y)z</Code></p> <p>Write an expression that applies the lambda abstraction <Code>λa.bc</Code> to the variable <Code>d</Code>.</p> </div> ), winCondition: ({ast}) => safeEqual(ast, parse('(λa.bc)d')), }, { title: 'Applying Variables to Lambdas', prompt: ( <div> <p>Fortunately, the other direction requires fewer parentheses. If we wanted to apply a variable to a lambda abstraction instead of the other way around, we'd just write them right next to each other, like any other application.</p> <p>Concretely, applying <Code>a</Code> to lambda abstraction <Code>λb.c</Code> is written as <Code>aλb.c</Code></p> <p>Try applying <Code>w</Code> to <Code>λx.yz</Code>!</p> </div> ), winCondition: ({ast}) => safeEqual(ast, parse('wλx.yz')), }, { title: 'Curry', prompt: ( <div> <p>As you may have noticed before, functions can only take one argument, which is kind of annoying.</p> <p>Let's say we quite reasonably want to write a function which takes more than one argument. Fortunately, we can sort of get around the single argument restriction by making it so that a function returns another function, which when evaluated subsequently gives you the result. Make sense?</p> <p>In practice, this looks like <Code>λa.λb. [some expression]</Code>. Go ahead and write any 'multi-argument' function!</p> </div> ), winCondition: ({ast}) => ( ast && ast.type === 'function' && ast.body.type === 'function' ), }, { title: 'And a Dash of Sugar', prompt: ( <div> <p>Getting the hang of it!</p> <p>Representing functions with multiple arguments like this is so convenient, we're going to introduce a special syntax. We'll write <Code>λab. [some expression]</Code> as shorthand for <Code>λa.λb. [some expression]</Code>. Try writing a function using that syntax!</p> </div> ), winCondition: ({text, ast}) => { // wow this is a garbage win condition const isMultiargumentFn = ast && ast.type === 'function' && ast.body.type === 'function'; if (!isMultiargumentFn) { return false; } // has special syntax.. better way than pulling the lexer?? // this shouldn't throw because by here we're guaranteed ast exists. const tokenStream = tokenize(text).filter( // only try to match '(((Lab' and don't care about the rest of the string. token => token.type !== 'openParen' ); return tokenStream.length >= 3 && tokenStream[0].type === 'lambda' && tokenStream[1].type === 'identifier' && tokenStream[2].type === 'identifier'; }, }, { title: 'Summing up Syntax', prompt: ( <div> <p>We've just gone through a whirlwind of syntax in the Lambda Calculus, but fortunately, it's almost everything you need to know.</p> <p>As a final challenge for this section on syntax, try writing out the expression that applies the expression <Code>aλb.c</Code> to variable <Code>d</Code></p> </div> ), winCondition: ({ast}) => safeEqual(ast, parse('(aλb.c)d')), }, { title: 'β-reducibility revisited', prompt: ( <div> <p>Let's take a deeper look at Beta Reductions.</p> <p>When an <Def e='expression'>expression</Def> is an <Def e='application'>application</Def> where the left side is a <Def e='lambda_abstraction'>lambda abstraction</Def>, we say that the expression is <i>beta reducible</i>.</p> <p>Here are a few examples of beta reducible expressions:</p> <table> <thead> <tr> <th scope="col">Expression</th> <th scope="col">Explanation</th> </tr> </thead> <tbody> <tr><td><Code>(λx.y)z</Code></td><td>Lambda abstraction <Code>λx.y</Code> applied to <Code>z</Code></td></tr> <tr><td><Code>(λa.b)λc.d</Code></td><td>Lambda abstraction <Code>λa.b</Code> applied to <Code>λc.d</Code></td></tr> <tr><td><Code>(λzz.top)λy.ee</Code></td><td>Lambda abstraction <Code>λz.λz.top</Code> applied to <Code>λy.ee</Code></td></tr> </tbody> </table> <p>And here are a few examples of expressions that are NOT beta reducible:</p> <table> <thead> <tr> <th scope="col">Expression</th> <th scope="col">Explanation</th> </tr> </thead> <tbody> <tr><td><Code>zλx.y</Code></td><td>Variable <Code>z</Code> applied to <Code>λx.y</Code></td></tr> <tr><td><Code>λa.bcd</Code></td><td>Lambda abstraction <Code>λa.bcd</Code>, but not applied to anything</td></tr> <tr><td><Code>bee</Code></td><td>Application <Code>be</Code> applied to <Code>e</Code></td></tr> <tr><td><Code>f(λg.h)i</Code></td><td>Application <Code>f(λg.h)</Code> applied to <Code>i</Code> (This one's tricky! Remember that applications are left-associative).</td></tr> </tbody> </table> <p>Write any beta reducible expression that does not appear in the above table.</p> </div> ), winCondition: ({ast}) => { const rejectList = [ '(λx.y)z', '(λa.b)λc.d', '(λz.λz.top)λy.ee', ]; const isInList = !!rejectList.find( rejectItem => safeEqual(ast, parse(rejectItem))); return !isInList && ast && bReduce(ast); } }, { title: 'A more precise look at β-reductions', prompt: ( <div> <p>As you might guess, if something is beta reducible, that means we can perform an operation called <i>beta reduction</i> on the expression.</p> <p>Beta reduction works as follows:</p> <table> <thead> <tr> <th scope="col">Expression</th> <th scope="col">Step</th> </tr> </thead> <tbody> <tr><td><Code>(λa.aba)c</Code></td><td>Start with a <Def e="beta_reducible_intro">beta reducible</Def> expression.</td></tr> <tr><td><Code>(λa.cbc)c</Code></td><td>In the <Def e='body'>body</Def> of the lambda abstraction, replace every occurrence of the <Def e='parameter'>parameter</Def> with the <Def e='argument'>argument</Def>.</td></tr> <tr><td><Code>λa.cbc</Code></td><td>Erase the argument.</td></tr> <tr><td><Code>cbc</Code></td><td>Erase the <Def e="head">head</Def> of the lambda expression.</td></tr> </tbody> </table> <p>That's all there is to it!</p> <p>Write any expression that beta reduces to <Code>pp</Code>.</p> </div> ), winCondition: ({ast}) => { return ast && safeEqual(bReduce(ast), parse('pp')); }, }, { title: 'β-reduction function reprise', prompt: ( <div> <p>As we showed in the beginning, this works on functions as well!</p> <p>Let's work through an example for a function:</p> <table> <thead> <tr> <th scope="col">Expression</th> <th scope="col">Step</th> </tr> </thead> <tbody> <tr><td><Code>(λx.yx)λa.a</Code></td><td>Start with a beta reducible expression.</td></tr> <tr><td><Code>(λx.y(λa.a))λa.a</Code></td><td>In the <Def e='body'>body</Def> of the lambda abstraction, replace every occurrence of the <Def e='parameter'>parameter</Def> with the <Def e='argument'>argument</Def>.</td></tr> <tr><td><Code>λx.y(λa.a)</Code></td><td>Erase the argument.</td></tr> <tr><td><Code>y(λa.a)</Code></td><td>Erase the <Def e='head'>head</Def> of the lambda expression.</td></tr> </tbody> </table> <p>Write any expression that beta reduces to <Code>iλj.k</Code>.</p> </div> ), winCondition: ({ast}) => { return ast && safeEqual(bReduce(ast), parse('i(λj.k)')); }, }, { title: 'Bound and Free Variables', prompt: ( <div> <p>It's prudent to make a distinction between bound and free variables. When a function takes an argument, every occurrence of the variable in the body of the function is <i>bound</i> to that parameter.</p> <p>For quick example, if you've got the expression <Code>λx.xy</Code>, the variable <Code>x</Code> is bound in the lambda expression, whereas the variable <Code>y</Code> is currently unbound. We call unbound variables like <Code>y</Code> <i>free variables</i>.</p> <p>Write a lambda expression with a free variable <Code>c</Code> (hint: this can be extremely simple).</p> </div> ), winCondition: ({ast}) => ast && getFreeVars(ast).map(item => item.name).includes('c'), }, { title: 'α conversions', prompt: ( <div> <p>Easy enough. In this REPL you can see what free variables are in an expression (as well as a lot of other information) by clicking the (+) that appears next to results.</p> <p>It might be obvious that there are multiple ways to write a single lambda abstraction. For example, let's take that identity function we wrote all the way in the beginning, <Code>λa.a</Code>. We could have just as easily used <Code>x</Code> as the parameter, yielding <Code>λx.x</Code>.</p> <p>The lambda calculus's word for "renaming a parameter" is <i>alpha-conversion.</i></p> <p>Manually perform an alpha conversion for the expression <Code>λz.yz</Code>, by replacing <Code>z</Code> with <Code>t</Code></p> </div> ), winCondition: ({ast}) => { return ast && safeEqual(ast, parse('λt.yt')); }, }, // --- Computation --- { title: 'β reductions + α conversions', prompt: ( <div> <p>Occasionally, we'll get into a situation where a variable that previously was unbound is suddenly bound to a parameter that it shouldn't be. For example, if we tried beta-reducing <Code>(λab.ab)b</Code> without renaming to resolve the conflict, we'd get <Code>λb.bb</Code>. What originally was a free variable <Code>b</Code> is now (accidentally) bound to the parameter of the lambda expression!</p> <p>To eliminate this conflict, we have to do an alpha-conversion prior to doing the beta reduction.</p> <p>Try inputting an expression (like <Code>(λab.ab)b</Code>) that requires an alpha conversion to see how the REPL handles this situation.</p> </div> ), // lol this win condition. winCondition: ({normalForm}) => ( normalForm && renderExpression(normalForm).includes('ε') ), }, { title: "Nested Redexes", prompt: ( <div> <p>Notice that epsilon that pops up? That's this REPL's placeholder variable for when it needs to rename a variable due to a conflict.</p> <p>Often, an expression is not beta reducible itself, but contains one or more beta reducible expressions (redexes) nested within. We can still evaluate the expression!</p> <p>Try writing a function with a nested redex!</p> <p>Possible solution: <span className='secret'>λa.(λb.b)c</span></p> </div> ), winCondition: ({ast}) => ( ast && !bReduce(ast) && leftmostOutermostRedex(ast) ), }, { title: "Leftmost Outermost Redex", prompt: ( <div> <p>"But wait," I hear you shout. "What if I have more than one reducible subexpression in my expression? Which do I evaluate first?"</p> <p>Let's traverse the expression, left to right, outer scope to inner scope, find the <i>leftmost outermost redex</i>, and evaluate that one. This is called the <i>normal order</i>.</p> <p>Try typing and expanding <Code>((λb.b)c)((λd.d)e)</Code> to see what I mean.</p> </div> ), // no need to be super restrictive in what they paste in here winCondition: ({ast}) => ast && equal(ast, parse('((λb.b)c)((λd.d)e)')), }, { title: 'Normal Form', prompt: ( <div> <p>If we do this repeatedly until there's nothing more to reduce, we get to what's called the "normal form". Finding the normal form is analogous to executing the lambda expression, and is in fact exactly what this REPL does when you enter an expression.</p> <p>In this REPL you can see the steps it took to get to normal form by pressing the (+) button beside the evaluated expression.</p> <p>Type in any expression to continue.</p> </div> ), winCondition: () => true, }, { title: 'Or Not', prompt: ( <div> <p>It's possible that this process never halts, meaning that a normal form for that expression doesn't exist.</p> <p>See if you can find an expression whose normal form doesn't exist!</p> <p>Possible answer: <span className="secret">(λa.aa)λa.aa</span></p> </div> ), winCondition: ({error}) => ( // TODO: make it so errors aren't compared by user string, that's dumb error && error.message === 'Normal form execution exceeded. This expression may not have a normal form.' ) }, { title: 'The Y-Combinator', prompt: ( <div> <p>You can expand that error that pops up to see the first few iterations. If you went with <Code>(λa.aa)λa.aa</Code>, you can see that performing a beta reduction gives you the exact same expression back!</p> <p>The famed Y-Combinator is one of these expressions without a normal form. Try inputting the Y-Combinator, and see what happens:</p> <p>Y: <Code>λg.(λx.g(xx))(λx.g(xx))</Code></p> </div> ), winCondition: ({ast}) => equal(ast, parse('λg.(λx.g(xx))(λx.g(xx))')), }, { title: "Assigning variables", prompt: ( <div> <p>In the lambda calculus, there's no formal notion of assigning variables, but it's far easier for us to refer to functions by name than just copy/paste the expression every time we want to use it.</p> <p>In this REPL, we've added a basic syntax around assign variables. (Note: You can't assign an expression with free variables.)</p> <p>This kind of <i>lexical environment</i> around the lambda calculus comes very close to the original sense of a <a href="https://en.wikipedia.org/wiki/Closure_(computer_programming)" target="blank">closure</a>, as presented in <a href="https://www.cs.cmu.edu/~crary/819-f09/Landin64.pdf" target="blank">The mechanical evaluation of expressions</a>.</p> <p>Try assigning <Code>ID</Code> to your identity function by typing <Code>ID := λa.a</Code></p> </div> ), winCondition: ({ast, lhs}) => { return ( // could probably be simplified by including execution context in winCondition. ast && lhs === 'ID' && safeEqual(ast, parse('λa.a')) ); } }, { title: 'Using assigned variables', prompt: ( <div> <p>Now that <Code>ID</Code> is defined in the <i>lexical environment</i>, we can use it as if it's a previously bound variable</p> <p>Try writing <Code>ID b</Code> in order to apply your newly defined identity function to <Code>b</Code>, with predictable results.</p> </div> ), winCondition: ({ast}) => ( // we don't really have a good way of testing whether or not // a certain variable was used, because execution context does var replacement, // which is kinda bad. whatever. just check if left is identical to ID. ast && ast.type === 'application' && safeEqual(ast.left, parse('λa.a')) ), }, { title: "Church Booleans", prompt: ( <div> <p>Now we're well equipped enough to start working with actual, meaningful values.</p> <p>Let's start off by introducing the booleans! The two booleans are:</p> <p>true: <Code>λab.a</Code></p> <p>false: <Code>λab.b</Code></p> <p>You'll notice that these values themselves are just functions. That's true of any value in the lambda calculus -- all values are just functions that take a certain form. They're called the Church booleans, after Alonzo Church, the mathematician who came up with the lambda calculus, as well as these specific encodings.</p> <p>It'll be helpful to assign them to <Code>TRUE</Code> and <Code>FALSE</Code> respectively. Do that.</p> </div> ), winCondition: ({executionContext}) => { const t = executionContext.definedVariables.TRUE; const f = executionContext.definedVariables.FALSE; if (!t || !f) { return false; } return renderAsChurchBoolean(t) === true && renderAsChurchBoolean(f) === false; }, }, { title: 'The Not Function', prompt: ( <div> <p>We're gonna work our way to defining the XOR (exclusive or) function on booleans.</p> <p>Our first step along the way is to define the NOT function. To do this, let's look at the structure of what a boolean looks like.</p> <p>True is just a two parameter function that selects the first, whereas false is just a two parameter function that selects the second argument. We can therefore call a potential true or false value like a function to select either the first or second parameter!</p> <p>For example, take the application <Code>mxy</Code>. If <Code>m</Code> is Church Boolean true, then <Code>mxy</Code> beta reduces to <Code>x</Code>. However, if <Code>m</Code> is Church Boolean false, <Code>mxy</Code> beta reduces to <Code>y</Code></p> <p>Try writing the NOT function, and assign that to <Code>NOT</Code>.</p> <p>Answer: <span className="secret">NOT := λm.m FALSE TRUE</span></p> </div> ), winCondition: ({ast, lhs}) => ( // should probably be a broader condition-- test for true and false respectively using N. lhs === 'NOT' && ast && satisfiesTruthTable( ast, [ [t, f], [f, t] ] )// safeEqual(ast, parse('λm.m(λa.λb.b)(λa.λb.a)')) ), }, { title: 'The Or Function', prompt: ( <div> <p>Nice! We've now done the heavy mental lifting of how to use the structure of the value to our advantage.</p> <p>You should be well equipped enough to come up with the OR function, a function which takes two booleans and outputs true if either of parameters are true, otherwise false.</p> <p>Give it a shot, and assign it to <Code>OR</Code></p> <p>Answer: <span className="secret">OR := λmn.m TRUE n</span></p> </div> ), winCondition: ({ast, lhs}) => ( // same here lhs === 'OR' && ast && satisfiesTruthTable( ast, [ [t, t, t], [t, f, t], [f, t, t], [f, f, f] ] ) //safeEqual(ast, parse('λm.λn.m(λa.λb.a)n')) ), }, { title: 'The And Function', prompt: ( <div> <p>Closer and closer.</p> <p>This one's very similar to the previous one. See if you can define the AND function, a function which takes two booleans and outputs true if both parameters are true, otherwise false.</p> <p>Assign your answer to <Code>AND</Code></p> <p>Answer: <span className="secret">AND := λmn.m n FALSE</span></p> </div> ), winCondition: ({ast, lhs}) => ( // same here lhs === 'AND' && ast && satisfiesTruthTable( ast, [ [t, t, t], [t, f, f], [f, t, f], [f, f, f] ] ) //&& safeEqual(ast, parse('λm.λn.mn(λa.λb.b)')) ), }, { title: 'NAND and NOR', prompt: ( <div> <p>The NOR and NAND functions are the opposite of OR and AND. For example, if AND returns true, NAND returns false, and vice versa. The same follows for OR and NOR</p> <p>Since we've already defined the <Code>NOT</Code>, <Code>AND</Code>, and <Code>OR</Code> functions, we can just compose those together to get <Code>NAND</Code> and <Code>NOR</Code></p> <p>Define NAND and NOR, and assign them to <Code>NAND</Code> and <Code>NOR</Code>.</p> <p>Answers:</p> <p><span className='secret'>NOR := λab. NOT (OR a b)</span></p> <p><span className='secret'>NAND := λab. NOT (AND a b)</span></p> </div> ), winCondition: ({executionContext}) => { const nor = executionContext.definedVariables.NOR; const nand = executionContext.definedVariables.NAND; if (!nor || !nand) { return false; } return satisfiesTruthTable( nor, [ [t, t, f], [t, f, f], [f, t, f], [f, f, t], ] ) && satisfiesTruthTable( nand, [ [t, t, f], [t, f, t], [f, t, t], [f, f, t], ] ); }, }, { title: 'Composing them all together', prompt: ( <div> <p>One last step!</p> <p>For reference, the XOR operation is true iff one parameter or the other is true, but not both. So <Code>XOR(true, false)</Code> would be true, but <Code>XOR(true, true)</Code> would be false.</p> <p>Let's see if you can translate that into a composition of the functions you've defined so far. Assign your answer to <Code>XOR</Code></p> <p>(There is, of course, a simpler way of defining <Code>XOR</Code> without composing functions, and that will work here too)</p> <p>Answer: <span className="secret">XOR := λmn. AND (OR m n) (NAND m n)</span></p> </div> ), winCondition: ({ast, lhs}) => ( // The likelihood that they got this exact one is pretty small... we really need to define truth tables. lhs === 'XOR' && ast && satisfiesTruthTable( ast, [ [t, t, f], [t, f, t], [f, t, t], [f, f, f] ] ) ), }, { title: 'Defining numbers', prompt: ( <div> <p>Well, that was a marathon. Take a little break, you've earned it.</p> <p>Now we're getting into the meat of it. We can encode numbers in the lambda calculus. Church numerals are 2 parameter functions in the following format:</p> <p> <pre> {` 0: λfn.n 1: λfn.f(n) 2: λfn.f(f(n)) 3: λfn.f(f(f(n))) `} </pre> </p> <p>Write Church Numeral 5</p> <p>Answer: <span className="secret">λfn.f(f(f(f(fn))))</span></p> </div> ), winCondition: ({ast}) => ast && (renderAsChurchNumeral(ast) === 5), }, { title: 'The Successor Function', prompt: ( <div> <p>We can write functions for these numbers. For example, let's look at the <i>successor function</i>, a function which simply adds 1 to its argument.</p> <p>If you're feeling brave, you can attempt to write the successor function yourself. It's a pretty interesting exercise. Otherwise, just copy/paste from the answer key, but feel a little defeated while doing so.</p> <p>Answer: <span className="secret">λn.λf.λx.f(nfx)</span></p> </div> ), winCondition: ({ast}) => ast && satisfiesTruthTable( ast, [ [parse('λfn.n'), parse('λfn.fn')], [parse('λfn.fn'), parse('λfn.f(f(n))')], [parse('λfn.f(f(n))'), parse('λfn.f(f(f(n)))')], [parse('λfn.f(f(f(n)))'), parse('λfn.f(f(f(f(n))))')], ] ), }, { title: "The Successor Function(cot'd)", prompt: ( <div> <p>So here's what we just did: Let's say we were adding 1 to <Code>λfn.f(f(f(f(n))))</Code>. We just wrote a function that replaced all the <Code>f</Code>'s with <Code>f</Code>'s again, and then replaced the <Code>n</Code> with a <Code>f(n)</Code>, thus creating a stack one higher than we had before! Magic!</p> <p>Assign the successor function to <Code>SUCC</Code>, we'll need it later</p> </div> ), winCondition: ({executionContext}) => ( executionContext.definedVariables.SUCC && satisfiesTruthTable( executionContext.definedVariables.SUCC, [ [parse('λfn.n'), parse('λfn.fn')], [parse('λfn.fn'), parse('λfn.f(f(n))')], [parse('λfn.f(f(n))'), parse('λfn.f(f(f(n)))')], [parse('λfn.f(f(f(n)))'), parse('λfn.f(f(f(f(n))))')], ] ) ), }, { title: "Adding Numbers bigger than 1", prompt: ( <div> <p>The nice thing about Church numerals as we've defined them is they encode "compose this function n times", so in order to compose a function 3 times, just apply the target function to the Church numeral 3.</p> <p>For example, let's say we had the function <Code>APPLY_C := λa.a c</Code> that applied free variable <Code>c</Code> to whatever function was passed in. If we wanted to write a function that applied c 3 times, we would write <Code>(λfn.f(f(fn))) APPLY_C</Code></p> <p>Write the "add 4" function by composing the successor function 4 times.</p> </div> ), winCondition: ({ast}) => ( ast && satisfiesTruthTable( ast, [ [parse('λfn.n'), parse('λfn.f(f(f(f(n))))')], [parse('λfn.fn'), parse('λfn.f(f(f(f(f(n)))))')], [parse('λfn.f(fn)'), parse('λfn.f(f(f(f(f(f(n))))))')], ] ) ), }, { title: "Defining the Addition Function", prompt: ( <div> <p>What's convenient about this is in order to add the numbers <Code>a</Code> and <Code>b</Code>, we just create the <Code>(add a)</Code> function and apply it to <Code>b</Code></p> <p>You can take this structure and abstract it out a little, turning it into a function.</p> <p>Go ahead and define <Code>ADD</Code> to be your newly crafted addition function.</p> <p>Answer: <span className="secret">ADD := λab.a SUCC b</span></p> </div> ), winCondition: ({lhs, ast}) => ( lhs === 'ADD' && ast && satisfiesTruthTable( ast, [ [parse('λfn.n'), parse('λfn.n'), parse('λfn.n')], [parse('λfn.f(n)'), parse('λfn.f(n)'), parse('λfn.f(fn)')], [parse('λfn.f(f(n))'), parse('λfn.f(f(f(n)))'), parse('λfn.f(f(f(f(f(n)))))')], ] ) ), }, { title: "Defining the Multiplication Function", prompt: ( <div> <p>Let's go ahead write the Multiply function by composing adds together. One possible way to think about a multiply function that takes <Code>x</Code> and <Code>y</Code> "Compose the <Code>Add x</Code> function <Code>y</Code> times, and evaluate that at zero".</p> <p>Go ahead and assign that to <Code>MULT</Code></p> <p>Answer: <span className="secret">MULT := λab.b(ADD a)λfn.n</span></p> </div> ), winCondition: ({lhs, ast}) => ( lhs === 'MULT' && ast && satisfiesTruthTable( ast, [ [parse('λfn.n'), parse('λfn.n'), parse('λfn.n')], [parse('λfn.f(n)'), parse('λfn.f(n)'), parse('λfn.f(n)')], [parse('λfn.f(f(n))'), parse('λfn.f(f(f(n)))'), parse('λfn.f(f(f(f(f(fn)))))')], ] ) ) }, { title: "To Exponentiation!", prompt: ( <div> <p>This shouldn't be too difficult, as it's very similar to the previous problem.</p> <p>Compose together a bunch of multiplications, for some starting position to get the exponentiation function. What's cool is that constructing the exponentiation this way means the function behaves correctly for the number 0 straight out of the box, without eta-reduction</p> <p>Assign your exponentiation function to EXP to win, and complete the tutorial.</p> <p>Answer is: <span className="secret">EXP := λab.b (MULT a) λfn.fn</span></p> </div> ), winCondition: ({lhs, ast}) => ( lhs === 'EXP' && ast && satisfiesTruthTable( ast, [ [parse('λfn.n'), parse('λfn.fn'), parse('λfn.n')], [parse('λfn.f(n)'), parse('λfn.f(n)'), parse('λfn.f(n)')], [parse('λfn.f(f(n))'), parse('λfn.n'), parse('λfn.f(n)')], [parse('λfn.f(f(n))'), parse('λfn.f(f(f(n)))'), parse('λfn.f(f(f(f(f(f(f(fn)))))))')], ] ) ) }, { title: "Challenges", prompt: ( <div> <p>You made it through! Not bad at all!</p> <p><b>Miscellaneous Challenges:</b></p> <p>(full disclosure: I haven't attempted these)</p> <p>1: Write the Subtract 1 function. (there are a number of tutorials you can find on this on the internet)</p> <p>2: Write the <Code>Max(a, b)</Code> function, a function that takes two numbers and outputs the larger of the two.</p> <p>3: Write a function that computes the decimal equivalent of its input in <a href="https://en.wikipedia.org/wiki/Gray_code">Gray code</a>. In other words, compute <a href="https://oeis.org/A003188">A003188</a></p> </div> ), winCondition: () => false, }, ];
app/components/options/ProfileCard.js
bjyoungblood/chrome-github-toolkit
import React from 'react'; import { Card, CardTitle, CardText, CardActions, Button, Icon, Spinner, } from 'react-mdl'; class ProfileCard extends React.Component { static propTypes = { onLogin: React.PropTypes.func.isRequired, onLogout: React.PropTypes.func.isRequired, token: React.PropTypes.object.isRequired, } onAuthClick(event) { event.preventDefault(); if (this.props.token.loading) { return; } this.props.onLogin(); } renderCardBody() { if (this.props.token.loading) { return <Spinner />; } if (! this.props.token.token) { return ( <h4>Not authenticated.</h4> ); } return <div>Authenticated!</div>; } renderLoginButton() { return ( <Button colored={true} disabled={this.props.token.loading} raised={true} onClick={this.onAuthClick.bind(this)}> Log in with Github </Button> ); } renderCardActions() { if (! this.props.token.token) { return this.renderLoginButton(); } return (<Button onClick={this.props.onLogout}>Logout</Button>); } render() { return ( <Card shadowLevel={1} className="options-card"> <CardTitle expand={true} className="mdl-color--primary mdl-color-text--primary-contrast"> <h2 className="mdl-card__title-text">Github Login</h2> </CardTitle> <CardText> {this.renderCardBody()} </CardText> <CardActions border={true}> {this.renderCardActions()} </CardActions> </Card> ); } } export default ProfileCard;