path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
fixtures/fiber-debugger/src/index.js
tomocchino/react
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render(<App />, document.getElementById('root'));
docs/src/sections/ImageSection.js
mmarcant/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function ImageSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="images">Images</Anchor> <small>Image</small> </h2> <h3><Anchor id="image-shape">Shape</Anchor></h3> <p>Use the <code>rounded</code>, <code>circle</code> and <code>thumbnail</code> props to customise the image.</p> <ReactPlayground codeText={Samples.ImageShape} /> <h3><Anchor id="image-responsive">Responsive</Anchor></h3> <p>Use the <code>responsive</code> to scale image nicely to the parent element.</p> <ReactPlayground codeText={Samples.ImageResponsive} /> <h3><Anchor id="image-props">Props</Anchor></h3> <PropTable component="Image"/> </div> ); }
addons/info/src/components/markdown/htags.js
enjoylife/storybook
import React from 'react'; import PropTypes from 'prop-types'; import { baseFonts } from '../theme'; const defaultProps = { children: null, id: null, }; const propTypes = { children: PropTypes.node, id: PropTypes.string, }; export function H1(props) { const styles = { ...baseFonts, borderBottom: '1px solid #eee', fontWeight: 600, margin: 0, padding: 0, fontSize: '40px', }; return <h1 id={props.id} style={styles}>{props.children}</h1>; } H1.defaultProps = defaultProps; H1.propTypes = propTypes; export function H2(props) { const styles = { ...baseFonts, fontWeight: 600, margin: 0, padding: 0, fontSize: '30px', }; return <h2 id={props.id} style={styles}>{props.children}</h2>; } H2.defaultProps = defaultProps; H2.propTypes = propTypes; export function H3(props) { const styles = { ...baseFonts, fontWeight: 600, margin: 0, padding: 0, fontSize: '22px', textTransform: 'uppercase', }; return <h3 id={props.id} style={styles}>{props.children}</h3>; } H3.defaultProps = defaultProps; H3.propTypes = propTypes; export function H4(props) { const styles = { ...baseFonts, fontWeight: 600, margin: 0, padding: 0, fontSize: '20px', }; return <h4 id={props.id} style={styles}>{props.children}</h4>; } H4.defaultProps = defaultProps; H4.propTypes = propTypes; export function H5(props) { const styles = { ...baseFonts, fontWeight: 600, margin: 0, padding: 0, fontSize: '18px', }; return <h5 id={props.id} style={styles}>{props.children}</h5>; } H5.defaultProps = defaultProps; H5.propTypes = propTypes; export function H6(props) { const styles = { ...baseFonts, fontWeight: 400, margin: 0, padding: 0, fontSize: '18px', }; return <h6 id={props.id} style={styles}>{props.children}</h6>; } H6.defaultProps = defaultProps; H6.propTypes = propTypes;
client/src/routes.js
saltypaul/SnipTodo
/** * This module defines route rules within the app. * */ import React from 'react'; import { Provider } from 'react-redux'; import configureStore from './store'; import { Router, Route, hashHistory, IndexRoute } from 'react-router'; import { Home, Welcome, Archive } from './components'; import { TodoListContainer } from './containers'; // THE only store for the whole app. const store = configureStore(); const routes = ( /** * Pass store to Provider, * making store available to all wrapped components. * * The URL structure: * / ==> Home/Welcome * /todolist ==> Archive/TodosContainer */ <Provider store={store}> <Router history={hashHistory}> <Route path="/" component={Home}> <IndexRoute component={Welcome} /> </Route> <Route path="/todolist" component={Archive}> <IndexRoute component={TodoListContainer}/> </Route> </Router> </Provider> ); export default routes;
js/BaseComponents/Input.js
telldus/telldus-live-mobile-v3
/** * Copyright 2016-present Telldus Technologies AB. * * This file is part of the Telldus Live! app. * * Telldus Live! app is free : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Telldus Live! app is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>. */ // @flow 'use strict'; import React from 'react'; import { View, TextInput } from 'react-native'; import Base from './Base'; import computeProps from './computeProps'; type Props = { placeholderTextColor: ?string, }; export default class Input extends Base { props: Props; getInitialStyle(): Object { return { input: { height: this.getTheme().inputHeightBase, color: this.getTheme().inputColor, paddingLeft: 5, paddingRight: 5, fontSize: this.getTheme().inputFontSize, lineHeight: this.getTheme().inputLineHeight, }, }; } prepareRootProps(): Object { let defaultProps = { style: this.getInitialStyle().input, }; return computeProps(this.props, defaultProps); } render(): React$Element<any> { return ( <View style={{ flex: 1 }}> <TextInput {...this.prepareRootProps()} placeholderTextColor={this.props.placeholderTextColor ? this.props.placeholderTextColor : this.getTheme().inputColorPlaceholder} underlineColorAndroid="rgba(0,0,0,0)"/> </View> ); } }
src/routes/home/index.js
willchertoff/Ben-Kinde
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Home from './Home'; import Layout from '../../components/Layout'; async function action() { return { chunks: ['home'], title: 'Ben Kinde', component: <Layout><Home /></Layout>, }; } export default action;
src/index.js
roycejewell/flux-ui-example
import React from 'react'; import ReactDOM from 'react-dom'; import Router from 'react-router'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import routes from './routes.js'; import 'styles/styles.css'; const router = { routes, history: createBrowserHistory(), createElement: (component, props) => { return React.createElement(component, { ...props }); } }; ReactDOM.render( React.createElement(Router, { ...router }), document.getElementById('root') );
src/containers/ChannelData/index.js
TerryCapan/twitchBot
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import SparklineChart from '../../components/SparklineChart'; import { getTone, unsetTone } from '../../actions/index'; /* component styles */ import { styles } from './styles.scss'; class ChannelData extends Component { constructor(props) { super(props); this.state = { currentMsgCount: 0, prevMinMsgCount: 0, prevSecMsgCount: 0, avgMsgPerMin: 0, avgMsgPerSec: 0, charCount: 0, avgLength: 0, lastMsg: '', time: new Date(), msgPerMinArray: [], msgLengthArray: [], msgPerSecArray: [], lastMinTotal: 0, lastSecTotal: 0, watsonString: '', }; } componentDidMount() { this.minuteInt = setInterval(() => { this.msgRateEveryMinute(); }, 60000); this.secondInt = setInterval(() => { this.msgRateEverySecond(); }, 1000); this.watsonInt = setInterval(() => { if (this.state.watsonString.length) { const currentWatsonString = this.state.watsonString; this.setState({ watsonString: '' }); this.props.getTone(currentWatsonString); } else { this.props.unsetTone(); } }, 3000); } componentWillReceiveProps(props) { this.calculateAverages(props); } componentWillUnmount() { clearInterval(this.minuteInt); clearInterval(this.secondInt); clearInterval(this.watsonInt); } msgRateEveryMinute() { const newCurrentCount = this.state.currentMsgCount; const lastMinMsgCount = newCurrentCount - this.state.prevMinMsgCount; const newMsgPerMinArray = this.state.msgPerMinArray.concat([lastMinMsgCount]); if (newMsgPerMinArray.length > 60) { newMsgPerMinArray.shift(); } this.setState({ prevMinMsgCount: newCurrentCount, msgPerMinArray: newMsgPerMinArray, lastMinTotal: lastMinMsgCount, }); } msgRateEverySecond() { const newCurrentCount = this.state.currentMsgCount; const lastSecMsgCount = newCurrentCount - this.state.prevSecMsgCount; const newMsgPerSecArray = this.state.msgPerSecArray.concat([lastSecMsgCount]); if (newMsgPerSecArray.length > 60) { newMsgPerSecArray.shift(); } this.setState({ prevSecMsgCount: newCurrentCount, msgPerSecArray: newMsgPerSecArray, lastSecTotal: lastSecMsgCount, }); } calculateAverages(props) { let newCount; let newAvgLength; let newCharCount; let newWatsonString; const elapsedMinutes = (Math.abs(new Date() - this.state.time)) / 60000; const elapsedSeconds = (Math.abs(new Date() - this.state.time)) / 1000; if (this.state.lastMsg !== props.message) { newWatsonString = this.state.watsonString.concat(props.message); newCount = this.state.currentMsgCount + 1; newCharCount = this.state.charCount + props.message.length; newAvgLength = newCharCount / newCount; } else { newWatsonString = this.state.watsonString; newCount = this.state.currentMsgCount; newCharCount = this.state.charCount; newAvgLength = this.state.avgLength; } const newMsgPerMin = newCount / elapsedMinutes; const newMsgPerSec = newCount / elapsedSeconds; const newMsgLengthArray = this.state.msgLengthArray.concat([props.message.length]); if (newMsgLengthArray.length > 200) { newMsgLengthArray.shift(); } this.setState({ currentMsgCount: newCount, avgMsgPerMin: newMsgPerMin, avgMsgPerSec: newMsgPerSec, charCount: newCharCount, avgLength: newAvgLength, lastMsg: props.message, msgLengthArray: newMsgLengthArray, watsonString: newWatsonString, }); } render() { return ( <section className={`${styles}`}> <div className="row"> <div className="col-md-4 col-md-push-8"> <section className="msg-data"> <h5>Average message length: {Math.round(this.state.avgLength)}</h5> <h5>Last message length: {this.state.lastMsg.length}</h5> <div className="msg-chart"><SparklineChart data={this.state.msgLengthArray} color="blue" limit={200} /></div> </section> </div> <div className="col-md-4"> <section className="msg-data"> <h5>Average Messages per Second: {(this.state.avgMsgPerSec).toFixed(2)}</h5> <h5>Last second's total: {this.state.lastSecTotal}</h5> <div className="msg-chart"><SparklineChart data={this.state.msgPerSecArray} color="green" limit={60} /></div> </section> </div> <div className="col-md-4 col-md-pull-8"> <section className="msg-data"> <h5>Average Messages per Minute: {Math.round(this.state.avgMsgPerMin)}</h5> <h5>Last minute's total: {this.state.lastMinTotal}</h5> <div className="msg-chart"><SparklineChart data={this.state.msgPerMinArray} color="red" limit={60} /></div> </section> </div> </div> <div className="row"> <span>Total Messages since arrival: {this.state.currentMsgCount}</span> </div> </section> ); } } ChannelData.propTypes = { getTone: React.PropTypes.func, unsetTone: React.PropTypes.func, }; function mapDispatchToProps(dispatch) { return bindActionCreators({ getTone, unsetTone }, dispatch); } export default connect(null, mapDispatchToProps)(ChannelData);
blueocean-material-icons/src/js/components/svg-icons/action/card-membership.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionCardMembership = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.11 0-2 .89-2 2v11c0 1.11.89 2 2 2h4v5l4-2 4 2v-5h4c1.11 0 2-.89 2-2V4c0-1.11-.89-2-2-2zm0 13H4v-2h16v2zm0-5H4V4h16v6z"/> </SvgIcon> ); ActionCardMembership.displayName = 'ActionCardMembership'; ActionCardMembership.muiName = 'SvgIcon'; export default ActionCardMembership;
app/components/CarsList/index.js
aditigoel23/React-Car-App
import React from 'react'; import _ from 'lodash'; import CarListItem from '../CarListItem/index'; import Wrapper from './Wrapper'; function CarsList(props) { const carTypes = _.get(props, 'metaData.CarTypes', []); let list = []; if (Array.isArray(props.items)) { list = _.map(props.items, (car) => <CarListItem key={car.ResultId} types={carTypes} item={car} /> ); } return ( <Wrapper> {list} </Wrapper> ); } CarsList.propTypes = { items: React.PropTypes.array, }; export default CarsList;
docs/src/examples/elements/Segment/Variations/SegmentExampleCompact.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Segment } from 'semantic-ui-react' const SegmentExampleCompact = () => <Segment compact>Compact content.</Segment> export default SegmentExampleCompact
imports/client/ui/components/HoursFormatted/index.js
focallocal/fl-maps
import React from 'react' import { formatDateWithWords, formatDate } from '/imports/client/utils/format' import { findNextEvent, calibrateEndWeekday } from '/imports/client/utils/findNextEvent' import './styles.scss' const HoursFormatted = ({ data }) => { const { startingDate, endingDate, startingTime, endingTime } = data if (data.multipleDays) { const isEnding = !!endingDate return ( <div className='hours-formatted multiple-days'> {isEnding && ( <div className='date'> {formatDateWithWords(startingDate)} - {formatDateWithWords(endingDate)} </div> )} {data.days.map((day, index) => ( (day && day.day) && <div key={index} className='day'> <div>{day.day.substr(0, 3)}</div> <span>{day.startingTime} - {day.endingTime}</span> </div> ))} </div> ) } const isSameDay = startingDate.toDateString() === endingDate.toDateString(); if (data.repeat) { const { days, every, forever, type, until, occurences, monthly, recurrenceEndDate } = data.recurring const weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] let daysOrdered = days if (days) daysOrdered = weekDays.filter((e) => days.indexOf(e) >= 0) let nextEventInstance = findNextEvent(startingDate, type, every, days, monthly) // DESCRIPTION: Reusable Fragment with timestamp on Next Occurence const nextOccurence = ( <li className='hours-formatted regular-date'> <span>Next:<br/> {formatDateWithWords(nextEventInstance)}<br/> {startingTime} - </span> {isSameDay ? endingTime : <div> {formatDateWithWords( new Date(Date.parse(nextEventInstance) + (endingDate.getTime() - startingDate.getTime())) )}, {endingTime} </div> } </li> ) // DESCRIPTION: Reusable Fragment with repetition details const repeatTitle = <span>Repeating:<br/></span> const repeatSchedule = `every ${every > 1 ? every : ''} ${type + (every > 1 ? 's' : '')}` const startingWeekday = startingDate.getDay() let endingWeekday = endingDate.getDay() if (daysOrdered) endingWeekday = weekDays.indexOf(daysOrdered[daysOrdered.length - 1]) const adjustedEndDate = calibrateEndWeekday(startingDate, endingDate, days, recurrenceEndDate) const notForeverDay = ( <div className='not-forever'> {(data.repeat && occurences) && `until ${formatDateWithWords(recurrenceEndDate)}`} {(data.repeat && until) && `until ${formatDateWithWords(until)}`} </div> ) const notForeverWeek = ( <div className='not-forever'> {(data.repeat && occurences && startingWeekday === endingWeekday) && `until ${formatDateWithWords(recurrenceEndDate)}`} {(data.repeat && occurences && startingWeekday !== endingWeekday) && `until ${formatDateWithWords(adjustedEndDate)}`} {(data.repeat && until) && `until ${formatDateWithWords(until)}`} </div> ) const notForeverMonth = ( <div className='not-forever'> {(data.repeat && occurences) && `through ${months[recurrenceEndDate.getMonth()]}`} {(data.repeat && until) && `through ${months[until.getMonth()]}`} </div> ) if (type === 'day') { return ( <ul className='hours-formatted repeat'> {(forever === true) && nextOccurence} {(!forever && recurrenceEndDate && new Date() < recurrenceEndDate) && nextOccurence} {(!forever && until && new Date() < until) && nextOccurence} <li>{repeatTitle} {repeatSchedule}, between {startingTime} - {endingTime} </li> {!forever && notForeverDay} </ul> ) } else if (type === 'week') { return ( <ul className='hours-formatted repeat'> {(forever === true) && nextOccurence} {(!forever && recurrenceEndDate && new Date() < recurrenceEndDate) && nextOccurence} {(!forever && until && new Date() < until) && nextOccurence} <li> <span className='every-sentence'>{repeatTitle} {repeatSchedule}</span><br/> {daysOrdered.map((day, index) => ( day && <div key={index} className='day'> <span>on {day.substr(0, 3)}, {startingTime} - {endingTime}</span><br/> </div> ))} </li> {!forever && notForeverWeek} </ul> ) } else if (type === 'month') { return ( <ul className='hours-formatted repeat'> {nextOccurence} <li> <span className='every-sentence'>{repeatTitle} {repeatSchedule} </span><br/> <span> {(monthly.type === 'byDayInMonth' && monthly.value === 1) && `on the ${monthly.value}st`} {(monthly.type === 'byDayInMonth' && monthly.value === 2) && `on the ${monthly.value}nd`} {(monthly.type === 'byDayInMonth' && monthly.value === 3) && `on the ${monthly.value}rd`} {(monthly.type === 'byDayInMonth' && monthly.value > 3) && `on the ${monthly.value}th`} {(monthly.type === 'byPosition' && monthly.value === 1) && `on the ${monthly.value}st ${weekDays[startingDate.getDay()]}`} {(monthly.type === 'byPosition' && monthly.value === 2) && `on the ${monthly.value}nd ${weekDays[startingDate.getDay()]}`} {(monthly.type === 'byPosition' && monthly.value === 3) && `on the ${monthly.value}rd ${weekDays[startingDate.getDay()]}`} {(monthly.type === 'byPosition' && monthly.value > 3) && `on the ${monthly.value}th ${weekDays[startingDate.getDay()]}`} </span> </li> {!forever && notForeverMonth} </ul> ) } } // DESCRIPTION: if !data.repeat then default view is start + end timestamp const endFragment = ( isSameDay ? endingTime : <div> {formatDateWithWords(endingDate)}, {endingTime} </div> ) const ongoing = endingDate.getFullYear() - startingDate.getFullYear() > 5 return ( <div className='hours-formatted regular-date'> <span>{ongoing && `From`} {formatDateWithWords(startingDate)}, {startingTime} - </span> {ongoing ? `until further notice` : endFragment} </div> ) } export default HoursFormatted
packages/icons/src/md/editor/VerticalAlignBottom.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdVerticalAlignBottom(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M32 26h-6V6h-4v20h-6l8 8 8-8zM8 38v4h32v-4H8z" /> </IconBase> ); } export default MdVerticalAlignBottom;
src/App.js
jp7internet/react-apz
import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import ContactList from './containers/ContactList'; import ContactCreate from './containers/ContactCreate'; import ContactEdit from './containers/ContactEdit'; import './App.css'; class App extends Component { render() { return ( <Router> <div> <nav className="navbar navbar-default"> <div className="container-fluid"> <div className="navbar-header"> <Link className="navbar-brand" to="/">React Apz</Link> </div> </div> </nav> <section id="content" className="container-fluid"> <h2>Contacts Manager</h2> <div className="container"> <Route exact path="/" component={ContactList} /> <Route path="/new" component={ContactCreate} /> <Route path="/edit/:contactId" component={ContactEdit} /> </div> </section> </div> </Router> ); } } export default App;
src/svg-icons/places/golf-course.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesGolfCourse = (props) => ( <SvgIcon {...props}> <circle cx="19.5" cy="19.5" r="1.5"/><path d="M17 5.92L9 2v18H7v-1.73c-1.79.35-3 .99-3 1.73 0 1.1 2.69 2 6 2s6-.9 6-2c0-.99-2.16-1.81-5-1.97V8.98l6-3.06z"/> </SvgIcon> ); PlacesGolfCourse = pure(PlacesGolfCourse); PlacesGolfCourse.displayName = 'PlacesGolfCourse'; PlacesGolfCourse.muiName = 'SvgIcon'; export default PlacesGolfCourse;
src/svg-icons/toggle/star-border.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ToggleStarBorder = (props) => ( <SvgIcon {...props}> <path d="M22 9.24l-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03L22 9.24zM12 15.4l-3.76 2.27 1-4.28-3.32-2.88 4.38-.38L12 6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28L12 15.4z"/> </SvgIcon> ); ToggleStarBorder = pure(ToggleStarBorder); ToggleStarBorder.displayName = 'ToggleStarBorder'; ToggleStarBorder.muiName = 'SvgIcon'; export default ToggleStarBorder;
src/components/pages/about.js
ranhouxingfu/website-by-react
import React from 'react' import { Grid, Col, Image, Icon } from 'amazeui-react' export default class aboutUs extends React.Component { constructor(props) { super(props); this.state = {} } render() { return( <div className='contain'> <div className='about-box'> <img src='../images/aboutus-bg.jpg'/> <div className='about-designP'> <h2 className='about-title'>欢迎来到Touch餐厅 </h2> </div></div> <p className='aboutus-describe'>高端氛围,奢华环境,精致产品,独特口感,让人流连忘返。高端氛围,奢华环境,精致产品,独特口感,让人流连忘返。高端氛围,奢华环境,精致产品,独特口感,让人流连忘返。</p> <Grid className='about-last-box'> <Col sm={12} md={5} lg={4} mdOffset={1} lgOffset={2}> <Col sm={12} className='about-left-box'> <Col sm={12} md={3} lg={2} className='about-design'> <Image src="../images/food-design3.jpg" width="70" height="70" circle /></Col> <Col sm={12} md={9} lg={9} lgOffset={1}> <h3 className='about-design'>好吃不胖特色菜</h3> <p className='about-design'>您的梦想需要一个非同凡响的网站</p> </Col> </Col> <Col sm={12} className='about-left-box'> <Col sm={12} md={3} lg={2} className='about-design'> <Image src="../images/food-design4.jpg" width="70" height="70" circle /></Col> <Col sm={12} md={9} lg={9} lgOffset={1}> <h3 className='about-design'>安全的原材料</h3> <p className='about-design'>您的梦想需要一个非同凡响的网站</p> </Col> </Col> <Col sm={12} className='about-left-box'> <Col sm={12} md={3} lg={2} className='about-design'> <Image src="../images/food-design4.jpg" width="70" height="70" circle /></Col> <Col sm={12} md={9} lg={9} lgOffset={1}> <h3 className='about-design'>最物美价廉的餐饮</h3> <p className='about-design'>您的梦想需要一个非同凡响的网站</p> </Col> </Col> </Col> <Col sm={12} md={5} lg={4} className='about-rigth-imgbox'> <img src='../images/food-design6.jpg'/> </Col> <Col md={1} lg={2} ></Col> </Grid> <div className='work-box'> <div className='work-content-box'> <h3>餐厅营业时间</h3> <p>午餐:<span><Icon icon='star'/><Icon icon='star'/><Icon icon='star'/><Icon icon='star'/><Icon icon='star'/></span></p> <p className='work-time'>10:00am--14:00pm</p> <p className='work-dinner'>晚餐:<span><Icon icon='star'/><Icon icon='star'/><Icon icon='star'/><Icon icon='star'/><Icon icon='star'/></span></p> <p className='work-time'>17:00pm--22:00pm</p> <p className='work-dinner'>地址:北京市海淀区惠民路1号高端创意科技广场B座25层</p> </div> </div> </div> ) } }
ExampleApp/index.ios.js
joonhocho/react-native-linkedin-sdk
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, TouchableHighlight } from 'react-native'; import LinkedInSDK from 'react-native-linkedin-sdk'; export default class ExampleApp extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> <TouchableHighlight onPress={async () => { const token = await LinkedInSDK.signIn({ // https://developer.linkedin.com/docs/oauth2 // iOS (Required) // The "API Key" value generated when you registered your application. clientID: '86ltc4i0wckzvo', // iOS (Required) clientSecret: 'KCPHGyyXOjmGy72S', // iOS (Required) // A unique string value of your choice that is hard to guess. Used to prevent CSRF. state: 'abcde', // iOS, Android (Required) scopes: [ 'r_basicprofile', ], // iOS (Required) // The URI your users will be sent back to after authorization. This value must match one of the defined OAuth 2.0 Redirect URLs in your application configuration. // e.g. https://www.example.com/auth/linkedin redirectUri: 'https://github.com/joonhocho/react-native-linkedin-sdk/oauth2callback', }); const profile = await LinkedInSDK.getRequest('https://api.linkedin.com/v1/people/~?format=json'); setTimeout(() => { alert(JSON.stringify({token, profile}, null, ' ')); }, 1500); }}> <Text style={styles.instructions}> LinkedIn Sign-In </Text> </TouchableHighlight> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('ExampleApp', () => ExampleApp);
test/integration/client-navigation/pages/memo-component.js
flybayer/next.js
import React from 'react' export default React.memo((props) => <span {...props}>Memo component</span>)
apps/marketplace/components/BuyerSpecialist/BuyerSpecialistAboutStage.js
AusDTO/dto-digitalmarketplace-frontend
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { Form } from 'react-redux-form' import Textfield from 'shared/form/Textfield' import Textarea from 'shared/form/Textarea' import CheckboxDetailsField from 'shared/form/CheckboxDetailsField' import formProps from 'shared/form/formPropsSelector' import { required } from 'marketplace/components/validators' import AUheadings from '@gov.au/headings/lib/js/react.js' import ErrorAlert from 'marketplace/components/Alerts/ErrorAlert' import locations from 'marketplace/components/BuyerBriefFlow/Locations' import styles from './BuyerSpecialistAboutStage.scss' const requiredTitle = v => required(v.title) const requiredOrg = v => required(v.organisation) const requiredSummary = v => required(v.summary) const atLeastOneLocation = v => v.location && v.location.length > 0 export const done = v => requiredTitle(v) && requiredOrg(v) && requiredSummary(v) && atLeastOneLocation(v) const BuyerSpecialistAboutStage = props => ( <Form model={props.model} validators={{ '': { requiredTitle, requiredOrg, requiredSummary, atLeastOneLocation } }} onSubmit={props.onSubmit} onSubmitFailed={props.onSubmitFailed} validateOn="submit" > <AUheadings level="1" size="xl"> About </AUheadings> <ErrorAlert model={props.model} messages={{ requiredTitle: 'Enter the title for your opportunity.', requiredOrg: 'Enter the name of your organisation.', requiredSummary: 'You must answer "what will the specialist do".', atLeastOneLocation: 'You must select at least one location.' }} /> <Textfield model={`${props.model}.title`} label="Role title" name="title" id="title" htmlFor="title" defaultValue={props[props.model].title} maxLength={100} validators={{ required }} /> <Textfield model={`${props.model}.organisation`} label="Who will the specialist work for?" description="Write the full name of the organisation." placeholder="For example, Digital Transformation Agency instead of DTA." name="organisation" id="organisation" htmlFor="organisation" defaultValue={props[props.model].organisation} maxLength={150} validators={{ required }} /> <Textarea model={`${props.model}.summary`} label="What will the specialist do?" name="summary" id="summary" htmlFor="summary" defaultValue={props[props.model].summary} controlProps={{ limit: 1000, rows: '10' }} validators={{ required }} messages={{ limitWords: 'Your summary has exceeded the 1000 word limit' }} /> <AUheadings level="2" size="sm"> Where can the work be done? </AUheadings> <div className={styles.locations}> {Object.keys(locations).map(key => ( <CheckboxDetailsField key={key} model={`${props.model}.location[]`} id={`location_${key}`} name={`location_${key}`} label={locations[key]} value={locations[key]} detailsModel={props.model} validators={{}} messages={{}} /> ))} </div> {props.formButtons} </Form> ) BuyerSpecialistAboutStage.defaultProps = { onSubmit: () => {}, onSubmitFailed: () => {} } BuyerSpecialistAboutStage.propTypes = { model: PropTypes.string.isRequired, formButtons: PropTypes.node.isRequired, onSubmit: PropTypes.func, onSubmitFailed: PropTypes.func } const mapStateToProps = (state, props) => ({ ...formProps(state, props.model) }) export default connect(mapStateToProps)(BuyerSpecialistAboutStage)
blueocean-material-icons/src/js/components/svg-icons/action/event-seat.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionEventSeat = (props) => ( <SvgIcon {...props}> <path d="M4 18v3h3v-3h10v3h3v-6H4zm15-8h3v3h-3zM2 10h3v3H2zm15 3H7V5c0-1.1.9-2 2-2h6c1.1 0 2 .9 2 2v8z"/> </SvgIcon> ); ActionEventSeat.displayName = 'ActionEventSeat'; ActionEventSeat.muiName = 'SvgIcon'; export default ActionEventSeat;
pages/notes/index.js
jhanstra/jh-gatsby
import React from 'react' import TopNav from '../../src/components/core/TopNav' class Notes extends React.Component { render () { return ( <div> <div className="full-title"> <h1>Notes</h1> <h3>Notes, reflections, and highlights from my studies and the books I read</h3> </div> <div className="row default"> </div> </div> ) } } export default Notes;
src/index.js
mduleone/crapshoot
import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import {BrowserRouter as Router} from 'react-router-dom'; import injectTapEventPlugin from "react-tap-event-plugin"; import MuiThemeProvider from "material-ui/styles/MuiThemeProvider"; import initializeStore from './config/store'; import RoutingTable from './config/routes'; import './index.css'; injectTapEventPlugin(); const store = initializeStore({}); ReactDOM.render( // @TODO: Update the basename to match your default path, or remove it if you are mounted at `/` <Provider store={store}> <MuiThemeProvider> <Router basename="/crapshoot"> <RoutingTable /> </Router> </MuiThemeProvider> </Provider>, document.getElementById('root') );
frontend/src/Movie/Details/Titles/MovieTitlesTableContentConnector.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import MovieTitlesTableContent from './MovieTitlesTableContent'; function createMapStateToProps() { return createSelector( (state) => state.movies, (movies) => { return movies; } ); } const mapDispatchToProps = { // fetchMovies }; class MovieTitlesTableContentConnector extends Component { // // Render render() { const movie = this.props.items.filter((obj) => { return obj.id === this.props.movieId; }); return ( <MovieTitlesTableContent {...this.props} items={movie[0].alternateTitles} /> ); } } MovieTitlesTableContentConnector.propTypes = { movieId: PropTypes.number.isRequired, items: PropTypes.arrayOf(PropTypes.object).isRequired }; export default connect(createMapStateToProps, mapDispatchToProps)(MovieTitlesTableContentConnector);
src/components/Logo/index.js
badT/Chatson
import React, { Component } from 'react'; import TimelineMax from 'gsap/src/minified/TimelineMax.min'; /* component styles */ import { styles } from './styles.scss'; export default class Logo extends Component { constructor(props) { super(props); this.state = { logo: new TimelineMax, hatson: new TimelineMax, animating: true, }; } componentDidMount() { const shrink = new TimelineMax; shrink.to('#hhh', 0, { scale: 0.25 }) .to('#aaa', 0, { scale: 0.25 }) .to('#ttt', 0, { scale: 0.25 }) .to('#sss', 0, { scale: 0.25 }) .to('#ooo', 0, { scale: 0.25 }) .to('#nnn', 0, { scale: 0.25 }); setTimeout(() => { this.logoAnimate().forward(); }, 1500); } logoAnimate() { const forward = () => { this.state.logo.to('#mouth', 2, { rotation: 270, x: 5, y: -4, transformOrigin: '10px 5px' }) .to('.eyes', 2, { rotation: 90, x: 41, y: -4 }, '-=2') .to('#left_ball', 0.75, { opacity: 0, x: 5, y: -45 }, '-=1.15') .to('#right_ball', 0.75, { opacity: 0, x: 25, y: -35 }, '-=0.8') .duration(1.5) .eventCallback('onReverseComplete', () => { setTimeout(() => { this.state.logo.timeScale(2.5).play(); }, 300); }); this.state.hatson .to('#hhh', 0.75, { opacity: 100, scale: 1.8, y: 4 }) .to('#aaa', 0.75, { opacity: 100, scale: 1.7, x: 12, y: 3 }, '-=0.5') .to('#ttt', 0.75, { opacity: 100, scale: 1.7, x: 22, y: -0.65 }, '-=0.5') .to('#sss', 0.75, { opacity: 100, scale: 1.7, x: 32, y: 3 }, '-=0.5') .to('#ooo', 0.75, { opacity: 100, scale: 1.7, x: 42, y: 3 }, '-=0.5') .to('#nnn', 0.75, { opacity: 100, scale: 1.7, x: 54, y: 3 }, '-=0.5') .duration(1.5) .eventCallback('onReverseComplete', () => { setTimeout(() => { this.state.hatson.timeScale(2.5).play(); }, 300); }) .eventCallback('onComplete', () => { this.setState({ animating: false }); }); }; const rewind = () => { if (!this.state.animating) { this.setState({ animating: true }); this.state.logo .timeScale(3) .reverse(0); this.state.hatson .timeScale(3) .reverse(0); } }; return { forward, rewind, }; } render() { return ( <div className={`${styles}`}> <span className="logo-holder"> <svg className="logo" width="60" height="60" viewBox="-2 -2 64 74" onMouseEnter={() => { this.logoAnimate().rewind(); }}> <g className="eyes"> <line id="left_eye" fill="none" stroke="#ffffff" strokeWidth="3" stroke-miterlimit="10" x1="12.5" y1="8.9" x2="24.3" y2="8.9" /> <line id="right_eye" fill="none" stroke="#ffffff" strokeWidth="3" stroke-miterlimit="10" x1="35.8" y1="8.9" x2="47.7" y2="8.9" /> <path id="left_ball" fill="#FF1D25" stroke="#FF1D25" strokeWidth="1.35" stroke-miterlimit="10" d="M14.9,10.3c0,1.9,1.4,3.5,3,3.8 c1.9,0.3,4.1-1.4,4.1-3.8" /> <path id="right_ball" fill="#FF1D25" stroke="#FF1D25" strokeWidth="1.35" stroke-miterlimit="10" d="M38.1,10.3c0,1.9,1.4,3.5,3,3.8 c1.9,0.3,4.1-1.4,4.1-3.8" /> </g> <path id="mouth" fill="none" stroke="#ffffff" strokeWidth="5" stroke-miterlimit="10" d="M46.1,47.6c0.3-1.3,1.2-5.4-0.7-9.9 c-1.7-4.2-4.9-6.4-5.8-7.1c-0.6-0.4-1.7-1.2-3.6-1.9c-0.7-0.3-3.6-1.3-7.4-1c-1.3,0.1-4.6,0.4-8,2.5c-1,0.6-3.2,2-4.9,4.6 c-1.6,2.3-1.9,4.5-2.2,5.7c-0.6,3-0.3,5.7,0.1,7.2" /> </svg> <span> <svg className="hatson" width="124.5" height="60" viewBox="0 0 200 100"> <g className="letters"> <path id="hhh" opacity="0" fill="none" stroke="#FF1D25" strokeWidth="2.5" stroke-miterlimit="10" d="M12.7,26.6c0.3-0.5,0.7-1.2,1.5-1.8 c0.8-0.6,1.5-0.9,2.1-1c1.2-0.3,2.1-0.3,2.6-0.3c0.6,0,1.5,0.1,2.5,0.6c0.4,0.2,1.1,0.5,1.7,1.2c0.2,0.2,0.7,0.8,1,1.7 c0.2,0.6,0.3,1.1,0.3,1.4c0.1,0.4,0.1,0.8,0.1,1.1c0,0.2,0,0.4,0,1.1c0,0.4,0,0.6,0,1c0,0.1,0,0.3,0,0.6c0,0.4,0,0.7,0,0.9 c0,0.6,0,0.8,0,1.5c0,0.7,0,1.2,0,1.6c0,0.8,0,2,0,4" /> <path id="aaa" opacity="0" strokeWidth="2" fill="#FF1D25" stroke="#FF1D25" d="M42.2,36.9c0,0.6,0,1.3,0.1,2c0.1,0.7,0.1,1.3,0.2,1.8h-0.8c0-0.2-0.1-0.5-0.1-0.9c0-0.4-0.1-0.7-0.1-1.1 c0-0.4-0.1-0.8-0.1-1.1c0-0.4,0-0.7,0-0.9h-0.1c-0.5,1.5-1.3,2.7-2.5,3.4c-1.2,0.7-2.5,1.1-3.9,1.1c-0.7,0-1.4-0.1-2-0.3 c-0.7-0.2-1.3-0.5-1.8-0.9c-0.5-0.4-1-0.9-1.3-1.5c-0.3-0.6-0.5-1.3-0.5-2.2c0-1.2,0.3-2.2,0.9-2.9c0.6-0.7,1.4-1.3,2.3-1.7 c0.9-0.4,1.9-0.7,3-0.8c1.1-0.1,2-0.2,2.9-0.2h3v-1.4c0-1.9-0.5-3.3-1.5-4.1c-1-0.9-2.3-1.3-3.9-1.3c-1,0-2,0.2-2.8,0.6 c-0.9,0.4-1.7,0.9-2.3,1.5l-0.4-0.6c0.8-0.7,1.7-1.2,2.7-1.6c1-0.4,2-0.5,2.9-0.5c1.9,0,3.5,0.5,4.6,1.5c1.1,1,1.7,2.6,1.7,4.7 V36.9z M41.4,31.5h-2.6c-0.9,0-1.9,0.1-3,0.2c-1,0.1-2,0.3-2.8,0.7c-0.9,0.3-1.6,0.8-2.1,1.5c-0.6,0.6-0.8,1.5-0.8,2.6 c0,0.8,0.2,1.4,0.5,2c0.3,0.5,0.7,1,1.2,1.3c0.5,0.3,1,0.6,1.6,0.7c0.6,0.1,1.1,0.2,1.6,0.2c1.3,0,2.3-0.2,3.1-0.7 c0.8-0.5,1.5-1.1,2-1.8c0.5-0.7,0.9-1.5,1.1-2.4c0.2-0.9,0.3-1.7,0.3-2.6V31.5z" /> <path id="ttt" opacity="0" strokeWidth="2" fill="#FF1D25" stroke="#FF1D25" d="M54.6,41c-0.4,0.1-0.8,0.1-1.1,0.1c-1.3,0-2.3-0.4-2.8-1.1c-0.6-0.7-0.8-1.7-0.8-2.8V24.5h-3.7v-0.7h3.7v-5h0.8v5h5v0.7 h-5v12.8c0,1.2,0.3,2,0.8,2.5c0.6,0.5,1.3,0.8,2.3,0.8c0.7,0,1.3-0.1,1.9-0.3l0.1,0.6C55.3,40.9,55,41,54.6,41z" /> <path id="sss" opacity="0" strokeWidth="2" fill="#FF1D25" stroke="#FF1D25" d="M69.9,36.3c0,0.8-0.1,1.4-0.4,2c-0.3,0.6-0.7,1.1-1.2,1.5c-0.5,0.4-1.1,0.7-1.8,1c-0.7,0.2-1.4,0.3-2.1,0.3 c-1.3,0-2.4-0.2-3.4-0.7c-1-0.5-1.9-1.2-2.5-2.1l0.7-0.4c1.2,1.7,3,2.6,5.3,2.6c0.5,0,1.1-0.1,1.6-0.3c0.6-0.2,1.1-0.4,1.5-0.8 c0.5-0.3,0.8-0.8,1.1-1.3c0.3-0.5,0.4-1.1,0.4-1.8c0-0.8-0.2-1.4-0.5-1.9c-0.4-0.5-0.8-0.9-1.3-1.2c-0.5-0.3-1.1-0.5-1.8-0.7 c-0.7-0.2-1.3-0.4-1.8-0.5c-0.6-0.2-1.2-0.4-1.7-0.6c-0.5-0.2-1-0.5-1.4-0.8c-0.4-0.3-0.7-0.7-1-1.2c-0.2-0.5-0.4-1.1-0.4-1.8 s0.1-1.4,0.4-1.9c0.3-0.5,0.7-1,1.2-1.3c0.5-0.4,1.1-0.6,1.7-0.8c0.6-0.2,1.3-0.3,1.9-0.3c2.3,0,4,0.8,5.2,2.5l-0.7,0.4 c-0.6-0.7-1.2-1.3-1.9-1.6c-0.7-0.4-1.6-0.5-2.6-0.5c-0.5,0-1,0.1-1.5,0.2c-0.5,0.1-1,0.3-1.4,0.6c-0.4,0.3-0.8,0.7-1.1,1.1 c-0.3,0.5-0.4,1-0.4,1.7c0,0.7,0.1,1.3,0.4,1.8c0.2,0.4,0.6,0.8,1,1.1c0.4,0.3,0.9,0.5,1.5,0.7c0.6,0.2,1.2,0.4,2,0.5 c0.7,0.2,1.3,0.4,1.9,0.6c0.6,0.2,1.2,0.5,1.7,0.9c0.5,0.3,0.9,0.8,1.1,1.3C69.7,34.9,69.9,35.5,69.9,36.3z" /> <path id="ooo" opacity="0" strokeWidth="2" fill="#FF1D25" stroke="#FF1D25" d="M91.9,32.2c0,1.3-0.2,2.5-0.6,3.6c-0.4,1.1-1,2.1-1.8,2.9c-0.8,0.8-1.7,1.4-2.8,1.9c-1.1,0.4-2.3,0.7-3.6,0.7 c-1.3,0-2.5-0.2-3.6-0.7c-1.1-0.4-2-1.1-2.8-1.9c-0.8-0.8-1.4-1.8-1.8-2.9c-0.4-1.1-0.6-2.3-0.6-3.6s0.2-2.5,0.6-3.6 c0.4-1.1,1-2,1.8-2.8c0.8-0.8,1.7-1.4,2.8-1.8c1.1-0.4,2.3-0.7,3.6-0.7c1.3,0,2.5,0.2,3.6,0.7c1.1,0.4,2,1.1,2.8,1.8 c0.8,0.8,1.4,1.7,1.8,2.8C91.7,29.7,91.9,30.9,91.9,32.2z M91.1,32.2c0-1.1-0.2-2.2-0.6-3.2c-0.4-1-0.9-1.9-1.6-2.6 c-0.7-0.7-1.6-1.3-2.5-1.8c-1-0.4-2.1-0.6-3.4-0.6c-1.3,0-2.4,0.2-3.4,0.6c-1,0.4-1.8,1-2.5,1.8c-0.7,0.7-1.2,1.6-1.6,2.6 c-0.4,1-0.6,2.1-0.6,3.2c0,1.2,0.2,2.2,0.6,3.2c0.4,1,0.9,1.9,1.6,2.6c0.7,0.7,1.5,1.3,2.5,1.8c1,0.4,2.1,0.7,3.4,0.7 c1.3,0,2.4-0.2,3.4-0.7c1-0.4,1.8-1,2.5-1.8c0.7-0.7,1.2-1.6,1.6-2.6C90.9,34.4,91.1,33.3,91.1,32.2z" /> <path id="nnn" opacity="0" strokeWidth="2" fill="#FF1D25" stroke="#FF1D25" d="M100,26.1c0.5-0.6,1-1.1,1.6-1.6c0.6-0.4,1.2-0.8,1.9-1c0.7-0.2,1.4-0.3,2.1-0.3c1.2,0,2.2,0.2,3,0.6 c0.8,0.4,1.4,1,1.9,1.7c0.5,0.7,0.8,1.5,1,2.3c0.2,0.9,0.3,1.7,0.3,2.6v10.2h-0.8V30.5c0-0.7-0.1-1.4-0.2-2.2 c-0.1-0.8-0.4-1.5-0.8-2.1c-0.4-0.6-1-1.2-1.6-1.6c-0.7-0.4-1.6-0.6-2.6-0.6c-0.9,0-1.8,0.2-2.6,0.6c-0.8,0.4-1.5,0.9-2.1,1.6 c-0.6,0.7-1.1,1.6-1.4,2.6c-0.4,1-0.5,2.2-0.5,3.5v8.5h-0.8V28c0-0.3,0-0.6,0-1c0-0.4,0-0.8,0-1.2c0-0.4,0-0.8-0.1-1.2 c0-0.4,0-0.7-0.1-0.9h0.8c0,0.2,0,0.6,0.1,0.9c0,0.4,0,0.8,0,1.2c0,0.4,0,0.8,0,1.3c0,0.4,0,0.8,0,1.1h0.1 C99.2,27.4,99.5,26.7,100,26.1z" /> </g> </svg> </span> </span> </div> ); } }
src/components/Tabs/Tabs-story.js
wfp/ui
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { withKnobs, number, text } from '@storybook/addon-knobs'; import Tabs from '../Tabs'; import Tab from '../Tab'; import Tag from '../Tag'; import TabsSkeleton from '../Tabs/Tabs.Skeleton'; const props = { tabs: () => ({ className: 'some-class', selected: number('The index of the selected tab (selected in <Tabs>)', 1), triggerHref: text( 'The href of trigger button for narrow mode (triggerHref in <Tabs>)', '#' ), role: text('ARIA role (role in <Tabs>)', 'navigation'), onClick: action('onClick'), onKeyDown: action('onKeyDown'), onSelectionChange: action('onSelectionChange'), }), tab: () => ({ className: 'another-class', href: text('The href for tab (href in <Tab>)', '#'), label: text('The label for tab (label in <Tab>)', 'Tab label'), role: text('ARIA role (role in <Tab>)', 'presentation'), tabIndex: number('Tab index (tabIndex in <Tab>)', 0), onClick: action('onClick'), onKeyDown: action('onKeyDown'), }), }; const el = ({ href, label }) => { return ( <a href={href}> <span> {label} <Tag type="wfp">renderAnchor</Tag> </span> </a> ); }; const listEl = ({ anchor, className, label, href }) => { return ( <li className={className}> <div className="wfp--tabs__nav-link" role="button" tabIndex={0} onKeyPress={() => { alert('Custom renderListElement keypress'); }} onClick={() => { alert('Custom renderListElement'); }}> {anchor.label} * </div> </li> ); }; /* const TabLink = (props) => ( <Route path={to} exact={exact} children={({ match }) => ( <div className={match ? "wfp--tabs__nav-item wfp--tabs__nav-item--selected" : "wfp--tabs__nav-item"}> <Link className="wfp--tabs__nav-link" to={to}>{children}</Link> </div> )} /> ); */ const FakeRoute = ({ children }) => { const Children = children; return <Children match />; }; const FakeLink = ({ children, className }) => ( <div className={className}>{children}</div> ); const listElReactRouter = ({ anchor, className, to, exact, match }) => ( <FakeRoute to={to} exact={exact} children={({ match }) => ( <li className={ match ? className + ' wfp--tabs__nav-item--selected' : className }> <FakeLink className={anchor.className} to={to}> {anchor.label} </FakeLink> </li> )} /> ); storiesOf('Components|Tabs', module) .addDecorator(withKnobs) .add('Default', () => ( <Tabs {...props.tabs()}> <Tab {...props.tab()} label={`${props.tab().label} 1`}> <div className="some-content">Content for first tab goes here.</div> </Tab> <Tab {...props.tab()} label={`${props.tab().label} 2`}> <div className="some-content">Content for second tab goes here.</div> </Tab> <Tab {...props.tab()} label={`${props.tab().label} 3`}> <div className="some-content">Content for third tab goes here.</div> </Tab> <Tab {...props.tab()} disabled label={`${props.tab().label} 4 disabled`}> <div className="some-content">Content for fourth tab goes here.</div> </Tab> </Tabs> )) .add('Custom Tab Content', () => ( <Tabs {...props.tabs()} customTabContent={true}> <Tab {...props.tab()} label="Tab label 1" href="http://www.de.wfp.org" /> <Tab {...props.tab()} label="Tab label 2" href="http://www.fr.wfp.org" /> <Tab {...props.tab()} label="Tab label 3" href="http://www.fr.wfp.org" to="/path" /> </Tabs> )) .add('Custom Tab Logic', () => ( <Tabs {...props.tabs()} customTabContent={true}> <Tab {...props.tab()} label="Custom" href="http://www.de.wfp.org" renderAnchor={el} /> <Tab {...props.tab()} label="Custom renderListElement" href="http://www.fr.wfp.org" renderListElement={listEl} /> <Tab {...props.tab()} label="React-Router Example" href="http://www.fr.wfp.org" to="/path" renderListElement={listElReactRouter} /> </Tabs> )) .add('skeleton', () => <TabsSkeleton />);
src/TextField/TextFieldLabel.js
igorbt/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import transitions from '../styles/transitions'; function getStyles(props) { const defaultStyles = { position: 'absolute', lineHeight: '22px', top: 38, transition: transitions.easeOut(), zIndex: 1, // Needed to display label above Chrome's autocomplete field background transform: 'scale(1) translate(0, 0)', transformOrigin: 'left top', pointerEvents: 'auto', userSelect: 'none', }; const shrinkStyles = props.shrink ? Object.assign({ transform: 'scale(0.75) translate(0, -28px)', pointerEvents: 'none', }, props.shrinkStyle) : null; return { root: Object.assign(defaultStyles, props.style, shrinkStyles), }; } const TextFieldLabel = (props) => { const { muiTheme, className, children, htmlFor, onClick, } = props; const {prepareStyles} = muiTheme; const styles = getStyles(props); return ( <label className={className} style={prepareStyles(styles.root)} htmlFor={htmlFor} onClick={onClick} > {children} </label> ); }; TextFieldLabel.propTypes = { /** * The label contents. */ children: PropTypes.node, /** * The css class name of the root element. */ className: PropTypes.string, /** * Disables the label if set to true. */ disabled: PropTypes.bool, /** * The id of the target element that this label should refer to. */ htmlFor: PropTypes.string, /** * @ignore * The material-ui theme applied to this component. */ muiTheme: PropTypes.object.isRequired, /** * Callback function for when the label is selected via a click. * * @param {object} event Click event targeting the text field label. */ onClick: PropTypes.func, /** * True if the floating label should shrink. */ shrink: PropTypes.bool, /** * Override the inline-styles of the root element when shrunk. */ shrinkStyle: PropTypes.object, /** * Override the inline-styles of the root element. */ style: PropTypes.object, }; TextFieldLabel.defaultProps = { disabled: false, shrink: false, }; export default TextFieldLabel;
src/svg-icons/device/signal-cellular-off.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellularOff = (props) => ( <SvgIcon {...props}> <path d="M21 1l-8.59 8.59L21 18.18V1zM4.77 4.5L3.5 5.77l6.36 6.36L1 21h17.73l2 2L22 21.73 4.77 4.5z"/> </SvgIcon> ); DeviceSignalCellularOff = pure(DeviceSignalCellularOff); DeviceSignalCellularOff.displayName = 'DeviceSignalCellularOff'; export default DeviceSignalCellularOff;
src/svg-icons/av/replay-5.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvReplay5 = (props) => ( <SvgIcon {...props}> <path d="M12 5V1L7 6l5 5V7c3.3 0 6 2.7 6 6s-2.7 6-6 6-6-2.7-6-6H4c0 4.4 3.6 8 8 8s8-3.6 8-8-3.6-8-8-8zm-1.3 8.9l.2-2.2h2.4v.7h-1.7l-.1.9s.1 0 .1-.1.1 0 .1-.1.1 0 .2 0h.2c.2 0 .4 0 .5.1s.3.2.4.3.2.3.3.5.1.4.1.6c0 .2 0 .4-.1.5s-.1.3-.3.5-.3.2-.4.3-.4.1-.6.1c-.2 0-.4 0-.5-.1s-.3-.1-.5-.2-.2-.2-.3-.4-.1-.3-.1-.5h.8c0 .2.1.3.2.4s.2.1.4.1c.1 0 .2 0 .3-.1l.2-.2s.1-.2.1-.3v-.6l-.1-.2-.2-.2s-.2-.1-.3-.1h-.2s-.1 0-.2.1-.1 0-.1.1-.1.1-.1.1h-.7z"/> </SvgIcon> ); AvReplay5 = pure(AvReplay5); AvReplay5.displayName = 'AvReplay5'; AvReplay5.muiName = 'SvgIcon'; export default AvReplay5;
website/src/components/charts/Tooltip/index.js
jwngr/notreda.me
import React from 'react'; import {TooltipWrapper} from './index.styles'; import {getWindowDimensions} from '../../../utils'; export default ({x, y, children}) => { const tooltipStyles = {}; const windowDimensions = getWindowDimensions(); if (y - window.scrollY < 100) { tooltipStyles.top = y; } else { tooltipStyles.bottom = windowDimensions.height - y; } if (windowDimensions.width - x < 150) { tooltipStyles.right = windowDimensions.width - x; } else { tooltipStyles.left = x; } return <TooltipWrapper style={tooltipStyles}>{children}</TooltipWrapper>; };
modules/TransitionHook.js
tikotzky/react-router
import React from 'react'; import warning from 'warning'; var { object } = React.PropTypes; var TransitionHook = { contextTypes: { router: object.isRequired }, componentDidMount() { warning( typeof this.routerWillLeave === 'function', 'Components that mixin TransitionHook should have a routerWillLeave method, check %s', this.constructor.displayName || this.constructor.name ); if (this.routerWillLeave) this.context.router.addTransitionHook(this.routerWillLeave); }, componentWillUnmount() { if (this.routerWillLeave) this.context.router.removeTransitionHook(this.routerWillLeave); } }; export default TransitionHook;
src/CarouselItem.js
laran/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import TransitionEvents from './utils/TransitionEvents'; const CarouselItem = React.createClass({ propTypes: { direction: React.PropTypes.oneOf(['prev', 'next']), onAnimateOutEnd: React.PropTypes.func, active: React.PropTypes.bool, animateIn: React.PropTypes.bool, animateOut: React.PropTypes.bool, caption: React.PropTypes.node, index: React.PropTypes.number }, getInitialState() { return { direction: null }; }, getDefaultProps() { return { active: false, animateIn: false, animateOut: false }; }, handleAnimateOutEnd() { if (this.props.onAnimateOutEnd && this.isMounted()) { this.props.onAnimateOutEnd(this.props.index); } }, componentWillReceiveProps(nextProps) { if (this.props.active !== nextProps.active) { this.setState({ direction: null }); } }, componentDidUpdate(prevProps) { if (!this.props.active && prevProps.active) { TransitionEvents.addEndEventListener( React.findDOMNode(this), this.handleAnimateOutEnd ); } if (this.props.active !== prevProps.active) { setTimeout(this.startAnimation, 20); } }, startAnimation() { if (!this.isMounted()) { return; } this.setState({ direction: this.props.direction === 'prev' ? 'right' : 'left' }); }, render() { let classes = { item: true, active: (this.props.active && !this.props.animateIn) || this.props.animateOut, next: this.props.active && this.props.animateIn && this.props.direction === 'next', prev: this.props.active && this.props.animateIn && this.props.direction === 'prev' }; if (this.state.direction && (this.props.animateIn || this.props.animateOut)) { classes[this.state.direction] = true; } return ( <div {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} {this.props.caption ? this.renderCaption() : null} </div> ); }, renderCaption() { return ( <div className="carousel-caption"> {this.props.caption} </div> ); } }); export default CarouselItem;
src/views/BootCard/BootCardDeck.js
shengnian/shengnian-ui-react
import React from 'react' import PropTypes from 'prop-types' import cx from 'classnames' import { mapToCssModules } from '../../lib/' const propTypes = { tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string]), className: PropTypes.string, cssModule: PropTypes.object, } const defaultProps = { tag: 'div', } const CardDeck = (props) => { const { className, cssModule, tag: Tag, ...attributes } = props const classes = mapToCssModules(cx( className, 'card-deck', ), cssModule) return ( <Tag {...attributes} className={classes} /> ) } CardDeck.propTypes = propTypes CardDeck.defaultProps = defaultProps export default CardDeck
public/pages/UpdateDynamicFormPage.js
dynamicform/dynamicform-react-client
import React from 'react'; import {connect} from 'react-redux'; import DynamicForm from '../../src/components/DynamicForm'; @connect() export default class UpdateDynamicFormPage extends React.Component{ onSubmit(er){ console.log('回调函数onSubmit'); } onSuccess(){ } //${this.props.match && this.props.match.params.name} //${this.props.match && this.props.match.params.id} render(){ return( <div> <DynamicForm formDefinitionSrc={`http://localhost:3000/api/getdefinition/${this.props.match && this.props.match.params.name}`} formDataSrc={`http://localhost:3000/api/loadformdataById/${this.props.match && this.props.match.params.id}`} _id={this.props.match && this.props.match.params.id} dataPath='data' onSuccess={this.onSuccess} /> </div> ); } }
web/app/layout/header.js
seanhess/serials
// @flow import React from 'react' import {RouteHandler, Link} from 'react-router' import {assign} from 'lodash' import {Users} from '../model/user' import {background, Colors, clickable} from '../style' import {LinkStyle, TitleStyle, NavBar, CenterText} from './style' import {AlertView} from '../alert' import {Alerts} from '../model/alert' import {Routes} from '../router' import {OffCanvas} from './offcanvas' //export class MainContainer extends React.Component { //render():React.Element { //return <div> //<OffCanvas> //hello //</OffCanvas> //</div> //} //} export class Header extends React.Component { logout() { Users.logout().then(function() { window.location.hash = "/login" }) } renderCurrentUser():React.Element { var currentUser = this.props.currentUser; if (currentUser) { return <div style={{display: 'inline-block'}}> <Link style={LinkStyle} to={Routes.bookshelf} params={{id: this.props.currentUser.id}}>My Books</Link> <a style={LinkStyle} onClick={this.logout.bind(this)}>Logout</a> </div> //<p style={LinkStyle}>Hello, {this.props.currentUser.firstName}</p> } else { return <div style={{display: 'inline-block'}}> <Link style={LinkStyle} to={Routes.login}>Login</Link> </div> } } render():React.Element { var isAdmin = false if (this.props.currentUser && this.props.currentUser.admin) { isAdmin = true } var adminStyle = assign({}, LinkStyle, { display: (isAdmin) ? 'inline-block' : 'none' }) var signup = "" if (!this.props.currentUser) { signup = <a style={LinkStyle} href="/hello">Sign Up</a> } var linkTo = {to: Routes.root} if (this.props.currentUser) { linkTo = {to: Routes.bookshelf, params: {id: this.props.currentUser.id}} } return <nav style={NavBar} role="navigation"> <div style={{float: 'right'}}> <Link to={Routes.about} style={LinkStyle}>About</Link> {signup} <Link style={adminStyle} to={Routes.admin}>Admin</Link> {this.renderCurrentUser()} </div> <div style={CenterText}> <Link {...linkTo} style={TitleStyle}> <img src="img/serials-icon-light.png" style={{height: 30, marginRight: 5}}/> <span style={{fontWeight: 'bold', color: Colors.light}}>Web Fiction</span> </Link> </div> </nav> } } export class SiteTitle extends React.Component { render() { var linkTo = {to: Routes.root} if (this.props.currentUser) { linkTo = {to: Routes.bookshelf, params: {id: this.props.currentUser.id}} } return <Link {...linkTo} style={TitleStyle}> <img src="img/serials-icon-light.png" style={{height: 26, marginRight: 5}}/> <span style={{fontWeight: 'bold', color: Colors.light}}>Web Fiction</span> </Link> } }
1m_Redux_Lynda/Ex_Files_Learning_Redux/Exercise Files/Ch05/05_05/finished/src/index.js
yevheniyc/C
import C from './constants' import React from 'react' import { render } from 'react-dom' import routes from './routes' import sampleData from './initialState' import storeFactory from './store' import { Provider } from 'react-redux' import { addError } from './actions' const initialState = (localStorage["redux-store"]) ? JSON.parse(localStorage["redux-store"]) : sampleData const saveState = () => localStorage["redux-store"] = JSON.stringify(store.getState()) const handleError = error => { store.dispatch( addError(error.message) ) } const store = storeFactory(initialState) store.subscribe(saveState) window.React = React window.store = store window.addEventListener("error", handleError) render( <Provider store={store}> {routes} </Provider>, document.getElementById('react-container') )
App.js
Jack3113/edtBordeaux
import React from 'react'; import { Image } from 'react-native'; import { AppLoading, SplashScreen } from 'expo'; import { Asset } from 'expo-asset'; import * as Font from 'expo-font'; import { Entypo, Feather, FontAwesome, Ionicons, MaterialCommunityIcons, MaterialIcons, SimpleLineIcons } from '@expo/vector-icons'; import RootContainer from './containers/rootContainer'; function cacheFonts(fonts) { return fonts.map((font) => Font.loadAsync(font)); } function cacheImages(images) { return images.map((image) => { if (typeof image === 'string') { return Image.prefetch(image); } else { return Asset.fromModule(image).downloadAsync(); } }); } export default class App extends React.Component { state = { isSplashReady: false, }; constructor(props) { super(props); this._loadAssetsAsync = this._loadAssetsAsync.bind(this); } render() { if (!this.state.isSplashReady) { return ( <AppLoading startAsync={this._loadAssetsAsync} onFinish={() => this.setState({ isSplashReady: true })} onError={console.warn} autoHideSplash={false} /> ); } return <RootContainer />; } async _loadAssetsAsync() { const imageAssets = cacheImages([require('./assets/icons/app.png')]); const fontAssets = cacheFonts([ FontAwesome.font, Feather.font, Ionicons.font, MaterialCommunityIcons.font, MaterialIcons.font, SimpleLineIcons.font, Entypo.font, ]); await Promise.all([...imageAssets, ...fontAssets]); SplashScreen.hide(); } }
src/router.js
Huanzhang89/rss-feed-example
import React from 'react'; import { Provider } from 'react-redux'; import history from './history'; import { Router, Route } from 'react-router-dom'; import store from './store' import App from './views/App'; const routes = ( <Route path='/' component={App} /> ) const Routes = () => ( <Provider store={store}> <Router history={history}> {routes} </Router> </Provider> ) export default Routes;
app/src/modules/shared/components/NavigationBar/NavigationBar.js
betofigueiredo/homelibraries.org
import React from 'react'; import PropTypes from 'prop-types'; // import { useSelector } from 'react-redux'; import { Link, withRouter } from 'react-router-dom'; // CSS import CSSModules from 'react-css-modules'; import styles from './style.module.scss'; // Language // import { translate } from '../../languages/translate'; // Components import NavButton from './NavButton'; function NavigationBar({ match }) { // const user = useSelector(store => store.user); // const { locale } = user; const libraries_matches = ['/libraries']; const mybooks_matches = ['/mybooks']; const messages_matches = [ '/messages', '/messages/view/:uuid', ]; const account_matches = [ '/account', '/account/name', '/account/url', '/account/address', '/account/map', '/account/lfl', '/account/email', '/account/password', '/account/language', ]; return ( <div styleName="navigation-wrapper"> <div styleName="menu-top"> <Link to="/libraries">.</Link> </div> <ul styleName="menu"> <NavButton label="Mapa" icon="fa fa-map-marker" link="/libraries" match={match} url_matches={libraries_matches} /> <NavButton label="Meus livros" icon="fa fa-book" link="/mybooks" match={match} url_matches={mybooks_matches} /> <NavButton label="Trocas" icon="fa fa-handshake-o" link="/trades" match={match} url_matches={[]} /> <NavButton label="Mensagens" icon="fa fa-comments" link="/messages" match={match} url_matches={messages_matches} /> <NavButton label="Conta" icon="fa fa-user" link="/account" match={match} url_matches={account_matches} /> </ul> </div> ); } NavigationBar.propTypes = { match: PropTypes.object.isRequired, }; export default withRouter(CSSModules(NavigationBar, styles, { allowMultiple: true }));
src/parser/demonhunter/havoc/modules/talents/Momentum.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS/index'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatPercentage, formatDuration } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; /* example report: https://www.warcraftlogs.com/reports/1HRhNZa2cCkgK9AV/#fight=48&source=10 * */ class Momentum extends Analyzer { constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.MOMENTUM_TALENT.id); } get buffUptime() { return this.selectedCombatant.getBuffUptime(SPELLS.MOMENTUM_BUFF.id) / this.owner.fightDuration; } get buffDuration() { return this.selectedCombatant.getBuffUptime(SPELLS.MOMENTUM_BUFF.id); } get suggestionThresholds() { return { actual: this.buffUptime, isLessThan: { minor: 0.55, average: 0.45, major: 0.40, }, style: 'percentage', }; } suggestions(when) { when(this.suggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<> Maintain the <SpellLink id={SPELLS.MOMENTUM_TALENT.id} /> buff to maximize damage.</>) .icon(SPELLS.MOMENTUM_TALENT.icon) .actual(`${formatPercentage(actual)}% buff uptime`) .recommended(`${formatPercentage(recommended)}% is recommended.`); }); } statistic() { return ( <StatisticBox position={STATISTIC_ORDER.CORE(3)} icon={<SpellIcon id={SPELLS.MOMENTUM_TALENT.id} />} value={`${formatPercentage(this.buffUptime)}%`} label="Momentum Uptime" tooltip={`The Momentum buff total uptime was ${formatDuration(this.buffDuration / 1000)}.`} /> ); } } export default Momentum;
src/interface/report/Results/EncounterStats.js
sMteX/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import SPECS from 'game/SPECS'; import ROLES from 'game/ROLES'; import ITEMS from 'common/ITEMS'; import fetchWcl from 'common/fetchWclApi'; import Icon from 'common/Icon'; import ItemLink from 'common/ItemLink'; import SpellLink from 'common/SpellLink'; import SpellIcon from 'common/SpellIcon'; import { formatDuration, formatPercentage, formatThousands } from 'common/format'; import ActivityIndicator from 'interface/common/ActivityIndicator'; import { makeItemApiUrl } from 'common/makeApiUrl'; /** * Show statistics (talents and trinkets) for the current boss, specID and difficulty */ const LEVEL_15_TALENT_ROW_INDEX = 0; class EncounterStats extends React.PureComponent { static propTypes = { currentBoss: PropTypes.number.isRequired, spec: PropTypes.number.isRequired, difficulty: PropTypes.number.isRequired, duration: PropTypes.number.isRequired, }; LIMIT = 100; //Currently does nothing but if Kihra reimplements it'd be nice to have SHOW_TOP_ENTRYS = 6; SHOW_TOP_ENTRYS_AZERITE = 10; SHOW_CLOSEST_KILL_TIME_LOGS = 10; metric = 'dps'; amountOfParses = 0; durationVariancePercentage = 0.2; //Marked in % to allow for similiar filtering on long/short fights constructor(props) { super(props); this.state = { mostUsedTrinkets: [], mostUsedTalents: [], similiarKillTimes: [], closestKillTimes: [], items: ITEMS, loaded: false, message: 'Loading statistics...', }; this.load = this.load.bind(this); this.load(); } addItem(array, item) { //add item to arry or increase amount by one if it exists if (item.id === null || item.id === 0) { return array; } const index = array.findIndex(elem => elem.id === item.id); if (index === -1) { array.push({ id: item.id, name: item.name.replace(/\\'/g, '\''), quality: item.quality, icon: item.icon, amount: 1, }); } else { array[index].amount += 1; } return array; } load() { switch (SPECS[this.props.spec].role) { case ROLES.HEALER: this.metric = 'hps'; break; default: this.metric = 'dps'; break; } const now = new Date(); const onejan = new Date(now.getFullYear(), 0, 1); const currentWeek = Math.ceil((((now - onejan) / 86400000) + onejan.getDay() + 1) / 7); // current calendar-week return fetchWcl(`rankings/encounter/${this.props.currentBoss}`, { class: SPECS[this.props.spec].ranking.class, spec: SPECS[this.props.spec].ranking.spec, difficulty: this.props.difficulty, limit: this.LIMIT, //Currently does nothing but if Kihra reimplements it'd be nice to have metric: this.metric, cache: currentWeek, // cache for a week }).then((stats) => { const talentCounter = [[], [], [], [], [], [], []]; const talents = []; let trinkets = []; let azerite = []; const similiarKillTimes = []; //These are the reports within the defined variance of the analyzed log const closestKillTimes = []; //These are the reports closest to the analyzed log regardless of it being within variance or not stats.rankings.forEach(rank => { rank.talents.forEach((talent, index) => { if (talent.id !== null && talent.id !== 0) { talentCounter[index].push(talent.id); } }); rank.gear.forEach((item, itemSlot) => { if (itemSlot === 12 || itemSlot === 13) { trinkets = this.addItem(trinkets, item); } }); rank.azeritePowers.forEach((azeritePower) => { azerite = this.addItem(azerite, azeritePower); }); if (this.props.duration > rank.duration * (1 - this.durationVariancePercentage) && this.props.duration < rank.duration * (1 + this.durationVariancePercentage)) { similiarKillTimes.push({ rank, variance: rank.duration - this.props.duration > 0 ? rank.duration - this.props.duration : this.props.duration - rank.duration }); } closestKillTimes.push({ rank, variance: rank.duration - this.props.duration > 0 ? rank.duration - this.props.duration : this.props.duration - rank.duration }); }); talentCounter.forEach(row => { const talentRow = row.reduce((prev, cur) => { prev[cur] = (prev[cur] || 0) + 1; return prev; }, {}); talents.push(talentRow); }); trinkets.sort((a, b) => { return (a.amount < b.amount) ? 1 : ((b.amount < a.amount) ? -1 : 0); }); azerite.sort((a, b) => { return (a.amount < b.amount) ? 1 : ((b.amount < a.amount) ? -1 : 0); }); similiarKillTimes.sort((a, b) => { return a.variance - b.variance; }); closestKillTimes.sort((a, b) => { return a.variance - b.variance; }); this.setState({ mostUsedTrinkets: trinkets.slice(0, this.SHOW_TOP_ENTRYS), mostUsedAzerite: azerite.slice(0, this.SHOW_TOP_ENTRYS_AZERITE), mostUsedTalents: talents, similiarKillTimes: similiarKillTimes.slice(0, this.SHOW_CLOSEST_KILL_TIME_LOGS), closestKillTimes: closestKillTimes.slice(0, this.SHOW_CLOSEST_KILL_TIME_LOGS), loaded: true, }); //fetch all missing icons from bnet-api and display them this.fillMissingIcons(); }).catch((err) => { this.setState({ message: 'Something went wrong.', }); }); } fillMissingIcons() { this.state.mostUsedTrinkets.forEach(trinket => { if (ITEMS[trinket.id] === undefined) { return fetch(makeItemApiUrl(trinket.id)) .then(response => response.json()) .then(data => { const updatedItems = this.state.items; updatedItems[trinket.id] = { icon: data.icon, id: trinket.id, name: trinket.name, }; this.setState({ items: updatedItems, }); this.forceUpdate(); }) .catch(err => { }); // ignore errors; } return null; }); } singleItem(item) { return ( <div key={item.id} className="col-md-12 flex-main" style={{ textAlign: 'left', margin: '5px auto' }}> <div className="row"> <div className="col-md-2" style={{ opacity: '.8', fontSize: '.9em', lineHeight: '2em', textAlign: 'right' }}> {formatPercentage(item.amount / this.amountOfParses, 0)}% </div> <div className="col-md-10"> <ItemLink id={item.id} className={item.quality} icon={false}> <Icon icon={this.state.items[item.id] === undefined ? this.state.items[0].icon : this.state.items[item.id].icon} className={item.quality} style={{ width: '2em', height: '2em', border: '1px solid', marginRight: 10 }} /> {item.name} </ItemLink> </div> </div> </div> ); } singleTrait(trait) { return ( <div key={trait.id} className="col-md-12 flex-main" style={{ textAlign: 'left', margin: '5px auto' }}> <div className="row"> <div className="col-md-2" style={{ opacity: '.8', fontSize: '.9em', lineHeight: '2em', textAlign: 'right' }}> {trait.amount}x </div> <div className="col-md-10"> <SpellLink id={trait.id} icon={false}> <Icon icon={trait.icon} style={{ width: '2em', height: '2em', border: '1px solid', marginRight: 10 }} /> {trait.name} </SpellLink> </div> </div> </div> ); } singleLog(log) { return ( <div key={log.reportID} className="col-md-12 flex-main" style={{ textAlign: 'left', margin: '5px auto' }}> <div className="row" style={{ opacity: '.8', fontSize: '.9em', lineHeight: '2em' }}> <div className="flex-column col-md-6"> <a href={`https://wowanalyzer.com/report/${log.reportID}/${log.fightID}/`} target="_blank" rel="noopener noreferrer" > <div> {log.name} ({log.itemLevel}) </div> </a> <div> {formatDuration(log.duration / 1000)} ({log.duration > this.props.duration ? ((log.duration - this.props.duration) / 1000).toFixed(1) + 's slower' : ((this.props.duration - log.duration) / 1000).toFixed(1) + 's faster'}) </div> </div> <div className="col-md-6"> {formatThousands(log.total)} {this.metric} </div> </div> </div> ); } similiarLogs() { return ( <div className="col-md-12 flex-main" style={{ textAlign: 'left', margin: '5px auto' }}> {this.state.similiarKillTimes.length > 1 ? 'These are' : 'This is'} {this.state.similiarKillTimes.length} of the top {this.amountOfParses} {this.state.similiarKillTimes.length > 1 ? 'logs' : 'log'} that {this.state.similiarKillTimes.length > 1 ? 'are' : 'is'} closest to your kill-time within {formatPercentage(this.durationVariancePercentage, 0)}% variance. {this.state.similiarKillTimes.map(log => this.singleLog(log.rank))} </div> ); } closestLogs() { return ( <div className="col-md-12 flex-main" style={{ textAlign: 'left', margin: '5px auto' }}> {this.state.closestKillTimes.length > 1 ? 'These are' : 'This is'} {this.state.closestKillTimes.length} of the top {this.amountOfParses} {this.state.closestKillTimes.length > 1 ? 'logs' : 'log'} that {this.state.closestKillTimes.length > 1 ? 'are' : 'is'} closest to your kill-time. Large differences won't be good for comparing. {this.state.closestKillTimes.map(log => this.singleLog(log.rank))} </div> ); } render() { const rows = [15, 30, 45, 60, 75, 90, 100]; if (!this.state.loaded) { return ( <div className="panel-heading" style={{ marginTop: 40, padding: 20, boxShadow: 'none', borderBottom: 0 }}> <ActivityIndicator text={this.state.message} /> </div> ); } // If there are below 100 parses for a given spec, use this amount to divide with to get accurate percentages. // This also enables us to work around certain logs being anonymised - as this will then ignore those, and cause us to divide by 99, making our percentages accurate again. this.amountOfParses = Object.values(this.state.mostUsedTalents[LEVEL_15_TALENT_ROW_INDEX]).reduce((total, parses) => total + parses, 0); return ( <> <h1>Statistics for this fight using the top {this.amountOfParses} logs, ranked by {this.metric.toLocaleUpperCase()}</h1> <div className="row"> <div className="col-md-12" style={{ padding: '0 30px' }}> <div className="row"> <div className="col-md-4"> <div className="row" style={{ marginBottom: '2em' }}> <div className="col-md-12"> <h2>Most used Trinkets</h2> </div> </div> <div className="row" style={{ marginBottom: '2em' }}> {this.state.mostUsedTrinkets.map(trinket => this.singleItem(trinket))} </div> <div className="row" style={{ marginBottom: '2em' }}> <div className="col-md-12"> <h2>Most used Azerite Traits</h2> </div> </div> <div className="row" style={{ marginBottom: '2em' }}> {this.state.mostUsedAzerite.map(azerite => this.singleTrait(azerite))} </div> </div> <div className="col-md-4"> <div className="row" style={{ marginBottom: '2em' }}> <div className="col-md-12"> <h2>Most used Talents</h2> </div> </div> {this.state.mostUsedTalents.map((row, index) => ( <div key={index} className="row" style={{ marginBottom: 15, paddingLeft: 20 }}> <div className="col-lg-1 col-xs-2" style={{ lineHeight: '3em', textAlign: 'right' }}>{rows[index]}</div> {Object.keys(row).sort((a, b) => row[b] - row[a]).map((talent, talentIndex) => ( <div key={talentIndex} className="col-lg-3 col-xs-4" style={{ textAlign: 'center' }}> <SpellLink id={Number(talent)} icon={false}> <SpellIcon style={{ width: '3em', height: '3em' }} id={Number(talent)} noLink /> </SpellLink> <span style={{ textAlign: 'center', display: 'block' }}>{formatPercentage(row[talent] / this.amountOfParses, 0)}%</span> </div> ))} </div> ))} </div> <div className="col-md-4"> <div className="row" style={{ marginBottom: '2em' }}> <div className="col-md-12"> <h2>{this.state.similiarKillTimes.length > 0 ? 'Similiar' : 'Closest'} kill times</h2> </div> </div> <div className="row" style={{ marginBottom: '2em' }}> {this.state.similiarKillTimes.length > 0 ? this.similiarLogs() : ''} {this.state.similiarKillTimes.length === 0 && this.state.closestKillTimes.length > 0 ? this.closestLogs() : ''} </div> </div> </div> </div> </div> </> ); } } export default EncounterStats;
views/blocks/Photo/Photo.js
dimastark/team5
import React from 'react'; import './Photo.css'; import b from 'b_'; const photo = b.lock('photo'); function Status(props) { if (props.userIsCreator || props.status === null) { return null; } return ( <div className={['control', photo('checker')].join(' ')}> <i className={`fa ${props.status ? 'fa-check' : 'fa-times'}`} area-hidden="true"></i> </div> ); } function Button(props) { if (props.userIsCreator || props.status) { return null; } return ( <button className={['control', photo('button')].join(' ')} disabled={!props.existGeolocation || props.sending} onClick={props.handleClick}> <i className={`fa fa-crosshairs ${props.sending ? 'fa-spin' : ''}`} aria-hidden="true"></i> </button> ); } function ShowDescriptionButton(props) { if (!(props.userIsCreator || props.status) || !props.description) { return null; } return ( <button className={['control', photo('button')].join(' ')} onClick={props.handleShowDescription}> <i className="fa fa-info" aria-hidden="true"></i> </button> ); } export default class Photo extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.handleShowDescription = this.handleShowDescription.bind(this); this.state = { showDescription: false }; } handleShowDescription() { this.setState(prevState => ({showDescription: !prevState.showDescription})); } handleClick() { this.props.canSend(canSend => { if (canSend) { this.props.onAction(); } }); } render() { const { existGeolocation, userIsCreator, description, sending, status, title, src } = this.props; return ( <div className={photo()}> <div className={photo('img', {hidden: this.state.showDescription})}> <Status status={status} userIsCreator={userIsCreator}/> <Button status={status} existGeolocation={existGeolocation} userIsCreator={userIsCreator} sending={sending} handleClick={this.handleClick} /> <ShowDescriptionButton status={status} handleShowDescription={this.handleShowDescription} userIsCreator={userIsCreator} description={description} /> <img src={src}></img> {(userIsCreator || status) && title && <p className={photo('title')}> {title} </p> } </div> {(userIsCreator || status) && description && <div className={photo('description', {show: this.state.showDescription})}> <p>{description}</p> <button className={['control', photo('button', {back: true})].join(' ')} onClick={this.handleShowDescription}> <i className="fa fa-times" aria-hidden="true"></i> </button> </div> } </div> ); } }
packages/react/src/components/molecules/SocialLinks/index.js
massgov/mayflower
/** * SocialLinks module. * @module @massds/mayflower-react/SocialLinks * @requires module:@massds/mayflower-assets/scss/02-molecules/social-links * @requires module:@massds/mayflower-assets/scss/01-atoms/svg-icons * @requires module:@massds/mayflower-assets/scss/01-atoms/svg-loc-icons */ import React from 'react'; import PropTypes from 'prop-types'; // eslint-disable-next-line import/no-unresolved import IconFacebook from 'MayflowerReactBase/Icon/IconFacebook'; // eslint-disable-next-line import/no-unresolved import IconTwitter from 'MayflowerReactBase/Icon/IconTwitter'; // eslint-disable-next-line import/no-unresolved import IconLinkedin from 'MayflowerReactBase/Icon/IconLinkedin'; // eslint-disable-next-line import/no-unresolved import IconYoutube from 'MayflowerReactBase/Icon/IconYoutube'; // eslint-disable-next-line import/no-unresolved import IconInstagram from 'MayflowerReactBase/Icon/IconInstagram'; const SocialLinks = (socialLinks) => ( <section className="ma__social-links"> {socialLinks.label && <span className="ma__social-links__label">{socialLinks.label}</span>} <ul className="ma__social-links__items"> { socialLinks.items.map((socialLink, i) => ( /* eslint-disable-next-line react/no-array-index-key */ <SocialLink {...socialLink} key={`socialLink_${i}`} index={i} /> )) } </ul> </section> ); const SocialLink = (socialLink) => { const icons = { facebook: IconFacebook, twitter: IconTwitter, linkedin: IconLinkedin, youtube: IconYoutube, instagram: IconInstagram }; const IconComponent = socialLink.linkType ? icons[socialLink.linkType] : null; return( <li className="ma__social-links__item"> <a href={socialLink.href} className="ma__social-links__link js-social-share" data-social-share={socialLink.linkType} aria-label={socialLink.altText} > <IconComponent /> </a> </li> ); }; SocialLink.propTypes = { /** The URL for the link */ href: PropTypes.string.isRequired, /** The type of social link and the icon name */ linkType: PropTypes.oneOf(['facebook', 'twitter', 'linkedin', 'youtube', 'instagram']).isRequired, /** Alt text for accessibility */ altText: PropTypes.string.isRequired }; SocialLinks.propTypes = { /** The optional label for the social links */ label: PropTypes.string, /** The social links to display */ items: PropTypes.arrayOf(PropTypes.shape(SocialLink.propTypes)).isRequired }; SocialLinks.defaultProps = { label: '' }; export default SocialLinks;
project/react-ant-multi-pages/src/pages/index/containers/AutoDestination/Item/index.js
FFF-team/generator-earth
import React from 'react' import moment from 'moment' import { DatePicker, Button, Form, Input, Col } from 'antd' import BaseContainer from 'ROOT_SOURCE/base/BaseContainer' import request from 'ROOT_SOURCE/utils/request' import { mapMoment } from 'ROOT_SOURCE/utils/fieldFormatter' import Rules from 'ROOT_SOURCE/utils/validateRules' const FormItem = Form.Item export default Form.create()(class extends BaseContainer { /** * 提交表单 */ submitForm = (e) => { e && e.preventDefault() const { form } = this.props form.validateFieldsAndScroll(async (err, values) => { if (err) { return; } // 提交表单最好新起一个事务,不受其他事务影响 await this.sleep() let _formData = { ...form.getFieldsValue() } // _formData里的一些值需要适配 _formData = mapMoment(_formData, 'YYYY-MM-DD HH:mm:ss') // action await request.post('/asset/updateAsset', _formData) //await this.props.updateForm(_formData) // 提交后返回list页 this.props.history.push(`${this.context.CONTAINER_ROUTE_PREFIX}/list`) }) } constructor(props) { super(props); this.state = {}; } async componentDidMount() { let { data } = await request.get('/asset/viewAsset', {id: this.props.match.params.id /*itemId*/}) this.setState(data) } render() { let { form, formData } = this.props let { getFieldDecorator } = form const { id, assetName, contract, contractDate, contacts, contactsPhone } = this.state return ( <div className="ui-background"> <Form layout="inline" onSubmit={this.submitForm}> {getFieldDecorator('id', { initialValue: id===undefined ? '' : +id})( <Input type="hidden" /> )} <FormItem label="资产方名称"> {getFieldDecorator('assetName', { rules: [{ required: true }], initialValue: assetName || '' })(<Input disabled />)} </FormItem> <FormItem label="签约主体"> {getFieldDecorator('contract', { rules: [{ required: true }], initialValue: contract || '' })(<Input disabled />)} </FormItem> <FormItem label="签约时间"> {getFieldDecorator('contractDate', { rules: [{ type: 'object', required: true }], initialValue: contractDate && moment(contractDate) })(<DatePicker showTime format='YYYY年MM月DD HH:mm:ss' style={{ width: '100%' }} />)} </FormItem> <FormItem label="联系人"> {getFieldDecorator('contacts', { initialValue: contacts || '' })(<Input />)} </FormItem> <FormItem label="联系电话" hasFeedback> {getFieldDecorator('contactsPhone', { rules: [{ pattern: Rules.phone, message: '无效' }], initialValue: contactsPhone || '' })(<Input maxLength="11" />)} </FormItem> <FormItem> <Button type="primary" htmlType="submit"> 提交 </Button> </FormItem> <FormItem> <Button type="primary" onClick={e=>window.history.back()}> 取消/返回 </Button> </FormItem> </Form> </div> ) } })
examples/BorderlessTable.js
15lyfromsaturn/react-materialize
import React from 'react'; import Table from '../src/Table'; export default <Table> <thead> <tr> <th data-field="id">Name</th> <th data-field="name">Item Name</th> <th data-field="price">Item Price</th> </tr> </thead> <tbody> <tr> <td>Alvin</td> <td>Eclair</td> <td>$0.87</td> </tr> <tr> <td>Alan</td> <td>Jellybean</td> <td>$3.76</td> </tr> <tr> <td>Jonathan</td> <td>Lollipop</td> <td>$7.00</td> </tr> </tbody> </Table>;
src/MasterPassword/SetupMasterPassword.js
Lynx-Productions/OPeM
/*** * Copyright 2017 - present Lynx Productions * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // @ts-check import React, { Component } from 'react'; import { connect } from 'react-redux'; import MasterPassword from './MasterPassword'; import { addMasterPassword } from '../actions'; export class SetupMasterPassword extends Component { constructor(props) { super(props); this.createMasterPassword = this.createMasterPassword.bind(this); } createMasterPassword(e, masterPassword) { e.preventDefault(); const { addMasterPassword } = this.props; addMasterPassword(masterPassword); } render() { return ( <MasterPassword title="Create a Master Password" btnTitle="Create" onSubmit={this.createMasterPassword} /> ); } } const mapStateToProps = state => { return {}; }; const mapDispatchToProps = dispatch => { return { addMasterPassword: masterPassword => { dispatch(addMasterPassword(masterPassword)); } }; }; export default connect(mapStateToProps, mapDispatchToProps)( SetupMasterPassword );
src/containers/SigninPage.js
ASIX-ALS/asix-final-project-frontend
import React from 'react'; import SigninPageLayout from '../components/SigninPageLayout'; class SigninPage extends React.Component { render() { return ( <SigninPageLayout /> ); } } export default SigninPage;
admin/client/components/FlashMessages.js
wmertens/keystone
import React from 'react'; import { Alert } from 'elemental'; var FlashMessage = React.createClass({ displayName: 'FlashMessage', propTypes: { message: React.PropTypes.oneOfType([ React.PropTypes.object, React.PropTypes.string, ]), type: React.PropTypes.string, }, renderMessage (message) { if (typeof message === 'string') return <span>{message}</span>; const title = message.title ? <h4>{message.title}</h4> : null; const detail = message.detail ? <p>{message.detail}</p> : null; const list = message.list ? ( <ul style={{ marginBottom: 0 }}> {message.list.map((item, i) => <li key={`i${i}`}>{item}</li>)} </ul> ) : null; return ( <span> {title} {detail} {list} </span> ); }, render () { return <Alert type={this.props.type}>{this.renderMessage(this.props.message)}</Alert>; }, }); var FlashMessages = React.createClass({ displayName: 'FlashMessages', propTypes: { messages: React.PropTypes.oneOfType([ React.PropTypes.bool, React.PropTypes.shape({ error: React.PropTypes.array, hilight: React.PropTypes.array, info: React.PropTypes.array, success: React.PropTypes.array, warning: React.PropTypes.array, }), ]), }, renderMessages (messages, type) { if (!messages || !messages.length) return null; return messages.map((message, i) => { return <FlashMessage message={message} type={type} key={`i${i}`} />; }); }, renderTypes (types) { return Object.keys(types).map(type => this.renderMessages(types[type], type)); }, render () { if (!this.props.messages) return null; return ( <div className="flash-messages"> {this.renderTypes(this.props.messages)} </div> ); }, }); module.exports = FlashMessages;
client/client.js
CityRay/React15-Todo-List
import React from 'react'; import { render } from 'react-dom'; import App from '../components/App'; import configureStore from '../redux/store'; import { Provider } from 'react-redux'; // configure and create our store // createStore(reducres, initialState) const initialState = { todos: [ { id: 0, completed: false, text: 'Initial todo for demo purposes' } ], user: { username: 'Ray Lin', memberId: '69' } }; let store = configureStore(initialState); // Provider 是使用在應用程式的根元件內,負責將唯一的 store 傳下去給其他子元件 const root = ( <Provider store={store}> <App /> </Provider> ); // Render render( root, document.getElementById('app') );
components/AR/ViroARImageMarker.js
viromedia/viro
/** * Copyright (c) 2017-present, Viro Media, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ViroARImageMarker */ 'use strict'; import { requireNativeComponent, View, StyleSheet, findNodeHandle, Platform } from 'react-native'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { checkMisnamedProps } from '../Utilities/ViroProps'; var createReactClass = require('create-react-class'); /** * Container for Viro Components anchored to a detected image. */ var ViroARImageMarker = createReactClass({ propTypes: { ...View.propTypes, target: PropTypes.string, pauseUpdates: PropTypes.bool, renderingOrder: PropTypes.number, visible: PropTypes.bool, opacity: PropTypes.number, ignoreEventHandling: PropTypes.bool, dragType: PropTypes.oneOf(["FixedDistance", "FixedDistanceOrigin", "FixedToWorld", "FixedToPlane"]), dragPlane: PropTypes.shape({ planePoint : PropTypes.arrayOf(PropTypes.number), planeNormal : PropTypes.arrayOf(PropTypes.number), maxDistance : PropTypes.number }), onHover: PropTypes.func, onClick: PropTypes.func, onClickState: PropTypes.func, onTouch: PropTypes.func, onScroll: PropTypes.func, onSwipe: PropTypes.func, onDrag: PropTypes.func, onPinch: PropTypes.func, onRotate: PropTypes.func, onFuse: PropTypes.oneOfType([ PropTypes.shape({ callback: PropTypes.func.isRequired, timeToFuse: PropTypes.number }), PropTypes.func ]), onCollision: PropTypes.func, viroTag: PropTypes.string, onAnchorFound: PropTypes.func, onAnchorUpdated: PropTypes.func, onAnchorRemoved: PropTypes.func, }, _onHover: function(event: Event) { this.props.onHover && this.props.onHover(event.nativeEvent.isHovering, event.nativeEvent.position, event.nativeEvent.source); }, _onClick: function(event: Event) { this.props.onClick && this.props.onClick(event.nativeEvent.position, event.nativeEvent.source); }, _onClickState: function(event: Event) { this.props.onClickState && this.props.onClickState(event.nativeEvent.clickState, event.nativeEvent.position, event.nativeEvent.source); let CLICKED = 3; // Value representation of Clicked ClickState within EventDelegateJni. if (event.nativeEvent.clickState == CLICKED){ this._onClick(event) } }, _onTouch: function(event: Event) { this.props.onTouch && this.props.onTouch(event.nativeEvent.touchState, event.nativeEvent.touchPos, event.nativeEvent.source); }, _onScroll: function(event: Event) { this.props.onScroll && this.props.onScroll(event.nativeEvent.scrollPos, event.nativeEvent.source); }, _onSwipe: function(event: Event) { this.props.onSwipe && this.props.onSwipe(event.nativeEvent.swipeState, event.nativeEvent.source); }, _onDrag: function(event: Event) { this.props.onDrag && this.props.onDrag(event.nativeEvent.dragToPos, event.nativeEvent.source); }, _onPinch: function(event: Event) { this.props.onPinch && this.props.onPinch(event.nativeEvent.pinchState, event.nativeEvent.scaleFactor, event.nativeEvent.source); }, _onRotate: function(event: Event) { this.props.onRotate && this.props.onRotate(event.nativeEvent.rotateState, event.nativeEvent.rotationFactor, event.nativeEvent.source); }, _onFuse: function(event: Event){ if (this.props.onFuse){ if (typeof this.props.onFuse === 'function'){ this.props.onFuse(event.nativeEvent.source); } else if (this.props.onFuse != undefined && this.props.onFuse.callback != undefined){ this.props.onFuse.callback(event.nativeEvent.source); } } }, _onCollision: function(event: Event){ if (this.props.onCollision){ this.props.onCollision(event.nativeEvent.viroTag, event.nativeEvent.collidedPoint, event.nativeEvent.collidedNormal); } }, _onAnchorFound: function(event: Event) { if (this.props.onAnchorFound) { this.props.onAnchorFound(event.nativeEvent.anchorFoundMap); } }, _onAnchorUpdated: function(event: Event) { if (this.props.onAnchorUpdated) { this.props.onAnchorUpdated(event.nativeEvent.anchorUpdatedMap); } }, _onAnchorRemoved: function(event: Event) { if (this.props.onAnchorRemoved) { this.props.onAnchorRemoved(); } }, setNativeProps: function(nativeProps) { this._component.setNativeProps(nativeProps); }, render: function() { // Uncomment this line to check for misnamed props //checkMisnamedProps("ViroARImageMarker", this.props); let timeToFuse = undefined; if (this.props.onFuse != undefined && typeof this.props.onFuse === 'object'){ timeToFuse = this.props.onFuse.timeToFuse; } return ( <VRTARImageMarker {...this.props} ref={ component => {this._component = component; }} canHover={this.props.onHover != undefined} canClick={this.props.onClick != undefined || this.props.onClickState != undefined} canTouch={this.props.onTouch != undefined} canScroll={this.props.onScroll != undefined} canSwipe={this.props.onSwipe != undefined} canDrag={this.props.onDrag != undefined} canPinch={this.props.onPinch != undefined} canRotate={this.props.onRotate != undefined} canFuse={this.props.onFuse != undefined} onHoverViro={this._onHover} onClickViro={this._onClickState} onTouchViro={this._onTouch} onScrollViro={this._onScroll} onSwipeViro={this._onSwipe} onDragViro={this._onDrag} onPinchViro={this._onPinch} onRotateViro={this._onRotate} onFuseViro={this._onFuse} timeToFuse={timeToFuse} canCollide={this.props.onCollision != undefined} onCollisionViro={this._onCollision} onAnchorFoundViro={this._onAnchorFound} onAnchorUpdatedViro={this._onAnchorUpdated} onAnchorRemovedViro={this._onAnchorRemoved} /> ); } }); var VRTARImageMarker = requireNativeComponent( 'VRTARImageMarker', ViroARImageMarker, { nativeOnly: { position : [], scale : [], rotation : [], scalePivot : [], rotationPivot : [], animation : {}, materials: [], physicsBody : {}, transformBehaviors: [], hasTransformDelegate:true, canHover: true, canClick: true, canTouch: true, canScroll: true, canSwipe: true, canDrag: true, canPinch: true, canRotate: true, canFuse: true, onHoverViro:true, onClickViro:true, onTouchViro:true, onScrollViro:true, onSwipeViro:true, onDragViro:true, onPinchViro:true, onRotateViro:true, onFuseViro:true, timeToFuse:true, canCollide:true, onCollisionViro:true, onAnchorFoundViro:true, onAnchorUpdatedViro:true, onAnchorRemovedViro:true, } } ); module.exports = ViroARImageMarker;
node_modules/react-router/es/IndexRoute.js
SpaceyRezum/react-trivia-game
import React from 'react'; import warning from './routerWarning'; import invariant from 'invariant'; import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils'; import { component, components, falsy } from './InternalPropTypes'; var func = React.PropTypes.func; /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ /* eslint-disable react/require-render-return */ var IndexRoute = React.createClass({ displayName: 'IndexRoute', statics: { createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = _createRouteFromReactElement(element); } else { process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRoute> does not make sense at the root of your route config') : void 0; } } }, propTypes: { path: falsy, component: component, components: components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRoute> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default IndexRoute;
src/pages/providers/lenon.js
gelo592/IntegrativeMed-Site
import React from 'react' import Layout from '../../components/layout' import SEO from '../../components/seo' import lenon from '../../images/lenon.jpg' import Typography from '@material-ui/core/Typography'; import Grid from '@material-ui/core/Grid'; import SubLayout from '../../components/sublayout'; import { withStyles } from '@material-ui/core/styles'; import { colors } from '../../constants/constants'; import withRoot from '../../components/withRoot'; const styles = theme => ({ para: { lineHeight: 2.2, fontSize: 17, paddingBottom: 20, color: colors.text, } }); const LenonPage = ({ classes }) => ( <Layout> <SEO title="Providers : Rachel Lenon" /> <SubLayout title={'Rachel Lenon, FNP-BC,'}> <Grid container justify='center'> <Grid item xs={8}> <img src={lenon} alt="Rachel Lenon" style={{ float: 'left', borderRadius: 12, width: 130, margin: 10 }} /> <Typography className={classes.para}> <b>Rachel Lenon, FNP-BC,</b> is a family nurse practitioner available to provide primary and integrative healthcare to patients of all ages. Rachel received her Master of Science in Nursing in the Family Nurse Practitioner program at the University of Missouri in 2011. She has completed advanced training in integrative and functional medicine including IFM’s (Institute of Functional Medicine) Applying Functional Medicine in Clinical Practice, Advanced Autoimmune Module, and Functional Medicine in Pediatrics Module. She continues on-going advanced training in integrative and functional medicine. </Typography> <Typography className={classes.para}> Rachel's passion for preventative medicine began while working as an RN in the Cardiac ICU. It was there she saw firsthand the value of prevention and healthy lifestyle to avoid chronic disease. Rachel worked as a nurse practitioner in a family medicine clinic, gaining valuable experience in treating a wide range of both acute and chronic illnesses. </Typography> <Typography className={classes.para}> Rachel joined the team at the Integrative Medicine Clinic (IMC) in June of 2014. Her goal is to provide a holistic approach to healthcare that focuses on prevention and looking for the root causes of a patient's health concerns, rather than just treating the symptoms. Lifestyle modifications such as stress management, regular exercise, nutrient dense diet, and quality sleep are foundational aspects of the Integrative Medicine approach. She provides to patients of all ages who prefer an integrative approach to medicine. </Typography> </Grid> </Grid> </SubLayout> </Layout> ) export default withRoot(withStyles(styles)(LenonPage))
demos/function-tree-demos/src/mobx/components/App/index.js
idream3/cerebral
import React from 'react' import run from '../../run' import './styles.css' import AddAssignment from '../AddAssignment' import Assignments from '../Assignments' import appMounted from '../../events/appMounted' class App extends React.Component { componentDidMount () { run('appMounted', appMounted) } render () { return ( <div className='App'> <AddAssignment store={this.props.store} /> <Assignments store={this.props.store} /> </div> ) } } export default App
thingmenn-frontend/src/components/party-details/index.js
baering/thingmenn
import React from 'react' import partyService from '../../services/party-service' import totalsService from '../../services/totals-service' import partySummaryService from '../../services/party-summary-service' import KPI from '../../widgets/key-performance-indicator' import Topics from '../../widgets/topics' import Topic from '../../widgets/topics/topic' import ColorLegend from '../../widgets/color-legend' import DetailsHeader from '../../widgets/details-header' import DetailsMenu from '../../widgets/details-menu' import Piechart from '../../widgets/piechart' import Speeches from '../../widgets/speeches' import BarChart from '../../widgets/bar-chart' import Items from '../../widgets/items' import WeekdayHourMatrix from '../../widgets/weekday-hour-matrix' import './styles.css' export default class PartyDetails extends React.Component { constructor(props) { super(props) this.state = { party: { lthings: [] }, lthing: null, lthings: [], lthingLookup: {}, voteSummary: { votePercentages: [], voteSummary: [] }, speechSummary: [], documentSummary: [], absentSummary: {}, votePositions: [], speechPositions: [], documentPositions: [], } } componentDidMount() { this.getData() } componentWillReceiveProps(nextProps) { this.getData(nextProps.routeParams.partyId, nextProps.routeParams.lthing) } getData(id, lthing) { const partyId = id || this.props.params.partyId const lthingId = lthing || this.props.params.lthing partyService.getPartyDetailsByLthing(partyId, 'allt').then((party) => { this.setState(() => ({ party })) }) partySummaryService .getPartyVoteSummaryByLthing(partyId, lthingId) .then((voteSummary) => { this.setState(() => ({ voteSummary, })) }) partySummaryService .getPartySpeechSummaryByLthing(partyId, lthingId) .then((speechSummary) => { this.setState(() => ({ speechSummary, })) }) partySummaryService .getPartyDocumentSummaryByLthing(partyId, lthingId) .then((documentSummary) => { this.setState(() => ({ documentSummary, })) }) partySummaryService .getPartyAbsentSummaryByLthing(partyId, lthingId) .then((absentSummary) => { this.setState(() => ({ absentSummary, })) }) partySummaryService .getPartyVotePositionsByLthing(partyId, lthingId) .then((votePositions) => { this.setState(() => ({ votePositions, })) }) partySummaryService .getPartySpeechPositionsByLthing(partyId, lthingId) .then((speechPositions) => { this.setState(() => ({ speechPositions, })) }) partySummaryService .getPartyDocumentPositionsByLthing(partyId, lthingId) .then((documentPositions) => { this.setState(() => ({ documentPositions, })) }) totalsService.getLthings().then((lthings) => { const lthingLookup = {} lthings.forEach((lthing) => (lthingLookup[lthing.id] = lthing)) this.setState(() => ({ lthings, lthingLookup, })) }) } generateLthingList(party, lthings, lthingLookup) { const initialList = [ { name: 'Samtölur', url: `/thingflokkar/${party.id}/thing/allt`, }, ] if (!party.lthings.length || !lthings.length) { return initialList } const lthingsFormatted = party.lthings.map((lthingInfo) => { return { year: lthingLookup[lthingInfo.lthing].start.split('.')[2], thing: lthingInfo.lthing, url: `/thingflokkar/${party.id}/thing/${lthingInfo.lthing}`, } }) return initialList.concat(lthingsFormatted) } getDividerSize(tabName, lthing) { if (lthing === 'allt') { if (tabName === 'speeches') { return 15 } else if (tabName === 'documents') { return 3 } } if (tabName === 'speeches') { return 3 } else if (tabName === 'documents') { return 0.4 } return 1 } render() { const { party, lthings, lthingLookup, voteSummary, speechSummary, documentSummary, votePositions, speechPositions, documentPositions, } = this.state const lthing = this.props.params.lthing return ( <div className="fill"> <DetailsMenu menuItems={this.generateLthingList(party, lthings, lthingLookup)} /> <DetailsHeader speechSummary={speechSummary} voteSummary={voteSummary} id={party.id} mpName={party.name} description={party.about} imagePath={party.imagePath} /> <div className="Details"> <KPI voteSummary={voteSummary} speechSummary={speechSummary} documentSummary={documentSummary} /> <div className="Details-item Details-item--large Details-item--no-padding"> <Topics> {(activeTab) => ( <span> <Topic active={activeTab === 0}> <div className="Topic-column"> <h1 className="Topic-heading"> Skipting atkvæða eftir flokkum </h1> <ColorLegend /> {votePositions.map((sectionSummary) => ( <BarChart sectionSummary={sectionSummary} key={sectionSummary.name} /> ))} </div> <div className="Topic-column"> <h1 className="Topic-heading">Skipting atkvæða</h1> <Piechart voteSummary={voteSummary} /> <ColorLegend includeAbsent /> </div> {!!this.state.absentSummary && !!this.state.absentSummary.statistics && ( <div className="Topic-column"> <h1 className="Topic-heading">Hvenær fjarverandi</h1> <WeekdayHourMatrix weekdayHourMatrixSummary={this.state.absentSummary} /> </div> )} </Topic> <Topic active={activeTab === 1}> <div className="Topic-column"> <h1 className="Topic-heading">Ræður eftir flokkum</h1> <Items divider={this.getDividerSize('speeches', lthing)} items={speechPositions} /> </div> <div className="Topic-column"> <h1 className="Topic-heading">Skipting ræðutíma</h1> <Speeches speechSummary={speechSummary} /> </div> </Topic> <Topic active={activeTab === 2}> <div className="Topic-column"> <h1 className="Topic-heading">Þingskjöl eftir flokkum</h1> <Items divider={this.getDividerSize('documents', lthing)} items={documentPositions} /> </div> </Topic> </span> )} </Topics> </div> </div> </div> ) } }
definitions/npm/@storybook/addon-actions_v3.x.x/test_addon-actions_v3.x.x.js
splodingsocks/FlowTyped
// @flow import React from 'react'; import { action, decorateAction } from '@storybook/addon-actions' const Button = (props) => <button {...props} />; const firstArgAction = decorateAction([ args => args.slice(0, 1) ]); // $FlowExpectedError const erroneous = action(123); // $FlowExpectedError const erroneousDecorate = decorateAction([ 'a string' ]); const App = () => ( <div> <Button onClick={action('button-click')}> Hello World! </Button> <Button onClick={firstArgAction('button-click')}> Hello World! </Button> </div> );
packages/react/components/searchbar.js
AdrianV/Framework7
import React from 'react'; import Utils from '../utils/utils'; import Mixins from '../utils/mixins'; import __reactComponentDispatchEvent from '../runtime-helpers/react-component-dispatch-event.js'; import __reactComponentSlots from '../runtime-helpers/react-component-slots.js'; import __reactComponentSetProps from '../runtime-helpers/react-component-set-props.js'; class F7Searchbar extends React.Component { constructor(props, context) { super(props, context); this.__reactRefs = {}; } search(query) { if (!this.f7Searchbar) return undefined; return this.f7Searchbar.search(query); } enable() { if (!this.f7Searchbar) return undefined; return this.f7Searchbar.enable(); } disable() { if (!this.f7Searchbar) return undefined; return this.f7Searchbar.disable(); } toggle() { if (!this.f7Searchbar) return undefined; return this.toggle.disable(); } clear() { if (!this.f7Searchbar) return undefined; return this.f7Searchbar.clear(); } onChange(event) { this.dispatchEvent('change', event); } onInput(event) { this.dispatchEvent('input', event); } onFocus(event) { this.dispatchEvent('focus', event); } onBlur(event) { this.dispatchEvent('blur', event); } onSubmit(event) { this.dispatchEvent('submit', event); } onClearButtonClick(event) { this.dispatchEvent('click:clear clickClear', event); } onDisableButtonClick(event) { this.dispatchEvent('click:disable clickDisable', event); } render() { const self = this; let clearEl; let disableEl; const props = self.props; const { placeholder, clearButton, disableButton, disableButtonText, form, noShadow, noHairline, expandable, className, style, id } = props; if (clearButton) { clearEl = React.createElement('span', { className: 'input-clear-button', onClick: self.onClearButtonClick.bind(self) }); } if (disableButton) { disableEl = React.createElement('span', { className: 'searchbar-disable-button', onClick: self.onDisableButtonClick.bind(self) }, disableButtonText); } const SearchbarTag = form ? 'form' : 'div'; const classes = Utils.classNames(className, 'searchbar', { 'no-shadow': noShadow, 'no-hairline': noHairline, 'searchbar-expandable': expandable }, Mixins.colorClasses(props)); return React.createElement(SearchbarTag, { ref: __reactNode => { this.__reactRefs['el'] = __reactNode; }, id: id, style: style, className: classes }, this.slots['before-inner'], React.createElement('div', { className: 'searchbar-inner' }, this.slots['inner-start'], React.createElement('div', { className: 'searchbar-input-wrap' }, this.slots['input-wrap-start'], React.createElement('input', { placeholder: placeholder, type: 'search', onInput: self.onInput.bind(self), onChange: self.onChange.bind(self), onFocus: self.onFocus.bind(self), onBlur: self.onBlur.bind(self) }), React.createElement('i', { className: 'searchbar-icon' }), clearEl, this.slots['input-wrap-end']), disableEl, this.slots['inner-end'], this.slots['default']), this.slots['after-inner']); } componentDidMount() { const self = this; const { init, searchContainer, searchIn, searchItem, hideOnEnableEl, hideOnSearchEl, foundEl, notFoundEl, backdrop, backdropEl, disableButton, ignore, customSearch, removeDiacritics, hideDividers, hideGroups, form } = self.props; if (!init) return; const el = self.refs.el; if (form && el) { self.onSubmitBound = self.onSubmit.bind(self); el.addEventListener('submit', self.onSubmitBound, false); } self.$f7ready(() => { const params = Utils.noUndefinedProps({ el: self.refs.el, searchContainer, searchIn, searchItem, hideOnEnableEl, hideOnSearchEl, foundEl, notFoundEl, backdrop, backdropEl, disableButton, ignore, customSearch, removeDiacritics, hideDividers, hideGroups, on: { search(searchbar, query, previousQuery) { self.dispatchEvent('searchbar:search searchbarSearch', searchbar, query, previousQuery); }, clear(searchbar, previousQuery) { self.dispatchEvent('searchbar:clear searchbarClear', searchbar, previousQuery); }, enable(searchbar) { self.dispatchEvent('searchbar:enable searchbarEnable', searchbar); }, disable(searchbar) { self.dispatchEvent('searchbar:disable searchbarDisable', searchbar); } } }); Object.keys(params).forEach(key => { if (params[key] === '') { delete params[key]; } }); self.f7Searchbar = self.$f7.searchbar.create(params); }); } componentWillUnmount() { const self = this; if (self.props.form && self.refs.el) { self.refs.el.removeEventListener('submit', self.onSubmitBound, false); } if (self.f7Searchbar && self.f7Searchbar.destroy) self.f7Searchbar.destroy(); } get slots() { return __reactComponentSlots(this.props); } dispatchEvent(events, ...args) { return __reactComponentDispatchEvent(this, events, ...args); } get refs() { return this.__reactRefs; } set refs(refs) {} } __reactComponentSetProps(F7Searchbar, Object.assign({ id: [String, Number], noShadow: Boolean, noHairline: Boolean, form: { type: Boolean, default: true }, placeholder: { type: String, default: 'Search' }, disableButton: { type: Boolean, default: true }, disableButtonText: { type: String, default: 'Cancel' }, clearButton: { type: Boolean, default: true }, expandable: Boolean, searchContainer: [String, Object], searchIn: { type: String, default: '.item-title' }, searchItem: { type: String, default: 'li' }, foundEl: { type: [String, Object], default: '.searchbar-found' }, notFoundEl: { type: [String, Object], default: '.searchbar-not-found' }, backdrop: { type: Boolean, default: true }, backdropEl: [String, Object], hideOnEnableEl: { type: [String, Object], default: '.searchbar-hide-on-enable' }, hideOnSearchEl: { type: [String, Object], default: '.searchbar-hide-on-search' }, ignore: { type: String, default: '.searchbar-ignore' }, customSearch: { type: Boolean, default: false }, removeDiacritics: { type: Boolean, default: false }, hideDividers: { type: Boolean, default: true }, hideGroups: { type: Boolean, default: true }, init: { type: Boolean, default: true } }, Mixins.colorProps)); F7Searchbar.displayName = 'f7-searchbar'; export default F7Searchbar;
src/pages/settings/settings-email.js
Lokiedu/libertysoil-site
/* This file is a part of libertysoil.org website Copyright (C) 2016 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import ApiClient from '../../api/client'; import { API_HOST } from '../../config'; import { ActionsTrigger } from '../../triggers'; import { createSelector, currentUserSelector } from '../../selectors'; class SettingsEmailPage extends React.Component { static displayName = 'SettingsEmailPage'; static propTypes = { dispatch: PropTypes.func.isRequired, }; handleMuteAllPosts = async () => { const client = new ApiClient(API_HOST); const triggers = new ActionsTrigger(client, this.props.dispatch); let comment_notifications; if (this.form.mute_all_posts.checked) { comment_notifications = 'off'; } else { comment_notifications = 'on'; } await triggers.updateUserInfo({ more: { comment_notifications } }); }; render() { const { current_user, is_logged_in, } = this.props; if (!is_logged_in) { return false; } return ( <div className="paper"> <Helmet title="Email Settings on " /> <div className="paper__page"> <h2 className="content__sub_title layout__row layout__row-small">Email settings</h2> <div className="layout__row"> <form className="paper__page" ref={c => this.form = c}> <label className="layout__row layout__row-small" htmlFor="mute_all_posts"> <input checked={current_user.getIn(['user', 'more', 'mute_all_posts'])} id="mute_all_posts" name="mute_all_posts" type="checkbox" onClick={this.handleMuteAllPosts} /> <span className="checkbox__label-right">Turn off all email notifications about new comments</span> </label> </form> </div> </div> </div> ); } } const selector = createSelector( currentUserSelector, state => state.get('messages'), state => state.get('following'), state => state.get('followers'), (current_user, messages, following, followers) => ({ messages, following, followers, ...current_user }) ); export default connect(selector)(SettingsEmailPage);
packages/react-error-overlay/src/containers/RuntimeError.js
0xaio/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React from 'react'; import Header from '../components/Header'; import StackTrace from './StackTrace'; import type { StackFrame } from '../utils/stack-frame'; import type { ErrorLocation } from '../utils/parseCompileError'; const wrapperStyle = { display: 'flex', flexDirection: 'column', }; export type ErrorRecord = {| error: Error, unhandledRejection: boolean, contextSize: number, stackFrames: StackFrame[], |}; type Props = {| errorRecord: ErrorRecord, editorHandler: (errorLoc: ErrorLocation) => void, |}; function RuntimeError({ errorRecord, editorHandler }: Props) { const { error, unhandledRejection, contextSize, stackFrames } = errorRecord; const errorName = unhandledRejection ? 'Unhandled Rejection (' + error.name + ')' : error.name; // Make header prettier const message = error.message; let headerText = message.match(/^\w*:/) || !errorName ? message : errorName + ': ' + message; headerText = headerText // TODO: maybe remove this prefix from fbjs? // It's just scaring people .replace(/^Invariant Violation:\s*/, '') // This is not helpful either: .replace(/^Warning:\s*/, '') // Break the actionable part to the next line. // AFAIK React 16+ should already do this. .replace(' Check the render method', '\n\nCheck the render method') .replace(' Check your code at', '\n\nCheck your code at'); return ( <div style={wrapperStyle}> <Header headerText={headerText} /> <StackTrace stackFrames={stackFrames} errorName={errorName} contextSize={contextSize} editorHandler={editorHandler} /> </div> ); } export default RuntimeError;
packages/cli-adapter/src/saihubot-cli-addon-dialog.js
gasolin/saihubot
'use strict'; import React from 'react'; import {Box, Text, useApp, useInput} from 'ink'; import SelectInput from 'ink-select-input'; const SelectBox = ({handleSelect, title, items}) => { const {exit} = useApp(); useInput((input, key) => { if (input === 'q' || key.escape) { exit(); } }); const options = []; items.forEach((item, idx) => { options.push({ label: item.title, value: idx, }); }); return ( <Box flexDirection="column"> <Text>{title}</Text> <SelectInput items={options} onSelect={handleSelect} /> </Box> ); }; // addon that provide confirm and selection dialog export const addonConfirm = { name: 'confirm', requirements: { adapters: ['cli'], }, action: (robot) => (title, items) => { const handleSelect = (item) => { // `item` = { label: 'First', value: 'first' } if (item && items[item.value] && items[item.value].action) { items[item.value].action(); } }; robot.chatHistory.push( <SelectBox title={title} items={items} handleSelect={handleSelect} /> ); robot.render(); }, }; const addons = [addonConfirm]; export {addons};
template/src/components/Message.js
phonegap/phonegap-template-react-hot-loader
import '../css/message.css'; import React from 'react'; import CSSTransitionGroup from 'react-addons-css-transition-group'; export default React.createClass({ displayName: 'Message', propTypes: { message: React.PropTypes.string, }, render() { const { message } = this.props; const msg = message ? <div className="hello-message" key="has-msg">{ message }</div> : <div key="no-msg"></div> return ( <CSSTransitionGroup transitionName="fade-message" transitionEnterTimeout={ 300 } transitionLeaveTimeout={ 300 }> { msg } </CSSTransitionGroup> ); } });
src/index.js
richgurney/ReactTemperatureApp
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import ReduxPromise from 'redux-promise'; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <App /> </Provider> , document.querySelector('.container'));
.history/src/components/InstaCelebs/index_20171001010701.js
oded-soffrin/gkm_viewer
import React from 'react'; import { connect } from 'react-redux' import _ from 'lodash' import '../../styles/insta-stats.scss' const imgMap = { d: 'https://instagram.ftlv1-2.fna.fbcdn.net/t51.2885-19/s150x150/18095129_753964814784600_2717222797960019968_a.jpg', e: 'https://instagram.ftlv1-2.fna.fbcdn.net/t51.2885-19/s150x150/12071219_1640349196212432_2045004332_a.jpg', k: 'https://instagram.ftlv1-2.fna.fbcdn.net/t51.2885-19/s150x150/18512724_1809268792724740_5337121181726146560_a.jpg' } const InstaCelebs = ({instaCeleb}) => { console.log('instaCeleb', instaCeleb) const stats = _.map(instaCeleb.stats, (x, y) => ( <div> <img src={imgMap[y]}/> <div className='data-box'><i className='fa fa-heart'/></div> <div className='data-box'>{x.like || 0}</div> <div className='data-box'><i className='fa fa-comment'/></div> <div className='data-box'>{x.comment || 0}</div> </div> )) return ( <div className="wrapper"> <div className="stats"> <h1><img src='https://static.wixstatic.com/media/8b1232_99ff6bf44fc74a22a9cc5ef7b578c1b1~mv2.png' /> Stats - Last 24h</h1> {stats} </div> </div> ) } const mapStateToProps = (state) => ({ instaCeleb: state.instaCeleb }) const InstaCelebsConnected = connect( mapStateToProps, { } )(InstaCelebs) export default InstaCelebsConnected
src/client/components/loading.react.js
steida/songary
// import './loading.styl'; import Component from '../components/component.react'; import React from 'react'; export default class Loading extends Component { static propTypes = { delay: React.PropTypes.number, msg: React.PropTypes.object.isRequired } // http://www.nngroup.com/articles/response-times-3-important-limits/ static defaultProps = { delay: 3000 } constructor(props) { super(props); this.state = {shown: false}; } componentDidMount() { this.timer = setTimeout(() => { this.setState({shown: true}); }, this.props.delay); } componentWillUnmount() { clearTimeout(this.timer); } render() { const {msg: {components: msg}} = this.props; // TODO: Some animated progress, rule .1s 1s 10s. return ( <div className="components-loading"> <p> {this.state.shown && msg.loading} </p> </div> ); } }
console/src/app/tasklogs/tasklogs.js
alfredking12/hp-scheduler
import React from 'react'; require('rc-pagination/assets/index.css'); require('rc-select/assets/index.css'); import Pagination from 'rc-pagination'; import Select from 'rc-select'; import ActionRefresh from 'material-ui/svg-icons/action/search'; import TextField from 'material-ui/TextField'; import IconButton from 'material-ui/IconButton'; import {Table, TableBody, TableFooter, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table'; import 'react-date-picker/index.css'; import { DateField } from 'react-date-picker'; import moment from 'moment'; import request from 'superagent/lib/client'; import config from '../config/config'; import BaseComponent from '../libs/BaseComponent'; const styles = { middle: { marginTop: 8 }, middleIcon: { width: 28, height: 28, }, } export default class TaskLogs extends BaseComponent { constructor(props, context) { super(props, context); Object.assign(this.state, { fixedHeader: true, fixedFooter: true, stripedRows: false, showRowHover: false, height: (window.innerHeight - 344) + 'px', tableStyle: null, start: null, end: null, key: '', pageSize: 30, page: 0, count: 0, data: [], expand_index: -1, expand_text: '' }); } handleResize(e) { super.handleResize(e); this.setState({height: (window.innerHeight - 344) + 'px'}); } componentDidMount() { super.componentDidMount(); this.load(); } handleChangeStart(dateString) { this.setState({ start: dateString }); } handleChangeEnd(dateString) { this.setState({ end: dateString }); } handleSearch() { this.load(); } handleChangeKey(e) { this.setState({ key: e.target.value }); } handleRowClick(data) { if (this.state.expand_index == data.index) { this.setState({ expand_text: null, expand_index: -1 }) } else { this.setState({ expand_text: this.status(data.item), expand_index: data.index }) } } status(item) { if (item.progress !== undefined && item.progress !== null) { if(item.progress < 0) { return '[失败] ' + item.message; } else { return '[进度 ' + item.progress + '%] ' + item.message; } } return item.message; } _render() { var _this = this; var page = this.state.page; var per_page = this.state.pageSize; const getTable = () => { var rows = []; for (var index = 0;index< _this.state.data.length;index++) { var row = _this.state.data[index]; var item = ( <TableRow key={index} style={{height: '28px'}} onTouchTap={_this.handleRowClick.bind(_this, {item: row, index: index})} > <TableRowColumn style={{height: '28px', width: '30px'}}>{index + 1 + page * per_page}</TableRowColumn> <TableRowColumn style={{height: '28px',width: '200px'}}>{row.name}</TableRowColumn> <TableRowColumn style={{height: '28px', width: '30px'}}>{row.taskrecord_id}</TableRowColumn> <TableRowColumn style={{height: '28px'}}>{_this.status(row)}</TableRowColumn> <TableRowColumn style={{height: '28px', width: '150px'}}>{row.time}</TableRowColumn> </TableRow> ); rows.push(item); if (index == _this.state.expand_index) { item = ( <TableRow key={'expand_' + index} style={{background: 'rgba(120, 120, 120, 0.1)'}} > <TableRowColumn colSpan="5" style={{ wordWrap: 'break-all', wordBreak: 'normal', whiteSpace: 'break-all' }}> {_this.state.expand_text} </TableRowColumn> </TableRow> ); rows.push(item); } } return ( <div> <Table height={this.state.height} fixedHeader={this.state.fixedHeader} fixedFooter={this.state.fixedFooter} selectable={false} style={this.state.tableStyle} > <TableHeader displaySelectAll={false} adjustForCheckbox={false} > <TableRow displayBorder={true}> <TableHeaderColumn tooltip="序号" style={{width: '30px'}}>#</TableHeaderColumn> <TableHeaderColumn style={{width: '200px'}}>任务名称</TableHeaderColumn> <TableHeaderColumn style={{width: '30px'}}>任务ID</TableHeaderColumn> <TableHeaderColumn>日志信息</TableHeaderColumn> <TableHeaderColumn style={{width: '150px'}}>时间</TableHeaderColumn> </TableRow> </TableHeader> <TableBody displayRowCheckbox={false} showRowHover={this.state.showRowHover} stripedRows={this.state.stripedRows} > {rows} </TableBody> </Table> </div> ); } const pager = (style) => { return ( <div style={{overflow: 'hidden'}}> <div style={style}> <Pagination showSizeChanger className="ant-pagination" current={this.state.page + 1} defaultCurrent={1} total={this.state.count} pageSize={this.state.pageSize} onChange={this.handlePageChange.bind(this)} pageSizeOptions={['30', '50', '100', '200']} selectComponentClass={Select} onShowSizeChange={this.handleSizeChange.bind(this)} /> </div> </div> ); } return ( <div> <div style={{paddingLeft: '20px', paddingRight: '20px'}}> <DateField style={{marginRight: '20px'}} value={this.state.start} placeholder={'开始时间'} dateFormat="YYYY-MM-DD HH:mm:ss" onChange={this.handleChangeStart.bind(this)} /> <DateField style={{marginRight: '20px'}} value={this.state.end} placeholder={'结束时间'} dateFormat="YYYY-MM-DD HH:mm:ss" onChange={this.handleChangeEnd.bind(this)} /> <TextField style={{marginRight: '20px', paddingTop: 0, marginTop: 0}} value={this.state.key} onChange={this.handleChangeKey.bind(this)} floatingLabelText="输入关键字搜索" /> <IconButton iconStyle={styles.middleIcon} style={styles.middle} onTouchTap={this.handleSearch.bind(this)} > <ActionRefresh /> </IconButton> </div> {pager({paddingRight: '10px', float:'right'})} {getTable()} {pager({paddingBottom: '10px', paddingRight: '10px', float:'right'})} </div> ); } handlePageChange(page) { this.setState({ page: page - 1 }); var _this = this; setTimeout(function() { _this.load(); }, 0); } handleSizeChange(current, pageSize) { this.setState({ pageSize: pageSize, page: 0 }); var _this = this; setTimeout(function() { _this.load(); }, 0); } _load(cb) { var page = this.state.page; var per_page = this.state.pageSize; var stime = this.state.start ? moment(this.state.start).valueOf() : ''; var etime = this.state.end ? moment(this.state.end).valueOf() : ''; var key = this.state.key; request .get(config.api_server + '/tasklogs?page=' + page + '&per_page=' + per_page + '&stime=' + stime + '&etime=' + etime + '&key=' + key) .set('Accept', 'application/json') .end(function (err, res) { if (err) { cb(err); } else { cb(null, res.body); } }); } load() { this.setState({ expand_index: -1, expand_text: null }); var _this = this; _this.showLoading(); this._load(function (err, data) { _this.hideLoading(); if (err) { _this.showAlert('提示', '加载任务日志列表失败', '重新加载', function() { setTimeout(function(){ _this.load(); }, 0); }); } else { _this.setState({ data: data.data.data, count: data.data.count }); } }); } }
docs/src/app/components/pages/components/RefreshIndicator/ExampleLoading.js
pomerantsev/material-ui
import React from 'react'; import RefreshIndicator from 'material-ui/RefreshIndicator'; const style = { container: { position: 'relative', }, refresh: { display: 'inline-block', position: 'relative', }, }; const RefreshIndicatorExampleLoading = () => ( <div style={style.container}> <RefreshIndicator size={40} left={10} top={0} status="loading" style={style.refresh} /> <RefreshIndicator size={50} left={70} top={0} loadingColor={"#FF9800"} status="loading" style={style.refresh} /> </div> ); export default RefreshIndicatorExampleLoading;
js/components/leads_old/index.js
aditya-simplecrm/iosReactAppNoresha
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Alert,TouchableHighlight } from 'react-native'; import { Image, AsyncStorage } from 'react-native'; import { Actions } from 'react-native-router-flux'; import { Container, Header, Title, Content, Text, Button, Icon, Left, Right, Body, List, ListItem,Thumbnail, Fab,View} from 'native-base'; import { openDrawer } from '../../actions/drawer'; import styles from './styles'; import ActionButton from 'react-native-action-button'; const call = require('../../../images/call.png'); const meeting = require('../../../images/meeting.png'); const task = require('../../../images/task.png'); class Leads extends Component { static propTypes = { name: React.PropTypes.string, index: React.PropTypes.number, list: React.PropTypes.arrayOf(React.PropTypes.string), openDrawer: React.PropTypes.func, } constructor(props) { super(props); this.state = { active: false }; } render() { const { props: { name, index, list } } = this; const goToView2 = () => { Actions.view2(); console.log('Navigation router run...'); }; return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={() => Actions.pop()}> <Icon name="ios-arrow-back" /> </Button> </Left> <Body> <Title>{(name) ? this.props.name : 'Leads'}</Title> </Body> <Right> <Button transparent onPress={this.props.openDrawer}> <Icon name="ios-menu" /> </Button> </Right> </Header> <Content> <List> <ListItem button onPress={() => Actions.view2()}> <Body> <Text>Kumar Pratik</Text> <Text>[email protected]</Text> <Text note>Doing what you like will always keep you happy . .</Text> </Body> <Right> <Text note>3:43 pm</Text> </Right> </ListItem> </List> </Content> </Container> ); } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), }; } const mapStateToProps = state => ({ name: state.user.name, index: state.list.selectedIndex, list: state.list.list, }); export default connect(mapStateToProps, bindAction)(Leads);
electron/app/pages/component/any.js
midsnow/snowelectric
import React from 'react'; import Debug from 'debug' import Gab from '../../common/gab' let debug = Debug('snowstreams:app:pages:component:any'); export default class Any extends React.Component { constructor(props) { super(props) this.displayName = 'Any Component' this.state = { html: props.children || props.html || <span /> } this._update = false debug('Any'); } componentWillReceiveProps(props) { debug('receiveProps'); this.setState({html: props.children || props.html}); this._update = true; } componentDidUpdate() { debug('didUpdate'); } componentDidMount() { debug('did mount'); } render() { debug('any', this.state); if('function' === typeof this.state.html) { // render a component return (<div> <this.state.html /> </div>); } else if('object' === typeof this.state.html) { // this is a rendered componenet return (<div> {this.state.html} </div>); } else { debug('any leftover', this.state); // add anything else return (<div dangerouslySetInnerHTML={{ __html: this.state.html }} />) } } }
src/templates/portfolio-page.js
tannerfiscus/tannerfisc.us
import React from 'react'; import Markdown from 'react-markdown'; import { Helmet } from 'react-helmet'; import { graphql } from 'gatsby'; import Layout from '../components/Layout'; import PreviewCompatibleImage from '../components/PreviewCompatibleImage' import styles from './portfolio-page.module.scss'; import Text from '../components/Text'; export const PortfolioItemTemplate = ({ content, date, featuredHeaderImage, slug, technologies = [], timeline = [], title, }) => { const hasTechnologies = Array.isArray(technologies) && technologies.length > 1; const hasTimeline = Array.isArray(timeline) && timeline.length > 1; const hasSidebarContent = hasTechnologies || hasTimeline; return ( <> <Helmet meta={ [ { name: 'description', content: `Find out what went into building ${title} with a detailed page summary.` }, { property: 'og:title', content: `${title} – a project by Tanner Fiscus` }, { property: 'og:description', content: 'A detailed look at one of the projects I\'ve developed.' }, { property: 'og:type', content: 'website' }, { property: 'og:url', content: `https://tannerfisc.us/${slug}` }, { property: 'og:image', content: 'https://tannerfisc.us/img/og/portfolio.jpg' } ] } title={`${title} – Project Details – Tanner Fiscus`} /> <div className={styles.portfolioCover}> <PreviewCompatibleImage imageInfo={{ image: featuredHeaderImage, alt: `Image showing the ${title} portfolio item on a web browser`, }} /> </div> <main className={styles.portfolioContent}> <div className={styles.portfolioContentLeft}> { content ? content.map(({ description, title }) => ( <section className={styles.portfolioDescription} key={title}> <h2>{ title } </h2> <Markdown source={description} /> </section> )): null } <Text bold className={`${styles.portfolioDate} ${styles.portfolioDateTop}`}> Last updated: {date} </Text> </div> { hasSidebarContent ? <div className={styles.portfolioContentRight}> { hasTechnologies && ( <React.Fragment> <h3>Applicable Technologies</h3> <div className={styles.portfolioPills}> { technologies.map(category => ( <div className={styles.portfolioPill} key={category}> { category } </div> )) } </div> </React.Fragment> ) } { hasTimeline && ( <React.Fragment> <h3>Timeline of Events</h3> <div className={styles.portfolioTimeline}> { timeline.map(timeline => ( <div className={styles.portfolioPill} key={timeline.time}> <div className={styles.portfolioTimelineTime}> { timeline.time } </div> { timeline.description } </div> )) } </div> </React.Fragment> ) } </div> : null } <Text bold className={`${styles.portfolioDate} ${styles.portfolioDateBottom}`}> Last updated: {date} </Text> </main> </> ) }; const BlogPost = ({ data }) => { const { markdownRemark: post } = data return ( <Layout pageTitle={post.frontmatter.title}> <PortfolioItemTemplate {...post.frontmatter} slug={post.fields.slug} /> </Layout> ) }; export default BlogPost; export const pageQuery = graphql` query PortfolioPostByID($id: String!) { markdownRemark(id: { eq: $id }) { id fields { slug } frontmatter { content { description title } date(formatString: "MMMM YYYY") featuredHeaderImage { childImageSharp { fluid(maxWidth: 2000, quality: 100) { ...GatsbyImageSharpFluid } } } technologies title timeline { time description } } } } `
js/src/views/Settings/Views/defaults.js
kushti/mpt
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import React from 'react'; import ActionAccountBalanceWallet from 'material-ui/svg-icons/action/account-balance-wallet'; import ActionTrackChanges from 'material-ui/svg-icons/action/track-changes'; import ActionSettings from 'material-ui/svg-icons/action/settings'; import CommunicationContacts from 'material-ui/svg-icons/communication/contacts'; import ImageGridOn from 'material-ui/svg-icons/image/grid-on'; import NavigationApps from 'material-ui/svg-icons/navigation/apps'; import { SignerIcon } from '../../../ui'; import styles from './views.css'; const defaultViews = { accounts: { active: true, fixed: true, icon: <ActionAccountBalanceWallet />, label: 'Accounts', route: '/accounts', value: 'account', description: 'A list of all the accounts associated to and imported into this Parity instance. Send transactions, receive incoming values, manage your balances and fund your accounts.' }, addresses: { active: true, icon: <CommunicationContacts />, label: 'Addressbook', route: '/addresses', value: 'address', description: 'A list of all contacts and address book entries that is managed by this Parity instance. Watch accounts and have the details available at the click of a button when transacting.' }, apps: { active: true, icon: <NavigationApps />, label: 'Applications', route: '/apps', value: 'app', description: 'Distributed applications that interact with the underlying network. Add applications, manage you application portfolio and interact with application from around the newtork.' }, contracts: { active: false, icon: <ImageGridOn />, label: 'Contracts', route: '/contracts', value: 'contract', description: 'Watch and interact with specific contracts that have been deployed on the network. This is a more technically-focussed environment, specifically for advanced users that understand the inner working of certain contracts.' }, status: { active: false, icon: <ActionTrackChanges />, label: 'Status', route: '/status', value: 'status', description: 'See how the Parity node is performing in terms of connections to the network, logs from the actual running instance and details of mining (if enabled and configured).' }, signer: { active: true, fixed: true, icon: <SignerIcon className={ styles.signerIcon } />, label: 'Signer', route: '/signer', value: 'signer', description: 'The security focussed area of the application where you can approve any outgoing transactions made from the application as well as those placed into the queue by distributed applications.' }, settings: { active: true, fixed: true, icon: <ActionSettings />, label: 'Settings', route: '/settings', value: 'settings', description: 'This view. Allows you to customize the application in term of options, operation and look and feel.' } }; export default defaultViews;
packages/material-ui-icons/src/BatteryCharging80TwoTone.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V9h4.93L13 7v2h4V5.33C17 4.6 16.4 4 15.67 4z" /><path d="M13 12.5h2L11 20v-5.5H9L11.93 9H7v11.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V9h-4v3.5z" /></React.Fragment> , 'BatteryCharging80TwoTone');
docs/src/app/components/pages/components/IconButton/Page.js
pancho111203/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import iconButtonCode from '!raw!material-ui/IconButton/IconButton'; import iconButtonReadmeText from './README'; import iconButtonExampleSimpleCode from '!raw!./ExampleSimple'; import IconButtonExampleSimple from './ExampleSimple'; import iconButtonExampleComplexCode from '!raw!./ExampleComplex'; import IconButtonExampleComplex from './ExampleComplex'; import iconButtonExampleSizeCode from '!raw!./ExampleSize'; import IconButtonExampleSize from './ExampleSize'; import iconButtonExampleTooltipCode from '!raw!./ExampleTooltip'; import IconButtonExampleTooltip from './ExampleTooltip'; import iconButtonExampleTouchCode from '!raw!./ExampleTouch'; import IconButtonExampleTouch from './ExampleTouch'; const descriptions = { simple: 'An Icon Button using an icon specified with the `iconClassName` property, and a `disabled` example.', tooltip: 'Icon Buttons showing the available `tooltip` positions.', touch: 'The `touch` property adjusts the tooltip size for better visibility on mobile devices.', size: 'Examples of Icon Button in different sizes.', other: 'An Icon Button using a nested [Font Icon](/#/components/font-icon), ' + 'a nested [SVG Icon](/#/components/svg-icon) and an icon font ligature.', }; const IconButtonPage = () => ( <div> <Title render={(previousTitle) => `Icon Button - ${previousTitle}`} /> <MarkdownElement text={iconButtonReadmeText} /> <CodeExample title="Simple example" description={descriptions.simple} code={iconButtonExampleSimpleCode} > <IconButtonExampleSimple /> </CodeExample> <CodeExample title="Further examples" description={descriptions.other} code={iconButtonExampleComplexCode} > <IconButtonExampleComplex /> </CodeExample> <CodeExample title="Size examples" description={descriptions.size} code={iconButtonExampleSizeCode} > <IconButtonExampleSize /> </CodeExample> <CodeExample title="Tooltip examples" description={descriptions.tooltip} code={iconButtonExampleTooltipCode} > <IconButtonExampleTooltip /> </CodeExample> <CodeExample title="Touch example" description={descriptions.touch} code={iconButtonExampleTouchCode} > <IconButtonExampleTouch /> </CodeExample> <PropTypeDescription code={iconButtonCode} /> </div> ); export default IconButtonPage;
admin/client/App/screens/List/components/ItemsTable/ItemsTableDragDropZone.js
naustudio/keystone
/** * THIS IS ORPHANED AND ISN'T RENDERED AT THE MOMENT * THIS WAS DONE TO FINISH THE REDUX INTEGRATION, WILL REWRITE SOON * - @mxstbr */ import React from 'react'; import DropZoneTarget from './ItemsTableDragDropZoneTarget'; import classnames from 'classnames'; var ItemsTableDragDropZone = React.createClass({ displayName: 'ItemsTableDragDropZone', propTypes: { columns: React.PropTypes.array, connectDropTarget: React.PropTypes.func, items: React.PropTypes.object, list: React.PropTypes.object, }, renderPageDrops () { const { items, currentPage, pageSize } = this.props; const totalPages = Math.ceil(items.count / pageSize); const style = { display: totalPages > 1 ? null : 'none' }; const pages = []; for (let i = 0; i < totalPages; i++) { const page = i + 1; const pageItems = '' + (page * pageSize - (pageSize - 1)) + ' - ' + (page * pageSize); const current = (page === currentPage); const className = classnames('ItemList__dropzone--page', { 'is-active': current, }); pages.push( <DropZoneTarget key={'page_' + page} page={page} className={className} pageItems={pageItems} pageSize={pageSize} currentPage={currentPage} drag={this.props.drag} dispatch={this.props.dispatch} /> ); } let cols = this.props.columns.length; if (this.props.list.sortable) cols++; if (!this.props.list.nodelete) cols++; return ( <tr style={style}> <td colSpan={cols} > <div className="ItemList__dropzone" > {pages} <div className="clearfix" /> </div> </td> </tr> ); }, render () { return this.renderPageDrops(); }, }); module.exports = ItemsTableDragDropZone;
js/components/App.js
js-mi/so
import React from 'react'; import Header from './Header'; import Container from './Container'; import Ribbon from './Ribbon'; class App extends React.Component { render () { return ( <div> <Header /> <Container /> <Ribbon /> </div> ); } } export default App;
docs/app/Examples/collections/Message/Types/MessageExampleIcon.js
vageeshb/Semantic-UI-React
import React from 'react' import { Message, Icon } from 'semantic-ui-react' const MessageExampleIcon = () => ( <Message icon> <Icon name='circle notched' loading /> <Message.Content> <Message.Header>Just one second</Message.Header> We are fetching that content for you. </Message.Content> </Message> ) export default MessageExampleIcon
src/svg-icons/av/sort-by-alpha.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSortByAlpha = (props) => ( <SvgIcon {...props}> <path d="M14.94 4.66h-4.72l2.36-2.36zm-4.69 14.71h4.66l-2.33 2.33zM6.1 6.27L1.6 17.73h1.84l.92-2.45h5.11l.92 2.45h1.84L7.74 6.27H6.1zm-1.13 7.37l1.94-5.18 1.94 5.18H4.97zm10.76 2.5h6.12v1.59h-8.53v-1.29l5.92-8.56h-5.88v-1.6h8.3v1.26l-5.93 8.6z"/> </SvgIcon> ); AvSortByAlpha = pure(AvSortByAlpha); AvSortByAlpha.displayName = 'AvSortByAlpha'; export default AvSortByAlpha;
src/components/Dashboard/index.js
LazyHaus/MyHaus
import React from 'react'; import { Card, } from 'react-mdl'; import './style.css'; import '../../../node_modules/react-grid-layout/css/styles.css'; import '../../../node_modules/react-mdl/extra/material.css'; import '../../../node_modules/react-mdl/extra/material.js'; import {Responsive, WidthProvider} from 'react-grid-layout'; const ResponsiveReactGridLayout = WidthProvider(Responsive); import SensorChart from '../SensorChart'; import {LazyPage} from '../LazyMain' var HausGrid = React.createClass({ render: function() { // layout is an array of objects, see the demo for more complete usage var dict = { isResizable: true, layout: [ {i: 'a', x: 0, y: 0, w: 1, h: 2}, {i: 'b', x: 1, y: 0, w: 3, h: 2, minW: 2, maxW: 4}, {i: 'c', x: 4, y: 0, w: 1, h: 2} ] }; return ( <ResponsiveReactGridLayout {...dict} className="layout" breakpoints={{lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0}} cols={{lg: 12, md: 10, sm: 6, xs: 4, xxs: 2}}> <Card key={'a'} shadow={0}><SensorChart /></Card> <Card key={'b'} shadow={0}> 2 </Card> <Card key={'c'} shadow={0}> 3 </Card> </ResponsiveReactGridLayout> ) } }); class Dashboard extends React.Component { constructor(...props) { super(...props); this.state = {} } render() { return ( <LazyPage title="Dashboard" pageName="Dashboard"> <div className="React-grid"> <HausGrid /> </div> </LazyPage> ) } } export default Dashboard;
src/components/chat-pane.js
johnamiahford/slack-clone
'use strict'; import React from 'react'; class ChatPane extends React.Component { render() { return ( <div className="ChatPane"> <div className="container"> <h2>Hey There!</h2> </div> </div> ); } } export default ChatPane;
src/components/TodoApp.js
bofa/react-education
import React from 'react'; // import todos from '../todos'; // import TodoApp = from './components/smart/TodoAppContainer'; // import IndexPage = from './components/smart/IndexPageContainer'; import { List } from 'immutable'; export default class TodoApp extends React.Component { render() { console.log('props', this.props) const { todos, addTodo, toggleTodo, removeTodo, reciveTodos, saveTodos } = this.props; return ( <div> <h1>Behond here there be TODOS!</h1> {this.props.children} </div> ); } componentDidMount() { const { reciveTodos } = this.props; reciveTodos(); } }
src/component/ToDoListWithFlux/TodoFooter.react.js
lyc-chengzi/reactProject
/** * Created by liuyc14 on 2016/9/26. */ import React from 'react'; import TodoAction from '../../flux/actions/TodoAction'; let ReactPropTypes = React.PropTypes; export default class TodoFooter extends React.Component{ constructor(props){ super(props); this._onClearCompletedClick = this._onClearCompletedClick.bind(this); } render() { var allTodos = this.props.allTodos; var total = Object.keys(allTodos).length; if (total === 0) { return null; } var completed = 0; for (var key in allTodos) { if (allTodos[key].complete) { completed++; } } var itemsLeft = total - completed; var itemsLeftPhrase = itemsLeft === 1 ? ' item ' : ' items '; itemsLeftPhrase += 'left'; // Undefined and thus not rendered if no completed items are left. var clearCompletedButton; if (completed) { clearCompletedButton = <button id="clear-completed" onClick={this._onClearCompletedClick}> 清理已完成事项 ({completed}) </button>; } return ( <footer id="footer"> <span id="todo-count"> <strong> {itemsLeft} </strong> {itemsLeftPhrase} </span> {clearCompletedButton} </footer> ); } /** * Event handler to delete all completed TODOs */ _onClearCompletedClick(){ TodoAction.removeCompleted(); } } TodoFooter.propTypes = { allTodos: ReactPropTypes.object.isRequired };
lib/components/notifications.js
ekmartin/hyperterm
import React from 'react'; import Component from '../component'; import {decorate} from '../utils/plugins'; import Notification_ from './notification'; const Notification = decorate(Notification_); export default class Notifications extends Component { template(css) { return (<div className={css('view')}> { this.props.customChildrenBefore } { this.props.fontShowing && <Notification key="font" backgroundColor="rgba(255, 255, 255, .2)" text={`${this.props.fontSize}px`} userDismissable={false} onDismiss={this.props.onDismissFont} dismissAfter={1000} /> } { this.props.resizeShowing && <Notification key="resize" backgroundColor="rgba(255, 255, 255, .2)" text={`${this.props.cols}x${this.props.rows}`} userDismissable={false} onDismiss={this.props.onDismissResize} dismissAfter={1000} /> } { this.props.messageShowing && <Notification key="message" backgroundColor="#FE354E" text={this.props.messageText} onDismiss={this.props.onDismissMessage} userDismissable={this.props.messageDismissable} userDismissColor="#AA2D3C" >{ this.props.messageURL ? [ this.props.messageText, ' (', <a key="link" style={{color: '#fff'}} onClick={ev => { window.require('electron').shell.openExternal(ev.target.href); ev.preventDefault(); }} href={this.props.messageURL} >more</a>, ')' ] : null } </Notification> } { this.props.updateShowing && <Notification key="update" backgroundColor="#7ED321" text={`Version ${this.props.updateVersion} ready`} onDismiss={this.props.onDismissUpdate} userDismissable > Version <b>{this.props.updateVersion}</b> ready. {this.props.updateNote && ` ${this.props.updateNote.trim().replace(/\.$/, '')}`} {' '} (<a style={{color: '#fff'}} onClick={ev => { window.require('electron').shell.openExternal(ev.target.href); ev.preventDefault(); }} href={`https://github.com/zeit/hyper/releases/tag/${this.props.updateVersion}`} >notes</a>). {' '} <a style={{ cursor: 'pointer', textDecoration: 'underline', fontWeight: 'bold' }} onClick={this.props.onUpdateInstall} > Restart </a>. { ' ' } </Notification> } { this.props.customChildren } </div>); } styles() { return { view: { position: 'fixed', bottom: '20px', right: '20px' } }; } }
generators/app/templates/app/src/components/SOQHighlightable/SOQHighlightable.js
hasura/generator-hasura-web
import React from 'react'; import { connect } from 'react-redux'; import { toggleHighlight } from './Actions'; import SOQuestion from '../SOQuestion/SOQuestion'; class SOQHighlightable extends React.Component { static propTypes = { question: React.PropTypes.shape({ title: React.PropTypes.string.isRequired, link: React.PropTypes.string.isRequired }).isRequired, unique: React.PropTypes.string.isRequired, highlighted: React.PropTypes.bool, dispatch: React.PropTypes.func.isRequired }; render() { const { question, dispatch, unique, highlighted } = this.props; return ( <div style={ (highlighted) ? {backgroundColor: 'yellow'} : {} }> <SOQuestion question={question}/> <a onClick={ (e) => { e.preventDefault(); dispatch(toggleHighlight(unique)); } } href=""> Highlight</a> </div> ); } } const mapStateToProps = (state, ownProps) => { return { unique: ownProps.unique, highlighted: state.soqh.questions.indexOf(ownProps.unique) > -1 }; }; export default connect(mapStateToProps)(SOQHighlightable);
modules/Link.js
Jastrzebowski/react-router
import React from 'react'; var { object, string, func } = React.PropTypes; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } /** * <Link> components are used to create an <a> element that links to a route. * When that route is active, the link gets an "active" class name (or the * value of its `activeClassName` prop). * * For example, assuming you have the following route: * * <Route name="showPost" path="/posts/:postID" handler={Post}/> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> * * Links may pass along query string parameters * using the `query` prop. * * <Link to="/posts/123" query={{ show:true }}/> */ export var Link = React.createClass({ contextTypes: { router: object }, propTypes: { activeStyle: object, activeClassName: string, to: string.isRequired, query: object, state: object, onClick: func }, getDefaultProps() { return { className: '', activeClassName: 'active', style: {} }; }, handleClick(event) { var allowTransition = true; var clickResult; if (this.props.onClick) clickResult = this.props.onClick(event); if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; if (clickResult === false || event.defaultPrevented === true) allowTransition = false; event.preventDefault(); if (allowTransition) this.context.router.transitionTo(this.props.to, this.props.query, this.props.state); }, render() { var { router } = this.context; var { to, query } = this.props; var props = Object.assign({}, this.props, { href: router.makeHref(to, query), onClick: this.handleClick }); // ignore if rendered outside of the context of a router, simplifies unit testing if (router && router.isActive(to, query)) { if (props.activeClassName) props.className += props.className !== '' ? ` ${props.activeClassName}` : props.activeClassName; if (props.activeStyle) props.style = Object.assign({}, props.style, props.activeStyle); } return React.createElement('a', props); } }); export default Link;
src/svg-icons/av/videocam.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvVideocam = (props) => ( <SvgIcon {...props}> <path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"/> </SvgIcon> ); AvVideocam = pure(AvVideocam); AvVideocam.displayName = 'AvVideocam'; AvVideocam.muiName = 'SvgIcon'; export default AvVideocam;
js/views/CalendarPage.js
ecohealthalliance/GoodQuestion
import React from 'react'; import { Text, View, } from 'react-native'; import moment from 'moment'; import Styles from '../styles/Styles'; import Color from '../styles/Color'; import Calendar from '../components/Calendar/Calendar'; import CalendarEvent from '../components/Calendar/CalendarEvent'; import Loading from '../components/Loading'; import { loadCachedFormDataById } from '../api/Forms'; import { loadCachedTimeTriggers } from '../api/Triggers'; const CalendarPage = React.createClass({ propTypes: { navigator: React.PropTypes.object.isRequired, survey: React.PropTypes.object, }, getInitialState() { return { stage: 'loading', events: [], selectedEvent: null, }; }, componentDidMount() { loadCachedTimeTriggers({ surveyId: this.props.survey ? this.props.survey.id : false, excludeCompleted: true, excludeExpired: true, }, (err, response) => { if (err) { console.warn(err); this.setState({ stage: 'error'}); return; } const responseLength = response.length; const eventDates = []; const eventIndex = {}; for (let i = 0; i < responseLength; i++) { const date = moment(response[i].datetime).format('YYYY-MM-DD'); eventDates.push(date); if (!eventIndex[date]) { eventIndex[date] = []; } eventIndex[date].push({ datetime: response[i].datetime, title: response[i].title, triggerId: response[i].id, formId: response[i].formId, surveyId: response[i].surveyId, }); } this.eventIndex = eventIndex; this.setState({ events: eventDates, selectedEvent: this.getSelectedEvent(moment().format('YYYY-MM-DD')), }); setTimeout(() => { if (!this.cancelCallbacks) { this.setState({stage: 'ready'}); } }, 300); }); }, componentWillUnmount() { this.cancelCallbacks = true; }, /* Methods */ selectDate(date) { const eventDate = moment(date).format('YYYY-MM-DD'); this.setState({ selectedDate: date, selectedEvent: this.getSelectedEvent(eventDate), }); }, getSelectedEvent(eventDate) { if (this.eventIndex[eventDate]) { const event = this.eventIndex[eventDate][0]; return { type: 'datetime', title: moment(eventDate).format('MMMM Do YYYY'), description: event.title, availability: `Available: ${moment(event.datetime).format('LT')}`, formId: event.formId, }; } return null; }, /* Render */ renderSelectedEvents() { if (this.state.selectedEvent) { const event = this.state.selectedEvent; return ( <CalendarEvent id='1' type='datetime' title={event.title} description={event.description} availability={event.availability} questionCount={10} onPress={() => { const data = loadCachedFormDataById(event.formId); this.props.navigator.push({ path: 'form', title: data.survey.title, survey: data.survey, form: data.form, type: 'datetime', }); }} /> ); } return <Text style={Styles.calendar.eventWarningText}>No remaining events present on this selected date.</Text>; }, render() { if (this.state.stage === 'loading') { return <Loading/>; } else if (this.state.stage === 'error') { return <Text style={[Styles.type.h2, {color: Color.faded}]}>Error loading scheduled dates...</Text>; } return ( <View style={[Styles.container.defaultWhite, { flex: 1, overflow: 'hidden' }]}> <Calendar ref='_calendar' showControls titleFormat={'MMMM YYYY'} prevButtonText={'Prev'} nextButtonText={'Next'} onDateSelect={this.selectDate} onTouchPrev={() => console.log('Back TOUCH')} onTouchNext={() => console.log('Forward TOUCH')} onSwipePrev={() => console.log('Back SWIPE')} onSwipeNext={() => console.log('Forward SWIPE')} eventDates={this.state.events} customStyle={Styles.calendar} /> {this.renderSelectedEvents()} </View> ); }, }); module.exports = CalendarPage;
admin/client/App/shared/Popout/PopoutBody.js
jstockwin/keystone
/** * Render the body of a popout */ import React from 'react'; import blacklist from 'blacklist'; import classnames from 'classnames'; var PopoutBody = React.createClass({ displayName: 'PopoutBody', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, scrollable: React.PropTypes.bool, }, render () { const className = classnames('Popout__body', { 'Popout__scrollable-area': this.props.scrollable, }, this.props.className); const props = blacklist(this.props, 'className', 'scrollable'); return ( <div className={className} {...props} /> ); }, }); module.exports = PopoutBody;
src/public/components/tree/index.js
Lunik/tcloud
import React from 'react' import $ from 'jquery' import Path from 'path' import Branch from './branch' export default class Tree extends React.Component { constructor (props) { super(props) this.state = {} this.initState(props) } initState (props) { Object.assign(this.state, { mobile: window.innerWidth <= 620 }) } componentWillReceiveProps (props) { this.initState(props) } componentWillMount () { $(window).on('resize', (event) => this.handleWindowResize()) } componentWillUnmount () { $(window).off('resize', (event) => this.handleWindowResize()) } handleWindowResize () { this.setState({ mobile: window.innerWidth <= 620 }) } render () { let branches = this.props.path.split('/') let currentPath = '' var JSXBranches = branches.map((branch, key) => { currentPath = Path.join(currentPath, branch) return ( <Branch id={branch} key={key} url={`#${currentPath}`} text={branch}/> ) }) return ( !this.state.mobile && <div className="tree" style={style.div}> <Branch id='files' url="#" text="files"/> {JSXBranches} </div> ) } } Tree.defaultProps = { path: '' } const style = { div: { display: 'inline-block' } }
src/svg-icons/maps/local-drink.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalDrink = (props) => ( <SvgIcon {...props}> <path d="M3 2l2.01 18.23C5.13 21.23 5.97 22 7 22h10c1.03 0 1.87-.77 1.99-1.77L21 2H3zm9 17c-1.66 0-3-1.34-3-3 0-2 3-5.4 3-5.4s3 3.4 3 5.4c0 1.66-1.34 3-3 3zm6.33-11H5.67l-.44-4h13.53l-.43 4z"/> </SvgIcon> ); MapsLocalDrink = pure(MapsLocalDrink); MapsLocalDrink.displayName = 'MapsLocalDrink'; MapsLocalDrink.muiName = 'SvgIcon'; export default MapsLocalDrink;
Realization/frontend/czechidm-core/src/content/dashboards/LongRunningTaskDashboard.js
bcvsolutions/CzechIdMng
import React from 'react'; import { connect } from 'react-redux'; import * as Basic from '../../components/basic'; import { SecurityManager, LongRunningTaskManager } from '../../redux'; import RunningTasks from '../scheduler/RunningTasks'; const manager = new LongRunningTaskManager(); const uiKeyPrefix = 'long-running-taks-table-'; /** * Identity info with link to profile * * @author Radek Tomiška */ class LongRunningTaskDashboard extends Basic.AbstractContent { getContentKey() { return 'dashboard.longRunningTaskDashboard'; } render() { const { identity, _total } = this.props; // if (!SecurityManager.hasAnyAuthority(['SCHEDULER_READ'])) { return null; } // return ( <Basic.Div className={ _total ? '' : 'hidden' }> <Basic.ContentHeader icon="component:scheduled-task" text={ this.i18n('dashboard.longRunningTaskDashboard.header') }/> <Basic.Panel> <RunningTasks manager={ manager } uiKey={ `${ uiKeyPrefix }${ identity ? identity.id : 'dashboard' }` } creatorId={ identity ? identity.id : null } /> </Basic.Panel> </Basic.Div> ); } } function select(state, component) { const uiKey = `${ uiKeyPrefix }${ component.identity ? component.identity.id : 'dashboard' }`; const ui = state.data.ui[uiKey]; if (!ui) { return { i18nReady: state.config.get('i18nReady') }; } return { _total: ui.total, i18nReady: state.config.get('i18nReady') }; } export default connect(select)(LongRunningTaskDashboard);
frontend/src/components/partners/profile/modals/updateObservationSanction/updateSanctionObservationForm.js
unicef/un-partner-portal
import React from 'react'; import R from 'ramda'; import { reduxForm } from 'redux-form'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { Grid } from 'material-ui'; import GridColumn from '../../../../common/grid/gridColumn'; import TextFieldForm from '../../../../forms/textFieldForm'; import SelectForm from '../../../../forms/selectForm'; import { selectNormalizedFlagCategoryChoices, selectNormalizedFlagTypeChoices } from '../../../../../store'; import ArrayForm from '../../../../forms/arrayForm'; import RadioForm from '../../../../forms/radioForm'; const messages = { comments: 'Comments', categoryOfRisk: 'Category of risk', decision: 'Reason for decision', enterDetails: 'Enter additional details...', }; export const SANCATION_DECISION = { NOTMATCH: 'NM', CONFIRMED: 'CM', }; const radioFlag = [ { value: SANCATION_DECISION.NOTMATCH, label: 'Not a true Match', }, { value: SANCATION_DECISION.CONFIRMED, label: 'Confirmed Match', }, ]; const commentFormControlStyle = { padding: '12px 0', }; const Decision = () => () => ( <Grid container> <Grid item sm={12} xs={12}> <RadioForm fieldName="reason_radio" values={radioFlag} /> <TextFieldForm commentFormControlStyle={commentFormControlStyle} label={messages.decision} placeholder={messages.enterDetails} fieldName="validation_comment" /> </Grid> </Grid> ); const UpdateSanctionObservationForm = (props) => { const { categoryChoices, handleSubmit } = props; return ( <form onSubmit={handleSubmit}> <GridColumn> <SelectForm label={messages.categoryOfRisk} fieldName="category" readOnly values={categoryChoices} /> <TextFieldForm label={messages.comments} readOnly fieldName="comment" /> <ArrayForm limit={1} fieldName="flag_decision" disableDeleting initial outerField={Decision()} /> </GridColumn> </form > ); }; UpdateSanctionObservationForm.propTypes = { /** * callback for form submit */ handleSubmit: PropTypes.func.isRequired, categoryChoices: PropTypes.array, }; const formUpdateSanctionObservation = reduxForm({ form: 'updateSanctionObservationForm', })(UpdateSanctionObservationForm); const mapStateToProps = (state, ownProps) => { const observation = R.find(R.propEq('id', ownProps.id), state.partnerObservationsList.items); return { categoryChoices: selectNormalizedFlagCategoryChoices(state), flagTypes: selectNormalizedFlagTypeChoices(state), initialValues: { contact_person: observation.contactPerson, contact_phone: observation.contactPhone, contact_email: observation.contactEmail, attachment: observation.attachment, category: observation.category, comment: observation.comment, }, }; }; export default connect( mapStateToProps, null, )(formUpdateSanctionObservation);
src/routes/private/PanelTools/FilesManager/FilesManager.js
sk-iv/iva-app
import React from 'react'; import {graphql, compose} from 'react-apollo'; import IconButton from '../../../../components/IconButton' import {ChevronRight, Hierarchy, Facets, Hash, Export, TextInput, Magnifier, Plus, Filter, ChevronDown, ChevronLeft, Square, FileUpload, Times, Image, Book} from '../../../../components/SvgIcon'; import List, { ListItem, ListItemIcon, ListItemSecondaryActionStart, ListItemSecondaryAction, ListItemText } from '../../../../components/List' import Checkbox from '../../../../components/Checkbox'; import FILES_LIST from '../../../../queries/fetchFilesList'; import ADD_FILE from '../../../../mutations/AddFile'; import Snackbar from '../../../../components/Snackbar' import Button from '../../../../components/Button' import Avatar from '../../../../components/Avatar' import StateGlobal from '../../../../hoc/StateGlobal' import ActionsPopup from './ActionsPopup' @graphql(FILES_LIST, {name: 'FilesList'}) @graphql(ADD_FILE, {name: 'AddFileMutation'}) @StateGlobal class FilesManager extends React.Component { state = { fileData:[] }; handleToggle = value => () => { const { checked } = this.state; const currentIndex = checked.indexOf(value); const newChecked = [...checked]; if (currentIndex === -1) { newChecked.push(value); } else { newChecked.splice(currentIndex, 1); } this.setState({ checked: newChecked, }); }; render(){ const { stateGlobalQuery:{ openPopup, }, FilesList:{filesList, loading} } = this.props; let type = ['image', 'epub'].map(type=>{ return ('image/jpeg').match(new RegExp(type, "g")); }).filter(x => !!x)[0] console.log(type[0]); const { vertical, horizontal, open, fileData } = this.state; if (loading) {return <div>Loading ...</div>;} return( <React.Fragment> <div className="py-3"> <div className="nav"> <div className="nav-item"> <IconButton aria-label="Zoom" color="primary" to={{pathname:`/private/entity-edit`}}> <Magnifier/> </IconButton> </div> <div className="nav-item"> <input style={{display: 'none'}} id="icon-button-file" type="file" multiple onChange={({ target: { validity, files } })=> { if(validity.valid){ var formData = new FormData(); for (var x = 0; x < files.length; x++){ formData.append("files", files[x]); } // stream progress: https://github.com/SitePen/javascript-streams-blog-examples/blob/master/streaming-fetch/main.js // https://www.sitepen.com/blog/2017/10/02/a-guide-to-faster-web-app-io-and-data-operations-with-streams/ fetch('/uploads',{ method: 'POST', body:formData }).then(res =>{ if (res.status !== 200) { console.log('Looks like there was a problem. Status Code: ' + res.status); return; } // this.consume(res.body.getReader()) res.json().then(data =>{ console.log(data); this.setState({ fileData: data }); this.props.AddFileMutation({ variables: { fileData: data }, }).then(upload =>{ console.log(upload); }) }) }).catch((error) => { console.warn(error); }); } }} /> <label htmlFor="icon-button-file"> <IconButton aria-label="FileUpload" color="primary" component="span"> <FileUpload/> </IconButton> </label> </div> </div> </div> <div className="row"> <div className="col-12"> <List> {filesList.map((item , index)=>( <ListItem key={index}> <Avatar className="mr-3"> <Book /> </Avatar> <ListItemText primary={item.fileName} /> <ListItemSecondaryAction> <ActionsPopup open={openPopup == `file${item.id}`} item={{ slug:`file${item.id}`, catalogHidden:1, id:item.id, type: `file` }} /> </ListItemSecondaryAction> </ListItem> ))} </List> </div> </div> <Snackbar anchorOrigin={{ vertical, horizontal }} open={open} onClose={this.handleClose} SnackbarContentProps={{ 'aria-describedby': 'message-id', }} message={[ <span id="message-id" key={0}>Загрузка файлов</span>, <List key={1}> {fileData.map((file, index)=>( file.originalname ? ( <ListItem key={index}> {file.originalname} </ListItem> ) : ( <ListItem key={index}> {file.error} </ListItem> ) ))} </List> ]} action={[ <IconButton key="close" aria-label="Close" color="inherit" onClick={this.handleClose} > <Times /> </IconButton>, ]} /> </React.Fragment>) } } export default FilesManager;
packages/vulcan-core/lib/modules/containers/withRemove.js
bengott/Telescope
/* Generic mutation wrapper to remove a document from a collection. Sample mutation: mutation moviesRemove($documentId: String) { moviesEdit(documentId: $documentId) { ...MoviesRemoveFormFragment } } Arguments: - documentId: the id of the document to remove Child Props: - removeMutation(documentId) */ import React, { Component } from 'react'; import { graphql } from 'react-apollo'; import gql from 'graphql-tag'; export default function withRemove(options) { const { collection } = options, mutationName = collection.options.mutations.remove.name return graphql(gql` mutation ${mutationName}($documentId: String) { ${mutationName}(documentId: $documentId) { _id } } `, { alias: 'withRemove', props: ({ ownProps, mutate }) => ({ removeMutation: ({ documentId }) => { return mutate({ variables: { documentId } }); }, }), }); }
src/components/GuitarApp/parts/Fretguide/index.js
jesusGalan/fretboardApp
import React, { Component } from 'react'; import {TransparentDiv} from './styled' import {Row} from 'components/common/Template' class Fretguide extends Component { render() { let frets = [] let x = 0 for (x = 0; x < 12; x++) { frets.push(x) } return ( <Row> {frets.map(this.renderTransparentDivs.bind(this))} </Row> ); } renderTransparentDivs(x) { if (x === 0 || x === 3 || x === 5 || x === 7) { return( <TransparentDiv key={x} number={x.toString()}>{x}</TransparentDiv> ) } else { return( <TransparentDiv key={x} number={x.toString()}></TransparentDiv> ) } } } export default Fretguide;
src/svg-icons/maps/add-location.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsAddLocation = (props) => ( <SvgIcon {...props}> <path d="M12 2C8.14 2 5 5.14 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.86-3.14-7-7-7zm4 8h-3v3h-2v-3H8V8h3V5h2v3h3v2z"/> </SvgIcon> ); MapsAddLocation = pure(MapsAddLocation); MapsAddLocation.displayName = 'MapsAddLocation'; MapsAddLocation.muiName = 'SvgIcon'; export default MapsAddLocation;
src/components/Select.js
aastein/crypto-trader
import React, { Component } from 'react'; import FontAwesome from 'react-fontawesome'; class Select extends Component { constructor(props) { super(props); this.state = { expanded: false, }; } handleExpand = (event) => { event.preventDefault(); this.setState(prevState => ( { expanded: !prevState.expanded } )); } render() { return ( <div className={`dropdown ${this.props.className}`}> <div className="dropdown-toggle Select-control" role="menu" onClick={this.handleExpand} tabIndex={0}> <span className="Select-value-label">{this.props.value}</span> <span className="Select-arrow-zone"> <span className="Select-arrow" /> </span> </div> { this.state.expanded && <div className="dropdown-menu" aria-hidden> { this.props.options.map((o, i) => ( <div key={`${o.value}${i}`}className="dropdown-item Select-option"> <span className="item-label">{o.label}</span> <div className="item-options"> <input defaultChecked={o.active} className="item-checkbox" type="checkbox" onChange={(e) => { this.props.onCheck(o.value); }} /> <div className="item-drilldown" role="button" onClick={(e) => { this.props.handleDrilldown(o.value); }} tabIndex={0}> <FontAwesome name="chevron-right" /> </div> </div> </div> )) } </div> } </div> ); } } export default Select;
examples/huge-apps/app.js
djkirby/react-router
import React from 'react' import { render } from 'react-dom' import { Router, browserHistory } from 'react-router' import withExampleBasename from '../withExampleBasename' import './stubs/COURSES' const rootRoute = { childRoutes: [ { path: '/', component: require('./components/App'), childRoutes: [ require('./routes/Calendar'), require('./routes/Course'), require('./routes/Grades'), require('./routes/Messages'), require('./routes/Profile') ] } ] } render(( <Router history={withExampleBasename(browserHistory, __dirname)} routes={rootRoute} /> ), document.getElementById('example')) // I've unrolled the recursive directory loop that is happening above to get a // better idea of just what this huge-apps Router looks like, or just look at the // file system :) // // import { Route } from 'react-router' // import App from './components/App' // import Course from './routes/Course/components/Course' // import AnnouncementsSidebar from './routes/Course/routes/Announcements/components/Sidebar' // import Announcements from './routes/Course/routes/Announcements/components/Announcements' // import Announcement from './routes/Course/routes/Announcements/routes/Announcement/components/Announcement' // import AssignmentsSidebar from './routes/Course/routes/Assignments/components/Sidebar' // import Assignments from './routes/Course/routes/Assignments/components/Assignments' // import Assignment from './routes/Course/routes/Assignments/routes/Assignment/components/Assignment' // import CourseGrades from './routes/Course/routes/Grades/components/Grades' // import Calendar from './routes/Calendar/components/Calendar' // import Grades from './routes/Grades/components/Grades' // import Messages from './routes/Messages/components/Messages' // render( // <Router> // <Route path="/" component={App}> // <Route path="calendar" component={Calendar} /> // <Route path="course/:courseId" component={Course}> // <Route path="announcements" components={{ // sidebar: AnnouncementsSidebar, // main: Announcements // }}> // <Route path=":announcementId" component={Announcement} /> // </Route> // <Route path="assignments" components={{ // sidebar: AssignmentsSidebar, // main: Assignments // }}> // <Route path=":assignmentId" component={Assignment} /> // </Route> // <Route path="grades" component={CourseGrades} /> // </Route> // <Route path="grades" component={Grades} /> // <Route path="messages" component={Messages} /> // <Route path="profile" component={Calendar} /> // </Route> // </Router>, // document.getElementById('example') // )
examples/examples/FinancialChartExample.react.js
ericgio/r-d3
import * as d3 from 'd3'; import React from 'react'; import {Axis, Candlestick, Chart, OHLC} from '../../src'; import {getInnerHeight, getInnerWidth, translate} from '../../src/utils'; import ohlcData from '../data/ohlc.csv'; /* example-start */ /** * Adapted from http://bl.ocks.org/andredumas/27c4a333b0e0813e093d */ class FinancialChartExample extends React.Component { state = { type: 'candlestick', }; render() { const {type} = this.state; const height = 500; const width = 960; const margin = {top: 20, right: 20, bottom: 30, left: 50}; const innerHeight = getInnerHeight(height, margin); const innerWidth = getInnerWidth(width, margin); const keys = ohlcData.columns.slice(1); const parseDate = d3.timeParse('%d-%b-%y'); const data = []; ohlcData.slice(50, 200).forEach((d) => { const date = parseDate(d.Date); const n = {date}; keys.forEach((k) => n[k.toLowerCase()] = +d[k]); data.push(n); }); const x = d3.scaleTime() .domain(d3.extent(data, (d) => d.date)) .rangeRound([0, innerWidth]); const y = d3.scaleLinear() .domain([ d3.min(data, (d) => d3.min([d.close, d.high, d.low, d.open])) - 1, d3.max(data, (d) => d3.max([d.close, d.high, d.low, d.open])) + 1, ]) .rangeRound([innerHeight, 0]); const Component = type === 'candlestick' ? Candlestick : OHLC; return ( <div> <div style={{right: '10px', position: 'absolute', top: '10px'}}> {['Candlestick', 'OHLC'].map((t) => ( <label key={t} style={{marginRight: '10px'}}> <input checked={t.toLowerCase() === type} name="ohlc-example" onChange={this._handleChange} type="radio" value={t.toLowerCase()} /> {t} Chart </label> ))} </div> <Chart height={height} transform={translate(margin.left, margin.top)} width={width}> <Axis className="x-axis" orient="bottom" scale={x} transform={translate(0, innerHeight)} /> <Axis className="y-axis" orient="left" scale={y}> <text dy="0.71em" fill="#000" textAnchor="end" transform="rotate(-90)" y={6}> Price ($) </text> </Axis> {data.map((d) => ( <Component {...d} key={d.date.getTime()} width={3} x={x} y={y} /> ))} </Chart> </div> ); } _handleChange = (e) => { this.setState({type: e.target.value}); } } /* example-end */ export default FinancialChartExample;
src/components/applications/index.js
Menternship/client-web
// @flow import React from 'react'; import { Route } from 'react-router'; import ShowAll from './ShowAll'; export default [<Route path="applications" component={ShowAll} />];
app/javascript/mastodon/components/avatar.js
corzntin/mastodon
import React from 'react'; import PropTypes from 'prop-types'; export default class Avatar extends React.PureComponent { static propTypes = { src: PropTypes.string.isRequired, staticSrc: PropTypes.string, size: PropTypes.number.isRequired, style: PropTypes.object, animate: PropTypes.bool, inline: PropTypes.bool, }; static defaultProps = { animate: false, size: 20, inline: false, }; state = { hovering: false, }; handleMouseEnter = () => { if (this.props.animate) return; this.setState({ hovering: true }); } handleMouseLeave = () => { if (this.props.animate) return; this.setState({ hovering: false }); } render () { const { src, size, staticSrc, animate, inline } = this.props; const { hovering } = this.state; let className = 'account__avatar'; if (inline) { className = className + ' account__avatar-inline'; } const style = { ...this.props.style, width: `${size}px`, height: `${size}px`, backgroundSize: `${size}px ${size}px`, }; if (hovering || animate) { style.backgroundImage = `url(${src})`; } else { style.backgroundImage = `url(${staticSrc})`; } return ( <div className={className} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} style={style} /> ); } }
www/src/App.js
ctnitchie/ec2-dashboard
import React from 'react'; import {ec2Service, eventBus} from './services'; import InstanceInfo from './InstanceInfo'; import autobind from 'react-autobind'; import _ from 'lodash'; export default class App extends React.Component { constructor() { super(); this.state = { instances: [], unfilteredInstances: [], filterText: '', showRunning: true, showStopped: true, loadPending: true }; autobind(this); } async componentDidMount() { let instances; try { instances = await ec2Service.listInstances(); instances = instances.sort((a, b) => { let aName = a.tags.Name || a.id; let bName = b.tags.Name || b.id; return aName < bName ? -1 : 1; }); } catch (e) { alert('Error loading instances.'); console.log(e); } this.setState({unfilteredInstances: instances, instances: instances, loadPending: false}); } onFilterChanged(event) { this.filterInstances({filterText: event.target.value}); } filterInstances(newConfig) { let newState = Object.assign( _.pick(this.state, 'filterText', 'showRunning', 'showStopped'), newConfig ); let instances = this.state.unfilteredInstances; let test = newState.filterText.toLowerCase(); newState.instances = this.state.unfilteredInstances.filter((instance) => { if (!newState.showRunning && (instance.state === 'running' || instance.state === 'pending')) { return false; } if (!newState.showStopped && (instance.state === 'stopped' || instance.state === 'stopping')) { return false; } if (test) { let name = instance.tags.Name || instance.id; name += " " + instance.id; instance.securityGroups.forEach(grp => name += " " + grp); Object.values(instance.tags).forEach(v => name += " " + v); return name.toLowerCase().indexOf(test) !== -1; } return true; }); this.setState(newState); } expandAll(event) { eventBus.emit('expandAll'); event.preventDefault(); return false; } collapseAll(event) { eventBus.emit('collapseAll'); event.preventDefault(); return false; } toggleShowStopped() { this.filterInstances({showStopped: !this.state.showStopped}); } toggleShowRunning() { this.filterInstances({showRunning: !this.state.showRunning}); } render() { let instanceList; if (this.state.instances.length) { instanceList = []; this.state.instances.forEach(instance => { instanceList.push(<InstanceInfo key={instance.id} record={instance}/>); }); } else if (this.state.loadPending) { instanceList = <p className="col-sm-offset-3"><span className="spinner"/>&nbsp;Loading...</p>; } else { instanceList = <p className="col-sm-offset-3"><b>No instances found.</b></p>; } return ( <div className="container"> <div className="row"> <div className="col-xs-12"> <h1>EC2 Instance Status Dashboard</h1> <hr/> <div className="row"> <div className="col-xs-12 col-sm-6 col-sm-offset-3"> <div className="form-group"> <label htmlFor="filterInput">Search:</label> <input type="text" className="form-control" id="filterInput" value={this.state.filterText} onChange={this.onFilterChanged} disabled={this.state.loadPending}/> </div> <div className="text-center"> <label> <input type="checkbox" checked={this.state.showRunning} disabled={this.state.loadPending} onChange={this.toggleShowRunning}/> {' Include running instances'} </label> {' '} <label> <input type="checkbox" checked={this.state.showStopped} disabled={this.state.loadPending} onChange={this.toggleShowStopped}/> {' Include stopped instances'} </label> </div> </div> </div> <div className="row"> <div className="col-xs-12 col-sm-6 col-sm-offset-3 expandCollapseButtons"> <a href="#" onClick={this.expandAll}>Expand All</a> &nbsp;|&nbsp; <a href="#" onClick={this.collapseAll}>Collapse All</a> </div> </div> <div className="row"> {instanceList} </div> </div> </div> </div> ); } }
src/svg-icons/notification/sms.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationSms = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM9 11H7V9h2v2zm4 0h-2V9h2v2zm4 0h-2V9h2v2z"/> </SvgIcon> ); NotificationSms = pure(NotificationSms); NotificationSms.displayName = 'NotificationSms'; NotificationSms.muiName = 'SvgIcon'; export default NotificationSms;