path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
app/components/Button.js
jcasner/EarthDawnDiceRoller
import React, { Component } from 'react'; import { Text, TouchableHighlight } from 'react-native'; import { buttonStyles } from './styles'; class Button extends Component { render() { const { handlePress, step, text, bigButton } = this.props; return ( <TouchableHighlight style={[buttonStyles.button, bigButton && buttonStyles.bigButton]} onPress={() => handlePress(step)} underlayColor='steelblue'> <Text style={[buttonStyles.buttonText, bigButton && buttonStyles.bigButtonText]}> {text} </Text> </TouchableHighlight> ); } } export default Button;
src/components/ScrollToTopRoute.js
ramaya314/UndocuFunds
import React, { Component } from 'react'; import { Route, withRouter } from 'react-router-dom'; class ScrollToTopRoute extends Component { componentDidUpdate(prevProps) { if (this.props.path === this.props.location.pathname && this.props.location.pathname !== prevProps.location.pathname) { window.scrollTo(0, 0) } } render() { const { component: Component, ...rest } = this.props; return <Route {...rest} render={props => (<Component {...props} />)} />; } } export default withRouter(ScrollToTopRoute);
public/app/components/ui-project-tab/properties-window.js
vincent-tr/mylife-home-studio
'use strict'; import React from 'react'; import icons from '../icons'; import PropertiesLabel from '../properties/properties-label'; import PropertiesTitle from '../properties/properties-title'; import PropertiesEditor from '../properties/properties-editor'; import ImageSelectorContainer from '../../containers/ui-project-tab/image-selector-container'; const PropertiesWindow = ({ project, window, onDelete, onChangeId, onResize, onChangeImage }) => ( <div> <PropertiesTitle icon={<icons.UiWindow/>} text={window.id} onDelete={onDelete} /> {/* details */} <table> <tbody> <tr> <td><PropertiesLabel text={'Id'} /></td> <td><PropertiesEditor id={`${window.uid}_id`} value={window.id} onChange={onChangeId} type={'s'} /></td> </tr> <tr> <td><PropertiesLabel text={'Width'} /></td> <td><PropertiesEditor id={`${window.uid}_width`} value={window.width} onChange={(value) => onResize({ height: window.height, width: value })} type={'i'} useRealType={true} /></td> </tr> <tr> <td><PropertiesLabel text={'Height'} /></td> <td><PropertiesEditor id={`${window.uid}_height`} value={window.height} onChange={(value) => onResize({ height: value, width: window.width })} type={'i'} useRealType={true} /></td> </tr> <tr> <td><PropertiesLabel text={'Background'} /></td> <td><ImageSelectorContainer project={project} image={window.backgroundResource} onImageChange={onChangeImage} /></td> </tr> </tbody> </table> </div> ); PropertiesWindow.propTypes = { project : React.PropTypes.number.isRequired, window : React.PropTypes.object.isRequired, onDelete : React.PropTypes.func.isRequired, onChangeId : React.PropTypes.func.isRequired, onResize : React.PropTypes.func.isRequired, onChangeImage : React.PropTypes.func.isRequired }; export default PropertiesWindow;
client/utility/groupViewHelper.js
AngryPulpGophers/fairshare
import React from 'react'; var Helper = module.exports; Helper.prettyDate = function(milliseconds){ var date = new Date(milliseconds); //console.log('samsam',this.props.location,'and pj', this.props.params) var am = "AM"; var hours = date.getHours(); var minutes = date.getMinutes(); if (hours > 12) { hours = hours - 12; am = "PM"; } else if (hours === 0){ hours = hours + 12; am = "AM"; } else if (hours === 12){ am = "PM"; } var timeDay = hours + ":" + (minutes>=10 ? minutes : ("0" + minutes))+ " " + am; var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var date = new Date(milliseconds); var day = date.getDate(); var monthIndex = date.getMonth(); var year = date.getFullYear(); var time = monthNames[monthIndex]+" "+day+", " +year+' '+ timeDay; return time; }; /* add this picture to any document <div classname = 'groupView'> <img src="http://i.imgur.com/4GXzMQB.jpg" /> </div> */ Helper.calcBalance = function() { if (this.props.currentGroupUsers){ console.log('what is going on', this.props.currentGroupUsers); //make a group object from current group array var groupObj = this.props.currentGroupUsers.reduce((acc,member) => { acc[member.user_id] = member; acc[member.user_id].balance = 0; acc[member.user_id].tempBalance = 0; return acc; },{}); console.log('groupObj in helper:', groupObj); //all numbers passed into this function is a string, so this function turns it into a number then rounds it to 2 decimalpoints //which turns it back into a string, so i turn it into a number again var round = function(num) { //console.log('broke here',num) num=Number(num); return Number(num.toFixed(2)); }; var splitActivities = (array) => { let [pay,cost] = [[],[]]; array.forEach( act => { if(act.type === 'expense'){ cost.push(act); }else{ pay.push(act); } }); return [pay,cost]; }; let [payments,expenses] = splitActivities(this.props.activity); // loop through each activity the group has expenses.forEach(act => { act.members.filter( person => person.id !== act.paid_by) .forEach( (person,idx) => { let portion = round(act.amount/act.members.length); let pennies = round(act.amount) - (round((act.amount/act.members.length) * act.members.length)); if(idx === act.members.length - 1){ groupObj[person.id].balance = round(groupObj[person.id].balance) - (portion + pennies); }else{ groupObj[person.id].balance = round(groupObj[person.id].balance) - portion; } groupObj[act.paid_by].balance = round(groupObj[act.paid_by].balance) + portion; }); }); payments.forEach(act => { groupObj[act.payee].balance = round(groupObj[act.payee].balance) + round(act.amount); groupObj[act.recipient].balance = round(groupObj[act.recipient].balance) - round(act.amount); }); // this code sets up balance in user_groups table // refactor this to use a state variable later var currentURL = window.location.href; var ID = currentURL.split('id=')[1]; var tempObj = {}; for (var ind in groupObj){ tempObj.user_id = Number(ind); tempObj.group_id = Number(ID); tempObj.balance = round(groupObj[ind].balance); // console.log('NEW PJ',tempObj.user_id,'USER', // tempObj.group_id,'group', // tempObj.balance); this.props.indBalance(JSON.stringify(tempObj)); tempObj = {}; } //for some reason I thought it was logical to sort the group before I settled all of the debt // so that is done here //maybe can use user ID instead if it is available // console.log('balances should be here',groupObj) var sortedGroup = []; for (var user in groupObj){ // console.log('real balance',groupObj[user].balance) sortedGroup.push(groupObj[user]); } sortedGroup = sortedGroup.map( obj => { obj.tempBalance = obj.balance; obj.owed = []; return obj; }); //console.log('current status', sortedGroup) //ADD user_ to all id below this point //loop through every member in group for (var p1 = 0; p1 < sortedGroup.length; p1++){ //only do logic if member is owed money if (sortedGroup[p1].tempBalance > 0){ //if member is owed money loop through the rest of the group for (var p2 = 0; p2 < sortedGroup.length ; p2++){ //ignore the same person if(p1!==p2){ //if you find a person that owes money if (sortedGroup[p2].tempBalance < 0){ //if the person doesnt owe enough to cover person1s balance if((sortedGroup[p1].tempBalance + sortedGroup[p2].tempBalance) > 0){ // console.log(sortedGroup[p1].name,sortedGroup[p1].tempBalance,sortedGroup[p2].name,sortedGroup[p2].tempBalance) sortedGroup[p2].owed.push({[sortedGroup[p1].name] : sortedGroup[p2].tempBalance}); //test to only show 'person2 owes person 1 $$$' //sortedGroup[p1].owed.push({[sortedGroup[p2].name] : -1 * sortedGroup[p2].tempBalance }) sortedGroup[p1].tempBalance += sortedGroup[p2].tempBalance; sortedGroup[p1].tempBalance = round(sortedGroup[p1].tempBalance); sortedGroup[p2].tempBalance = 0; //if person ones debt is settled, then stop looking for members to give him money if(sortedGroup[p1].tempBalance===0){ break; } //console.log(sortedGroup[p1].name,sortedGroup[p1].tempBalance,sortedGroup[p2].name,sortedGroup[p2].tempBalance) } //if person 2 does have enough to cover persons ones balance else if ((sortedGroup[p1].tempBalance + sortedGroup[p2].tempBalance) <= 0){ // console.log(sortedGroup[p1].name,sortedGroup[p1].tempBalance,sortedGroup[p2].name,sortedGroup[p2].tempBalance) sortedGroup[p2].owed.push({[sortedGroup[p1].name] : -1 * sortedGroup[p1].tempBalance}); //test to only show 'person2 owes person 1 $$$' //sortedGroup[p1].owed.push({[sortedGroup[p2].name] : sortedGroup[p1].tempBalance }) sortedGroup[p2].tempBalance += sortedGroup[p1].tempBalance; sortedGroup[p2].tempBalance = round(sortedGroup[p2].tempBalance); sortedGroup[p1].tempBalance = 0; //person one needs no more money, so stop looking through members to give him money break; // console.log(sortedGroup[p1].name,sortedGroup[p1].tempBalance,sortedGroup[p2].name,sortedGroup[p2].tempBalance) } } } } } } // console.log(sortedGroup) //very useful console.logs sortedGroup.map(function(user){ // console.log(user.name,user.owed) }); return sortedGroup; } else{ return []; } }; Helper.makeGroupObj = function(){ var makeGroupObject = {}; for (var i = 0 ; i < this.props.currentGroupUsers.length ; i++){ makeGroupObject[this.props.currentGroupUsers[i].user_id]=this.props.currentGroupUsers[i]; //makeGroupObject[this.props.currentGroupUsers[i].user_id].balance = 0 } return makeGroupObject; }; Helper.test = function(x,obj){ // console.log('holly', x,obj) if (obj.display==='none'){ delete obj.display; return {}; } else{ return { display: 'none' }; } }; Helper.showDebt = function(showUserBalance){ var testBal = 0; for (var i = 0 ; i < showUserBalance.length ; i++){ for (var x = 0 ; x < showUserBalance[i].owed.length ; x++){ testBal = testBal + Number(showUserBalance[i].owed[x][Object.keys(showUserBalance[i].owed[x])]); } } if (testBal===0){ return ( <div>Your group has a $0 balance</div> ) } console.log('*^&*%^%*%&*&^*&%*&%got into the show user balance func') return showUserBalance.map(function(user){ return ( <span key={user.user_id}> {user.owed.map(function(person, index){ return ( <div key={index+user.name}> {this.seeIfYou(user.name)} {this.seeIfYou(user.name) === 'You' ? " owe " + Object.keys(person) + " $" + (-1 * person[Object.keys(person)]).toFixed(2) : "owes " + this.seeIfYou(Object.keys(person)) +" $"+ (-1*person[Object.keys(person)]).toFixed(2)} </div> ) }.bind(this)) } </span> ) }.bind(this)) } Helper.getImage = function(activity,members){ let img; members.forEach(member => { if(member.id == activity.paid_by){ // console.log('here is the image:', member.img_url) img = member.img_url; } }) return <img className="roundCorner-image expense-user" src={img} />; }
src/js/admin/articles/filters/filter-bar-bottom/filter-bar-bottom.js
ucev/blog
import React from 'react' import FilterBar from '../filter-bar' import GroupOperationSelect from '../group-operation-select' const FilterBarBottom = () => ( <FilterBar type="bottom"> <GroupOperationSelect /> </FilterBar> ) export default FilterBarBottom
app/containers/Home.js
thomasantony/BudgetFirst
import React, { Component } from 'react'; import { Link } from 'react-router'; import {bindActionCreators} from 'redux'; import { connect } from 'react-redux'; import * as AccountActions from '../actions/accounts' import * as LedgerActions from '../actions/ledger' // import styles from './Home.module.css'; import { createSelector } from 'reselect' // import accountTxnSelector from '../selectors/transactionSelectors'; import {accountSelector} from '../selectors/accountSelectors'; import AccountList from '../components/AccountList'; import TransactionList from '../components/TransactionList'; class Home extends Component { constructor(props) { super(props); this.state = {activeAccountId: -1}; } loadDummy() { this.props.loadDummyAccounts(); this.props.loadDummyTransactions(); } addAccount() { this.props.addAccount({ name: 'Dummy '+Math.floor(100*Math.random()), type: 'checking', openingDate: '2016-01-15', openingBalance: 5000*Math.random()-2500, onBudget: true }) } onAddTransfer() { alert('Nothing to see here!!') } onAddTxn() { if(this.state.activeAccountId > 0) { this.props.addTransaction( { date: '2016-01-09', type: 'regular', account_id: this.state.activeAccountId, payee: 'Random payee', // category_id: 2, // TODO: Make category a derived field category: 'Blah blah', memo: '¯\\_(ツ)_/¯', amount: Math.random()*1000-500, cleared: true } ); }else{ // Safeguard console.log('Add an account first.') } } showAccount(account_id) { this.setState({activeAccountId: account_id}); } render() { return ( <div className="window"> <header className="toolbar toolbar-header"> <h1 className="title">Budget First</h1> <div className="toolbar-actions"> <div className="btn-group"> <button className="btn btn-default"> <span className="icon icon-home"></span> </button> <button className="btn btn-default active"> <span className="icon icon-doc-text"></span> </button> <button className="btn btn-default"> <span className="icon icon-chart-bar"></span> </button> <button className="btn btn-default"> <span className="icon icon-cog"></span> </button> </div> <button className="btn btn-default" onClick={this.loadDummy.bind(this)}> <span className="icon icon-folder icon-text"></span> Load dummy data </button> </div> </header> <div className="window-content"> <div className="pane-group"> <div className="pane pane-sm sidebar" style={{width:'250px'}}> <AccountList title="Budget Accounts" onBudget={true} activeItem={this.state.activeAccountId} onSelect={this.showAccount.bind(this)}/> <AccountList title="Off-Budget Accounts" onBudget={false} activeItem={this.state.activeAccountId} onSelect={this.showAccount.bind(this)}/> <nav className="nav-group" style={{padding:'10px'}}> <button className="btn btn-default" onClick={this.addAccount.bind(this)}> <span className="icon icon-plus icon-text"></span> Add Account </button> </nav> </div> <div className="pane"> <TransactionList accountId={this.state.activeAccountId} onAddTxn={this.onAddTxn.bind(this)} onAddTransfer={this.onAddTransfer.bind(this)} style={{visibility:this.state.activeAccountId > 0 ? 'visible': 'hidden'}} /> </div> </div> </div> </div> ); } } export default connect(null, (dispatch) => bindActionCreators({...AccountActions,...LedgerActions}, dispatch))(Home);
client/components/AceEditor/AceEditor.js
YMFE/yapi
import React from 'react'; import mockEditor from './mockEditor'; import PropTypes from 'prop-types'; import './AceEditor.scss'; const ModeMap = { javascript: 'ace/mode/javascript', json: 'ace/mode/json', text: 'ace/mode/text', xml: 'ace/mode/xml', html: 'ace/mode/html' }; const defaultStyle = { width: '100%', height: '200px' }; function getMode(mode) { return ModeMap[mode] || ModeMap.text; } class AceEditor extends React.PureComponent { constructor(props) { super(props); } static propTypes = { data: PropTypes.any, onChange: PropTypes.func, className: PropTypes.string, mode: PropTypes.string, //enum[json, text, javascript], default is javascript readOnly: PropTypes.bool, callback: PropTypes.func, style: PropTypes.object, fullScreen: PropTypes.bool, insertCode: PropTypes.func }; componentDidMount() { this.editor = mockEditor({ container: this.editorElement, data: this.props.data, onChange: this.props.onChange, readOnly: this.props.readOnly, fullScreen: this.props.fullScreen }); let mode = this.props.mode || 'javascript'; this.editor.editor.getSession().setMode(getMode(mode)); if (typeof this.props.callback === 'function') { this.props.callback(this.editor.editor); } } componentWillReceiveProps(nextProps) { if (!this.editor) { return; } if (nextProps.data !== this.props.data && this.editor.getValue() !== nextProps.data) { this.editor.setValue(nextProps.data); let mode = nextProps.mode || 'javascript'; this.editor.editor.getSession().setMode(getMode(mode)); this.editor.editor.clearSelection(); } } render() { return ( <div className={this.props.className} style={this.props.className ? undefined : this.props.style || defaultStyle} ref={editor => { this.editorElement = editor; }} /> ); } } export default AceEditor;
routes.js
m4n3z40/fluxone
import React from 'react'; import { Route, DefaultRoute } from 'react-router'; import RootComponent from 'components/RootComponent.js'; import AppComponent from 'components/AppComponent.js'; export default function getRoutes() { return ( <Route name="app" path="/" handler={RootComponent}> <DefaultRoute handler={AppComponent} /> </Route> ); };
docs/app/Examples/elements/Container/Variations/index.js
aabustamante/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' import { Message } from 'semantic-ui-react' const ContainerVariationsExamples = () => ( <ExampleSection title='Variations'> <ComponentExample title='Text Alignment' description='A container can specify its text alignment.' examplePath='elements/Container/Variations/ContainerExampleAlignment' /> <ComponentExample title='Fluid' description='A fluid container has no maximum width.' examplePath='elements/Container/Variations/ContainerExampleFluid' > <Message info> Fluid containers are useful for setting text alignment, or other variations on unstyled content. </Message> </ComponentExample> </ExampleSection> ) export default ContainerVariationsExamples
src/js/ui/card.js
SpaceHexagon/pylon
import React from 'react'; import Icon from './icon.js'; export default class Card extends React.Component { constructor() { super(); // Initial state of the component this.state = { visible: true, background: "", thumbnailState: 0 }; } componentDidMount () { if (!!this.props.thumbURL) { if (this.state.thumbnailState == 0) { this.loadThumbnail(this.props.thumbURL); } } } handleClick (component, event) { component.props.open(); } close (comp) { this.setState({ visible: false }); } loadThumbnail (url) { var xhr = new XMLHttpRequest(), comp = this; xhr.onload = function () { comp.setState({thumbnailState: 1, background: JSON.parse(xhr.responseText).dataURL}); } xhr.open("GET", url, true); xhr.send(); } render() { var cardStyle = { display: this.state.visible ? "inline-block" : "none" }, cardClass = "card", contextMenu = null, background = "", title = (this.props.link.length < 1 ? <h3>{this.props.title}</h3> : ""), link = (this.props.link.length > 1 ? <h3><a href={this.props.link} target="_blank">{this.props.title}</a></h3> : ""); if (this.state.background.length > 1) { background = this.state.background; } else if (this.props.background.length > 1) { background = this.props.background; } if (!!this.props.contextMenu) { contextMenu = this.props.contextMenu; } else { contextMenu = <Icon src={"/images/"+ (background == "" ? "dark" : "") +"/x.png"} title="close" open={()=>{this.close()}} />; } if (background.length > 1) { cardStyle.backgroundImage = "url("+background+")"; cardClass += " background"; } return ( <article className={cardClass} style={cardStyle} title={this.props.title} > {this.props.CardIcon} {title} {link} {contextMenu} <p>{this.props.text}</p> </article> ); } } Card.defaultProps = { text: "", link: "", background: "" };
routes/oldHome.js
Belhalaribi/PFE
import React, { Component } from 'react'; import AppBar from 'material-ui/AppBar'; import Header from '../components/Header.js'; import Content from '../components/Content.js'; import Footer from '../components/Footer.js'; import Root from '../components/Root.js'; import Paper from 'material-ui/Paper'; import Menu from 'material-ui/Menu'; import MenuItem from 'material-ui/MenuItem'; import {Tabs, Tab} from 'material-ui/Tabs'; import FontIcon from 'material-ui/FontIcon'; import MapsPersonPin from 'material-ui/svg-icons/maps/person-pin'; import Login from '../components/Login.js'; export default class Home extends Component { render(){ return( <Root> <Header /> <div class="content"> <div > <Paper class="LangPaper"> <Menu class="LangMenu"> <a href="#/login"> <MenuItem class="LangMenuItem" primaryText="English" /> </a> <MenuItem class="LangMenuItem" primaryText="Francais" /> <MenuItem class="LangMenuItem" primaryText="العربية" /> </Menu> </Paper> </div> </div> <Footer> <Tabs> <Tab icon={<FontIcon className="material-icons">phone</FontIcon>} label="RECENTS" /> <Tab icon={<FontIcon className="material-icons">favorite</FontIcon>} label="FAVORITES" /> <Tab icon={<MapsPersonPin />} label="NEARBY" /> </Tabs> </Footer> </Root> ) } }
app/javascript/mastodon/features/status/components/detailed_status.js
rainyday/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Avatar from '../../../components/avatar'; import DisplayName from '../../../components/display_name'; import StatusContent from '../../../components/status_content'; import MediaGallery from '../../../components/media_gallery'; import { Link } from 'react-router-dom'; import { FormattedDate } from 'react-intl'; import Card from './card'; import ImmutablePureComponent from 'react-immutable-pure-component'; import Video from '../../video'; import Audio from '../../audio'; import scheduleIdleTask from '../../ui/util/schedule_idle_task'; import classNames from 'classnames'; import Icon from 'mastodon/components/icon'; import AnimatedNumber from 'mastodon/components/animated_number'; export default class DetailedStatus extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map, onOpenMedia: PropTypes.func.isRequired, onOpenVideo: PropTypes.func.isRequired, onToggleHidden: PropTypes.func.isRequired, measureHeight: PropTypes.bool, onHeightChange: PropTypes.func, domain: PropTypes.string.isRequired, compact: PropTypes.bool, showMedia: PropTypes.bool, onToggleMediaVisibility: PropTypes.func, }; state = { height: null, }; handleAccountClick = (e) => { if (e.button === 0 && !(e.ctrlKey || e.metaKey) && this.context.router) { e.preventDefault(); this.context.router.history.push(`/accounts/${this.props.status.getIn(['account', 'id'])}`); } e.stopPropagation(); } handleOpenVideo = (media, options) => { this.props.onOpenVideo(media, options); } handleExpandedToggle = () => { this.props.onToggleHidden(this.props.status); } _measureHeight (heightJustChanged) { if (this.props.measureHeight && this.node) { scheduleIdleTask(() => this.node && this.setState({ height: Math.ceil(this.node.scrollHeight) + 1 })); if (this.props.onHeightChange && heightJustChanged) { this.props.onHeightChange(); } } } setRef = c => { this.node = c; this._measureHeight(); } componentDidUpdate (prevProps, prevState) { this._measureHeight(prevState.height !== this.state.height); } handleModalLink = e => { e.preventDefault(); let href; if (e.target.nodeName !== 'A') { href = e.target.parentNode.href; } else { href = e.target.href; } window.open(href, 'mastodon-intent', 'width=445,height=600,resizable=no,menubar=no,status=no,scrollbars=yes'); } render () { const status = (this.props.status && this.props.status.get('reblog')) ? this.props.status.get('reblog') : this.props.status; const outerStyle = { boxSizing: 'border-box' }; const { compact } = this.props; if (!status) { return null; } let media = ''; let applicationLink = ''; let reblogLink = ''; let reblogIcon = 'retweet'; let favouriteLink = ''; if (this.props.measureHeight) { outerStyle.height = `${this.state.height}px`; } if (status.get('media_attachments').size > 0) { if (status.getIn(['media_attachments', 0, 'type']) === 'audio') { const attachment = status.getIn(['media_attachments', 0]); media = ( <Audio src={attachment.get('url')} alt={attachment.get('description')} duration={attachment.getIn(['meta', 'original', 'duration'], 0)} height={110} preload /> ); } else if (status.getIn(['media_attachments', 0, 'type']) === 'video') { const attachment = status.getIn(['media_attachments', 0]); media = ( <Video preview={attachment.get('preview_url')} blurhash={attachment.get('blurhash')} src={attachment.get('url')} alt={attachment.get('description')} width={300} height={150} inline onOpenVideo={this.handleOpenVideo} sensitive={status.get('sensitive')} visible={this.props.showMedia} onToggleVisibility={this.props.onToggleMediaVisibility} /> ); } else { media = ( <MediaGallery standalone sensitive={status.get('sensitive')} media={status.get('media_attachments')} height={300} onOpenMedia={this.props.onOpenMedia} visible={this.props.showMedia} onToggleVisibility={this.props.onToggleMediaVisibility} /> ); } } else if (status.get('spoiler_text').length === 0) { media = <Card onOpenMedia={this.props.onOpenMedia} card={status.get('card', null)} />; } if (status.get('application')) { applicationLink = <span> · <a className='detailed-status__application' href={status.getIn(['application', 'website'])} target='_blank' rel='noopener noreferrer'>{status.getIn(['application', 'name'])}</a></span>; } if (status.get('visibility') === 'direct') { reblogIcon = 'envelope'; } else if (status.get('visibility') === 'private') { reblogIcon = 'lock'; } if (['private', 'direct'].includes(status.get('visibility'))) { reblogLink = <Icon id={reblogIcon} />; } else if (this.context.router) { reblogLink = ( <Link to={`/statuses/${status.get('id')}/reblogs`} className='detailed-status__link'> <Icon id={reblogIcon} /> <span className='detailed-status__reblogs'> <AnimatedNumber value={status.get('reblogs_count')} /> </span> </Link> ); } else { reblogLink = ( <a href={`/interact/${status.get('id')}?type=reblog`} className='detailed-status__link' onClick={this.handleModalLink}> <Icon id={reblogIcon} /> <span className='detailed-status__reblogs'> <AnimatedNumber value={status.get('reblogs_count')} /> </span> </a> ); } if (this.context.router) { favouriteLink = ( <Link to={`/statuses/${status.get('id')}/favourites`} className='detailed-status__link'> <Icon id='star' /> <span className='detailed-status__favorites'> <AnimatedNumber value={status.get('favourites_count')} /> </span> </Link> ); } else { favouriteLink = ( <a href={`/interact/${status.get('id')}?type=favourite`} className='detailed-status__link' onClick={this.handleModalLink}> <Icon id='star' /> <span className='detailed-status__favorites'> <AnimatedNumber value={status.get('favourites_count')} /> </span> </a> ); } return ( <div style={outerStyle}> <div ref={this.setRef} className={classNames('detailed-status', { compact })}> <a href={status.getIn(['account', 'url'])} onClick={this.handleAccountClick} className='detailed-status__display-name'> <div className='detailed-status__display-avatar'><Avatar account={status.get('account')} size={48} /></div> <DisplayName account={status.get('account')} localDomain={this.props.domain} /> </a> <StatusContent status={status} expanded={!status.get('hidden')} onExpandedToggle={this.handleExpandedToggle} /> {media} <div className='detailed-status__meta'> <a className='detailed-status__datetime' href={status.get('url')} target='_blank' rel='noopener noreferrer'> <FormattedDate value={new Date(status.get('created_at'))} hour12={false} year='numeric' month='short' day='2-digit' hour='2-digit' minute='2-digit' /> </a>{applicationLink} · {reblogLink} · {favouriteLink} </div> </div> </div> ); } }
config/express.js
DockerVN/simple-paas-api
'use strict'; /** * Module dependencies. */ import 'babel/register'; import fs from 'fs'; import http from 'http'; import express from 'express'; import jwt from 'express-jwt'; import morgan from 'morgan'; import bodyParser from 'body-parser'; import compress from 'compression'; import methodOverride from 'method-override'; import cookieParser from 'cookie-parser'; import helmet from 'helmet'; import flash from 'connect-flash'; import consolidate from 'consolidate'; import path from 'path'; import chalk from 'chalk'; import React from 'react'; import cors from 'cors'; import config from './config'; import App from '../public/components/App'; import rethinkdbService from '../app/services/rethinkdb.server.service.js'; import {secret} from './env/all'; export default function () { // Initialize express app const app = express(); // secure based on jwt token let jwtCheck = jwt({ secret: secret }); app.use('/api', jwtCheck); // Globbing model files config.getGlobbedFiles('./app/models/**/*.js').forEach(modelPath => { require(path.resolve(modelPath)); }); // Setting application local variables app.locals.title = config.app.title; app.locals.description = config.app.description; app.locals.keywords = config.app.keywords; // Passing the request url to environment locals app.use((req, res, next) => { res.locals.url = req.protocol + '://' + req.headers.host + req.url; next(); }); // Should be placed before express.static app.use(compress({ filter: (req, res) => { return (/json|text|javascript|css/).test(res.getHeader('Content-Type')); }, level: 9 })); // Showing stack errors app.set('showStackError', true); // Set swig as the template engine app.engine('server.view.html', consolidate[config.templateEngine]); // Set views path and view engine app.set('view engine', 'server.view.html'); app.set('views', './app/views'); // Set content variable // var appComp = React.createFactory(App); // app.locals.bodyHtml = React.renderToString(appComp()); app.locals.bodyHtml = ''; // Environment dependent middleware if (process.env.NODE_ENV === 'development') { // Enable logger (morgan) app.use(morgan('dev')); // Disable views cache app.set('view cache', false); } else if (process.env.NODE_ENV === 'production') { app.locals.cache = 'memory'; } // Request body parsing middleware should be above methodOverride app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(methodOverride()); // CookieParser should be above session app.use(cookieParser()); // connect flash for flash messages app.use(flash()); // Use helmet to secure Express headers app.use(helmet.xframe()); app.use(helmet.xssFilter()); app.use(helmet.nosniff()); app.use(helmet.ienoopen()); app.disable('x-powered-by'); // enable CORS app.use(cors()); // Setting the app router and static folder app.use(express.static(path.resolve('./www'))); // Globbing routing files config.getGlobbedFiles('./app/routes/**/*.js').forEach(routePath => { require(path.resolve(routePath))(app); }); // Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc. app.use((err, req, res, next) => { // If the error object doesn't exists if (!err) return next(); else { if(err.status == 401) { res.status(401).json(err); } } // Log it console.error(err.stack); // Error page res.status(500).render('500', { error: err.stack }); }); // Assume 404 since no middleware responded app.use((req, res) => { let returnView = res.status(404); let returnData = { url: req.originalUrl, error: 'Not Found' }; if(req.is('json')) { returnView.json('404', returnData); } else { returnView.render('404', returnData); } }); // Return Express server instance return app; };
node_modules/redbox-react/examples/react-transform-catch-errors/index.js
hnikupet/dddhackaton
import React from 'react' import App from './components/App' const root = document.getElementById('root') React.render(<App />, root)
packages/expo-dev-menu/vendored/react-native-gesture-handler/src/GestureComponents.js
exponentjs/exponent
import React from 'react'; import ReactNative from 'react-native'; import createNativeWrapper from './createNativeWrapper'; const MEMOIZED = new WeakMap(); function memoizeWrap(Component, config) { if (Component == null) { return null; } let memoized = MEMOIZED.get(Component); if (!memoized) { memoized = createNativeWrapper(Component, config); MEMOIZED.set(Component, memoized); } return memoized; } module.exports = { /* RN's components */ get ScrollView() { return memoizeWrap(ReactNative.ScrollView, { disallowInterruption: true, shouldCancelWhenOutside: false, }); }, get Switch() { return memoizeWrap(ReactNative.Switch, { shouldCancelWhenOutside: false, shouldActivateOnStart: true, disallowInterruption: true, }); }, get TextInput() { return memoizeWrap(ReactNative.TextInput); }, get DrawerLayoutAndroid() { const DrawerLayoutAndroid = memoizeWrap(ReactNative.DrawerLayoutAndroid, { disallowInterruption: true, }); DrawerLayoutAndroid.positions = ReactNative.DrawerLayoutAndroid.positions; return DrawerLayoutAndroid; }, get FlatList() { if (!MEMOIZED.FlatList) { const ScrollView = this.ScrollView; MEMOIZED.FlatList = React.forwardRef((props, ref) => ( <ReactNative.FlatList ref={ref} {...props} renderScrollComponent={scrollProps => <ScrollView {...scrollProps} />} /> )); } return MEMOIZED.FlatList; }, };
analysis/druidguardian/src/modules/talents/Pulverize.js
anom0ly/WoWAnalyzer
import { t } from '@lingui/macro'; import { formatPercentage } from 'common/format'; import SPELLS from 'common/SPELLS'; import { SpellLink } from 'interface'; import Analyzer from 'parser/core/Analyzer'; import BoringSpellValue from 'parser/ui/BoringSpellValue'; import Statistic from 'parser/ui/Statistic'; import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY'; import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER'; import React from 'react'; class Pulverize extends Analyzer { constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.PULVERIZE_TALENT.id); } suggestions(when) { const pulverizeUptimePercentage = this.selectedCombatant.getBuffUptime(SPELLS.PULVERIZE_BUFF.id) / this.owner.fightDuration; this.selectedCombatant.hasTalent(SPELLS.PULVERIZE_TALENT.id) && when(pulverizeUptimePercentage) .isLessThan(0.9) .addSuggestion((suggest, actual, recommended) => suggest( <span> {' '} Your <SpellLink id={SPELLS.PULVERIZE_TALENT.id} /> uptime was{' '} {formatPercentage(pulverizeUptimePercentage)}%, unless there are extended periods of downtime it should be over should be near 100%. <br /> All targets deal less damage to you due to the{' '} <SpellLink id={SPELLS.PULVERIZE_BUFF.id} /> buff. </span>, ) .icon(SPELLS.PULVERIZE_TALENT.icon) .actual( t({ id: 'druid.guardian.suggestions.pulverize.uptime', message: `${formatPercentage(pulverizeUptimePercentage)}% uptime`, }), ) .recommended(`${Math.round(formatPercentage(recommended))}% is recommended`) .regular(recommended - 0.1) .major(recommended - 0.2), ); } statistic() { const pulverizeUptimePercentage = this.selectedCombatant.getBuffUptime(SPELLS.PULVERIZE_BUFF.id) / this.owner.fightDuration; return ( <Statistic position={STATISTIC_ORDER.CORE(13)} category={STATISTIC_CATEGORY.TALENTS} size="flexible" > <BoringSpellValue spell={SPELLS.PULVERIZE_TALENT} value={`${formatPercentage(pulverizeUptimePercentage)}%`} label="Pulverize uptime" /> </Statistic> ); } } export default Pulverize;
src/App/scenes/Characters/Characters.js
JonatanSCS/Marvel-Data
import React from 'react' import { Route } from 'react-router-dom' import CharacterList from './containers/CharacterList/CharacterList' import CharacterDetail from './containers/CharacterDetail/CharacterDetail' const Characters = ({ match }) => ( <div> <h2>Characters</h2> <Route exact path={`${match.url}/`} component={ CharacterList }/> <Route exact path={`${match.url}/:name`} component={ CharacterList }/> <Route path={`${match.url}/character/:id`} component={ CharacterDetail }/> </div> ) export default Characters
src/SplitButton.js
PeterDaveHello/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' }; }, 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;
node/client/src/routes.js
wasong/cmpt433
import React from 'react' import Radium from 'radium' import Dashboard from './Dashboard' const styles = { display: 'flex', minHeight: '100vh', } export default Radium(() => ( <div style={styles}> <Dashboard /> </div> ))
fields/types/url/UrlColumn.js
helloworld3q3q/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var UrlColumn = React.createClass({ displayName: 'UrlColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { var value = this.props.data.fields[this.props.col.path]; if (!value) return; // if the value doesn't start with a prototcol, assume http for the href var href = value; if (href && !/^(mailto\:)|(\w+\:\/\/)/.test(href)) { href = 'http://' + value; } // strip the protocol from the link if it's http(s) var label = value.replace(/^https?\:\/\//i, ''); return ( <ItemsTableValue to={href} padded exterior field={this.props.col.type}> {label} </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = UrlColumn;
src/svg-icons/maps/add-location.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsAddLocation = (props) => ( <SvgIcon {...props}> <path d="M12 2C8.14 2 5 5.14 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.86-3.14-7-7-7zm4 8h-3v3h-2v-3H8V8h3V5h2v3h3v2z"/> </SvgIcon> ); MapsAddLocation = pure(MapsAddLocation); MapsAddLocation.displayName = 'MapsAddLocation'; MapsAddLocation.muiName = 'SvgIcon'; export default MapsAddLocation;
src/routes/makeRoutes.js
Hylozoic/hylo-redux
import React from 'react' import { Route, IndexRoute } from 'react-router' import Signup from '../containers/Signup' import Login from '../containers/Login' import SetPassword from '../containers/SetPassword' import App from '../containers/App' import AllCommunities, { AllPosts } from '../containers/AllCommunities' import People from '../containers/People' import Projects from '../containers/Projects' import { CreateCommunity, CreateCommunityInvite } from '../containers/CreateCommunity' import CommunityProfile from '../containers/community/CommunityProfile' import CommunityPosts from '../containers/community/CommunityPosts' import CommunityJoinLinkHandler from '../containers/community/CommunityJoinLinkHandler' import InvitationHandler from '../containers/community/InvitationHandler' import AboutCommunity from '../containers/community/AboutCommunity' import CommunitySettings from '../containers/community/CommunitySettings' import CommunityInvite from '../containers/community/CommunityInvite' import TagSettings from '../containers/TagSettings' import TagPosts from '../containers/tag/TagPosts' import BioPrompt from '../containers/onboarding/BioPrompt' import TopicsPrompt from '../containers/onboarding/TopicsPrompt' import SkillsPrompt from '../containers/onboarding/SkillsPrompt' import WelcomePage from '../containers/onboarding/WelcomePage' import PersonProfile from '../containers/person/PersonProfile' import UserSettings from '../containers/user/UserSettings' import SinglePost from '../containers/SinglePost' import NetworkProfile from '../containers/network/NetworkProfile' import NetworkPosts from '../containers/network/NetworkPosts' import NetworkMembers from '../containers/network/NetworkMembers' import AboutNetwork from '../containers/network/AboutNetwork' import IconTest from '../containers/IconTest' import ThreadPage from '../containers/ThreadPage' import NetworkCommunities from '../containers/network/NetworkCommunities' import NetworkEditor from '../containers/network/NetworkEditor' import Search from '../containers/Search' import Events from '../containers/Events' import StandalonePostEditor from '../containers/StandalonePostEditor' import ImageViewer from '../containers/ImageViewer' import Admin from '../containers/Admin' import PageWithNav from '../containers/PageWithNav' import TestBench from '../containers/TestBench' import { debug } from '../util/logging' import { makeUrl } from '../util/navigation' import { get, pick } from 'lodash' import { isLoggedIn } from '../models/currentUser' export default function makeRoutes (store) { const requireLoginWithOptions = (options = {}) => (nextState, replace) => { let { startAtSignup, addParams } = options if (isLoggedIn(store.getState())) return true const start = startAtSignup ? 'signup' : 'login' debug(`redirecting to ${start}`) const { location: { pathname, query } } = nextState let params = { next: pathname, ...pick(query, 'ctt', 'cti', 'ctcn'), ...(addParams ? addParams(nextState) : null) } replace(makeUrl(`/${start}`, params)) } const requireLogin = requireLoginWithOptions() const requireAdmin = (nextState, replace) => { const currentUser = store.getState().people.current if (!get(currentUser, 'is_admin')) { replace('/noo/admin/login') } } return <Route component={App}> <Route path='/' onEnter={(_, replace) => replace('/app')} /> <Route path='signup' component={Signup} /> <Route path='login' component={Login} /> <Route path='create' component={CreateCommunity} onEnter={requireLogin} /> <Route path='invite' component={CreateCommunityInvite} onEnter={requireLogin} /> <Route path='set-password' component={SetPassword} /> <Route path='image/:url/:fromUrl' component={ImageViewer} /> <Route path='add-skills' component={SkillsPrompt} onEnter={requireLogin} /> <Route path='add-bio' component={BioPrompt} onEnter={requireLogin} /> <Route path='choose-topics' component={TopicsPrompt} onEnter={requireLogin} /> <Route path='c/:id/new' component={StandalonePostEditor} community onEnter={requireLogin} /> <Route path='c/:id/events/new' component={StandalonePostEditor} community type='event' onEnter={requireLogin} /> <Route path='c/:id/projects/new' component={StandalonePostEditor} community type='project' onEnter={requireLogin} /> <Route path='p/new' component={StandalonePostEditor} onEnter={requireLogin} /> <Route path='p/:id/edit' component={StandalonePostEditor} onEnter={requireLogin} /> <Route path='h/use-invitation' component={InvitationHandler} onEnter={requireLoginWithOptions({ startAtSignup: true, addParams: ({ location: { query: { token, email } } }) => ({token, email, action: 'use-invitation'}) })} /> <Route component={PageWithNav}> <Route path='settings' component={UserSettings} onEnter={requireLogin} /> <Route path='search' component={Search} onEnter={requireLogin} /> <Route path='u/:id' component={PersonProfile} onEnter={requireLogin} /> <Route path='admin' component={Admin} onEnter={requireAdmin} /> <Route path='c/:id/join/:code' component={CommunityJoinLinkHandler} onEnter={requireLoginWithOptions({ startAtSignup: true, addParams: ({ params: { id } }) => ({id, action: 'join-community'}) })} /> <Route path='c/:id/join/:code/tag/:tagName' component={CommunityJoinLinkHandler} onEnter={requireLoginWithOptions({ startAtSignup: true, addParams: ({ params: { id } }) => ({id, action: 'join-community-tag'}) })} /> <Route path='c/:id/onboarding' component={WelcomePage} onEnter={requireLogin} /> <Route path='c/:id' component={CommunityProfile}> <IndexRoute component={CommunityPosts} /> <Route path='people' component={People} onEnter={requireLogin} /> <Route path='events' component={Events} /> <Route path='projects' component={Projects} /> <Route path='about' component={AboutCommunity} /> <Route path='settings/tags' component={TagSettings} /> <Route path='settings' component={CommunitySettings} onEnter={requireLogin} /> <Route path='tag/:tagName' component={TagPosts} onEnter={requireLogin} /> <Route path='invite' component={CommunityInvite} onEnter={requireLogin} /> </Route> <Route path='t/:id' component={ThreadPage} onEnter={requireLogin} /> <Route path='p/:id' component={SinglePost} /> <Route path='n/new' component={NetworkEditor} onEnter={requireLogin} /> <Route path='n/:id' component={NetworkProfile} onEnter={requireLogin}> <IndexRoute component={NetworkPosts} /> <Route path='communities' component={NetworkCommunities} /> <Route path='members' component={NetworkMembers} /> <Route path='about' component={AboutNetwork} /> </Route> <Route path='n/:id/edit' component={NetworkEditor} onEnter={requireLogin} /> <Route component={AllCommunities}> <Route path='app' component={AllPosts} /> <Route path='tag/:tagName' component={TagPosts} /> <Route path='projects' component={Projects} onEnter={requireLogin} /> <Route path='events' component={Events} onEnter={requireLogin} /> <Route path='people' component={People} onEnter={requireLogin} /> </Route> <Route path='testbench' component={TestBench} /> <Route path='icons' component={IconTest} /> </Route> {/* legacy route name, for old versions of the mobile app */} <Route path='h/forgot-password' component={SetPassword} /> </Route> }
app/components/queue/queue.js
ritishgumber/dashboard-ui
import React from 'react'; import {connect} from 'react-redux'; import Toolbar from '../toolbar/toolbar.js'; import Footer from '../footer/footer.jsx'; import FirstDisplay from './firstDisplay.js' import {fetchQueue,resetQueueState} from '../../actions'; import QueueCRUD from './queueCRUD.js' import RefreshIndicator from 'material-ui/RefreshIndicator'; class Queue extends React.Component { constructor(props){ super(props) this.state = { } } static get contextTypes() { return { router: React.PropTypes.object.isRequired, } } componentWillMount(){ // redirect if active app not found if(!this.props.appData.viewActive){ this.context.router.push('/') } else { this.props.onLoad() } } componentWillUnmount(){ this.props.resetQueueState() } render() { let compToDisplay = <RefreshIndicator size={50} left={70} top={0} status="loading" className="loadermain" /> if(this.props.loaded){ compToDisplay = this.props.noQueueFound ? <FirstDisplay/> : <QueueCRUD/> } return ( <div id= "" style={{backgroundColor: '#FFF'}}> <div className="tables cache queue"> { compToDisplay } </div> </div> ); } } const mapStateToProps = (state) => { let noQueueFound = state.queue.allQueues.length == 0 return { appData: state.manageApp, noQueueFound:noQueueFound, loaded:state.queue.loaded }; }; const mapDispatchToProps = (dispatch) => { return { onLoad: () => dispatch(fetchQueue()), resetQueueState: () => dispatch(resetQueueState()) } }; export default connect(mapStateToProps, mapDispatchToProps)(Queue);
es/Stepper/StepLabel.js
uplevel-technology/material-ui-next
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; import Typography from '../Typography'; import StepIcon from './StepIcon'; export const styles = theme => ({ root: { display: 'flex', alignItems: 'center' }, horizontal: {}, vertical: {}, active: { fontWeight: 500 }, completed: { fontWeight: 500 }, disabled: { cursor: 'default' }, iconContainer: {}, iconContainerNoAlternative: { paddingRight: theme.spacing.unit }, alternativeLabelRoot: { flexDirection: 'column' }, alternativeLabel: { textAlign: 'center', marginTop: theme.spacing.unit * 2 } }); function StepLabel(props) { const { active, children, classes, className: classNameProp, completed, disabled, icon, orientation, alternativeLabel, last, optional } = props, other = _objectWithoutProperties(props, ['active', 'children', 'classes', 'className', 'completed', 'disabled', 'icon', 'orientation', 'alternativeLabel', 'last', 'optional']); const className = classNames(classes.root, classes[orientation], { [classes.disabled]: disabled, [classes.completed]: completed, [classes.alternativeLabelRoot]: alternativeLabel, classNameProp }); const labelClassName = classNames({ [classes.alternativeLabel]: alternativeLabel, [classes.completed]: completed, [classes.active]: active }); return React.createElement( 'div', _extends({ className: className }, other), icon && React.createElement( 'div', { className: classNames(classes.iconContainer, { [classes.iconContainerNoAlternative]: !alternativeLabel }) }, React.createElement(StepIcon, { completed: completed, active: active, icon: icon, alternativeLabel: alternativeLabel }) ), React.createElement( 'div', null, React.createElement( Typography, { type: 'body1', className: labelClassName }, children ), optional && React.createElement( Typography, { type: 'caption', className: classes.optional }, 'Optional' ) ) ); } StepLabel.defaultProps = { active: false, alternativeLabel: false, completed: false, disabled: false, last: false, optional: false, orientation: 'horizontal' }; StepLabel.muiName = 'StepLabel'; export default withStyles(styles)(StepLabel);
packages/react/src/components/molecules/CalloutLink/CalloutLink.stories.js
massgov/mayflower
import React from 'react'; import { StoryPage } from 'StorybookConfig/preview'; import CalloutLink from './index'; import CalloutLinkDocs from './CalloutLink.md'; import calloutLinkOptions from './CalloutLink.knobs.options'; const Template = (args) => <CalloutLink {...args} />; export const CalloutLinkExample = Template.bind({}); CalloutLinkExample.storyName = 'Default'; CalloutLinkExample.args = { text: 'Link to another page', href: '', info: 'this will be the tooltip text on hover', description: '', eyebrow: '', time: '', emphasized: '', theme: '' }; CalloutLinkExample.argTypes = { theme: { control: { type: 'select', options: calloutLinkOptions.theme } } }; export const CalloutLinkDescription = Template.bind({}); CalloutLinkDescription.storyName = 'CalloutLink with Description'; CalloutLinkDescription.args = { text: 'Link to another page', href: '', info: 'this will be the tooltip text on hover', description: 'This is some more important information about the text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque rutrum mauris quam, et imperdiet purus pellentesque vel.', theme: '' }; CalloutLinkDescription.argTypes = { theme: { control: { type: 'select', options: calloutLinkOptions.theme } } }; export const CalloutLinkDetails = Template.bind({}); CalloutLinkDetails.storyName = 'CalloutLink with Details'; CalloutLinkDetails.args = { text: 'Attorney General Announces a New Health Care Program', href: '', info: 'this will be the tooltip text on hover', eyebrow: 'Press Release', time: '30 mins Ago', emphasized: 'Office of the Attorney General', theme: 'white' }; CalloutLinkDetails.argTypes = { theme: { control: { type: 'select', options: calloutLinkOptions.theme } } }; export default { title: 'molecules/CalloutLink', component: CalloutLink, parameters: { docs: { page: () => <StoryPage Description={CalloutLinkDocs} /> } } };
src/shared/element-react/dist/npm/es6/src/input-number/InputNumber.js
thundernet8/Elune-WWW
import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import { Component, PropTypes } from '../../libs'; import Input from '../input'; import { accAdd, accSub } from './util'; var InputNumber = function (_Component) { _inherits(InputNumber, _Component); function InputNumber(props) { _classCallCheck(this, InputNumber); var _this = _possibleConstructorReturn(this, _Component.call(this, props)); _this.state = { value: props.defaultValue, inputActive: false }; return _this; } InputNumber.prototype.componentWillReceiveProps = function componentWillReceiveProps(props) { if (props.value != this.props.value) { this.setState({ value: props.value }); } }; InputNumber.prototype.onKeyDown = function onKeyDown(e) { switch (e.keyCode) { case 38: // KeyUp e.preventDefault(); this.increase(); break; case 40: // KeyDown e.preventDefault(); this.decrease(); break; default: break; } }; InputNumber.prototype.onBlur = function onBlur() { var value = this.state.value; if (this.isValid) { value = Number(value); if (value > this.props.max) { value = Number(this.props.max); } else if (value < this.props.min) { value = Number(this.props.min); } } else { value = undefined; } this.setState({ value: value }, this.onChange); }; InputNumber.prototype.onInput = function onInput(value) { var _this2 = this; this.setState({ value: value }, function () { clearTimeout(_this2.timeout); _this2.timeout = setTimeout(function () { _this2.onBlur(); }, 750); }); }; InputNumber.prototype.onChange = function onChange() { if (this.props.onChange) { this.props.onChange(this.state.value); } }; InputNumber.prototype.increase = function increase() { var _props = this.props, step = _props.step, max = _props.max, disabled = _props.disabled, min = _props.min; var _state = this.state, value = _state.value, inputActive = _state.inputActive; if (this.maxDisabled) { inputActive = false; } else { if (value + Number(step) > max || disabled) return; if (value + Number(step) < min) value = min - Number(step); value = accAdd(step, value); } this.setState({ value: value, inputActive: inputActive }, this.onChange); }; InputNumber.prototype.decrease = function decrease() { var _props2 = this.props, step = _props2.step, min = _props2.min, disabled = _props2.disabled, max = _props2.max; var _state2 = this.state, value = _state2.value, inputActive = _state2.inputActive; if (this.minDisabled) { inputActive = false; } else { if (value - Number(step) < min || disabled) return; if (value - Number(step) > max) value = Number(max) + Number(step); value = accSub(value, step); } this.setState({ value: value, inputActive: inputActive }, this.onChange); }; InputNumber.prototype.activeInput = function activeInput(disabled) { if (!this.props.disabled && !disabled) { this.setState({ inputActive: true }); } }; InputNumber.prototype.inactiveInput = function inactiveInput(disabled) { if (!this.props.disabled && !disabled) { this.setState({ inputActive: false }); } }; InputNumber.prototype.render = function render() { var _props3 = this.props, controls = _props3.controls, disabled = _props3.disabled, size = _props3.size; var _state3 = this.state, value = _state3.value, inputActive = _state3.inputActive; return React.createElement( 'div', { style: this.style(), className: this.className('el-input-number', size && 'el-input-number--' + size, { 'is-disabled': disabled, 'is-without-controls': !controls }) }, controls && React.createElement( 'span', { className: this.classNames("el-input-number__decrease", { 'is-disabled': this.minDisabled }), onClick: this.decrease.bind(this) }, React.createElement('i', { className: 'el-icon-minus' }) ), controls && React.createElement( 'span', { className: this.classNames("el-input-number__increase", { 'is-disabled': this.maxDisabled }), onClick: this.increase.bind(this) }, React.createElement('i', { className: 'el-icon-plus' }) ), React.createElement(Input, { ref: 'input', className: this.classNames({ 'is-active': inputActive }), value: value, disabled: disabled, size: size, onChange: this.onInput.bind(this), onKeyDown: this.onKeyDown.bind(this), onBlur: this.onBlur.bind(this) }) ); }; _createClass(InputNumber, [{ key: 'isValid', get: function get() { return this.state.value !== '' && !isNaN(Number(this.state.value)); } }, { key: 'minDisabled', get: function get() { return !this.isValid || this.state.value - Number(this.props.step) < this.props.min; } }, { key: 'maxDisabled', get: function get() { return !this.isValid || this.state.value + Number(this.props.step) > this.props.max; } }]); return InputNumber; }(Component); export default InputNumber; InputNumber.propTypes = { defaultValue: PropTypes.number, value: PropTypes.number, step: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), max: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), min: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), disabled: PropTypes.bool, controls: PropTypes.bool, size: PropTypes.string, onChange: PropTypes.func }; InputNumber.defaultProps = { step: 1, controls: true, max: Infinity, min: 0 };
src/svg-icons/action/settings-input-svideo.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsInputSvideo = (props) => ( <SvgIcon {...props}> <path d="M8 11.5c0-.83-.67-1.5-1.5-1.5S5 10.67 5 11.5 5.67 13 6.5 13 8 12.33 8 11.5zm7-5c0-.83-.67-1.5-1.5-1.5h-3C9.67 5 9 5.67 9 6.5S9.67 8 10.5 8h3c.83 0 1.5-.67 1.5-1.5zM8.5 15c-.83 0-1.5.67-1.5 1.5S7.67 18 8.5 18s1.5-.67 1.5-1.5S9.33 15 8.5 15zM12 1C5.93 1 1 5.93 1 12s4.93 11 11 11 11-4.93 11-11S18.07 1 12 1zm0 20c-4.96 0-9-4.04-9-9s4.04-9 9-9 9 4.04 9 9-4.04 9-9 9zm5.5-11c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5zm-2 5c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5z"/> </SvgIcon> ); ActionSettingsInputSvideo = pure(ActionSettingsInputSvideo); ActionSettingsInputSvideo.displayName = 'ActionSettingsInputSvideo'; ActionSettingsInputSvideo.muiName = 'SvgIcon'; export default ActionSettingsInputSvideo;
src/balloon.js
toolmantim/sams-29th-birthday
import React from 'react'; import Color from 'color'; import classnames from 'classnames'; import uuid from 'uuid'; import ExplosionOfSams from './explosion-of-sams'; import './balloon.css'; class Balloon extends React.Component { static colors = [ "#FFBA03", "#03BEFF", "#E366FD" ] constructor(props) { super(props); this.state = { color: this._randomColor(), popped: false, uuid: uuid() }; } static propTypes = { left: React.PropTypes.number.isRequired }; render() { return ( <div className={classnames("Balloon",{"Balloon--popped": this.state.popped})} style={this._style()}> <div className="Balloon__inner"> <svg className="Balloon__inner__touch-action" viewBox="0 0 300 600" onTouchStart={() => this._pop()} onClick={() => this._pop()}> <defs> <radialGradient cx="50%" cy="21.5625%" fx="50%" fy="21.5625%" r="44.7005208%" id={this._specularHighlightId()}> <stop stopColor={Color(this.state.color).lighten(0.5).hexString()} offset="0%"></stop> <stop stopColor={this.state.color} offset="100%"></stop> </radialGradient> </defs> <g transform="translate(50,100)"> <g className="Balloon__shadow"> <path d="M102,249 C82,229 2,169 2,109 C2,49 42,9 102,9 C162,9 202,49 202,109 C202,169 122,229 102,249 Z" opacity="0.4" fill="#000033"></path> </g> <g className="Balloon__object" fillRule="evenodd" fill="none"> <path className="Balloon__string" d="M105.425866,227 C84.0586786,247 126.793054,267.382812 105.425866,287.191406 C84.0586782,307 124.445398,332.050781 105.425866,347 C86.4063344,361.949219 126.28125,386.398437 105.640625,406.699219" stroke="#000000" strokeWidth="5"></path> <path className="Balloon__rubber" d="M100,240 C80,220 3.67394019e-15,160 0,100 C3.6739404e-15,40 40,7.3478808e-15 100,0 C160,-7.34788037e-15 200,40 200,100 C200,160 120,220 100,240 Z" fill={`url(#${this._specularHighlightId()})`}></path> </g> </g> </svg> <ExplosionOfSams exploding={this.state.popped} /> </div> </div> ) } _specularHighlightId() { return `specular-highlight-${this.state.uuid}` } _pop() { this.setState({popped: true}); } _style() { return { width: 100, left: `calc(${this.props.left * 100}%)` } } _randomColor() { return Balloon.colors[Math.floor(Math.random() * Balloon.colors.length)]; } } export default Balloon;
packages/wix-style-react/src/StatisticsWidget/test/StatisticsWidget.visual.js
wix/wix-style-react
import React from 'react'; import { storiesOf } from '@storybook/react'; import StatisticsWidget from '../StatisticsWidget'; import { SIZES } from '../constants'; import WixStyleReactProvider from '../../WixStyleReactProvider'; const sizes = Object.values(SIZES); const tests = [ { describe: 'sanity', its: [ { it: '3 items', props: { items: [ { value: '$7,500', description: 'Monday', percentage: 21, invertedPercentage: true, }, { value: '1 200 000', description: 'Tuesday', descriptionInfo: 'Sales on Tuesday', percentage: 11, }, { value: '21k', description: 'Wednesday', }, ], }, }, { it: '5 items', props: { items: [ { value: '$500', description: 'Monday', percentage: 21, }, { value: '$1,500', description: 'Tuesday', percentage: 21, invertedPercentage: true, }, { value: '$2,500', percentage: -11, }, { value: '$3,500', description: 'Thursday', percentage: -11, invertedPercentage: true, descriptionInfo: 'Sales on Thursday', }, { value: '0', description: 'Friday', percentage: 0, invertedPercentage: true, descriptionInfo: 'Sales on Friday', }, ], }, }, { it: '> 5 items', props: { items: [ { value: '$500', description: 'Monday', }, { value: '$1,500', description: 'Tuesday', percentage: 21, invertedPercentage: true, }, { value: '$2,500', percentage: 11, }, { value: '$3,500', description: 'Thursday', percentage: 0, invertedPercentage: true, descriptionInfo: 'Sales on Thursday', }, { value: '$4,500', description: 'Friday', descriptionInfo: 'Sales on Friday', }, { value: '$5,500', description: 'Saturday', percentage: 0, }, ], }, }, ], }, { describe: 'title', its: [ { it: 'without short text in a value', props: { items: [ { value: '$7,500,000,000', }, { value: '$1,200,000', }, { value: '$1,872', }, { value: 'Testing very very long text', }, ], }, }, { it: 'with tiny values', props: { size: 'tiny', items: [ { value: '$7,500,000,000', }, { value: '$1,200,000', }, { value: '$1,872', }, ], }, }, { it: 'with items alignment to start', props: { size: 'tiny', alignItems: 'start', items: [ { value: '$7,500,', }, { value: '$1,200', }, { value: '$1,872', }, ], }, }, { it: 'with short text in a value', props: { items: [ { value: '$7,500,000,000', valueInShort: '$7,5B', }, { value: '$1,200,000', valueInShort: '$1,2M', }, { value: '$1,872', valueInShort: '$1,8K', }, { value: 'Testing very very long text', valueInShort: 'Text', }, ], }, }, { it: 'empty values', props: { items: [ { description: 'Sales', }, { description: 'Views', }, { description: 'Revenues', }, ], }, }, ], }, { describe: 'description', its: [ { it: 'extra long description', props: { items: [ { value: '$1,000', description: 'The income out of trading goods on Monday', descriptionInfo: 'Sales on Monday', }, { value: '$2,000', description: 'The income out of trading goods on Tuesday', }, { value: '$3,000', description: 'The income out of trading goods on Wednesday', }, { value: '$4,000', description: 'The income out of trading goods on Thursday', descriptionInfo: 'Sales on Thursday', }, { value: '$4,000', description: 'The income out of trading goods on Friday', }, ], }, }, { it: 'Info icons', props: { items: [ { value: '$500', description: 'Monday', descriptionInfo: 'Sales on Thursday', }, { value: '$1,500', descriptionInfo: 'I am not visible because there is no description', }, { value: '$2,500', description: 'Wednesday', descriptionInfo: 'Sales on Wednesday', }, { value: '$2,500', description: 'The income out of trading goods on Thursday', descriptionInfo: 'Sales on Wednesday', }, { value: '$4,250,000,000', valueInShort: '$4,3B', description: 'The income out of trading goods on Friday', }, ], }, }, { it: 'empty values', props: { items: [ { description: 'Views', }, { description: 'Likes', }, { description: 'Revenue', }, ], }, }, { it: 'With tiny values', props: { size: 'tiny', items: [ { value: '$500', description: 'Monday', descriptionInfo: 'Sales on Thursday', }, { value: '$1,500', descriptionInfo: 'I am not visible because there is no description', }, { value: '$2,500', description: 'Wednesday', descriptionInfo: 'Sales on Wednesday', }, { value: '$2,500', description: 'The income out of trading goods on Thursday', descriptionInfo: 'Sales on Wednesday', }, { value: '$4,250,000,000', valueInShort: '$4,3B', description: 'The income out of trading goods on Friday', }, ], }, }, ], }, { describe: 'trends', its: [ { it: 'trends and inverted trends', props: { items: [ { value: '$500', description: 'Monday', percentage: 21, }, { value: '$1,500', description: 'Tuesday', percentage: 21, invertedPercentage: true, }, { value: '$2,500', percentage: -11, }, { value: '$3,500', description: 'Thursday', percentage: -11, invertedPercentage: true, descriptionInfo: 'Sales on Thursday', }, { value: '0', description: 'Friday', percentage: 0, invertedPercentage: true, descriptionInfo: 'Sales on Friday', }, ], }, }, ], }, { describe: 'children', its: [ { it: 'renders children', props: { items: [ { value: '100', description: 'Money', children: <div>That's a lot</div>, }, ], }, }, ], }, { describe: 'size', its: sizes.map(size => ({ it: size, props: { size, items: [ { value: '1,500', description: 'Orders', percentage: 21, invertedPercentage: true, }, { value: '$2,500', description: 'Outcome', percentage: -11, }, { value: '$3,500', description: 'Revenue', percentage: -11, invertedPercentage: true, descriptionInfo: 'Sales on Thursday', }, ], }, })), }, ]; tests.forEach(({ describe, its }) => { its.forEach(({ it, props }) => { storiesOf(`StatisticsWidget${describe ? '/' + describe : ''}`, module).add( it, () => ( <div style={{ marginLeft: 100, marginTop: 100 }}> <StatisticsWidget {...props} /> </div> ), ); }); }); sizes.forEach(size => { storiesOf(`Layout And Spacing| StatisticsWidget/sanity`, module).add( size, () => ( <WixStyleReactProvider features={{ reducedSpacingAndImprovedLayout: true }} > <div style={{ marginLeft: 100, marginTop: 100 }}> <StatisticsWidget size={size} items={[ { value: '1,500', description: 'Orders', percentage: 21, invertedPercentage: true, }, { value: '$2,500', description: 'Outcome', percentage: -11, }, { value: '$3,500', description: 'Revenue', percentage: -11, invertedPercentage: true, descriptionInfo: 'Sales on Thursday', }, ]} /> </div> </WixStyleReactProvider> ), ); });
src/components/inputs/TextInput.js
rghorbani/react-native-common
/** * Copyright 2016 Reza (github.com/rghorbani) * * @flow */ 'use strict'; import React from 'react'; import PropTypes from 'prop-types'; import { TextInput as RNTextInput, StyleSheet, Animated, TouchableOpacity, } from 'react-native'; import _ from 'lodash'; import { Colors, Constants, Modal, Image, Text, Typography, View, } from 'react-native-ui-lib'; import BaseInput from './BaseInput'; import TextArea from './TextArea'; const DEFAULT_COLOR_BY_STATE = { default: Colors.dark40, focus: Colors.blue30, error: Colors.red30, }; const DEFAULT_UNDERLINE_COLOR_BY_STATE = { default: Colors.dark70, focus: Colors.blue30, error: Colors.red30, }; const LABEL_TYPOGRAPHY = Typography.text80; export default class TextInput extends BaseInput { static displayName = 'TextInput'; static propTypes = { ...RNTextInput.propTypes, ...BaseInput.propTypes, /** * make component rtl */ rtl: PropTypes.bool, /** * should placeholder have floating behavior */ floatingPlaceholder: PropTypes.bool, /** * floating placeholder color as a string or object of states, ex. {default: 'black', error: 'red', focus: 'blue'} */ floatingPlaceholderColor: PropTypes.oneOfType([ PropTypes.string, PropTypes.object, ]), /** * This text will appear as a placeholder when the textInput becomes focused, only when passing floatingPlaceholder * as well (NOT for expandable textInputs) */ helperText: PropTypes.string, /** * hide text input underline, by default false */ hideUnderline: PropTypes.bool, /** * underline color as a string or object of states, ex. {default: 'black', error: 'red', focus: 'blue'} */ underlineColor: PropTypes.oneOfType([PropTypes.string, PropTypes.object]), /** * the color of all text when the input is disabled (if undefined will not apply color) */ disabledColor: PropTypes.string, /** * should text input be align to center */ centered: PropTypes.bool, /** * input error message, should be empty if no error exists */ error: PropTypes.string, /** * should the input component support error messages */ enableErrors: PropTypes.bool, /** * should the input expand to another text area modal */ expandable: PropTypes.bool, /** * Render custom expandable input (requires expandable to be true) */ renderExpandableInput: PropTypes.func, /** * allow custom rendering of expandable content when clicking on the input (useful for pickers) * accept props and state as params, ex. (props, state) => {...} * use toggleExpandableModal(false) method to toggle off the expandable content */ renderExpandable: PropTypes.func, /** * transform function executed on value and return transformed value */ transformer: PropTypes.func, /** * Fixed title that will displayed above the input (note: floatingPlaceholder MUST be 'false') */ title: PropTypes.string, /** * The title's color as a string or object of states, ex. {default: 'black', error: 'red', focus: 'blue'} */ titleColor: PropTypes.oneOfType([PropTypes.string, PropTypes.object]), /** * Additional styles for the title (not including 'color') */ titleStyle: PropTypes.oneOfType([ PropTypes.object, PropTypes.number, PropTypes.array, ]), /** * should the input display a character counter (only when passing 'maxLength') */ showCharacterCounter: PropTypes.bool, /** * should float the placeholer when focused (instead of when typing) */ floatOnFocus: PropTypes.bool, /** * should the errors be displayed at the top */ useTopErrors: PropTypes.bool, /** * Icon asset source for showing on the right side, appropriate for dropdown icon and such */ rightIconSource: PropTypes.oneOfType([PropTypes.object, PropTypes.number]), /** * Use to identify the component in tests */ testId: PropTypes.string, }; static defaultProps = { placeholderTextColor: DEFAULT_COLOR_BY_STATE.default, enableErrors: true, }; constructor(props) { super(props); this.updateFloatingPlaceholderState = this.updateFloatingPlaceholderState.bind( this, ); this.toggleExpandableModal = this.toggleExpandableModal.bind(this); this.state = { value: props.value, floatingPlaceholderState: new Animated.Value( this.shouldFloatPlacholder(props.value) ? 1 : 0, ), showExpandableModal: false, }; this.generatePropsWarnings(props); } componentWillReceiveProps(nextProps) { if (nextProps.value !== this.props.value) { this.setState( { value: nextProps.value }, this.updateFloatingPlaceholderState, ); } } componentDidMount() { // this.getHeight(); } /** Actions */ generatePropsWarnings(props) { if (props.maxLength === 0) { console.warn('Setting maxLength to zero will block typing in this input'); } if (props.showCharacterCounter && !props.maxLength) { console.warn( "In order to use showCharacterCount please pass 'maxLength' prop", ); } } generateStyles() { this.styles = createStyles(this.props); } toggleExpandableModal(value) { this.setState({ showExpandableModal: value }); } updateFloatingPlaceholderState(withoutAnimation) { if (withoutAnimation) { this.state.floatingPlaceholderState.setValue( this.shouldFloatPlacholder() ? 1 : 0, ); } else { Animated.spring(this.state.floatingPlaceholderState, { toValue: this.shouldFloatPlacholder() ? 1 : 0, duration: 150, }).start(); } } getPlaceholderText() { const { placeholder, helperText } = this.props; const text = this.shouldFakePlaceholder() ? this.shouldShowHelperText() ? helperText : ' ' : this.shouldShowTopError() && this.shouldShowHelperText() ? helperText : placeholder; return text; } // getHeight() { // const {multiline, numberOfLines} = this.props; // const typography = this.getTypography(); // if (!multiline) { // return typography.lineHeight; // } // // numberOfLines support for both platforms // if (multiline && numberOfLines) { // return typography.lineHeight * numberOfLines; // } // } isDisabled() { return this.props.editable === false; } getStateColor(colorProp, isUnderline) { const { focused } = this.state; const { error, disabledColor } = this.props; const colorByState = _.cloneDeep( isUnderline ? DEFAULT_UNDERLINE_COLOR_BY_STATE : DEFAULT_COLOR_BY_STATE, ); if (this.isDisabled() && disabledColor) { return disabledColor; } if (colorProp) { if (_.isString(colorProp)) { // use given color for any state return colorProp; } else if (_.isObject(colorProp)) { // set given colors by states _.merge(colorByState, colorProp); } } // return the right color for the current state let color = colorByState.default; if (error && isUnderline) { color = colorByState.error; } else if (focused) { color = colorByState.focus; } return color; } getCharCount() { const { value } = this.state; if (value) { return value.length; } return 0; } isCounterLimit() { const { maxLength } = this.props; const counter = this.getCharCount(); return counter === 0 ? false : maxLength <= counter; } hasText(value) { return !_.isEmpty(value || this.state.value); } shouldShowHelperText() { const { focused } = this.state; const { helperText } = this.props; return focused && helperText; } shouldFloatOnFocus() { const { focused } = this.state; const { floatOnFocus } = this.props; return focused && floatOnFocus; } shouldFloatPlacholder(text) { return ( this.hasText(text) || this.shouldShowHelperText() || this.shouldFloatOnFocus() ); } shouldFakePlaceholder() { const { floatingPlaceholder, centered } = this.props; return Boolean( floatingPlaceholder && !centered && !this.shouldShowTopError(), ); } shouldShowError() { const { enableErrors, error } = this.props; return enableErrors && error; } shouldShowTopError() { const { useTopErrors } = this.props; return this.shouldShowError() && useTopErrors; } /** Renders */ renderPlaceholder() { const { floatingPlaceholderState } = this.state; const { centered, expandable, placeholder, placeholderTextColor, floatingPlaceholderColor, multiline, } = this.props; const typography = this.getTypography(); const placeholderColor = this.getStateColor(placeholderTextColor); if (this.shouldFakePlaceholder()) { return ( <Animated.Text style={[ this.styles.floatingPlaceholder, this.styles.placeholder, typography, centered && this.styles.placeholderCentered, !centered && { top: floatingPlaceholderState.interpolate({ inputRange: [0, 1], outputRange: [multiline ? 30 : 28, multiline ? 7 : 0], }), fontSize: floatingPlaceholderState.interpolate({ inputRange: [0, 1], outputRange: [typography.fontSize, LABEL_TYPOGRAPHY.fontSize], }), color: floatingPlaceholderState.interpolate({ inputRange: [0, 1], outputRange: [ placeholderColor, this.getStateColor(floatingPlaceholderColor), ], }), lineHeight: this.shouldFloatPlacholder() ? LABEL_TYPOGRAPHY.lineHeight : typography.lineHeight, }, ]} numberOfLines={1} onPress={() => expandable && this.toggleExpandableModal(true)} suppressHighlighting > {placeholder} </Animated.Text> ); } } renderTitle() { const { floatingPlaceholder, title, titleColor, titleStyle } = this.props; const color = this.getStateColor(titleColor); if (!floatingPlaceholder && title) { return ( <Text style={[ { color }, this.styles.topLabel, this.styles.label, titleStyle, ]} > {title} </Text> ); } } renderCharCounter() { const { focused } = this.state; const { maxLength, showCharacterCounter, disabledColor } = this.props; if (maxLength && showCharacterCounter) { const counter = this.getCharCount(); const textColor = this.isCounterLimit() && focused ? DEFAULT_COLOR_BY_STATE.error : DEFAULT_COLOR_BY_STATE.default; const color = this.isDisabled() && disabledColor ? disabledColor : textColor; return ( <Text style={[{ color }, this.styles.bottomLabel, this.styles.label]}> {counter} / {maxLength} </Text> ); } } renderError(visible) { const { enableErrors, error, useTopErrors } = this.props; const positionStyle = useTopErrors ? this.styles.topLabel : this.styles.bottomLabel; if (visible && enableErrors) { return ( <Text style={[this.styles.errorMessage, this.styles.label, positionStyle]} > {error} </Text> ); } } renderExpandableModal() { const { renderExpandable } = this.props; const { showExpandableModal } = this.state; if (_.isFunction(renderExpandable) && showExpandableModal) { return renderExpandable(this.props, this.state); } return ( <Modal animationType={'slide'} visible={showExpandableModal} onRequestClose={() => this.toggleExpandableModal(false)} > <Modal.TopBar onCancel={() => this.toggleExpandableModal(false)} onDone={this.onDoneEditingExpandableInput} /> <View style={this.styles.expandableModalContent}> <TextArea ref={textarea => { this.expandableInput = textarea; }} {...this.props} value={this.state.value} /> </View> </Modal> ); } renderExpandableInput() { const { style, floatingPlaceholder, placeholder, hideUnderline, renderExpandableInput, rightIconSource, } = this.props; const { value } = this.state; const typography = this.getTypography(); const color = this.getStateColor( this.props.color || this.extractColorValue(), ); const minHeight = typography.lineHeight; const shouldShowPlaceholder = _.isEmpty(value) && !floatingPlaceholder; const inputStyle = [ this.styles.input, hideUnderline && this.styles.inputWithoutUnderline, typography, color && { color }, style, ]; if (_.isFunction(renderExpandableInput)) { return renderExpandableInput(this.getThemeProps()); } return ( <TouchableOpacity style={this.styles.expandableInput} activeOpacity={1} onPress={() => !this.isDisabled() && this.toggleExpandableModal(true)} > <Text style={[ { minHeight }, inputStyle, shouldShowPlaceholder && this.styles.placeholder, ]} numberOfLines={3} > {shouldShowPlaceholder ? placeholder : value} </Text> {rightIconSource && ( <Image pointerEvents="none" source={rightIconSource} /> )} </TouchableOpacity> ); } renderTextInput() { const { value } = this.state; // value set on state for floatingPlaceholder functionality const color = this.getStateColor( this.props.color || this.extractColorValue(), ); const typography = this.getTypography(); /* eslint-disable no-unused-vars */ const { style, placeholder, placeholderTextColor, floatingPlaceholder, rtl, centered, multiline, hideUnderline, numberOfLines, helperText, ...others } = this.props; /* eslint-enable no-unused-vars */ const inputStyle = [ this.styles.input, hideUnderline && this.styles.inputWithoutUnderline, typography, color && { color }, rtl && this.styles.inputRTL, centered && this.styles.inputCentered, // with the right flex on the tree hierarchy we might not need this // {height: this.getHeight()}, style, ]; // HACK: passing whitespace instead of undefined. Issue fixed in RN56 const placeholderText = this.getPlaceholderText(); const placeholderColor = this.getStateColor(placeholderTextColor); return ( <RNTextInput {...others} value={value} placeholder={placeholderText} placeholderTextColor={placeholderColor} underlineColorAndroid="transparent" style={inputStyle} multiline={multiline} numberOfLines={numberOfLines} onKeyPress={this.onKeyPress} onChangeText={this.onChangeText} onChange={this.onChange} onFocus={this.onFocus} onBlur={this.onBlur} ref={input => { this.input = input; }} /> ); } getTopPaddings() { const { floatingPlaceholder } = this.props; return floatingPlaceholder ? this.shouldShowTopError() ? undefined : 25 : undefined; } render() { const { centered, expandable, containerStyle, underlineColor, useTopErrors, hideUnderline, } = this.props; const underlineStateColor = this.getStateColor(underlineColor, true); return ( <View style={[this.styles.container, containerStyle]} collapsable={false}> <View> {this.shouldShowTopError() ? this.renderError(useTopErrors) : this.renderTitle()} </View> <View style={[ this.styles.innerContainer, hideUnderline && this.styles.innerContainerWithoutUnderline, { borderColor: underlineStateColor }, { paddingTop: this.getTopPaddings() }, ]} > {this.renderPlaceholder()} {expandable ? this.renderExpandableInput() : this.renderTextInput()} {this.renderExpandableModal()} </View> <View row> <View flex left={centered !== true}> {this.renderError(!useTopErrors)} </View> {this.renderCharCounter()} </View> </View> ); } /** Events */ onDoneEditingExpandableInput = () => { const expandableInputValue = _.get(this.expandableInput, 'state.value'); this.setState({ value: expandableInputValue }); this.state.floatingPlaceholderState.setValue(expandableInputValue ? 1 : 0); _.invoke(this.props, 'onChangeText', expandableInputValue); this.toggleExpandableModal(false); }; onKeyPress = event => { this.lastKey = event.nativeEvent.key; _.invoke(this.props, 'onKeyPress', event); }; onChangeText = text => { // when character count exceeds maxLength text will be empty string. // HACK: To avoid setting state value to '' we check the source of that deletion if (text === '' && this.lastKey && this.lastKey !== 'Backspace') { return; } const { transformer } = this.props; let transformedText = text; if (_.isFunction(transformer)) { transformedText = transformer(text); } _.invoke(this.props, 'onChangeText', transformedText); this.setState( { value: transformedText }, this.updateFloatingPlaceholderState, ); }; onFocus = (...args) => { _.invoke(this.props, 'onFocus', ...args); this.setState({ focused: true }, this.updateFloatingPlaceholderState); }; onBlur = (...args) => { _.invoke(this.props, 'onBlur', ...args); this.setState({ focused: false }, this.updateFloatingPlaceholderState); }; } function createStyles({ rtl, placeholderTextColor, centered }) { return StyleSheet.create({ container: {}, innerContainer: { flexDirection: 'row', borderBottomWidth: 1, borderColor: Colors.dark70, justifyContent: centered ? 'center' : undefined, flexGrow: 1, }, innerContainerWithoutUnderline: { borderBottomWidth: 0, }, input: { flexGrow: 1, marginBottom: Constants.isIOS ? 10 : 5, padding: 0, // textAlign: centered ? 'center' : (rtl ? 'right' : undefined), // writingDirection: rtl ? 'rtl' : undefined, backgroundColor: 'transparent', }, inputRTL: { textAlign: 'right', writingDirection: 'rtl', }, inputCentered: { textAlign: 'center', writingDirection: undefined, }, expandableInput: { flexDirection: 'row', alignItems: 'center', flexGrow: 1, }, inputWithoutUnderline: { marginBottom: undefined, }, floatingPlaceholder: { position: 'absolute', width: '100%', }, placeholder: { color: placeholderTextColor, textAlign: 'left', }, placeholderCentered: { left: 0, right: 0, textAlign: 'center', }, errorMessage: { color: Colors.red30, textAlign: centered ? 'center' : undefined, }, expandableModalContent: { flex: 1, paddingTop: 15, paddingHorizontal: 20, }, topLabel: { marginBottom: Constants.isIOS ? 6 : 7, }, bottomLabel: { marginTop: 1, }, label: { ...LABEL_TYPOGRAPHY, height: LABEL_TYPOGRAPHY.lineHeight, }, }); }
src/SectionHeaderActivityModal/index.js
christianalfoni/ducky-components
import IconAvaWrapper from '../IconAvaWrapper'; import React from 'react'; import PropTypes from 'prop-types'; import ButtonIcon from '../ButtonIcon'; import classNames from 'classnames'; import styles from './styles.css'; function SectionHeaderActivityModal(props) { return ( <div className={classNames(styles.wrapper, { [props.className]: props.className })}> {props.favorite ? <div className={styles.buttonIcon}> <ButtonIcon icon={'icon-star-off'} onClick={props.handleButtonOnClick} > {"Legg til favoritter"} </ButtonIcon> </div> : <div className={styles.buttonIcon}> <ButtonIcon icon={'icon-star_border'} onClick={props.handleButtonOnClick} > {"Fjern som favoritt"} </ButtonIcon> </div> } <div className={styles.iconWrapper}> <IconAvaWrapper icon={'icon-close'} onClick={props.onIconClose} size={"standard"} /> </div> </div> ); } SectionHeaderActivityModal.propTypes = { className: PropTypes.string, favorite: PropTypes.bool, handleButtonOnClick: PropTypes.func, onClick: PropTypes.func, onIconClose: PropTypes.func }; export default SectionHeaderActivityModal;
src/www/js/components/card-size-button.js
nickolusroy/react_dnd
import React from 'react'; import { SubmitButton } from '../form-fields/submit-button.js'; export class CardSizeButton extends React.Component { constructor(props) { super(props); this.updateSize = this.updateSize.bind(this); }; updateCardSize(size) { var cards = document.querySelector('.spell-card-container'); cards.setAttribute("data-card-size", size); } updateSize(e) { let size = e.target.innerHTML; let active = document.querySelector(".size-buttons .btn.active"); let buttons = document.querySelectorAll(".size-buttons"); if (e.target.className.indexOf("active") > -1) { e.target.className = "btn"; size = ""; } else if (active) { active.className = active.className.replace(/active/g,""); e.target.className += " active"; } else { e.target.className += " active"; } this.updateCardSize(size); } render() { return <div className="size-buttons"> <SubmitButton cssClass="sm" label="sm" onUpdate={this.updateSize} /> <SubmitButton cssClass="md" label="md" onUpdate={this.updateSize} /> <SubmitButton cssClass="lg" label="lg" onUpdate={this.updateSize} /> <SubmitButton cssClass="xl" label="xl" onUpdate={this.updateSize} /> </div> } }
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/Tests/setupTests.js
nuwand/carbon-apimgt
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import Enzyme, { shallow, render, mount } from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; import renderer from 'react-test-renderer'; import SwaggerParser from 'swagger-parser'; import path from 'path'; const CARBON_APIMGT_ROOT = path.join(__dirname, '../../../../../../../../../'); const SWAGGER_RELATIVE_PATH = 'components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml'; const swaggerFilePath = path.join(CARBON_APIMGT_ROOT, SWAGGER_RELATIVE_PATH); // React 16 Enzyme adapter Enzyme.configure({ adapter: new Adapter() }); // Make Enzyme functions available in all test files without importing global.React = React; global.shallow = shallow; global.render = render; global.mount = mount; global.renderer = renderer; if (global.document) { // To resolve createRange not defined issue https://github.com/airbnb/enzyme/issues/1626#issuecomment-398588616 document.createRange = () => ({ setStart: () => {}, setEnd: () => {}, commonAncestorContainer: { nodeName: 'BODY', ownerDocument: document, }, }); } global.apiDef = SwaggerParser.dereference(swaggerFilePath);
examples/todos/src/components/Link.js
gaearon/redux
import React from 'react' import PropTypes from 'prop-types' const Link = ({ active, children, onClick }) => ( <button onClick={onClick} disabled={active} style={{ marginLeft: '4px', }} > {children} </button> ) Link.propTypes = { active: PropTypes.bool.isRequired, children: PropTypes.node.isRequired, onClick: PropTypes.func.isRequired } export default Link
src/containers/Home/Home.js
nbuechler/friendly-finder
import React, { Component } from 'react'; import { Link } from 'react-router'; import { Button, Jumbotron } from 'react-bootstrap'; class Home extends Component { render() { return ( <Jumbotron style={{margin: '0%', padding: '10%', background: '#111 none repeat scroll 0% 0%'}}> <h2 style={{textAlign: 'right'}}>Friendly Finder</h2> <h5>The introspective learning tool includes a variety of data visualizations.</h5> <h5>Fantastic understandings about your log entries are synthesized to enhance your emotional intelligence.</h5> <h5>Compare your findings to those of your friends!</h5> <Link to="/login"> <Button bsStyle="success" className="pull-right"> Great! </Button> </Link> </Jumbotron> ); } } export default Home
src/docs/examples/ProgressBar/Example20Percent.js
dryzhkov/ps-react-dr
import React from 'react'; import ProgressBar from 'ps-react/ProgressBar'; /** An example showing a progress bar of 20 percent */ const Example20Percent = () => { return <ProgressBar percent={20} width={100} /> }; export default Example20Percent;
src/components/shared/no-connection.js
quanglam2807/webcatalog
import React from 'react'; import PropTypes from 'prop-types'; import Button from '@material-ui/core/Button'; import ErrorIcon from '@material-ui/icons/Error'; import Typography from '@material-ui/core/Typography'; import { withStyles } from '@material-ui/core/styles'; const styles = (theme) => ({ root: { alignItems: 'center', display: 'flex', flex: 1, flexDirection: 'column', height: '100%', width: '100%', color: theme.palette.text.disabled, }, icon: { height: 64, width: 64, }, tryAgainButton: { marginTop: 16, }, }); const NoConnection = (props) => { const { classes, onTryAgainButtonClick, } = props; return ( <div className={classes.root}> <ErrorIcon className={classes.icon} color="disabled" /> <br /> <Typography color="inherit" variant="h6" > Failed to Connect to Server </Typography> <Typography color="inherit" align="center" variant="subtitle1" > Please check your Internet connection. </Typography> <Button className={classes.tryAgainButton} color="primary" onClick={onTryAgainButtonClick} > Try Again </Button> </div> ); }; NoConnection.propTypes = { classes: PropTypes.object.isRequired, onTryAgainButtonClick: PropTypes.func.isRequired, }; export default withStyles(styles, { name: 'NoConnection' })(NoConnection);
SentenceMosaics/index.android.js
DFAxCMU/sentence-mosaics
/** * 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 SentenceMosaics 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.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button 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('SentenceMosaics', () => SentenceMosaics);
src/svg-icons/image/looks-3.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLooks3 = (props) => ( <SvgIcon {...props}> <path d="M19.01 3h-14c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4 7.5c0 .83-.67 1.5-1.5 1.5.83 0 1.5.67 1.5 1.5V15c0 1.11-.9 2-2 2h-4v-2h4v-2h-2v-2h2V9h-4V7h4c1.1 0 2 .89 2 2v1.5z"/> </SvgIcon> ); ImageLooks3 = pure(ImageLooks3); ImageLooks3.displayName = 'ImageLooks3'; ImageLooks3.muiName = 'SvgIcon'; export default ImageLooks3;
app/javascript/mastodon/features/audio/index.js
maa123/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; import { formatTime } from 'mastodon/features/video'; import Icon from 'mastodon/components/icon'; import classNames from 'classnames'; import { throttle } from 'lodash'; import { getPointerPosition, fileNameFromURL } from 'mastodon/features/video'; import { debounce } from 'lodash'; import Visualizer from './visualizer'; const messages = defineMessages({ play: { id: 'video.play', defaultMessage: 'Play' }, pause: { id: 'video.pause', defaultMessage: 'Pause' }, mute: { id: 'video.mute', defaultMessage: 'Mute sound' }, unmute: { id: 'video.unmute', defaultMessage: 'Unmute sound' }, download: { id: 'video.download', defaultMessage: 'Download file' }, }); const TICK_SIZE = 10; const PADDING = 180; export default @injectIntl class Audio extends React.PureComponent { static propTypes = { src: PropTypes.string.isRequired, alt: PropTypes.string, poster: PropTypes.string, duration: PropTypes.number, width: PropTypes.number, height: PropTypes.number, editable: PropTypes.bool, fullscreen: PropTypes.bool, intl: PropTypes.object.isRequired, cacheWidth: PropTypes.func, backgroundColor: PropTypes.string, foregroundColor: PropTypes.string, accentColor: PropTypes.string, currentTime: PropTypes.number, autoPlay: PropTypes.bool, volume: PropTypes.number, muted: PropTypes.bool, deployPictureInPicture: PropTypes.func, }; state = { width: this.props.width, currentTime: 0, buffer: 0, duration: null, paused: true, muted: false, volume: 0.5, dragging: false, }; constructor (props) { super(props); this.visualizer = new Visualizer(TICK_SIZE); } setPlayerRef = c => { this.player = c; if (this.player) { this._setDimensions(); } } _pack() { return { src: this.props.src, volume: this.audio.volume, muted: this.audio.muted, currentTime: this.audio.currentTime, poster: this.props.poster, backgroundColor: this.props.backgroundColor, foregroundColor: this.props.foregroundColor, accentColor: this.props.accentColor, }; } _setDimensions () { const width = this.player.offsetWidth; const height = this.props.fullscreen ? this.player.offsetHeight : (width / (16/9)); if (this.props.cacheWidth) { this.props.cacheWidth(width); } this.setState({ width, height }); } setSeekRef = c => { this.seek = c; } setVolumeRef = c => { this.volume = c; } setAudioRef = c => { this.audio = c; if (this.audio) { this.setState({ volume: this.audio.volume, muted: this.audio.muted }); } } setCanvasRef = c => { this.canvas = c; this.visualizer.setCanvas(c); } componentDidMount () { window.addEventListener('scroll', this.handleScroll); window.addEventListener('resize', this.handleResize, { passive: true }); } componentDidUpdate (prevProps, prevState) { if (prevProps.src !== this.props.src || this.state.width !== prevState.width || this.state.height !== prevState.height || prevProps.accentColor !== this.props.accentColor) { this._clear(); this._draw(); } } componentWillUnmount () { window.removeEventListener('scroll', this.handleScroll); window.removeEventListener('resize', this.handleResize); if (!this.state.paused && this.audio && this.props.deployPictureInPicture) { this.props.deployPictureInPicture('audio', this._pack()); } } togglePlay = () => { if (!this.audioContext) { this._initAudioContext(); } if (this.state.paused) { this.setState({ paused: false }, () => this.audio.play()); } else { this.setState({ paused: true }, () => this.audio.pause()); } } handleResize = debounce(() => { if (this.player) { this._setDimensions(); } }, 250, { trailing: true, }); handlePlay = () => { this.setState({ paused: false }); if (this.audioContext && this.audioContext.state === 'suspended') { this.audioContext.resume(); } this._renderCanvas(); } handlePause = () => { this.setState({ paused: true }); if (this.audioContext) { this.audioContext.suspend(); } } handleProgress = () => { const lastTimeRange = this.audio.buffered.length - 1; if (lastTimeRange > -1) { this.setState({ buffer: Math.ceil(this.audio.buffered.end(lastTimeRange) / this.audio.duration * 100) }); } } toggleMute = () => { const muted = !this.state.muted; this.setState({ muted }, () => { this.audio.muted = muted; }); } handleVolumeMouseDown = e => { document.addEventListener('mousemove', this.handleMouseVolSlide, true); document.addEventListener('mouseup', this.handleVolumeMouseUp, true); document.addEventListener('touchmove', this.handleMouseVolSlide, true); document.addEventListener('touchend', this.handleVolumeMouseUp, true); this.handleMouseVolSlide(e); e.preventDefault(); e.stopPropagation(); } handleVolumeMouseUp = () => { document.removeEventListener('mousemove', this.handleMouseVolSlide, true); document.removeEventListener('mouseup', this.handleVolumeMouseUp, true); document.removeEventListener('touchmove', this.handleMouseVolSlide, true); document.removeEventListener('touchend', this.handleVolumeMouseUp, true); } handleMouseDown = e => { document.addEventListener('mousemove', this.handleMouseMove, true); document.addEventListener('mouseup', this.handleMouseUp, true); document.addEventListener('touchmove', this.handleMouseMove, true); document.addEventListener('touchend', this.handleMouseUp, true); this.setState({ dragging: true }); this.audio.pause(); this.handleMouseMove(e); e.preventDefault(); e.stopPropagation(); } handleMouseUp = () => { document.removeEventListener('mousemove', this.handleMouseMove, true); document.removeEventListener('mouseup', this.handleMouseUp, true); document.removeEventListener('touchmove', this.handleMouseMove, true); document.removeEventListener('touchend', this.handleMouseUp, true); this.setState({ dragging: false }); this.audio.play(); } handleMouseMove = throttle(e => { const { x } = getPointerPosition(this.seek, e); const currentTime = this.audio.duration * x; if (!isNaN(currentTime)) { this.setState({ currentTime }, () => { this.audio.currentTime = currentTime; }); } }, 15); handleTimeUpdate = () => { this.setState({ currentTime: this.audio.currentTime, duration: this.audio.duration, }); } handleMouseVolSlide = throttle(e => { const { x } = getPointerPosition(this.volume, e); if(!isNaN(x)) { this.setState({ volume: x }, () => { this.audio.volume = x; }); } }, 15); handleScroll = throttle(() => { if (!this.canvas || !this.audio) { return; } const { top, height } = this.canvas.getBoundingClientRect(); const inView = (top <= (window.innerHeight || document.documentElement.clientHeight)) && (top + height >= 0); if (!this.state.paused && !inView) { this.audio.pause(); if (this.props.deployPictureInPicture) { this.props.deployPictureInPicture('audio', this._pack()); } this.setState({ paused: true }); } }, 150, { trailing: true }); handleMouseEnter = () => { this.setState({ hovered: true }); } handleMouseLeave = () => { this.setState({ hovered: false }); } handleLoadedData = () => { const { autoPlay, currentTime, volume, muted } = this.props; if (currentTime) { this.audio.currentTime = currentTime; } if (volume !== undefined) { this.audio.volume = volume; } if (muted !== undefined) { this.audio.muted = muted; } if (autoPlay) { this.togglePlay(); } } _initAudioContext () { const AudioContext = window.AudioContext || window.webkitAudioContext; const context = new AudioContext(); const source = context.createMediaElementSource(this.audio); this.visualizer.setAudioContext(context, source); source.connect(context.destination); this.audioContext = context; } handleDownload = () => { fetch(this.props.src).then(res => res.blob()).then(blob => { const element = document.createElement('a'); const objectURL = URL.createObjectURL(blob); element.setAttribute('href', objectURL); element.setAttribute('download', fileNameFromURL(this.props.src)); document.body.appendChild(element); element.click(); document.body.removeChild(element); URL.revokeObjectURL(objectURL); }).catch(err => { console.error(err); }); } _renderCanvas () { requestAnimationFrame(() => { if (!this.audio) return; this.handleTimeUpdate(); this._clear(); this._draw(); if (!this.state.paused) { this._renderCanvas(); } }); } _clear() { this.visualizer.clear(this.state.width, this.state.height); } _draw() { this.visualizer.draw(this._getCX(), this._getCY(), this._getAccentColor(), this._getRadius(), this._getScaleCoefficient()); } _getRadius () { return parseInt(((this.state.height || this.props.height) - (PADDING * this._getScaleCoefficient()) * 2) / 2); } _getScaleCoefficient () { return (this.state.height || this.props.height) / 982; } _getCX() { return Math.floor(this.state.width / 2); } _getCY() { return Math.floor(this._getRadius() + (PADDING * this._getScaleCoefficient())); } _getAccentColor () { return this.props.accentColor || '#ffffff'; } _getBackgroundColor () { return this.props.backgroundColor || '#000000'; } _getForegroundColor () { return this.props.foregroundColor || '#ffffff'; } seekBy (time) { const currentTime = this.audio.currentTime + time; if (!isNaN(currentTime)) { this.setState({ currentTime }, () => { this.audio.currentTime = currentTime; }); } } handleAudioKeyDown = e => { // On the audio element or the seek bar, we can safely use the space bar // for playback control because there are no buttons to press if (e.key === ' ') { e.preventDefault(); e.stopPropagation(); this.togglePlay(); } } handleKeyDown = e => { switch(e.key) { case 'k': e.preventDefault(); e.stopPropagation(); this.togglePlay(); break; case 'm': e.preventDefault(); e.stopPropagation(); this.toggleMute(); break; case 'j': e.preventDefault(); e.stopPropagation(); this.seekBy(-10); break; case 'l': e.preventDefault(); e.stopPropagation(); this.seekBy(10); break; } } render () { const { src, intl, alt, editable, autoPlay } = this.props; const { paused, muted, volume, currentTime, duration, buffer, dragging } = this.state; const progress = Math.min((currentTime / duration) * 100, 100); return ( <div className={classNames('audio-player', { editable })} ref={this.setPlayerRef} style={{ backgroundColor: this._getBackgroundColor(), color: this._getForegroundColor(), width: '100%', height: this.props.fullscreen ? '100%' : (this.state.height || this.props.height) }} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} tabIndex='0' onKeyDown={this.handleKeyDown}> <audio src={src} ref={this.setAudioRef} preload={autoPlay ? 'auto' : 'none'} onPlay={this.handlePlay} onPause={this.handlePause} onProgress={this.handleProgress} onLoadedData={this.handleLoadedData} crossOrigin='anonymous' /> <canvas role='button' tabIndex='0' className='audio-player__canvas' width={this.state.width} height={this.state.height} style={{ width: '100%', position: 'absolute', top: 0, left: 0 }} ref={this.setCanvasRef} onClick={this.togglePlay} onKeyDown={this.handleAudioKeyDown} title={alt} aria-label={alt} /> <img src={this.props.poster} alt='' width={(this._getRadius() - TICK_SIZE) * 2} height={(this._getRadius() - TICK_SIZE) * 2} style={{ position: 'absolute', left: this._getCX(), top: this._getCY(), transform: 'translate(-50%, -50%)', borderRadius: '50%', pointerEvents: 'none' }} /> <div className='video-player__seek' onMouseDown={this.handleMouseDown} ref={this.setSeekRef}> <div className='video-player__seek__buffer' style={{ width: `${buffer}%` }} /> <div className='video-player__seek__progress' style={{ width: `${progress}%`, backgroundColor: this._getAccentColor() }} /> <span className={classNames('video-player__seek__handle', { active: dragging })} tabIndex='0' style={{ left: `${progress}%`, backgroundColor: this._getAccentColor() }} onKeyDown={this.handleAudioKeyDown} /> </div> <div className='video-player__controls active'> <div className='video-player__buttons-bar'> <div className='video-player__buttons left'> <button type='button' title={intl.formatMessage(paused ? messages.play : messages.pause)} aria-label={intl.formatMessage(paused ? messages.play : messages.pause)} className='player-button' onClick={this.togglePlay}><Icon id={paused ? 'play' : 'pause'} fixedWidth /></button> <button type='button' title={intl.formatMessage(muted ? messages.unmute : messages.mute)} aria-label={intl.formatMessage(muted ? messages.unmute : messages.mute)} className='player-button' onClick={this.toggleMute}><Icon id={muted ? 'volume-off' : 'volume-up'} fixedWidth /></button> <div className={classNames('video-player__volume', { active: this.state.hovered })} ref={this.setVolumeRef} onMouseDown={this.handleVolumeMouseDown}> <div className='video-player__volume__current' style={{ width: `${volume * 100}%`, backgroundColor: this._getAccentColor() }} /> <span className='video-player__volume__handle' tabIndex='0' style={{ left: `${volume * 100}%`, backgroundColor: this._getAccentColor() }} /> </div> <span className='video-player__time'> <span className='video-player__time-current'>{formatTime(Math.floor(currentTime))}</span> <span className='video-player__time-sep'>/</span> <span className='video-player__time-total'>{formatTime(Math.floor(this.state.duration || this.props.duration))}</span> </span> </div> <div className='video-player__buttons right'> <a title={intl.formatMessage(messages.download)} aria-label={intl.formatMessage(messages.download)} className='video-player__download__icon player-button' href={this.props.src} download> <Icon id={'download'} fixedWidth /> </a> </div> </div> </div> </div> ); } }
src/redux/utils/createDevToolsWindow.js
teebszet/iplayer-azListing
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import DevTools from '../../containers/DevToolsWindow' export default function createDevToolsWindow (store) { const win = window.open( null, 'redux-devtools', // give it a name so it reuses the same window `width=400,height=${window.outerHeight},menubar=no,location=no,resizable=yes,scrollbars=no,status=no` ) // reload in case it's reusing the same window with the old content win.location.reload() // wait a little bit for it to reload, then render setTimeout(() => { // Wait for the reload to prevent: // "Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element." win.document.write('<div id="react-devtools-root"></div>') win.document.body.style.margin = '0' ReactDOM.render( <Provider store={store}> <DevTools /> </Provider> , win.document.getElementById('react-devtools-root') ) }, 10) }
src/layout/hero-head.js
bokuweb/re-bulma
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styles from '../../build/styles'; import { getCallbacks } from '../helper/helper'; export default class HeroHead extends Component { static propTypes = { style: PropTypes.object, children: PropTypes.any, className: PropTypes.string, }; static defaultProps = { style: {}, className: '', }; createClassName() { return [ styles.heroHead, this.props.className, ].join(' ').trim(); } render() { return ( <section {...getCallbacks(this.props)} style={this.props.style} className={this.createClassName()} > {this.props.children} </section> ); } }
src/svg-icons/action/android.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAndroid = (props) => ( <SvgIcon {...props}> <path d="M6 18c0 .55.45 1 1 1h1v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V19h2v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V19h1c.55 0 1-.45 1-1V8H6v10zM3.5 8C2.67 8 2 8.67 2 9.5v7c0 .83.67 1.5 1.5 1.5S5 17.33 5 16.5v-7C5 8.67 4.33 8 3.5 8zm17 0c-.83 0-1.5.67-1.5 1.5v7c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5v-7c0-.83-.67-1.5-1.5-1.5zm-4.97-5.84l1.3-1.3c.2-.2.2-.51 0-.71-.2-.2-.51-.2-.71 0l-1.48 1.48C13.85 1.23 12.95 1 12 1c-.96 0-1.86.23-2.66.63L7.85.15c-.2-.2-.51-.2-.71 0-.2.2-.2.51 0 .71l1.31 1.31C6.97 3.26 6 5.01 6 7h12c0-1.99-.97-3.75-2.47-4.84zM10 5H9V4h1v1zm5 0h-1V4h1v1z"/> </SvgIcon> ); ActionAndroid = pure(ActionAndroid); ActionAndroid.displayName = 'ActionAndroid'; ActionAndroid.muiName = 'SvgIcon'; export default ActionAndroid;
assets/javascripts/kitten/karl/pages/homepage/partners/index.js
KissKissBankBank/kitten
import React from 'react' import styled from 'styled-components' import { Card } from './components/card' import { pxToRem, Title, Carousel, mediaQueries, Grid, GridCol } from 'kitten' import classNames from 'classnames' const StyledPartners = styled.div` .Partners__col { display: flex; } .Partners__colCards { &:first-child { margin-right: ${pxToRem(20)}; } &:last-child { margin-left: ${pxToRem(20)}; } } ` const selectionData = [ { title: 'Sloe, le soin nomade et naturel à la conquête', text: 'Découvrez des soins 100% naturels et écologiques pour vous aider à passer le cap et en finir avec le plastique.', imageSrc: 'https://source.unsplash.com/random/315x198?kitten,1', title2: 'Un titre court', text2: 'Découvrez des soins 100% naturels et écologiques pour vous aider à passer le cap et en finir avec le plastique.', imageSrc2: 'https://source.unsplash.com/random/315x198?kitten,2', title3: 'Lancement des prochains pantalons à plis intemporels', text3: 'Soutenez le lancement des prochains pantalons à plis intemporels fabriqués à Paris', imageSrc3: 'https://source.unsplash.com/random/315x198?kitten,3', }, { title: 'Sloe, le soin nomade et naturel à la conquête de vos salles de bain', text: 'Découvrez des soins 100% naturels et écologiques pour vous aider à passer le cap et en finir avec le plastique.', imageSrc: 'https://source.unsplash.com/random/315x198?kitten,4', title2: 'Un titre court', text2: 'Découvrez des soins 100% naturels et écologiques pour vous aider à passer le cap et en finir avec le plastique.', imageSrc2: 'https://source.unsplash.com/random/315x198?kitten,5', title3: 'Lancement des prochains pantalons à plis intemporels', text3: 'Soutenez le lancement des prochains pantalons à plis intemporels fabriqués à Paris', imageSrc3: 'https://source.unsplash.com/random/315x198?kitten,6', }, ] const PartnersBase = ({ viewportIsXSOrLess }) => ( <StyledPartners> <Title tag="h3" className={classNames( 'Homepage__section__title', 'k-u-margin-top-none', 'k-u-margin-bottom-singleHalf@s-up', 'k-u-margin-bottom-single@s-down', )} > Lorem ipsum dolor sit </Title> <div className="k-u-hidden@l-up"> <Carousel itemMinWidth={viewportIsXSOrLess ? 250 : 490} baseItemMarginBetween={10} paginationPosition={{ default: 'bottom' }} smallButtons showPageSquares preferCompletePaginationOnMobile loop > {selectionData.map((item, index) => ( <div key={index}> <Card title={item.title} text={item.text} imageProps={{ src: item.imageSrc, alt: 'Image alt', }} /> <Card title={item.title2} text={item.text2} imageProps={{ src: item.imageSrc2, alt: 'Image alt', }} /> <Card title={item.title3} text={item.text3} imageProps={{ src: item.imageSrc3, alt: 'Image alt', }} /> </div> ))} </Carousel> </div> <Grid className="k-u-hidden@m-down"> <GridCol className="Partners__col"> {selectionData.map((item, index) => ( <div className="Partners__colCards" key={index}> <Card title={item.title} text={item.text} imageProps={{ src: item.imageSrc, alt: 'Image alt', }} /> <Card title={item.title2} text={item.text2} imageProps={{ src: item.imageSrc2, alt: 'Image alt', }} /> <Card title={item.title3} text={item.text3} imageProps={{ src: item.imageSrc3, alt: 'Image alt', }} /> </div> ))} </GridCol> </Grid> </StyledPartners> ) export const Partners = mediaQueries(PartnersBase, { viewportIsXSOrLess: true, })
src/icons/FolderSpecialIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class FolderSpecialIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M40 12H24l-4-4H8c-2.2 0-4 1.8-4 4v24c0 2.2 1.8 4 4 4h32c2.2 0 4-1.8 4-4V16c0-2.2-1.8-4-4-4zm-4.13 22L30 30.56 24.13 34l1.56-6.66-5.18-4.48 6.83-.59L30 16l2.67 6.28 6.83.59-5.18 4.48L35.87 34z"/></svg>;} };
src/main/assets/components/ListPoster.js
kristenkotkas/moviediary
import React from 'react'; import '../static/css/index.css'; import FontAwesome from 'react-fontawesome'; export default class ListPoster extends React.Component { constructor(props) { super(props); } /* <span className={'hoverOpen'}>Open</span>*/ removeMovie() { this.props.removeCallback(this.props.movieId); } openMovie() { this.props.openCallback(this.props.movieId); } render() { return ( <div className={'boxContainer'}> <div className={'listBox'}> <div className={'hoverBackground'}></div> <span className={'hoverYear'}>{this.props.movieYear}</span> <span className={'hoverTitle'}>{this.props.movieTitle}</span> <span className={'hoverRating'}>{this.props.movieRating}</span> {this.props.movieSeen ? <span className={'hoverSeen'}></span> : null} <div className={'hoverBorder'}></div> <span className={'hoverOpen'} onClick={this.openMovie.bind(this)}>Open</span> <FontAwesome className={'posterClose'} name={'times'} size={'lg'} onClick={this.removeMovie.bind(this)} /> <img src={this.props.moviePosterPath} className={'listPosterImg'} alt=""/> </div> </div> ); } }
node_modules/rebass/src/Arrow.js
HasanSa/hackathon
import React from 'react' import Base from './Base' /** Arrow for use in dropdowns and other UI elements */ const Arrow = ({ direction, children, ...props }, { rebass }) => { return ( <Base {...props} className='Arrow' baseStyle={{ display: 'inline-block', width: 0, height: 0, marginLeft: '.5em', verticalAlign: 'middle', borderRight: '.3125em solid transparent', borderLeft: '.3125em solid transparent', borderTop: direction === 'down' ? '.4375em solid' : null, borderBottom: direction === 'up' ? '.4375em solid' : null }} /> ) } Arrow.propTypes = { /** Direction of arrow */ direction: React.PropTypes.oneOf(['up', 'down']) } Arrow.defaultProps = { direction: 'down' } Arrow.contextTypes = { rebass: React.PropTypes.object } export default Arrow
examples/js/hacker-news/client/containers/App.js
reimagined/resolve
import React from 'react' import { NavLink, Link as NormalLink } from 'react-router-dom' import styled from 'styled-components' import { renderRoutes } from 'react-router-config' import { Splitter } from '../components/Splitter' import { Header } from './Header' import { LoginInfo } from './LoginInfo' import { StaticImage } from './StaticImage' import { Search } from './Search' const ContentRoot = styled.div` width: 90%; max-width: 1280px; margin: 8px auto; color: #000; background-color: #f5f5f5; font-size: 10pt; font-family: Verdana, Geneva, sans-serif; @media only screen and (max-width: 750px) and (min-width: 300px) { width: 100%; margin: 0px auto; } ` const PageHeader = styled.div` color: #fff; background-color: #3949ab; padding: 6px; line-height: 18px; vertical-align: middle; position: relative; ` const Link = styled(NavLink)` color: white; &.active { font-weight: bold; text-decoration: underline; } ` const PageTitle = styled.div` display: inline-block; font-weight: bold; color: #fff; margin-left: 0.25em; margin-right: 0.75em; @media only screen and (max-width: 750px) and (min-width: 300px) { display: none; } ` const Content = styled.div` overflow-wrap: break-word; word-wrap: break-word; padding: 1em; ` const Footer = styled.div` margin-top: 1em; border-top: 1px solid #e7e7e7; text-align: center; padding: 6px 0; ` const FooterLink = styled.a` color: #333; text-decoration: underline; ` const App = ({ route }) => ( <div> <Header title="reSolve Hacker News" favicon="/favicon.png" css={['/style.css']} /> <ContentRoot> <PageHeader> <Link to="/"> <StaticImage src="/reSolve-logo.svg" width="18" height="18" alt="" /> </Link> <Link to="/newest"> <PageTitle>reSolve HN</PageTitle> </Link>{' '} <Link to="/newest">new</Link> <Splitter color="white" /> <Link to="/comments">comments</Link> <Splitter color="white" /> <Link to="/show">show</Link> <Splitter color="white" /> <Link to="/ask">ask</Link> <Splitter color="white" /> <NormalLink to="/submit">submit</NormalLink> <LoginInfo /> <Search /> </PageHeader> <Content>{renderRoutes(route.routes)}</Content> <Footer> <FooterLink href="https://github.com/reimagined/resolve"> reimagined/resolve </FooterLink> </Footer> </ContentRoot> </div> ) export { App }
app/routes/home-routes.js
KleeGroup/focus-starter-kit
import React from 'react'; import HomeView from '../views/home'; const routes = [ { path: 'home', component: HomeView }, { path: 'admin', component: (() => <div><h2>{'Administration'}</h2></div>) } ]; export default routes;
src/client/components/menu/chatSearch.js
uuchat/uuchat
import React, { Component } from 'react'; import { Modal, message, Input } from 'antd'; import ChatMessageItem from '../message/chatMessageItem'; import String2int from '../common/utils'; import '../../static/css/common.css'; import '../../static/css/customerSuccess.css'; let chatHistory = {}; let searchContent = ''; let pageNum = 0; class ChatSearchItem extends Component{ msgConver = (msg) => { let str = ''; if (/"email":/g.test(msg)) { msg = JSON.parse(msg); str += '<span>Offline messages(email: '+msg.email+'): </span>'; str += msg.content; } else { str = msg.replace(/#/gi, "<br />").replace(/((https?|ftp|file|http):\/\/[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*)/g, function(match) { return '<a href="' + match + '" target="_blank">' + match + '</a>'; }); } return <div dangerouslySetInnerHTML={{__html: str}}></div>; }; showHistory = (e) => { this.props.showHistory(this.props.cid); }; render() { return ( <li onClick={this.showHistory}> <div className={"fl search-avatar avatar-icon-"+String2int(this.props.cid)}>{this.props.cid.substr(0, 1).toUpperCase()}</div> <div className="fr search-text">{this.msgConver(this.props.msg)}</div> </li> ); } } class ChatSearch extends Component{ constructor() { super(); this.state = { csid: localStorage.getItem('uuchat.csid') || '', searchList: [], hisCid: '', isHisVis: false, hisTitle: '', isViewMore: false }; } componentDidMount() { let search = window.location.href; let content = ''; if (search.indexOf('?search=') > -1) { search = search.split('?')[1].split('&'); for (let i = 0, l = search.length; i < l; i++) { if (search[i].indexOf('search=') > -1) { content = search[i].split('=')[1]; break; } } searchContent = content; this.getSearchList(content); } } getSearchList = (content) => { let that = this; fetch('/messages/cs/'+that.state.csid+'/search?msg='+content).then(function(d){ return d.json(); }).then(function(d){ if (d.code === 200) { let isView = true; if (d.msg.length > 0) { pageNum++; } else { pageNum = 0; message.info('There has no chats result aboute '+content, 4); } if (d.msg.length <5) { isView = false; } that.setState({ searchList: d.msg, isViewMore: isView }); } }).catch(function(e){}); }; fetchHistory = (cid) => { let that = this, avatar = localStorage.getItem('uuchat.avatar') ? localStorage.getItem('uuchat.avatar') : require('../../static/images/contact.png'); fetch('/messages/customer/'+cid+'/cs/'+that.state.csid) .then((data) => data.json()) .then(d =>{ let historyMessage = []; d.msg.map((dd) =>{ return historyMessage.push({ msgAvatar: (dd.type === 1) ? avatar : '', msgText: dd.msg, msgType: dd.type, msgTime: new Date(dd.createdAt) }); }); chatHistory[cid] = historyMessage; that.renderHistory(cid); }) .catch(function(e){}); }; renderHistory = (cid) => { this.setState({ hisCid: cid, isHisVis: true, hisTitle: 'U-'+(cid.substr(0, 6).toUpperCase())+' chats history' }); }; historyClose = () => { this.setState({ isHisVis: false }); }; viewMore = () => { let that = this; fetch('/messages/cs/'+that.state.csid+'/search/latestmonth?msg='+searchContent+'&pageNum='+(pageNum * 5)).then(function(d){ return d.json(); }).then(function(d){ if (d.code === 200) { if (d.msg.length > 0) { let sList = that.state.searchList; sList = sList.concat(d.msg); pageNum++; that.setState({ searchList: sList }); } else { pageNum = 0; message.info('There has no more result!', 4); } if (d.msg.length < 5) { that.setState({ isViewMore: false }); } } }).catch(function(e){}); }; onSearchHandler = (e) => { if (e.target.value!=="") { this.getSearchList(e.target.value); } }; render() { let state = this.state; let sArr = []; let searchL = state.searchList; let chatHistoryData = chatHistory[state.hisCid]; let historyColorIndex = String2int(state.hisCid); for (let i = 0, l = searchL.length; i < l; i++) { sArr.push(<ChatSearchItem key={i} cid={searchL[i].cid} msg={searchL[i].msg} showHistory={this.fetchHistory} />); } return ( <div className="search-body"> <div className="customerSuccess-header"> <div className="search-user-info"> <Input.Search placeholder="Type text and enter" onPressEnter={this.onSearchHandler} name="search" /> </div> </div> <Modal title={state.hisTitle} visible={state.isHisVis} footer={null} onCancel={this.historyClose} className={"history-header history-header-"+historyColorIndex} > <div className="message-lists chat-lists-history"> {chatHistoryData && chatHistoryData.map((msg ,index)=> <ChatMessageItem key={index} ownerType={msg.msgType} ownerAvatar={ msg.msgAvatar ? msg.msgAvatar : <div className={"avatar-color avatar-icon-"+historyColorIndex} >{state.hisCid.substr(0, 1).toUpperCase()}</div> } ownerText={msg.msgText} time={msg.msgTime} /> )} </div> </Modal> <div className="search-main"> <ul className="search-list"> <li> Chats history lists </li> {sArr} <li className="more-search" style={{display: state.isViewMore ? '' : 'none'}} onClick={this.viewMore}>View more </li> </ul> <div className="none-results" style={{display: searchL.length > 0 ? 'none' : ''}}>No relevant results were found</div> </div> </div> ); } } export default ChatSearch;
app/containers/RepoListItem/index.js
darrellesh/redux-react-boilerplate
/** * RepoListItem * * Lists the name and the issue count of a repository */ import React from 'react'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import { FormattedNumber } from 'react-intl'; import { makeSelectCurrentUser } from 'containers/App/selectors'; import { MdStarBorder } from 'react-icons/lib/md/'; import ListItem from 'components/ListItem'; import IssueIcon from './IssueIcon'; import IssueLink from './IssueLink'; import RepoLink from './RepoLink'; import Wrapper from './Wrapper'; export class RepoListItem extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { const item = this.props.item; let nameprefix = ''; // If the repository is owned by a different person than we got the data for // it's a fork and we should show the name of the owner if (item.owner.login !== this.props.currentUser) { nameprefix = `${item.owner.login}/`; } // Put together the content of the repository const content = ( <Wrapper> <RepoLink href={item.html_url} target="_blank"> {nameprefix + item.name} </RepoLink> <IssueLink href={`${item.html_url}/stargazers`} target="_blank"> <MdStarBorder /> </IssueLink> <IssueLink href={`${item.html_url}/issues`} target="_blank"> <IssueIcon /> <FormattedNumber value={item.open_issues_count} /> </IssueLink> </Wrapper> ); // Render the content into a list item return ( <ListItem key={`repo-list-item-${item.full_name}`} item={content} /> ); } } RepoListItem.propTypes = { item: React.PropTypes.object, currentUser: React.PropTypes.string, }; export default connect(createStructuredSelector({ currentUser: makeSelectCurrentUser(), }))(RepoListItem);
index.js
michaelchance/stacksnowverflow
require('babel-core/polyfill'); import { createStore, applyMiddleware } from 'redux'; import thunkMiddleware from 'redux-thunk'; import apiMiddleware from './apiMiddleware.js'; import loggerMiddleware from 'redux-logger'; import rootReducer from './reducers.js'; import React from 'react'; import { Provider } from 'react-redux'; import { Router, Route, IndexRoute } from 'react-router'; import createHashHistory from 'history/lib/createHashHistory'; // import HashHistory from 'react-router/lib/HashHistory'; import App from './pages/app.js'; import HomePage from './pages/home.js'; import SearchPage from './pages/search.js'; import QuestionPage from './pages/question.js'; import TagListingPage from './pages/taglisting.js'; import TagDetailPage from './pages/tagdetail.js'; import ProfileContainer from './pages/profilecontainer.js'; import ProfilePage from './pages/profile.js'; import ProfileFavoritesPage from './pages/favorites.js'; import ProfileAnswersPage from './pages/answers.js'; // const history = new HashHistory(); const initialState = {version:"201509141044"}; const store = applyMiddleware( thunkMiddleware, apiMiddleware, loggerMiddleware )(createStore)(rootReducer, initialState); React.render( <Provider store={store}> {()=> <Router history={createHashHistory()}> <Route path="/" component={App}> <IndexRoute component={HomePage}/> <Route path="/search" component={SearchPage}/> <Route path="/question/:id" component={QuestionPage}/> <Route path="/tags" component={TagListingPage}/> <Route path="/tags/:tag" component={TagDetailPage}/> <Route path="/profile" component={ProfileContainer}> <Route path="favorites" component={ProfileFavoritesPage}/> <Route path="answers" component={ProfileAnswersPage}/> </Route> </Route> </Router> } </Provider>, document.getElementById('root'));
src/app/management/Users/index.js
omrilitov/react-universal
import React from 'react'; import {connect} from 'react-redux'; import {asyncConnect} from 'redux-connect'; import * as users from './redux'; import Users from './Users'; import {Card} from 'material-ui'; const card = { backgroundColor: 'white' }; @asyncConnect([{ promise: ({store: {dispatch}}) => dispatch(users.load()) }]) @connect(state => state.management.users, users) export default class UsersContainer extends React.Component { render () { return ( <Card style={card}> {this.props.error && <div>{this.props.error.message}</div>} {this.props.loading && <div>{'Loading'}</div>} {this.props.loaded && <Users users={this.props.users} />} </Card> ); } }
app/components/D3Map/index.js
impact-learning/frontend-demo
/** * * D3Map * */ import React from 'react'; import { Map, TileLayer, } from 'react-leaflet'; import topojson from 'topojson'; import styles from './styles.css'; import MapOverlay from './map-overlay'; import { toD3Path } from './utils'; /* eslint-disable react/prefer-stateless-function */ class D3Map extends React.Component { // componentWillReceiveProps(nextProps) { // const { map } // if (nextProps.boundsForZoom !== this.props.boundsForZoom) { // // } // } render() { const { center, zoom, maxZoom, borderData, impactData, onViewreset, bounds, boundsForZoom, height, onClickCircle, } = this.props; // const countriesBorders = topojson.feature(CountryTopoData, CountryTopoData.objects.countries); const provincesGeo = topojson.feature(borderData, borderData.objects.states_chn); return ( <div className={styles.map} > <Map zoom={zoom} center={center} className={styles.map} style={{ height, }} > <TileLayer attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' maxZoom={maxZoom} url="http://{s}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png" /> <MapOverlay provincesGeo={provincesGeo} onViewreset={onViewreset} bounds={bounds} impactData={impactData} boundsForZoom={boundsForZoom} onClickCircle={onClickCircle} /> </Map> </div> ); } } D3Map.propTypes = { center: React.PropTypes.array, height: React.PropTypes.number, boundsForZoom: React.PropTypes.array, maxZoom: React.PropTypes.number, zoom: React.PropTypes.number, borderData: React.PropTypes.object, impactData: React.PropTypes.array, projectCoordinates: React.PropTypes.object, bounds: React.PropTypes.array, onViewreset: React.PropTypes.func, onClickCircle: React.PropTypes.func, }; export { toD3Path }; export default D3Map;
examples/js/selection/all-select.js
rolandsusans/react-bootstrap-table
/* eslint max-len: 0 */ /* eslint no-alert: 0 */ /* eslint guard-for-in: 0 */ /* eslint no-console: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(50); export default class SelectAllOnAllPage extends React.Component { onSelectAll = (isSelected) => { if (isSelected) { return products.map(row => row.id); } else { return []; } } render() { const selectRowProp = { mode: 'checkbox', clickToSelect: true, onSelectAll: this.onSelectAll }; return ( <BootstrapTable ref='table' data={ products } selectRow={ selectRowProp } pagination> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
src/assets/js/react/router/coreFontRouter.js
blueliquiddesigns/gravity-forms-pdf-extended
import React from 'react' import PropTypes from 'prop-types' import { HashRouter as Router, Route, Switch } from 'react-router-dom' import CoreFontContainer from '../components/CoreFonts/CoreFontContainer' /** * @package Gravity PDF * @copyright Copyright (c) 2020, Blue Liquid Designs * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License * @since 5.0 */ /** * Contains the React Router Routes for our Core Font downloader. * We are using hashHistory instead of browserHistory so as not to affect the backend * * Routes include: * * /downloadCoreFonts * /retryDownloadCoreFonts * * @param button DOM Node containing the original static <button> markup (gets replaced by React) * * @since 5.0 */ const Routes = ({ button }) => ( <Router> <Switch> <Route render={(props) => <CoreFont history={props.history} button={button} />} /> <Route path='/downloadCoreFonts' exact render={(props) => <CoreFont history={props.history} button={button} />} /> <Route path='/retryDownloadCoreFonts' exact render={(props) => <CoreFont history={props.history} button={button} />} /> </Switch> </Router> ) /** * @since 5.0 */ Routes.propTypes = { history: PropTypes.object, button: PropTypes.object } /** * Because we used the same component multiple times above, the real component was abstracted * * @param history HashHistory object * @param button DOM Node * * @since 5.0 */ const CoreFont = ({ history, button }) => ( <CoreFontContainer history={history} location={history.location} buttonClassName={button.className} buttonText={button.innerText} success={GFPDF.coreFontSuccess} error={GFPDF.coreFontError} itemPending={GFPDF.coreFontItemPendingMessage} itemSuccess={GFPDF.coreFontItemSuccessMessage} itemError={GFPDF.coreFontItemErrorMessage} counterText={GFPDF.coreFontCounter} retryText={GFPDF.coreFontRetry} /> ) /** * @since 5.0 */ CoreFont.propTypes = { history: PropTypes.object, button: PropTypes.object } export default Routes
app/javascript/mastodon/features/compose/containers/warning_container.js
tri-star/mastodon
import React from 'react'; import { connect } from 'react-redux'; import Warning from '../components/warning'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { me } from '../../../initial_state'; const buildHashtagRE = () => { try { const HASHTAG_SEPARATORS = '_\\u00b7\\u200c'; const ALPHA = '\\p{L}\\p{M}'; const WORD = '\\p{L}\\p{M}\\p{N}\\p{Pc}'; return new RegExp( '(?:^|[^\\/\\)\\w])#((' + '[' + WORD + '_]' + '[' + WORD + HASHTAG_SEPARATORS + ']*' + '[' + ALPHA + HASHTAG_SEPARATORS + ']' + '[' + WORD + HASHTAG_SEPARATORS +']*' + '[' + WORD + '_]' + ')|(' + '[' + WORD + '_]*' + '[' + ALPHA + ']' + '[' + WORD + '_]*' + '))', 'iu', ); } catch { return /(?:^|[^\/\)\w])#(\w*[a-zA-Z·]\w*)/i; } }; const APPROX_HASHTAG_RE = buildHashtagRE(); const mapStateToProps = state => ({ needsLockWarning: state.getIn(['compose', 'privacy']) === 'private' && !state.getIn(['accounts', me, 'locked']), hashtagWarning: state.getIn(['compose', 'privacy']) !== 'public' && APPROX_HASHTAG_RE.test(state.getIn(['compose', 'text'])), directMessageWarning: state.getIn(['compose', 'privacy']) === 'direct', }); const WarningWrapper = ({ needsLockWarning, hashtagWarning, directMessageWarning }) => { if (needsLockWarning) { return <Warning message={<FormattedMessage id='compose_form.lock_disclaimer' defaultMessage='Your account is not {locked}. Anyone can follow you to view your follower-only posts.' values={{ locked: <a href='/settings/profile'><FormattedMessage id='compose_form.lock_disclaimer.lock' defaultMessage='locked' /></a> }} />} />; } if (hashtagWarning) { return <Warning message={<FormattedMessage id='compose_form.hashtag_warning' defaultMessage="This toot won't be listed under any hashtag as it is unlisted. Only public toots can be searched by hashtag." />} />; } if (directMessageWarning) { const message = ( <span> <FormattedMessage id='compose_form.direct_message_warning' defaultMessage='This toot will only be sent to all the mentioned users.' /> <a href='/terms' target='_blank'><FormattedMessage id='compose_form.direct_message_warning_learn_more' defaultMessage='Learn more' /></a> </span> ); return <Warning message={message} />; } return null; }; WarningWrapper.propTypes = { needsLockWarning: PropTypes.bool, hashtagWarning: PropTypes.bool, directMessageWarning: PropTypes.bool, }; export default connect(mapStateToProps)(WarningWrapper);
js/components/footer/badgeFooter.js
bengaara/simbapp
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { actions } from 'react-native-navigation-redux-helpers'; import { Container, Header, Title, Content, Button, Footer, FooterTab, Text, Body, Left, Right, Icon } from 'native-base'; import { Actions } from 'react-native-router-flux'; import styles from './styles'; const { popRoute, } = actions; class BadgeFooter extends Component { static propTypes = { popRoute: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } constructor(props) { super(props); this.state = { tab1: false, tab2: false, tab3: true, tab4: false, }; } toggleTab1() { this.setState({ tab1: true, tab2: false, tab3: false, tab4: false, }); } toggleTab2() { this.setState({ tab1: false, tab2: true, tab3: false, tab4: false, }); } toggleTab3() { this.setState({ tab1: false, tab2: false, tab3: true, tab4: false, }); } toggleTab4() { this.setState({ tab1: false, tab2: false, tab3: false, tab4: true, }); } popRoute() { this.props.popRoute(this.props.navigation.key); } render() { return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={() => Actions.pop()}> <Icon name="arrow-back" /> </Button> </Left> <Body> <Title>Footer</Title> </Body> <Right /> </Header> <Content padder /> <Footer> <FooterTab> <Button active={this.state.tab1} onPress={() => this.toggleTab1()} badgeValue={2} badgeValueStyle={{ color: '#FFF' }}> <Icon active={this.state.tab1} name="apps" /> <Text>Apps</Text> </Button> <Button active={this.state.tab2} onPress={() => this.toggleTab2()} > <Icon active={this.state.tab2} name="camera" /> <Text>Camera</Text> </Button> <Button active={this.state.tab3} onPress={() => this.toggleTab3()} badgeValue={51} badgeColor="blue"> <Icon active={this.state.tab3} name="compass" /> <Text>Compass</Text> </Button> <Button active={this.state.tab4} onPress={() => this.toggleTab4()} > <Icon active={this.state.tab4} name="contact" /> <Text>Contact</Text> </Button> </FooterTab> </Footer> </Container> ); } } function bindAction(dispatch) { return { popRoute: key => dispatch(popRoute(key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(BadgeFooter);
docs/app/Examples/modules/Dimmer/States/DimmerExampleActive.js
vageeshb/Semantic-UI-React
import React from 'react' import { Dimmer, Segment } from 'semantic-ui-react' const DimmerExampleActive = () => ( <Segment> <Dimmer active /> <p> <img src='http://semantic-ui.com/images/wireframe/short-paragraph.png' /> </p> <p> <img src='http://semantic-ui.com/images/wireframe/short-paragraph.png' /> </p> </Segment> ) export default DimmerExampleActive
fixtures/nesting/src/modern/index.js
cpojer/react
import React from 'react'; import {StrictMode} from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import App from './App'; import {store} from '../store'; ReactDOM.render( <StrictMode> <Provider store={store}> <App /> </Provider> </StrictMode>, document.getElementById('root') );
my-app/src/App.js
sThig/jabbascrypt
import React, { Component } from 'react'; import './App.css'; import Nav from './components/scaffold/nav'; import Content from './components/scaffold/content'; import { Route } from 'react-router-dom'; import Projects from './components/pages/projects.js'; import About from './components/pages/about'; import Blog from './components/pages/blog'; import Contact from './components/pages/contact'; import Footer from './components/scaffold/footer'; import Galaxy from '../src/components/pages/projectpages/stars/galaxy.js'; import StarDates from '../src/components/pages/projectpages/dates/stardates.js'; import FearAnger from '../src/components/pages/projectpages/state/fearanger'; import Counting from '../src/components/pages/projectpages/counter/counting'; import SortableSimple from '../src/components/pages/projectpages/dnd2/index'; import SWCrawler from '../src/components/pages/projectpages/crawler/index'; import Switch from '../src/components/pages/projectpages/onoff/index'; import Quotes from '../src/components/pages/projectpages/quotes/index'; import Desks from '../src/components/pages/projectpages/desks/index'; import Wookieeyears from '../src/components/pages/projectpages/wookieeyears/index'; import ArrayExercise from '../src/components/pages/projectpages/arrayexercise/index'; import ArrayExercise2 from '../src/components/pages/projectpages/arrayexercise2/index'; class App extends Component { constructor(props) { super(props); this.state = { navClass: 'navClear', lastScrollPos: 0 }; this.handleScroll = this.handleScroll.bind(this); } componentDidMount() { window.addEventListener('scroll', this.handleScroll); } componentWillUnmount() { window.removeEventListener('scroll', this.handleScroll); } handleScroll(event) { if (this.state.lastScrollPos > event.currentTarget.scrollY) { this.setState({ navClass: 'navClear', lastScrollPos: event.currentTarget.scrollY }); } else if (this.state.lastScrollPos < event.currentTarget.scrollY) { this.setState({ navClass: 'navBlack', lastScrollPos: event.currentTarget.scrollY }); } } render() { return ( <div className="App"> <Nav style={{ zIndex: 10000 }} navClass={this.state.navClass} /> <Route path="/welcome" component={Content} /> <Route path="/home" component={Content} /> <Route path="/projects" component={Projects} /> <Route path="/about" component={About} /> <Route path="/blog" component={Blog} /> <Route path="/contact" component={Contact} /> <Route path="/projectpages/stars/galaxy" component={Galaxy} /> <Route path="/projectpages/dates/stardates" component={StarDates} /> <Route path="/projectpages/state/fearanger" component={FearAnger} /> <Route path="/projectpages/counter/counting" component={Counting} /> <Route path="/projectpages/dnd2/index" component={SortableSimple} /> <Route path="/projectpages/crawler/index" component={SWCrawler} /> <Route path="/projectpages/onoff/index" component={Switch} /> <Route path="/projectpages/quotes/index" component={Quotes} /> <Route path="/projectpages/desks/index" component={Desks} /> <Route path="/projectpages/wookieeyears/index" component={Wookieeyears} /> <Route path="/projectpages/arrayexercise/index" component={ArrayExercise} /> <Route path="/projectpages/arrayexercise2/index" component={ArrayExercise2} /> <Footer style={{ zIndex: 10000 }} /> </div> ); } } export default App;
front-end/src/components/header.js
aravindio/readable
import React from 'react' import { Link } from 'react-router-dom' import { Navbar, Nav, NavItem } from 'react-bootstrap' import { LinkContainer } from 'react-router-bootstrap' const Header = ({ categories }) => { return ( <div className='app'> <Navbar inverse collapseOnSelect> <Navbar.Header> <Navbar.Brand> <Link to='/'>Readable</Link> </Navbar.Brand> {categories && <Navbar.Toggle />} </Navbar.Header> {categories && ( <Navbar.Collapse> <Nav pullRight> {categories.map(c => ( <LinkContainer exact key={c.path} to={`/${c.path}`}> <NavItem>{c.name}</NavItem> </LinkContainer> ))} </Nav> </Navbar.Collapse> )} </Navbar> </div> ) } export default Header
app/src/js/main.js
a3itj/react-setup
"use strict"; import React from 'react'; import {render} from 'react-dom'; import { Router } from 'react-router'; import routes from './routes'; console.log(routes) render(<Router>{routes}</Router>,document.getElementById('app'))
addons/themes/forty/includes/Footer.js
rendact/rendact
import React from 'react'; class Footer extends React.Component { render(){ return ( <footer id="footer"> <div className="inner"> <ul className="copyright"> <li>Forty based theme</li> <li>html5up</li> <li>converted by Rendact Team</li> </ul> </div> </footer> ) } } export default Footer;
app/containers/LanguageProvider/index.js
adoveil/max
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { IntlProvider } from 'react-intl'; import { selectLocale } from './selectors'; export class LanguageProvider extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}> {React.Children.only(this.props.children)} </IntlProvider> ); } } LanguageProvider.propTypes = { locale: React.PropTypes.string, messages: React.PropTypes.object, children: React.PropTypes.element.isRequired, }; const mapStateToProps = createSelector( selectLocale(), (locale) => ({ locale }) ); export default connect(mapStateToProps)(LanguageProvider);
docs/src/pages/layout/grid/SpacingGrid.js
dsslimshaddy/material-ui
// @flow weak import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import Grid from 'material-ui/Grid'; import { FormLabel, FormControlLabel } from 'material-ui/Form'; import Radio, { RadioGroup } from 'material-ui/Radio'; import Paper from 'material-ui/Paper'; const styles = theme => ({ root: { flexGrow: 1, }, paper: { height: 140, width: 100, }, control: { padding: theme.spacing.unit * 2, }, }); class GuttersGrid extends Component { state = { spacing: '16', }; handleChange = key => (event, value) => { this.setState({ [key]: value, }); }; render() { const classes = this.props.classes; const { spacing } = this.state; return ( <Grid container className={classes.root}> <Grid item xs={12}> <Grid container className={classes.demo} justify="center" spacing={Number(spacing)}> {[0, 1, 2].map(value => <Grid key={value} item> <Paper className={classes.paper} /> </Grid>, )} </Grid> </Grid> <Grid item xs={12}> <Paper className={classes.control}> <Grid container> <Grid item> <FormLabel>spacing</FormLabel> <RadioGroup name="spacing" aria-label="spacing" selectedValue={spacing} onChange={this.handleChange('spacing')} row > <FormControlLabel value="0" control={<Radio />} label="0" /> <FormControlLabel value="8" control={<Radio />} label="8" /> <FormControlLabel value="16" control={<Radio />} label="16" /> <FormControlLabel value="24" control={<Radio />} label="24" /> <FormControlLabel value="40" control={<Radio />} label="40" /> </RadioGroup> </Grid> </Grid> </Paper> </Grid> </Grid> ); } } GuttersGrid.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(GuttersGrid);
Tests/Components/RoundedButtonTest.js
tk1cntt/KanjiMaster
// https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md import test from 'ava' import React from 'react' import RoundedButton from '../../App/Components/RoundedButton' import { shallow } from 'enzyme' test('component exists', t => { const wrapper = shallow(<RoundedButton onPress={() => {}} text='hi' />) t.is(wrapper.length, 1) // exists }) test('component structure', t => { const wrapper = shallow(<RoundedButton onPress={() => {}} text='hi' />) t.is(wrapper.name(), 'TouchableOpacity') // the right root component t.is(wrapper.children().length, 1) // has 1 child t.is(wrapper.children().first().name(), 'Text') // that child is Text }) test('onPress', t => { let i = 0 // i guess i could have used sinon here too... less is more i guess const onPress = () => i++ const wrapper = shallow(<RoundedButton onPress={onPress} text='hi' />) t.is(wrapper.prop('onPress'), onPress) // uses the right handler t.is(i, 0) wrapper.simulate('press') t.is(i, 1) }) test('renders children text when passed', t => { const wrapper = shallow(<RoundedButton onPress={() => {}}>Howdy</RoundedButton>) t.is(wrapper.children().length, 1) // has 1 child t.is(wrapper.children().first().name(), 'Text') // that child is Text })
src/components/nav/header.js
ChrisRast/Le-Taguenet
import React from 'react'; import * as ui from 'semantic-ui-react'; export default function Header (props) { return ( <ui.Header textAlign="center" className="space-bottom" > <ui.Header.Content as="h1" size="huge" className="ui text" > Le Taguenet </ui.Header.Content> <ui.Header.Subheader> Le Taguenet est un texte lacunaire à remplir en utilisant les villes et villages de Suisse romande.<br />Adapté d'un texte lacunaire sur les communes vaudoises, cette version se veut plus généraliste. </ui.Header.Subheader> </ui.Header> ); }
src/pages/authorizing.js
guzmonne/mcp
import React from 'react' import Rx from 'rx-dom' import RowColXS12 from '../components/bootstrap/row.col-xs-12.js' import Hypnotize from '../components/helpers/hypnotize.js' import Loading from '../components/helpers/loading.js' import Social from '../components/helpers/social_icons.helper.js' class Authorizing extends React.Component { constructor(){ super() } componentWillMount(){ // TODO } render(){ const provider = this.props.provider || this.props.location.query.provider return ( <div className="Authorizing"> <h3 style={{opacity: 0.5}}>Autorizando</h3> <Loading> <Social icon={provider} type="eclipse" /> </Loading> </div> ) } } export default Authorizing
app/containers/HomePage/index.js
kdavidmoore/react-redux-kata
/* * 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 { Link } from 'react-router'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <div style={{ padding: '20px' }}> <h1> <FormattedMessage {...messages.header} /> </h1> <Link to="user">Manage Users</Link> </div> ); } }
Docker/KlusterKiteMonitoring/klusterkite-web/src/components/Form/submit.js
KlusterKite/KlusterKite
import React from 'react'; import { Row } from 'formsy-react-components'; import Icon from 'react-fa'; import './styles.css'; export default class Submit extends React.Component { // eslint-disable-line react/prefer-stateless-function static propTypes = { canSubmit: React.PropTypes.bool.isRequired, buttonText: React.PropTypes.string, savedText: React.PropTypes.string, saving: React.PropTypes.bool, deleting: React.PropTypes.bool, saved: React.PropTypes.bool, saveErrors: React.PropTypes.arrayOf(React.PropTypes.string), saveError: React.PropTypes.string, disabled: React.PropTypes.bool, onCancel: React.PropTypes.func, onSubmit: React.PropTypes.func, onDelete: React.PropTypes.func, }; onSubmit() { // This clutch is needed to prevent submitting on enter // Another possible hack with preventDefault on keyPress affects textareas and makes editing hard this.refs.submitButton.removeAttribute('disabled'); this.refs.submitButton.click(); this.refs.submitButton.setAttribute('disabled', true); } render() { let saveClassName = ''; if (this.props.saving) { saveClassName += ' fa-spin'; } let deleteClassName = ''; if (this.props.deleting) { deleteClassName += ' fa-spin'; } let text = 'Save'; if (this.props.buttonText) { text = this.props.buttonText; } let savedText = 'Saved'; if (this.props.savedText) { savedText = this.props.savedText; } let disabled = false; if (this.props.saving || this.props.deleting){ disabled = true; } const deleteText = 'Delete'; return ( <fieldset> <Row layout="horizontal"> {this.props.saveError && <div className="alert alert-danger" role="alert"> <span className="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> {' '} {this.props.saveError} </div> } {this.props.saveErrors && this.props.saveErrors.map((error, index) => { return ( <div className="alert alert-danger" role="alert" key={`error-${index}`}> <span className="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> {' '} {error} </div> ); }) } {this.props.saved && <div className="alert alert-success" role="alert"> <span className="glyphicon glyphicon-ok" aria-hidden="true"></span> {' '} {savedText} </div> } <button className="btn btn-primary" disabled={disabled} type={this.props.submitOnEnter ? 'submit' : 'button'} onClick={this.props.onSubmit}> <Icon name="pencil" className={saveClassName} /> {' '} {text} </button> {this.props.onCancel && <button className="btn btn-default btn-margined" type="button" onClick={this.props.onCancel}> Cancel </button> } {this.props.onDelete && <button className="btn btn-danger btn-margined" disabled={disabled} type="button" onClick={this.props.onDelete}> <Icon name="remove" className={deleteClassName}/> {' '} {deleteText} </button> } </Row> </fieldset> ); } }
step4-router/node_modules/react-router/modules/IndexLink.js
jintoppy/react-training
import React from 'react' import Link from './Link' /** * An <IndexLink> is used to link to an <IndexRoute>. */ const IndexLink = React.createClass({ render() { return <Link {...this.props} onlyActiveOnIndex={true} /> } }) export default IndexLink
src/containers/round.js
RamonSchmitt/draw-and-guess-front
import React from 'react'; import Choice from '../components/choice'; import Answer from '../components/answer'; import Timer from '../components/timer'; class Round extends React.Component { generateAnswer() { let possibleAnswers = this.props.roundChoices console.log(possibleAnswers) let picked = Math.round(Math.random()*possibleAnswers.length-1) console.log(picked) let newAnswer = this.props.roundChoices[picked].image; console.log(newAnswer) let answerValidation = this.props.roundChoices[picked].option; return ( <div style={{width: "100%", backgroundColor: "#ddd", padding: "24", margin: "0"}}> <div style={{width: "60%", margin: "0 auto"}}> <Timer/> <div> <img src = {this.props.roundChoices[picked].image}/> </div> <div> {this.props.roundChoices.map((choice) => { return <Choice key={choice._id} data={choice} validation={answerValidation} /> })} </div> </div> </div> ) } render() { return this.generateAnswer(); } } export default Round;
src/index.js
mpbill/ca.scta.admin.client
/* eslint-disable import/default */ import React from 'react'; import { render } from 'react-dom'; import { browserHistory } from 'react-router'; import { AppContainer } from 'react-hot-loader'; import Root from './components/Root'; import configureStore from './store/configureStore'; require('./favicon.ico'); // Tell webpack to load favicon.ico import './styles/styles.scss'; // Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page. import { syncHistoryWithStore } from 'react-router-redux'; const store = configureStore(); // Create an enhanced history that syncs navigation events with the store const history = syncHistoryWithStore(browserHistory, store); render( <AppContainer> <Root store={store} history={history} /> </AppContainer>, document.getElementById('app') ); if (module.hot) { module.hot.accept('./components/Root', () => { const NewRoot = require('./components/Root').default; render( <AppContainer> <NewRoot store={store} history={history} /> </AppContainer>, document.getElementById('app') ); }); }
client/src/components/BackButton/BackButton.js
silverstripe/silverstripe-asset-admin
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import droppable from 'components/GalleryItem/droppable'; import Badge from 'components/Badge/Badge'; import i18n from 'i18n'; class BackButton extends Component { render() { const { isDropping, badge, onClick } = this.props; const classList = [ 'btn', 'btn-secondary', 'btn--no-text', 'font-icon-level-up', 'btn--icon-large', 'gallery__back', ]; if (isDropping) { classList.push('z-depth-1'); classList.push('gallery__back--droppable-hover'); } const backBadge = badge ? ( <Badge className="gallery__back-badge" status={badge.status} message={badge.message} /> ) : null; const button = ( <button className={classList.join(' ')} title={i18n._t('AssetAdmin.BACK_DESCRIPTION', 'Navigate up a level')} onClick={onClick} > {backBadge} </button> ); return button; } } BackButton.propTypes = { onClick: PropTypes.func, isDropping: PropTypes.bool, badge: PropTypes.shape(Badge.propTypes), }; export { BackButton as Component }; export default droppable('GalleryItem')(BackButton);
src/components/pages/DirectorPage.js
zdizzle6717/universal-react-movie-app
'use strict'; import React from 'react'; import { Link } from 'react-router'; import NotFoundPage from '../pages/NotFoundPage'; import DirectorActions from '../../actions/DirectorActions'; import DirectorStore from '../../stores/DirectorStore'; export default class DirectorPage extends React.Component { constructor() { super(); this.state = { director: {} } this.onChange = this.onChange.bind(this); } componentWillMount() { DirectorStore.addChangeListener(this.onChange); } componentDidMount() { document.title = "Sandbox | Director"; DirectorActions.getDirector(this.props.params.directorId); } componentWillUnmount() { DirectorStore.removeChangeListener(this.onChange); } onChange() { this.setState({ director: DirectorStore.getDirector(this.props.params.directorId) }); } render() { return ( <div className="row"> <div className="small-12 columns"> <h1>ReactJs, Hapi.js & PostgreSQL</h1> <h3 className="push-bottom-2x">Dynamic Movie App: <strong>{this.state.director.firstName} {this.state.director.lastName}</strong></h3> <h5>ID: {this.state.director.id}</h5> <label><u>Bio</u></label> <p className="text-justify"> {this.state.director.bio} </p> </div> </div> ); } }
src/helpers/BibleRefSelector.js
OCMC-Translation-Projects/ioc-liturgical-react
import React from 'react'; import PropTypes from 'prop-types'; import { get } from 'lodash'; import Select from 'react-select'; import {Col, ControlLabel, Grid, Row } from 'react-bootstrap'; import MessageIcons from './MessageIcons'; class BibleRefSelector extends React.Component { constructor(props) { super(props); let citeBook = ""; let citeChapter = ""; let citeVerse = ""; if (props.book) { citeBook = props.book; citeChapter = props.chapter.substring(1,props.chapter.length); try { citeChapter = parseInt(citeChapter); } catch (err) { citeChapter = props.chapter; } citeVerse = 0; try { citeVerse = parseInt(props.verse); } catch (err) { citeVerse = props.verse; }; } let labels = props.session.labels; let labelTopics = props.session.labelTopics; this.state = { labels: { thisClass: labels[labelTopics.BibleRefSelector] , buttons: labels[labelTopics.button] , messages: labels[labelTopics.messages] , resultsTableLabels: labels[labelTopics.resultsTable] } , messageIcons: MessageIcons.getMessageIcons() , messageIcon: MessageIcons.getMessageIcons().info , message: labels[labelTopics.messages].initial , selectedBook: props.book , selectedChapter: props.chapter , selectedVerse: props.verse , selectedRef: "" , citeBook: citeBook , citeChapter: citeChapter , citeVerse: citeVerse }; this.handleBookChange = this.handleBookChange.bind(this); this.handleChapterChange = this.handleChapterChange.bind(this); this.handleVerseChange = this.handleVerseChange.bind(this); this.handleStateChange = this.handleStateChange.bind(this); this.handleCallback = this.handleCallback.bind(this); } componentWillMount = () => { }; componentDidMount = () => { // make any initial function calls here... }; componentWillReceiveProps = (nextProps) => { if (this.props.session.languageCode !== nextProps.session.languageCode) { let labels = nextProps.session.labels; let labelTopics = nextProps.session.labelTopics; this.setState((prevState, props) => { return { labels: { thisClass: labels[labelTopics.BibleRefSelector] , buttons: labels[labelTopics.button] , messages: labels[labelTopics.messages] , resultsTableLabels: labels[labelTopics.resultsTable] } , message: labels[labelTopics.messages].initial , selectedBook: get(this.state, "selectedBook", nextProps.book) , selectedChapter: get(this.state, "selectedChapter", nextProps.chapter) , selectedVerse: get(this.state, "selectedVerse", nextProps.verse) } }, function () { return this.handleStateChange("place holder")}); } }; // if we need to do something after setState, do it here... handleStateChange = (parm) => { // call a function if needed }; handleCallback = () => { this.props.callback( this.state.selectedBook , this.state.selectedChapter , this.state.selectedVerse , this.state.citeBook +" " + this.state.citeChapter + ":" + this.state.citeVerse ); }; handleBookChange = (selection) => { let book = selection["value"]; let bookLabel = selection["label"]; let citeBook = ""; try { let parts = bookLabel.split(" - "); citeBook = parts[0]; } catch (err) { citeBook = book; } this.setState({ selectedBook: book , citeBook: citeBook , selectedRef: book + "~" + this.state.selectedChapter + "~" + this.state.selectedVerse }, this.handleCallback); }; handleChapterChange = (selection) => { if (selection && selection["value"]) { let chapter = selection["value"]; let citeChapter = chapter.substring(1,chapter.length); try { citeChapter = parseInt(citeChapter); } catch (err) { citeChapter = selection["value"]; } this.setState({ selectedChapter: chapter , citeChapter: citeChapter , selectedRef: this.state.selectedBook + "~" + chapter + "~" + this.state.selectedVerse }, this.handleCallback); } }; handleVerseChange = (selection) => { if (selection && selection["value"]) { let verse = selection["value"]; let citeVerse = verse; try { citeVerse = parseInt(verse); } catch (err) { citeVerse = verse; }; this.setState({ selectedVerse: selection["value"] , citeVerse: citeVerse , selectedRef: this.state.selectedBook + "~" + this.state.selectedChapter + "~" + verse }, this.handleCallback); } }; render() { return ( <Row className="show-grid App-Bible-Ref-Selector-Row"> <Col className="App App-Bible-Ref-Selector-Label" xs={3} md={3}> <ControlLabel>Bible Ref:</ControlLabel> </Col> <Col className="App-Bible-Ref-Selector-Container" xs={2} md={2}> <Select name="App-Bible-Ref-Selector-Book" className="App-Bible-Ref-Selector-Book" value={this.state.selectedBook} options={this.props.session.dropdowns.biblicalBooksDropdown} onChange={this.handleBookChange} multi={false} autosize={true} clearable /> <Col className="App App-Bible-Ref-Selector-Label" xs={2} md={2}> </Col> <Select name="App-Bible-Ref-Selector-Chapter" className="App-Bible-Ref-Selector-Chapter" value={this.state.selectedChapter} options={this.props.session.dropdowns.biblicalChaptersDropdown} onChange={this.handleChapterChange} multi={false} autosize={true} clearable /> <Col className="App App-Bible-Ref-Selector-Label" xs={2} md={2}> </Col> <Select name="App-Bible-Ref-Selector-Verse" className="App-Bible-Ref-Selector-Verse" value={this.state.selectedVerse} options={this.props.session.dropdowns.biblicalVersesDropdown} onChange={this.handleVerseChange} multi={false} autosize={true} clearable /> </Col> <Col className="App App-Bible-Ref-Selector-Label" xs={3} md={3}> </Col> </Row> ) } } BibleRefSelector.propTypes = { session: PropTypes.object.isRequired , callback: PropTypes.func.isRequired , book: PropTypes.string , chapter: PropTypes.string , verse: PropTypes.string }; // set default values for props here BibleRefSelector.defaultProps = { book: "" , chapter: "" , verse: "" }; export default BibleRefSelector;
docs/src/sections/GlyphiconSection.js
egauci/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function GlyphiconSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="glyphicons">Glyphicons</Anchor> <small>Glyphicon</small> </h2> <p>Use them in buttons, button groups for a toolbar, navigation, or prepended form inputs.</p> <ReactPlayground codeText={Samples.Glyphicon} /> <h3><Anchor id="glyphicons-props">Props</Anchor></h3> <PropTable component="Glyphicon"/> </div> ); }
js/pages/iptt_report/components/report/reportBody.js
mercycorps/TolaActivity
import React from 'react'; import IPTTHeader from './header'; import ReportTableHeader from './tableHeader'; import ReportTableBody from './tableBody'; export default () => { return <main className="iptt_table_wrapper"> <div id="id_div_top_iptt_report"> <IPTTHeader /> <table className="table table-sm table-hover table__iptt" id="iptt_table"> <ReportTableHeader /> <ReportTableBody /> </table> </div> </main>; }
public/src/js/components/buckets/comp-linkInput.js
asarode/learn-buckets
import React from 'react'; class LinkInput extends React.Component { constructor(props) { super(props); this.state = {}; } render() { let { index, onTitleChange, onUrlChange, onTypeChange, onRemoveClick } = this.props return ( <div> <input type="text" placeholder="Link title" onChange={() => onTitleChange(index)} /> <input type="text" placeholder="http://link-to-resource" onChange={() => onUrlChange(index)}/> <select onChange={() => onTypeChange(index)}> <option value="article">Article</option> <option value="video">Video</option> <option value="source">Source Code</option> </select> <button className="lb-button-minor" type="button" onClick={() => onRemoveClick(index)}>✕ Remove</button> </div> ); } } LinkInput.PropTypes = { className: React.PropTypes.object, index: React.PropTypes.number, onTitleChange: React.PropTypes.func, onUrlChange: React.PropTypes.func, onTypeChange: React.PropTypes.func, onRemoveClick: React.PropTypes.func }; LinkInput.defaultProps = { className: {}, index: 0, onClickDelete: () => {}, onTitleChange: () => {}, onUrlChange: () => {}, onTypeChange: () => {}, onRemoveClick: () => {} }; export default LinkInput;
src/containers/About/index.js
korabh/quran.com-frontend
import React from 'react'; import IndexHeader from 'components/IndexHeader'; import Helmet from 'react-helmet'; export default () => ( <div> <Helmet title="About Quran.com" /> <IndexHeader noSearch /> <div className="about-text container-fluid"> <div className="row"> <div className="col-md-8 col-md-offset-2"> <h4 className="source-sans"> The Noble Qur&apos;an is the central religious text of Islam. Muslims believe the Qur’an is the book of Divine guidance and direction for mankind, and consider the original Arabic text the final revelation of Allah (God).[<a href="en.wikipedia.org/wiki/Quran">1</a>] All translations of the original Arabic text are thus interpretations of the original meanings and should be embraced as such. For more information about the Noble Qur&apos;an, you may visit its <a href="https://en.wikipedia.org/wiki/Quran">Wikipedia article.</a> </h4> </div> </div> <div className="row"> <div className="col-md-8 col-md-offset-2"> <h3>MECCAN SURAHS</h3> <h4 className="source-sans"> The Meccan Surahs are the chronologically earlier chapters (Surahs) of the Qur&apos;an that were, according to Islamic tradition, revealed anytime before the migration of the Islamic prophet Muhammed and his followers from Mecca to Medina (Hijra). The Medinan Surahs are those revelations that occurred after the move to the city of that name. </h4> </div> </div> <div className="row"> <div className="col-md-8 col-md-offset-2"> <h3>MEDINAN SURAHS</h3> <h4 className="source-sans"> The Medinan Surahs or Medinan Chapters of the Qur&apos;an are the latest 24 Surahs that, according to Islamic tradition, were revealed at Medina after Muhammad&apos;s Hijra from Mecca. These Surahs were revealed by Allah when the Muslim community was larger and more developed, as opposed to their minority position in Mecca. </h4> </div> </div> <div className="row"> <div className="col-md-8 col-md-offset-2"> <h3>BROWSING SURAHS ON THIS WEBSITE</h3> <h4 className="source-sans"> We have redesigned the website with a user friendly approach in mind. To browse through the Surahs, click on the button (shown left) in the READ & LISTEN page and navigate Surah by title or by page. In future iterations, we will be integrating more search and audio features, ان شاء الله. If you have any suggestions on how we can make the website a better experience please do not hesitate to <a href="https://quran.zendesk.com/hc/en-us">contact us</a>. </h4> </div> </div> <div className="row credits"> <div className="col-md-8 col-md-offset-2"> <h3><strong>CREDITS</strong></h3> <h4> This website was created by a few volunteers and was made possible with the will of Allah (Glory be unto Him) and with the help of the open source Muslim community online. Data sources include <a href="http://www.tanzil.info">Tanzil</a>, <a href="http://www.qurancomplex.com"> Qur&apos;anComplex</a>, <a href="https://github.com/cpfair/quran-align"> Colin Fair&apos;s work on audio segments</a>, <a href="http://www.zekr.org"> Zekr</a> and <a href="http://www.al-quran.info"> Online Qur&apos;an Project</a>. Special thanks to the <a href="http://elmohafez.com"> Elmohafez team</a> for word by word timing files. If you have any questions, you may visit the <a href="/contact">Contact</a> page. </h4> </div> </div> </div> </div> );
client/containers/NavigationContainer.js
horiaradu/twitter-challenge
import React from 'react'; import {connect} from 'react-redux'; import Navigation from '../components/Navigation'; import * as actionCreators from '../actions'; export default connect( mapStateToProps, actionCreators )(Navigation); function mapStateToProps(state) { return { isAuthenticated: state.getIn(['auth', 'isAuthenticated'], false), email: state.getIn(['auth', 'email']) }; }
packages/icons/src/md/av/SurroundSound.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdSurroundSound(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M40 8c2.21 0 4 1.79 4 4v24c0 2.21-1.79 4-4 4H8c-2.21 0-4-1.79-4-4V12c0-2.21 1.79-4 4-4h32zM15.51 32.49A11.978 11.978 0 0 1 12 24c0-3.07 1.18-6.15 3.52-8.48l-2.83-2.83A15.947 15.947 0 0 0 8 24c0 4.1 1.57 8.19 4.68 11.32l2.83-2.83zM24 32c4.42 0 8-3.58 8-8s-3.58-8-8-8-8 3.58-8 8 3.58 8 8 8zm11.31 3.31C38.43 32.19 40 28.1 40 24c0-4.1-1.57-8.19-4.68-11.32l-2.83 2.83A12.02 12.02 0 0 1 36 24c0 3.07-1.17 6.15-3.52 8.48l2.83 2.83zM24 20c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z" /> </IconBase> ); } export default MdSurroundSound;
lib/manager/components/version/VersionRetrievalBadge.js
conveyal/datatools-manager
// @flow import Icon from '@conveyal/woonerf/components/icon' import React from 'react' import toSentenceCase from '../../../common/util/to-sentence-case' import type { FeedVersion, RetrievalMethod } from '../../../types' type Props = { retrievalMethod?: RetrievalMethod, version?: FeedVersion } const iconForRetrievalMethod = (retrievalMethod: RetrievalMethod | 'UNKNOWN') => { switch (retrievalMethod) { case 'SERVICE_PERIOD_MERGE': return 'code-fork' case 'REGIONAL_MERGE': return 'globe' case 'PRODUCED_IN_HOUSE': case 'PRODUCED_IN_HOUSE_GTFS_PLUS': return 'pencil' case 'MANUALLY_UPLOADED': return 'upload' case 'FETCHED_AUTOMATICALLY': return 'cloud-download' case 'VERSION_CLONE': return 'clone' default: return 'file-archive-o' } } export default function VersionRetrievalBadge (props: Props) { const { retrievalMethod, version } = props const method = retrievalMethod || (version && version.retrievalMethod) || 'UNKNOWN' return ( <Icon title={toSentenceCase(method.replace(/_/g, ' '))} type={iconForRetrievalMethod(method)} /> ) }
src/components/modal/Mask.js
quark-ui/quark-ui
/** * Mask Component * @author ryan.bian */ import React from 'react'; import PropTypes from 'prop-types'; import styles from './Modal.css'; const Mask = ({ visible, children }) => ( <div className={styles[`mask${visible ? '--visible' : ''}`]}> {children} </div> ); Mask.defaultProps = { visible: false, }; Mask.propTypes = { visible: PropTypes.bool, }; export default Mask;
src/App.js
css459/personal-website
import React from 'react'; import Resume from "./components/resume"; import Research from "./components/research"; import Web from "./components/web"; import IOS from "./components/ios"; import UNIX from "./components/unix"; import HomeDecoration from "./components/homeDecoration"; import Stackoverflow from "./resources/stackoverflow.png"; import LinkedIn from "./resources/linkedin.png"; import Github from "./resources/github.png"; import './App.css'; class App extends React.Component { constructor(props) { super(props); this.state = { presenting: "" }; this.makeButtons = this.makeButtons.bind(this); this.presentPage = this.presentPage.bind(this); } makeButtons(labels) { let buttons = []; for (let i of labels) { buttons.push( <button key={i} className="Button" onClick={() => { this.presentPage(i) }} > {i} </button> ); } return buttons; } presentPage(label) { switch (label) { case "Resume": this.setState({ presenting: <Resume dismissCallback={() => this.presentPage("")}/> }); break; case "Research": this.setState({ presenting: <Research dismissCallback={() => this.presentPage("")}/> }); break; case "iOS": this.setState({ presenting: <IOS dismissCallback={() => this.presentPage("")}/> }); break; case "Web": this.setState({ presenting: <Web dismissCallback={() => this.presentPage("")}/> }); break; case "UNIX": this.setState({ presenting: <UNIX dismissCallback={() => this.presentPage("")}/> }); break; case "Off Topic": break; default: this.setState({presenting: ""}); } } // noinspection JSMethodCanBeStatic render() { let homeView = ( <div className="Home"> <HomeDecoration width={window.innerHeight * 0.3} height={window.innerHeight * 0.3} /> <div className="AppHeader"> Cole Smith</div> <div className="Divider"/> <div className="AppSubHeader">Development and Design</div> <div className="DividerSmall"/> <div className="Nav"> {this.makeButtons(["Resume", "Research", "iOS", "Web", "UNIX", "Off Topic"])} </div> <br/> <div className="SocialLinks"> <a href="https://github.com/css459"> <img className="Link" src={Github} alt="Go to my GitHub"/> </a> <a href="https://stackoverflow.com/users/4487982/cole"> <img className="Link" src={Stackoverflow} alt="Go to my Stackoverflow"/> </a> <a href="https://www.linkedin.com/in/cole-smith-b666b5100/"> <img className="Link" src={LinkedIn} alt="Go to my LinkedIn"/> </a> </div> <div className="BuiltWith"> <a href="https://github.com/css459/personal-website"> View Source </a> </div> </div> ); let pageView = ( <div className="PageWrapper"> {this.state.presenting} </div> ); return ( <div className="App"> {this.state.presenting ? pageView : homeView} </div> ); } } export default App;
static/js/index.js
deVinnnie/SDO_Live
import React from 'react'; import ReactDOM from 'react-dom'; import {Main} from './Main'; import {Spinner} from './Spinner'; window.onload = function () { launchFullScreen(document.documentElement); //Request Full Screen. Normally requires user interaction. Use Firefox and alter config so that: //full-screen-api.allow-trusted-requests-only = false //See: http://stackoverflow.com/questions/9454125/javascript-request-fullscreen-is-unreliable let spinner = new Spinner(); ReactDOM.render( <Main spinner={spinner}/>, document.getElementById('root') ); } // From: http://davidwalsh.name/fullscreen // Find the right method, call on correct element function launchFullScreen(element) { if(element.requestFullScreen) { element.requestFullScreen(); } else if(element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if(element.webkitRequestFullScreen) { element.webkitRequestFullScreen(); } }
node_modules/react-bootstrap/es/Checkbox.js
okristian1/react-info
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import warning from 'warning'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { inline: React.PropTypes.bool, disabled: React.PropTypes.bool, /** * Only valid if `inline` is not set. */ validationState: React.PropTypes.oneOf(['success', 'warning', 'error', null]), /** * Attaches a ref to the `<input>` element. Only functions can be used here. * * ```js * <Checkbox inputRef={ref => { this.input = ref; }} /> * ``` */ inputRef: React.PropTypes.func }; var defaultProps = { inline: false, disabled: false }; var Checkbox = function (_React$Component) { _inherits(Checkbox, _React$Component); function Checkbox() { _classCallCheck(this, Checkbox); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Checkbox.prototype.render = function render() { var _props = this.props, inline = _props.inline, disabled = _props.disabled, validationState = _props.validationState, inputRef = _props.inputRef, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['inline', 'disabled', 'validationState', 'inputRef', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var input = React.createElement('input', _extends({}, elementProps, { ref: inputRef, type: 'checkbox', disabled: disabled })); if (inline) { var _classes2; var _classes = (_classes2 = {}, _classes2[prefix(bsProps, 'inline')] = true, _classes2.disabled = disabled, _classes2); // Use a warning here instead of in propTypes to get better-looking // generated documentation. process.env.NODE_ENV !== 'production' ? warning(!validationState, '`validationState` is ignored on `<Checkbox inline>`. To display ' + 'validation state on an inline checkbox, set `validationState` on a ' + 'parent `<FormGroup>` or other element instead.') : void 0; return React.createElement( 'label', { className: classNames(className, _classes), style: style }, input, children ); } var classes = _extends({}, getClassSet(bsProps), { disabled: disabled }); if (validationState) { classes['has-' + validationState] = true; } return React.createElement( 'div', { className: classNames(className, classes), style: style }, React.createElement( 'label', null, input, children ) ); }; return Checkbox; }(React.Component); Checkbox.propTypes = propTypes; Checkbox.defaultProps = defaultProps; export default bsClass('checkbox', Checkbox);
src/encoded/static/components/viz/ChartDetailCursor/CursorViewBounds.js
hms-dbmi/fourfront
'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; import _ from 'underscore'; import * as vizUtil from '@hms-dbmi-bgm/shared-portal-components/es/components/viz/utilities'; import { console, isServerSide, layout, analytics, WindowEventDelegator } from '@hms-dbmi-bgm/shared-portal-components/es/components/util'; import { barplot_color_cycler } from './../ColorCycler'; import ChartDetailCursor from './ChartDetailCursor'; /** * Use this Component to wrap a chart or other view which displays any sort of Experiment Set 'Node'(s). * A "Node" here implies an object with properties: 'field', 'term', 'experiment_sets', 'experiments', and 'files'. * Optionally may have a 'parent' node also, and any other metada. * * This components adjusts child Component to pass down props: * {function} onNodeMouseEnter(node, evt) * {function} onNodeMouseLeave(node, evt) * {function} onNodeClick(node, evt) * {string} selectedTerm * {string} selectedParentTerm * {string} hoverTerm * {string} hoverParentTerm * * The added prop callback functions should be used in the view whenever a "Node" element is hovered over or clicked on, * to pass node to them for the popover display. * * Added prop strings should be used alongside CursorViewBounds.isSelected or similar to determine to highlight a node element that is selected, or something. * * @export * @class CursorViewBounds * @extends {React.Component} */ export default class CursorViewBounds extends React.PureComponent { /** * Check if 'node' is currently selected. * * @public * @param {Object} node - A 'node' containing at least 'field', 'term', and 'parent' if applicable. * @param {string} selectedTerm - Currently selected subdivision field term. * @param {string} selectedParentTerm - Currently selected X-Axis field term. * @returns {boolean} True if node (and node.parent, if applicable) matches selectedTerm & selectedParentTerm. */ static isSelected(node, selectedTerm, selectedParentTerm){ if ( node.term === selectedTerm && ( ((node.parent && node.parent.term) || null) === (selectedParentTerm || null) ) ) return true; return false; } static defaultProps = { 'cursorContainerMargin' : 100, 'highlightTerm' : false, // Return an object with 'x', 'y'. 'clickCoordsFxn' : function(node, containerPosition, boundsHeight, isOnRightSide){ return { x : containerPosition.left, y : containerPosition.top + boundsHeight, }; } }; constructor(props){ super(props); this.componentDidUpdate = this.componentDidUpdate.bind(this); this.updateDetailCursorFromNode = this.updateDetailCursorFromNode.bind(this); this.handleMouseMoveToUnsticky = this.handleMouseMoveToUnsticky.bind(this); this.handleClickAnywhere = this.handleClickAnywhere.bind(this); this.onNodeMouseEnter = this.onNodeMouseEnter.bind(this); this.onNodeMouseLeave = this.onNodeMouseLeave.bind(this); this.onNodeClick = this.onNodeClick.bind(this); this.state = { 'selectedParentTerm' : null, 'selectedTerm' : null, 'hoverTerm' : null, 'hoverParentTerm' : null }; this.boundsContainerRef = React.createRef(); this.cursorRef = React.createRef(); } /** * Important lifecycle method. * Checks if a selected bar section (via state.selectedTerm) has been set or unset. * Then passes that to the ChartDetailCursor's 'sticky' state. * * Also enables or disables a 'click' event listener to cancel out stickiness/selected section. * * @param {Object} pastProps - Previous props of this component. * @param {Object} pastState - Previous state of this component. */ componentDidUpdate(pastProps, pastState){ if (pastProps.href !== this.props.href){ this.cursorRef.current.reset(true); } else if (pastState.selectedTerm !== this.state.selectedTerm){ // If we now have a selected bar section, enable click listener. // Otherwise, disable it. // And set ChartDetailCursor to be 'stickied'. This is the only place where the ChartDetailCursor state should be updated. if (typeof this.state.selectedTerm === 'string'){ this.cursorRef.current.update({ 'sticky' : true }); setTimeout(()=>{ WindowEventDelegator.addHandler('click', this.handleClickAnywhere); WindowEventDelegator.addHandler('mousemove', this.handleMouseMoveToUnsticky); }, 100); } else { WindowEventDelegator.removeHandler('click', this.handleClickAnywhere); WindowEventDelegator.removeHandler('mousemove', this.handleMouseMoveToUnsticky); if (!this.state.hoverTerm){ this.cursorRef.current.reset(true); } else { this.cursorRef.current.update({ 'sticky' : false }); } } } } updateDetailCursorFromNode(node, overrideSticky = false){ const { actions = null, aggregateType } = this.props; const newCursorDetailState = { 'path' : [], 'includeTitleDescendentPrefix' : false, actions }; if (node.parent) newCursorDetailState.path.push(node.parent); if (typeof aggregateType === 'string') { newCursorDetailState.primaryCount = aggregateType; } newCursorDetailState.path.push(node); this.cursorRef.current.update(newCursorDetailState, null, overrideSticky); } handleMouseMoveToUnsticky(evt){ const container = this.boundsContainerRef && this.boundsContainerRef.current; const { cursorContainerMargin } = this.props; if (container){ var containerOffset = layout.getElementOffset(container), marginTop = (cursorContainerMargin && cursorContainerMargin.top) || cursorContainerMargin || 0, marginBottom = (cursorContainerMargin && cursorContainerMargin.bottom) || marginTop || 0, marginLeft = (cursorContainerMargin && cursorContainerMargin.left) || marginTop || 0, marginRight = (cursorContainerMargin && cursorContainerMargin.right) || marginLeft || 0; if ( (evt.pageY || evt.clientY) < containerOffset.top - marginTop || (evt.pageY || evt.clientY) > containerOffset.top + container.clientHeight + marginBottom || (evt.pageX || evt.clientX) < containerOffset.left - marginLeft || (evt.pageX || evt.clientX) > containerOffset.left + container.clientWidth + marginRight ){ this.setState({ 'selectedParentTerm' : null, 'selectedTerm' : null }); return true; } return false; } else { return false; } } handleClickAnywhere(evt){ // Don't do anything if clicked on DetailCursor. UNLESS it's a button. if ( //evt.target.className && //evt.target.className.split(' ').indexOf('btn') === -1 && ChartDetailCursor.isTargetDetailCursor(evt.target) ){ return false; } this.setState({ 'selectedParentTerm' : null, 'selectedTerm' : null }); } onNodeMouseEnter(node, evt){ const { selectedTerm, selectedParentTerm } = this.state; // Cancel if same node as selected. if (CursorViewBounds.isSelected(node, selectedTerm, selectedParentTerm)){ return false; } if (selectedTerm === null){ this.updateDetailCursorFromNode(node, false); } const newOwnState = {}; // Update hover state _.extend(newOwnState, { 'hoverTerm' : node.term || null, 'hoverParentTerm' : (node.parent && node.parent.term) || null, }); if (_.keys(newOwnState).length > 0){ this.setState(newOwnState); } if (this.props.highlightTerm && typeof vizUtil.highlightTerm === 'function') vizUtil.highlightTerm(node.field, node.term, node.color || barplot_color_cycler.colorForNode(node)); } onNodeMouseLeave(node, evt){ // Update hover state this.setState({ 'hoverTerm' : null, 'hoverParentTerm' : null }); if (!evt || !ChartDetailCursor.isTargetDetailCursor(evt.relatedTarget)){ this.cursorRef.current.reset(false); } } onNodeClick(node, evt){ const { selectedTerm, selectedParentTerm } = this.state; evt.preventDefault(); evt.stopPropagation(); // Prevent this event from being captured by this.handleClickAnywhere() listener. // If this section already selected: if (CursorViewBounds.isSelected(node, selectedTerm, selectedParentTerm)){ this.setState({ 'selectedTerm' : null, 'selectedParentTerm' : null }); } else { const { context, styleOptions, windowWidth, clickCoordsFxn, eventCategory } = this.props; // Manually adjust popover position if a different bar section is already selected. if (selectedTerm) { const container = this.boundsContainerRef && this.boundsContainerRef.current; const containerPos = layout.getElementOffset(container); let containerWidth; //var mouseXInContainer = (evt.pageX || evt.clientX) - containerPos.left; // Try to use window width. if (!isServerSide() && typeof windowWidth === 'number'){ containerWidth = windowWidth; } else { containerWidth = container.clientWidth; } const isPopoverOnRightSide = (evt.pageX || evt.clientX) > (containerWidth / 2); const coords = clickCoordsFxn(node, containerPos, container.clientHeight, isPopoverOnRightSide); // Manually update popover coords then update its contents this.cursorRef.current.setCoords( _.extend({ 'onRightSide' : isPopoverOnRightSide }, coords), this.updateDetailCursorFromNode.bind(this, node, true) ); } // Set new selected bar part. this.setState({ 'selectedTerm' : node.term || null, 'selectedParentTerm' : (node.parent && node.parent.term) || null }, function(){ // Track 'BarPlot':'Change Experiment Set Filters':ExpSetFilters event. setTimeout(()=>{ analytics.event(eventCategory || 'CursorViewBounds', 'Select Node', { eventLabel : analytics.eventLabelFromChartNode(node), currentFilters : analytics.getStringifiedCurrentFilters(context && context.filters) }); }, 10); }); } return false; } render(){ const { children, ...passProps } = this.props; return ( <div className="popover-bounds-container" ref={this.boundsContainerRef} style={_.pick(this.props, 'width', 'height')}> { React.cloneElement(children, _.extend( passProps, _.pick(this.state, 'selectedTerm', 'selectedParentTerm', 'hoverTerm', 'hoverParentTerm'), _.pick(this, 'onNodeMouseEnter', 'onNodeMouseLeave', 'onNodeClick') )) } <ChartDetailCursor {..._.pick(this.props, 'windowWidth', 'windowHeight', 'href', 'schemas')} ref={this.cursorRef} /> </div> ); } }
src/svg-icons/social/notifications.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialNotifications = (props) => ( <SvgIcon {...props}> <path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"/> </SvgIcon> ); SocialNotifications = pure(SocialNotifications); SocialNotifications.displayName = 'SocialNotifications'; SocialNotifications.muiName = 'SvgIcon'; export default SocialNotifications;
src/svg-icons/action/info-outline.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionInfoOutline = (props) => ( <SvgIcon {...props}> <path d="M11 17h2v-6h-2v6zm1-15C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zM11 9h2V7h-2v2z"/> </SvgIcon> ); ActionInfoOutline = pure(ActionInfoOutline); ActionInfoOutline.displayName = 'ActionInfoOutline'; ActionInfoOutline.muiName = 'SvgIcon'; export default ActionInfoOutline;
src/js/components/icons/base/Code.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-code`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'code'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M9,22 L15,2 M17,17 L22,12 L17,7 M7,17 L2,12 L7,7"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Code'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/results/ResultListWrapper.react.js
codeforamerica/citybook
import React, { Component } from 'react'; import LoadingSpinner from '../LoadingSpinner.react.js'; import Grid from 'react-bootstrap/lib/Grid'; import ResultsList from './ResultsList.react.js'; import ResultFilters from './ResultFilters.react.js'; import '../../styles/loading-spinner.scss'; import '../../styles/styles.scss'; export default class ResultListWrapper extends Component { constructor(){ super(); this.state = { } } render(){ return( <Grid> <ResultFilters loaded={this.props.loaded} filterOptions={this.props.filterOptions} setFilters={this.props.setFilters} /> <ResultsList loaded={this.props.loaded} results={this.props.results}/> </Grid> ) } }
examples/src/components/UsersField.js
urvashi01/react-select
import GravatarOption from './CustomOption'; import GravatarValue from './CustomSingleValue'; import React from 'react'; import Select from 'react-select'; const USERS = require('../data/users'); var UsersField = React.createClass({ propTypes: { hint: React.PropTypes.string, label: React.PropTypes.string, }, renderHint () { if (!this.props.hint) return null; return ( <div className="hint">{this.props.hint}</div> ); }, render () { return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select onOptionLabelClick={this.onLabelClick} placeholder="Select user" optionComponent={GravatarOption} singleValueComponent={GravatarValue} options={USERS.users}/> {this.renderHint()} </div> ); } }); module.exports = UsersField;
fields/types/text/TextFilter.js
xyzteam2016/keystone
import React from 'react'; import { findDOMNode } from 'react-dom'; import { FormField, FormInput, FormSelect, SegmentedControl } from 'elemental'; const INVERTED_OPTIONS = [ { label: 'Matches', value: false }, { label: 'Does NOT Match', value: true }, ]; const MODE_OPTIONS = [ { label: 'Contains', value: 'contains' }, { label: 'Exactly', value: 'exactly' }, { label: 'Begins with', value: 'beginsWith' }, { label: 'Ends with', value: 'endsWith' }, ]; function getDefaultValue () { return { mode: MODE_OPTIONS[0].value, inverted: INVERTED_OPTIONS[0].value, value: '', }; } var TextFilter = React.createClass({ propTypes: { filter: React.PropTypes.shape({ mode: React.PropTypes.oneOf(MODE_OPTIONS.map(i => i.value)), inverted: React.PropTypes.boolean, value: React.PropTypes.string, }), }, statics: { getDefaultValue: getDefaultValue, }, getDefaultProps () { return { filter: getDefaultValue(), }; }, updateFilter (value) { this.props.onChange({ ...this.props.filter, ...value }); }, selectMode (mode) { this.updateFilter({ mode }); findDOMNode(this.refs.focusTarget).focus(); }, toggleInverted (inverted) { this.updateFilter({ inverted }); findDOMNode(this.refs.focusTarget).focus(); }, updateValue (e) { this.updateFilter({ value: e.target.value }); }, render () { const { field, filter } = this.props; const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0]; const placeholder = field.label + ' ' + mode.label.toLowerCase() + '...'; return ( <div> <FormField> <SegmentedControl equalWidthSegments options={INVERTED_OPTIONS} value={filter.inverted} onChange={this.toggleInverted} /> </FormField> <FormSelect options={MODE_OPTIONS} onChange={this.selectMode} value={mode.value} /> <FormField> <FormInput autoFocus ref="focusTarget" value={this.props.filter.value} onChange={this.updateValue} placeholder={placeholder} /> </FormField> </div> ); }, }); module.exports = TextFilter;
src/shared/views/plans/plans/PlansList/PlansList.js
in-depth/indepth-demo
import React from 'react' import { PlanLink } from '../index' import styles from './plansList.css' const PlansList = (props) => { return ( <div className={styles.main}> <div className={styles.pageHeader}> <h1>PLAN</h1> </div> <h2 className={styles.subHeader}>Pick a plan below to get a custom itinerary.</h2> <div className={styles.gridWrapper}> <div className={styles.grid}> {props.plans.map((plan) => ( <div key={plan.title} className={styles.planWrapper}> <PlanLink image={plan.backgroundUrl} subtitle={plan.subtitle} title={plan.title} backgroundUrl={plan.backgroundUrl} path={plan.path} /> </div> ))} </div> </div> </div> ) } PlansList.propTypes = { plans: React.PropTypes.array.isRequired, } export default PlansList
src/svg-icons/av/mic-off.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvMicOff = (props) => ( <SvgIcon {...props}> <path d="M19 11h-1.7c0 .74-.16 1.43-.43 2.05l1.23 1.23c.56-.98.9-2.09.9-3.28zm-4.02.17c0-.06.02-.11.02-.17V5c0-1.66-1.34-3-3-3S9 3.34 9 5v.18l5.98 5.99zM4.27 3L3 4.27l6.01 6.01V11c0 1.66 1.33 3 2.99 3 .22 0 .44-.03.65-.08l1.66 1.66c-.71.33-1.5.52-2.31.52-2.76 0-5.3-2.1-5.3-5.1H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c.91-.13 1.77-.45 2.54-.9L19.73 21 21 19.73 4.27 3z"/> </SvgIcon> ); AvMicOff = pure(AvMicOff); AvMicOff.displayName = 'AvMicOff'; AvMicOff.muiName = 'SvgIcon'; export default AvMicOff;
admin/client/components/ItemsTable/ItemsTableCell.js
tony2cssc/keystone
import React from 'react'; var ItemsTableCell = React.createClass({ displayName: 'ItemsTableCell', propTypes: { className: React.PropTypes.string, }, getDefaultProps () { return { className: '', }; }, render () { const className = `ItemList__col ${this.props.className}`; return ( <td {...this.props} className={className} /> ); }, }); module.exports = ItemsTableCell;
resources/apps/frontend/src/pages/services/index.js
johndavedecano/PHPLaravelGymManagementSystem
import React from 'react'; import Loadable from 'components/Loadable'; import {PrivateLayout} from 'components/Layouts'; import renderRoutes from './../routes'; export default { exact: false, auth: true, path: '/services', component: ({routes}) => { return <PrivateLayout>{renderRoutes(routes)}</PrivateLayout>; }, routes: [ { exact: true, auth: true, path: '/services', component: Loadable({ loader: () => import('./lists'), }), }, { exact: true, auth: true, path: '/services/create', component: Loadable({ loader: () => import('./create'), }), }, { exact: true, auth: true, path: '/services/:id', component: Loadable({ loader: () => import('./show'), }), }, { exact: true, auth: true, path: '/services/:id/edit', component: Loadable({ loader: () => import('./edit'), }), }, ], };
src/components/NotFoundPage.js
Opelvectra/hello.react.redux
import React from 'react'; import { Link } from 'react-router'; const NotFoundPage = () => { return ( <div> <h4> 404 Page Not Found </h4> <Link to="/"> Go back to homepage </Link> </div> ); }; export default NotFoundPage;