path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
frontend/src/Components/DragPreviewLayer.js
lidarr/Lidarr
import PropTypes from 'prop-types'; import React from 'react'; import styles from './DragPreviewLayer.css'; function DragPreviewLayer({ children, ...otherProps }) { return ( <div {...otherProps}> {children} </div> ); } DragPreviewLayer.propTypes = { children: PropTypes.node, className: PropTypes.string }; DragPreviewLayer.defaultProps = { className: styles.dragLayer }; export default DragPreviewLayer;
src/parser/paladin/retribution/modules/core/ArtOfWar.js
sMteX/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import Combatants from 'parser/shared/modules/Combatants'; import Analyzer from 'parser/core/Analyzer'; import SpellUsable from 'parser/shared/modules/SpellUsable'; const ART_OF_WAR_DURATION = 10000; class AoWProcTracker extends Analyzer { static dependencies = { combatants: Combatants, spellUsable: SpellUsable, }; consumedAoWProcs = 0; wastedAoWProcs = 0; totalAoWProcs = 0; lastAoWProcTime = null; on_byPlayer_applybuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.BLADE_OF_WRATH_PROC.id) { return; } this.totalAoWProcs += 1; if (this.spellUsable.isOnCooldown(SPELLS.BLADE_OF_JUSTICE.id)) { this.spellUsable.endCooldown(SPELLS.BLADE_OF_JUSTICE.id); this.lastAoWProcTime = event.timestamp; } } on_byPlayer_refreshbuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.BLADE_OF_WRATH_PROC.id) { return; } this.wastedAoWProcs += 1; this.totalAoWProcs += 1; } get consumedProcsPercent() { return this.consumedAoWProcs / this.totalAoWProcs; } get suggestionThresholds() { return { actual: this.consumedProcsPercent, isLessThan: { minor: 0.95, average: 0.9, major: 0.85, }, style: 'percentage', }; } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (SPELLS.BLADE_OF_JUSTICE.id !== spellId) { return; } if (this.lastAoWProcTime !== event.timestamp) { if (this.lastAoWProcTime === null) { return; } const AoWTimeframe = this.lastAoWProcTime + ART_OF_WAR_DURATION; if (event.timestamp <= AoWTimeframe) { this.consumedAoWProcs += 1; this.lastAoWProcTime = null; } } } suggestions(when) { when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => { return suggest(<>You used {formatPercentage(this.consumedProcsPercent)}% of your <SpellLink id={SPELLS.ART_OF_WAR.id} icon /> procs.</>) .icon(SPELLS.ART_OF_WAR.icon) .actual(`${formatPercentage(this.consumedProcsPercent)}% proc(s) used.`) .recommended(`Using >${formatPercentage(recommended)}% is recommended`); }); } statistic() { return ( <StatisticBox position={STATISTIC_ORDER.OPTIONAL(2)} icon={<SpellIcon id={SPELLS.ART_OF_WAR.id} />} value={`${formatPercentage(this.consumedProcsPercent)}%`} label="Art of War Procs Used" tooltip={`You got ${this.totalAoWProcs} Art of War procs and used ${this.consumedAoWProcs} of them.`} /> ); } } export default AoWProcTracker;
src/components/TimelineBox/index.js
IDEOorg/steps-guide-builder
import React from 'react'; import PropTypes from 'prop-types'; import marked from 'marked'; import './index.less'; import { getTranslation } from '../../globals/utils'; marked.setOptions({ breaks: true }); const hrLine = (<hr className="timeline-hr" />); const TimelineBox = (props) => { let sections = props.content; let items = []; if (window.innerWidth < 1065) items.push(hrLine); for (let i = 0; i < sections.length; i++) { items.push(( <div className="timeline_content_box" dangerouslySetInnerHTML={{ "__html": marked(getTranslation(sections[i].content, props.language)) }} key={`${i}`} /> )); if (window.innerWidth > 1065) { items.push(( <img src={require('../../assets/timeline-arrow.svg')} /> )); } else { items.push(hrLine); } } if (items.length) { items.pop(); } return ( <div className="timeline_box"> <div className="timeline_title" dangerouslySetInnerHTML={{ "__html": marked(props.title, props.language) }} /> <div className="timeline_content_section"> {items} </div> </div> ); }; export default TimelineBox; TimelineBox.propTypes = { content: PropTypes.string }; TimelineBox.displayName = 'TimelineBox';
admin/client/App/components/Navigation/Mobile/ListItem.js
rafmsou/keystone
/** * A list item of the mobile navigation */ import React from 'react'; import { Link } from 'react-router'; const MobileListItem = React.createClass({ displayName: 'MobileListItem', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, href: React.PropTypes.string.isRequired, onClick: React.PropTypes.func, }, render () { return ( <Link className={this.props.className} to={this.props.href} onClick={this.props.onClick} tabIndex="-1" > {this.props.children} </Link> ); }, }); module.exports = MobileListItem;
react_native/mobile_app/index.ios.js
gilson27/LearnRevise
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; class mobile_app 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> </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('mobile_app', () => mobile_app);
server/sonar-web/src/main/js/apps/projects/components/AllProjects.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import PageHeaderContainer from './PageHeaderContainer'; import ProjectsListContainer from './ProjectsListContainer'; import ProjectsListFooterContainer from './ProjectsListFooterContainer'; import PageSidebar from './PageSidebar'; import VisualizationsContainer from '../visualizations/VisualizationsContainer'; import { parseUrlQuery } from '../store/utils'; import '../styles.css'; export default class AllProjects extends React.Component { static propTypes = { isFavorite: React.PropTypes.bool.isRequired, location: React.PropTypes.object.isRequired, fetchProjects: React.PropTypes.func.isRequired, organization: React.PropTypes.object, router: React.PropTypes.object.isRequired }; state = { query: {} }; componentDidMount() { this.handleQueryChange(); document.getElementById('footer').classList.add('search-navigator-footer'); } componentDidUpdate(prevProps) { if (prevProps.location.query !== this.props.location.query) { this.handleQueryChange(); } } componentWillUnmount() { document.getElementById('footer').classList.remove('search-navigator-footer'); } handleQueryChange() { const query = parseUrlQuery(this.props.location.query); this.setState({ query }); this.props.fetchProjects(query, this.props.isFavorite, this.props.organization); } handleViewChange = view => { const query = { ...this.props.location.query, view: view === 'list' ? undefined : view }; if (query.view !== 'visualizations') { Object.assign(query, { visualization: undefined }); } this.props.router.push({ pathname: this.props.location.pathname, query }); }; handleVisualizationChange = visualization => { this.props.router.push({ pathname: this.props.location.pathname, query: { ...this.props.location.query, view: 'visualizations', visualization } }); }; render() { const { query } = this.state; const isFiltered = Object.keys(query).some(key => query[key] != null); const view = query.view || 'list'; const visualization = query.visualization || 'quality'; const top = this.props.organization ? 95 : 30; return ( <div className="page-with-sidebar page-with-left-sidebar projects-page"> <aside className="page-sidebar-fixed page-sidebar-sticky projects-sidebar"> <div className="page-sidebar-sticky-inner" style={{ top }}> <PageSidebar query={query} isFavorite={this.props.isFavorite} organization={this.props.organization} /> </div> </aside> <div className="page-main"> <PageHeaderContainer onViewChange={this.handleViewChange} view={view} /> {view === 'list' && <ProjectsListContainer isFavorite={this.props.isFavorite} isFiltered={isFiltered} organization={this.props.organization} />} {view === 'list' && <ProjectsListFooterContainer query={query} isFavorite={this.props.isFavorite} organization={this.props.organization} />} {view === 'visualizations' && <VisualizationsContainer onVisualizationChange={this.handleVisualizationChange} sort={query.sort} visualization={visualization} />} </div> </div> ); } }
Demo4/Container/ArticleDetail.js
Quxiaolei/Study_RN
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, Image, ListView, Dimensions, Navigator, NavigatorIOS, ScrollView, ActivityIndicator, Platform, WebView, View, PanResponder } from 'react-native'; import Article from './Article'; import ArticleList from './ArticleList'; let HostApi = 'http://172.16.101.202/'; let ArticleDetailAPI = HostApi+'play/circle/getPostInfo4C'; // let ArticleDetailAPI = HostApi+'forum/articles/articleinfo/0/350/350.html'; let {height,width} = Dimensions.get('window'); class ArticleDetailView extends Component{ constructor(props){ super(props); this.state = { webViewHeight:100, } } componentWillMount(){ this._panResponder = PanResponder.create({ onMoveShouldSetPanResponder: (evt, gestureState) => true, onMoveShouldSetPanResponderCapture: (evt, gestureState) => true, onPanResponderMove: (evt, gestureState) => { // console.warn('x轴偏移量'+gestureState.dx); if(gestureState.dx > 50){ // console.warn(`2231231`+this.props.tabbarHidden); this.props.tabbarHidden(false); //返回列表 this.props.navigator.pop(); } }, }); } render(){ let result = this.props.articleData; let postTime = new Date(); postTime.setTime(result.postInfo.postTime); // console.warn(HostApi+result.postInfo.contentHtml); // console.warn(result.postInfo.title); return ( <ScrollView style = {styles.container} {...this._panResponder.panHandlers}> {/* <Text style = {{backgroundColor:'red',textAlign:'center'}}>{this.props.text}</Text> */} <Image source = {{uri:HostApi+result.postInfo.coverImgURL}} style = {styles.imageStyle}></Image> <Text style = {styles.titleText,{backgroundColor:'white'}}> {result.postInfo.title}</Text> <View style = {{backgroundColor:'white',flexDirection:'row','justifyContent':'space-between'}}> <Text style = {{fontSize:13,backgroundColor:'white'}}> {result.postInfo.authorInfo.nickName} {postTime.toLocaleString()}</Text> <Text style = {{fontSize:13,backgroundColor:'white'}}>{result.postInfo.visitNumber} </Text> </View> <WebView ref = 'webView' automaticallyAdjustContentInsets = {true} source = {{uri:HostApi+result.postInfo.contentHtml}} startInLoadingState = {true} scalesPageToFit = {true} scrollEnabled = {false} style = {{backgroundColor:'red',height:this.state.webViewHeight}} injectedJavaScript="document.addEventListener('message', function(e) {eval(e.data);});" onMessage = {(event)=>{ //网页端的window.postMessage会发送一个参数data.RN端获取webView的参数在event对象中,即event.nativeEvent.data //网页端收到高度参数 let webViewHeight = Number(event.nativeEvent.data); // alert('webViewHeight:'+webViewHeight); this.setState({ webViewHeight:webViewHeight, }) }} onLoadStart = {()=>{ // console.warn('webView load start \n'+Date().toLocaleString()); }} // onContentSizeChange = {()=>{ // console.warn(`contentHeight`); // }} onLoad = {()=>{ // FIXME 动态改变webView高度 // console.warn(`webView.height`); // console.warn('webView load end \n'+Date().toLocaleString()); // console.warn(this.refs.webView.height); // this.refs.webView.height = 1000; // console.warn(webView); }} onNavigationStateChange = {(navState) => { // console.warn(navState.url); // console.warn(this.refs.webView); }} onLoadEnd = {()=>{ //调用webview网页内部的window.postMessage方法发送参数,实现RN与网页之间的交互 //发送webView的高度 this.refs.webView.postMessage('window.postMessage(document.body.offsetHeight);'); // console.warn('webView load end \n'+Date().toLocaleString()); }} renderLoading = {()=><View style = {{flex:1,'justifyContent':'center'}}> <ActivityIndicator animating = {true} size = 'large'/> <Text style = {{textAlign:'center',color:'gray'}}>Loading...</Text> </View> } > </WebView> </ScrollView> ); } } export default class ArticleDetail extends Component { constructor(props){ super(props); // this.props.navigator.passProps.text; // console.warn(`title `+this.props.text); // console.warn(`navigator `+this.props.navigator.props.postId); this.state = { articleDetailData:null, }; } _requestArticleDetail(postId:string){ // console.warn(postId); fetch(ArticleDetailAPI,{ method:'POST', headers:{ 'Content-Type':'application/x-www-form-urlencoded', }, body:'postId='+postId, }) .then((response)=>response.json()) .then((responseJson)=>{ // console.warn(responseJson.result.postInfo.coverImgURL); this.setState({articleDetailData:responseJson}); // console.warn(responseJson.result.postInfo.contentHtml); }) .catch((error)=>{ console.error(error); }) .done(); } // componentWillMount(){ // this._panResponder = PanResponder.create({ // onPanResponderMove: (evt, gestureState) => { // The most recent move distance is gestureState.move{X,Y} // // The accumulated gesture distance since becoming responder is // // gestureState.d{x,y} // console.warn(evt,gestureState); // }, // }); // } componentDidMount(){ if(this.props.postId){ //请求帖子详情 this._requestArticleDetail(this.props.postId); } } componentWillUnmoont(){ clearInterval(); } _BackToArticleList(){ console.warn('帖子列表'); } render() { let defaultComponent = ArticleDetailView; let defaultName = 'ArticleList'; // console.warn(this.state.articleDetailData); if(!this.state.articleDetailData){ return ( <View style = {{flex:1,'justifyContent':'center'}}> <ActivityIndicator animating = {true} size = 'large'/> <Text style = {{textAlign:'center',color:'gray'}}>Loading...</Text> </View> ); } // console.warn(this.props.navigator.title); // console.warn(`title `+this.props.text); // console.warn(`postid `+this.props.postId); return ( <ArticleDetailView articleData = {this.state.articleDetailData.result} navigator = {this.props.navigator} tabbarHidden = {this.props.tabbarHidden}/> // <NavigatorIOS // initialRoute = {{ // component:ArticleDetailView, // title:'投资圈', // rightButtonTitle:'详情', // onRightButtonPress:()=>this._GoToArticleDetail(), // }} // style = {{flex:1}} // ></NavigatorIOS> ); } } const styles = StyleSheet.create({ container: { flex: 1, //子元素沿主轴的对齐方式 // justifyContent: 'center', //子元素沿着次轴的对齐方式 // alignItems: 'center', // backgroundColor: 'yellow', // '#FFFFFF', // overflow:'hidden', // paddingTop:20, // height:height, }, imageStyle:{ alignSelf:'center', // margin:10, width:width, height:200, }, titleText:{ // backgroundColor:'red', fontSize:20, height:25, }, }); // AppRegistry.registerComponent('Demo4', () => Demo4);
newclient/scripts/components/admin/detail-view/additional-review-panel/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ import styles from './style'; import React from 'react'; import {AdminActions} from '../../../../actions/admin-actions'; import {FileUpload} from '../../../file-upload'; import AutoSuggest from '../../../auto-suggest'; import Suggestion from '../reviewer-suggestion'; import AdditionalReviewer from '../additional-reviewer'; import { DISCLOSURE_STATUS } from '../../../../../../coi-constants'; const {SUBMITTED_FOR_APPROVAL, RESUBMITTED} = DISCLOSURE_STATUS; import classNames from 'classnames'; export default function AdditionalReviewPanel(props) { let additionalReview; if (props.reviewers.length > 0) { const reviewers = props.reviewers.map(reviewer => { return ( <AdditionalReviewer key={reviewer.userId} readOnly={props.readonly} id={reviewer.id} dates={reviewer.dates} name={reviewer.name} email={reviewer.email} active={reviewer.active == true} /> ); }); additionalReview = ( <div className={styles.reviewers}> <span className={styles.reviewerLabel}>Additional Reviewers</span> {reviewers} </div> ); } else { additionalReview = ( <div className={styles.noReviewers}> You have not assigned additional reviewers to this disclosure.<br /> Search for reviewers above to add here. </div> ); } let reviewerSearch; if ( [SUBMITTED_FOR_APPROVAL, RESUBMITTED].includes(props.statusCd) && props.displayAdditionalReviewers) { reviewerSearch = ( <div> <label style={{fontSize: '12px', paddingBottom: '5px', color: '#777'}}> SEARCH REVIEWERS </label> <AutoSuggest suggestion={Suggestion} endpoint={`/api/coi/reviewers/${props.disclosureId}/`} value={props.reviewerSearchValue} onSuggestionSelected={AdminActions.addAdditionalReviewer} className={styles.autoSuggest} inline={false} /> </div> ); } let additionalReviewers; if (props.displayAdditionalReviewers || props.reviewers.length > 0) { additionalReviewers = ( <div style={{paddingTop: 12, borderTop: '1px solid #777'}}> <div style={{paddingTop: 12, marginBottom: 15}}> <span className={styles.subLabel}>ADDITIONAL REVIEWERS</span> </div> {reviewerSearch} {additionalReview} </div> ); } return ( <div className={classNames(styles.container, props.className)}> <div style={{paddingBottom: 20}}> <span className={styles.close} onClick={AdminActions.hideAdditionalReviewPanel} > <i className="fa fa-times" style={{fontSize: 23}} /> CLOSE </span> <span className={styles.title}>ADDITIONAL REVIEW</span> </div> <div style={{paddingTop: 12, marginBottom: 25}}> <span className={styles.subLabel}>MANAGEMENT PLAN</span> </div> <FileUpload fileType='Management Plan' readonly={props.readonly} onDrop={AdminActions.addManagementPlan} delete={AdminActions.deleteManagementPlan} files={props.managementPlan} multiple={true} className={`${styles.override} ${styles.fileUploadStyles}`} > <div>Drag and drop or upload your management plan</div> <div style={{fontSize: 10, marginTop: 2}}> Acceptable Formats: .pdf, .png, .doc, .jpeg </div> </FileUpload> {additionalReviewers} </div> ); }
src/scenes/home/getInvolved/whyGive/whyGive.js
OperationCode/operationcode_frontend
import React from 'react'; import FontAwesomeIcon from '@fortawesome/react-fontawesome'; import faCheck from '@fortawesome/fontawesome-free-solid/faCheck'; import LinkButton from 'shared/components/linkButton/linkButton'; import Section from 'shared/components/section/section'; import styles from '../getInvolved.css'; const WhyGive = () => ( <Section title="Why give to Operation Code?" theme="white"> <div className={styles.wrapper}> <div className={styles.half}> <img src="https://s3.amazonaws.com/operationcode-assets/page-get_involved/benefit_dinner_2017.jpg" alt="Benefit Dinner 2017" className={styles.photo} /> </div> <div className={styles.half}> <ul className={styles.list}> <li className={styles.listItem}> <FontAwesomeIcon icon={faCheck} size="2x" /> <p className={styles.itemText}> To provide veterans, transitioning servicemembers, and military spouses with transformative educational experiences </p> </li> <li className={styles.listItem}> <FontAwesomeIcon icon={faCheck} size="2x" /> <p className={styles.itemText}> To advocate for more diversity and opportunity in the tech industry </p> </li> <li className={styles.listItem}> <FontAwesomeIcon icon={faCheck} size="2x" /> <p className={styles.itemText}> To enable our mission to reach more members of the military community </p> </li> <li className={styles.listItem}> <FontAwesomeIcon icon={faCheck} size="2x" /> <p className={styles.itemText}> Scholarship funding for comp sci education, industry certification </p> </li> <li className={styles.listItem}> <FontAwesomeIcon icon={faCheck} size="2x" /> <p className={styles.itemText}> Sending veterans to conferences and major tech industry events </p> </li> <li className={styles.listItem}> <FontAwesomeIcon icon={faCheck} size="2x" /> <p className={styles.itemText}> Building more tech communities near military installations </p> </li> </ul> </div> </div> <div className={styles.button}> <LinkButton text="Donate" theme="red" link="https://opencollective.com/operationcode#support" isExternal /> </div> </Section> ); export default WhyGive;
example/src/components/app.js
jerairrest/react-chartjs-2
import React from 'react'; import DoughnutExample from './doughnut'; import DynamicDoughnutExample from './dynamic-doughnut'; import PieExample from './pie'; import LineExample from './line'; import BarExample from './bar'; import HorizontalBarExample from './horizontalBar'; import RadarExample from './radar'; import PolarExample from './polar'; import BubbleExample from './bubble'; import ScatterExample from './scatter'; import MixedDataExample from './mix'; import RandomizedDataLineExample from './randomizedLine'; import CrazyDataLineExample from './crazyLine'; import LegendOptionsExample from './legend-options'; import LegendHandlersExample from './legend-handlers'; export default class App extends React.Component { render() { return ( <div> <hr /> <DoughnutExample /> <hr /> <DynamicDoughnutExample /> <hr /> <PieExample /> <hr /> <LineExample /> <hr /> <BarExample /> <hr /> <HorizontalBarExample /> <hr /> <RadarExample /> <hr /> <PolarExample /> <hr /> <BubbleExample /> <hr /> <ScatterExample /> <hr /> <MixedDataExample /> <hr /> <RandomizedDataLineExample /> <hr /> <CrazyDataLineExample /> <hr /> <LegendOptionsExample /> <hr /> <LegendHandlersExample /> </div> ); } }
webapp/app/components/DashboardByUser/Save/index.js
EIP-SAM/SAM-Solution-Node-js
// // Component save dashboard by user page // import React from 'react'; import { Panel, ButtonToolbar, Glyphicon } from 'react-bootstrap'; import SaveHistoryTable from 'containers/SaveHistory/Table'; import moment from 'moment'; import LinkContainerButton from 'components/Button'; import styles from './styles.css'; /* eslint-disable react/prefer-stateless-function */ export default class DashboardByUserSave extends React.Component { constructor(props) { super(props); this.state = { expanded: false, }; } componentDidMount() { const url = window.location.pathname.split('/'); const username = url[2]; const userId = url[3]; this.props.getHistorySavesByUserRequest(username, 5); this.props.listUsers([{ id: userId, name: username }]); } getHeaderPanel() { const icon = (this.state.expanded) ? 'minus-sign' : 'plus-sign'; const helpText = (this.state.expanded) ? '(click to hide)' : '(click to show)'; return ( <h5> <Glyphicon glyph={icon} /> {' Save '} <span className={styles.panelHelpText} onClick={() => this.setState({ expanded: !this.state.expanded })}> {helpText} </span> </h5> ); } handleClick() { this.props.dateSave(moment().format('DD/MM/YYYY')); this.props.dateDisabled(true); this.props.timeSave(moment().format('HH:mm')); this.props.timeDisabled(true); this.props.frequencySave('No Repeat'); this.props.frequencyDisabled(true); } render() { return ( <Panel header={this.getHeaderPanel()} collapsible bsStyle="primary"> <ButtonToolbar className={styles.saveButtons}> <LinkContainerButton buttonBsStyle="info" buttonText="Launch save" link="/create-save" onClick={() => this.handleClick()} /> <LinkContainerButton buttonBsStyle="info" buttonText="Program save" link="/create-save" /> </ButtonToolbar> <SaveHistoryTable /> </Panel> ); } } DashboardByUserSave.propTypes = { getHistorySavesByUserRequest: React.PropTypes.func, listUsers: React.PropTypes.func, dateSave: React.PropTypes.func, dateDisabled: React.PropTypes.func, timeSave: React.PropTypes.func, timeDisabled: React.PropTypes.func, frequencySave: React.PropTypes.func, frequencyDisabled: React.PropTypes.func, };
src/pages/about.js
nennes/nenn_es
import React from 'react' const AboutPage = () => ( <div> <h1>About me</h1> <section> I studied Industrial Management and then Computer Engineering, before coming to the UK. I currently work at eBay, where I help bring awesome web experiences to life. After work, I try to remain creative and on weekends I mentor at CodeYourFuture (check it out!) </section> </div> ) export default AboutPage
src/components/common/svg-icons/maps/directions-bus.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsDirectionsBus = (props) => ( <SvgIcon {...props}> <path d="M4 16c0 .88.39 1.67 1 2.22V20c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h8v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1.78c.61-.55 1-1.34 1-2.22V6c0-3.5-3.58-4-8-4s-8 .5-8 4v10zm3.5 1c-.83 0-1.5-.67-1.5-1.5S6.67 14 7.5 14s1.5.67 1.5 1.5S8.33 17 7.5 17zm9 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm1.5-6H6V6h12v5z"/> </SvgIcon> ); MapsDirectionsBus = pure(MapsDirectionsBus); MapsDirectionsBus.displayName = 'MapsDirectionsBus'; MapsDirectionsBus.muiName = 'SvgIcon'; export default MapsDirectionsBus;
client/modules/Post/__tests__/components/PostList.spec.js
jyothigundeti/sample-app
import React from 'react'; import test from 'ava'; import { shallow } from 'enzyme'; import PostList from '../../components/PostList'; const posts = [ { name: 'Prashant', title: 'Hello Mern', slug: 'hello-mern', cuid: 'f34gb2bh24b24b2', content: "All cats meow 'mern!'" }, { name: 'Mayank', title: 'Hi Mern', slug: 'hi-mern', cuid: 'f34gb2bh24b24b3', content: "All dogs bark 'mern!'" }, ]; test('renders the list', t => { const wrapper = shallow( <PostList posts={posts} handleShowPost={() => {}} handleDeletePost={() => {}} /> ); t.is(wrapper.find('PostListItem').length, 2); });
docs/src/app/components/pages/components/FlatButton/ExampleSimple.js
barakmitz/material-ui
import React from 'react'; import FlatButton from 'material-ui/FlatButton'; const FlatButtonExampleSimple = () => ( <div> <FlatButton label="Default" /> <FlatButton label="Primary" primary={true} /> <FlatButton label="Secondary" secondary={true} /> <FlatButton label="Disabled" disabled={true} /> </div> ); export default FlatButtonExampleSimple;
NavigationReactMobile/sample/isomorphic/Isomorphic.js
grahammendick/navigation
import React from 'react'; import {NavigationMotion} from 'navigation-react-mobile'; export default () => ( <NavigationMotion unmountedStyle={{opacity: 1, translate: 100}} mountedStyle={{opacity: 1, translate: 0}} crumbStyle={{opacity: 0, translate: -100}}> {({opacity, translate}, scene, key, active) => ( <div key={key} className="scene" style={{ opacity, transform: `translate(${translate}%)`, }}> {scene} </div> )} </NavigationMotion> );
test/test_helper.js
fab1o/YouTube-Viewer
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/server/router.js
junkycoder/obycejnaholka
import React from 'react'; import { match, RouterContext } from 'react-router' import render from './render'; import routes from '../routes'; export default function () { return (req, res) => match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { if (error) { res.status(500).send(error.message); return; } if (redirectLocation) { res.status(302, redirectLocation.pathname + redirectLocation.search); return; } if (renderProps) { const html = render(<RouterContext {...renderProps} />); res.status(200).send(html); return; } res.status(404).send('Not found'); }); }
src/svg-icons/editor/format-shapes.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatShapes = (props) => ( <SvgIcon {...props}> <path d="M23 7V1h-6v2H7V1H1v6h2v10H1v6h6v-2h10v2h6v-6h-2V7h2zM3 3h2v2H3V3zm2 18H3v-2h2v2zm12-2H7v-2H5V7h2V5h10v2h2v10h-2v2zm4 2h-2v-2h2v2zM19 5V3h2v2h-2zm-5.27 9h-3.49l-.73 2H7.89l3.4-9h1.4l3.41 9h-1.63l-.74-2zm-3.04-1.26h2.61L12 8.91l-1.31 3.83z"/> </SvgIcon> ); EditorFormatShapes = pure(EditorFormatShapes); EditorFormatShapes.displayName = 'EditorFormatShapes'; EditorFormatShapes.muiName = 'SvgIcon'; export default EditorFormatShapes;
admin/client/components/Forms/EditFormHeader.js
Tangcuyu/keystone
import React from 'react'; import ReactDOM from 'react-dom'; import Toolbar from '../Toolbar'; import { Button, FormIconField, FormInput, ResponsiveText } from 'elemental'; var Header = React.createClass({ displayName: 'EditFormHeader', propTypes: { data: React.PropTypes.object, list: React.PropTypes.object, toggleCreate: React.PropTypes.func, }, getInitialState () { return { searchString: '', }; }, toggleCreate (visible) { this.props.toggleCreate(visible); }, searchStringChanged (event) { this.setState({ searchString: event.target.value, }); }, handleEscapeKey (event) { const escapeKeyCode = 27; if (event.which === escapeKeyCode) { ReactDOM.findDOMNode(this.refs.searchField).blur(); } }, renderDrilldown () { return ( <Toolbar.Section left> {this.renderDrilldownItems()} {this.renderSearch()} </Toolbar.Section> ); }, renderDrilldownItems () { var list = this.props.list; var items = this.props.data.drilldown ? this.props.data.drilldown.items : []; var els = items.map((dd, i) => { var links = []; dd.items.forEach((el, i) => { links.push(<a key={'dd' + i} href={el.href} title={dd.list.singular}>{el.label}</a>); if (i < dd.items.length - 1) { links.push(<span key={'ds' + i} className="separator">,</span>); // eslint-disable-line comma-spacing } }); var more = dd.more ? <span>...</span> : ''; return ( <li key={`dd-${i}`}> {links} {more} </li> ); }); if (!els.length) { return ( <Button type="link" href={`${Keystone.adminPath}/${list.path}`}> <span className="octicon octicon-chevron-left" /> {list.plural} </Button> ); } else { // add the current list els.push( <li key="back"> <a type="link" href={`${Keystone.adminPath}/${list.path}`}>{list.plural}</a> </li> ); return <ul className="item-breadcrumbs" key="drilldown">{els}</ul>; } }, renderSearch () { var list = this.props.list; return ( <form action={`${Keystone.adminPath}/${list.path}`} className="EditForm__header__search"> <FormIconField iconPosition="left" iconColor="primary" iconKey="search" className="EditForm__header__search-field"> <FormInput ref="searchField" type="search" name="search" value={this.state.searchString} onChange={this.searchStringChanged} onKeyUp={this.handleEscapeKey} placeholder="Search" className="EditForm__header__search-input" /> </FormIconField> </form> ); }, renderInfo () { return ( <Toolbar.Section right> {this.renderCreateButton()} </Toolbar.Section> ); }, renderCreateButton () { if (this.props.list.nocreate) return null; var props = {}; if (this.props.list.autocreate) { props.href = '?new' + Keystone.csrf.query; } else { props.onClick = () => { this.toggleCreate(true); }; } return ( <Button type="success" {...props}> <span className="octicon octicon-plus" /> <ResponsiveText hiddenXS={`New ${this.props.list.singular}`} visibleXS="Create" /> </Button> ); }, render () { return ( <Toolbar> {this.renderDrilldown()} {this.renderInfo()} </Toolbar> ); }, }); module.exports = Header;
packages/containers/src/AppLoader/AppLoader.stories.js
Talend/ui
import React from 'react'; import { AppLoader as AppLoaderComponent } from '@talend/react-components'; import { Inject } from '@talend/react-cmf'; import AppLoader from '.'; const ICON = "url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNiAxNiI+Cgk8ZyBmaWxsPSJub25lIj4KCQk8cGF0aCBkPSJNMTYgOEE4IDggMCAxIDEgMCA4YTggOCAwIDAgMSAxNiAwIiBjbGFzcz0idGktZGF0YXN0cmVhbXMtcG9zaXRpdmUtYmciIGZpbGw9IiM1ZDg4YWEiLz4KCQk8ZyBjbGFzcz0idGktZGF0YXN0cmVhbXMtcG9zaXRpdmUtbG9nbyIgZmlsbD0iI0ZGRiI+CgkJCTxwYXRoIGQ9Ik05LjI4OCAxMS40NTdjLS41NDMgMC0xLjA3OC0uMjYtMS41ODktLjc3MS0uNDAyLS40MDEtLjc5LS41ODUtMS4xNTYtLjU0NS0uNTY5LjA1OS0uOTU2LjYzNi0uOTYuNjQyYS4zNzMuMzczIDAgMCAxLS41MTYuMTEyLjM3NS4zNzUgMCAwIDEtLjExMi0uNTE3Yy4wMjQtLjAzNi41OC0uODgyIDEuNTEtLjk4MS42LS4wNjMgMS4xOTMuMTkyIDEuNzYyLjc2LjQuNDAyLjc5LjU4NCAxLjE2LjU0OC41ODItLjA2Ljk4NC0uNjQyLjk4Ny0uNjQ3YS4zNzUuMzc1IDAgMCAxIC41MTgtLjEwNi4zNzUuMzc1IDAgMCAxIC4xMDUuNTE5Yy0uMDI0LjAzNS0uNTk2Ljg4Mi0xLjUzNi45NzdhMS42NyAxLjY3IDAgMCAxLS4xNzMuMDA5bTAtMi41MjJjLS41NDMgMC0xLjA3OC0uMjU4LTEuNTg5LS43Ny0uNC0uNC0uNzg2LS41ODQtMS4xNTItLjU0Ni0uNTcyLjA1Ny0uOTYuNjM4LS45NjUuNjQ0YS4zNzQuMzc0IDAgMCAxLS42MjctLjQwNmMuMDI0LS4wMzYuNTgtLjg4MiAxLjUxLS45ODIuNi0uMDYzIDEuMTkzLjE5MyAxLjc2Mi43NjEuNC40MDEuNzkuNTg0IDEuMTYuNTQ3LjU4Mi0uMDU5Ljk4NC0uNjQyLjk4Ny0uNjQ3YS4zNzQuMzc0IDAgMCAxIC42MjMuNDEzYy0uMDI0LjAzNi0uNTk2Ljg4My0xLjUzNi45NzdhMS42NyAxLjY3IDAgMCAxLS4xNzMuMDFtMC0yLjUxMmMtLjU0MyAwLTEuMDc4LS4yNi0xLjU4OS0uNzcxLS40MDItLjQwMS0uNzktLjU4NS0xLjE1Ni0uNTQ2LS41NjkuMDYtLjk1Ni42MzctLjk2LjY0M2EuMzc0LjM3NCAwIDAgMS0uNjI4LS40MDVjLjAyNC0uMDM2LjU4LS44ODIgMS41MS0uOTgxLjYtLjA2NCAxLjE5My4xOTIgMS43NjIuNzYuNC40Ljc5LjU4NSAxLjE2LjU0OC41ODItLjA2Ljk4NC0uNjQyLjk4Ny0uNjQ3YS4zNzQuMzc0IDAgMCAxIC42MjMuNDEyYy0uMDI0LjAzNi0uNTk2Ljg4My0xLjUzNi45NzhhMS42NyAxLjY3IDAgMCAxLS4xNzMuMDA5Ii8+CgkJCTxwYXRoIGQ9Ik0yLjEwMyA4LjcwM0EuNzA1LjcwNSAwIDAgMCAyLjE5NiA3LjRhNS44MjQgNS44MjQgMCAwIDEgNC4wMTEtNC45OTljMi44NzYtLjkzNCA2LjAyNi41MTUgNy4xOTIgMy4zMDJsLS43MzQuMjM4IDEuMzc3Ljg2Ni42MDctMS41MS0uNzQuMjRDMTIuNjUgMi40NjYgOS4yMDEuODY1IDYuMDQzIDEuODkyQTYuMzU4IDYuMzU4IDAgMCAwIDEuNjYgNy4zNjVhLjcwNS43MDUgMCAwIDAgLjQ0MiAxLjMzOG0xMi42NzctLjk3YS43MDYuNzA2IDAgMCAwLTEuMzQyLjQzNi43MDIuNzAyIDAgMCAwIC4zNzIuNDE4IDUuODQgNS44NCAwIDAgMS00LjAwMyA0LjkyNGMtMi44MS45MTItNS45MzQtLjQ4Mi03LjEzNy0zLjE3N2wuNzE0LS4yMzMtMS4zNzctLjg2NC0uNjA4IDEuNTEuNzU5LS4yNDdjMS4yOTggMi45OCA0LjcyMiA0LjUyNSA3LjgxNCAzLjUyYTYuMzc2IDYuMzc2IDAgMCAwIDQuMzczLTUuNDA2LjcwNi43MDYgMCAwIDAgLjQzNS0uODgiLz4KCQk8L2c+Cgk8L2c+Cjwvc3ZnPgo=')"; const header = { component: 'HeaderBar', brand: { label: 'Example app' }, }; const hasCollections = ['photos1', 'photos2', 'photos3']; const steps = [ { actionCreators: ['http:get:photos1'] }, { sagas: ['saga:get:photos3'] }, { waitFor: ['photos1', 'photos3'] }, { actionCreators: ['http:get:photos2'] }, ]; export default { title: 'AppLoader', }; export const Default = () => ( <div> <style>{AppLoaderComponent.getLoaderStyle(ICON)}</style> <AppLoader hasCollections={hasCollections} steps={steps} saga="appLoaderSaga"> Loaded content </AppLoader> </div> ); export const Renderer = () => { const renderer = loaderElement => ( <Inject component="Layout" mode="OneColumn" header={header} content={loaderElement} /> ); return ( <div> <style>{AppLoaderComponent.getLoaderStyle(ICON)}</style> <AppLoader hasCollections={hasCollections} steps={steps} saga="appLoaderSaga" renderer={renderer} > Loaded content </AppLoader> </div> ); };
src/components/MembershipsWithData.js
OpenCollective/frontend
import React from 'react'; import PropTypes from 'prop-types'; import Error from './Error'; import withIntl from '../lib/withIntl'; import { graphql } from 'react-apollo'; import gql from 'graphql-tag'; import Membership from './Membership'; import { Button } from 'react-bootstrap'; import { FormattedMessage } from 'react-intl'; const MEMBERSHIPS_PER_PAGE = 10; class MembershipsWithData extends React.Component { static propTypes = { memberCollectiveSlug: PropTypes.string, orderBy: PropTypes.string, limit: PropTypes.number, onChange: PropTypes.func, LoggedInUser: PropTypes.object, }; constructor(props) { super(props); this.fetchMore = this.fetchMore.bind(this); this.refetch = this.refetch.bind(this); this.onChange = this.onChange.bind(this); this.state = { role: null, loading: false, }; } onChange() { const { onChange } = this.props; onChange && this.node && onChange({ height: this.node.offsetHeight }); } componentDidMount() { this.onChange(); } fetchMore(e) { e.target.blur(); this.setState({ loading: true }); this.props.fetchMore().then(() => { this.setState({ loading: false }); this.onChange(); }); } refetch(role) { this.setState({ role }); this.props.refetch({ role }); } render() { const { data, LoggedInUser } = this.props; if (data.error) { console.error('graphql error>>>', data.error.message); return <Error message="GraphQL error" />; } if (!data.allMembers) { return <div />; } const memberships = [...data.allMembers]; if (memberships.length === 0) { return <div />; } const limit = this.props.limit || MEMBERSHIPS_PER_PAGE * 2; return ( <div className="MembersContainer" ref={node => (this.node = node)}> <style jsx> {` :global(.loadMoreBtn) { margin: 1rem; text-align: center; } .Collectives { display: flex; flex-wrap: wrap; flex-direction: row; justify-content: center; overflow: hidden; margin: 1rem 0; } `} </style> <div className="Collectives cardsList"> {memberships.map(membership => ( <Membership key={membership.id} membership={membership} LoggedInUser={LoggedInUser} /> ))} </div> {memberships.length % 10 === 0 && memberships.length >= limit && ( <div className="loadMoreBtn"> <Button bsStyle="default" onClick={this.fetchMore}> {this.state.loading && <FormattedMessage id="loading" defaultMessage="loading" />} {!this.state.loading && <FormattedMessage id="loadMore" defaultMessage="load more" />} </Button> </div> )} </div> ); } } const getMembershipsQuery = gql` query Members($memberCollectiveSlug: String, $role: String, $limit: Int, $offset: Int, $orderBy: String) { allMembers( memberCollectiveSlug: $memberCollectiveSlug role: $role limit: $limit offset: $offset orderBy: $orderBy ) { id role createdAt stats { totalDonations } tier { id name } collective { id type name currency description slug image backgroundImage stats { id backers { all } yearlyBudget } } } } `; export const addMembershipsData = graphql(getMembershipsQuery, { options(props) { return { variables: { memberCollectiveSlug: props.memberCollectiveSlug, offset: 0, role: props.role, orderBy: props.orderBy || 'totalDonations', limit: props.limit || MEMBERSHIPS_PER_PAGE * 2, }, }; }, props: ({ data }) => ({ data, fetchMore: () => { return data.fetchMore({ variables: { offset: data.allMembers.length, limit: MEMBERSHIPS_PER_PAGE, }, updateQuery: (previousResult, { fetchMoreResult }) => { if (!fetchMoreResult) { return previousResult; } return Object.assign({}, previousResult, { // Append the new posts results to the old one allMembers: [...previousResult.allMembers, ...fetchMoreResult.allMembers], }); }, }); }, }), }); export default addMembershipsData(withIntl(MembershipsWithData));
src/List/ListItemTextSecondary.js
kradio3/react-mdc-web
import PropTypes from 'prop-types'; import React from 'react'; import classnames from 'classnames'; const propTypes = { className: PropTypes.string, }; const ListItemTextSecondary = ({ className, ...otherProps }) => ( <span className={classnames('mdc-list-item__text__secondary', className)} {...otherProps} /> ); ListItemTextSecondary.propTypes = propTypes; export default ListItemTextSecondary;
admin/client/App/screens/Home/components/Lists.js
linhanyang/keystone
import React from 'react'; import _ from 'lodash'; import { connect } from 'react-redux'; import { plural } from '../../../../utils/string'; import ListTile from './ListTile'; export class Lists extends React.Component { render () { return ( <div className="dashboard-group__lists"> {_.map(this.props.lists, (list, key) => { // If an object is passed in the key is the index, // if an array is passed in the key is at list.key const listKey = list.key || key; const href = list.external ? list.path : `${Keystone.adminPath}/${list.path}`; const listData = this.props.listsData[list.path]; const isNoCreate = listData ? listData.nocreate : false; return ( <ListTile key={list.path} path={list.path} label={list.label} hideCreateButton={isNoCreate} href={href} count={plural(this.props.counts[listKey], '* Item', '* Items')} spinner={this.props.spinner} /> ); })} </div> ); } } Lists.propTypes = { counts: React.PropTypes.object.isRequired, lists: React.PropTypes.oneOfType([ React.PropTypes.array, React.PropTypes.object, ]).isRequired, spinner: React.PropTypes.node, }; export default connect((state) => { return { listsData: state.lists.data, }; })(Lists);
js/views/memoir/CreateMemoir.js
n8e/memoirs
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Relay from 'react-relay'; import { Grid, Row, Col, Alert, FormGroup, Button, ControlLabel, FormControl } from 'react-bootstrap'; import { hashHistory } from 'react-router'; import global from 'global'; import CreateMemoirMutation from '../../mutations/CreateMemoirMutation'; class CreateMemoir extends Component { constructor(props) { super(props); this.state = { fail: 'none', success: 'none', memoir: { title: null, content: null, }, }; this.handleMemoirSave = this.handleMemoirSave.bind(this); this.onSuccess = this.onSuccess.bind(this); this.onFailure = this.onFailure.bind(this); this.handleChange = this.handleChange.bind(this); } onSuccess() { this.setState({ success: 'block' }); hashHistory.push('/welcome'); } onFailure() { this.setState({ fail: 'block' }); } handleChange(e) { const { name, value } = e.target; this.setState({ memoir: Object.assign({}, this.state.memoir, { [name]: value }) }); } handleMemoirSave() { console.log('GLOBAL - CREATE MEMOIR', global); const token = global.token; const onSuccess = this.onSuccess; const onFailure = this.onFailure; Relay.Store.commitUpdate(new CreateMemoirMutation({ title: this.state.memoir.title, content: this.state.memoir.content, token, viewer: this.props.viewer, }), { onFailure, onSuccess }); } render() { return ( <Grid> <Row className="page-body"> <Alert bsStyle="danger" ref={(failAlert) => { this.failAlert = failAlert; }} style={{ display: this.state.fail }} > <strong>Error!</strong> Failed to save </Alert> <Alert bsStyle="success" ref={(successAlert) => { this.successAlert = successAlert; }} style={{ display: this.state.success }} > <strong>Memoir created successfully!</strong> </Alert> <div> <FormGroup controlId={'formHorizontalTitle'}> <Col componentClass={ControlLabel} sm={2}> Title </Col> <Col sm={10}> <FormControl type="text" name="title" placeholder="Title" onChange={this.handleChange} /> </Col> </FormGroup> <FormGroup controlId="formHorizontalContent"> <Col sm={2}> <ControlLabel>Content</ControlLabel> </Col> <Col sm={10}> <FormControl name="content" componentClass="textarea" placeholder="Content" onChange={this.handleChange} /> </Col> </FormGroup> <FormGroup> <Col smOffset={2} sm={10}> <Button onClick={this.handleMemoirSave}> Save </Button> </Col> </FormGroup> </div> </Row> </Grid> ); } } CreateMemoir.propTypes = { viewer: PropTypes.shape({ memoir: PropTypes.shape({ id: PropTypes.string, }), }).isRequired, }; export default Relay.createContainer(CreateMemoir, { fragments: { viewer: () => Relay.QL` fragment on User { ${CreateMemoirMutation.getFragment('viewer')}, memoir { id } } `, }, });
app/components/0_Global/Navigation/Navigation.js
shug0/Awesomidi
// CORE import React from 'react'; import AppBar from 'material-ui/AppBar'; import FlatButton from 'material-ui/FlatButton'; import { green200, red500 } from 'material-ui/styles/colors'; const Navigation = (props) => { const statusColor = props.executeBindings ? green200 : red500; const statusText = props.executeBindings ? 'Bindings activated' : 'Bindings desactivated'; return ( <AppBar title={props.title} titleStyle={{fontWeight: 300}} iconElementRight={ <FlatButton icon={<div style={{ height: '10px', width: '10px', background: statusColor, display: 'inline-block', borderRadius: '50%' }}/>} label={statusText} style={{ fontSize: '0.7em' }} disableTouchRipple onTouchTap={ props.executeBindings ? props.stopExecuteBindings : props.startExecuteBindings } /> } /> ); }; export default Navigation;
webpack/ForemanTasks/Components/TasksDashboard/Components/TasksCardsGrid/Components/TasksDonutChart/TasksDonutChart.stories.js
theforeman/foreman-tasks
import React from 'react'; import { number, text, select, action } from '@theforeman/stories'; import { TASKS_DONUT_CHART_FOCUSED_ON_OPTIONS_ARRAY } from './TasksDonutChartConstants'; import TasksDonutChart from './TasksDonutChart'; export default { title: 'TasksDashboard/TasksCardsGrid/Charts/TasksDonutChart', component: TasksDonutChart, }; export const Basic = () => ( <TasksDonutChart last={number('last', 3)} older={number('older', 5)} time={text('time', '24h')} focusedOn={select( 'focusedOn', TASKS_DONUT_CHART_FOCUSED_ON_OPTIONS_ARRAY, TasksDonutChart.defaultProps.focusedOn )} onTotalClick={action('onTotalClick')} onLastClick={action('onLastClick')} onOlderClick={action('onOlderClick')} /> );
src/index.js
aubrian-halili/shout-out
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware, compose } from 'redux'; import thunk from 'redux-thunk'; import { browserHistory } from 'react-router'; import * as storage from 'redux-storage'; import createEngine from 'redux-storage-engine-localstorage'; import reducers from './reducers'; import Root from './components/Root'; import css from './styles/app.css'; // Added comments again const engine = createEngine('YjGQoDeJHdAm'); const storageMiddleware = storage.createMiddleware(engine); const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const store = createStore( storage.reducer(reducers), composeEnhancers( applyMiddleware(thunk, storageMiddleware), ), ); const load = storage.createLoader(engine); load(store).then(() => { render( <Provider store={store}> <Root history={browserHistory} /> </Provider>, document.getElementById('app'), ); });
src/Buttons.js
gocreating/react-tocas
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Box from './Box'; class Buttons extends Component { render() { let { fluid, vertical, separated, relaxed, stackable, className, ...rest } = this.props; let cx = classNames( { fluid, vertical, separated, relaxed, stackable, }, 'buttons', className ); return ( <Box ts className={cx} {...rest} /> ); } } Buttons.displayName = 'Buttons'; Buttons.propTypes = { fluid: PropTypes.bool, vertical: PropTypes.bool, separated: PropTypes.bool, relaxed: PropTypes.bool, stackable: PropTypes.bool, }; export default Buttons;
js/jqwidgets/demos/react/app/datatable/columnshierarchy/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxDataTable from '../../../jqwidgets-react/react_jqxdatatable.js'; class App extends React.Component { render() { let source = { dataType: 'xml', dataFields: [ { name: 'SupplierName', type: 'string' }, { name: 'Quantity', type: 'number' }, { name: 'OrderDate', type: 'date' }, { name: 'OrderAddress', type: 'string' }, { name: 'Freight', type: 'number' }, { name: 'Price', type: 'number' }, { name: 'City', type: 'string' }, { name: 'ProductName', type: 'string' }, { name: 'Address', type: 'string' } ], url: '../sampledata/orderdetailsextended.xml', root: 'DATA', record: 'ROW' }; let dataAdapter = new $.jqx.dataAdapter(source); let columns = [ { text: 'Supplier Name', cellsAlign: 'center', align: 'center', dataField: 'SupplierName', width: 200 }, { text: 'Name', columngroup: 'ProductDetails', cellsAlign: 'center', align: 'center', dataField: 'ProductName', width: 200 }, { text: 'Quantity', columngroup: 'ProductDetails', dataField: 'Quantity', cellsFormat: 'd', cellsAlign: 'center', align: 'center', width: 80 }, { text: 'Freight', columngroup: 'OrderDetails', dataField: 'Freight', cellsFormat: 'd', cellsAlign: 'center', align: 'center', width: 100 }, { text: 'Order Date', columngroup: 'OrderDetails', cellsAlign: 'center', align: 'center', cellsFormat: 'd', dataField: 'OrderDate', width: 100 }, { text: 'Order Address', columngroup: 'OrderDetails', cellsAlign: 'center', align: 'center', dataField: 'OrderAddress', width: 100 }, { text: 'Price', columngroup: 'ProductDetails', dataField: 'Price', cellsFormat: 'c2', align: 'center', cellsAlign: 'center', width: 70 }, { text: 'Address', columngroup: 'Location', cellsAlign: 'center', align: 'center', dataField: 'Address', width: 120 }, { text: 'City', columngroup: 'Location', cellsAlign: 'center', align: 'center', dataField: 'City', width: 80 } ]; let columnGroups = [ { text: 'Product Details', align: 'center', name: 'ProductDetails' }, { text: 'Order Details', parentGroup: 'ProductDetails', align: 'center', name: 'OrderDetails' }, { text: 'Location', align: 'center', name: 'Location' } ]; return ( <JqxDataTable width={850} height={400} source={dataAdapter} altRows={true} pageable={true} columnsResize={true} columns={columns} columnGroups={columnGroups} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/main/Controls.js
snaheth/pileup.js
/** * Controls for zooming to particular ranges of the genome. * @flow */ 'use strict'; import type {PartialGenomeRange} from './types'; import React from 'react'; import _ from 'underscore'; import utils from './utils'; import Interval from './Interval'; type Props = { range: ?GenomeRange; contigList: string[]; onChange: (newRange: GenomeRange)=>void; }; class Controls extends React.Component { props: Props; state: void; // no state constructor(props: Object) { super(props); } makeRange(): GenomeRange { return { contig: this.refs.contig.value, start: Number(this.refs.start.value), stop: Number(this.refs.stop.value) }; } completeRange(range: ?PartialGenomeRange): GenomeRange { range = range || {}; if (range.start && range.stop === undefined) { // Construct a range centered around a value. This matches IGV. range.stop = range.start + 20; range.start -= 20; } if (range.contig) { // There are major performance issues with having a 'chr' mismatch in the // global location object. const contig = range.contig; var altContig = _.find(this.props.contigList, ref => utils.isChrMatch(contig, ref)); if (altContig) range.contig = altContig; } return (_.extend({}, this.props.range, range) : any); } handleContigChange(e: SyntheticEvent) { this.props.onChange(this.completeRange({contig: this.refs.contig.value})); } handleFormSubmit(e: SyntheticEvent) { e.preventDefault(); var range = this.completeRange(utils.parseRange(this.refs.position.value)); this.props.onChange(range); } // Sets the values of the input elements to match `props.range`. updateRangeUI() { const r = this.props.range; if (!r) return; this.refs.position.value = utils.formatInterval(new Interval(r.start, r.stop)); if (this.props.contigList) { var contigIdx = this.props.contigList.indexOf(r.contig); this.refs.contig.selectedIndex = contigIdx; } } zoomIn(e: any) { e.preventDefault(); this.zoomByFactor(0.5); } zoomOut(e: any) { e.preventDefault(); this.zoomByFactor(2.0); } zoomByFactor(factor: number) { var r = this.props.range; if (!r) return; var iv = utils.scaleRange(new Interval(r.start, r.stop), factor); this.props.onChange({ contig: r.contig, start: iv.start, stop: iv.stop }); } render(): any { var contigOptions = this.props.contigList ? this.props.contigList.map((contig, i) => <option key={i}>{contig}</option>) : null; // Note: input values are set in componentDidUpdate. return ( <form className='controls' onSubmit={this.handleFormSubmit.bind(this)}> <select ref='contig' onChange={this.handleContigChange.bind(this)}> {contigOptions} </select>{' '} <input ref='position' type='text' />{' '} <button className='btn-submit' onClick={this.handleFormSubmit.bind(this)}>Go</button>{' '} <div className='zoom-controls'> <button className='btn-zoom-out' onClick={this.zoomOut.bind(this)}></button>{' '} <button className='btn-zoom-in' onClick={this.zoomIn.bind(this)}></button> </div> </form> ); } componentDidUpdate(prevProps: Object) { if (!_.isEqual(prevProps.range, this.props.range)) { this.updateRangeUI(); } } componentDidMount() { this.updateRangeUI(); } } module.exports = Controls;
client/src/views/Letter.js
MissUchiha/CANX
import React from 'react' import Footer from './Footer' import Modal from 'react-modal' import {modalStyle} from '../style/modalStyle.js' import DrawApi from '../api/DrawApi' import ErrorModal from './ErrorModal' class Letter extends React.Component { constructor(...args) { super(...args) this.openModal = this.openModal.bind(this) this.closeModal = this.closeModal.bind(this) this.clearCanvas = this.clearCanvas.bind(this) this.saveCanvas = this.saveCanvas.bind(this) this.handleOnMouseUp = this.handleOnMouseUp.bind(this) this.handleOnMouseDown = this.handleOnMouseDown.bind(this) this.handleOnMouseMove = this.handleOnMouseMove.bind(this) this.handleOnTouchEnd = this.handleOnTouchEnd.bind(this) this.handleOnTouchStart = this.handleOnTouchStart.bind(this) this.handleOnTouchMove = this.handleOnTouchMove.bind(this) this.onUp = this.onUp.bind(this) this.onDown = this.onDown.bind(this) this.onMove = this.onMove.bind(this) this.minXFromStrokes = this.minXFromStrokes.bind(this) this.minYFromStrokes = this.minYFromStrokes.bind(this) this.init = this.init.bind(this) this.initState = this.initState.bind(this) this.initCanvasConf = this.initCanvasConf.bind(this) this.initVar = this.initVar.bind(this) this.init() } init() { this.initState() this.initCanvasConf() this.initVar() } initState() { this.state = { openDeleteModal: false, openSaveModal: false, openErrorModal: false, errorTitle: "", strokes: [] } } initCanvasConf() { this.ctx = null this.canvas = null this.rect = null } initVar() { this.points = [] this.lastPoint = null this.startTime = null } openModal(opened) { return () => this.setState({[opened] : true}) } closeModal() { this.setState({openDeleteModal: false, openSaveModal: false, openErrorModal: false}) } componentWillMount() { document.getElementsByTagName('body')[0].style.overflow = 'hidden' } componentWillUnmount() { document.getElementsByTagName('body')[0].style.overflow = 'scroll' document.removeEventListener('onmouseup', this.handleOnMouseUp, false) } componentDidMount() { document.addEventListener('onmouseup', this.handleOnMouseUp, false) this.canvas = document.getElementById('canvas') this.rect = this.canvas.getBoundingClientRect() this.ctx = this.canvas.getContext('2d') const style = window.getComputedStyle(this.canvas) this.ctx.canvas.width = parseInt(style.getPropertyValue('width'), 10) this.ctx.canvas.height = parseInt(style.getPropertyValue('height'), 10) this.ctx.lineWidth = 10 // this.ctx.shadowBlur = 1; // this.ctx.shadowColor = "#cccccc"; this.ctx.lineJoin = 'round' this.ctx.lineCap = 'round' this.ctx.strokeStyle = '#cccccc' } midPoint(p1, p2) { return { x: p1.x + (p2.x - p1.x) / 2, y: p1.y + (p2.y - p1.y) / 2 } } currentPoint(x, y) { return { x: Math.round((x-this.rect.left)/(this.rect.right-this.rect.left)*this.canvas.width), y: Math.round((y-this.rect.top)/(this.rect.bottom-this.rect.top)*this.canvas.height), time: (new Date()).getTime() } } onDown(x,y) { const current = this.currentPoint(x, y) this.points.push(current) this.lastPoint = current this.isDrawing = true this.startTime = (new Date()).getTime() this.ctx.beginPath() this.ctx.arc(current.x, current.y, 1, 0, 2 * Math.PI, true) this.ctx.stroke() this.ctx.beginPath() this.ctx.moveTo(current.x, current.y) } onUp() { const newStrokes = { points: this.points, startTime: this.startTime, endTime: (new Date()).getTime() } this.isDrawing = false this.points = [] this.lastPoint = null this.setState({ strokes: [ ...this.state.strokes, newStrokes] }) } onMove(x, y) { const current = this.currentPoint(x, y) const midPoint = this.midPoint(this.lastPoint, current) this.ctx.quadraticCurveTo(this.lastPoint.x, this.lastPoint.y, midPoint.x, midPoint.y) this.ctx.stroke() this.points.push(current) this.lastPoint = current } handleOnMouseDown(e) { this.onDown(e.clientX, e.clientY) } handleOnMouseMove(e) { if (!this.isDrawing) return this.onMove(e.clientX, e.clientY) } handleOnMouseUp() { this.onUp() } handleOnTouchStart(e) { if(e.touches) if(e.touches.length === 1) this.onDown(e.touches[0].pageX,e.touches[0].pageY) } handleOnTouchMove(e) { if(!this.isDrawing) return if(e.touches) if(e.touches.length === 1) this.onMove(e.touches[0].pageX,e.touches[0].pageY) } handleOnTouchEnd() { this.onUp() } clearCanvas() { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height) this.initState() this.initVar() this.closeModal() } minXPoint(points) { return points.reduce((prevPoint, currPoint) => { return (prevPoint.x < currPoint.x) ? prevPoint : currPoint }, points[0]) } minYPoint(points) { return points.reduce((prevPoint, currPoint) => { return (prevPoint.y < currPoint.y) ? prevPoint : currPoint }, points[0]) } minXFromStrokes(strokes) { const minXStroke= strokes.reduce((prevStroke, currStroke) => { const minPrevPointX = this.minXPoint(prevStroke.points) const minCurrPointX = this.minXPoint(currStroke.points) return { points : [ (minPrevPointX.x < minCurrPointX.x) ? minPrevPointX : minCurrPointX ]} }, strokes[0]) return minXStroke.points[0].x } minYFromStrokes(strokes) { const minYStroke= strokes.reduce((prevStroke, currStroke) => { const minPrevPointY = this.minYPoint(prevStroke.points) const minCurrPointY = this.minYPoint(currStroke.points) return { points : [ (minPrevPointY.y < minCurrPointY.y) ? minPrevPointY : minCurrPointY ]} }, strokes[0]) return minYStroke.points[0].y } // TODO: refactor and sub first stroke start time from time in each point transformStrokes() { const maxY = this.canvas.width const rotatedStrokes = this.state.strokes.map((stroke) => { const transformedPoints = stroke.points.map((point) => { return Object.assign(point, { y: maxY - point.y}) }) return Object.assign(stroke, {points: transformedPoints}) }) const minX = this.minXFromStrokes(rotatedStrokes) const minY = this.minYFromStrokes(rotatedStrokes) return this.state.strokes.map((stroke) => { const transformedPoints = stroke.points.map((point) => { return Object.assign(point, {x: point.x-minX, y: point.y - minY}) }) return Object.assign(stroke, {points: transformedPoints}) }) } saveCanvas() { const transformedStrokes = this.transformStrokes() const capitalizedCategory = this.props.args.title.charAt(0).toUpperCase() + this.props.args.title.slice(1) DrawApi.postDraw({letter: this.props.args.letter, category: capitalizedCategory, content: JSON.stringify(transformedStrokes), uid: this.props.args.id }).catch(err => this.openModal('openErrorModal')) this.clearCanvas() this.closeModal() } render() { const argsFoot = {left: "/categories/"+this.props.args.title+"/letters/"+this.props.args.before, right: "/categories/"+this.props.args.title+"/letters/"+this.props.args.after, onClick: this.clearCanvas} return ( <div className='letter-page'> <h1 className='letter-h1'> {this.props.args.letter} </h1> <canvas id='canvas' className='letter-canvas' onMouseDown={this.handleOnMouseDown} onMouseUp={this.handleOnMouseUp} onMouseMove={this.handleOnMouseMove} onTouchStart={this.handleOnTouchStart} onTouchEnd={this.handleOnTouchEnd} onTouchMove={this.handleOnTouchMove} ></canvas> <div className='letter-btn-left' onClick={this.openModal("openDeleteModal")} > </div> <div className='letter-btn-right' onClick={this.openModal("openSaveModal")} > </div> <Modal isOpen={this.state.openDeleteModal} onRequestClose={this.closeModal} contentLabel="Delete" shouldCloseOnOverlayClick={true} style={modalStyle} > <h2> Are you sure? </h2> <button className='modal-yes modal-trash' type='button' onTouchStart={this.clearCanvas} onClick={this.clearCanvas}> </button> <button className='modal-no modal-close' type='button' value='No' onTouchStart={this.closeModal} onClick={this.closeModal}> </button> </Modal> <Modal isOpen={this.state.openSaveModal} onRequestClose={this.closeModal} contentLabel="Save" shouldCloseOnOverlayClick={true} style={modalStyle} > <h2> Are you sure? </h2> <button className='modal-yes modal-check' type='button' onTouchStart={this.saveCanvas} onClick={this.saveCanvas}> </button> <button className='modal-no modal-close' type='button' value='No' onTouchStart={this.closeModal} onClick={this.closeModal}> </button> </Modal> <ErrorModal args={{title: this.state.errorTitle, closeModal: this.closeModal, isOpen: this.state.openErrorModal}} /> <div className='footer-back'></div> <Footer args={argsFoot}/> </div> ) } } export default Letter
src/client/todos/tocheck.react.js
jaeh/este
import Component from '../components/component.react'; import React from 'react'; import {FormattedHTMLMessage} from 'react-intl'; import {Link} from 'react-router'; export default class ToCheck extends Component { static propTypes = { msg: React.PropTypes.object.isRequired } render() { const {msg} = this.props; return ( <div className="tocheck"> <h3>{msg.header}</h3> <ul> {msg.itemListHtml.map(item => <li key={item.key}> <FormattedHTMLMessage message={item.txt} /> </li> )} <li> {msg.isomorphicPage}{' '} <Link to="/this-is-not-the-web-page-you-are-looking-for">404</Link>. </li> <li> {msg.andMuchMore} </li> </ul> </div> ); } }
src/components/LandingPage.js
partneran/partneran
import React, { Component } from 'react'; import Intro from './Intro'; import ModalVideo from './ModalVideo'; import PopularIdea from './Category/PopularIdea'; import LatestIdea from './Category/LatestIdea'; // import RecommendedIdea from './Category/RecommendedIdea'; import Marketing from './Marketing' import Footer from './Footer/Footer'; import { loadIdeas } from '../actions/idea' import { bindActionCreators } from 'redux' import { connect } from 'react-redux' class LandingPage extends Component { componentDidMount() { this.props.loadIdeas() } render() { return ( <div className="landing-page"> <div className="wrapper"> <Intro /> <ModalVideo /> <div className="main"> <PopularIdea /> <LatestIdea /> <Marketing /> <Footer /> </div> </div> </div> ) } } function mapDispatchToProps(dispatch) { return { loadIdeas: bindActionCreators(loadIdeas, dispatch) } } const mapStateToProps = (state) => { return { ideas: state.ideas } } export default connect(mapStateToProps, mapDispatchToProps)(LandingPage)
app/app/common/components/modal.js
inquisive/simpledocs
import React from 'react'; import Dialog from 'material-ui/lib/dialog'; import FlatButton from 'material-ui/lib/flat-button'; import RaisedButton from 'material-ui/lib/raised-button'; export default class DialogExampleModal extends React.Component { constructor(props) { super(props); this.state = { open: false, }; } handleOpen = () => { this.setState({open: true}); } handleClose = () => { this.setState({open: false}); } render() { const actions = [ <FlatButton label="Cancel" secondary={true} onTouchTap={this.handleClose} />, <FlatButton label="Submit" primary={true} disabled={true} onTouchTap={this.handleClose} />, ]; return ( <div> <RaisedButton label="Modal Dialog" onTouchTap={this.handleOpen} /> <Dialog title="Dialog With Actions" actions={actions} modal={true} open={this.state.open}> Only actions can close this dialog. </Dialog> </div> ); } }
client/components/Dynamic/Containers/DashboardPage.js
Treeeater/expresshome
import React from 'react'; import PropTypes from 'prop-types'; import { Redirect } from 'react-router-dom'; import { Dashboard } from '../AuthUI/Dashboard'; export class DashboardPage extends React.Component { /** * Render the component. */ render() { return (<Dashboard userEmail={this.context.userEmail} userName={this.context.userName} />); } } DashboardPage.contextTypes = { userEmail: PropTypes.string, userName: PropTypes.string, updateUserInfo: PropTypes.func, }; export default DashboardPage;
src/js/components/Panel.js
nicholasodonnell/moonshine
import React from 'react'; class Panel extends React.Component { constructor() { super(); } componentWillMount() { } render() { return ( <div class="o-panel"> {this.props.children} </div> ); } } export default Panel;
hunt/src/components/HistoryItem.js
StamusNetworks/scirius
import React from 'react'; import PropTypes from 'prop-types'; import moment from 'moment'; import { connect } from 'react-redux'; import { Col, Icon, Row, ListViewItem, ListViewInfoItem, ListViewIcon } from 'patternfly-react'; import { PAGE_STATE, sections } from 'hunt_common/constants'; import { addFilter } from '../containers/App/stores/global'; const HistoryItem = (props) => { const date = moment(props.data.date).format('YYYY-MM-DD, hh:mm:ss a'); const info = [ <ListViewInfoItem key="date"> <p>Date: {date}</p> </ListViewInfoItem>, <ListViewInfoItem key="user"> <p> <Icon type="pf" name="user" /> {props.data.username} </p> </ListViewInfoItem>, ]; if (props.data.ua_objects.ruleset && props.data.ua_objects.ruleset.pk) { info.push( <ListViewInfoItem key="ruleset"> <p> <Icon type="fa" name="th" /> {props.data.ua_objects.ruleset.value} </p> </ListViewInfoItem>, ); } if (props.data.ua_objects.rule && props.data.ua_objects.rule.sid) { info.push( <ListViewInfoItem key="rule"> <p> <a onClick={() => { props.addFilter(sections.GLOBAL, { id: 'alert.signature_id', value: props.data.ua_objects.rule.sid, negated: false }); props.switchPage(PAGE_STATE.rules_list, props.data.ua_objects.rule.sid); }} > <i className="pficon-security" /> {props.data.ua_objects.rule.sid} </a> </p> </ListViewInfoItem>, ); } return ( <ListViewItem leftContent={<ListViewIcon name="envelope" />} additionalInfo={info} heading={props.data.title} description={props.data.description} key={props.data.pk} compoundExpand={props.expand_row} compoundExpanded > {(props.data.comment || props.data.client_ip) && ( <Row> {props.data.comment && ( <Col sm={10}> <div className="container-fluid"> <strong>Comment</strong> <p>{props.data.comment}</p> </div> </Col> )} {props.data.client_ip && ( <Col sm={2}> <div className="container-fluid"> <strong>IP</strong> <p>{props.data.client_ip}</p> </div> </Col> )} </Row> )} </ListViewItem> ); }; HistoryItem.propTypes = { data: PropTypes.any, switchPage: PropTypes.any, expand_row: PropTypes.any, addFilter: PropTypes.func, }; const mapDispatchToProps = { addFilter, }; export default connect(null, mapDispatchToProps)(HistoryItem);
node_modules/_rc-calendar@9.0.4@rc-calendar/es/Picker.js
ligangwolai/blog
import React from 'react'; import ReactDOM from 'react-dom'; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; import createChainedFunction from 'rc-util/es/createChainedFunction'; import KeyCode from 'rc-util/lib/KeyCode'; import placements from './picker/placements'; import Trigger from 'rc-trigger'; function noop() {} function refFn(field, component) { this[field] = component; } var Picker = createReactClass({ displayName: 'Picker', propTypes: { animation: PropTypes.oneOfType([PropTypes.func, PropTypes.string]), disabled: PropTypes.bool, transitionName: PropTypes.string, onChange: PropTypes.func, onOpenChange: PropTypes.func, children: PropTypes.func, getCalendarContainer: PropTypes.func, calendar: PropTypes.element, style: PropTypes.object, open: PropTypes.bool, defaultOpen: PropTypes.bool, prefixCls: PropTypes.string, placement: PropTypes.any, value: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), defaultValue: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), align: PropTypes.object }, getDefaultProps: function getDefaultProps() { return { prefixCls: 'rc-calendar-picker', style: {}, align: {}, placement: 'bottomLeft', defaultOpen: false, onChange: noop, onOpenChange: noop }; }, getInitialState: function getInitialState() { var props = this.props; var open = void 0; if ('open' in props) { open = props.open; } else { open = props.defaultOpen; } var value = props.value || props.defaultValue; this.saveCalendarRef = refFn.bind(this, 'calendarInstance'); return { open: open, value: value }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { var value = nextProps.value, open = nextProps.open; if ('value' in nextProps) { this.setState({ value: value }); } if (open !== undefined) { this.setState({ open: open }); } }, componentDidUpdate: function componentDidUpdate(_, prevState) { if (!prevState.open && this.state.open) { this.focusTimeout = setTimeout(this.focusCalendar, 0, this); } }, componentWillUnmount: function componentWillUnmount() { clearTimeout(this.focusTimeout); }, onCalendarKeyDown: function onCalendarKeyDown(event) { if (event.keyCode === KeyCode.ESC) { event.stopPropagation(); this.close(this.focus); } }, onCalendarSelect: function onCalendarSelect(value) { var cause = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var props = this.props; if (!('value' in props)) { this.setState({ value: value }); } if (cause.source === 'keyboard' || !props.calendar.props.timePicker && cause.source !== 'dateInput' || cause.source === 'todayButton') { this.close(this.focus); } props.onChange(value); }, onKeyDown: function onKeyDown(event) { if (event.keyCode === KeyCode.DOWN && !this.state.open) { this.open(); event.preventDefault(); } }, onCalendarOk: function onCalendarOk() { this.close(this.focus); }, onCalendarClear: function onCalendarClear() { this.close(this.focus); }, onVisibleChange: function onVisibleChange(open) { this.setOpen(open); }, getCalendarElement: function getCalendarElement() { var props = this.props; var state = this.state; var calendarProps = props.calendar.props; var value = state.value; var defaultValue = value; var extraProps = { ref: this.saveCalendarRef, defaultValue: defaultValue || calendarProps.defaultValue, selectedValue: value, onKeyDown: this.onCalendarKeyDown, onOk: createChainedFunction(calendarProps.onOk, this.onCalendarOk), onSelect: createChainedFunction(calendarProps.onSelect, this.onCalendarSelect), onClear: createChainedFunction(calendarProps.onClear, this.onCalendarClear) }; return React.cloneElement(props.calendar, extraProps); }, setOpen: function setOpen(open, callback) { var onOpenChange = this.props.onOpenChange; if (this.state.open !== open) { if (!('open' in this.props)) { this.setState({ open: open }, callback); } onOpenChange(open); } }, open: function open(callback) { this.setOpen(true, callback); }, close: function close(callback) { this.setOpen(false, callback); }, focus: function focus() { if (!this.state.open) { ReactDOM.findDOMNode(this).focus(); } }, focusCalendar: function focusCalendar() { if (this.state.open && this.calendarInstance !== null) { this.calendarInstance.focus(); } }, render: function render() { var props = this.props; var prefixCls = props.prefixCls, placement = props.placement, style = props.style, getCalendarContainer = props.getCalendarContainer, align = props.align, animation = props.animation, disabled = props.disabled, transitionName = props.transitionName, children = props.children; var state = this.state; return React.createElement( Trigger, { popup: this.getCalendarElement(), popupAlign: align, builtinPlacements: placements, popupPlacement: placement, action: disabled && !state.open ? [] : ['click'], destroyPopupOnHide: true, getPopupContainer: getCalendarContainer, popupStyle: style, popupAnimation: animation, popupTransitionName: transitionName, popupVisible: state.open, onPopupVisibleChange: this.onVisibleChange, prefixCls: prefixCls }, React.cloneElement(children(state, props), { onKeyDown: this.onKeyDown }) ); } }); export default Picker;
src/components/common/svg-icons/device/signal-cellular-connected-no-internet-0-bar.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellularConnectedNoInternet0Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M20 22h2v-2h-2v2zm0-12v8h2v-8h-2z"/> </SvgIcon> ); DeviceSignalCellularConnectedNoInternet0Bar = pure(DeviceSignalCellularConnectedNoInternet0Bar); DeviceSignalCellularConnectedNoInternet0Bar.displayName = 'DeviceSignalCellularConnectedNoInternet0Bar'; DeviceSignalCellularConnectedNoInternet0Bar.muiName = 'SvgIcon'; export default DeviceSignalCellularConnectedNoInternet0Bar;
src/Notification-Added.js
robreczarek/clouds-stepone-app
import React, { Component } from 'react'; import { withRouter } from 'react-router'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import Paper from 'material-ui/Paper'; import {Card, CardText} from 'material-ui/Card'; class NotificationAdded extends Component { render() { if (this.props.location.query.success === "true") { return ( <div className="notification"> <MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}> <Paper> <Card> <CardText> Record has been added </CardText> </Card> </Paper> </MuiThemeProvider> </div> ) } else { return null } } } export default withRouter(NotificationAdded);
packages/mineral-ui-icons/src/IconCallEnd.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconCallEnd(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08a.956.956 0 0 1-.29-.7c0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28a11.27 11.27 0 0 0-2.67-1.85.996.996 0 0 1-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"/> </g> </Icon> ); } IconCallEnd.displayName = 'IconCallEnd'; IconCallEnd.category = 'communication';
public/src/index.js
alexisbellido/node-tests
// let's go! import React from 'react'; import { render } from 'react-dom'; import { BrowserRouter, Match, Miss } from 'react-router'; import './css/style.css'; import StorePicker from './components/StorePicker'; import App from './components/App'; import NotFound from './components/NotFound'; const Root = () => { return ( <BrowserRouter> <div> <Match exactly pattern="/" component={StorePicker} /> <Match pattern="/store/:storeId" component={App} /> <Miss component={NotFound} /> </div> </BrowserRouter> ) } render(<Root/>, document.querySelector('#main'));
src/svg-icons/av/fiber-dvr.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvFiberDvr = (props) => ( <SvgIcon {...props}> <path d="M17.5 10.5h2v1h-2zm-13 0h2v3h-2zM21 3H3c-1.11 0-2 .89-2 2v14c0 1.1.89 2 2 2h18c1.11 0 2-.9 2-2V5c0-1.11-.89-2-2-2zM8 13.5c0 .85-.65 1.5-1.5 1.5H3V9h3.5c.85 0 1.5.65 1.5 1.5v3zm4.62 1.5h-1.5L9.37 9h1.5l1 3.43 1-3.43h1.5l-1.75 6zM21 11.5c0 .6-.4 1.15-.9 1.4L21 15h-1.5l-.85-2H17.5v2H16V9h3.5c.85 0 1.5.65 1.5 1.5v1z"/> </SvgIcon> ); AvFiberDvr = pure(AvFiberDvr); AvFiberDvr.displayName = 'AvFiberDvr'; AvFiberDvr.muiName = 'SvgIcon'; export default AvFiberDvr;
node_modules/_redux-form@6.8.0@redux-form/es/createFormValues.js
ligangwolai/blog
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import prefixName from './util/prefixName'; var createValues = function createValues(_ref) { var getIn = _ref.getIn; return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var valuesMap = void 0; if (typeof args[0] === 'string') { valuesMap = args.map(function (k) { return { prop: k, path: k }; }); } else { var config = args[0]; valuesMap = Object.keys(config).map(function (k) { return { prop: k, path: config[k] }; }); } if (!valuesMap.length) { throw new Error('formValues(): You must specify values to get as formValues(name1, name2, ...) or formValues({propName1: propPath1, ...})'); } // create a class that reads current form name and creates a selector // return return function (Component) { var FormValues = function (_React$Component) { _inherits(FormValues, _React$Component); function FormValues(props, context) { _classCallCheck(this, FormValues); var _this = _possibleConstructorReturn(this, (FormValues.__proto__ || Object.getPrototypeOf(FormValues)).call(this, props, context)); if (!context._reduxForm) { throw new Error('formValues() must be used inside a React tree decorated with reduxForm()'); } var getValues = context._reduxForm.getValues; var formValuesSelector = function formValuesSelector(_) { // Yes, we're only using connect() for listening to updates var props = {}; var values = getValues(); valuesMap.forEach(function (_ref2) { var prop = _ref2.prop, path = _ref2.path; return props[prop] = getIn(values, prefixName(context, path)); }); return props; }; _this.Component = connect(formValuesSelector, function () { return {}; } // ignore dispatch )(Component); return _this; } _createClass(FormValues, [{ key: 'render', value: function render() { return React.createElement(this.Component, this.props); } }]); return FormValues; }(React.Component); FormValues.contextTypes = { _reduxForm: PropTypes.object }; return FormValues; }; }; }; export default createValues;
src/universalRouter.js
zangrafx/react-redux-universal-hot-example
import React from 'react'; import Router from 'react-router'; import createRoutes from './views/createRoutes'; import { Provider } from 'react-redux'; const getFetchData = (component = {}) => { return component.WrappedComponent ? getFetchData(component.WrappedComponent) : component.fetchData; }; export function createTransitionHook(store) { return (nextState, transition, callback) => { const { params, location: { query } } = nextState; const promises = nextState.branch .map(route => route.component) // pull out individual route components .filter((component) => getFetchData(component)) // only look at ones with a static fetchData() .map(getFetchData) // pull out fetch data methods .map(fetchData => fetchData(store, params, query || {})); // call fetch data methods and save promises Promise.all(promises) .then(() => { callback(); // can't just pass callback to then() because callback assumes first param is error }, (error) => { callback(error); }); }; } export default function universalRouter(location, history, store) { const routes = createRoutes(store); return new Promise((resolve, reject) => { Router.run(routes, location, [createTransitionHook(store)], (error, initialState, transition) => { if (error) { return reject(error); } if (transition && transition.redirectInfo) { return resolve({ transition, isRedirect: true }); } if (history) { // only on client side initialState.history = history; } const component = ( <Provider store={store} key="provider"> {() => <Router {...initialState} children={routes}/>} </Provider> ); return resolve({ component, isRedirect: false }); }); }); }
fixtures/kitchensink/src/features/webpack/LinkedModules.js
altiore/webpack-react
/** * 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. */ import React from 'react'; import './assets/style.css'; import { test, version } from 'test-integrity'; export default () => { const v = version(); if (!test() || v !== '2.0.0') { throw new Error('Functionality test did not pass.'); } return ( <p id="feature-linked-modules"> {v} </p> ); };
app/javascript/mastodon/features/compose/components/compose_form.js
glitch-soc/mastodon
import React from 'react'; import CharacterCounter from './character_counter'; import Button from '../../../components/button'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import ReplyIndicatorContainer from '../containers/reply_indicator_container'; import AutosuggestTextarea from '../../../components/autosuggest_textarea'; import AutosuggestInput from '../../../components/autosuggest_input'; import PollButtonContainer from '../containers/poll_button_container'; import UploadButtonContainer from '../containers/upload_button_container'; import { defineMessages, injectIntl } from 'react-intl'; import SpoilerButtonContainer from '../containers/spoiler_button_container'; import PrivacyDropdownContainer from '../containers/privacy_dropdown_container'; import EmojiPickerDropdown from '../containers/emoji_picker_dropdown_container'; import PollFormContainer from '../containers/poll_form_container'; import UploadFormContainer from '../containers/upload_form_container'; import WarningContainer from '../containers/warning_container'; import { isMobile } from '../../../is_mobile'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { length } from 'stringz'; import { countableText } from '../util/counter'; import Icon from 'mastodon/components/icon'; import { maxChars } from '../../../initial_state'; const allowedAroundShortCode = '><\u0085\u0020\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\u0009\u000a\u000b\u000c\u000d'; const messages = defineMessages({ placeholder: { id: 'compose_form.placeholder', defaultMessage: 'What is on your mind?' }, spoiler_placeholder: { id: 'compose_form.spoiler_placeholder', defaultMessage: 'Write your warning here' }, publish: { id: 'compose_form.publish', defaultMessage: 'Toot' }, publishLoud: { id: 'compose_form.publish_loud', defaultMessage: '{publish}!' }, saveChanges: { id: 'compose_form.save_changes', defaultMessage: 'Save changes' }, }); export default @injectIntl class ComposeForm extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { intl: PropTypes.object.isRequired, text: PropTypes.string.isRequired, suggestions: ImmutablePropTypes.list, spoiler: PropTypes.bool, privacy: PropTypes.string, spoilerText: PropTypes.string, focusDate: PropTypes.instanceOf(Date), caretPosition: PropTypes.number, preselectDate: PropTypes.instanceOf(Date), isSubmitting: PropTypes.bool, isChangingUpload: PropTypes.bool, isEditing: PropTypes.bool, isUploading: PropTypes.bool, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, onClearSuggestions: PropTypes.func.isRequired, onFetchSuggestions: PropTypes.func.isRequired, onSuggestionSelected: PropTypes.func.isRequired, onChangeSpoilerText: PropTypes.func.isRequired, onPaste: PropTypes.func.isRequired, onPickEmoji: PropTypes.func.isRequired, showSearch: PropTypes.bool, anyMedia: PropTypes.bool, isInReply: PropTypes.bool, singleColumn: PropTypes.bool, }; static defaultProps = { showSearch: false, }; handleChange = (e) => { this.props.onChange(e.target.value); } handleKeyDown = (e) => { if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) { this.handleSubmit(); } } getFulltextForCharacterCounting = () => { return [this.props.spoiler? this.props.spoilerText: '', countableText(this.props.text)].join(''); } canSubmit = () => { const { isSubmitting, isChangingUpload, isUploading, anyMedia } = this.props; const fulltext = this.getFulltextForCharacterCounting(); const isOnlyWhitespace = fulltext.length !== 0 && fulltext.trim().length === 0; return !(isSubmitting || isUploading || isChangingUpload || length(fulltext) > maxChars || (isOnlyWhitespace && !anyMedia)); } handleSubmit = () => { if (this.props.text !== this.autosuggestTextarea.textarea.value) { // Something changed the text inside the textarea (e.g. browser extensions like Grammarly) // Update the state to match the current text this.props.onChange(this.autosuggestTextarea.textarea.value); } if (!this.canSubmit()) { return; } this.props.onSubmit(this.context.router ? this.context.router.history : null); } onSuggestionsClearRequested = () => { this.props.onClearSuggestions(); } onSuggestionsFetchRequested = (token) => { this.props.onFetchSuggestions(token); } onSuggestionSelected = (tokenStart, token, value) => { this.props.onSuggestionSelected(tokenStart, token, value, ['text']); } onSpoilerSuggestionSelected = (tokenStart, token, value) => { this.props.onSuggestionSelected(tokenStart, token, value, ['spoiler_text']); } handleChangeSpoilerText = (e) => { this.props.onChangeSpoilerText(e.target.value); } handleFocus = () => { if (this.composeForm && !this.props.singleColumn) { const { left, right } = this.composeForm.getBoundingClientRect(); if (left < 0 || right > (window.innerWidth || document.documentElement.clientWidth)) { this.composeForm.scrollIntoView(); } } } componentDidMount () { this._updateFocusAndSelection({ }); } componentDidUpdate (prevProps) { this._updateFocusAndSelection(prevProps); } _updateFocusAndSelection = (prevProps) => { // This statement does several things: // - If we're beginning a reply, and, // - Replying to zero or one users, places the cursor at the end of the textbox. // - Replying to more than one user, selects any usernames past the first; // this provides a convenient shortcut to drop everyone else from the conversation. if (this.props.focusDate !== prevProps.focusDate) { let selectionEnd, selectionStart; if (this.props.preselectDate !== prevProps.preselectDate && this.props.isInReply) { selectionEnd = this.props.text.length; selectionStart = this.props.text.search(/\s/) + 1; } else if (typeof this.props.caretPosition === 'number') { selectionStart = this.props.caretPosition; selectionEnd = this.props.caretPosition; } else { selectionEnd = this.props.text.length; selectionStart = selectionEnd; } // Because of the wicg-inert polyfill, the activeElement may not be // immediately selectable, we have to wait for observers to run, as // described in https://github.com/WICG/inert#performance-and-gotchas Promise.resolve().then(() => { this.autosuggestTextarea.textarea.setSelectionRange(selectionStart, selectionEnd); this.autosuggestTextarea.textarea.focus(); }).catch(console.error); } else if(prevProps.isSubmitting && !this.props.isSubmitting) { this.autosuggestTextarea.textarea.focus(); } else if (this.props.spoiler !== prevProps.spoiler) { if (this.props.spoiler) { this.spoilerText.input.focus(); } else { this.autosuggestTextarea.textarea.focus(); } } } setAutosuggestTextarea = (c) => { this.autosuggestTextarea = c; } setSpoilerText = (c) => { this.spoilerText = c; } setRef = c => { this.composeForm = c; }; handleEmojiPick = (data) => { const { text } = this.props; const position = this.autosuggestTextarea.textarea.selectionStart; const needsSpace = data.custom && position > 0 && !allowedAroundShortCode.includes(text[position - 1]); this.props.onPickEmoji(position, data, needsSpace); } render () { const { intl, onPaste, showSearch } = this.props; const disabled = this.props.isSubmitting; let publishText = ''; if (this.props.isEditing) { publishText = intl.formatMessage(messages.saveChanges); } else if (this.props.privacy === 'private' || this.props.privacy === 'direct') { publishText = <span className='compose-form__publish-private'><Icon id='lock' /> {intl.formatMessage(messages.publish)}</span>; } else { publishText = this.props.privacy !== 'unlisted' ? intl.formatMessage(messages.publishLoud, { publish: intl.formatMessage(messages.publish) }) : intl.formatMessage(messages.publish); } return ( <div className='compose-form'> <WarningContainer /> <ReplyIndicatorContainer /> <div className={`spoiler-input ${this.props.spoiler ? 'spoiler-input--visible' : ''}`} ref={this.setRef}> <AutosuggestInput placeholder={intl.formatMessage(messages.spoiler_placeholder)} value={this.props.spoilerText} onChange={this.handleChangeSpoilerText} onKeyDown={this.handleKeyDown} disabled={!this.props.spoiler} ref={this.setSpoilerText} suggestions={this.props.suggestions} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} onSuggestionSelected={this.onSpoilerSuggestionSelected} searchTokens={[':']} id='cw-spoiler-input' className='spoiler-input__input' /> </div> <AutosuggestTextarea ref={this.setAutosuggestTextarea} placeholder={intl.formatMessage(messages.placeholder)} disabled={disabled} value={this.props.text} onChange={this.handleChange} suggestions={this.props.suggestions} onFocus={this.handleFocus} onKeyDown={this.handleKeyDown} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} onSuggestionSelected={this.onSuggestionSelected} onPaste={onPaste} autoFocus={!showSearch && !isMobile(window.innerWidth)} > <EmojiPickerDropdown onPickEmoji={this.handleEmojiPick} /> <div className='compose-form__modifiers'> <UploadFormContainer /> <PollFormContainer /> </div> </AutosuggestTextarea> <div className='compose-form__buttons-wrapper'> <div className='compose-form__buttons'> <UploadButtonContainer /> <PollButtonContainer /> <PrivacyDropdownContainer disabled={this.props.isEditing} /> <SpoilerButtonContainer /> </div> <div className='character-counter__wrapper'><CharacterCounter max={maxChars} text={this.getFulltextForCharacterCounting()} /></div> </div> <div className='compose-form__publish'> <div className='compose-form__publish-button-wrapper'><Button text={publishText} onClick={this.handleSubmit} disabled={!this.canSubmit()} block /></div> </div> </div> ); } }
es6/Steps/Steps.js
yurizhang/ishow
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import PropTypes from 'prop-types'; import { default as Component } from '../Common/plugs/index.js'; //提供style, classname方法 import '../Common/css/Steps.css'; import '../Common/css/Step.css'; var Steps = function (_Component) { _inherits(Steps, _Component); function Steps() { _classCallCheck(this, Steps); return _possibleConstructorReturn(this, (Steps.__proto__ || Object.getPrototypeOf(Steps)).apply(this, arguments)); } _createClass(Steps, [{ key: 'calcProgress', value: function calcProgress(status, index) { var step = 100; var style = {}; style.transitionDelay = 150 * index + 'ms'; var nextStatus = this.calStatus(index + 1); // 前后状态不一致时,并且当前status为完成,statusLine的长度才为50% if (nextStatus !== status) { if (status === this.props.finishStatus) { step = 50; } else if (status === 'wait') { step = 0; style.transitionDelay = -150 * index + 'ms'; } } this.props.direction === 'vertical' ? style.height = step + '%' : style.width = step + '%'; return style; } }, { key: 'calStatus', value: function calStatus(index) { var _props = this.props, active = _props.active, finishStatus = _props.finishStatus, processStatus = _props.processStatus; var status = 'wait'; if (active > index) { status = finishStatus; } else if (active === index) { status = processStatus; } return status; } }, { key: 'render', value: function render() { var _this2 = this; var _props2 = this.props, children = _props2.children, space = _props2.space, direction = _props2.direction; return React.createElement( 'div', { style: this.style(), className: this.className('ishow-steps') }, React.Children.map(children, function (child, index) { var computedSpace = space ? space + 'px' : 100 / children.length + '%'; var style = direction === 'horizontal' ? { width: computedSpace } : { height: index === children.length - 1 ? 'auto' : computedSpace }; var status = _this2.calStatus(index); var lineStyle = _this2.calcProgress(status, index); return React.cloneElement(child, { style: style, lineStyle: lineStyle, direction: direction, status: status, stepNumber: index + 1 }); }) ); } }]); return Steps; }(Component); Steps.defaultProps = { direction: 'horizontal', finishStatus: 'finish', processStatus: 'process', active: 0 }; export default Steps; var statusMap = ['wait', 'process', 'finish', 'error', 'success']; Steps.propTypes = { space: PropTypes.number, active: PropTypes.number, direction: PropTypes.oneOf(['vertical', 'horizontal']), finishStatus: PropTypes.oneOf(statusMap), processStatus: PropTypes.oneOf(statusMap) };
react-dev/components/menu.js
575617819/yanghang
import React, { Component } from 'react'; import AppBar from 'material-ui/AppBar'; import Drawer from 'material-ui/Drawer'; import { MenuItems } from './menu_items'; import SearchBar from '../containers/search_bar'; export default class Menu extends Component { constructor(props) { super(props); this.state = { open: this.props.open, width: 1200, height: null }; } componentWillMount() { this.setState(this.updateDimensions()); window.addEventListener('resize', this.setState(this.updateDimensions())); } componentDidMount() { window.addEventListener('resize', this.setState(this.updateDimensions())); } componentWillUnmount() { window.removeEventListener('resize', this.setState(this.updateDimensions())); } getMenuWidth = () => { //some responsiveness to the menu if (this.state.width > 1600) return 400; else if (this.state.width <= 1600 && this.state.width > 1200) return 350; else if (this.state.width <= 1200 && this.state.width > 600) return 300; else if (this.state.width <= 600) return 256; } updateDimensions = () => { const w = window; const d = document; const documentElement = d.documentElement; const body = d.getElementsByTagName('body')[0]; const width = w.innerWidth || documentElement.clientWidth || body.clientWidth; const height = w.innerHeight || documentElement.clientHeight || body.clientHeight; return ({ width, height }); }; render() { return ( <Drawer docked width={this.getMenuWidth()} open={this.props.open} onRequestChange={this.props.handleToggle} swipeAreaWidth={200} className="menu-overflow" containerClassName="menu-overflow" > <AppBar title="Menu" onLeftIconButtonTouchTap={this.props.handleToggle} iconElementRight={<SearchBar getMenuWidth={this.getMenuWidth} location={this.props.location} />} /> <MenuItems config={this.props.config} /> </Drawer> ); } }
examples/websdk-samples/LayerReactNativeSample/src/ui/announcements/MessageListItem.js
layerhq/layer-js-sampleapps
import React, { Component } from 'react'; import { StyleSheet, View, TouchableOpacity, Text } from 'react-native'; import LayerHelper from '../../layer_helper.js' import TextMessagePart from './TextMessagePart'; import Avatar from '../Avatar'; import Icon from 'react-native-vector-icons/FontAwesome'; /** * This Component renders a single Message in a Message List * which includes Avatar, sender name, message body, * timestamp and status. */ export default class MessageListItem extends Component { constructor(props) { super(props); } /** * At this time we are marking any Message that has been * rendered as read. A more advanced implementation * would test if was scrolled into view. */ markMessageRead() { const { onMarkMessageRead, message } = this.props; if (message.isUnread) { onMarkMessageRead(message.id); } } showItem = (event) => { this.markMessageRead(); } render() { const { message, users } = this.props; return ( <TouchableOpacity style={styles.container} onPress={this.showItem} activeOpacity={.5} > {(!message.isRead) && <Icon style={styles.unreadBullet} name='circle' /> } <Text style={styles.displayName}>{message.sender.displayName}</Text> <View style={styles.announcementParts}> {message.parts.map((messagePart) => { return ( <TextMessagePart key={messagePart.id} messagePart={messagePart}/> ) })} </View> <Text style={styles.timestamp}>{LayerHelper.dateFormat(message.sentAt)}</Text> </TouchableOpacity> ); } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'row', backgroundColor: 'white', padding: 10 }, displayName: { fontFamily: 'System', color: '#666', fontWeight: 'bold', width: 100, }, announcementParts: { marginHorizontal: 5, flex: 1, }, unreadBullet: { marginTop: 3, marginRight: 5 }, timestamp: { fontFamily: 'System', fontSize: 10, width: 100, color: '#666', textAlign: 'right', } });
samples/react-1/lib/App.js
abouthiroppy/sweetpack
import React from 'react'; import styles from './style.css'; const App = () => ( <div> <h1 className={styles.title}>sample</h1> <input /> <div className={styles.js} /> </div> ); export default App;
src/components/Form/CateSelect/CateSelect.js
hahoocn/hahoo-admin
import React from 'react'; import FormControl from 'react-bootstrap/lib/FormControl'; function makeOptions(options, i) { let items = []; let deep = i; let prefix = '|-'; for (let j = 0; j < deep; j++) { prefix = `\u3000${prefix}`; } for (const option of options) { items.push(<option key={option.id} value={option.id}>{prefix}{option.title}</option>); if (option.subItems && option.subItems.length > 0) { deep++; items = items.concat(makeOptions(option.subItems, deep)); deep--; } } return items; } class CateSelect extends React.Component { static propTypes = { options: React.PropTypes.array, preOptions: React.PropTypes.array, lastOptions: React.PropTypes.array, isShowFirstInfo: React.PropTypes.bool } static defaultProps = { options: [], preOptions: [], lastOptions: [], isShowFirstInfo: true } render() { const { options, preOptions, lastOptions, isShowFirstInfo, ...rest } = this.props; delete rest.componentClass; let items = []; if (isShowFirstInfo) { items.push(<option key={-1} value="">---请选择---</option>); } if (preOptions && preOptions.length > 0) { items = items.concat(makeOptions(preOptions, 0)); } items = items.concat(makeOptions(options, 0)); if (lastOptions && lastOptions.length > 0) { items = items.concat(makeOptions(lastOptions, 0)); } return ( <FormControl componentClass="select" style={{ textAlign: 'left' }} {...rest} > {items} </FormControl> ); } } export default CateSelect;
app/src/components/common/ReduxTextField/ReduxTextField.js
joedunu/react-redux-example
import React from 'react' import PropTypes from 'prop-types' import TextField from 'material-ui/TextField' const ReduxTextField = ( { input, label, meta: {touched, error} }) => ( <TextField label={label} error={touched && !!error} helperText={touched && error} {...input} multiline fullWidth /> ) ReduxTextField.propTypes = { input: PropTypes.object, label: PropTypes.string, meta: PropTypes.object } export default ReduxTextField
src/components/common/svg-icons/action/delete-forever.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionDeleteForever = (props) => ( <SvgIcon {...props}> <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zm2.46-7.12l1.41-1.41L12 12.59l2.12-2.12 1.41 1.41L13.41 14l2.12 2.12-1.41 1.41L12 15.41l-2.12 2.12-1.41-1.41L10.59 14l-2.13-2.12zM15.5 4l-1-1h-5l-1 1H5v2h14V4z"/> </SvgIcon> ); ActionDeleteForever = pure(ActionDeleteForever); ActionDeleteForever.displayName = 'ActionDeleteForever'; ActionDeleteForever.muiName = 'SvgIcon'; export default ActionDeleteForever;
src/components/TaskHistory/index.js
bruceli1986/contract-react
import React from 'react' import formatter from 'utils/formatter.js' /** 流转历史列表*/ class TaskHistory extends React.Component { static propTypes = { history: React.PropTypes.arrayOf(React.PropTypes.shape({ assignee: React.PropTypes.string, comment: React.PropTypes.string, taskName: React.PropTypes.string, startTime: React.PropTypes.number, endTime: React.PropTypes.number })), loaded: React.PropTypes.bool } render () { return ( <div className='table-responsive' style={{position: 'relative'}}> <div className={this.props.loaded ? '' : 'hidden'}> { this.props.history.length > 0 ? ( <table className='table table-striped table-hover'> <thead> <tr> <th style={{width: '10%'}}>处理人</th> <th style={{minWidth: '15em', width: '30%'}}>处理意见</th> <th style={{minWidth: '10em', width: '20%'}}>任务名</th> <th style={{width: '15%'}}>开始时间</th> <th style={{width: '15%'}}>结束时间</th> </tr> </thead> <tbody> { this.props.history.map((x, i) => ( <tr key={i}> <td>{x.assignee}</td> <td style={{whiteSpace: 'normal', textAlign: 'left'}}>{x.comment ? x.comment : '-'}</td> <td style={{whiteSpace: 'normal'}}>{x.taskName}</td> <td>{formatter.formatTime(x.startTime)}</td> <td>{x.endTime ? formatter.formatTime(x.endTime) : '-'}</td> </tr> )) } </tbody> </table>) : (<span>空</span>) } </div> <div style={{height: '200px'}} className={this.props.loaded ? 'hidden' : 'payment-mask'} /> </div> ) } } export default TaskHistory
src/components/appRegionSelect.js
owstat/owstat
import React from 'react' import { Zoom } from 'animate-components' import { CheckServerStatus } from './appStatus' const regionNames = { America: { text_enUS: 'America', text_kr: '미국' }, Europe: { text_enUS: 'Europe', text_kr: '유럽' }, Asia: { text_enUS: 'Asia', text_kr: '아시아' }, PTR: { text_enUS: 'PTR', text_kr: 'PTR' } } export default class AppRegionSelector extends React.Component { render () { return ( <section className='appRegionSelect'> <table> <tbody> <tr> <td> <Zoom as='div' duration='0.75s' className='regionButton' onClick={() => CheckServerStatus('US')}> <img id='regionUS' src='../static/svg/region_us.svg' /> <br /> <span>{regionNames.America.text_enUS}</span> </Zoom> </td> </tr> <tr> <td> <Zoom as='div' duration='1.25s' className='regionButton' onClick={() => CheckServerStatus('EU')}> <img id='regionEU' src='../static/svg/region_eu.svg' /> <br /> <span>{regionNames.Europe.text_enUS}</span> </Zoom> </td> </tr> <tr> <td> <Zoom as='div' duration='1.75s' className='regionButton' onClick={() => CheckServerStatus('ASIA')}> <img id='regionAsia' src='../static/svg/region_asia.svg' /> <br /> <span>{regionNames.Asia.text_enUS}</span> </Zoom> </td> </tr> </tbody> </table> </section> ) } }
example-expo/NavBar.js
FaridSafi/react-native-gifted-messenger
/* eslint jsx-a11y/accessible-emoji: 0 */ import React from 'react'; import { Text } from 'react-native'; import NavBar, { NavTitle, NavButton } from 'react-native-nav'; import { Constants } from 'expo'; export default function NavBarCustom() { return ( <NavBar> <NavButton /> <NavTitle> 💬 Gifted Chat{'\n'} <Text style={{ fontSize: 10, color: '#aaa' }}> ({Constants.expoVersion}) </Text> </NavTitle> <NavButton /> </NavBar> ); }
app/src/components/ProgressBar/index.js
oh-my-github/yo-omg-basic
import React from 'react' import ReactTooltip from 'react-tooltip' import styles from './index.css' /** ref: http://cssdeck.com/labs/twitter-bootstrap-progress-bars */ class ProgressBar extends React.Component { render() { const { width, color, label, animated, tooltipLabel, } = this.props const animationStyle = (animated) ? styles.animated : '' const tooltipId = `tooltipIdFor${label}` const tooltipElement = (tooltipLabel) ? <div> <ReactTooltip id={tooltipId} place='top' type='dark' effect='float'> {tooltipLabel} </ReactTooltip> </div> : null return ( <div className={`${styles.progress}`}> <div className={`${styles.bar} ${animationStyle}`} style={{width, backgroundColor: color,}}> <div data-tip data-for={tooltipId}>{label}</div> {tooltipElement} </div> </div> ) } } export default ProgressBar ProgressBar.propTypes = { width: React.PropTypes.string.isRequired, color: React.PropTypes.string.isRequired, label: React.PropTypes.string.isRequired, animated: React.PropTypes.bool, tooltipLabel: React.PropTypes.string, }
fields/types/select/SelectField.js
michaelerobertsjr/keystone
import Field from '../Field'; import React from 'react'; import Select from 'react-select'; import { FormInput } from 'elemental'; /** * TODO: * - Custom path support */ module.exports = Field.create({ displayName: 'SelectField', statics: { type: 'Select', }, valueChanged (newValue) { // TODO: This should be natively handled by the Select component if (this.props.numeric && typeof newValue === 'string') { newValue = newValue ? Number(newValue) : undefined; } this.props.onChange({ path: this.props.path, value: newValue, }); }, renderValue () { var selected = this.props.ops.find(option => option.value === this.props.value); return <FormInput noedit>{selected ? selected.label : null}</FormInput>; }, renderField () { // TODO: This should be natively handled by the Select component var ops = (this.props.numeric) ? this.props.ops.map(function (i) { return { label: i.label, value: String(i.value) }; }) : this.props.ops; var value = (typeof this.props.value === 'number') ? String(this.props.value) : this.props.value; return <Select simpleValue name={this.props.path} value={value} options={ops} onChange={this.valueChanged} />; }, });
app/components/LoadingIndicator/index.js
tomazy/react-boilerplate
import React from 'react'; import Circle from './Circle'; import Wrapper from './Wrapper'; const LoadingIndicator = () => ( <Wrapper> <Circle /> <Circle rotate={30} delay={-1.1} /> <Circle rotate={60} delay={-1} /> <Circle rotate={90} delay={-0.9} /> <Circle rotate={120} delay={-0.8} /> <Circle rotate={150} delay={-0.7} /> <Circle rotate={180} delay={-0.6} /> <Circle rotate={210} delay={-0.5} /> <Circle rotate={240} delay={-0.4} /> <Circle rotate={270} delay={-0.3} /> <Circle rotate={300} delay={-0.2} /> <Circle rotate={330} delay={-0.1} /> </Wrapper> ); export default LoadingIndicator;
packages/material-ui-icons/src/Backup.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Backup = props => <SvgIcon {...props}> <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM14 13v4h-4v-4H7l5-5 5 5h-3z" /> </SvgIcon>; Backup = pure(Backup); Backup.muiName = 'SvgIcon'; export default Backup;
src/components/views/leftsidebar/LeftSidebar.js
DataKind-BLR/antara
import React from 'react'; import { Link, IndexLink } from 'react-router'; import TabsPanel from './subcomponents/TabsPanel'; class LeftSidebar extends React.Component{ render(){ let leftSideBarComponent= this.props.config; let logoWrapper = null; if(leftSideBarComponent.top_logo.format == "text") { logoWrapper = ( <h2 className="app-title">{leftSideBarComponent.top_logo.text_config.text}<sub className="app-version">{leftSideBarComponent.top_logo.text_config.release_version}</sub> <hr className="title-hr" /></h2> ); } else if(leftSideBarComponent.top_logo.format == "img") { logoWrapper = ( <div > <img className="app-logo" width={leftSideBarComponent.top_logo.img_config.width} src={leftSideBarComponent.top_logo.img_config.source} /> <hr className="title-hr" /> </div> ); } return( <div> <div className="row-fluid"> <IndexLink to="/" className="app-logo"> {logoWrapper} </IndexLink> </div> <div className="select-panel row-fluid"> <TabsPanel panelData = {leftSideBarComponent.selection_panel.panels} /> </div> {/* ToDo : Add Social Media Integration <div className="social-icons-wrapper row-fluid"> <ShareIcons /> </div>*/} <div className="row-fluid leftsidebar-bottom-logos"> {leftSideBarComponent.bottom_logo.contributor_organizations.map(function(image){ return (<a href={image.link} target="_blank" className="organization-logo-link" key={image.image_name}> <img src={image.url} alt={image.alt} height={image.height} /> </a>); })} </div> </div> ); } } LeftSidebar.propTypes = { config:React.PropTypes.object }; export default LeftSidebar;
src/utils/getTipContent.js
wwayne/react-tooltip
/** * To get the tooltip content * it may comes from data-tip or this.props.children * it should support multiline * * @params * - `tip` {String} value of data-tip * - `children` {ReactElement} this.props.children * - `multiline` {Any} could be Bool(true/false) or String('true'/'false') * * @return * - String or react component */ import React from 'react'; export default function(tip, children, getContent, multiline) { if (children) return children; if (getContent !== undefined && getContent !== null) return getContent; // getContent can be 0, '', etc. if (getContent === null) return null; // Tip not exist and children is null or undefined const regexp = /<br\s*\/?>/; if (!multiline || multiline === 'false' || !regexp.test(tip)) { // No trim(), so that user can keep their input return tip; } // Multiline tooltip content return tip.split(regexp).map((d, i) => { return ( <span key={i} className="multi-line"> {d} </span> ); }); }
src/components/drag/DragContainer.js
TonyYang9527/my-app
import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import {observer} from 'mobx-react'; import DragulaContainers from '../../dragula/DragulaContainers'; import DragDropTip from './DragDropTip'; class DragContainer extends React.Component{ static propTypes = { random: PropTypes.string, }; static defaultProps = { random : '' }; componentDidMount=()=> { DragulaContainers.addDragContainers(ReactDOM.findDOMNode(this)) ; }; render =() =>{ let id ='builder-element-'+this.props.random ; return( <div id={id} className="col-xs-8 col-sm-9 col-md-10 formarea drag-container" style={{visibility : 'visible',position :'relative'}}> <DragDropTip random={id} /> </div>) ; }; } export default observer(DragContainer);
js/App/Components/Sensor/AddSensor/SensorsListAddSensor.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 { FlatList } from 'react-native'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { View, InfoBlock, ThemedRefreshControl, } from '../../../../BaseComponents'; import { SensorRow, } from './SubViews'; import { getNoNameSensors, } from '../../../Lib/SensorUtils'; import capitalize from '../../../Lib/capitalize'; import Theme from '../../../Theme'; import i18n from '../../../Translations/common'; type Props = { rows: Array<Object>, currentScreen: string, route: Object, navigation: Object, appLayout: Object, onDidMount: (string, string, ?Object) => void, actions: Object, intl: Object, }; type State = { isRefreshing: boolean, }; class SensorsListAddSensor extends View<Props, State> { props: Props; state: State; renderRow: (Object) => Object; onRefresh: () => void; constructor(props: Props) { super(props); this.state = { isRefreshing: false, }; this.renderRow = this.renderRow.bind(this); this.onRefresh = this.onRefresh.bind(this); } componentDidMount() { const { onDidMount, intl } = this.props; const { formatMessage } = intl; onDidMount(capitalize(formatMessage(i18n.labelSelectSensor)), formatMessage(i18n.labelSelectSensorToAdd)); } shouldComponentUpdate(nextProps: Object, nextState: Object): boolean { return nextProps.currentScreen === 'SensorsListAddSensor'; } keyExtractor(item: Object): string { return item.id.toString(); } onRefresh() { const { actions } = this.props; this.setState({ isRefreshing: true, }); actions.getGateways().then(() => { this.setState({ isRefreshing: false, }); }).catch(() => { this.setState({ isRefreshing: false, }); }); } getPadding(): number { const { appLayout } = this.props; const { height, width } = appLayout; const isPortrait = height > width; const deviceWidth = isPortrait ? width : height; return deviceWidth * Theme.Core.paddingFactor; } onSelectSensor = (sensor: Object) => { const { navigation, route } = this.props; const prevParams = route.params || {}; navigation.navigate('SetSensorName', { sensor, ...prevParams, }); } renderRow(item: Object): Object { return ( <SensorRow onSelectSensor={this.onSelectSensor} appLayout={this.props.appLayout} item={item.item}/> ); } render(): Object { const padding = this.getPadding(); const { rows, intl, appLayout } = this.props; const { emptyCover, infoContainer, } = this.getStyles(appLayout); if (rows.length === 0) { return ( <View style={emptyCover}> <InfoBlock infoContainer={infoContainer} appLayout={appLayout} text={intl.formatMessage(i18n.noSensorsFound)}/> </View> ); } return ( <FlatList data={rows} renderItem={this.renderRow} refreshControl={ <ThemedRefreshControl onRefresh={this.onRefresh} refreshing={this.state.isRefreshing} /> } keyExtractor={this.keyExtractor} contentContainerStyle={{ paddingVertical: padding, }} /> ); } getStyles = (appLayout: Object): Object => { const { height, width } = appLayout; const isPortrait = height > width; const deviceWidth = isPortrait ? width : height; const { paddingFactor, } = Theme.Core; const padding = deviceWidth * paddingFactor; return { emptyCover: { flex: 1, margin: padding, alignItems: 'center', justifyContent: 'flex-start', }, infoContainer: { flex: 0, width: '100%', }, }; } } const parse433SensorsForListView = (sensors: Object, gatewayId: string): Array<Object> => { return getNoNameSensors(sensors, gatewayId); }; const getRows433Sensors = createSelector( [ ({ sensors }: Object): Object => sensors, ({ gateway }: Object): Object => gateway.id, ], (sensors: Object, gatewayId: string): Array<any> => parse433SensorsForListView(sensors, gatewayId) ); function mapStateToProps(state: Object, ownProps: Object): Object { const { gateway = {}} = ownProps.route.params || {}; return { rows: getRows433Sensors({...state, gateway}), }; } export default (connect(mapStateToProps, null)(SensorsListAddSensor): Object);
src/components/NavBar/NavBar.stories.js
Galernaya20/galernaya20.com
//@flow import React from 'react' import {storiesOf} from '@storybook/react' import {NavBar} from './NavBar.js' import {contextDecorator} from '../../../stories/decorators' storiesOf('NavBar', module) .addDecorator( contextDecorator({ router: { history: { push: () => {}, replace: () => {}, isActive: () => false, location: {pathname: '', query: {auth: false}}, createHref: id => id, }, }, }), ) .add('NavBar', () => <NavBar />)
src/ButtonInput.js
chilts/react-bootstrap
import React from 'react'; import Button from './Button'; import FormGroup from './FormGroup'; import InputBase from './InputBase'; import childrenValueValidation from './utils/childrenValueInputValidation'; class ButtonInput extends InputBase { renderFormGroup(children) { let {bsStyle, value, ...other} = this.props; return <FormGroup {...other}>{children}</FormGroup>; } renderInput() { let {children, value, ...other} = this.props; let val = children ? children : value; return <Button {...other} componentClass="input" ref="input" key="input" value={val} />; } } ButtonInput.types = ['button', 'reset', 'submit']; ButtonInput.defaultProps = { type: 'button' }; ButtonInput.propTypes = { type: React.PropTypes.oneOf(ButtonInput.types), bsStyle(props) { //defer to Button propTypes of bsStyle return null; }, children: childrenValueValidation, value: childrenValueValidation }; export default ButtonInput;
src/svg-icons/social/pages.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialPages = (props) => ( <SvgIcon {...props}> <path d="M3 5v6h5L7 7l4 1V3H5c-1.1 0-2 .9-2 2zm5 8H3v6c0 1.1.9 2 2 2h6v-5l-4 1 1-4zm9 4l-4-1v5h6c1.1 0 2-.9 2-2v-6h-5l1 4zm2-14h-6v5l4-1-1 4h5V5c0-1.1-.9-2-2-2z"/> </SvgIcon> ); SocialPages = pure(SocialPages); SocialPages.displayName = 'SocialPages'; SocialPages.muiName = 'SvgIcon'; export default SocialPages;
docs/src/sections/ProgressBarSection.js
jesenko/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 ProgressBarSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="progress">Progress bars</Anchor> <small>ProgressBar</small> </h2> <p className="lead">Provide up-to-date feedback on the progress of a workflow or action with simple yet flexible progress bars.</p> <h2><Anchor id="progress-basic">Basic example</Anchor></h2> <p>Default progress bar.</p> <ReactPlayground codeText={Samples.ProgressBarBasic} /> <h2><Anchor id="progress-label">With label</Anchor></h2> <p>Add a <code>label</code> prop to show a visible percentage. For low percentages, consider adding a min-width to ensure the label's text is fully visible.</p> <p>The following keys are interpolated with the current values: <code>%(min)s</code>, <code>%(max)s</code>, <code>%(now)s</code>, <code>%(percent)s</code>, <code>%(bsStyle)s</code></p> <ReactPlayground codeText={Samples.ProgressBarWithLabel} /> <h2><Anchor id="progress-screenreader-label">Screenreader only label</Anchor></h2> <p>Add a <code>srOnly</code> prop to hide the label visually.</p> <ReactPlayground codeText={Samples.ProgressBarScreenreaderLabel} /> <h2><Anchor id="progress-contextual">Contextual alternatives</Anchor></h2> <p>Progress bars use some of the same button and alert classes for consistent styles.</p> <ReactPlayground codeText={Samples.ProgressBarContextual} /> <h2><Anchor id="progress-striped">Striped</Anchor></h2> <p>Uses a gradient to create a striped effect. Not available in IE8.</p> <ReactPlayground codeText={Samples.ProgressBarStriped} /> <h2><Anchor id="progress-animated">Animated</Anchor></h2> <p>Add <code>active</code> prop to animate the stripes right to left. Not available in IE9 and below.</p> <ReactPlayground codeText={Samples.ProgressBarAnimated} /> <h2><Anchor id="progress-stacked">Stacked</Anchor></h2> <p>Nest <code>&lt;ProgressBar /&gt;</code>s to stack them.</p> <ReactPlayground codeText={Samples.ProgressBarStacked} /> <h3><Anchor id="progress-props">ProgressBar</Anchor></h3> <PropTable component="ProgressBar"/> </div> ); }
packages/ui/stories/decorators/withWidget.js
plouc/mozaik
import React from 'react' import styled from 'styled-components' import { Widget } from '../../src' const Container = styled.div` position: fixed; top: 0; left: 0; bottom: 0; right: 0; overflow: auto; display: flex; justify-content: center; align-items: center; background: ${props => props.theme.root.background}; color: ${props => props.theme.root.color}; ` const widgetStyle = { width: 320, height: 320, } export default story => ( <Container> <Widget style={widgetStyle}>{story()}</Widget> </Container> )
src/app.js
MatthewKosloski/howlongago
import React, { Component } from 'react'; import { render } from 'react-dom'; import HowLongAgo from './components/HowLongAgo'; render(<HowLongAgo/>, document.getElementById('app'));
src/svg-icons/editor/drag-handle.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorDragHandle = (props) => ( <SvgIcon {...props}> <path d="M20 9H4v2h16V9zM4 15h16v-2H4v2z"/> </SvgIcon> ); EditorDragHandle = pure(EditorDragHandle); EditorDragHandle.displayName = 'EditorDragHandle'; EditorDragHandle.muiName = 'SvgIcon'; export default EditorDragHandle;
src/svg-icons/device/signal-wifi-1-bar.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalWifi1Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M12.01 21.49L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l11.63 14.49.01.01.01-.01z"/><path d="M6.67 14.86L12 21.49v.01l.01-.01 5.33-6.63C17.06 14.65 15.03 13 12 13s-5.06 1.65-5.33 1.86z"/> </SvgIcon> ); DeviceSignalWifi1Bar = pure(DeviceSignalWifi1Bar); DeviceSignalWifi1Bar.displayName = 'DeviceSignalWifi1Bar'; DeviceSignalWifi1Bar.muiName = 'SvgIcon'; export default DeviceSignalWifi1Bar;
src/scripts/components/Footer.js
LWanjiru/ki-news
import React from 'react'; const Footer = () => { function getYear() { const dateNow = new Date(); const thisYear = dateNow.getFullYear(); return thisYear; } return ( <div className="col text-white"> <p>Made with &#x2764;, React, Webpack & Bootstrap</p> <p>Know It All(KI-ALL) News</p> <p>Powered by <a href="https://newsapi.org/" target="_blank" rel="noopener noreferrer">NewsAPI</a></p> <p>&#169; {getYear()}</p> </div> ); }; export default Footer;
theme/src/components/checkoutSuccess.js
cezerin/cezerin
import React from 'react'; import PropTypes from 'prop-types'; import { NavLink } from 'react-router-dom'; import { text } from '../lib/settings'; import * as helper from '../lib/helper'; const getCheckoutField = (checkoutFields, fieldName) => { if (checkoutFields && checkoutFields.length > 0) { return checkoutFields.find( f => f.name === fieldName && f.status !== 'hidden' ); } return null; }; const MobileField = ({ order, checkoutFields }) => { const checkoutField = getCheckoutField(checkoutFields, 'mobile'); return checkoutField && order.mobile !== '' ? ( <ShippingFieldDiv label={helper.getCheckoutFieldLabel(checkoutField)} value={order.mobile} /> ) : null; }; const CityField = ({ order, checkoutFields }) => { const checkoutField = getCheckoutField(checkoutFields, 'city'); return checkoutField && order.shipping_address.city !== '' ? ( <ShippingFieldDiv label={helper.getCheckoutFieldLabel(checkoutField)} value={order.shipping_address.city} /> ) : null; }; const CommentsField = ({ order, checkoutFields }) => { const checkoutField = getCheckoutField(checkoutFields, 'comments'); return checkoutField && order.comments !== '' ? ( <ShippingFieldDiv label={helper.getCheckoutFieldLabel(checkoutField)} value={order.comments} /> ) : null; }; const ShippingFields = ({ order, shippingMethod }) => { let shippingFields = null; if ( shippingMethod && shippingMethod.fields && shippingMethod.fields.length > 0 ) { shippingFields = shippingMethod.fields.map((field, index) => { const fieldLabel = helper.getShippingFieldLabel(field); const fieldValue = order.shipping_address[field.key]; return ( <ShippingFieldDiv key={index} label={fieldLabel} value={fieldValue} /> ); }); } return <div>{shippingFields}</div>; }; const ShippingFieldDiv = ({ label, value }) => ( <div className="shipping-field"> <label>{label}: </label> {value} </div> ); const OrderItem = ({ item, settings }) => ( <div className="columns is-mobile is-gapless checkout-success-row"> <div className="column is-6"> {item.name} <br /> <span>{item.variant_name}</span> </div> <div className="column is-2 has-text-right"> {helper.formatCurrency(item.price, settings)} </div> <div className="column is-2 has-text-centered">{item.quantity}</div> <div className="column is-2 has-text-right"> {helper.formatCurrency(item.price_total, settings)} </div> </div> ); const OrderItems = ({ items, settings }) => { if (items && items.length > 0) { const rows = items.map(item => ( <OrderItem key={item.id} item={item} settings={settings} /> )); return <div>{rows}</div>; } return null; }; const CheckoutSuccess = ({ order, settings, pageDetails, shippingMethod, checkoutFields }) => { if (order && order.items && order.items.length > 0) { return ( <div className="checkout-success-details"> <h1 className="checkout-success-title"> <img src="/assets/images/success.svg" alt="" /> <br /> {text.checkoutSuccessTitle} </h1> <div dangerouslySetInnerHTML={{ __html: pageDetails.content }} /> <hr /> <div className="columns" style={{ marginBottom: '3rem' }}> <div className="column is-6"> <b>{text.shipping}</b> <MobileField order={order} checkoutFields={checkoutFields} /> <CityField order={order} checkoutFields={checkoutFields} /> <ShippingFields order={order} shippingMethod={shippingMethod} /> <CommentsField order={order} checkoutFields={checkoutFields} /> </div> <div className="column is-6"> <b>{text.orderNumber}</b>: {order.number} <br /> <b>{text.shippingMethod}</b>: {order.shipping_method} <br /> <b>{text.paymentMethod}</b>: {order.payment_method} <br /> </div> </div> <div className="columns is-mobile is-gapless checkout-success-row"> <div className="column is-6"> <b>{text.productName}</b> </div> <div className="column is-2 has-text-right"> <b>{text.price}</b> </div> <div className="column is-2 has-text-centered"> <b>{text.qty}</b> </div> <div className="column is-2 has-text-right"> <b>{text.total}</b> </div> </div> <OrderItems items={order.items} settings={settings} /> <div className="columns"> <div className="column is-offset-7 checkout-success-totals"> <div> <span>{text.subtotal}:</span> <span>{helper.formatCurrency(order.subtotal, settings)}</span> </div> <div> <span>{text.shipping}:</span> <span> {helper.formatCurrency(order.shipping_total, settings)} </span> </div> <div> <b>{text.grandTotal}:</b> <b>{helper.formatCurrency(order.grand_total, settings)}</b> </div> </div> </div> </div> ); } return <div className="has-text-centered">{text.cartEmpty}</div>; }; CheckoutSuccess.propTypes = { order: PropTypes.shape({}), settings: PropTypes.shape({}).isRequired, pageDetails: PropTypes.shape({}).isRequired, shippingMethod: PropTypes.shape({}).isRequired, checkoutFields: PropTypes.arrayOf(PropTypes.shape({})).isRequired }; CheckoutSuccess.defaultProps = { order: null }; export default CheckoutSuccess;
src/svg-icons/maps/place.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsPlace = (props) => ( <SvgIcon {...props}> <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/> </SvgIcon> ); MapsPlace = pure(MapsPlace); MapsPlace.displayName = 'MapsPlace'; export default MapsPlace;
src/Watermark.js
quantfive/DotDotDotLoader
/*** * watermark of deployed by helloDeploy */ import React from 'react' import './Watermark.css' export default class Watermark extends React.Component { render() { return ( <a href='https://www.hellodeploy.com' target='_blank' rel="noopener noreferrer"> <div className='watermark'> Deployed by <span className='hello'>Hello</span><span className='deploy'>Deploy</span> </div> </a> ) } }
src/components/BleedContainer/index.js
deltaidea/planning-app
import React from 'react'; export default props => <div {...props} style={{ display: 'flex', flex: 1 }}>{props.children}</div>;
src/svg-icons/notification/mms.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationMms = (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-2zM5 14l3.5-4.5 2.5 3.01L14.5 8l4.5 6H5z"/> </SvgIcon> ); NotificationMms = pure(NotificationMms); NotificationMms.displayName = 'NotificationMms'; NotificationMms.muiName = 'SvgIcon'; export default NotificationMms;
routes/Statistic/components/Card/Title.js
YongYuH/Ludo
import React from 'react'; import styled from 'styled-components'; const Wrapper = styled.div` font-weight: bold; margin: 10px 0; `; const Title = () => ( <Wrapper> DIY月餅挑戰 </Wrapper> ); export default Title;
src/TextdomainContext.js
eugene-manuilov/react-gettext
import React from 'react'; import buildTextdomain from './buildTextdomain'; const TextdomainContext = React.createContext(buildTextdomain({}, 'n != 1')); export default TextdomainContext;
app/javascript/mastodon/features/account_gallery/components/media_item.js
ambition-vietnam/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import Permalink from '../../../components/permalink'; import { displaySensitiveMedia } from '../../../initial_state'; export default class MediaItem extends ImmutablePureComponent { static propTypes = { media: ImmutablePropTypes.map.isRequired, }; state = { visible: !this.props.media.getIn(['status', 'sensitive']) || displaySensitiveMedia, }; handleClick = () => { if (!this.state.visible) { this.setState({ visible: true }); return true; } return false; } render () { const { media } = this.props; const { visible } = this.state; const status = media.get('status'); const focusX = media.getIn(['meta', 'focus', 'x']); const focusY = media.getIn(['meta', 'focus', 'y']); const x = ((focusX / 2) + .5) * 100; const y = ((focusY / -2) + .5) * 100; const style = {}; let label, icon; if (media.get('type') === 'gifv') { label = <span className='media-gallery__gifv__label'>GIF</span>; } if (visible) { style.backgroundImage = `url(${media.get('preview_url')})`; style.backgroundPosition = `${x}% ${y}%`; } else { icon = ( <span className='account-gallery__item__icons'> <i className='fa fa-eye-slash' /> </span> ); } return ( <div className='account-gallery__item'> <Permalink to={`/statuses/${status.get('id')}`} href={status.get('url')} style={style} onInterceptClick={this.handleClick}> {icon} {label} </Permalink> </div> ); } }
src/utils/ValidComponentChildren.js
chilts/react-bootstrap
import React from 'react'; /** * Maps children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The mapFunction provided index will be normalised to the components mapped, * so an invalid component would not increase the index. * * @param {?*} children Children tree container. * @param {function(*, int)} mapFunction. * @param {*} mapContext Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapValidComponents(children, func, context) { let index = 0; return React.Children.map(children, function (child) { if (React.isValidElement(child)) { let lastIndex = index; index++; return func.call(context, child, lastIndex); } return child; }); } /** * Iterates through children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc. * @param {*} forEachContext Context for forEachContext. */ function forEachValidComponents(children, func, context) { let index = 0; return React.Children.forEach(children, function (child) { if (React.isValidElement(child)) { func.call(context, child, index); index++; } }); } /** * Count the number of "valid components" in the Children container. * * @param {?*} children Children tree container. * @returns {number} */ function numberOfValidComponents(children) { let count = 0; React.Children.forEach(children, function (child) { if (React.isValidElement(child)) { count++; } }); return count; } /** * Determine if the Child container has one or more "valid components". * * @param {?*} children Children tree container. * @returns {boolean} */ function hasValidComponent(children) { let hasValid = false; React.Children.forEach(children, function (child) { if (!hasValid && React.isValidElement(child)) { hasValid = true; } }); return hasValid; } export default { map: mapValidComponents, forEach: forEachValidComponents, numberOf: numberOfValidComponents, hasValidComponent };
app/containers/NotFoundPage/index.js
frascata/vivaifrappi
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
src/components/Feed.js
wind85/waterandboards
import React from 'react' import ReactDOM from 'react-dom' import PropTypes from 'prop-types' import IconButton from 'material-ui/IconButton' import InfiniteScroll from 'react-infinite-scroller' import PostedItem from '../components/PostedItem.js'; import ActionViewModule from 'material-ui/svg-icons/action/view-module' class Feed extends React.Component { render(){ let dimensions, styles let feed = this.props.feed switch(feed.cols){ case 3: styles = {...FeedStyles.size, width: 1140} break case 2: styles = {...FeedStyles.size, width: 1080} break case 1: styles = {...FeedStyles.size, width: 720} break default: styles = {...FeedStyles.size, width: 720} } const items = [] for(let idx = 0; idx < feed.list.length; idx++){ items.push ( <div key={idx} style={FeedStyles.tile}> <PostedItem index={idx} size={feed.size} videoId={feed.list[idx].videoId} itemChips={feed.list[idx].itemChips} cardHeader={feed.list[idx].cardHeader} /> </div> ) } return( <div> <IconButton tooltip="change view" style={FeedStyles.views} onTouchTap={this.props.hChangeView} > <ActionViewModule /> </IconButton> <div style={FeedStyles.root}> <InfiniteScroll pageStart={0} loadMore={() => { return false }} hasMore={false} useWindow={true} > {items} </InfiniteScroll> </div> </div> ) } } Feed.propTypes = { feed: PropTypes.object.isRequired, hChangeView: PropTypes.func.isRequired, } const FeedStyles = { tile: { margin: 5, height: 'auto', }, size : { marginTop: 20, width: 720, overflowY: 'auto', }, root: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-around', }, views: { height: 25, marginTop: 100, marginLeft: "90%", zIndex: 1, }, } export default Feed
src/Slide.js
react-materialize/react-materialize
import React from 'react'; import PropTypes from 'prop-types'; const Slide = ({ image, children }) => ( <li> {image} {children} </li> ); Slide.propTypes = { className: PropTypes.string, children: PropTypes.node, /** * The image that will be used in the Slide */ image: PropTypes.node.isRequired }; export default Slide;
src/svg-icons/image/photo-library.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImagePhotoLibrary = (props) => ( <SvgIcon {...props}> <path d="M22 16V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2zm-11-4l2.03 2.71L16 11l4 5H8l3-4zM2 6v14c0 1.1.9 2 2 2h14v-2H4V6H2z"/> </SvgIcon> ); ImagePhotoLibrary = pure(ImagePhotoLibrary); ImagePhotoLibrary.displayName = 'ImagePhotoLibrary'; ImagePhotoLibrary.muiName = 'SvgIcon'; export default ImagePhotoLibrary;
actor-apps/app-web/src/app/components/DialogSection.react.js
Jaeandroid/actor-platform
import _ from 'lodash'; import React from 'react'; import { PeerTypes } from 'constants/ActorAppConstants'; import MessagesSection from 'components/dialog/MessagesSection.react'; import TypingSection from 'components/dialog/TypingSection.react'; import ComposeSection from 'components/dialog/ComposeSection.react'; import DialogStore from 'stores/DialogStore'; import MessageStore from 'stores/MessageStore'; import GroupStore from 'stores/GroupStore'; import DialogActionCreators from 'actions/DialogActionCreators'; // On which scrollTop value start loading older messages const LoadMessagesScrollTop = 100; const initialRenderMessagesCount = 20; const renderMessagesStep = 20; let renderMessagesCount = initialRenderMessagesCount; let lastPeer = null; let lastScrolledFromBottom = 0; const getStateFromStores = () => { const messages = MessageStore.getAll(); let messagesToRender; if (messages.length > renderMessagesCount) { messagesToRender = messages.slice(messages.length - renderMessagesCount); } else { messagesToRender = messages; } return { peer: DialogStore.getSelectedDialogPeer(), messages: messages, messagesToRender: messagesToRender }; }; class DialogSection extends React.Component { constructor(props) { super(props); this.state = getStateFromStores(); DialogStore.addSelectListener(this.onSelectedDialogChange); MessageStore.addChangeListener(this.onMessagesChange); } componentWillUnmount() { DialogStore.removeSelectListener(this.onSelectedDialogChange); MessageStore.removeChangeListener(this.onMessagesChange); } componentDidUpdate() { this.fixScroll(); this.loadMessagesByScroll(); } render() { const peer = this.state.peer; if (peer) { let isMember = true; let memberArea; if (peer.type === PeerTypes.GROUP) { const group = GroupStore.getGroup(peer.id); isMember = DialogStore.isGroupMember(group); } if (isMember) { memberArea = ( <div> <TypingSection/> <ComposeSection peer={this.state.peer}/> </div> ); } else { memberArea = ( <section className="compose compose--disabled row center-xs middle-xs"> <h3>You are not member</h3> </section> ); } return ( <section className="dialog" onScroll={this.loadMessagesByScroll}> <MessagesSection messages={this.state.messagesToRender} peer={this.state.peer} ref="MessagesSection"/> {memberArea} </section> ); } else { return ( <section className="dialog dialog--empty row middle-xs center-xs"> Select dialog or start a new one. </section> ); } } fixScroll = () => { if (lastPeer !== null ) { let node = React.findDOMNode(this.refs.MessagesSection); node.scrollTop = node.scrollHeight - lastScrolledFromBottom; } } onSelectedDialogChange = () => { renderMessagesCount = initialRenderMessagesCount; if (lastPeer != null) { DialogActionCreators.onConversationClosed(lastPeer); } lastPeer = DialogStore.getSelectedDialogPeer(); DialogActionCreators.onConversationOpen(lastPeer); } onMessagesChange = _.debounce(() => { this.setState(getStateFromStores()); }, 10, {maxWait: 50, leading: true}); loadMessagesByScroll = _.debounce(() => { if (lastPeer !== null ) { let node = React.findDOMNode(this.refs.MessagesSection); let scrollTop = node.scrollTop; lastScrolledFromBottom = node.scrollHeight - scrollTop; if (node.scrollTop < LoadMessagesScrollTop) { DialogActionCreators.onChatEnd(this.state.peer); if (this.state.messages.length > this.state.messagesToRender.length) { renderMessagesCount += renderMessagesStep; if (renderMessagesCount > this.state.messages.length) { renderMessagesCount = this.state.messages.length; } this.setState(getStateFromStores()); } } } }, 5, {maxWait: 30}); } export default DialogSection;
src/svg-icons/action/all-out.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAllOut = (props) => ( <SvgIcon {...props}> <path d="M16.21 4.16l4 4v-4zm4 12l-4 4h4zm-12 4l-4-4v4zm-4-12l4-4h-4zm12.95-.95c-2.73-2.73-7.17-2.73-9.9 0s-2.73 7.17 0 9.9 7.17 2.73 9.9 0 2.73-7.16 0-9.9zm-1.1 8.8c-2.13 2.13-5.57 2.13-7.7 0s-2.13-5.57 0-7.7 5.57-2.13 7.7 0 2.13 5.57 0 7.7z"/> </SvgIcon> ); ActionAllOut = pure(ActionAllOut); ActionAllOut.displayName = 'ActionAllOut'; export default ActionAllOut;
src/svg-icons/hardware/memory.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareMemory = (props) => ( <SvgIcon {...props}> <path d="M15 9H9v6h6V9zm-2 4h-2v-2h2v2zm8-2V9h-2V7c0-1.1-.9-2-2-2h-2V3h-2v2h-2V3H9v2H7c-1.1 0-2 .9-2 2v2H3v2h2v2H3v2h2v2c0 1.1.9 2 2 2h2v2h2v-2h2v2h2v-2h2c1.1 0 2-.9 2-2v-2h2v-2h-2v-2h2zm-4 6H7V7h10v10z"/> </SvgIcon> ); HardwareMemory = pure(HardwareMemory); HardwareMemory.displayName = 'HardwareMemory'; HardwareMemory.muiName = 'SvgIcon'; export default HardwareMemory;
src/components/partials/top.js
mangal49/HORECA
import React, { Component } from 'react'; class Top extends Component { render() { return ( <div > xxxxx </div> ); } } export default Top;
src/components/game.js
koscelansky/Dama
import React from 'react' import { useSelector } from 'react-redux' import Container from 'react-bootstrap/Container' import Row from 'react-bootstrap/Row' import Col from 'react-bootstrap/Col' import MoveSelector from '../containers/move-selector' import Footer from '../containers/footer' import Player from '../containers/player' import WelcomeDlg from '../containers/welcome-dlg' import History from '../features/history' import { GlobalState } from '../reducers/consts' const Game = () => { const showWelcome = useSelector(state => state.globalState === GlobalState.New) return ( <> <WelcomeDlg show={showWelcome} /> <Container> <Row> <Col> <Player color='white' /> </Col> <Col> <Player color='black' right /> </Col> </Row> <Row> <Col className='px-0'> <MoveSelector /> </Col> <Col sm='3' className='pr-0 pl-1'> <History /> </Col> </Row> <Row> <Col className='px-0'> <Footer /> </Col> </Row> </Container> </> ) } export default Game
src/react/panels/panels.js
pivotal-cf/pivotal-ui
import React from 'react'; import {Grid, FlexCol} from '../flex-grids'; import PropTypes from 'prop-types'; import classnames from 'classnames'; export class Panel extends React.Component { static propTypes = { title: PropTypes.string, titleCols: PropTypes.array, titleClassName: PropTypes.string, panelClassName: PropTypes.string, header: PropTypes.node, headerCols: PropTypes.array, headerClassName: PropTypes.string, loading: PropTypes.bool, bodyClassName: PropTypes.string, footer: PropTypes.node, footerClassName: PropTypes.string }; static defaultProps = { titleCols: [], headerCols: [] }; componentDidMount() { require('../../css/panels'); require('../../css/box-shadows'); } render() { const {className, title, titleCols, titleClassName, panelClassName, header, headerCols, headerClassName, bodyClassName, loading, children, footer, footerClassName, ...props} = this.props; return ( <section {...{...props, className: classnames('pui-panel-container', className)}}> {(title || titleCols.length > 0) && <Grid className={classnames('pui-panel-title', titleClassName)}> {title && <FlexCol contentAlignment="middle" className="h5 em-high type-ellipsis">{title}</FlexCol>} {titleCols.map((el, key) => React.cloneElement(el, {key}))} </Grid>} <div {...{className: classnames('pui-panel bg-white box-shadow-1 border-rounded', panelClassName)}}> {loading && ( <div className="pui-panel-loading-indicator-container"> <div className="pui-panel-loading-indicator" /> </div> )} {(header || headerCols.length > 0) && <Grid className={classnames('pui-panel-header', headerClassName)}> {header && <FlexCol contentAlignment="middle" className="type-ellipsis em-high">{header}</FlexCol>} {headerCols.map((el, key) => React.cloneElement(el, {key}))} </Grid>} {children && ( <div className={classnames('pui-panel-body', bodyClassName)}> {children} </div> )} {footer && <div className={classnames('pui-panel-footer type-ellipsis h6', footerClassName)}>{footer}</div>} </div> </section> ); } }
src/propTypes/colSizeType.js
react-fabric/react-fabric
import React from 'react' export const COL_SIZES = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ] export default React.PropTypes.oneOf(COL_SIZES)
demo/components/ParseInput.js
technicallyfeasible/dataparser
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import DataParser from '../../src/DataParser'; import Context from '../../src/PatternContext'; export default class DataParserTest extends Component { static propTypes = { parser: PropTypes.instanceOf(DataParser), }; static defaultProps = { parser: null, }; constructor() { super(); this.state = { stats: {}, results: [], reasons: [], showReasons: false, reasonDetails: {}, }; } onChange(e) { const value = e.target.value; window.setTimeout(() => { this.parseInput(value); }, 0); } parseInput(text) { const { parser } = this.props; const start = new Date().getTime(); const context = new Context({ reasons: true, }); const result = parser.parse(text, context); const parse = new Date().getTime() - start; this.setState({ results: result.values, reasons: result.reasons, stats: { parse, }, }); } toggleShowReasons() { this.setState({ showReasons: !this.state.showReasons }); } toggleReasonDetails(index) { this.setState({ reasonDetails: { ...this.state.reasonDetails, [index]: !this.state.reasonDetails[index], }, }); } render() { const { parser } = this.props; const { stats, results, reasons, showReasons } = this.state; if (!parser) { return null; } let resultElements = ''; if (results && results.length > 0) { resultElements = results.map((result, index) => { const type = result.constructor.name; /* eslint-disable react/no-array-index-key */ return ( <div key={index}> <span className="label label-primary">{ type }</span> { JSON.stringify(result) } </div> ); /* eslint-enable */ }); } let reasonElements = ''; if (reasons && reasons.length > 0 && showReasons) { // flatten reasons const flatReasons = []; reasons.forEach(reason => { const { token, token: { pos }, patterns, result } = reason; patterns.forEach(patternInfo => { const { pattern, isReachable } = patternInfo; let finalPos = pos; if (result) { finalPos = token.exactMatch ? pos + token.value.length : pattern.indexOf('}', pos) + 1; } flatReasons.push({ // advance position beyond the current token if it was still successful pos: finalPos, pattern, isReachable, reasons: reason.reasons, }); }); }); // sort by success first flatReasons.sort((a, b) => { if (a.isReachable && !b.isReachable) return -1; if (!a.isReachable && b.isReachable) return 1; if (a.pos !== b.pos) { return b.pos - a.pos; } return a.pattern.localeCompare(b.pattern); }); // output paths with match position reasonElements = flatReasons.map((patternInfo, index) => { const { pos, isReachable, pattern, reasons: patternReasons } = patternInfo; let texts; if (isReachable) { // whole pattern was successful texts = [ pattern, ]; } else { texts = [ pattern.substring(0, pos), pattern.substring(pos), ]; } const showDetails = this.state.reasonDetails[index]; return ( // eslint-disable-next-line react/no-array-index-key <div key={index}> <button className="btn btn-link" onClick={() => this.toggleReasonDetails(index)}> <span style={{ color: 'green' }}>{ texts[0] }</span> { texts[1] ? <span style={{ color: 'red' }}>{ texts[1] }</span> : null } </button> { !showDetails ? null : <div>{ JSON.stringify(patternReasons, null, 2) }</div> } </div> ); }); } return ( <div className="parse-input"> <div className="inputs"> <div className="panel panel-showcase"> <div className="panel-heading"> <h3 className="panel-title">Type some text to analyse it</h3> </div> <div className="panel-body"> <textarea type="text" className="form-control" onChange={e => this.onChange(e)} /> </div> </div> <div className="panel panel-showcase"> <div className="panel-heading"> <h3 className="panel-title">Results{ typeof stats.parse === 'number' ? `: ${stats.parse}ms` : '' }</h3> </div> <div className="panel-body">{ resultElements }</div> </div> </div> <div className="row"> <div className="col col-xs-12"> <h3> Reasons{ reasons ? `: ${reasons.length}` : '' } <button className="btn btn-link" onClick={() => this.toggleShowReasons()}> { showReasons ? 'hide' : 'show' } </button> </h3> <pre>{ reasonElements }</pre> </div> </div> </div> ); } }
blueocean-material-icons/src/js/components/svg-icons/action/flight-takeoff.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionFlightTakeoff = (props) => ( <SvgIcon {...props}> <path d="M2.5 19h19v2h-19zm19.57-9.36c-.21-.8-1.04-1.28-1.84-1.06L14.92 10l-6.9-6.43-1.93.51 4.14 7.17-4.97 1.33-1.97-1.54-1.45.39 1.82 3.16.77 1.33 1.6-.43 5.31-1.42 4.35-1.16L21 11.49c.81-.23 1.28-1.05 1.07-1.85z"/> </SvgIcon> ); ActionFlightTakeoff.displayName = 'ActionFlightTakeoff'; ActionFlightTakeoff.muiName = 'SvgIcon'; export default ActionFlightTakeoff;
component-starter-server/src/main/frontend/src/app/components/DatasetList/DatasetList.component.js
chmyga/component-runtime
/** * Copyright (C) 2006-2020 Talend Inc. - www.talend.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */import React from 'react'; import { Action } from '@talend/react-components/lib/Actions'; import DatasetContext from '../../DatasetContext'; import DatasetForm from '../DatasetForm'; import theme from './DatasetList.scss'; import DatasetDelete from '../DatasetDelete'; function DatasetList() { return ( <DatasetContext.Consumer> {dataset => ( <div className={theme.container}> <div className={theme.column}> <h2>Dataset</h2> <Action id={`${theme['add-new-dataset']}`} label="Add new Dataset" bsStyle="info" icon="talend-plus-circle" onClick={() => { dataset.setCurrent(); }} /> {dataset.datasets.length === 0 && ( <div className="alert alert-warning"> <div> <p>No dataset found.</p> <p> Datasets are required in many cases. They define the way to take data throw a datastore. </p> <p>You should define at least one dataset to get data from a datastore.</p> <p>In the case of JDBC, the dataset is a SQL query.</p> </div> </div> )} <ul> {dataset.datasets.map((d, index) => ( <li key={index} className={theme.li}> <Action bsStyle="link" onClick={() => dataset.setCurrent(d)} label={d.name} /> <DatasetDelete item={d} /> </li> ))} </ul> </div> <div className={theme.column}> <DatasetForm dataset={dataset.current} className={theme.column} /> </div> </div> )} </DatasetContext.Consumer> ); } DatasetList.displayName = 'DatasetList'; DatasetList.propTypes = {}; export default DatasetList;
scripts/src/pages/views/dashboard.js
Twogether/just-meet-frontend
import React from 'react'; import Helmet from 'react-helmet'; import { Link } from 'react-router'; import Moment from 'react-moment'; import BigCalendar from 'react-big-calendar'; export default (self) => { return ( <div> <Helmet title="Just Meet | Meeting List" /> <div className="left quarter"> <nav className="side-nav"> <ul> {self.state.menu.map((link, index) => { return ( <li key={index}> <Link to={link.path}><i className={'fa fa-' + link.icon} aria-hidden="true"></i> {link.text}</Link> <ul className="sub-menu"> {link.children && link.children.map((link, index) => { return ( <li key={`child-${index}`}><Link to={link.path}><i className={'fa fa-' + link.icon} aria-hidden="true"></i> {link.text}</Link></li> ); })} </ul> </li> ); })} </ul> </nav> </div> <div className="three-quarters right white-bg padding-medium"> <div className="container"> <h2>Calendar</h2> <BigCalendar events={self.state.events} /> </div> </div> </div> ); };
src/parser/mage/shared/modules/features/MirrorImage.js
FaideWW/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import TalentStatisticBox, { STATISTIC_ORDER } from 'interface/others/TalentStatisticBox'; import Analyzer from 'parser/core/Analyzer'; const INCANTERS_FLOW_EXPECTED_BOOST = 0.12; class MirrorImage extends Analyzer { // all images summoned by player seem to have the same sourceID, and vary only by instanceID mirrorImagesId; damage = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.MIRROR_IMAGE_TALENT.id); } on_byPlayer_summon(event) { // there are a dozen different Mirror Image summon IDs which is used where or why... this is the easy way out if(event.ability.name === SPELLS.MIRROR_IMAGE_SUMMON.name) { this.mirrorImagesId = event.targetID; } } on_byPlayerPet_damage(event) { if(this.mirrorImagesId === event.sourceID) { this.damage += event.amount + (event.absorbed || 0); } } get damagePercent() { return this.owner.getPercentageOfTotalDamageDone(this.damage); } get damageIncreasePercent() { return this.damagePercent / (1 - this.damagePercent); } get damageSuggestionThresholds() { return { actual: this.damageIncreasePercent, isLessThan: { minor: INCANTERS_FLOW_EXPECTED_BOOST, average: INCANTERS_FLOW_EXPECTED_BOOST, major: INCANTERS_FLOW_EXPECTED_BOOST - 0.03, }, style: 'percentage', }; } suggestions(when) { when(this.damageSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>Your <SpellLink id={SPELLS.MIRROR_IMAGE_TALENT.id} /> damage is below the expected passive gain from <SpellLink id={SPELLS.INCANTERS_FLOW_TALENT.id} />. Consider switching to <SpellLink id={SPELLS.INCANTERS_FLOW_TALENT.id} />.</>) .icon(SPELLS.MIRROR_IMAGE_TALENT.icon) .actual(`${formatPercentage(this.damageIncreasePercent)}% damage increase from Mirror Image`) .recommended(`${formatPercentage(recommended)}% is the passive gain from Incanter's Flow`); }); } statistic() { return ( <TalentStatisticBox talent={SPELLS.MIRROR_IMAGE_TALENT.id} position={STATISTIC_ORDER.CORE(100)} value={`${formatPercentage(this.damagePercent)} %`} label="Mirror Image damage" tooltip={`This is the portion of your total damage attributable to Mirror Image. Expressed as an increase vs never using Mirror Image, this is a <b>${formatPercentage(this.damageIncreasePercent)}% damage increase</b>.`} /> ); } } export default MirrorImage;