path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/components/app.js
RobertHebel/ToDoList
import React from 'react'; import TasksTable from './task/tasksTable'; import TaskDetails from './task/taskDetails'; import * as taskActions from '../actions/taskActions'; import NewTaskForm from './task/taskForm'; import TaskFilters from './task/taskFilters'; import Footer from './footer'; import {connect} from 'react-redux'; import {bindActionCreators} from "redux"; class app extends React.Component { constructor(props, context) { super(props, context); this.state = { task: {}, errors: {}, timestamp: new Date() }; this.updateTasks = this.updateTasks.bind(this); this.saveTask = this.saveTask.bind(this); } //update task property when change on the form occurs updateTasks(event) { const field = event.target.name; let task = this.state.task; task[field] = event.target.value; return this.setState({task: task}); } //if task name is too short or category has not been chosen form is invalid taskFormIsValid() { let formIsValid = true; let errors = {}; if (!this.state.task.taskName ||this.state.task.taskName.length < 5){ errors.titleLengthError = 'Title must be at least 5 characters.'; formIsValid = false; } this.setState({errors: errors}); return formIsValid; } //generate unique id number for each task created generateId() { let task = this.state.task; task.done = false; if(!this.props.allTasks.length){ task.id = 0; } else{ let lastTask = this.props.allTasks[this.props.allTasks.length - 1]; task.id = Number(lastTask.id + 1); } this.setState({task: task}); } clearForm() { this.setState({ task: {}, timestamp: new Date() }); } saveTask(event) { event.preventDefault(); this.render(); if(!this.taskFormIsValid()) { return; } this.generateId(); this.clearForm(); this.props.actions.saveTask(this.state.task); //dispatch an action to save task } render () { return ( <div> <div className="container page-wrap"> <h1 className="text-center title">ToDo App</h1> <div className="task-form"> <NewTaskForm key={this.state.timestamp} //timestamp assures that key is unique task={this.state.task} onSave={this.saveTask} onChange={this.updateTasks} errors={this.state.errors} /> </div> <div className="row justify-content-center"> <div className="col-xs-10 col-sm-10 col-md-5 col-lg-5"> <div className="card"> <div className="card-header"> <TaskFilters/> </div> <TasksTable/> </div> </div> <div className="col-xs-10 col-sm-10 col-md-5 col-lg-5"> <TaskDetails/> </div> </div> </div> <div className="site-footer"> <Footer/> </div> </div> ); } } function mapStateToProps(state) { return { currentTask: state.activeTask, allTasks: Object.assign([],state.allTasks), categories: state.allCategories }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(taskActions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(app);
shorterly/src/components/shortener/details.js
daedelus-j/shorterly
'use strict'; import React from 'react'; import cx from 'classnames'; import copy from 'copy-to-clipboard'; import { connect } from 'react-redux'; import { updateDeviceUrl, updateForm, validateDetailsField, updateActiveDevice, showDetailsEditForm, closeDetailsEditForm, copiedUrl, validateField, } from '../../actions/shorterly' import { url_types } from '../../constants' import pvd from '../../general-libs/preventer'; import { isFormValid } from '../../reducers/shorterly/create/validations'; import FormBody from './create/body' const UrlType = ({ type, onSelect, selected, icon_classname }) => { const classNames = cx({ 'url-type': true, 'url-type--active': selected, 'url-type--details': true, center: true, }); const headerClassnames = cx({ 'header--4': true, 'header--4--active': selected, 'spacer--quarter-top': true, center: true, }) return ( <div onClick={pvd(()=>onSelect(type))} className={classNames}> <i className={`fa fa-${icon_classname}`} /> <h3 className={headerClassnames}>{type}</h3> </div> ); } const UrlButtons = ({ selected, onSelect }) => { return ( <div className='container__inner--spacer'> { url_types.map(type => { return <UrlType onSelect={onSelect} selected={selected === type.type} key={type.type} {...type} /> }) } </div> ); } const UrlDetails = React.createClass({ onChange(props) { const { updateForm, dispatch } = this.props; dispatch(updateForm(props)); }, onSubmit() { const { active_device_model, shortener_details_form, updateDeviceUrl } = this.props; const { url } = shortener_details_form; const { dispatch, validateField } = this.props; if (isFormValid(shortener_details_form)) { dispatch( updateDeviceUrl(active_device_model, url) ); } else { dispatch(validateField({ field_key: 'url', field_value: url })); } }, onSelect(type) { const { shortener_details_form, dispatch, updateActiveDevice } = this.props; if (shortener_details_form.form_active) return; dispatch(updateActiveDevice(type)) }, showForm() { const { dispatch, showDetailsEditForm } = this.props; dispatch(showDetailsEditForm()); }, closeForm() { const { dispatch, closeDetailsEditForm } = this.props; dispatch(closeDetailsEditForm()); }, onCopy() { const { active_device_model, copiedText, dispatch, synced_url, } = this.props; const { short_url } = synced_url; dispatch(copiedUrl()); copy(short_url); }, render() { const { shortener_details_form, synced_url_desktop, synced_url_mobile, synced_url_tablet, active_device_model, copied_url, synced_url, } = this.props; const devices = { synced_url_desktop, synced_url_mobile, synced_url_tablet, }; const { short_url } = synced_url; const { selected_device, form_active, } = shortener_details_form; const { url, visits, url_id, url_domain, } = active_device_model; const urlCopiedClassnames = cx({ 'url-copied': true, 'url-copied--active': copied_url.active, }); const body = form_active ? <div> <FormBody label={`Url`} form={shortener_details_form} {...this.props} onChange={this.onChange} onSubmit={this.onSubmit} /> <div className='actions--right'> <a onClick={pvd(this.closeForm)} className='btn--sm btn btn--shorten spacer--quarter-right' href='#'>Cancel</a> <a onClick={pvd(this.onSubmit)} className='btn--sm btn--primary btn--shorten' href='#'>Update</a> </div> </div> : <div className='edit-cont'> <div className='header--4 spacer--quarter-bottom'>Redirect Url</div> <div className='float-r'> <a onClick={this.showForm} className='btn--primary btn--icon'> <i className='fa fa-pencil' /> </a> </div> <div className='edit-placeholder'> {url} </div> </div> return ( <div className='container__inner'> <div className='spacer center'> <h1 className='header--1 spacer--half-bottom'>SHORTERLY</h1> <h2 className='header--2'>Your favorite url shortener</h2> </div> <div className='container--raised'> <div className='center clipboard spacer--half-bottom'> <div className='header--4 spacer--quarter-bottom'>Total Visits: {synced_url.total_visits}</div> Shortened Url: <br/> <span className='clipboard__url header--2'>{short_url}</span> <a onClick={pvd(this.onCopy)} className='spacer--quarter-top spacer--quarter-right btn--sm btn--primary'> Copy </a> <div className={urlCopiedClassnames}>Copied!</div> </div> <div className='btn-cont spacer--bottom btn-cont--details'> <h3 className='header--3 spacer--half-bottom'>{selected_device}</h3> <div className='header--4 spacer--half-bottom'>Visits: <b>{visits}</b></div> {body} </div> <UrlButtons onSelect={this.onSelect} selected={selected_device} /> </div> </div> ); } }); const mapStateToProps = ({ form_global_errors, form_validations, shortener_details_form, synced_url_desktop, synced_url_mobile, synced_url_tablet, copied_url, synced_url, }) => { const devices = { synced_url_desktop, synced_url_mobile, synced_url_tablet, }; const { selected_device } = shortener_details_form; const active_device_model = devices[`synced_url_${selected_device.toLowerCase()}`]; return { // reducers form_global_errors, form_validations, shortener_details_form, synced_url_desktop, synced_url_mobile, synced_url_tablet, active_device_model, synced_url, copied_url, // actions updateForm, validateDetailsField, updateDeviceUrl, updateActiveDevice, showDetailsEditForm, closeDetailsEditForm, copiedUrl, validateField }; }; export default connect(mapStateToProps)(UrlDetails);
demos/demo/src/components/Notification/index.js
FWeinb/cerebral
import React from 'react' import {connect} from 'cerebral/react' import {signal, state} from 'cerebral/tags' import translations from '../../common/computed/translations' export default connect( { dismiss: signal`app.dismissNotificationClicked`, error: state`app.$error`, t: translations }, function Notification ({dismiss, error, t}) { if (error) { return ( <div className='notification is-warning'> <button className='delete' onClick={() => dismiss()} /> {error} </div> ) } else { return null } } )
app/components/ToggleOption/index.js
Third9/mark-one
/** * * ToggleOption * */ import React from 'react'; import { injectIntl, intlShape } from 'react-intl'; const ToggleOption = ({ value, message, intl }) => ( <option value={value}> {message ? intl.formatMessage(message) : value} </option> ); ToggleOption.propTypes = { value: React.PropTypes.string.isRequired, message: React.PropTypes.object, intl: intlShape.isRequired, }; export default injectIntl(ToggleOption);
react/comments/src/CommentBox.js
sabertazimi/st-proj
import React from 'react'; import CommentList from './CommentList'; import CommentForm from './CommentForm'; export default class CommentBox extends React.Component { constructor(props, context) { super(props, context); this.state = { data: [ { id: 1, author: 'sabertazimi', text: 'Hello React' } ] }; this.handleCommentSubmit = this.handleCommentSubmit.bind(this); } handleCommentSubmit(comment) { comment.id = Date.now(); const comments = this.state.data; const newComments = comments.concat([comment]); this.setState({ data: newComments }); } render() { return ( <div className="commentBox"> <h1>Comments</h1> <CommentList data={this.state.data}/> <CommentForm onCommentSubmit={this.handleCommentSubmit}/> </div> ); } }
react-flux-mui/js/material-ui/docs/src/app/components/pages/components/IconMenu/ExampleScrollable.js
pbogdan/react-flux-mui
import React from 'react'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import IconButton from 'material-ui/IconButton'; import MapsPlace from 'material-ui/svg-icons/maps/place'; /** * The `maxHeight` property limits the height of the menu, above which it will be scrollable. */ const IconMenuExampleScrollable = () => ( <IconMenu iconButtonElement={<IconButton><MapsPlace /></IconButton>} anchorOrigin={{horizontal: 'left', vertical: 'top'}} targetOrigin={{horizontal: 'left', vertical: 'top'}} maxHeight={272} > <MenuItem value="AL" primaryText="Alabama" /> <MenuItem value="AK" primaryText="Alaska" /> <MenuItem value="AZ" primaryText="Arizona" /> <MenuItem value="AR" primaryText="Arkansas" /> <MenuItem value="CA" primaryText="California" /> <MenuItem value="CO" primaryText="Colorado" /> <MenuItem value="CT" primaryText="Connecticut" /> <MenuItem value="DE" primaryText="Delaware" /> <MenuItem value="DC" primaryText="District Of Columbia" /> <MenuItem value="FL" primaryText="Florida" /> <MenuItem value="GA" primaryText="Georgia" /> <MenuItem value="HI" primaryText="Hawaii" /> <MenuItem value="ID" primaryText="Idaho" /> <MenuItem value="IL" primaryText="Illinois" /> <MenuItem value="IN" primaryText="Indiana" /> <MenuItem value="IA" primaryText="Iowa" /> <MenuItem value="KS" primaryText="Kansas" /> <MenuItem value="KY" primaryText="Kentucky" /> <MenuItem value="LA" primaryText="Louisiana" /> <MenuItem value="ME" primaryText="Maine" /> <MenuItem value="MD" primaryText="Maryland" /> <MenuItem value="MA" primaryText="Massachusetts" /> <MenuItem value="MI" primaryText="Michigan" /> <MenuItem value="MN" primaryText="Minnesota" /> <MenuItem value="MS" primaryText="Mississippi" /> <MenuItem value="MO" primaryText="Missouri" /> <MenuItem value="MT" primaryText="Montana" /> <MenuItem value="NE" primaryText="Nebraska" /> <MenuItem value="NV" primaryText="Nevada" /> <MenuItem value="NH" primaryText="New Hampshire" /> <MenuItem value="NJ" primaryText="New Jersey" /> <MenuItem value="NM" primaryText="New Mexico" /> <MenuItem value="NY" primaryText="New York" /> <MenuItem value="NC" primaryText="North Carolina" /> <MenuItem value="ND" primaryText="North Dakota" /> <MenuItem value="OH" primaryText="Ohio" /> <MenuItem value="OK" primaryText="Oklahoma" /> <MenuItem value="OR" primaryText="Oregon" /> <MenuItem value="PA" primaryText="Pennsylvania" /> <MenuItem value="RI" primaryText="Rhode Island" /> <MenuItem value="SC" primaryText="South Carolina" /> <MenuItem value="SD" primaryText="South Dakota" /> <MenuItem value="TN" primaryText="Tennessee" /> <MenuItem value="TX" primaryText="Texas" /> <MenuItem value="UT" primaryText="Utah" /> <MenuItem value="VT" primaryText="Vermont" /> <MenuItem value="VA" primaryText="Virginia" /> <MenuItem value="WA" primaryText="Washington" /> <MenuItem value="WV" primaryText="West Virginia" /> <MenuItem value="WI" primaryText="Wisconsin" /> <MenuItem value="WY" primaryText="Wyoming" /> </IconMenu> ); export default IconMenuExampleScrollable;
public/src/redux/todos/components/App.js
codelegant/react-action
/** * Author: 赖传峰 * Email: laichuanfeng@hotmail.com * Homepage: http://laichuanfeng.com/ * Date: 2016/7/18 */ import React from 'react'; import Footer from './Footer'; import AddTodo from '../containers/AddTodo'; import VisibleTodoList from '../containers/VisibleTodoList'; const App = () => ( <div ref={() => console.log('App')}> <AddTodo /> <VisibleTodoList /> <Footer /> </div> ); export default App;
src/components/Elements/IFrame/index.js
jmikrut/keen-2017
import React from 'react'; import './IFrame.css'; export default (props) => { const className = props.className ? `iframe ${props.className}` : 'iframe'; return ( <div className={className}> <iframe width="16" height="9" title={props.title} src={props.src} frameBorder="0" allowFullScreen /> </div> ); }
packages/icons/src/md/device/Bluetooth.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdBluetooth(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M36.41 15.41L27.83 24l8.58 8.59L25 44h-2V28.83L13.83 38 11 35.17 22.17 24 11 12.83 13.83 10 23 19.17V4h2l11.41 11.41zM27 11.66v7.51l3.76-3.75L27 11.66zm3.76 20.93L27 28.82v7.52l3.76-3.75z" /> </IconBase> ); } export default MdBluetooth;
src-changed/Watch.js
aryalprakash/omgyoutube
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Router, Route, Link, browserHistory } from 'react-router'; import {getVideoData, getChannelVideos, getRelatedVideos} from './actions/video.js' import Header from './Header.js' import Loader from './Loader.js' class Watch extends Component { constructor(){ super() this.state = { videoData: null, title: null, url : null, uploader : null, thumbnail : null, download_button : null, formats : null, format_list : null, views : null } } componentWillMount(){ this.props.dispatch(getRelatedVideos(this.props.routeParams.videoID)); this.props.dispatch(getVideoData(this.props.routeParams.videoID)); } componentWillUpdate(){ //this.props.dispatch(getRelatedVideos(this.props.routeParams.videoID)); //this.props.dispatch(getVideoData(this.props.routeParams.videoID)); } gotoVideo(videoId){ this.props.dispatch(getRelatedVideos(videoId)); this.props.dispatch(getVideoData(videoId)); this.context.router.push(`/watch/v=${videoId}`); } toggleView = () => { this.setState({ renderSearch: true }) } render() { console.log(this.props); let videoData, title, url, uploader, thumbnail, download_button, formats, format_list, views; //if(this.props.vidinfo && this.props.vidinfo.info){ try { let relatedVideos = this.props.relatedVideos.items; videoData = this.props.vidinfo; url = videoData.url; title = videoData.info.title; uploader = videoData.info.uploader; thumbnail = videoData.info.thumbnail; views = videoData.info.view_count + ' views'; download_button = <a href={videoData.info.url} download ={title+".mp4"}><div className="download-button">Download</div></a>; formats = videoData.info.formats.filter(x=> x.format_id == '18' || x.format_id =='22'); format_list = formats.map(vid => <span className="dwn_format"><a href={vid.url} download={title+"."+vid.ext}>{vid.format_note}</a></span> ) //} const video = this.props.routeParams.videoID; return (<div> <Header toggleView={this.toggleView} /> <div className="transparent"> <div className="left"> <div className="video-details-controller"> <iframe src={'https://www.youtube.com/embed/' + video + '?autoplay=1&rel=0&amp;showinfo=0'} border="none" allowFullScreen></iframe> </div> <div className="video-details white"> <div className="video-details-title">{title}</div> <img className="video-channel-thumb" src={thumbnail} /> <div className="video-info"> <div className="video-channel">{uploader}</div> <div className="download"> {download_button} {format_list} </div> <span className="views">{views}</span> </div> </div> <div className="video-share white"> <div className="share-title">Share</div> <div className="line"></div> <div className="share"> <img src="../img/share.png" /> </div> </div> <div className="video-comments white"> {url} </div> </div> <div className="right white"> <div className="sidebar-video-list"> Recommended <div className="line"></div> { relatedVideos ? relatedVideos.map(video =>{ return(<div> <div className="sidebar-video"> <div className="sidebar-video-thumbnail"> <img src={video.snippet.thumbnails.medium.url} width="100%"/> </div> <div className="sidebar-video-info"> <div className="video-title"> <a className="title-link" onClick={_=> this.gotoVideo(video.id.videoId)}>{video.snippet.title}</a> </div> <div className="video-channel">{video.snippet.channelTitle}</div> </div> </div> <div className="line"></div> </div>) }): null } <div className="get-more" >Show More</div> </div> </div> </div> </div> ) }catch(e){ console.log(e); return(<div> <Header /> <Loader /> </div>) } } } Watch.contextTypes = { router: React.PropTypes.object } const mapStateToProps = ({ vidinfo, relatedVideos }) => ({ vidinfo, relatedVideos }) export default connect(mapStateToProps)( Watch )
examples/huge-apps/routes/Profile/components/Profile.js
arusakov/react-router
import React from 'react'; class Profile extends React.Component { render () { return ( <div> <h2>Profile</h2> </div> ); } } export default Profile;
client/admin/permissions/NewRolePage.js
iiet/iiet-chat
import React from 'react'; import { Box, FieldGroup, ButtonGroup, Button, Margins } from '@rocket.chat/fuselage'; import { useMutableCallback } from '@rocket.chat/fuselage-hooks'; import RoleForm from './RoleForm'; import { useForm } from '../../hooks/useForm'; import { useTranslation } from '../../contexts/TranslationContext'; import { useMethod } from '../../contexts/ServerContext'; import { useToastMessageDispatch } from '../../contexts/ToastMessagesContext'; const NewRolePage = () => { const t = useTranslation(); const dispatchToastMessage = useToastMessageDispatch(); const { values, handlers } = useForm({ name: '', description: '', scope: 'Users', mandatory2fa: false, }); const saveRole = useMethod('authorization:saveRole'); const handleSave = useMutableCallback(async () => { try { await saveRole(values); dispatchToastMessage({ type: 'success', message: t('Saved') }); } catch (error) { dispatchToastMessage({ type: 'error', message: error }); } }); return <Box w='full' alignSelf='center' mb='neg-x8'> <Margins block='x8'> <FieldGroup> <RoleForm values={values} handlers={handlers}/> </FieldGroup> <ButtonGroup stretch w='full'> <Button primary onClick={handleSave}>{t('Save')}</Button> </ButtonGroup> </Margins> </Box>; }; export default NewRolePage;
stories/Carousel.stories.js
reactstrap/reactstrap
import React from 'react'; export default { title: 'Components/Carousel', parameters: { docs: { description: { component: ` [Bootstrap Carousel](https://getbootstrap.com/docs/5.1/components/carousel/) A slideshow component for cycling through elements, images, or slides of text — like a carousel. `, } } } }; export { default as Carousel } from './examples/Carousel'; export { default as CustomTag } from './examples/CarouselCustomTag'; export { default as Uncontrolled } from './examples/CarouselUncontrolled'; export { default as Props } from './examples/CarouselProps';
stories/RichTextArea/index.js
nirhart/wix-style-react
import React from 'react'; import {storiesOf} from '@kadira/storybook'; import InteractiveCodeExample from '../utils/Components/InteractiveCodeExample'; import Markdown from '../utils/Components/Markdown'; import ReadMe from '../../src/RichTextArea/README.md'; import RichTextAreaExample from './RichTextAreaExample'; storiesOf('Core', module) .add('RichTextArea', () => ( <div> <Markdown source={ReadMe}/> <InteractiveCodeExample title="Customize a <RichTextArea/>"> <RichTextAreaExample /> </InteractiveCodeExample> </div> ));
app/components/BottomIndicator.js
yandan66/react-native-maicai
import React from 'react'; import {View, Image, StyleSheet} from 'react-native'; export default class BottomIndicator extends React.Component { constructor(props) { super(props) } render() { const isShow = this.props.show; return (isShow ? <View style={styles.Indicator}> <Image style={styles.IndicatorBg} source={require('../static/bg-bottom.png')}/> </View> : null) } } const styles = StyleSheet.create({ Indicator: { alignItems: 'center', justifyContent: 'center' }, IndicatorBg: { height: 30, resizeMode: 'contain' } })
src/InputBase.js
egauci/react-bootstrap
import classNames from 'classnames'; import React from 'react'; import FormGroup from './FormGroup'; import Glyphicon from './Glyphicon'; class InputBase extends React.Component { getInputDOMNode() { return this.refs.input; } getValue() { if (this.props.type === 'static') { return this.props.value; } else if (this.props.type) { if (this.props.type === 'select' && this.props.multiple) { return this.getSelectedOptions(); } return this.getInputDOMNode().value; } throw new Error('Cannot use getValue without specifying input type.'); } getChecked() { return this.getInputDOMNode().checked; } getSelectedOptions() { let values = []; Array.prototype.forEach.call( this.getInputDOMNode().getElementsByTagName('option'), (option) => { if (option.selected) { let value = option.getAttribute('value') || option.innerHtml; values.push(value); } }); return values; } isCheckboxOrRadio() { return this.props.type === 'checkbox' || this.props.type === 'radio'; } isFile() { return this.props.type === 'file'; } renderInputGroup(children) { let addonBefore = this.props.addonBefore ? ( <span className="input-group-addon" key="addonBefore"> {this.props.addonBefore} </span> ) : null; let addonAfter = this.props.addonAfter ? ( <span className="input-group-addon" key="addonAfter"> {this.props.addonAfter} </span> ) : null; let buttonBefore = this.props.buttonBefore ? ( <span className="input-group-btn"> {this.props.buttonBefore} </span> ) : null; let buttonAfter = this.props.buttonAfter ? ( <span className="input-group-btn"> {this.props.buttonAfter} </span> ) : null; let inputGroupClassName; switch (this.props.bsSize) { case 'small': inputGroupClassName = 'input-group-sm'; break; case 'large': inputGroupClassName = 'input-group-lg'; break; default: } return addonBefore || addonAfter || buttonBefore || buttonAfter ? ( <div className={classNames(inputGroupClassName, 'input-group')} key="input-group"> {addonBefore} {buttonBefore} {children} {addonAfter} {buttonAfter} </div> ) : children; } renderIcon() { if (this.props.hasFeedback) { if (this.props.feedbackIcon) { return React.cloneElement(this.props.feedbackIcon, { formControlFeedback: true }); } switch (this.props.bsStyle) { case 'success': return <Glyphicon formControlFeedback glyph="ok" key="icon" />; case 'warning': return <Glyphicon formControlFeedback glyph="warning-sign" key="icon" />; case 'error': return <Glyphicon formControlFeedback glyph="remove" key="icon" />; default: return <span className="form-control-feedback" key="icon" />; } } else { return null; } } renderHelp() { return this.props.help ? ( <span className="help-block" key="help"> {this.props.help} </span> ) : null; } renderCheckboxAndRadioWrapper(children) { let classes = { 'checkbox': this.props.type === 'checkbox', 'radio': this.props.type === 'radio' }; return ( <div className={classNames(classes)} key="checkboxRadioWrapper"> {children} </div> ); } renderWrapper(children) { return this.props.wrapperClassName ? ( <div className={this.props.wrapperClassName} key="wrapper"> {children} </div> ) : children; } renderLabel(children) { let classes = { 'control-label': !this.isCheckboxOrRadio() }; classes[this.props.labelClassName] = this.props.labelClassName; return this.props.label ? ( <label htmlFor={this.props.id} className={classNames(classes)} key="label"> {children} {this.props.label} </label> ) : children; } renderInput() { if (!this.props.type) { return this.props.children; } switch (this.props.type) { case 'select': return ( <select {...this.props} className={classNames(this.props.className, 'form-control')} ref="input" key="input"> {this.props.children} </select> ); case 'textarea': return <textarea {...this.props} className={classNames(this.props.className, 'form-control')} ref="input" key="input" />; case 'static': return ( <p {...this.props} className={classNames(this.props.className, 'form-control-static')} ref="input" key="input"> {this.props.value} </p> ); default: const className = this.isCheckboxOrRadio() || this.isFile() ? '' : 'form-control'; return <input {...this.props} className={classNames(this.props.className, className)} ref="input" key="input" />; } } renderFormGroup(children) { return <FormGroup {...this.props}>{children}</FormGroup>; } renderChildren() { return !this.isCheckboxOrRadio() ? [ this.renderLabel(), this.renderWrapper([ this.renderInputGroup( this.renderInput() ), this.renderIcon(), this.renderHelp() ]) ] : this.renderWrapper([ this.renderCheckboxAndRadioWrapper( this.renderLabel( this.renderInput() ) ), this.renderHelp() ]); } render() { let children = this.renderChildren(); return this.renderFormGroup(children); } } InputBase.propTypes = { type: React.PropTypes.string, label: React.PropTypes.node, help: React.PropTypes.node, addonBefore: React.PropTypes.node, addonAfter: React.PropTypes.node, buttonBefore: React.PropTypes.node, buttonAfter: React.PropTypes.node, bsSize: React.PropTypes.oneOf(['small', 'medium', 'large']), bsStyle: React.PropTypes.oneOf(['success', 'warning', 'error']), hasFeedback: React.PropTypes.bool, feedbackIcon: React.PropTypes.node, id: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]), groupClassName: React.PropTypes.string, wrapperClassName: React.PropTypes.string, labelClassName: React.PropTypes.string, multiple: React.PropTypes.bool, disabled: React.PropTypes.bool, value: React.PropTypes.any }; InputBase.defaultProps = { disabled: false, hasFeedback: false, multiple: false }; export default InputBase;
src/Form.js
tanbo800/react-ui
'use strict' import React from 'react' import classnames from 'classnames' import { forEach } from './utils/objects' import FormControl from './FormControl' import FormSubmit from './FormSubmit' import { requireCss } from './themes' requireCss('form') export default class Form extends React.Component { static displayName = 'Form' static propTypes = { beforeSubmit: React.PropTypes.func, children: React.PropTypes.any, className: React.PropTypes.string, data: React.PropTypes.oneOfType([ React.PropTypes.object, React.PropTypes.func ]).isRequired, hintType: React.PropTypes.oneOf(['block', 'none', 'pop', 'inline']), layout: React.PropTypes.oneOf(['aligned', 'stacked', 'inline']), onSubmit: React.PropTypes.func, style: React.PropTypes.object } static defaultProps = { data: {}, layout: 'inline' } componentWillMount () { this.fetchData(this.props.data) } componentWillReceiveProps (nextProps) { if (this.props.data !== this.props.data) { this.fetchData(nextProps.data) } } state = { locked: false, data: {} } fetchData (data) { if (typeof data === 'function') { data.then(res => { this.fetchData(res) })() return } this.setState({ data }) this.setData(data) } getValue () { let data = this.state.data forEach(this.refs, (ref, k) => { if (!ref.props.ignore) { data[k] = ref.getValue() } }) return data } setValue (key, value) { let data = this.state.data data[key] = value this.setState({ data }) } setData (data) { forEach(this.refs, (ref, k) => { ref.setValue(data[k]) }) } equalValidate (targetRef, equalRef) { let self = this return function () { let target = self.refs[targetRef] if (!target) { console.warn(`equal target '${targetRef}' not existed`) return false } let equal = self.refs[equalRef] return target.getValue() === equal.getValue() } } renderChildren () { return React.Children.map(this.props.children, child => { let props = { hintType: child.props.hintType || this.props.hintType, readOnly: child.props.readOnly || this.state.locked, layout: this.props.layout } if (child.type === FormControl) { if (!child.props.name) { console.warn('FormControl must have a name!') return null } props.ref = child.props.name if (this.state.data[child.props.name] !== undefined) { props.value = this.state.data[child.props.name] } if (child.props.equal) { props.onValidate = this.equalValidate(child.props.equal, child.props.name) } } else if (child.type === FormSubmit) { props.locked = this.state.locked } child = React.cloneElement(child, props) return child }) } getReference (name) { return this.refs[name] } validate () { let success = true forEach(this.refs, function (child) { if (child.props.ignore) { return } let suc = child.validate() success = success && suc }) return success } handleSubmit (event) { if (this.state.locked) { return } event.preventDefault() this.onSubmit() } onSubmit () { this.setState({ locked: true }) let success = this.validate() if (success && this.props.beforeSubmit) { success = this.props.beforeSubmit() } if (!success) { this.setState({ locked: false }) return } if (this.props.onSubmit) { this.props.onSubmit(this.getValue()) this.setState({ locked: false }) } } render () { let className = classnames( this.props.className, 'rct-form', { 'rct-form-aligned': this.props.layout === 'aligned', 'rct-form-inline': this.props.layout === 'inline', 'rct-form-stacked': this.props.layout === 'stacked' } ) return ( <form onSubmit={this.handleSubmit.bind(this)} style={this.props.style} className={className}> {this.renderChildren()} </form> ) } }
src/index.js
WangCao/react-blog
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import Router from './router/Route.jsx' // css import './style/base.less'; import './style/header.less'; ReactDOM.render(<Router />, document.getElementById('root')); registerServiceWorker();
web/src/js/components/Widget/EditWidgetChip.js
gladly-team/tab
import React from 'react' import PropTypes from 'prop-types' import Measure from 'react-measure' import Paper from 'material-ui/Paper' import DeleteIcon from 'material-ui/svg-icons/navigation/cancel' import CheckCircleIcon from 'material-ui/svg-icons/action/check-circle' import LockClosedIcon from 'material-ui/svg-icons/action/lock-outline' import LockOpenIcon from 'material-ui/svg-icons/action/lock-open' import AddCircleIcon from 'material-ui/svg-icons/content/add-circle' import appTheme, { widgetEditButtonInactive, widgetEditButtonHover, } from 'js/theme/default' import EditWidgetChipAnimation from 'js/components/Widget/EditWidgetChipAnimation' // Holds the widget name and any "add" or "edit" // buttons and menus. class EditWidgetChip extends React.Component { constructor(props) { super(props) this.state = { dimensions: {}, } } render() { const animationDurationMs = 140 const content = this.props.open ? ( <span key={'widget-edit-chip-add-form'} style={{ position: 'absolute', bottom: 0, left: 0, width: '100%', paddingTop: 20, boxSizing: 'border-box', }} > {this.props.widgetAddItemForm} </span> ) : ( <span key={'widget-edit-chip-content'} style={{ position: 'absolute', minHeight: 32, top: 0, left: 0, paddingLeft: 12, paddingRight: 8, }} > <span>{this.props.widgetName}</span> </span> ) // Measure the dimensions of the child content and add // the dimensions to state. Then, we'll set the width // and height of the parent container to fit the child // content. We do this so we can animate the container // expansion while still allowing dynamic child content. const measuredContent = ( <Measure bounds onResize={contentRect => { if (contentRect.bounds) { this.setState({ dimensions: contentRect.bounds, }) } }} > {({ measureRef }) => { return ( <EditWidgetChipAnimation> {React.cloneElement(content, { ref: measureRef, })} </EditWidgetChipAnimation> ) }} </Measure> ) // Icons const iconContainerStyle = { display: 'flex', justifyContent: 'flex-end', position: 'absolute', zIndex: 5, top: 4, right: 8, } const iconBaseStyle = { cursor: 'pointer', color: 'rgba(255,255,255,.3)', display: 'inline-block', } var editIcon = null if (this.props.showEditOption) { if (this.props.editMode) { editIcon = ( <LockOpenIcon onClick={() => { this.props.onEditModeToggle(false) }} hoverColor={widgetEditButtonHover} style={Object.assign({}, iconBaseStyle, { color: widgetEditButtonHover, float: 'right', marginLeft: 4, })} /> ) } else { editIcon = ( <LockClosedIcon onClick={() => { this.props.onEditModeToggle(true) }} hoverColor={widgetEditButtonHover} style={Object.assign({}, iconBaseStyle, { float: 'right', marginLeft: 4, })} /> ) } } const icons = this.props.open ? ( <div key={'icons-expanded'} style={iconContainerStyle}> <DeleteIcon color={widgetEditButtonInactive} hoverColor={widgetEditButtonHover} style={iconBaseStyle} onClick={() => { this.props.onCancelAddItemClick() }} /> <CheckCircleIcon color={widgetEditButtonInactive} hoverColor={widgetEditButtonHover} style={iconBaseStyle} onClick={() => { this.props.onItemCreatedClick() }} /> </div> ) : ( <div key={'icons-closed'} style={iconContainerStyle}> {editIcon} <AddCircleIcon key={'widget-add-icon'} color={widgetEditButtonInactive} hoverColor={widgetEditButtonHover} style={Object.assign({}, iconBaseStyle, { float: 'right', marginLeft: 4, })} onClick={() => { this.props.onEditModeToggle(false) this.props.onAddItemClick() }} /> </div> ) // Sizing const titleHeight = 32 const iconWidth = this.props.showEditOption ? 62 : 36 const expandedWidth = 290 const width = this.props.open ? expandedWidth : this.state.dimensions.width ? this.state.dimensions.width + iconWidth : 'auto' const height = this.state.dimensions.height ? this.state.dimensions.height : 'auto' return ( <span> <Paper zDepth={0} style={{ width: width, height: height, cursor: 'default', position: 'relative', overflow: 'hidden', justifyContent: 'center', alignItems: 'space-between', fontSize: 14, lineHeight: `${titleHeight}px`, transition: `width ${animationDurationMs}ms ease-in-out, height ${animationDurationMs}ms ease-in-out`, margin: 5, background: appTheme.palette.primary1Color, color: '#FFF', userSelect: 'none', }} > <div style={{ display: 'inline-flex', justifyContent: 'flex-end', position: 'absolute', zIndex: 3, width: '100%', left: 0, top: 0, boxSizing: 'border-box', }} > <EditWidgetChipAnimation>{icons}</EditWidgetChipAnimation> </div> {measuredContent} </Paper> </span> ) } } EditWidgetChip.propTypes = { open: PropTypes.bool, widgetName: PropTypes.string.isRequired, // The form to fill when adding a new widget item. widgetAddItemForm: PropTypes.element, // Whether or not there's an "edit mode" button. showEditOption: PropTypes.bool, // Called when enabling/disabling edit mode. onEditModeToggle: PropTypes.func, // Whether we're currently in edit mode. editMode: PropTypes.bool, // Called when clicking to add a new item. onAddItemClick: PropTypes.func, // Called when exiting the form without creating a // new iem. onCancelAddItemClick: PropTypes.func, // Called when confirming creation from the // `widgetAddItemForm` view. onItemCreatedClick: PropTypes.func, } EditWidgetChip.defaultProps = { open: false, showEditOption: false, onEditModeToggle: () => {}, editMode: false, onAddItemClick: () => {}, onCancelAddItemClick: () => {}, onItemCreatedClick: () => {}, } export default EditWidgetChip
src/components/Home/index.js
TerryCapan/twitchBot
import React from 'react'; import DocumentMeta from 'react-document-meta'; import { TopChannels } from '../../containers/TopChannels'; import { styles } from './styles.scss'; const metaData = { title: 'Chatson: Watson Chat Analysis', description: 'Get a visual representation of a chat channel\'s activity and group sentiment', canonical: 'http://chatson.science', meta: { charset: 'utf-8', name: { keywords: 'twitch,chat,sentiment', }, }, }; export function Home() { return ( <section className={`${styles}`}> <DocumentMeta {...metaData} /> <div className="home-container"> <p>Welcome to Chatson! We use Watson's tone analyzer to provide you with a visualization of the mood and attitude in a chat stream. See the menu above to read more about our process or to select one of the top currently streaming Twitch chat channels to see a live analysis.</p> </div> <TopChannels /> </section> ); }
example/src/components/Row.js
coteries/react-native-navigation
import React from 'react'; import PropTypes from 'prop-types'; import {StyleSheet, View, Text, TouchableHighlight, Platform} from 'react-native'; function Row({title, onPress, platform, testID}) { if (platform && platform !== Platform.OS) { return <View />; } return ( <TouchableHighlight onPress={onPress} testID={testID} underlayColor={'rgba(0, 0, 0, 0.054)'} > <View style={styles.row}> <Text style={styles.text}>{title}</Text> </View> </TouchableHighlight> ); } Row.propTypes = { title: PropTypes.string.isRequired, onPress: PropTypes.func.isRequired, }; const styles = StyleSheet.create({ row: { height: 48, paddingHorizontal: 16, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', borderBottomWidth: 1, borderBottomColor: 'rgba(0, 0, 0, 0.054)', }, text: { fontSize: 16, }, }); export default Row;
src/components/photoshop/line/PhotoshopLine.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './PhotoshopLine.svg' /** PhotoshopLine */ function PhotoshopLine({ width, height, className }) { return ( <SVGDeviconInline className={'PhotoshopLine' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } PhotoshopLine.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default PhotoshopLine
src/frontend/screens/not-found.js
Koleso/invoicer
import React from 'react'; // Components import { Grid, GridColumn } from 'components/Grid'; import Screen from 'components/Screen'; import Box from 'components/Box'; import EmptyState from 'components/EmptyState'; const NotFound = () => ( <Screen title="Stránka nenalezena"> <Grid> <GridColumn> <Box> <EmptyState title="Tato stránka neexistuje" modifiers={['page', 'big']}> Nevím co se stalo, ale tato stránka tu už není. Asi ji někdo smazal. </EmptyState> </Box> </GridColumn> </Grid> </Screen> ); export default NotFound;
app/containers/FormDialog.js
river-lee/react-group
import React from 'react'; import Model from '../components/model'; import Button from '../components/button'; import YmtApi from 'YmtApi'; const searchParams = YmtApi.utils.getUrlObj(); let FormDialog = React.createClass({ getInitialState(){ return { msgTxt:'', isSendMsgCode:true } }, //在该函数中调用 this.setState() 将不会引起第二次渲染。 componentWillReceiveProps(nextProps){ const { resetCountDown = false } = this.props; if(resetCountDown){ clearInterval(this.timer); this.setState({ msgTxt:'', isSendMsgCode:true }); } }, shouldComponentUpdate (nextProps,nextState){ return nextState.msgTxt !== this.state.msgTxt || nextProps.show !== this.props.show; }, onSendMsgCode(){ const { UserId , AccessToken } = YmtApi.utils.getAuthInfo(); const { actions,showToast } = this.props; const { value } = this.refs.mobile; if(!value){ return showToast('请填写手机号码') } if(!/^\d{11}$/.test(value)){ return showToast('请填写正确手机号码') } if(this.state.isSendMsgCode){ actions.sendValidateCode({ AccessToken, phone:value },(result)=>{ showToast('验证码发送成功') }); clearInterval(this.timer); this.setState({ msgTxt:'60s后重试', isSendMsgCode:false }); this.timer = setInterval(()=>{ let seconds = parseInt(this.state.msgTxt) - 1; if(seconds){ this.setState({msgTxt:seconds+'s后重试'}); }else{ clearInterval(this.timer); this.setState({ msgTxt:'', isSendMsgCode:true }); } },1E3); } }, onBindMobile(){ const { actions,showToast,bindMobileFn,mobelBinedFn,onHideDialog } = this.props; const { AccessToken } = YmtApi.utils.getAuthInfo(); actions.bindMobile({ AccessToken, phone:this.refs.mobile.value, pcode:this.refs.msgCode.value, unionId:searchParams.unionId, openId:searchParams.openId, wxToken:searchParams.wxToken },(result)=>{ let token = result.Data.AccessToken; YmtApi.sendEvent('userStatusChange',{ AccessToken:token }); var date = new Date(); var expireTime = 2 * 60 * 60 * 1000; date.setTime(date.getTime() + expireTime); document.cookie = 'AccessToken=' + token + ';expires=' + date.toGMTString(); onHideDialog(); bindMobileFn && bindMobileFn(); },(result)=>{ if(result.BCode == 503 || result.BCode == 505){ onHideDialog() return mobelBinedFn && mobelBinedFn(result.Msg,result.BCode == 503) } showToast(result.Msg) }); }, onChangeCanSubmit(){ // let hasError = false; // for(let i in this.refs){ // if(!this.refs[i].value){ // hasError = true; // } // } // if(!hasError){ // this.setState({ // isBindSubmit:true // }) // }else{ // this.setState({ // isBindSubmit:false // }) // } }, render (){ const { show,onHideDialog,bindMobileTxt } = this.props; return ( <Model show={show}> <div className="model-dialog bottom bottom-form-dialog"> <div className="model-content"> <div className="model-dialog-hd"> {bindMobileTxt}需要绑定手机 <span className="close-btn pull-right" onClick={onHideDialog}>X</span> </div> <div className="model-dialog-bd"> <div className="form-row"> <input type="text" placeholder="输入手机号" ref="mobile" onInput={this.onChangeCanSubmit} /> </div> <div className="form-row"> <input type="text" placeholder="输入短信校验码" ref="msgCode" onInput={this.onChangeCanSubmit} maxLength="6"/> <Button className={"btn btn-primary btn-sm send-code-btn"+(this.state.msgTxt?' invalid':'')} onClick={this.onSendMsgCode}>{this.state.msgTxt || '获取短信校验码'}</Button> </div> <Button className={"btn btn-full btn-primary confirm-btn"} onClick={this.onBindMobile}>确认绑定并{bindMobileTxt}</Button> </div> <div className="model-dialog-ft"> <div className="tips"> 哈尼,如收不到短信验证码,<br/> 请联系洋管家微信账户ymatou1,工作时间:每天9:00-24:00。 </div> </div> </div> </div> </Model> ) } }); export default FormDialog;
modules/Router.js
ArmendGashi/react-router
import React from 'react' import warning from 'warning' import createHashHistory from 'history/lib/createHashHistory' import { createRoutes } from './RouteUtils' import RoutingContext from './RoutingContext' import useRoutes from './useRoutes' import { routes } from './PropTypes' const { func, object } = React.PropTypes /** * A <Router> is a high-level API for automatically setting up * a router that renders a <RoutingContext> with all the props * it needs each time the URL changes. */ const Router = React.createClass({ propTypes: { history: object, children: routes, routes, // alias for children createElement: func, onError: func, onUpdate: func, parseQueryString: func, stringifyQuery: func }, getInitialState() { return { location: null, routes: null, params: null, components: null } }, handleError(error) { if (this.props.onError) { this.props.onError.call(this, error) } else { // Throw errors by default so we don't silently swallow them! throw error // This error probably occurred in getChildRoutes or getComponents. } }, componentWillMount() { let { history, children, routes, parseQueryString, stringifyQuery } = this.props let createHistory = history ? () => history : createHashHistory this.history = useRoutes(createHistory)({ routes: createRoutes(routes || children), parseQueryString, stringifyQuery }) this._unlisten = this.history.listen((error, state) => { if (error) { this.handleError(error) } else { this.setState(state, this.props.onUpdate) } }) }, componentWillReceiveProps(nextProps) { warning( nextProps.history === this.props.history, "The `history` provided to <Router/> has changed, it will be ignored." ) }, componentWillUnmount() { if (this._unlisten) this._unlisten() }, render() { let { location, routes, params, components } = this.state let { createElement } = this.props if (location == null) return null // Async match return React.createElement(RoutingContext, { history: this.history, createElement, location, routes, params, components }) } }) export default Router
app/index.js
datic15/wave
import React from 'react'; import ReactDOM from 'react-dom'; import injectTapEventPlugin from 'react-tap-event-plugin'; import Root from "./components/Root.jsx"; injectTapEventPlugin(); ReactDOM.render( <Root />, document.getElementById('root') );
Examples/UIExplorer/js/ActivityIndicatorExample.js
DanielMSchmidt/react-native
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * The examples provided by Facebook are for non-commercial testing and * evaluation purposes only. * * Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @flow * @providesModule ActivityIndicatorExample */ 'use strict'; import React, { Component } from 'react'; import { ActivityIndicator, StyleSheet, View } from 'react-native'; /** * Optional Flowtype state and timer types definition */ type State = { animating: boolean; }; type Timer = number; class ToggleAnimatingActivityIndicator extends Component { /** * Optional Flowtype state and timer types */ state: State; _timer: Timer; constructor(props) { super(props); this.state = { animating: true, }; } componentDidMount() { this.setToggleTimeout(); } componentWillUnmount() { clearTimeout(this._timer); } setToggleTimeout() { this._timer = setTimeout(() => { this.setState({animating: !this.state.animating}); this.setToggleTimeout(); }, 2000); } render() { return ( <ActivityIndicator animating={this.state.animating} style={[styles.centering, {height: 80}]} size="large" /> ); } } exports.displayName = (undefined: ?string); exports.framework = 'React'; exports.title = '<ActivityIndicator>'; exports.description = 'Animated loading indicators.'; exports.examples = [ { title: 'Default (small, white)', render() { return ( <ActivityIndicator style={[styles.centering, styles.gray]} color="white" /> ); } }, { title: 'Gray', render() { return ( <View> <ActivityIndicator style={[styles.centering]} /> <ActivityIndicator style={[styles.centering, {backgroundColor: '#eeeeee'}]} /> </View> ); } }, { title: 'Custom colors', render() { return ( <View style={styles.horizontal}> <ActivityIndicator color="#0000ff" /> <ActivityIndicator color="#aa00aa" /> <ActivityIndicator color="#aa3300" /> <ActivityIndicator color="#00aa00" /> </View> ); } }, { title: 'Large', render() { return ( <ActivityIndicator style={[styles.centering, styles.gray]} size="large" color="white" /> ); } }, { title: 'Large, custom colors', render() { return ( <View style={styles.horizontal}> <ActivityIndicator size="large" color="#0000ff" /> <ActivityIndicator size="large" color="#aa00aa" /> <ActivityIndicator size="large" color="#aa3300" /> <ActivityIndicator size="large" color="#00aa00" /> </View> ); } }, { title: 'Start/stop', render() { return <ToggleAnimatingActivityIndicator />; } }, { title: 'Custom size', render() { return ( <ActivityIndicator style={[styles.centering, {transform: [{scale: 1.5}]}]} size="large" /> ); } }, { platform: 'android', title: 'Custom size (size: 75)', render() { return ( <ActivityIndicator style={styles.centering} size={75} /> ); } }, ]; const styles = StyleSheet.create({ centering: { alignItems: 'center', justifyContent: 'center', padding: 8, }, gray: { backgroundColor: '#cccccc', }, horizontal: { flexDirection: 'row', justifyContent: 'space-around', padding: 8, }, });
src/components/SearchInput.js
telpalbrox/EliteTime
import React, { Component } from 'react'; import PropTypes from 'prop-types'; export default class SearchInput extends Component { constructor() { super(); this.search = this.search.bind(this); } componentDidMount() { this.refs.search.value = this.props.query || ''; } render() { return ( <div className="row"> <form id="search-form" onSubmit={this.search}> <div className="input-group"> <input type="text" className="form-control" placeholder="Search" name="srch-term" id="search-query" value={this.query} ref="search"/> <div className="input-group-btn"> <button className="btn btn-default" type="submit"><i className="glyphicon glyphicon-search"/></button> </div> </div> </form> </div> ); } search(event) { event.preventDefault(); this.props.search(this.refs.search.value); } }; SearchInput.propTypes = { search: PropTypes.func.isRequired, query: PropTypes.string };
examples/real-world/index.js
timuric/redux
import 'babel-core/polyfill'; import React from 'react'; import Root from './containers/Root'; import BrowserHistory from 'react-router/lib/BrowserHistory'; React.render( <Root history={new BrowserHistory()} />, document.getElementById('root') );
app/components/ItemOnLineNewsView.js
yanbober/RNPolymerPo
/* * MIT License * * Copyright (c) 2016 yanbo * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ 'use strict'; import React, { Component } from 'react'; import { Text, View, Image, TouchableNativeFeedback, StyleSheet, } from 'react-native'; /** * 新闻Item View */ export default class ItemOnLineNewsView extends Component { static propTypes = { bean: React.PropTypes.object.isRequired, itemClicked: React.PropTypes.func.isRequired, }; render() { return ( <TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackground()} onPress={this.props.itemClicked}> <View style={styles.itemContainer}> <Image style={styles.itemIcon} source={{uri: (this.props.bean.thumbnail_pic_s=='' ? 'defaults' : this.props.bean.thumbnail_pic_s)}}/> <View style={styles.itemDescription}> <Text style={styles.itemTitle} numberOfLines={4}> {this.props.bean.title} </Text> <Text style={styles.fromText} numberOfLines={1}> {this.props.bean.author_name} </Text> </View> </View> </TouchableNativeFeedback> ); } } const styles = StyleSheet.create({ itemContainer: { backgroundColor: 'white', marginVertical: 4, borderColor: '#dddddd', borderStyle: null, borderWidth: 0.5, borderRadius: 2, height: 113, flexDirection: 'row' }, itemIcon: { width: 163, height: 113, backgroundColor: '#e9e9e9', }, itemDescription: { flex: 1, marginLeft: 8, marginTop: 12, marginRight: 8, marginBottom: 8, }, itemTitle: { flex: 5, color: '#535252', fontSize: 14, }, fromText: { flex: 1, fontSize: 9, color: '#ff9800', alignSelf: 'flex-end', }, });
imports/ui/components/personalInfo/components/DisabilityStatus.js
AdmitHub/ScholarFisher
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Collapse from 'react-collapse'; import { selectDisabilityStatus, selectDisabilityType, } from '../../../../redux/actions/personalInfo'; class DisabilityStatus extends Component { constructor(props) { super(props); this.state = { disabilityClicked: [], opened: false, disabilityOpened: false, }; this.removeFromList = this.removeFromList.bind(this); this.handleDisabilityNone = this.handleDisabilityNone.bind(this); this.handleTitleCheckMark = this.handleTitleCheckMark.bind(this); this.dispatchDisabilityStatus = this.dispatchDisabilityStatus.bind(this); this.dispatchDisabilityType = this.dispatchDisabilityType.bind(this); this.handleX = this.handleX.bind(this); this.handleDisabilityOpened = this.handleDisabilityOpened.bind(this); } dispatchDisabilityStatus(value) { const { dispatch } = this.props; dispatch(selectDisabilityStatus(value)); } dispatchDisabilityType(value) { const { dispatch } = this.props; dispatch(selectDisabilityType(value)); } removeFromList(value) { let newArray = this.state.disabilityClicked const index = this.state.disabilityClicked.indexOf(value); newArray.splice(index, 1); this.setState({ disabilityClicked: this.state.disabilityClicked}, function () { }); } handleDisabilityNone(value) { const newArray = []; if (value === 'No Disability') { this.setState({ disabilityClicked: newArray }); } } renderSelected() { return this.state.disabilityClicked.map((currentEl, index) => ( <div> <div className={'secondary-color'} onClick={() => { this.removeFromList(currentEl); this.dispatchDisabilityType(null); }} key={index} > <span>ⓧ</span> <span>{currentEl}</span> <span>✓</span> </div> </div> )); } renderDisabilityStatus() { const { options } = this.props; return options.map((currentEl, index) => ( <div className={'pill ' + (currentEl.type === this.props.selectedDisabilityStatus ? 'selected' : '')} onClick={() => { if (currentEl.type === 'I Have a Disability') { this.setState({ opened: !this.state.opened }, function() { }) } else { this.setState({opened: false }) } this.dispatchDisabilityStatus(currentEl.type); this.handleDisabilityNone(currentEl.type); }} key={index} > {currentEl.type} </div> )); } renderDisabilityType() { if (this.props.selectedDisabilityStatus === 'I Have a Disability') { const { disabilities } = this.props; return disabilities.map((currentEl, index) => ( <div className={'pill ' + (this.props.selected.indexOf(currentEl.type) > -1 ? 'selected' : '')} onClick={() => { this.dispatchDisabilityType(currentEl.type); }} key={index} > {currentEl.type} </div> )); } return null; } handleTitleCheckMark() { const disabilityStatus = this.props.selectedDisabilityStatus; if (disabilityStatus && disabilityStatus !== 'I Have a Disability') { return ( <span className="flex pull-right"> <i className="fa fa-check-circle fa-lg"></i> </span> ); } if (disabilityStatus && this.props.selectedDisabilityType) { return ( <span className="flex pull-right"> <i className="fa fa-check-circle fa-lg"></i> </span> ); } return ( <span className="flex pull-right"> <i className="fa fa-circle-o fa-lg"></i> </span> ); } handleX() { this.setState({ opened: false }); } handleDisabilityOpened() { this.setState({ disabilityOpened: !this.state.disabilityOpened }); } render() { return ( <div> <div className="row"> <div className="col-xs-12"> <h4 onClick={this.handleDisabilityOpened} > DISABILITY STATUS <div className="pull-right"> {this.handleTitleCheckMark()} </div> </h4> <Collapse isOpened={this.state.disabilityOpened}> <p className="caption"> <span className="caption-paragraph"> a physical or mental impairment that substantially limits one or more major life activity. If your disability is not listed, just selected disability in general </span> </p> </Collapse> </div> </div> <div className="row"> <div className="col-xs-12 flex-wrapper"> {this.renderDisabilityStatus()} </div> </div> <div className="row"> <div className="col-xs-12"> <Collapse isOpened={this.state.opened}> <span className="flex pull-right"> <i onClick={this.handleX} className="fa fa-times-circle" id="expand_cancel" aria-hidden="true" > </i> </span> <div className="flex-wrapper background" id="expand_menu"> {this.renderDisabilityType()} </div> </Collapse> </div> </div> <div className="row"> <div className="col-xs-12"> {this.renderSelected()} </div> </div> </div> ); } } function mapStateToProps(state) { return state.query.personalInfo; } export default connect(mapStateToProps)(DisabilityStatus);
src/components/Tabs.js
henrytao-me/react-native-mdcore
import React from 'react' import { TouchableWithoutFeedback, View } from 'react-native' import PropTypes from './PropTypes' import PureComponent from './PureComponent' import StyleSheet from './StyleSheet' export default class Tabs extends PureComponent { static contextTypes = { theme: PropTypes.any } static propTypes = { backgroundColor: PropTypes.color, indicatorEnabled: PropTypes.bool, indicatorStyle: PropTypes.style, initialItem: PropTypes.number, onItemSelected: PropTypes.func } static defaultProps = { indicatorEnabled: true, initialItem: 0, onItemSelected: (_options = { index: 0 }) => { } } state = { index: undefined } render() { const { theme } = this.context const styles = Styles.get(theme, this.props) return ( <View style={[styles.container, this.props.style]}> {this.props.children && this.props.children.map(this._renderItem)} </View> ) } setItem = (index) => { this.setState({ index }) } _getIndex = () => { return this.state.index !== undefined ? this.state.index : this.props.initialItem } _onItemPress = (index) => { this.setState({ index }) this.props.onItemSelected({ index }) } _renderItem = (item, index) => { const { theme } = this.context const styles = Styles.get(theme, this.props) const active = index === this._getIndex() item = item.props.active === active ? item : React.cloneElement(item, { active }) return ( <TouchableWithoutFeedback key={index} onPress={() => this._onItemPress(index)}> <View style={styles.item}> {this.props.indicatorEnabled && active && <View style={[styles.indicator, this.props.indicatorStyle]} />} {item} </View> </TouchableWithoutFeedback> ) } } const Styles = StyleSheet.create((theme, { backgroundColor }) => { const container = { backgroundColor: backgroundColor || theme.palette.primary, flexDirection: 'row' } const indicator = { position: 'absolute', left: 0, right: 0, bottom: 0, backgroundColor: theme.palette.accent, height: theme.tab.indicatorHeight } const item = { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' } return { container, indicator, item } })
src/icons/CameraEnhanceIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class CameraEnhanceIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M9 3L7.17 5H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2h-3.17L15 3H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-1l1.25-2.75L16 13l-2.75-1.25L12 9l-1.25 2.75L8 13l2.75 1.25z"/></svg>;} };
internals/templates/homePage/homePage.js
StrikeForceZero/react-typescript-boilerplate
/* * HomePage * * This is the first thing users see of our App, at the '/' 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 HomePage extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
src/components/layout.js
JoshBarr/joshbarr.github.io
import React from 'react' import PropTypes from 'prop-types' import { StaticQuery, graphql } from 'gatsby' import Helmet from 'react-helmet' import Header from './header' import './layout.css' const Layout = ({ children, theme = 'theme--light' }) => ( <StaticQuery query={graphql` query SiteTitleQuery { site { siteMetadata { title } } } `} render={data => ( <> <link href="https://fonts.googleapis.com/css?family=Merriweather:300,400,400i,700|Lato:400,400i,700" rel="stylesheet" /> <Helmet bodyAttributes={{ class: `${theme} theme-body`, }} /> <div> <div> <Header theme={theme} siteTitle={data.site.siteMetadata.title} /> </div> <div className={`children`}> <div className="theme-background">{children}</div> </div> <div className="theme--footer"> <footer className="footer theme-background theme-text"> <div className="container container--secondary small"> <ul className="list-inline"> <li> © 2021, built with{' '} <a href="https://www.gatsbyjs.org" className="theme-link"> Gatsby </a> </li> <li> <a className="theme-link" href="https://github.com/joshbarr/joshbarr.github.io" > Source code on Github </a> </li> </ul> </div> </footer> </div> </div> </> )} /> ) Layout.propTypes = { children: PropTypes.node.isRequired, } export default Layout
app/javascript/mastodon/components/icon_with_badge.js
Ryanaka/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Icon from 'mastodon/components/icon'; const formatNumber = num => num > 40 ? '40+' : num; const IconWithBadge = ({ id, count, issueBadge, className }) => ( <i className='icon-with-badge'> <Icon id={id} fixedWidth className={className} /> {count > 0 && <i className='icon-with-badge__badge'>{formatNumber(count)}</i>} {issueBadge && <i className='icon-with-badge__issue-badge' />} </i> ); IconWithBadge.propTypes = { id: PropTypes.string.isRequired, count: PropTypes.number.isRequired, issueBadge: PropTypes.bool, className: PropTypes.string, }; export default IconWithBadge;
src/decorators/withViewport.js
HoomanGriz/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let EE; let viewport = {width: 1366, height: 768}; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = {width: window.innerWidth, height: window.innerHeight}; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on(RESIZE_EVENT, this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport}/>; } handleResize(value) { this.setState({viewport: value}); } }; } export default withViewport;
src/mui/field/UrlField.js
marmelab/admin-on-rest
import React from 'react'; import PropTypes from 'prop-types'; import get from 'lodash.get'; import pure from 'recompose/pure'; const UrlField = ({ source, record = {}, elStyle }) => ( <a href={get(record, source)} style={elStyle}> {get(record, source)} </a> ); UrlField.propTypes = { addLabel: PropTypes.bool, elStyle: PropTypes.object, label: PropTypes.string, record: PropTypes.object, source: PropTypes.string.isRequired, }; const PureUrlField = pure(UrlField); PureUrlField.defaultProps = { addLabel: true, }; export default PureUrlField;
webvis/src/index.js
kacperzuk/mldrive
import React from 'react'; import ReactDOM from 'react-dom'; import { createStore } from 'redux' import { batchedSubscribe } from 'redux-batched-subscribe'; import debounce from 'lodash.debounce'; import { Provider } from 'react-redux' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); import App from './components/App'; import reducer from './reducers'; import connector from './connector'; import controller from './controller'; import './index.css'; const debounceNotify = debounce(notify => notify(), 10); const store = createStore(reducer, undefined, batchedSubscribe(debounceNotify)); connector.init(store); controller.init(store); ReactDOM.render( <Provider store={store}> <MuiThemeProvider> <App/> </MuiThemeProvider> </Provider>, document.getElementById('root') );
docs/src/app/components/pages/components/Stepper/GranularControlStepper.js
barakmitz/material-ui
import React from 'react'; import { Step, Stepper, StepButton, } from 'material-ui/Stepper'; import RaisedButton from 'material-ui/RaisedButton'; import FlatButton from 'material-ui/FlatButton'; const getStyles = () => { return { root: { width: '100%', maxWidth: 700, margin: 'auto', }, content: { margin: '0 16px', }, actions: { marginTop: 12, }, backButton: { marginRight: 12, }, }; }; /** * This is similiar to the horizontal non-linear example, except the * `<Step>` components are being controlled manually via individual props. * * An enhancement made possible by this functionality (shown below), * is to permanently mark steps as complete once the user has satisfied the * application's required conditions (in this case, once it has visited the step). * */ class GranularControlStepper extends React.Component { state = { stepIndex: null, visited: [], }; componentWillMount() { const {stepIndex, visited} = this.state; this.setState({visited: visited.concat(stepIndex)}); } componentWillUpdate(nextProps, nextState) { const {stepIndex, visited} = nextState; if (visited.indexOf(stepIndex) === -1) { this.setState({visited: visited.concat(stepIndex)}); } } handleNext = () => { const {stepIndex} = this.state; if (stepIndex < 2) { this.setState({stepIndex: stepIndex + 1}); } }; handlePrev = () => { const {stepIndex} = this.state; if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}); } }; getStepContent(stepIndex) { switch (stepIndex) { case 0: return 'Select campaign settings...'; case 1: return 'What is an ad group anyways?'; case 2: return 'This is the bit I really care about!'; default: return 'Click a step to get started.'; } } render() { const {stepIndex, visited} = this.state; const styles = getStyles(); return ( <div style={styles.root}> <p> <a href="#" onClick={(event) => { event.preventDefault(); this.setState({stepIndex: null, visited: []}); }} > Click here </a> to reset the example. </p> <Stepper linear={false}> <Step completed={visited.indexOf(0) !== -1} active={stepIndex === 0}> <StepButton onClick={() => this.setState({stepIndex: 0})}> Select campaign settings </StepButton> </Step> <Step completed={visited.indexOf(1) !== -1} active={stepIndex === 1}> <StepButton onClick={() => this.setState({stepIndex: 1})}> Create an ad group </StepButton> </Step> <Step completed={visited.indexOf(2) !== -1} active={stepIndex === 2}> <StepButton onClick={() => this.setState({stepIndex: 2})}> Create an ad </StepButton> </Step> </Stepper> <div style={styles.content}> <p>{this.getStepContent(stepIndex)}</p> {stepIndex !== null && ( <div style={styles.actions}> <FlatButton label="Back" disabled={stepIndex === 0} onTouchTap={this.handlePrev} style={styles.backButton} /> <RaisedButton label="Next" primary={true} onTouchTap={this.handleNext} /> </div> )} </div> </div> ); } } export default GranularControlStepper;
src/main.js
leshek-pawlak/itenteges
import React from 'react' import ReactDOM from 'react-dom' import AppContainer from './containers/AppContainer' // ======================================================== // Init // ======================================================== const initialState = window.___INITIAL_STATE__ // Render Setup // ======================================================== const MOUNT_NODE = document.getElementById('root') let render = () => { const routes = require('./routes/index').default(initialState) ReactDOM.render( <AppContainer routes={routes} />, MOUNT_NODE ) } // This code is excluded from production bundle if (__DEV__) { if (module.hot) { // Development render functions const renderApp = render const renderError = (error) => { const RedBox = require('redbox-react').default ReactDOM.render(<RedBox error={error} />, MOUNT_NODE) } // Wrap render in try/catch render = () => { try { renderApp() } catch (error) { console.error(error) renderError(error) } } // Setup hot module replacement module.hot.accept('./routes/index', () => setImmediate(() => { ReactDOM.unmountComponentAtNode(MOUNT_NODE) render() }) ) } } // ======================================================== // Go! // ======================================================== render()
installer/frontend/form.js
yifan-gu/tectonic-installer
import _ from 'lodash'; import React from 'react'; import { connect } from 'react-redux'; import { dispatch as dispatch_ } from './store'; import { configActions, registerForm } from './actions'; import { toError, toIgnore, toAsyncError, toExtraData, toInFly, toExtraDataInFly, toExtraDataError } from './utils'; import { ErrorComponent, ConnectedFieldList } from './components/ui'; import { TectonicGA } from './tectonic-ga'; import { PLATFORM_TYPE } from './cluster-config'; const { setIn, batchSetIn, append, removeAt } = configActions; const nop = () => undefined; // TODO: (kans) make a sideffectful field instead of putting all side effects in async validate let clock_ = 0; class Node { constructor (id, opts) { if (!id) { throw new Error('I need an id'); } this.clock_ = 0; this.id = id; this.name = opts.name || id; this.validator = opts.validator || nop; this.dependencies = opts.dependencies || []; this.ignoreWhen_ = opts.ignoreWhen; this.asyncValidator_ = opts.asyncValidator; this.getExtraStuff_ = opts.getExtraStuff; } updateClock (now) { return this.clock_ = Math.max(now || clock_, this.clock_); } get isNow () { const now = this.clock_; return () => this.clock_ === now; } getExtraStuff (dispatch, clusterConfig, FIELDS, now) { if (!this.getExtraStuff_) { return Promise.resolve(); } const path = toExtraDataInFly(this.id); const unsatisfiedDeps = this.dependencies .map(d => FIELDS[d]) .filter(d => !d.isValid(clusterConfig)); if (unsatisfiedDeps.length) { return setIn(toExtraData(this.id), undefined, dispatch); } this.updateClock(now); setIn(path, true, dispatch); const isNow = this.isNow; return this.getExtraStuff_(dispatch, isNow).then(data => { if (!isNow()) { return; } batchSetIn(dispatch, [ [path, undefined], [toExtraData(this.id), data], [toExtraDataError(this.id), undefined], ]); }, e => { if (!isNow()) { return; } batchSetIn(dispatch, [ [path, undefined], [toExtraData(this.id), undefined], [toExtraDataError(this.id), e.message || e.toString()], ]); }); } async validate (dispatch, getState, oldCC, now) { const id = this.id; const clusterConfig = getState().clusterConfig; const value = this.getData(clusterConfig); const extraData = _.get(clusterConfig, toExtraData(id)); const syncErrorPath = toError(id); const inFlyPath = toInFly(id); const oldValue = this.getData(oldCC); const batches = []; if (_.get(clusterConfig, inFlyPath)) { batches.push([inFlyPath, false]); } console.debug(`validating ${this.name}`); const syncError = this.validator(value, clusterConfig, oldValue, extraData); if (!_.isEmpty(syncError)) { console.info(`sync error ${this.name}: ${JSON.stringify(syncError)}`); batches.push([syncErrorPath, syncError]); batchSetIn(dispatch, batches); return false; } const oldError = _.get(oldCC, syncErrorPath); if (!_.isEmpty(oldError)) { batches.push([syncErrorPath, undefined]); batchSetIn(dispatch, batches); } const isValid = this.isValid(getState().clusterConfig, true); if (!isValid) { batchSetIn(dispatch, batches); return false; } if (!this.asyncValidator_) { batchSetIn(dispatch, batches); return true; } batches.push([inFlyPath, true]); batchSetIn(dispatch, batches); let asyncError; this.updateClock(now); try { asyncError = await this.asyncValidator_(dispatch, getState, value, oldValue, this.isNow, extraData); } catch (e) { asyncError = e.message || e.toString(); } if (this.clock_ !== now) { console.log(`${this.name} is stale ${this.clock_} ${now}`); return false; } batches.push([inFlyPath, false]); const asyncErrorPath = toAsyncError(id); if (!_.isEmpty(asyncError)) { if (!_.isString(asyncError)) { console.warn(`asyncError is not a string!?:\n${JSON.stringify(asyncError)}`); if (asyncError.type && asyncError.payload) { console.warn('Did you accidentally return a dispatch?'); asyncError = null; } else { asyncError = asyncError.toString ? asyncError.toString() : JSON.stringify(asyncError); } } console.log(`asyncError for ${this.name}: ${asyncError}`); batches.push([asyncErrorPath, asyncError]); batchSetIn(dispatch, batches); return false; } const oldAsyncError = _.get(getState().clusterConfig, asyncErrorPath); if (oldAsyncError) { batches.push([asyncErrorPath, undefined]); } batchSetIn(dispatch, batches); return true; } ignoreWhen (dispatch, clusterConfig) { if (!this.ignoreWhen_) { return false; } const value = !!this.ignoreWhen_(clusterConfig); console.debug(`ignoring ${this.id} value ${value}`); setIn(toIgnore(this.id), value, dispatch); return value; } isIgnored (clusterConfig) { return _.get(clusterConfig, toIgnore(this.id)); } } async function promisify (dispatch, getState, oldCC, now, deps, FIELDS) { const { clusterConfig } = getState(); // TODO: (kans) earlier return [] if not now? const promises = deps.map(field => { const { id } = field; field.ignoreWhen(dispatch, clusterConfig); return field.getExtraStuff(dispatch, clusterConfig, FIELDS, now) .then(() => field.validate(dispatch, getState, oldCC, now)) .then(res => { if (!res) { console.debug(`${id} is invalid`); } else { console.debug(`${id} is valid`); } return res && id; }).catch(err => { console.error(err); }); }); return await Promise.all(promises).then(p => p.filter(id => id)); } export class Field extends Node { constructor(id, opts = {}) { super(id, opts); if (!_.has(opts, 'default')) { throw new Error(`${id} needs a default`); } this.default = opts.default; } getExtraData (clusterConfig) { return _.get(clusterConfig, toExtraData(this.id)); } getData (clusterConfig) { return clusterConfig[this.id]; } async update (dispatch, value, getState, FIELDS, FIELD_TO_DEPS, split) { const oldCC = getState().clusterConfig; const now = ++ clock_; let id = this.id; if (split && split.length) { id = `${id}.${split.join('.')}`; } console.info(`updating ${this.name}`); // TODO: (kans) - We need to lock the entire validation chain, not just validate proper setIn(id, value, dispatch); const isValid = await this.validate(dispatch, getState, oldCC, now); if (!isValid) { const dirty = getState().dirty; if (dirty[this.name]) { TectonicGA.sendEvent('Validation Error', 'user input', this.name, oldCC[PLATFORM_TYPE]); } console.debug(`${this.name} is invalid`); return; } const visited = new Set(); const toVisit = [FIELD_TO_DEPS[this.id]]; if (!toVisit[0].length) { console.debug(`no deps for ${this.name}`); return; } while (toVisit.length) { const deps = toVisit.splice(0, 1)[0]; // TODO: check for relationship between deps const nextDepIDs = await promisify(dispatch, getState, oldCC, now, deps, FIELDS); nextDepIDs.forEach(depID => { const nextDeps = _.filter(FIELD_TO_DEPS[depID], d => !visited.has(d.id)); if (!nextDeps.length) { return; } nextDeps.forEach(d => visited.add(d.id)); toVisit.push(nextDeps); }); } console.info(`finish validating ${this.name} ${isValid}`); } validationData_ (clusterConfig, syncOnly) { const id = this.id; const value = _.get(clusterConfig, id); const ignore = _.get(clusterConfig, toIgnore(id)); let error = _.get(clusterConfig, toError(id)); if (!error && !syncOnly) { error = _.get(clusterConfig, toAsyncError(id)); } return {value, ignore, error}; } isValid_ ({ignore, error, value}) { return ignore || value !== '' && value !== undefined && _.isEmpty(error); } isValid (clusterConfig, syncOnly) { return this.isValid_(this.validationData_(clusterConfig, syncOnly)); } inFly (clusterConfig) { return _.get(clusterConfig, toInFly(this.id)) || _.get(clusterConfig, toExtraDataInFly(this.id)); } } export class Form extends Node { constructor(id, fields, opts = {}) { super(id, opts); this.isForm = true; this.fields = fields; this.fieldIDs = fields.map(f => f.id); this.dependencies = [...this.fieldIDs].concat(this.dependencies); this.errorComponent = connect( ({clusterConfig}) => ({ error: _.get(clusterConfig, toError(id)) || _.get(clusterConfig, toAsyncError(id)), }) )(ErrorComponent); registerForm(this, fields); } isValid (clusterConfig, syncOnly) { const ignore = _.get(clusterConfig, toIgnore(this.id)); if (ignore) { return true; } let error = _.get(clusterConfig, toError(this.id)); if (!syncOnly && !error) { error = _.get(clusterConfig, toAsyncError(this.id)); } if (error) { return false; } const invalidFields = this.fields.filter(field => !field.isValid(clusterConfig)); return invalidFields.length === 0; } getExtraData (clusterConfig) { return this.fields.filter(f => !f.isIgnored(clusterConfig)).reduce((acc, f) => { acc[f.name] = f.getExtraData(clusterConfig); return acc; }, {}); } getData (clusterConfig) { return this.fields.filter(f => !f.isIgnored(clusterConfig)).reduce((acc, f) => { acc[f.name] = f.getData(clusterConfig); return acc; }, {}); } inFly (clusterConfig) { return _.get(clusterConfig, toInFly(this.id)) || _.some(this.fields, f => f.inFly(clusterConfig)); } get canNavigateForward () { return ({clusterConfig}) => !this.inFly(clusterConfig) && this.isValid(clusterConfig); } get Errors () { return this.errorComponent; } } const toValidator = (fields, listValidator) => (value, clusterConfig, oldValue, extraData) => { const errs = listValidator ? listValidator(value, clusterConfig, oldValue, extraData) : []; if (errs && !_.isObject(errs)) { throw new Error(`FieldLists validator must return an Array-like Object, not:\n${errs}`); } _.each(value, (child, i) => { errs[i] = errs[i] || {}; _.each(child, (childValue, name) => { // TODO: check that the name is in the field... const validator = _.get(fields, [name, 'validator']); if (!validator) { return; } const err = validator(childValue, clusterConfig, _.get(oldValue, [i, name]), _.get(extraData, [i, name])); if (!err) { return; } errs[i][name] = err; }); }); return _.every(errs, err => _.isEmpty(err)) ? {} : errs; }; const toDefaultOpts = opts => { const default_ = {}; _.each(opts.fields, (v, k) => { default_[k] = v.default; }); return Object.assign({}, opts, {default: [default_], validator: toValidator(opts.fields, opts.validator)}); }; export class FieldList extends Field { constructor(id, opts = {}) { super(id, toDefaultOpts(opts)); this.fields = opts.fields; } get Map () { if (this.OuterListComponent_) { return this.OuterListComponent_; } const id = this.id; const fields = this.fields; this.OuterListComponent_ = function Outer ({children}) { return React.createElement(ConnectedFieldList, {id, fields}, children); }; return this.OuterListComponent_; } get addOnClick () { return () => dispatch_(configActions.appendField(this.id)); } get NonFieldErrors () { if (this.errorComponent_) { return this.errorComponent_; } const id = this.id; this.errorComponent_ = connect( ({clusterConfig}) => ({error: _.get(clusterConfig, toError(id), {})}), )(({error}) => React.createElement(ErrorComponent, {error: error[-1]})); return this.errorComponent_; } append (dispatch, getState) { const child = {}; _.each(this.fields, (f, name) => { child[name] = _.cloneDeep(f.default); }); append(this.id, child, dispatch); this.validate(dispatch, getState, getState().clusterConfig, () => true); } remove (dispatch, i, getState) { removeAt(this.id, i, dispatch); this.validate(dispatch, getState, getState().clusterConfig, () => true); } }
src/components/FormField.js
michaelgodshall/fullstack-challenge-frontend
import React from 'react'; // A reusable form field component const FormField = (props) => { // Generate the field element let fieldElement; if (props.element === 'select') { // Generate the options if it's a select field const optionElements = props.options.map((option) => { return ( <option value={option.value} key={option.value}>{option.name}</option> ); }); fieldElement = ( <select {...props.input} className="form-control"> <option></option> {optionElements} </select> ); } else { // Default field element fieldElement = ( <props.element {...props.input} type={props.type} className="form-control" /> ); } return ( <div className={`form-group ${props.meta.touched && props.meta.invalid ? 'has-danger': ''}`}> <label htmlFor={props.input.name} className="form-control-label">{props.label}</label> {fieldElement} {props.meta.touched && props.meta.error && <span className="form-control-feedback">{props.meta.error}</span>} </div> ); }; export default FormField;
src/SplitButton.js
aparticka/react-bootstrap
/* eslint react/prop-types: [2, {ignore: "bsSize"}] */ /* BootstrapMixin contains `bsSize` type validation */ import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import DropdownStateMixin from './DropdownStateMixin'; import Button from './Button'; import ButtonGroup from './ButtonGroup'; import DropdownMenu from './DropdownMenu'; const SplitButton = React.createClass({ mixins: [BootstrapMixin, DropdownStateMixin], propTypes: { pullRight: React.PropTypes.bool, title: React.PropTypes.node, href: React.PropTypes.string, id: React.PropTypes.string, target: React.PropTypes.string, dropdownTitle: React.PropTypes.node, dropup: React.PropTypes.bool, onClick: React.PropTypes.func, onSelect: React.PropTypes.func, disabled: React.PropTypes.bool, className: React.PropTypes.string, children: React.PropTypes.node }, getDefaultProps() { return { dropdownTitle: 'Toggle dropdown', disabled: false, dropup: false, pullRight: false }; }, render() { let groupClasses = { 'open': this.state.open, 'dropup': this.props.dropup }; let button = ( <Button {...this.props} ref="button" onClick={this.handleButtonClick} title={null} id={null}> {this.props.title} </Button> ); let dropdownButton = ( <Button {...this.props} ref="dropdownButton" className={classNames(this.props.className, 'dropdown-toggle')} onClick={this.handleDropdownClick} title={null} href={null} target={null} id={null}> <span className="sr-only">{this.props.dropdownTitle}</span> <span className="caret" /> <span style={{letterSpacing: '-.3em'}}>&nbsp;</span> </Button> ); return ( <ButtonGroup bsSize={this.props.bsSize} className={classNames(groupClasses)} id={this.props.id}> {button} {dropdownButton} <DropdownMenu ref="menu" onSelect={this.handleOptionSelect} aria-labelledby={this.props.id} pullRight={this.props.pullRight}> {this.props.children} </DropdownMenu> </ButtonGroup> ); }, handleButtonClick(e) { if (this.state.open) { this.setDropdownState(false); } if (this.props.onClick) { this.props.onClick(e, this.props.href, this.props.target); } }, handleDropdownClick(e) { e.preventDefault(); this.setDropdownState(!this.state.open); }, handleOptionSelect(key) { if (this.props.onSelect) { this.props.onSelect(key); } this.setDropdownState(false); } }); export default SplitButton;
src/components/picker/city_picker.js
n7best/react-weui
import React from 'react'; import PropTypes from 'prop-types'; import Picker from './picker'; /** * An city pick component build on top of picker * */ class CityPicker extends React.Component { static propTypes = { /** * Array of item trees, consists property for label and subitems * */ data: PropTypes.array.isRequired, /** * keys for data provide, `id` to indicate property name for label, `items` to indicate property name for subitems * */ dataMap: PropTypes.object, /** * currently selected item * */ selected: PropTypes.array, /** * display the component * */ show: PropTypes.bool, /** * language object consists of `leftBtn` and `rightBtn` * */ lang: PropTypes.object, } static defaultProps = { data: [], dataMap: { id: 'name', items: 'sub' }, selected: [], show: false, lang: { leftBtn: '取消', rightBtn: '确定' } } constructor(props){ super(props); const { data, selected, dataMap } = this.props; const { groups, newselected } = this.parseData(data, dataMap.items, selected); this.state = { groups, selected: newselected, picker_show: false, text: '' }; //console.log(this.state.groups) this.updateGroup = this.updateGroup.bind(this); this.parseData = this.parseData.bind(this); this.handleChange = this.handleChange.bind(this); } //@return array of group with options parseData(data, subKey, selected = [], group = [], newselected = []){ let _selected = 0; if ( Array.isArray(selected) && selected.length > 0){ let _selectedClone = selected.slice(0); _selected = _selectedClone.shift(); selected = _selectedClone; } if (typeof data[_selected] === 'undefined'){ _selected = 0; } newselected.push(_selected); let item = data[_selected]; var _group = JSON.parse(JSON.stringify(data)); _group.forEach(g=>delete g[subKey]); group.push({ items: _group, mapKeys: { 'label': this.props.dataMap.id } }); if (typeof item[subKey] !== 'undefined' && Array.isArray(item[subKey])){ return this.parseData(item[subKey], subKey, selected, group, newselected); } else { return { groups: group, newselected }; } } updateDataBySelected(selected, cb){ const { data, dataMap } = this.props; //validate if item exists const { groups, newselected } = this.parseData(data, dataMap.items, selected); let text = ''; try { groups.forEach( (group, _i) => { text += `${group['items'][selected[_i]][this.props.dataMap.id]} `; }); } catch (err){ //wait text = this.state.text; } this.setState({ groups, text, selected: newselected }, ()=>cb()); } updateGroup(item, i, groupIndex, selected, picker){ this.updateDataBySelected(selected, ()=>{ //update picker picker.setState({ selected: this.state.selected }); }); } handleChange(selected){ //handle unchange if (selected === this.state.selected){ this.updateDataBySelected(selected, ()=>{ if (this.props.onChange) this.props.onChange(this.state.text); }); } if (this.props.onChange) this.props.onChange(this.state.text); } render(){ return ( <Picker show={this.props.show} onGroupChange={this.updateGroup} onChange={this.handleChange} defaultSelect={this.state.selected} groups={this.state.groups} onCancel={this.props.onCancel} lang={this.props.lang} /> ); } } export default CityPicker;
src/pages/UserProfile/index.js
JSLancerTeam/crystal-dashboard
import React from 'react'; import ProfileForm from './ProfileForm'; import UserInfo from './UserInfo'; const UserProfile = () => ( <div className="content"> <div className="container-fluid"> <div className="row"> <div className="col-md-8"> <ProfileForm /> </div> <div className="col-md-4"> <UserInfo /> </div> </div> </div> </div> ); export default UserProfile;
src/svg-icons/action/work.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionWork = (props) => ( <SvgIcon {...props}> <path d="M20 6h-4V4c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-6 0h-4V4h4v2z"/> </SvgIcon> ); ActionWork = pure(ActionWork); ActionWork.displayName = 'ActionWork'; export default ActionWork;
src/Radio/windows/index.js
gabrielbull/react-desktop
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Radium, { getState } from 'radium'; import styles from './styles/windows'; import Text from '../../Text/windows'; import { ThemeContext, themePropTypes, themeContextTypes } from '../../style/theme/windows'; import Hidden, { hiddenPropTypes } from '../../style/hidden'; import { ColorContext, colorPropTypes, colorContextTypes } from '../../style/color/windows'; import ValueRef from '../../ValueRef'; @ValueRef() @Hidden() @ColorContext() @ThemeContext() @Radium class Radio extends Component { static propTypes = { ...hiddenPropTypes, ...colorPropTypes, ...themePropTypes, label: PropTypes.string, onChange: PropTypes.func }; static contextTypes = { ...themeContextTypes, ...colorContextTypes }; constructor(props) { super(); this.state = { checked: !!props.defaultChecked === true }; } componentDidMount() { document.addEventListener('change', this.onSiblingChange); } componentWillUnmount() { document.removeEventListener('change', this.onSiblingChange); } onSiblingChange = () => { if (this.refs.element.checked !== this.state.checked) { this.setState({ checked: this.refs.element.checked }); } }; handleChange = event => { this.setState({ checked: event.target.checked }); if (this.props.onChange) { this.props.onChange(event); } }; render() { let { style, label, color, ...props } = this.props; let componentStyle = { ...styles.radio, ...(this.context.theme === 'dark' ? styles['radioDark'] : {}) }; let labelStyle = styles.label; let circleStyle = { ...styles.circle, ...(this.context.theme === 'dark' ? styles['circleDark'] : {}) }; if (this.state.checked) { componentStyle = { ...componentStyle, borderColor: color || this.context.color }; } if (getState(this.state, null, ':active')) { if (this.state.checked) { componentStyle = { ...componentStyle, ...styles['radio:checked:active'], ...(this.context.theme === 'dark' ? styles['radioDark:checked:active'] : {}) }; circleStyle = { ...circleStyle, ...styles['circle:active'], ...(this.context.theme === 'dark' ? styles['circleDark:active'] : {}) }; } else { componentStyle = { ...componentStyle, ...styles['radio:active'], ...(this.context.theme === 'dark' ? styles['radioDark:active'] : {}) }; } } else if (getState(this.state, null, ':hover')) { if (this.state.checked) { circleStyle = { ...circleStyle, ...styles['circle:hover'], ...(this.context.theme === 'dark' ? styles['circleDark:hover'] : {}) }; } else { componentStyle = { ...componentStyle, ...styles['radio:hover'], ...(this.context.theme === 'dark' ? styles['radioDark:hover'] : {}) }; } } componentStyle = { ...componentStyle, ...style }; return ( <div style={styles.container}> <label style={labelStyle}> <div style={styles.inputWrapper}> <input ref="element" type="radio" {...props} style={componentStyle} onChange={this.handleChange} /> {this.state.checked ? <div style={circleStyle} /> : null} </div> <Text style={{ ...styles.text, ...(this.context.theme === 'dark' ? styles.textDark : {}) }} > {label} </Text> </label> </div> ); } } export default Radio;
frontend/src/admin/branchManagement/memberView/MembersView.js
rabblerouser/core
import React, { Component } from 'react'; import { connect } from 'react-redux'; import EditMemberForm from './EditMemberForm'; import FilteredMembersList from './FilteredMembersList'; import { Modal, A, Panel } from '../../common'; import { finishEditMember, memberListRequested } from './actions'; import { getIsEditActive } from './reducers'; import { getSelectedBranchId } from '../../reducers/branchReducers'; export class MembersView extends Component { componentWillReceiveProps(nextProps) { if (nextProps.branchId && nextProps.branchId !== this.props.branchId) { this.props.membersRequested(); } } render() { return ( <Panel> <A href={`/branches/${this.props.branchId}/members.csv`}>Export all members...</A> <FilteredMembersList /> <Modal isOpen={this.props.isModalOpen} handleClose={this.props.handleCloseModal} > <EditMemberForm onSuccess={this.closeEditForm} /> </Modal> </Panel> ); } } const mapDispatchToProps = dispatch => ({ membersRequested: () => dispatch(memberListRequested()), handleCloseModal: finishEditMember, }); const mapStateToProps = state => ({ branchId: getSelectedBranchId(state), isModalOpen: getIsEditActive(state), }); export default connect(mapStateToProps, mapDispatchToProps)(MembersView);
src/AffixMixin.js
Cellule/react-bootstrap
import React from 'react'; import domUtils from './utils/domUtils'; import EventListener from './utils/EventListener'; const AffixMixin = { propTypes: { offset: React.PropTypes.number, offsetTop: React.PropTypes.number, offsetBottom: React.PropTypes.number }, getInitialState() { return { affixClass: 'affix-top' }; }, getPinnedOffset(DOMNode) { if (this.pinnedOffset) { return this.pinnedOffset; } DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, ''); DOMNode.className += DOMNode.className.length ? ' affix' : 'affix'; this.pinnedOffset = domUtils.getOffset(DOMNode).top - window.pageYOffset; return this.pinnedOffset; }, checkPosition() { let DOMNode, scrollHeight, scrollTop, position, offsetTop, offsetBottom, affix, affixType, affixPositionTop; // TODO: or not visible if (!this.isMounted()) { return; } DOMNode = React.findDOMNode(this); scrollHeight = document.documentElement.offsetHeight; scrollTop = window.pageYOffset; position = domUtils.getOffset(DOMNode); if (this.affixed === 'top') { position.top += scrollTop; } offsetTop = this.props.offsetTop != null ? this.props.offsetTop : this.props.offset; offsetBottom = this.props.offsetBottom != null ? this.props.offsetBottom : this.props.offset; if (offsetTop == null && offsetBottom == null) { return; } if (offsetTop == null) { offsetTop = 0; } if (offsetBottom == null) { offsetBottom = 0; } if (this.unpin != null && (scrollTop + this.unpin <= position.top)) { affix = false; } else if (offsetBottom != null && (position.top + DOMNode.offsetHeight >= scrollHeight - offsetBottom)) { affix = 'bottom'; } else if (offsetTop != null && (scrollTop <= offsetTop)) { affix = 'top'; } else { affix = false; } if (this.affixed === affix) { return; } if (this.unpin != null) { DOMNode.style.top = ''; } affixType = 'affix' + (affix ? '-' + affix : ''); this.affixed = affix; this.unpin = affix === 'bottom' ? this.getPinnedOffset(DOMNode) : null; if (affix === 'bottom') { DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, 'affix-bottom'); affixPositionTop = scrollHeight - offsetBottom - DOMNode.offsetHeight - domUtils.getOffset(DOMNode).top; } this.setState({ affixClass: affixType, affixPositionTop }); }, checkPositionWithEventLoop() { setTimeout(this.checkPosition, 0); }, componentDidMount() { this._onWindowScrollListener = EventListener.listen(window, 'scroll', this.checkPosition); this._onDocumentClickListener = EventListener.listen(domUtils.ownerDocument(this), 'click', this.checkPositionWithEventLoop); }, componentWillUnmount() { if (this._onWindowScrollListener) { this._onWindowScrollListener.remove(); } if (this._onDocumentClickListener) { this._onDocumentClickListener.remove(); } }, componentDidUpdate(prevProps, prevState) { if (prevState.affixClass === this.state.affixClass) { this.checkPositionWithEventLoop(); } } }; export default AffixMixin;
React Fundamentals/Exercise_Reac_Components/react-components/src/App.js
NikiStanchev/SoftUni
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Slider from './components/Slider' import Roster from './components/Roster' import Char from './components/Char' import Bio from './components/Bio' import observerMenu from './utils/observer' class App extends Component { constructor(params){ super(params) this.state = { focusedChar:0 } this.eventHandler = (newState)=>{ this.setState(newState) } } componentDidMount(){ observerMenu.addObserver("changeFocus", this.eventHandler) } render() { return ( <div className="App"> <Slider/> <Roster/> <Bio params={({id:Number(this.state.id)})}/> </div> ); } } export default App;
assets/jqwidgets/demos/react/app/chart/liveupdates/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxChart from '../../../jqwidgets-react/react_jqxchart.js'; import JqxDropDownList from '../../../jqwidgets-react/react_jqxdropdownlist.js'; class App extends React.Component { componentDidMount() { this.refs.dropDownColors.on('change', (event) => { let value = event.args.item.value; this.refs.myChart.colorScheme(value); this.refs.myChart.update(); }); this.refs.dropDownSeries.on('change', (event) => { let args = event.args; if (args) { let value = args.item.value; let isLine = value.indexOf('line') != -1; let isArea = value.indexOf('area') != -1; let group = this.refs.myChart.seriesGroups()[0]; group.series[0].opacity = group.series[1].opacity = isArea ? 0.7 : 1; group.series[0].lineWidth = group.series[1].lineWidth = isLine ? 2 : 1; this.refs.myChart.seriesGroups()[0].type = value; this.refs.myChart.update(); } }); let data = this.refs.myChart.source(); let timer = setInterval( () => { let max = 800; for (let i = 0; i < data.length; i++) { data[i].a = Math.max(100, (Math.random() * 1000) % max); data[i].b = Math.max(100, (Math.random() * 1000) % max); } this.refs.myChart.update(); }, 3000); } render() { let data = [ { a: 100, b: 200, c: 1 }, { a: 120, b: 140, c: 2 }, { a: 100, b: 110, c: 3 }, { a: 90, b: 135, c: 4 }, { a: 70, b: 210, c: 5 }, { a: 170, b: 210, c: 5 }, { a: 270, b: 350, c: 5 }, { a: 710, b: 410, c: 5 }, { a: 230, b: 305, c: 5 } ]; let padding = { left: 5, top: 5, right: 5, bottom: 5 }; let titlePadding = { left: 0, top: 0, right: 0, bottom: 10 }; let xAxis = { unitInterval: 1, gridLines: { interval: 2 }, valuesOnTicks: false }; let valueAxis = { minValue: 0, maxValue: 1000, title: { text: 'Index Value' }, labels: { horizontalAlignment: 'right' } }; let seriesGroups = [ { type: 'column', columnsGapPercent: 50, alignEndPointsWithIntervals: true, series: [ { dataField: 'a', displayText: 'a', opacity: 1, lineWidth: 1, symbolType: 'circle', fillColorSymbolSelected: 'white', radius: 15 }, { dataField: 'b', displayText: 'b', opacity: 1, lineWidth: 1, symbolType: 'circle', fillColorSymbolSelected: 'white', radius: 15 } ] } ]; let colorsSchemesList = ['scheme01', 'scheme02', 'scheme03', 'scheme04', 'scheme05', 'scheme06', 'scheme07', 'scheme08']; let seriesList = ['splinearea', 'spline', 'column', 'scatter', 'stackedcolumn', 'stackedsplinearea', 'stackedspline']; return ( <div> <JqxChart ref='myChart' style={{ width: 850, height: 500 }} title={'Live updates demo'} description={''} animationDuration={1000} showLegend={true} enableAnimations={true} padding={padding} enableAxisTextAnimation={true} titlePadding={titlePadding} source={data} xAxis={xAxis} valueAxis={valueAxis} colorScheme={'scheme03'} seriesGroups={seriesGroups} /> <table style={{ width: 680 }}> <tbody> <tr> <td style={{ paddingLeft: 50 }}> <p>Select the series type:</p> <JqxDropDownList ref='dropDownSeries' width={200} height={25} selectedIndex={2} dropDownHeight={100} source={seriesList} /> </td> <td> <p>Select color scheme:</p> <JqxDropDownList ref='dropDownColors' width={200} height={25} selectedIndex={2} dropDownHeight={100} source={colorsSchemesList} /> </td> </tr> </tbody> </table> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
examples/huge-apps/routes/Course/routes/Assignments/routes/Assignment/components/Assignment.js
sleexyz/react-router
import React from 'react'; class Assignment extends React.Component { //static loadProps (params, cb) { //cb(null, { //assignment: COURSES[params.courseId].assignments[params.assignmentId] //}); //} render () { //var { title, body } = this.props.assignment; var { courseId, assignmentId } = this.props.params; var { title, body } = COURSES[courseId].assignments[assignmentId] return ( <div> <h4>{title}</h4> <p>{body}</p> </div> ); } } export default Assignment;
src/main.js
bblassingame/at-home-climate-website
import React from 'react' import ReactDOM from 'react-dom' import App from './app' import './reset.css' import './layout-v2/style2.css' /*global process*/ if (process.env.NODE_ENV !== 'production') { console.log('Dev Environment Detected: Starting Application') } ReactDOM.render( <App />, document.getElementById('main') )
src/router.js
trunk-studio/trunksys-lbcs
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import Router from 'react-routing/src/Router'; import http from './core/http'; import App from './components/App'; import ContentPage from './components/ContentPage'; import ContactPage from './components/ContactPage'; import LoginPage from './components/LoginPage'; import RegisterPage from './components/RegisterPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}>{component}</App>; }); on('/contact', async () => <ContactPage />); on('/login', async () => <LoginPage />); on('/register', async () => <RegisterPage />); on('*', async (state) => { const content = await http.get(`/api/content?path=${state.path}`); return content && <ContentPage {...content} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App>); }); export default router;
packages/material-ui-icons/src/Nfc.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 18H4V4h16v16zM18 6h-5c-1.1 0-2 .9-2 2v2.28c-.6.35-1 .98-1 1.72 0 1.1.9 2 2 2s2-.9 2-2c0-.74-.4-1.38-1-1.72V8h3v8H8V8h2V6H6v12h12V6z" /></g> , 'Nfc');
ui/js/dfv/src/admin/edit-pod/main-tabs/dynamic-tab-content.js
pods-framework/pods
/** * External dependencies */ import React from 'react'; import PropTypes from 'prop-types'; /** * WordPress Dependencies */ import { withSelect, withDispatch } from '@wordpress/data'; import { compose } from '@wordpress/compose'; import { __, sprintf } from '@wordpress/i18n'; /** * Pods dependencies */ import FieldSet from 'dfv/src/components/field-set'; import { FIELD_PROP_TYPE_SHAPE } from 'dfv/src/config/prop-types'; const MISSING = __( '[MISSING DEFAULT]', 'pods' ); /** * Process pod values, to correct some inconsistencies from how * the fields expect values compared to the API, specifically for * pick_object fields. * * @param {Array} fields Array of all field data. * @param {Object} allPodValues Map of all field keys to values. * * @return {Array} Updated map of all field keys to values. */ const processAllPodValues = ( fields, allPodValues ) => { // Workaround for the pick_object value: this value should be changed // to a combination of the `pick_object` sent by the API and the // `pick_val`. This was originally done to make the form easier to select. // // But this processing may not need to happen - it'll get set correctly // after a UI update, but will be wrong after the update from saving to the API, // so we'll check that the values haven't already been merged. if ( ! allPodValues.pick_object || ! allPodValues.pick_val ) { return allPodValues; } const pickObjectField = fields.find( ( field ) => 'pick_object' === field.name ); if ( ! pickObjectField ) { return allPodValues; } // Each of the options are under a header to distinguish the types. const pickObjectFieldPossibleOptions = Object.keys( pickObjectField.data || {} ).reduce( ( accumulator, currentKey ) => { if ( 'string' === typeof pickObjectField.data?.[ currentKey ] ) { return [ ...accumulator, pickObjectField.data[ currentKey ], ]; } else if ( 'object' === typeof pickObjectField.data?.[ currentKey ] ) { return [ ...accumulator, ...( Object.keys( pickObjectField.data[ currentKey ] ) ), ]; } return accumulator; }, [] ); const pickObject = allPodValues.pick_object; const pickVal = allPodValues.pick_val; if ( ! pickObjectFieldPossibleOptions.includes( pickObject ) && ! pickObject.endsWith( `-${ pickVal }` ) ) { allPodValues.pick_object = `${ pickObject }-${ pickVal }`; } return allPodValues; }; const getDynamicParamValue = ( paramFormat, paramOption, paramDefault, value ) => { // No param option set, just return the plain param value. if ( ! paramOption ) { return paramFormat; } // Replace the %s with the value as necessary. return sprintf( paramFormat, value || paramDefault || MISSING ); }; const DynamicTabContent = ( { storeKey, podType, podName, tabOptions, allPodFields, allPodValues, setOptionValue, setOptionsValues, } ) => { const fields = tabOptions.map( ( tabOption ) => { const { description: optionDescription, description_param: optionDescriptionParam, description_param_default: optionDescriptionParamDefault, help: optionHelp, help_param: optionHelpParam, help_param_default: optionHelpParamDefault, label: optionLabel, label_param: optionLabelParam, label_param_default: optionLabelParamDefault, placeholder: optionPlaceholder, placeholder_param: optionPlaceholderParam, placeholder_param_default: optionPlaceholderParamDefault, html_content: optionHtmlContent, html_content_param: optionHtmlContentParam, html_content_param_default: optionHtmlContentParamDefault, } = tabOption; return { ...tabOption, description: getDynamicParamValue( optionDescription, optionDescriptionParam, optionDescriptionParamDefault, allPodValues[ optionDescriptionParam ] ), help: getDynamicParamValue( optionHelp, optionHelpParam, optionHelpParamDefault, allPodValues[ optionHelpParam ] ), label: getDynamicParamValue( optionLabel, optionLabelParam, optionLabelParamDefault, allPodValues[ optionLabelParam ] ), placeholder: getDynamicParamValue( optionPlaceholder, optionPlaceholderParam, optionPlaceholderParamDefault, allPodValues[ optionPlaceholderParam ] ), html_content: getDynamicParamValue( optionHtmlContent, optionHtmlContentParam, optionHtmlContentParamDefault, allPodValues[ optionHtmlContentParam ] ), }; } ); return ( <FieldSet storeKey={ storeKey } podType={ podType } podName={ podName } fields={ fields } allPodFields={ allPodFields } allPodValues={ processAllPodValues( allPodFields, allPodValues ) } setOptionValue={ setOptionValue } setOptionsValues={ setOptionsValues } /> ); }; DynamicTabContent.propTypes = { /** * Redux store key. */ storeKey: PropTypes.string.isRequired, /** * Pod type being edited. */ podType: PropTypes.string.isRequired, /** * Pod slug being edited. */ podName: PropTypes.string.isRequired, /** * Array of fields that should be rendered. */ tabOptions: PropTypes.arrayOf( FIELD_PROP_TYPE_SHAPE ).isRequired, /** * All fields from the Pod, including ones that belong to other groups. */ allPodFields: PropTypes.arrayOf( FIELD_PROP_TYPE_SHAPE ).isRequired, /** * A map object with all of the Pod's current values. */ allPodValues: PropTypes.object.isRequired, /** * Function to update the field's value on change. */ setOptionValue: PropTypes.func.isRequired, /** * Function to update the values of multiple options. */ setOptionsValues: PropTypes.func.isRequired, }; export default compose( [ withSelect( ( select, ownProps ) => { const { storeKey } = ownProps; const storeSelect = select( storeKey ); return { podType: storeSelect.getPodOption( 'type' ), podName: storeSelect.getPodOption( 'name' ), }; } ), withDispatch( ( dispatch, ownProps ) => { const { storeKey } = ownProps; return { setOptionsValues: dispatch( storeKey ).setOptionsValues, }; } ), ] )( DynamicTabContent );
src/Parser/Mage/Fire/CONFIG.js
enragednuke/WoWAnalyzer
import React from 'react'; import { Fyruna, Sharrq } from 'MAINTAINERS'; import SPECS from 'common/SPECS'; import SPEC_ANALYSIS_COMPLETENESS from 'common/SPEC_ANALYSIS_COMPLETENESS'; import CombatLogParser from './CombatLogParser'; import CHANGELOG from './CHANGELOG'; export default { spec: SPECS.FIRE_MAGE, maintainers: [Fyruna, Sharrq], completeness: SPEC_ANALYSIS_COMPLETENESS.NEEDS_MORE_WORK, // good = it matches most common manual reviews in class discords, great = it support all important class features changelog: CHANGELOG, description: ( <div> Hello Everyone! We are always looking to improve the Fire Mage Analyzers and Modules; so if you find any issues or if there is something missing that you would like to see added, please open an Issue on GitHub or send a message to Sharrq on Discord (Sharrq#7530) <br /> <br /> Additionally, if you need further assistance in improving your gameplay as a Fire Mage, you can refer to the following resources:<br /> <a href="https://discord.gg/0gLMHikX2aZ23VdA" target="_blank" rel="noopener noreferrer">Mage Class Discord</a> <br /> <a href="https://www.altered-time.com/forum/" target="_blank" rel="noopener noreferrer">Altered Time (Mage Forums/Guides)</a> <br /> <a href="https://www.icy-veins.com/wow/fire-mage-pve-dps-guide" target="_blank" rel="noopener noreferrer">Icy Veins (Fire Mage Guide)</a> <br/> </div> ), specDiscussionUrl: 'https://github.com/WoWAnalyzer/WoWAnalyzer/issues/519', parser: CombatLogParser, path: __dirname, // used for generating a GitHub link directly to your spec };
src/svg-icons/image/style.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageStyle = (props) => ( <SvgIcon {...props}> <path d="M2.53 19.65l1.34.56v-9.03l-2.43 5.86c-.41 1.02.08 2.19 1.09 2.61zm19.5-3.7L17.07 3.98c-.31-.75-1.04-1.21-1.81-1.23-.26 0-.53.04-.79.15L7.1 5.95c-.75.31-1.21 1.03-1.23 1.8-.01.27.04.54.15.8l4.96 11.97c.31.76 1.05 1.22 1.83 1.23.26 0 .52-.05.77-.15l7.36-3.05c1.02-.42 1.51-1.59 1.09-2.6zM7.88 8.75c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-2 11c0 1.1.9 2 2 2h1.45l-3.45-8.34v6.34z"/> </SvgIcon> ); ImageStyle = pure(ImageStyle); ImageStyle.displayName = 'ImageStyle'; ImageStyle.muiName = 'SvgIcon'; export default ImageStyle;
src/components/TMMKButton.js
tiagofumo/renaSMS
import React from 'react'; import { Text } from 'react-native'; import { MKButton, MKColor } from 'react-native-material-kit'; const TMMKButton = ({onPress, backgroundColor, children, style, textStyle, ...custom}) => { const Button = MKButton.coloredButton() .withBackgroundColor(backgroundColor) .withText(children) .withStyle(style) .withTextStyle(textStyle) .withOnPress(onPress) .build(); return (<Button {...custom}/>); }; export default TMMKButton;
src/app/components/AppsIconButton.js
lili668668/lili668668.github.io
import React from 'react' import PropTypes from 'prop-types' import classnames from 'classnames' import { withStyles } from '@material-ui/core/styles' import ButtonBase from '@material-ui/core/ButtonBase' import Typography from '@material-ui/core/Typography' import Grid from '@material-ui/core/Grid' const styles = theme => ({ root: { padding: theme.spacing.unit }, img: { width: 64, height: 64, padding: theme.spacing.unit } }) function AppsIconButton (props) { const { classes, name, alt, src, href, className, style } = props const root = classnames(classes.root, className) return ( <div className={root} style={style} > <ButtonBase component="a" href={href}> <Grid container direction="column" alignItems="center"> <img className={classes.img} style={style} alt={alt} src={src} /> <Typography>{name}</Typography> </Grid> </ButtonBase> </div> ) } AppsIconButton.propTypes = { alt: PropTypes.string.isRequired, src: PropTypes.string.isRequired, href: PropTypes.string.isRequired, children: PropTypes.any, className: PropTypes.string, style: PropTypes.object } export default withStyles(styles)(AppsIconButton)
app/javascript/mastodon/features/lists/components/new_list_form.js
mhffdq/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { changeListEditorTitle, submitListEditor } from '../../../actions/lists'; import IconButton from '../../../components/icon_button'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ label: { id: 'lists.new.title_placeholder', defaultMessage: 'New list title' }, title: { id: 'lists.new.create', defaultMessage: 'Add list' }, }); const mapStateToProps = state => ({ value: state.getIn(['listEditor', 'title']), disabled: state.getIn(['listEditor', 'isSubmitting']), }); const mapDispatchToProps = dispatch => ({ onChange: value => dispatch(changeListEditorTitle(value)), onSubmit: () => dispatch(submitListEditor(true)), }); @connect(mapStateToProps, mapDispatchToProps) @injectIntl export default class NewListForm extends React.PureComponent { static propTypes = { value: PropTypes.string.isRequired, disabled: PropTypes.bool, intl: PropTypes.object.isRequired, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, }; handleChange = e => { this.props.onChange(e.target.value); } handleSubmit = e => { e.preventDefault(); this.props.onSubmit(); } handleClick = () => { this.props.onSubmit(); } render () { const { value, disabled, intl } = this.props; const label = intl.formatMessage(messages.label); const title = intl.formatMessage(messages.title); return ( <form className='column-inline-form' onSubmit={this.handleSubmit}> <label> <span style={{ display: 'none' }}>{label}</span> <input className='setting-text' value={value} disabled={disabled} onChange={this.handleChange} placeholder={label} /> </label> <IconButton disabled={disabled} icon='plus' title={title} onClick={this.handleClick} /> </form> ); } }
src/Header.js
yrezgui/ubuntu-deploy
import React from 'react'; export default class Header extends React.Component { constructor(props) { super(props); } render() { return ( <header className="border bg-header-ubuntu white"> <nav className="clearfix"> <div className="sm-col"> <a href="/" className="btn py2">Ubuntu Deploy</a> </div> <div className="sm-col-right"> <a href="/" className="btn py2">About</a> <a href="/" className="btn py2">GitHub</a> </div> </nav> </header> ); } }
app/jsx/gradebook-history/SearchResults.js
venturehive/canvas-lms
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import { arrayOf, bool, func, node, shape, string } from 'prop-types'; import $ from 'jquery'; import 'jquery.instructure_date_and_time' import I18n from 'i18n!gradebook_history'; import Container from 'instructure-ui/lib/components/Container'; import ScreenReaderContent from 'instructure-ui/lib/components/ScreenReaderContent'; import Spinner from 'instructure-ui/lib/components/Spinner'; import Table from 'instructure-ui/lib/components/Table'; import Typography from 'instructure-ui/lib/components/Typography'; import { getHistoryNextPage } from 'jsx/gradebook-history/actions/SearchResultsActions'; import SearchResultsRow from 'jsx/gradebook-history/SearchResultsRow'; const colHeaders = [ I18n.t('Date'), <ScreenReaderContent>{I18n.t('Anonymous Grading')}</ScreenReaderContent>, I18n.t('Student'), I18n.t('Grader'), I18n.t('Assignment'), I18n.t('Before'), I18n.t('After'), I18n.t('Current') ]; const nearPageBottom = () => ( document.body.clientHeight - (window.innerHeight + window.scrollY) < 100 ); class SearchResultsComponent extends Component { static propTypes = { getNextPage: func.isRequired, fetchHistoryStatus: string.isRequired, caption: node.isRequired, historyItems: arrayOf(shape({ anonymous: bool.isRequired, assignment: string.isRequired, date: string.isRequired, displayAsPoints: bool.isRequired, grader: string.isRequired, gradeAfter: string.isRequired, gradeBefore: string.isRequired, gradeCurrent: string.isRequired, id: string.isRequired, pointsPossibleAfter: string.isRequired, pointsPossibleBefore: string.isRequired, pointsPossibleCurrent: string.isRequired, student: string.isRequired })).isRequired, nextPage: string.isRequired, requestingResults: bool.isRequired }; componentDidMount () { this.attachListeners(); } componentDidUpdate (prevProps) { // if the page doesn't have a scrollbar, scroll event listener can't be triggered if (document.body.clientHeight <= window.innerHeight) { this.getNextPage(); } if (prevProps.historyItems.length < this.props.historyItems.length) { $.screenReaderFlashMessage(I18n.t('More results were added at the bottom of the page.')); } this.attachListeners(); } componentWillUnmount () { this.detachListeners(); } getNextPage = () => { if (!this.props.requestingResults && this.props.nextPage && nearPageBottom()) { this.props.getNextPage(this.props.nextPage); this.detachListeners(); } } attachListeners = () => { if (this.props.requestingResults || !this.props.nextPage) { return; } document.addEventListener('scroll', this.getNextPage); window.addEventListener('resize', this.getNextPage); } detachListeners = () => { document.removeEventListener('scroll', this.getNextPage); window.removeEventListener('resize', this.getNextPage); } hasHistory () { return this.props.historyItems.length > 0; } noResultsFound () { return this.props.fetchHistoryStatus === 'success' && !this.hasHistory(); } showResults = () => ( <div> <Table caption={this.props.caption} > <thead> <tr> {colHeaders.map(header => ( <th scope="col" key={`${header}-column`}>{ header }</th> ))} </tr> </thead> <tbody> {this.props.historyItems.map(item => ( <SearchResultsRow key={`history-items-${item.id}`} item={item} /> ))} </tbody> </Table> </div> ) showStatus = () => { if (this.props.requestingResults) { $.screenReaderFlashMessage(I18n.t('Loading more gradebook history results.')); return ( <Spinner size="small" title={I18n.t('Loading Results')} /> ); } if (this.noResultsFound()) { return (<Typography fontStyle="italic">{I18n.t('No results found.')}</Typography>); } if (!this.props.requestingResults && !this.props.nextPage && this.hasHistory()) { return (<Typography fontStyle="italic">{I18n.t('No more results to load.')}</Typography>); } return null; } render () { return ( <div> {this.hasHistory() && this.showResults()} <Container as="div" textAlign="center" margin="medium 0 0 0"> {this.showStatus()} </Container> </div> ); } } const mapStateToProps = state => ( { fetchHistoryStatus: state.history.fetchHistoryStatus || '', historyItems: state.history.items || [], nextPage: state.history.nextPage || '', requestingResults: state.history.loading || false, } ); const mapDispatchToProps = dispatch => ( { getNextPage: (url) => { dispatch(getHistoryNextPage(url)); } } ); export default connect(mapStateToProps, mapDispatchToProps)(SearchResultsComponent); export { SearchResultsComponent };
src/components/ThreeScene.js
taylord65/taylord65.github.io
import React from 'react'; import * as THREE from 'three'; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"; import { SVGLoader } from "three/examples/jsm/loaders/SVGLoader"; import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js'; import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js'; import { GlitchPass } from 'three/examples/jsm/postprocessing/GlitchPass.js'; import TWEEN from "@tweenjs/tween.js"; import { animateCSS } from '../helpers/animateCSS' import { setBackgroundToBlack } from '../helpers/setBackgroundToBlack' import { cleanMaterial } from '../helpers/cleanMaterial' const cubeSize = 10500; const cubeHeight = 3900; const floorPositionY = -3000; const blockRotateSpeed = 0.004; const glitchTime = 700; class ThreeScene extends React.Component { constructor(props) { super(props) this.state = { showWebGLNotice: false, colorThemeName: 'NEW', glitchEnabled: false }; } componentDidMount() { if (window.WebGLRenderingContext) { this.sceneSetup(); this.generateSceneObjects(); //this.generateFloor(); this.generateGrid(); this.generateTitle(); //this.generateSkybox(); this.glitch(glitchTime); animateCSS('#three', ['fadeIn'], () => { setBackgroundToBlack(); }); this.startAnimationLoop(); window.addEventListener("resize", this.updateDimensions); } else { const span = document.createElement("span"); const message = "Unable to initialize WebGL. Your browser or machine may not support it."; const textContent = document.createTextNode(message); span.appendChild(textContent); this.mount.appendChild(span); this.setState({showWebGLNotice: true}); } } componentWillUnmount() { if (!this.state.showWebGLNotice) { window.removeEventListener("resize", this.updateDimensions); window.cancelAnimationFrame(this.frameId); this.controls.dispose(); this.scene.traverse(object => { if (!object.isMesh) return object.geometry.dispose() if (object.material.isMaterial) { cleanMaterial(object.material) } else { for (const material of object.material) cleanMaterial(material) } }); for (let i = this.scene.children.length - 1; i >= 0; i--) { this.scene.remove(this.scene.children[i]) } this.scene.dispose(); this.scene = null; } } componentDidUpdate(prevProps){ if (!this.state.showWebGLNotice) { if (this.props.blurOn !== prevProps.blurOn) { if (this.props.blurOn) { this.zoomCamera(1); } else { this.zoomCamera(-1); } } } } generateTitle = () => { const loader = new SVGLoader(); // load a SVG resource loader.load( 'name.svg', (data) => { let paths = data.paths; let group = new THREE.Group(); for (let i = 0; i < paths.length; i++) { let path = paths[i]; let material = new THREE.MeshBasicMaterial({ color: path.color, side: THREE.DoubleSide, depthWrite: false }); let shapes = path.toShapes(true); for (let j = 0; j < shapes.length; j++) { let shape = shapes[ j ]; let geometry = new THREE.ShapeBufferGeometry( shape ); geometry.applyMatrix(new THREE.Matrix4().makeScale ( 1, -1, 1 )); let mesh = new THREE.Mesh( geometry, material ); group.add(mesh); } } const scaleAmount = 3; group.scale.set(scaleAmount, scaleAmount, scaleAmount); //Center the SVG let bbox = new THREE.Box3().setFromObject(group); const center = new THREE.Vector3(); let width = bbox.getSize(center).x; let height = bbox.getSize(center).y; group.translateX(-width/2); group.translateY(height/2); this.scene.add(group); }, function (xhr) { //console.log((xhr.loaded / xhr.total * 100) + '% loaded'); }, function (error) { //console.log('An error happened'); } ); }; generateGrid = () => { let material = new THREE.LineBasicMaterial({ color: 0x0c4677 }); let horizontalSquare = (y) => { for (let i=0; i< 4; i++) { let x1, x2, z1, z2; let geometry = new THREE.Geometry(); switch(i) { case 0: x1 = (-1) * cubeSize/2; z1 = cubeSize/2; x2 = cubeSize/2; z2 = cubeSize/2; break; case 1: x1 = cubeSize/2; z1 = cubeSize/2; x2 = cubeSize/2; z2 = (-1) * cubeSize/2; break; case 2: x1 = cubeSize/2; z1 = (-1) * cubeSize/2; x2 = (-1) * cubeSize/2; z2 = (-1) * cubeSize/2; break; case 3: x1 = (-1) * cubeSize/2; z1 = (-1) * cubeSize/2; x2 = (-1) * cubeSize/2; z2 = cubeSize/2; break; default: } geometry.vertices.push( new THREE.Vector3(x1, y, z1), new THREE.Vector3(x2, y, z2) ); let line = new THREE.Line( geometry, material ); this.scene.add( line ); } }; let upRights = () => { for (let i=0; i< 4; i++) { let x, z; let geometry = new THREE.Geometry(); switch(i) { case 0: x = cubeSize/2; z = cubeSize/2; break; case 1: x = (-1) * cubeSize/2; z = cubeSize/2; break; case 2: x = (-1) * cubeSize/2; z = (-1) * cubeSize/2; break; case 3: x = cubeSize/2; z = (-1) * cubeSize/2; break; default: } geometry.vertices.push( new THREE.Vector3(x, cubeHeight, z), new THREE.Vector3(x, floorPositionY, z) ); let line = new THREE.Line( geometry, material ); this.scene.add( line ); } } horizontalSquare(cubeHeight); horizontalSquare(floorPositionY); upRights(); }; getRandomColor = (customThemeName) => { let randomColor; let Theme = this.state.colorThemeName; let colorTheme = { BLACK: { colorName: 'BLACK', colorSet: ['1BE7FF', '6EEB83', 'E4FF1A', 'E8AA14', 'FF5714', 'F46036', '2E294E', '1B998B', 'E71D36', 'C5D86D'] }, WHITE: { colorName: 'WHITE', colorSet: ['7B777D', 'A29F99', 'A3A09A', '85837E', '8892A1', '737075', '57A6CF'] //colorSet: ['1BE7FF', '6EEB83', 'E4FF1A', 'E8AA14', 'FF5714', 'F46036', '2E294E', '1B998B', 'E71D36', 'C5D86D'] }, ALT: { colorName: 'COLORNAME', colorSet: ['363635', '62A87C', '617073', '4D685A', '545775', '202C39', '1F487E', '60B2E5', 'AEECEF'] }, NEW: { colorName: 'NEW', colorSet: ['022B3A', '235789', '4C86A8', '235789', '4C86A8', 'a80707', '8cfc03'] }, CAMO: { colorName: 'CAMO', colorSet: ['BAAD80', '4B6329', '260500', '142513'] } }; if(customThemeName){ randomColor = colorTheme[customThemeName].colorSet[Math.floor(Math.random()*colorTheme[customThemeName].colorSet.length)]; } else { randomColor = colorTheme[Theme].colorSet[Math.floor(Math.random()*colorTheme[Theme].colorSet.length)]; } return parseInt('0x' + randomColor); }; generateSceneObjects = () => { this.group = new THREE.Group(); let geometry = new THREE.BoxGeometry( 40, 30, 40 ); let numObjects = 300; for ( let i = 0; i < numObjects; i ++ ) { let object = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial({ color: this.getRandomColor() }) ); let spread = 5000; object.position.x = (Math.round(Math.random()) * 2 - 1) * Math.random() * spread; object.position.y = (Math.round(Math.random()) * 2 - 1) * Math.random() * spread; object.position.z = (Math.round(Math.random()) * 2 - 1) * Math.random() * spread; object.rotation.x = Math.random() * 2 * Math.PI; object.rotation.y = Math.random() * 2 * Math.PI; object.rotation.z = Math.random() * 2 * Math.PI; let masterScale = 0.95; object.scale.x = (10*Math.random() * 2 + 1)*masterScale; object.scale.y = (5*Math.random() * 2 + 1)*masterScale; object.scale.z = (4*Math.random() * 2 + 1)*masterScale; object.castShadow = true; object.receiveShadow = false; this.group.add( object ); } this.group.scale.set(0.001,0.001,0.001); this.scaleBlocks(); this.scene.add(this.group); }; generateFloor = () => { let loader = new THREE.TextureLoader(); let self = this; const url = 'darkness.png'; loader.load(url, function ( texture ) { texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping; texture.repeat.set( 25, 25 ); let material = new THREE.MeshLambertMaterial({ map : texture }); let geometry = new THREE.PlaneGeometry(cubeSize, cubeSize, 8, 8); let plane = new THREE.Mesh( geometry, material ); plane.rotateX( - Math.PI / 2); plane.position.y = floorPositionY; self.scene.add( plane ); }); }; generateSkybox = () => { let materialArray = []; let texture_ft = new THREE.TextureLoader().load( 'spaceTest.jpg'); let texture_bk = new THREE.TextureLoader().load( 'spaceTest.jpg'); let texture_up = new THREE.TextureLoader().load( 'spaceTest.jpg'); let texture_dn = new THREE.TextureLoader().load( 'spaceTest.jpg'); let texture_rt = new THREE.TextureLoader().load( 'spaceTest.jpg'); let texture_lf = new THREE.TextureLoader().load( 'spaceTest.jpg'); materialArray.push(new THREE.MeshBasicMaterial( { map: texture_ft })); materialArray.push(new THREE.MeshBasicMaterial( { map: texture_bk })); materialArray.push(new THREE.MeshBasicMaterial( { map: texture_up })); materialArray.push(new THREE.MeshBasicMaterial( { map: texture_dn })); materialArray.push(new THREE.MeshBasicMaterial( { map: texture_rt })); materialArray.push(new THREE.MeshBasicMaterial( { map: texture_lf })); for (let i = 0; i < 6; i++) { materialArray[i].side = THREE.BackSide; } const boxDistance = 30000; let skyboxGeo = new THREE.BoxGeometry( boxDistance, boxDistance, boxDistance); let skybox = new THREE.Mesh( skyboxGeo, materialArray ); this.scene.add( skybox ); }; sceneSetup = () => { const width = window.innerWidth; const height = window.innerHeight; this.scene = new THREE.Scene(); this.camera = new THREE.PerspectiveCamera(70, width / height, 1, cubeSize*3 ); this.camera.position.z = 5061; this.camera.position.y = -1144; const light = new THREE.SpotLight( 0xffffff, 0.3 ); const ambientLight = new THREE.AmbientLight( 0x313131 ); light.position.set(0, 5000, 0 ); this.scene.add(light); this.scene.add(ambientLight); this.renderer = new THREE.WebGLRenderer({ antialias: true}); this.renderer.setSize(width, height); this.renderer.setPixelRatio(window.devicePixelRatio); this.renderer.shadowMap.enabled = true; this.renderer.shadowMap.type = THREE.PCFShadowMap; this.controls = new OrbitControls( this.camera, this.renderer.domElement ); this.controls.enabled = true; this.controls.enableZoom = true; this.controls.enablePan = false; this.controls.enableDamping = false; this.controls.maxDistance = 6000; this.composer = new EffectComposer(this.renderer); this.composer.addPass(new RenderPass(this.scene, this.camera)); const glitchPass = new GlitchPass(); this.composer.addPass(glitchPass); this.scene.background = new THREE.Color( 0x000000 ); this.mount.appendChild(this.renderer.domElement); }; startAnimationLoop = () => { this.rotateBlocks(); if (this.state.glitchEnabled) { this.composer.render(); } else { this.renderer.render(this.scene, this.camera); } TWEEN.update(); this.frameId = window.requestAnimationFrame(this.startAnimationLoop); }; zoomCamera = (direction) => { const center = new THREE.Vector3(0,0,0); const zoomAmount = 400; let newLength; let cameraPositionClone = new THREE.Vector3(this.camera.position.x , this.camera.position.y, this.camera.position.z); let distanceFromCenterToCamera = center.distanceTo(cameraPositionClone); if (direction > 0) { newLength = distanceFromCenterToCamera + zoomAmount; } else { newLength = distanceFromCenterToCamera - zoomAmount; } let destinationPosition = cameraPositionClone.sub(center).setLength(newLength).add(center); let tween = new TWEEN.Tween(this.camera.position).to(destinationPosition, 180).start(); return tween; }; rotateBlocks = () => { this.group.children.forEach((object) => { object.rotateX(blockRotateSpeed); //object.rotateY(blockRotateSpeed); //object.rotateZ(blockRotateSpeed); }); }; scaleBlocks = () => { //Scale the cluster out after a delay setTimeout(() => { let tween = new TWEEN.Tween(this.group.scale).to({x: 1, y: 1, z: 1}, 160).start(); return tween; }, 500); }; glitch = (time) => { this.setState({glitchEnabled: true}); setTimeout(() => { this.setState({ glitchEnabled: false }); }, time); }; updateDimensions = () => { this.renderer.setSize(window.innerWidth, window.innerHeight) this.camera.aspect = window.innerWidth / window.innerHeight; this.camera.updateProjectionMatrix(); }; render() { return ( <div id="three" className={`${this.state.showWebGLNotice ? 'webgl-notice' : ''}`} ref={mount => (this.mount = mount)} /> ) } } export default ThreeScene;
src/Stepper/StepLabel.js
hai-cea/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import CheckCircle from '../svg-icons/action/check-circle'; import SvgIcon from '../SvgIcon'; const getStyles = ({active, completed, disabled}, {muiTheme, stepper}) => { const { textColor, disabledTextColor, iconColor, inactiveIconColor, } = muiTheme.stepper; const {baseTheme} = muiTheme; const {orientation} = stepper; const styles = { root: { height: orientation === 'horizontal' ? 72 : 64, color: textColor, display: 'flex', alignItems: 'center', fontFamily: baseTheme.fontFamily, fontSize: 14, paddingLeft: 14, paddingRight: 14, }, icon: { color: iconColor, display: 'block', fontSize: 24, width: 24, height: 24, }, iconContainer: { paddingRight: 8, }, }; if (active) { styles.root.fontWeight = 500; } if (!completed && !active) { styles.icon.color = inactiveIconColor; } if (disabled) { styles.icon.color = inactiveIconColor; styles.root.color = disabledTextColor; styles.root.cursor = 'default'; } return styles; }; const renderIcon = (completed, icon, styles) => { const iconType = typeof icon; if (iconType === 'number' || iconType === 'string') { if (completed) { return ( <CheckCircle color={styles.icon.color} style={styles.icon} /> ); } return ( <SvgIcon color={styles.icon.color} style={styles.icon}> <circle cx="12" cy="12" r="10" /> <text x="12" y="16" textAnchor="middle" fontSize="12" fill="#fff" > {icon} </text> </SvgIcon> ); } return icon; }; const StepLabel = (props, context) => { const { active, // eslint-disable-line no-unused-vars children, completed, icon: userIcon, iconContainerStyle, last, // eslint-disable-line no-unused-vars style, ...other } = props; const {prepareStyles} = context.muiTheme; const styles = getStyles(props, context); const icon = renderIcon(completed, userIcon, styles); return ( <span style={prepareStyles(Object.assign(styles.root, style))} {...other}> {icon && ( <span style={prepareStyles(Object.assign(styles.iconContainer, iconContainerStyle))}> {icon} </span> )} {children} </span> ); }; StepLabel.muiName = 'StepLabel'; StepLabel.propTypes = { /** * Sets active styling. Overrides disabled coloring. */ active: PropTypes.bool, /** * The label text node */ children: PropTypes.node, /** * Sets completed styling. Overrides disabled coloring. */ completed: PropTypes.bool, /** * Sets disabled styling. */ disabled: PropTypes.bool, /** * The icon displayed by the step label. */ icon: PropTypes.oneOfType([ PropTypes.element, PropTypes.string, PropTypes.number, ]), /** * Override the inline-styles of the icon container element. */ iconContainerStyle: PropTypes.object, /** * @ignore */ last: PropTypes.bool, /** * Override the inline-style of the root element. */ style: PropTypes.object, }; StepLabel.contextTypes = { muiTheme: PropTypes.object.isRequired, stepper: PropTypes.object, }; export default StepLabel;
example/src/index.js
luisfcofv/react-native-deep-linking
import React, { Component } from 'react'; import { Button, Linking, StyleSheet, Text, View } from 'react-native'; import DeepLinking from 'react-native-deep-linking'; export default class App extends Component { state = { response: {}, }; componentDidMount() { DeepLinking.addScheme('example://'); Linking.addEventListener('url', this.handleUrl); DeepLinking.addRoute('/test', (response) => { // example://test this.setState({ response }); }); DeepLinking.addRoute('/test/:id', (response) => { // example://test/23 this.setState({ response }); }); DeepLinking.addRoute('/test/:id/details', (response) => { // example://test/100/details this.setState({ response }); }); Linking.getInitialURL().then((url) => { if (url) { Linking.openURL(url); } }).catch(err => console.error('An error occurred', err)); } componentWillUnmount() { Linking.removeEventListener('url', this.handleUrl); } handleUrl = ({ url }) => { Linking.canOpenURL(url).then((supported) => { if (supported) { DeepLinking.evaluateUrl(url); } }); } render() { return ( <View style={styles.container}> <View style={styles.container}> <Button onPress={() => Linking.openURL('example://test')} title="Open example://test" /> <Button onPress={() => Linking.openURL('example://test/23')} title="Open example://test/23" /> <Button onPress={() => Linking.openURL('example://test/100/details')} title="Open example://test/100/details" /> </View> <View style={styles.container}> <Text style={styles.text}>{this.state.response.scheme ? `Url scheme: ${this.state.response.scheme}` : ''}</Text> <Text style={styles.text}>{this.state.response.path ? `Url path: ${this.state.response.path}` : ''}</Text> <Text style={styles.text}>{this.state.response.id ? `Url id: ${this.state.response.id}` : ''}</Text> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, text: { fontSize: 18, margin: 10, }, });
src/encoded/static/components/news.js
T2DREAM/t2dream-portal
import React from 'react'; import PropTypes from 'prop-types'; import moment from 'moment'; import querystring from 'querystring'; import _ from 'underscore'; import url from 'url'; import * as globals from './globals'; import { Panel, PanelBody } from '../libs/bootstrap/panel'; // Display a news preview item from a search result @graph object. const NewsPreviewItem = (props) => { const { item } = props; return ( <div key={item['@id']} className="news-listing-item"> <h3>{item.title}</h3> <h4>{moment.utc(item.date_created).format('MMMM D, YYYY')}</h4> <div className="news-excerpt">{item.news_excerpt}</div> <div className="news-listing-readmore"> <a className="btn btn-info btn-sm" href={item['@id']} title={`View news post for ${item.title}`} key={item['@id']}>Read more</a> </div> </div> ); }; NewsPreviewItem.propTypes = { item: PropTypes.object.isRequired, // News search result object to display }; // Display a list of news preview items from search results. const NewsPreviews = (props) => { const { items } = props; if (items && items.length) { return ( <div className="news-listing"> {items.map(item => ( <NewsPreviewItem key={item['@id']} item={item} /> ))} </div> ); } return <div className="news-empty">No news available at this time</div>; }; NewsPreviews.propTypes = { items: PropTypes.array, // Items from search result @graph }; NewsPreviews.defaultProps = { items: null, }; export default NewsPreviews; // Default news facet-rendering component for any type of facet not specifically registered to render // in its own component, so the vast majority of news facets use this component. const DefaultFacet = (props) => { const { facet, baseUri, searchFilters } = props; // Get the query string portion of the base URI, if any. This tells us if we need to append // new query string parameters with a '?' or a '&'. const query = url.parse(baseUri).search; return ( <div key={facet.field} className="news-facet"> <div className="news-facet__title"> {facet.title} </div> <ul className="news-facet__items"> {facet.nonEmptyTerms.map((term) => { // Make the facet term link either the current URI appended with // the facet field and term, or from any matching filter’s `remove` // URI. Have to parse the `remove` URI to trim any vestiges of add // query string. let termFilter = searchFilters[facet.field] && searchFilters[facet.field][term.key] && searchFilters[facet.field][term.key].remove; if (termFilter && termFilter[termFilter.length - 1] === '?') { termFilter = termFilter.slice(0, -1); } const qs = globals.encodedURIComponent(`${facet.field}=${term.key}`); const termHref = termFilter || `${baseUri}${query ? '&' : '?'}${qs}`; return ( <li key={term.key} className="news-facet__item"> <a href={termHref} className={termFilter ? 'selected' : ''}> <span className="news-facet__item-title"> {term.key}&nbsp; </span> <span className="news-facet__item-count"> ({term.doc_count}) </span> </a> </li> ); })} </ul> </div> ); }; DefaultFacet.propTypes = { facet: PropTypes.object.isRequired, // One facet from search results baseUri: PropTypes.string.isRequired, // Current URI and query string searchFilters: PropTypes.object.isRequired, // Search-result filter object; see <NewsFacets /> }; // Register this component to be the fallback facet-display component used when no other facet // field has been registered to specifically render that kind of facet. globals.facetView.register(DefaultFacet, ''); globals.facetView.fallback = () => DefaultFacet; // Special news facet-rendering component to render facets with facet.field==='month_released'. const DateFacet = (props) => { const { facet, baseUri, searchFilters } = props; let allYearsUri = ''; let inMonthUri = ''; let queryParms = {}; let yearsSelected; let selectedMonthYears = []; // Array of years for which a month is selected // Generate the href for the "All years" facet term if we need one. This involves removing // all (normally one) year_released parameters from the query string. Start by getting the // query string portion of the base URI, if any. const baseUriComps = url.parse(baseUri); if (baseUriComps.search) { // A query string exists. Parse it to see if it has one or more year_released // parameters. If it does, delete it. Have to strip the first character off the query // string because it's always a question mark which querystring.parse can't handle. queryParms = querystring.parse(baseUriComps.search.substring(1)); // Generate the "All years" facet term link, but only if one or more years is currently // selected. if (queryParms.year_released) { // At least one "year_released" query string parameter found. First get what their // values are so we can display it in the facet title. yearsSelected = (typeof queryParms.year_released === 'string') ? [queryParms.year_released] : queryParms.year_released; // Now delete the year_released query string parameters and generate an href // without them to use to clear the year while leaving other query string // parameters intact. Use this for the 'All years' static facet item. const allYearsQueries = _(queryParms).omit(['year_released', 'month_released']); const allYearsQS = querystring.stringify(allYearsQueries); allYearsUri = `${baseUriComps.pathname}${allYearsQS ? `?${allYearsQS}` : ''}`; } // Now calculate a URI with month_released removed, for individual month facet term // hrefs while another individual month is selected. if (queryParms.month_released) { // One of more month_released in the given query string. Generate a new query // without any months selected. When we render the link, we'll just add the current // facet term month. const monthRemovedQueries = _(queryParms).omit('month_released'); inMonthUri = `${baseUriComps.pathname}?${querystring.stringify(monthRemovedQueries)}`; // If at least one month is selected, we'll only show "All {year}" facets for those // selected months. So make an array of years that cover the currently selected // months. Of course through the UI only one month_released can occur -- this // covers the case where the user directly manipulated the URL. if (typeof queryParms.month_released === 'string') { // Only one month selected. Just get its year. selectedMonthYears = [queryParms.month_released.substr(0, 4)]; } else { // Multiple months selected in an array, so get all their years. selectedMonthYears = queryParms.month_released.map(monthReleased => monthReleased.substr(0, 4)); } } else { inMonthUri = baseUri; } } // If no baseUriComps.search exists, then no query string exists. // If >= 12 (a year) of facets to display, set a flag to know that we need to coalesce // older months into years. Don't coalesce if a year is currently selected. const coalesce = !yearsSelected && facet.nonEmptyTerms.length > 12; // Generate lists of facet terms to render based on whether we have to coalesce past years // or not. let trimmedMonthTerms = []; let coYearGroups = {}; let inYearGroups = {}; let years = []; if (coalesce) { // We have enough months in a facet to justify coalescing past years. First make a // YYYY-MM string for 11 months before now for something to compare against. const earliestMonth = moment().subtract(11, 'months').format('YYYY-MM'); // Break terms into two keys in an object: one with the key `in` that's an array of all // terms that get rendered as individual months within the past 11 months, and one with // the key `co` with all the terms that need to be coalesced into years. const trimmedMonthGroups = _(facet.nonEmptyTerms).groupBy(term => ((term.key >= earliestMonth) ? 'in' : 'co')); // Get the terms from the past 11 months we individually render. trimmedMonthTerms = trimmedMonthGroups.in; // Group the coalesced terms into an object keyed by year, and also make a reverse- // sorted list of years. Also group the individual terms in case we need to sum up // overlapping years. coYearGroups = _(trimmedMonthGroups.co).groupBy(term => term.key.substr(0, 4)); inYearGroups = _(trimmedMonthGroups.in).groupBy(term => term.key.substr(0, 4)); years = Object.keys(coYearGroups).sort((a, b) => ((a < b) ? 1 : (b < a ? -1 : 0))); // If at least one individual month is selected, only include years for those selected // months. if (selectedMonthYears.length) { years = _(years).filter(year => selectedMonthYears.indexOf(year) !== -1); } } else { // Not enough months to display in a facet to justify coalescing past years. Just sort // and display all available facet terms. trimmedMonthTerms = facet.nonEmptyTerms; } // Sort the individual month terms by date. trimmedMonthTerms = trimmedMonthTerms.sort((a, b) => ((a.key < b.key) ? 1 : (b.key < a.key ? -1 : 0))); return ( <div key={facet.field} className="news-facet"> <div className="news-facet__title"> Months {yearsSelected ? <span> for {yearsSelected.join(', ')}</span> : null} </div> <ul className="news-facet__items"> {trimmedMonthTerms.map((term) => { // Loop to display the individual month terms. Make the facet term link // either the current URI appended with the facet field and term, or from // any matching filter’s `remove` URI. Have to parse the `remove` URI to // trim any vestiges of add query string. let termFilter = searchFilters[facet.field] && searchFilters[facet.field][term.key] && searchFilters[facet.field][term.key].remove; if (termFilter && termFilter[termFilter.length - 1] === '?') { termFilter = termFilter.slice(0, -1); } const qs = globals.encodedURIComponent(`${facet.field}=${term.key}`); const termHref = termFilter || `${inMonthUri}${baseUriComps.search ? '&' : '?'}${qs}`; return ( <li key={term.key} className="news-facet__item"> <a href={termHref} className={termFilter ? 'selected' : ''}> <span className="news-facet__item-title"> {moment(term.key).format('MMMM YYYY')}&nbsp; </span> <span className="news-facet__item-count"> ({term.doc_count}) </span> </a> </li> ); })} {years.map((year) => { // Loop to display the coalesced year terms. Sum up the doc_counts for the // year being rendered. If we have overlapping term years, we have to add // those to the total too. let yearTotal = coYearGroups[year].reduce((total, term) => total + term.doc_count, 0); if (inYearGroups[year]) { yearTotal += inYearGroups[year].reduce((total, term) => total + term.doc_count, 0); } // Calculate the href. Works differently for coalesced facet terms because // only one can be selected at a time. const qs = globals.encodedURIComponent(`year_released=${year}`); const termHref = `${baseUri}${baseUriComps.search ? '&' : '?'}${qs}`; return ( <li key={year} className="news-facet__item"> <a href={termHref}> <span className="news-facet__item-title"> All {year}&nbsp; </span> <span className="news-facet__item-count"> ({yearTotal}) </span> </a> </li> ); })} {yearsSelected ? <li className="news-facet__item"> <a href={allYearsUri}> <span className="news-facet__item-title">All years</span> </a> </li> : null} </ul> </div> ); }; DateFacet.propTypes = { facet: PropTypes.object.isRequired, // One facet from search results baseUri: PropTypes.string.isRequired, // Current URI and query string searchFilters: PropTypes.object.isRequired, // Search-result filter object; see <NewsFacets /> }; globals.facetView.register(DateFacet, 'month_released'); // Display the news facets. const NewsFacets = (props) => { const { facets, filters, baseUri } = props; // Filter out facets that have all-zero term counts. Also attach a filtered list of non- // empty terms to each facet so that we only display those. const nonEmptyFacets = facets.filter((facet) => { // Filter out terms with zero counts. const nonEmptyTerms = facet.terms.filter(term => term.doc_count); // Attach the filtered term list to the facet, and return whether there were any terms // left after filtering. Also set @type of the facet so that we can use the view // registry lookup. facet.nonEmptyTerms = nonEmptyTerms; facet['@type'] = [facet.field]; return !!nonEmptyTerms.length; }); // Now generate an object representing the search-result filters that's dereferenceable // as filters[facet.field][term.key] to avoid doing a search of the filters array for each // inner iteration of the facet display loop. If we have no query string, filters can have // zero elements in it. const searchFilters = {}; if (filters.length) { filters.forEach((filter) => { if (!searchFilters[filter.field]) { // A key for the filter's field doesn't exist, so make it an empty object we can add to // on the next line. searchFilters[filter.field] = {}; } searchFilters[filter.field][filter.term] = filter; }); } return ( <div className="news-facets"> {nonEmptyFacets.map((facet) => { const FacetView = globals.facetView.lookup(facet); return <FacetView key={facet.field} facet={facet} baseUri={baseUri} searchFilters={searchFilters} />; })} </div> ); }; NewsFacets.propTypes = { facets: PropTypes.array.isRequired, // Array of facets, each containing an array of facet items filters: PropTypes.array.isRequired, // Array of filters from the search results baseUri: PropTypes.string.isRequired, // Current URI and query string }; // Rendering component for the stand-alone news preview page. const News = (props) => { const { context } = props; const items = context['@graph']; const facets = context.facets; // Only display the full news page if the current query string and data give us news items // to display. if (context['@graph'].length && facets) { return ( <Panel> <PanelBody> <div className="news-page"> <div className="news-page__previews"> <div className="news-page__previews-title"> <h1>News</h1> </div> <NewsPreviews items={items} /> </div> <div className="news-page__facets"> <NewsFacets facets={facets} filters={context.filters} baseUri={context['@id']} /> </div> </div> </PanelBody> </Panel> ); } // Either the query string or the current data aren't giving us any news items to display. // Just show a message. return ( <Panel addClasses="news-blank"> <h2>No matching news items</h2> <a href="/news/">Latest Common Metabolic Diseases Genome Atlas News</a> </Panel> ); }; News.propTypes = { context: PropTypes.object.isRequired, // Search results }; globals.contentViews.register(News, 'News');
src/content/commands/mount.js
jessepollak/command
import $ from 'jquery' import ReactDOM from 'react-dom' import React from 'react' function getContainer() { let $container = $('.command__container') if (!$container.length) { $container = $('<div>') .addClass('command__container') .appendTo('body') } return $container[0] } /** * mountReactComponent * * This function is a helper that makes it easy to mount a * command that displays a React component. * * @param {React.Component} Component - the React component to mount * @param {Field} field - the field to mount on * @param {function} onDone - completed callback * @param {fucntion} onInsert - a callback to insert Types to the Field * * Usage: * * export let mount = mountReactComponent.bind(null, Component) */ export function mountReactComponent(Component, field, onDone, onInsert) { let caretOffset = field.getCaretOffset() let container = getContainer() let _onDone = (result) => { ReactDOM.unmountComponentAtNode(container) onDone(result) } ReactDOM.render( <Component field={field} top={caretOffset.top} left={caretOffset.left} onInsert={onInsert} onDone={_onDone} container={container} />, container ) }
app/index.js
BoringTorvalds/mirror-frontend
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Router, hashHistory } from 'react-router'; import ready from 'domready' import { syncHistoryWithStore } from 'react-router-redux'; import routes from './routes'; import configureStore from './store/configureStore'; import './app.global.css'; import * as actions from './actions/websocket'; const store = configureStore(); const history = syncHistoryWithStore(hashHistory, store); store.dispatch(actions.connect()); ready(()=>{ render( <Provider store={store}> <Router history={history} routes={routes} /> </Provider>, document.getElementById('root') ); });
src/components/Footer/Footer.js
FamilyPlanerTeam/family-planner
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Footer.css'; import Link from '../Link'; class Footer extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <span className={s.text}>© Your Company</span> <span className={s.spacer}>·</span> <Link className={s.link} to="/">Home</Link> <span className={s.spacer}>·</span> <Link className={s.link} to="/admin">Admin</Link> <span className={s.spacer}>·</span> <Link className={s.link} to="/privacy">Privacy</Link> <span className={s.spacer}>·</span> <Link className={s.link} to="/not-found">Not Found</Link> </div> </div> ); } } export default withStyles(s)(Footer);
src/components/Nav.js
phuchle/recipeas
import React from 'react'; import { Link } from 'react-router-dom'; import { Navbar, Nav, NavItem } from 'react-bootstrap'; const Navigation = (props) => { return ( <Navbar> <Navbar.Header> <Navbar.Brand> <Link to="/"> Recipeas </Link> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav> <NavItem href="https://github.com/phuchle/recipeas"> Source Code </NavItem> </Nav> </Navbar.Collapse> </Navbar> ); }; export default Navigation;
app/javascript/mastodon/features/account_timeline/components/header.js
verniy6462/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import InnerHeader from '../../account/components/header'; import ActionBar from '../../account/components/action_bar'; import MissingIndicator from '../../../components/missing_indicator'; import ImmutablePureComponent from 'react-immutable-pure-component'; export default class Header extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map, me: PropTypes.number.isRequired, onFollow: PropTypes.func.isRequired, onBlock: PropTypes.func.isRequired, onMention: PropTypes.func.isRequired, onReport: PropTypes.func.isRequired, onMute: PropTypes.func.isRequired, onBlockDomain: PropTypes.func.isRequired, onUnblockDomain: PropTypes.func.isRequired, }; static contextTypes = { router: PropTypes.object, }; handleFollow = () => { this.props.onFollow(this.props.account); } handleBlock = () => { this.props.onBlock(this.props.account); } handleMention = () => { this.props.onMention(this.props.account, this.context.router.history); } handleReport = () => { this.props.onReport(this.props.account); } handleMute = () => { this.props.onMute(this.props.account); } handleBlockDomain = () => { const domain = this.props.account.get('acct').split('@')[1]; if (!domain) return; this.props.onBlockDomain(domain, this.props.account.get('id')); } handleUnblockDomain = () => { const domain = this.props.account.get('acct').split('@')[1]; if (!domain) return; this.props.onUnblockDomain(domain, this.props.account.get('id')); } render () { const { account, me } = this.props; if (account === null) { return <MissingIndicator />; } return ( <div className='account-timeline__header'> <InnerHeader account={account} me={me} onFollow={this.handleFollow} /> <ActionBar account={account} me={me} onBlock={this.handleBlock} onMention={this.handleMention} onReport={this.handleReport} onMute={this.handleMute} onBlockDomain={this.handleBlockDomain} onUnblockDomain={this.handleUnblockDomain} /> </div> ); } }
app/components/shared/Autocomplete/Dialog/index.js
fotinakis/buildkite-frontend
import React from 'react'; import PropTypes from 'prop-types'; import Dialog from '../../Dialog'; import SearchField from '../../SearchField'; import Suggestion from './suggestion'; import ErrorMessage from '../error-message'; import Loader from '../loader'; class AutocompleteDialog extends React.PureComponent { static propTypes = { isOpen: PropTypes.bool.isRequired, onRequestClose: PropTypes.func.isRequired, width: PropTypes.number, onSelect: PropTypes.func.isRequired, onSearch: PropTypes.func.isRequired, placeholder: PropTypes.string, selectLabel: PropTypes.string, items: PropTypes.array }; state = { searching: false }; componentWillReceiveProps(nextProps) { if (nextProps.items && this.state.searching) { // We can turn off searching now since we've got some items this.setState({ searching: false }); } } clear() { this._searchField.clear(); } focus() { this._searchField.focus(); } selectItem(item) { this._searchField.blur(); this.props.onSelect(item); this.props.onRequestClose(); } isNonSuggestionComponent(node) { return node && node.type && (node.type.displayName === ErrorMessage.displayName || node.type.displayName === Loader.displayName); } render() { return ( <Dialog isOpen={this.props.isOpen} onRequestClose={this.props.onRequestClose} width={this.props.width} > <div className="px4 pt4 pb3"> <SearchField ref={(_searchField) => this._searchField = _searchField} onChange={this.handleSearchChange} onKeyDown={this.handleKeyDown} placeholder={this.props.placeholder} searching={this.state.searching} /> </div> <hr className="m0 bg-gray border-none height-0" style={{ height: 1 }} /> {this.renderSuggestions()} </Dialog> ); } renderSuggestions() { const items = this.props.items; // Insert a seperator between each section const suggestions = []; let key = 0; for (let index = 0, length = items.length; index < length; index++) { if (this.isNonSuggestionComponent(items[index])) { suggestions.push( <div key={key += 1} className="px3 py2 center"> {items[index]} </div> ); } else { suggestions.push( <Suggestion key={key += 1} className="rounded" suggestion={items[index][1]} onSelect={this.handleSuggestionSelection} selectLabel={this.props.selectLabel} > {items[index][0]} </Suggestion> ); suggestions.push(<hr key={key += 1} className="p0 m0 bg-gray" style={{ border: "none", height: 1 }} />); } } return ( <div className="block" style={{ width: "100%", maxHeight: 250, height: '50vh', overflow: 'auto' }}> <ul className="list-reset m0 p0"> {suggestions} </ul> </div> ); } handleSuggestionSelection = (suggestion) => { this.selectItem(suggestion); }; handleSearchChange = (value) => { this.props.onSearch(value); this.setState({ searching: true }); }; } AutocompleteDialog.ErrorMessage = ErrorMessage; AutocompleteDialog.Loader = Loader; export default AutocompleteDialog;
src/screens/App/screens/Home/components/Movie/index.js
tulsajs/redux-workshop
import React from 'react'; import { Link } from 'react-router-dom'; import { Text, Box } from 'BuildingBlocks'; const baseURL = 'https://image.tmdb.org/t/p/w500/'; export default ({ movie: { id, title, posterPath } }) => ( <Box width={[1, 1 / 2, 1 / 3, 1 / 4, 1 / 5, 1 / 6]} p={[0, 2, 4]}> <Link to={`/${id}`}> <img style={{ width: '100%' }} src={`${baseURL}${posterPath}`} alt={title} /> </Link> <Text textAlign="center" fontSize={[4, 2]} m={2}> <Link to={`/${id}`}>{title}</Link> </Text> </Box> );
docs/pages/api-docs/toggle-button.js
lgollut/material-ui
import React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown'; const pageFilename = 'api/toggle-button'; const requireRaw = require.context('!raw-loader!./', false, /\/toggle-button\.md$/); export default function Page({ docs }) { return <MarkdownDocs docs={docs} />; } Page.getInitialProps = () => { const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw }); return { demos, docs }; };
src/svg-icons/action/perm-phone-msg.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPermPhoneMsg = (props) => ( <SvgIcon {...props}> <path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.58l2.2-2.21c.28-.27.36-.66.25-1.01C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM12 3v10l3-3h6V3h-9z"/> </SvgIcon> ); ActionPermPhoneMsg = pure(ActionPermPhoneMsg); ActionPermPhoneMsg.displayName = 'ActionPermPhoneMsg'; ActionPermPhoneMsg.muiName = 'SvgIcon'; export default ActionPermPhoneMsg;
reactNativeThermo/index.ios.js
jontore/web_bluetooth_demo
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class reactNativeThermo 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('reactNativeThermo', () => reactNativeThermo);
admin/src/components/SecondaryNavigation.js
mekanics/keystone
import blacklist from 'blacklist'; import classnames from 'classnames'; import React from 'react'; import { Container } from 'elemental'; var SecondaryNavItem = React.createClass({ displayName: 'SecondaryNavItem', propTypes: { className: React.PropTypes.string, children: React.PropTypes.node.isRequired, href: React.PropTypes.string.isRequired, title: React.PropTypes.string, }, render () { return ( <li className={this.props.className}> <a href={this.props.href} title={this.props.title} tabIndex="-1"> {this.props.children} </a> </li> ); }, }); var SecondaryNavigation = React.createClass({ displayName: 'SecondaryNavigation', propTypes: { currentListKey: React.PropTypes.string, lists: React.PropTypes.array.isRequired, }, renderNavigation (lists) { if (!lists || lists.length <= 1) return null; let navigation = lists.map((list) => { let href = list.external ? list.path : ('/keystone/' + list.path); let className = (this.props.currentListKey && this.props.currentListKey === list.path) ? 'active' : null; return ( <SecondaryNavItem className={className} href={href}> {list.label} </SecondaryNavItem> ); }); return ( <ul className="app-nav app-nav--secondary app-nav--left"> {navigation} </ul> ); }, render () { return ( <nav className="secondary-navbar"> <Container clearfix> {this.renderNavigation(this.props.lists)} </Container> </nav> ); } }); module.exports = SecondaryNavigation;
src/svg-icons/action/perm-scan-wifi.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPermScanWifi = (props) => ( <SvgIcon {...props}> <path d="M12 3C6.95 3 3.15 4.85 0 7.23L12 22 24 7.25C20.85 4.87 17.05 3 12 3zm1 13h-2v-6h2v6zm-2-8V6h2v2h-2z"/> </SvgIcon> ); ActionPermScanWifi = pure(ActionPermScanWifi); ActionPermScanWifi.displayName = 'ActionPermScanWifi'; ActionPermScanWifi.muiName = 'SvgIcon'; export default ActionPermScanWifi;
src/js/admin/articles/filters/filter-select/filter-select.js
ucev/blog
import React from 'react' import { connect } from 'react-redux' import FilterItem, { FilterItemLabel, FilterItemSelect } from '../filter-item' import { filterOptionChange } from '$actions/articles' class FilterSelect extends React.Component { constructor (props) { super(props) this.change = this.change.bind(this) } change (value) { var title = this.props.title this.props.change(title, value) } refHandle (e) { this.select = e } render () { const options = this.props.options.map(opt => ( <option value={opt.value} key={opt.value}> {opt.title} </option> )) return ( <FilterItem> <FilterItemLabel title={this.props.label} /> <FilterItemSelect value={this.props.value} change={this.change}> {options} </FilterItemSelect> </FilterItem> ) } } const mapStateToProps = () => ({}) const mapDispatchToProps = dispatch => ({ change: (title, value) => { dispatch(filterOptionChange(title, value)) }, }) const _FilterSelect = connect( mapStateToProps, mapDispatchToProps )(FilterSelect) export default _FilterSelect
src/parser/rogue/subtlety/modules/core/NightbladeUptime.js
FaideWW/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import Analyzer from 'parser/core/Analyzer'; import Enemies from 'parser/shared/modules/Enemies'; import StatisticBox from 'interface/others/StatisticBox'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage } from 'common/format'; import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER'; class NightbladeUptime extends Analyzer { static dependencies = { enemies: Enemies, }; get percentUptime() { return this.enemies.getBuffUptime(SPELLS.NIGHTBLADE.id) / this.owner.fightDuration; } get thresholds() { return { actual: this.percentUptime, isLessThan: { minor: 0.98, average: 0.95, major: 0.9, }, style: 'percentage', }; } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.NIGHTBLADE.id} />} value={`${formatPercentage(this.percentUptime)}%`} label="Nightblade Uptime" /> ); } statisticOrder = STATISTIC_ORDER.CORE(100); } export default NightbladeUptime;
packages/ringcentral-widgets/components/AlertRenderer/RateExceededAlert/index.js
ringcentral/ringcentral-js-widget
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import errorMessages from 'ringcentral-integration/modules/RateLimiter/errorMessages'; import FormattedMessage from '../../FormattedMessage'; import i18n from './i18n'; function calculateState(duration, timestamp) { return { ttl: Math.max(Math.floor((duration - (Date.now() - timestamp)) / 1000), 0), }; } class RequestRateExceededAlert extends Component { constructor(props) { super(props); this.state = calculateState(props.duration, props.timestamp); } componentDidMount() { this.timer = setInterval(() => { this.setState(calculateState(this.props.duration, this.props.timestamp)); }, 1000); } componentWillReceiveProps(nextProps) { this.setState(calculateState(nextProps.duration, nextProps.timestamp)); } componentWillUnmount() { clearInterval(this.timer); } render() { return ( <FormattedMessage message={i18n.getString('rateExceeded', this.props.currentLocale)} values={{ ttl: this.state.ttl }} /> ); } } RequestRateExceededAlert.propTypes = { timestamp: PropTypes.number.isRequired, duration: PropTypes.number.isRequired, currentLocale: PropTypes.string.isRequired, }; RequestRateExceededAlert.handleMessage = ({ message }) => message === errorMessages.rateLimitReached; export default RequestRateExceededAlert;
app/components/List/index.js
spiridonov-oa/management-tool
import React from 'react'; import Ul from './Ul'; import Wrapper from './Wrapper'; function List(props) { const ComponentToRender = props.component; let content = (<div></div>); // If we have items, render them if (props.items) { content = props.items.map((item, index) => ( <ComponentToRender key={`item-${index}`} item={item} /> )); } else { // Otherwise render a single component content = (<ComponentToRender />); } return ( <Wrapper> <Ul> {content} </Ul> </Wrapper> ); } List.propTypes = { component: React.PropTypes.func.isRequired, items: React.PropTypes.array, }; export default List;
docs/src/NavMain.js
yuche/react-bootstrap
import React from 'react'; import { Link } from 'react-router'; import Navbar from '../../src/Navbar'; import Nav from '../../src/Nav'; const NAV_LINKS = { 'introduction': { link: 'introduction', title: 'Introduction' }, 'getting-started': { link: 'getting-started', title: 'Getting started' }, 'components': { link: 'components', title: 'Components' }, 'support': { link: 'support', title: 'Support' } }; const NavMain = React.createClass({ propTypes: { activePage: React.PropTypes.string }, render() { let brand = <Link to='home' className="navbar-brand">React-Bootstrap</Link>; let links = Object.keys(NAV_LINKS).map(this.renderNavItem).concat([ <li key='github-link'> <a href='https://github.com/react-bootstrap/react-bootstrap' target='_blank'>GitHub</a> </li> ]); return ( <Navbar componentClass='header' brand={brand} staticTop className="bs-docs-nav" role="banner" toggleNavKey={0}> <Nav className="bs-navbar-collapse" role="navigation" eventKey={0} id="top"> {links} </Nav> </Navbar> ); }, renderNavItem(linkName) { let link = NAV_LINKS[linkName]; return ( <li className={this.props.activePage === linkName ? 'active' : null} key={linkName}> <Link to={link.link}>{link.title}</Link> </li> ); } }); export default NavMain;
src/components/tables/TableFooter.js
ProAI/react-essentials
import React from 'react'; import PropTypes from 'prop-types'; import BaseView from '../../utils/rnw-compat/BaseView'; const propTypes = { children: PropTypes.node.isRequired, }; const TableFooter = React.forwardRef((props, ref) => ( // TODO: Remove pseudo view and add react-native compatible component <BaseView {...props} ref={ref} essentials={{ tag: 'tfoot', pseudo: true }} /> )); TableFooter.displayName = 'TableFooter'; TableFooter.propTypes = propTypes; export default TableFooter;
ContosoUniversity.Spa.React/ClientApp/src/components/about/AboutPage.js
alimon808/contoso-university
import React from 'react'; export default function() { return( <div> <h1>About Page</h1> </div> ); }
javascript/ShareAdmin/SharedStoriesListing.js
AppStateESS/stories
'use strict' import React from 'react' import PropTypes from 'prop-types' import './style.css' const ShareStoriesListing = ({listing, approve, deny}) => { if (!listing || listing.length === 0) { return <p>No shared stories.</p> } let rows = listing.map((value, key) => { const denyLink = ( <a className="d-block badge badge-danger text-white pointer" onClick={deny.bind(null, value.id)}> Deny story </a> ) let approveListLink let approveNoListLink if (value.error == undefined) { approveListLink = ( <a className="d-block badge badge-success text-light mb-1 pointer" onClick={approve.bind(null, value.id, 1)}> Add to list </a> ) approveNoListLink = ( <a className="d-block badge badge-success text-light mb-1 pointer" onClick={approve.bind(null, value.id, 0)}> Add, do not list </a> ) return ( <tr key={key}> <td className="w-30"> <ul className="list-unstyled"> <li>{approveListLink}</li> <li>{approveNoListLink}</li> <li>{denyLink}</li> </ul> </td> <td> <img className="share-thumbnail" src={value.thumbnail}/> </td> <td> <a href={value.siteUrl}>{value.siteName}</a> </td> <td> <a href={value.url}>{value.title}</a> </td> <td> <abbr className="summary" title={value.strippedSummary}>{value.strippedSummary.substr(0, 50)}</abbr> </td> </tr> ) } else { return ( <tr key={key}> <td>{denyLink}</td> <td></td> <td> <a href={value.siteUrl}>{value.siteName}</a> </td> <td colSpan="2">Failure to communicate with guest site. Suggest denying share.<br/> <a href={value.url}>{value.url}</a> </td> </tr> ) } }) return ( <div> <table className="table table-striped"> <tbody> <tr> <th>&nbsp;</th> <th>&nbsp;</th> <th>Site</th> <th>Title</th> <th>Summary</th> </tr> {rows} </tbody> </table> </div> ) } ShareStoriesListing.propTypes = { listing: PropTypes.array, approve: PropTypes.func, deny: PropTypes.func } export default ShareStoriesListing
client/components/settings/index.js
bnjbvr/kresus
import React from 'react'; import PropTypes from 'prop-types'; import { translate as $t } from '../../helpers'; import BankAccountsList from './bank-accesses'; import BackupParameters from './backup'; import EmailsParameters from './emails'; import WeboobParameters from './weboob'; import ThemesParameters from './themes'; import LogsSection from './logs'; import TabsContainer from '../ui/tabs.js'; const SettingsComponents = props => { const pathPrefix = '/settings'; let { currentAccountId } = props.match.params; let tabs = new Map(); tabs.set(`${pathPrefix}/accounts/${currentAccountId}`, { name: $t('client.settings.tab_accounts'), component: BankAccountsList }); tabs.set(`${pathPrefix}/emails/${currentAccountId}`, { name: $t('client.settings.tab_alerts'), component: EmailsParameters }); tabs.set(`${pathPrefix}/backup/${currentAccountId}`, { name: $t('client.settings.tab_backup'), component: BackupParameters }); tabs.set(`${pathPrefix}/weboob/${currentAccountId}`, { name: $t('client.settings.tab_weboob'), component: WeboobParameters }); tabs.set(`${pathPrefix}/themes/${currentAccountId}`, { name: $t('client.settings.tab_themes'), component: ThemesParameters }); tabs.set(`${pathPrefix}/logs/${currentAccountId}`, { name: $t('client.settings.tab_logs'), component: LogsSection }); return ( <TabsContainer tabs={tabs} defaultTab={`${pathPrefix}/accounts/${currentAccountId}`} selectedTab={props.location.pathname} history={props.history} location={props.location} /> ); }; SettingsComponents.propTypes = { // The history object, providing access to the history API. // Automatically added by the Route component. history: PropTypes.object.isRequired, // Location object (contains the current path). Automatically added by react-router. location: PropTypes.object.isRequired }; export default SettingsComponents;
actor-apps/app-web/src/app/components/Login.react.js
zillachan/actor-platform
import _ from 'lodash'; import React from 'react'; import classNames from 'classnames'; import { Styles, RaisedButton, TextField } from 'material-ui'; import { AuthSteps } from 'constants/ActorAppConstants'; import Banner from 'components/common/Banner.react'; import LoginActionCreators from 'actions/LoginActionCreators'; import LoginStore from 'stores/LoginStore'; import ActorTheme from 'constants/ActorTheme'; const ThemeManager = new Styles.ThemeManager(); let getStateFromStores = function () { return ({ step: LoginStore.getStep(), errors: LoginStore.getErrors(), smsRequested: LoginStore.isSmsRequested(), signupStarted: LoginStore.isSignupStarted(), codeSent: false }); }; class Login extends React.Component { static contextTypes = { router: React.PropTypes.func }; static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } componentWillUnmount() { LoginStore.removeChangeListener(this.onChange); } componentDidMount() { this.handleFocus(); } componentDidUpdate() { this.handleFocus(); } constructor(props) { super(props); this.state = _.assign({ phone: '', name: '', code: '' }, getStateFromStores()); ThemeManager.setTheme(ActorTheme); if (LoginStore.isLoggedIn()) { window.setTimeout(() => this.context.router.replaceWith('/'), 0); } else { LoginStore.addChangeListener(this.onChange); } } onChange = () => { this.setState(getStateFromStores()); } onPhoneChange = event => { this.setState({phone: event.target.value}); } onCodeChange = event => { this.setState({code: event.target.value}); } onNameChange = event => { this.setState({name: event.target.value}); } onRequestSms = event => { event.preventDefault(); LoginActionCreators.requestSms(this.state.phone); } onSendCode = event => { event.preventDefault(); LoginActionCreators.sendCode(this.context.router, this.state.code); } onSignupRequested = event => { event.preventDefault(); LoginActionCreators.sendSignup(this.context.router, this.state.name); } onWrongNumberClick = event => { event.preventDefault(); LoginActionCreators.wrongNumberClick(); } handleFocus = () => { switch (this.state.step) { case AuthSteps.PHONE_WAIT: this.refs.phone.focus(); break; case AuthSteps.CODE_WAIT: this.refs.code.focus(); break; case AuthSteps.SIGNUP_NAME_WAIT: this.refs.name.focus(); break; default: return; } } render() { let requestFormClassName = classNames('login__form', 'login__form--request', { 'login__form--done': this.state.step > AuthSteps.PHONE_WAIT, 'login__form--active': this.state.step === AuthSteps.PHONE_WAIT }); let checkFormClassName = classNames('login__form', 'login__form--check', { 'login__form--done': this.state.step > AuthSteps.CODE_WAIT, 'login__form--active': this.state.step === AuthSteps.CODE_WAIT }); let signupFormClassName = classNames('login__form', 'login__form--signup', { 'login__form--active': this.state.step === AuthSteps.SIGNUP_NAME_WAIT }); return ( <section className="login-new row center-xs middle-xs"> <Banner/> <div className="login-new__welcome col-xs row center-xs middle-xs"> <img alt="Actor messenger" className="logo" src="assets/img/logo.png" srcSet="assets/img/logo@2x.png 2x"/> <article> <h1 className="login-new__heading">Welcome to <strong>Actor</strong></h1> <p> Actor Messenger brings all your business network connections into one place, makes it easily accessible wherever you go. </p> <p> Our aim is to make your work easier, reduce your email amount, make the business world closer by reducing time to find right contacts. </p> </article> <footer> <div className="pull-left"> Actor Messenger © 2015 </div> <div className="pull-right"> <a href="//actor.im/ios">iPhone</a> <a href="//actor.im/android">Android</a> </div> </footer> </div> <div className="login-new__form col-xs-6 col-md-4 row center-xs middle-xs"> <div> <h1 className="login-new__heading">Sign in</h1> <form className={requestFormClassName} onSubmit={this.onRequestSms}> <TextField className="login__form__input" disabled={this.state.step > AuthSteps.PHONE_WAIT} errorText={this.state.errors.phone} floatingLabelText="Phone number" onChange={this.onPhoneChange} ref="phone" type="text" value={this.state.phone}/> <footer className="text-center"> <RaisedButton label="Request code" type="submit"/> </footer> </form> <form className={checkFormClassName} onSubmit={this.onSendCode}> <TextField className="login__form__input" disabled={this.state.step > AuthSteps.CODE_WAIT} errorText={this.state.errors.code} floatingLabelText="Auth code" onChange={this.onCodeChange} ref="code" type="text" value={this.state.code}/> <footer className="text-center"> <RaisedButton label="Check code" type="submit"/> </footer> </form> <form className={signupFormClassName} onSubmit={this.onSignupRequested}> <TextField className="login__form__input" errorText={this.state.errors.signup} floatingLabelText="Your name" onChange={this.onNameChange} ref="name" type="text" value={this.state.name}/> <footer className="text-center"> <RaisedButton label="Sign up" type="submit"/> </footer> </form> </div> </div> </section> ); } } export default Login;
src/svg-icons/action/view-week.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionViewWeek = (props) => ( <SvgIcon {...props}> <path d="M6 5H3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h3c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zm14 0h-3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h3c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zm-7 0h-3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h3c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1z"/> </SvgIcon> ); ActionViewWeek = pure(ActionViewWeek); ActionViewWeek.displayName = 'ActionViewWeek'; ActionViewWeek.muiName = 'SvgIcon'; export default ActionViewWeek;
src/components/Infinia5.js
aryalprakash/aryalprakash.github.io
/** * Created by user on 8/29/2016. */ import React, { Component } from 'react'; import { Link } from 'react-router'; let style={ header: { background: 'grey' }, slider:{ 'position': 'relative', 'top': '90px', padding: '0px 50px 20px 50px', display: 'flex', alignItems: 'center', justifyContent: 'space-around', background: "url('../../img/infinia/back1.png')", backgroundSize: 'cover', height: '85vh' }, tag:{ width: '1050px' }, icat:{ display: 'flex', flexWrap: 'wrap', justifyContent: 'flex-end' }, category:{ border: '0px', height: '225px', width: '225px', margin: '10px' }, pointer:{ cursor: 'pointer' }, deals:{ width: "65%", padding: "0px 50px 20px 50px", marginTop:"-100px" } } export default class Infinia5 extends Component{ constructor(){ super(); this.state={ list: false, place: 'Dubai', class: '', loc: 'active-color', cat: 'passive-color' } this.show = this.show.bind(this) this.hide = this.hide.bind(this) this.change = this.change.bind(this) } componentDidMount(){ window.addEventListener('scroll', function(e){ let distanceY = window.pageYOffset || document.documentElement.scrollTop, shrinkOn = 10, header = document.querySelector("iheader"); if (distanceY > shrinkOn) { this.setState({ class: 'smaller' }) } else { this.setState({ class: '' }) } }.bind(this)); } show(){ this.setState({ list: !this.state.list }) } hide(){ this.setState({ list: false }) } change(place){ this.setState({ place, cat: 'active-color', loc: 'passive-color' }) this.hide() } render(){ return(<div className="container"> <div className="top"> <div className={`fheader blue head-border `+this.state.class}> <Link to="/" className="link"><div className="ilogo"> <img src="./img/infinia/logo1.png" /> <div className="ilogo-text"><span className="blue">Infinia</span><span className="orange"> Stores</span></div> </div></Link> <div className="imenu"> <div className="imenu-list search-box"> <input className="search-input" placeholder="What are you looking for?" type="text" /> </div> <div className="imenu-list menu-button">Add your Store</div> <div className="imenu-list">Account</div> <div className="imenu-list"><img src="../img/infinia/cart1.png" width="30px" /></div> </div> </div> <div style={style.slider}> <div style={style.tag}> <div className="tag-text">Shop The Best Deals From Retail Stores</div> <div className="buttons"> <div className={`active-button `+this.state.loc} style={style.pointer} onClick={_=>this.show()}> <div className="style active">1. Select a location</div> <div className="place-name">{this.state.place}</div> <div className="place-drop"> <img src="../img/select-project.png" width="100%"/> </div> {this.state.list?<div className="all-places"> <div className="place" onClick={_=>this.change('Dubai')}>Dubai</div> <div className="place" onClick={_=>this.change('Qatar')}>Qatar</div> <div className="place" onClick={_=>this.change('Arab')}>Arab</div> </div>:null} </div> </div> </div> <div className="girl"> <div className="iselect"> <div className={`active-button cat-button `+this.state.cat}> <div className="style active">2. Choose a category </div> </div> <div className="icat" style={style.icat}> <div className="icategory cat-small sup"> <div className="cat-title">Supermarket</div> </div> <div className="icategory cat-small fas"> <div className="cat-title">Fashion</div> </div> <div className="icategory cat-small ele"> <div className="cat-title">Electronics</div> </div> <div className="icategory cat-small kid"> <div className="cat-title">Kids' Zone</div> </div> </div> </div> </div> </div> </div> <div style={style.deals}> <div className="ideals"> <div className="ideals-title">Infinia Deals</div> <div className="deal-list"> <img src="../img/infinia/shop.png" className="deal-img" />ABC Supermarket is Offering 50% discount on Select Goods. Buy Now </div> </div> </div> <div className="ifooter"> <div className="imenu-list">About</div> <div className="imenu-list">Terms Conditions</div> <div className="imenu-list">Policy</div> </div> </div>) } }
spec/javascripts/jsx/external_apps/components/Lti2EditSpec.js
djbender/canvas-lms
/* * Copyright (C) 2014 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import ReactDOM from 'react-dom' import TestUtils from 'react-dom/test-utils' import Lti2Edit from 'jsx/external_apps/components/Lti2Edit' const {Simulate} = TestUtils const wrapper = document.getElementById('fixtures') const createElement = data => ( <Lti2Edit tool={data.tool} handleActivateLti2={data.handleActivateLti2} handleDeactivateLti2={data.handleDeactivateLti2} handleCancel={data.handleCancel} /> ) const renderComponent = data => ReactDOM.render(createElement(data), wrapper) QUnit.module('ExternalApps.Lti2Edit', { teardown() { ReactDOM.unmountComponentAtNode(wrapper) } }) test('renders', () => { const data = { tool: { app_id: 3, app_type: 'Lti::ToolProxy', description: null, enabled: false, installed_locally: true, name: 'Twitter' }, handleActivateLti2() {}, handleDeactivateLti2() {}, handleCancel() {} } const component = renderComponent(data) ok(component) ok(TestUtils.isCompositeComponentWithType(component, Lti2Edit)) })
app/components/ToggleOption/index.js
fenderface66/spotify-smart-playlists
/** * * ToggleOption * */ import React from 'react'; import { injectIntl, intlShape } from 'react-intl'; const ToggleOption = ({ value, message, intl }) => ( <option value={value}> {message ? intl.formatMessage(message) : value} </option> ); ToggleOption.propTypes = { value: React.PropTypes.string.isRequired, message: React.PropTypes.object, intl: intlShape.isRequired, }; export default injectIntl(ToggleOption);
frontend/src/WorkflowDetailForm.js
aclowes/yawn
import React from 'react'; import { Checkbox, FormGroup, FormControl, ControlLabel, Button, ButtonToolbar, Alert, Pagination } from 'react-bootstrap'; import API from './API' import {formatDateTime} from "./utilities"; /* Helper to extract form values from a given object */ function formValues(object) { let parameters; // convert the parameters between 'bash' and 'dict' syntax if (typeof object.parameters === "string") { parameters = {}; object.parameters.split(/\r\n|\r|\n/g).forEach((line) => { const parts = line.split('='); if (parts.length === 2) parameters[parts[0]] = parts[1]; }) } else { parameters = Object.keys(object.parameters).map((key) => { return `${key}=${object.parameters[key]}` }); parameters = (parameters || []).join('\n'); // empty object returns null } return { schedule: object.schedule, schedule_active: object.schedule_active, parameters: parameters, next_run: object.next_run, } } export default class WorkflowDetailForm extends React.Component { constructor(props) { super(props); this.state = { editable: false, error: null, versions: [], ...formValues(this.props.workflow) }; } componentDidMount() { API.get(`/api/names/${this.props.workflow.name_id}/`, (payload, error) => { this.setState({versions: payload.versions, error}) }); } componentWillReceiveProps(nextProps) { // the version changed... if (nextProps.workflow !== this.props.workflow) { this.setState({...formValues(nextProps.workflow)}); } } selectVersion = (eventKey) => { const version = this.state.versions[eventKey - 1]; this.props.router.push(`/workflows/${version}`); }; toggleEditable = () => { this.setState({editable: !this.state.editable}); }; toggleCheckbox = (event) => { this.setState({[event.target.value]: event.target.checked}); }; handleChange = (event) => { this.setState({[event.target.id]: event.target.value}); }; handleSubmit = (event) => { const update = formValues(this.state); API.patch(`/api/workflows/${this.props.workflow.id}/`, update, (payload, error) => { // if there is an error, don't parse the payload const form = error ? {} : formValues(payload); this.setState({...form, error, editable: !!error}); }); event.preventDefault(); }; render() { if (this.state.editable) { return ( <form onSubmit={this.handleSubmit}> {this.state.error && <Alert bsStyle="danger">{this.state.error}</Alert>} <Checkbox value="schedule_active" onChange={this.toggleCheckbox} checked={this.state.schedule_active}>Schedule Active</Checkbox> <FormGroup controlId="schedule"> <ControlLabel>Schedule</ControlLabel> <FormControl type="text" placeholder="<minute> <hour> <weekday>" onChange={this.handleChange} value={this.state.schedule}/> </FormGroup> <FormGroup controlId="parameters"> <ControlLabel>Parameters</ControlLabel> <FormControl componentClass="textarea" placeholder="VARIABLE=value (one per line)" onChange={this.handleChange} value={this.state.parameters}/> </FormGroup> <ButtonToolbar> <Button onClick={this.toggleEditable}>Cancel</Button> <Button type="submit" bsStyle="primary">Save</Button> </ButtonToolbar> </form> ); } else { return ( <div> {this.state.error && <Alert bsStyle="danger">{this.state.error}</Alert>} <dl className="dl-horizontal"> <dt>Name</dt> <dd>{this.props.workflow.name}</dd> <dt>Version</dt> <dd>{} <Pagination ellipsis bsSize="small" items={this.state.versions.length} maxButtons={10} activePage={this.props.workflow.version} onSelect={this.selectVersion}/> </dd> <dt>Schedule Active</dt> <dd>{this.state.schedule_active ? 'True' : 'False'}</dd> <dt>Schedule</dt> <dd>{this.state.schedule}</dd> <dt>Next Run</dt> <dd>{formatDateTime(this.state.next_run)}</dd> <dt>Parameters</dt> <dd> <pre>{this.state.parameters}</pre> </dd> </dl> <Button onClick={this.toggleEditable}>Edit</Button> </div> ) } } }
src/svg-icons/action/hourglass-empty.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionHourglassEmpty = (props) => ( <SvgIcon {...props}> <path d="M6 2v6h.01L6 8.01 10 12l-4 4 .01.01H6V22h12v-5.99h-.01L18 16l-4-4 4-3.99-.01-.01H18V2H6zm10 14.5V20H8v-3.5l4-4 4 4zm-4-5l-4-4V4h8v3.5l-4 4z"/> </SvgIcon> ); ActionHourglassEmpty = pure(ActionHourglassEmpty); ActionHourglassEmpty.displayName = 'ActionHourglassEmpty'; export default ActionHourglassEmpty;
src/svg-icons/av/mic-none.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvMicNone = (props) => ( <SvgIcon {...props}> <path d="M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm-1.2-9.1c0-.66.54-1.2 1.2-1.2.66 0 1.2.54 1.2 1.2l-.01 6.2c0 .66-.53 1.2-1.19 1.2-.66 0-1.2-.54-1.2-1.2V4.9zm6.5 6.1c0 3-2.54 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c3.28-.48 6-3.3 6-6.72h-1.7z"/> </SvgIcon> ); AvMicNone = pure(AvMicNone); AvMicNone.displayName = 'AvMicNone'; AvMicNone.muiName = 'SvgIcon'; export default AvMicNone;
app/containers/TagsList/index.js
vonkanehoffen/wp-react
/** * Tags List */ import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router' import config from 'config' import { loadTags } from '../../store/tags/actions'; import './style.scss' class TagsList extends React.Component { componentDidMount() { if(this.props.tags.tags.length < 1) { this.props.loadTags() } } render() { const { tags } = this.props return ( <ul className="TagsList"> {tags.tags.length > 0 && tags.tags.map((tag, i) => <li key={i}><Link to={'/tag/'+tag.slug}>{tag.name}</Link></li> )} </ul> ) } } export function mapDispatchToProps(dispatch) { return { loadTags: () => dispatch(loadTags()), }; } const mapStateToProps = (state) => { return { tags: state.tags } } export default connect(mapStateToProps, mapDispatchToProps)(TagsList)
packages/ringcentral-widgets/components/MessageTabButton/index.js
ringcentral/ringcentral-js-widget
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import styles from './styles.scss'; function NavigationButton({ active, icon, label, noticeCounts, onClick, width, fullSizeInk, }) { let notice = null; if (noticeCounts && noticeCounts > 0) { if (noticeCounts > 99) { notice = ( <div data-sign="noticeCounts" className={styles.notices}> 99+ </div> ); } else { notice = ( <div data-sign="noticeCounts" className={styles.notice}> {noticeCounts} </div> ); } } return ( <div onClick={onClick} className={classnames( styles.navigationButton, active && styles.active, fullSizeInk ? null : styles.linearBorder, )} style={{ width, }} > <div className={styles.iconHolder} title={label} data-sign={label}> <div className={styles.icon}>{icon}</div> {notice} </div> </div> ); } NavigationButton.propTypes = { icon: PropTypes.node.isRequired, active: PropTypes.bool, label: PropTypes.string, noticeCounts: PropTypes.number, width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired, onClick: PropTypes.func, fullSizeInk: PropTypes.bool, }; NavigationButton.defaultProps = { active: false, label: undefined, noticeCounts: undefined, onClick: undefined, fullSizeInk: true, }; export default NavigationButton;
docs/server.js
brentertz/react-bootstrap
/* eslint no-console: 0 */ import 'colors'; import React from 'react'; import express from 'express'; import path from 'path'; import Router from 'react-router'; import routes from './src/Routes'; import httpProxy from 'http-proxy'; import metadata from './generate-metadata'; import ip from 'ip'; const development = process.env.NODE_ENV !== 'production'; const port = process.env.PORT || 4000; let app = express(); if (development) { let proxy = httpProxy.createProxyServer(); let webpackPort = process.env.WEBPACK_DEV_PORT; let target = `http://${ip.address()}:${webpackPort}`; app.get('/assets/*', function (req, res) { proxy.web(req, res, { target }); }); proxy.on('error', function(e) { console.log('Could not connect to webpack proxy'.red); console.log(e.toString().red); }); console.log('Prop data generation started:'.green); metadata().then( props => { console.log('Prop data generation finished:'.green); app.use(function renderApp(req, res) { res.header('Access-Control-Allow-Origin', target); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); Router.run(routes, req.url, Handler => { let html = React.renderToString(<Handler assetBaseUrl={target} propData={props}/>); res.send('<!doctype html>' + html); }); }); }); } else { app.use(express.static(path.join(__dirname, '../docs-built'))); } app.listen(port, function () { console.log(`Server started at:`); console.log(`- http://localhost:${port}`); console.log(`- http://${ip.address()}:${port}`); });