path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
src/svg-icons/device/signal-wifi-off.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalWifiOff = (props) => (
<SvgIcon {...props}>
<path d="M23.64 7c-.45-.34-4.93-4-11.64-4-1.5 0-2.89.19-4.15.48L18.18 13.8 23.64 7zm-6.6 8.22L3.27 1.44 2 2.72l2.05 2.06C1.91 5.76.59 6.82.36 7l11.63 14.49.01.01.01-.01 3.9-4.86 3.32 3.32 1.27-1.27-3.46-3.46z"/>
</SvgIcon>
);
DeviceSignalWifiOff = pure(DeviceSignalWifiOff);
DeviceSignalWifiOff.displayName = 'DeviceSignalWifiOff';
DeviceSignalWifiOff.muiName = 'SvgIcon';
export default DeviceSignalWifiOff;
|
src/client/react/user/components/dashboards/PostRaceDashboard.js | bwyap/ptc-amazing-g-race | import React from 'react';
import { Route } from 'react-router-dom';
import { connect } from 'react-redux';
import { Switch, Redirect } from 'react-router-dom';
import Base from '../Base';
import PostRaceMenu from '../menus/PostRaceMenu';
import TeamDashboard from '../../views/TeamDashboard';
import Feed from '../../views/Feed';
import NotFound from '../../views/NotFound';
const mapStateToProps = (state, ownProps) => {
return {
authenticated: state.auth.login.authenticated
}
}
@connect(mapStateToProps)
class Dashboard extends React.Component {
render() {
if (!this.props.authenticated) {
return <Redirect to={{
pathname: '/login',
state: { next: '/dashboard' }
}}/>;
}
const { url } = this.props.match;
return (
<div className='pt-dark'>
<Base/>
<PostRaceMenu/>
<Switch>
<Route exact path={`${url}`}>
<TeamDashboard hideChallenges/>
</Route>
<Route exact path={`${url}/feed`} component={Feed}/>
<Route component={NotFound}/>
</Switch>
</div>
);
}
}
export default Dashboard;
|
app/App.js | singun/kanban-app | import React from 'react';
import ReactDOM, { render } from 'react-dom';
import { Router, Route } from 'react-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import KanbanBoardContainer from './KanbanBoardContainer';
import KanbanBoard from './KanbanBoard';
import EditCard from './EditCard';
import NewCard from './NewCard';
let cards = [
{
id: 1,
title: "Read the Book",
description: "I should read the **whole** book",
color: '#BD8D31',
status: "in-progress",
tasks: []
},
{
id: 2,
title: "Write some code",
description: "Code along with the samples in the book. The complete source can be found at [github](https://github.com/pro-react)",
color: '#3A7E28',
status: "to do",
tasks: [
{
id: 1,
name: "ContactList Example",
done: true
},
{
id: 2,
name: "Kanban Example",
done: false
},
{
id: 3,
name: "My own experiments",
done: false
}
]
}
]
// ReactDOM.render(<KanbanBoard cards={cards} />, document.getElementById('root'));
// ReactDOM.render(<KanbanBoardContainer />, document.getElementById('root'));
render((
<Router history={createBrowserHistory()}>
<Route component={KanbanBoardContainer}>
<Route path="/" component={KanbanBoard}>
<Route path="new" component={NewCard} />
<Route path="edit/:card_id" component={EditCard} />
</Route>
</Route>
</Router>
), document.getElementById('root'));
|
app/views/listing/add.js | jtparrett/countcals | import React from 'react'
import { StyleSheet, View, TextInput, Button } from 'react-native'
import Moment from 'moment'
import Input from '../../components/input'
export default class AddEntry extends React.Component {
constructor(props) {
super(props)
this.state = {
...props,
timestamp: props.currentDate.unix(),
name: '',
calories: ''
}
}
submit = () => {
this.state.API.post('foods/add', this.state).then((response) => {
this.state.onNewEntry(response.data)
this.setState({
name: '',
calories: ''
})
this.state.closeEvent()
})
}
render() {
return (
<View style={ styles.container }>
<Input value={ this.state.name } onChangeText={(value) => {
this.setState({
name: value
})
}} placeholder="Food name" />
<Input value={ this.state.calories } onChangeText={(value) => {
this.setState({
calories: value
})
}} placeholder="Calories" keyboardType="numeric" />
<Button title="Submit" onPress={ this.submit }></Button>
<Button title="Cancel" onPress={ this.state.closeEvent }></Button>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
margin: 20
}
}) |
src/parser/hunter/shared/modules/talents/BindingShot.js | FaideWW/WoWAnalyzer | import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import TalentStatisticBox from 'interface/others/TalentStatisticBox';
import React from 'react';
/**
* Fires a magical projectile, tethering the enemy and any other enemies within 5 yards for 10 sec, rooting them in place for 5 sec if they move more than 5 yards from the arrow.
*/
class BindingShot extends Analyzer {
_roots = 0;
_applications = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.BINDING_SHOT_TALENT.id);
}
on_byPlayer_applydebuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.BINDING_SHOT_ROOT.id && spellId !== SPELLS.BINDING_SHOT_TETHER.id) {
return;
}
if (spellId === SPELLS.BINDING_SHOT_ROOT.id) {
this._roots += 1;
}
if (spellId === SPELLS.BINDING_SHOT_TETHER.id) {
this._applications += 1;
}
}
statistic() {
return (
<TalentStatisticBox
talent={SPELLS.BINDING_SHOT_TALENT.id}
value={`${this._roots} roots / ${this._applications} possible`}
/>
);
}
}
export default BindingShot;
|
examples/huge-apps/routes/Course/routes/Announcements/components/Sidebar.js | fanhc019/react-router | import React from 'react';
import { Link } from 'react-router';
export default class AnnouncementsSidebar extends React.Component {
render () {
var announcements = COURSES[this.props.params.courseId].announcements;
return (
<div>
<h3>Sidebar Assignments</h3>
<ul>
{announcements.map(announcement => (
<li key={announcement.id}>
<Link to={`/course/${this.props.params.courseId}/announcements/${announcement.id}`}>
{announcement.title}
</Link>
</li>
))}
</ul>
</div>
);
}
}
|
frontend/src/screens/qa/qa.js | linea-it/qlf | import React, { Component } from 'react';
import Steps from './widgets/steps/steps';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
const styles = {
container: {
display: 'flex',
justifyContent: 'space-around',
flexDirection: 'column',
marginBottom: '1vh',
flex: 1,
},
green: {
display: 'inline-block',
verticalAlign: 'top',
width: '10px',
height: '10px',
borderRadius: '50%',
border: 'solid 1px #333',
background: '#008000',
fontSize: 0,
textIndent: '-9999em',
},
yellow: {
display: 'inline-block',
verticalAlign: 'top',
width: '10px',
height: '10px',
borderRadius: '50%',
border: 'solid 1px #333',
background: '#ffff00',
fontSize: 0,
textIndent: '-9999em',
},
red: {
display: 'inline-block',
verticalAlign: 'top',
width: '10px',
height: '10px',
borderRadius: '50%',
border: 'solid 1px #333',
background: '#ff0000',
fontSize: 0,
textIndent: '-9999em',
},
lightgray: {
display: 'inline-block',
verticalAlign: 'top',
width: '10px',
height: '10px',
borderRadius: '50%',
border: 'solid 1px #333',
background: '#d3d3d3',
fontSize: 0,
textIndent: '-9999em',
},
black: {
display: 'inline-block',
verticalAlign: 'top',
width: '10px',
height: '10px',
borderRadius: '50%',
border: 'solid 1px #333',
background: '#000000',
fontSize: 0,
textIndent: '-9999em',
},
};
class QA extends Component {
static propTypes = {
exposureId: PropTypes.string,
qaTests: PropTypes.array,
arms: PropTypes.array.isRequired,
spectrographs: PropTypes.array.isRequired,
mjd: PropTypes.string,
date: PropTypes.string,
time: PropTypes.string,
navigateToMetrics: PropTypes.func,
navigateToProcessingHistory: PropTypes.func,
petalSizeFactor: PropTypes.number.isRequired,
processId: PropTypes.number,
monitor: PropTypes.bool,
flavor: PropTypes.string,
};
componentDidMount() {
document.title = 'QA';
}
renderMetrics = (step, spectrographNumber, arm) => {
if (this.props.navigateToMetrics) {
this.props.navigateToMetrics(
step,
spectrographNumber,
arm,
this.props.exposureId
);
}
};
renderSteps = () => {
return (
<Steps
navigateToProcessingHistory={this.props.navigateToProcessingHistory}
qaTests={this.props.qaTests}
renderMetrics={this.renderMetrics}
mjd={this.props.mjd}
exposureId={this.props.exposureId}
date={this.props.date}
time={this.props.time}
petalSizeFactor={this.props.petalSizeFactor}
processId={this.props.processId}
monitor={this.props.monitor}
flavor={this.props.flavor}
/>
);
};
render() {
return <div style={styles.container}>{this.renderSteps()}</div>;
}
}
export default withStyles(styles)(QA);
|
CalcScreen.js | stevenpan91/ChemicalEngineerHelper | 'use strict'
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Button,
TouchableHighlight,
TouchableOpacity,
TextInput,
Navigator
} from 'react-native';
class CalcScreen extends Component {
render() {
return (
<Navigator
renderScene={this.renderScene.bind(this)}
navigator={this.props.navigator}
navigationBar={
<Navigator.NavigationBar style={{backgroundColor: '#246dd5'}}
routeMapper={NavigationBarRouteMapper} />
} />
);
}
renderScene(route, navigator) {
return (
<View style={{flex: 1}}>
<TextInput style={{textAlign: 'left', marginTop: 100}}>Input Test</TextInput>
<Text style={{textAlign: 'left', marginTop:200}}>Result</Text>
</View>
);
}
// gotoMain() {
// this.props.navigator.push({
// id: 'MainScreen',
// sceneConfig: Navigator.SceneConfigs.FloatFromBottom,
// });
// }
}
var NavigationBarRouteMapper = {
LeftButton(route, navigator, index, nextState) {
return (
<TouchableOpacity style={{flex: 1, justifyContent: 'center'}}
onPress={() => navigator.parentNavigator.pop()}>
<Text style={{color: 'white', margin: 10,}}>
Back
</Text>
</TouchableOpacity>
);
},
RightButton(route, navigator, index, nextState) {
return (
<TouchableOpacity style={{flex: 1, justifyContent: 'center'}}
onPress={() => navigator.parentNavigator.push({id: 'unknown'})}>
<Text style={{color: 'white', margin: 10,}}>
Test
</Text>
</TouchableOpacity>
);
},
Title(route, navigator, index, nextState) {
return (
<TouchableOpacity style={{flex: 1, justifyContent: 'center'}}
onPress={() => navigator.push({
id: 'MainScreen',
sceneConfig: Navigator.SceneConfigs.FloatFromBottom,
})}>
<Text style={{color: 'white', margin: 10, fontSize: 16}}>
Main Page
</Text>
</TouchableOpacity>
);
}
};
module.exports = CalcScreen; |
webapp/imports/ui/layouts/SecurityDialog.js | clinical-meteor/meteor-on-fhir | // base layout
import { CardHeader, CardText, CardTitle } from 'material-ui/Card';
import PropTypes from 'prop-types';
import { ReactMeteorData } from 'meteor/react-meteor-data';
import ReactMixin from 'react-mixin';
import React, { Component } from 'react';
import FlatButton from 'material-ui/FlatButton';
import { Session } from 'meteor/session';
import Dialog from 'material-ui/Dialog';
import { Container, Col, Row } from 'react-bootstrap';
import { get, has } from 'lodash';
import Interweave from 'interweave';
Session.setDefault('securityDialogOpen', false);
Session.setDefault('securityDialogResourceType', '');
Session.setDefault('securityDialogResourceId', '');
Session.setDefault('securityDialogResourceJson', null);
Session.setDefault('securityDialogDisplayRawJson', false);
export class SecurityDialog extends React.Component {
constructor(props) {
super(props);
}
getMeteorData() {
let data = {
securityDialog: {
open: Session.get('securityDialogOpen'),
resourceType: Session.get('securityDialogResourceType'),
resourceId: Session.get('securityDialogResourceId'),
resourceJsonRaw: Session.get('securityDialogResourceJson'),
resourceJson: JSON.stringify(Session.get('securityDialogResourceJson'), null, 2)
},
fields: {
mongoId: '',
id: '',
narrative: '',
versionId: '',
lastUpdated: '',
sourceUrl: '',
securityTags: [],
extensions: [],
tags: [],
profiles: []
},
displayRawJson: Session.get('securityDialogDisplayRawJson')
};
if(get(data, 'securityDialog.resourceJsonRaw.text.div')){
data.fields.narrative = get(data, 'securityDialog.resourceJsonRaw.text.div');
}
if(get(data, 'securityDialog.resourceJsonRaw.meta.versionId')){
data.fields.versionId = get(data, 'securityDialog.resourceJsonRaw.meta.versionId');
}
if(get(data, 'securityDialog.resourceJsonRaw.meta.lastUpdated')){
data.fields.lastUpdated = get(data, 'securityDialog.resourceJsonRaw.meta.lastUpdated');
}
if(get(data, 'securityDialog.resourceJsonRaw.meta.source')){
data.fields.sourceUrl = get(data, 'securityDialog.resourceJsonRaw.meta.source');
}
if(get(data, 'securityDialog.resourceJsonRaw.id')){
data.fields.id = get(data, 'securityDialog.resourceJsonRaw.id');
}
if(get(data, 'securityDialog.resourceJsonRaw._id')){
data.fields.mongoId = get(data, 'securityDialog.resourceJsonRaw._id');
}
if(get(data, 'securityDialog.resourceJsonRaw.extension')){
data.securityDialog.resourceJsonRaw.extension.forEach(function(extension){
//let parts = extension.url.split("/");
data.fields.extensions.push(extension.url.split("/")[extension.url.split("/").length - 1])
})
}
if(get(data, 'securityDialog.resourceJsonRaw.meta.security')){
data.securityDialog.resourceJsonRaw.meta.security.forEach(function(securityTag){
data.fields.securityTags.push(get(securityTag, 'display'))
})
}
if(get(data, 'securityDialog.resourceJsonRaw.meta.tag')){
data.securityDialog.resourceJsonRaw.meta.tag.forEach(function(tag){
data.fields.tags.push(get(tag, 'text'))
})
}
if(get(data, 'securityDialog.resourceJsonRaw.meta.profile')){
data.securityDialog.resourceJsonRaw.meta.profile.forEach(function(profile){
data.fields.profiles.push(get(profile, 'url'))
})
}
// console.log("SecurityDialog[data]", data);
return data;
}
handleCloseSecurityDialog(){
Session.set('securityDialogOpen', false);
}
toggleRawDataDisplay(){
Session.toggle('securityDialogDisplayRawJson');
}
handleTextareaUpdate(){
}
render(){
let securityTagChips = [];
this.data.fields.securityTags.forEach(function(tag, index){
securityTagChips.push(<div key={index}>
{tag}
</div>)
});
let profileChips = [];
this.data.fields.profiles.forEach(function(tag, index){
profileChips.push(<div key={index}>
<a href={tag} target="_blank">{tag}</a>
</div>)
});
let extensionChips = [];
this.data.fields.extensions.forEach(function(tag, index){
extensionChips.push(<div key={index}>
{tag}
</div>)
});
let tagChips = [];
this.data.fields.tags.forEach(function(extension, index){
tagChips.push(<div key={index}>
{extension}
</div>)
});
let dialogContent;
let toggleButtonText = "Show Raw Data"
if(get(this, 'data.displayRawJson')){
toggleButtonText = "Show Metadata Summary"
dialogContent = <CardText style={{overflowY: "auto", marginTop: '60px'}}>
<textarea
id='securityDialogJson'
onChange= { this.handleTextareaUpdate }
value={get(this, 'data.securityDialog.resourceJson') }
style={{width: '100%', position: 'relative', minHeight: '200px', height: '400px', backgroundColor: '#f5f5f5', borderColor: '#ccc', borderRadius: '4px', lineHeight: '16px'}}
/>
</CardText>
} else {
let dialogSectionStyle = {
minHeight: '80px'
}
dialogContent = <CardText style={{overflowY: "auto", marginTop: '60px'}}>
{/* <div style={dialogSectionStyle}>
<Row>
<Col md={4}>
<h4>Source Id</h4>
{get(this, 'data.fields.id')}
</Col>
<Col md={4}>
<h4>Version</h4>
{get(this, 'data.fields.versionId')}
</Col>
<Col md={4}>
<h4>Last Updated</h4>
{get(this, 'data.fields.lastUpdated')}
</Col>
</Row>
</div> */}
<div style={dialogSectionStyle}>
<h4>Narrative</h4>
<pre>
<Interweave
content={get(this, 'data.fields.narrative')}
// matchers={[new UrlMatcher('url'), new HashtagMatcher('hashtag')]}
/>
<br />
</pre>
</div>
<Row>
<Col md={6}>
<div style={dialogSectionStyle}>
<h4>Version: </h4>
{get(this, 'data.fields.versionId')}
</div>
<div style={dialogSectionStyle}>
<h4>Last Updated</h4>
{get(this, 'data.fields.lastUpdated')}
</div>
<div style={dialogSectionStyle}>
<h4>Source</h4>
{get(this, 'data.fields.sourceUrl')}
</div>
<div style={dialogSectionStyle}>
<h4>Source ID</h4>
{get(this, 'data.fields.id')}
</div>
</Col>
<Col md={6}>
<div style={dialogSectionStyle}>
<h4>Extentions</h4>
{extensionChips}
</div>
<div style={dialogSectionStyle}>
<h4>Profile</h4>
{profileChips}
</div>
<div style={dialogSectionStyle}>
<h4>Security Tags</h4>
{securityTagChips}
</div>
<div style={dialogSectionStyle}>
<h4>Tags</h4>
{tagChips}
</div>
</Col>
</Row>
</CardText>
}
const securityActions = [
<FlatButton
label={toggleButtonText}
primary={true}
onClick={this.toggleRawDataDisplay}
style={{float: 'left'}}
/>,
<FlatButton
label="Close"
primary={true}
keyboardFocused={true}
onClick={this.handleCloseSecurityDialog}
/>
];
let cardTitle = "Resource Metadata";
return (
<Dialog
actions={securityActions}
modal={false}
open={this.data.securityDialog.open}
onRequestClose={this.handleCloseSecurityDialog}
style={{minHeight: '560px'}}
>
<Row id='metaDataHeader' style={{height: '80px', position: 'absolute', width: '100%'}}>
<CardTitle
title="Metadata"
/>
<CardTitle
title={get(this, 'data.fields.mongoId')}
style={{right: '10px', position: 'absolute', top: '0px'}}
className="barcode"
/>
</Row>
{ dialogContent }
</Dialog>
);
}
}
ReactMixin(SecurityDialog.prototype, ReactMeteorData);
export default SecurityDialog; |
src/svg-icons/action/history.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionHistory = (props) => (
<SvgIcon {...props}>
<path d="M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"/>
</SvgIcon>
);
ActionHistory = pure(ActionHistory);
ActionHistory.displayName = 'ActionHistory';
ActionHistory.muiName = 'SvgIcon';
export default ActionHistory;
|
node_modules/react-bootstrap/es/ModalBody.js | newphew92/newphew92.github.io | 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 { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var ModalBody = function (_React$Component) {
_inherits(ModalBody, _React$Component);
function ModalBody() {
_classCallCheck(this, ModalBody);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
ModalBody.prototype.render = function render() {
var _props = this.props;
var className = _props.className;
var props = _objectWithoutProperties(_props, ['className']);
var _splitBsProps = splitBsProps(props);
var bsProps = _splitBsProps[0];
var elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement('div', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return ModalBody;
}(React.Component);
export default bsClass('modal-body', ModalBody); |
example/src/TabOne.js | PlexChat/mobx-navigation | import React from 'react';
import {
Button,
Text,
TextInput,
StyleSheet,
View
} from 'react-native';
import { inject, observer } from 'mobx-react';
import { scene } from '../..';
import Circular from './Circular';
const styles = StyleSheet.create({
test: {
backgroundColor: 'green',
},
});
@scene('Tab1') @inject('testStore') @observer
export class Tab1 extends React.Component {
static navConfig = {
tabAffinity: '1',
tabBarVisible: true,
navBarVisible: true,
cardStyle: styles.test,
templates: ['test'],
};
onPress = () => {
this.props.navState.push('Tab1Scene1');
};
onPress2 = () => {
this.props.navState.push('Tab1Scene1Alt');
};
onPress3 = () => {
this.props.navState.push('Tab2Scene1', { custom: ' there' });
};
onPress4 = () => {
this.props.navState.push('Circular');
}
onPress5 = () => {
this.props.navState.reset();
}
render() {
return (
<View style={{ flex: 1 }}>
<Button title={'scene 1'} onPress={this.onPress} style={{ backgroundColor: 'white' }} />
<Button title={'scene 1 alt'} onPress={this.onPress2} style={{ backgroundColor: 'white' }} />
<Button title={'Tab 2 scene 1'} onPress={this.onPress3} style={{ backgroundColor: 'white' }} />
<Button title={'Circular'} onPress={this.onPress4} />
<Button title={'reset'} onPress={this.onPress5} />
<Text style={{ color: 'white' }} >
{this.props.testStore.data}
</Text>
</View>
);
}
}
@scene
class Tab1Scene1 extends React.Component {
static navConfig = {
custom: {
myCustomConfig: 'custom config',
},
navBarCenter: (props) => {
return (
<View>
<Text>
{'Common config'}
</Text>
</View>
);
}
};
static multiNavConfig = {
Tab1Scene1: {
tabAffinity: '1',
tabBarVisible: true,
navBarVisible: true,
},
Tab1Scene1Alt: {
tabAffinity: '1',
tabBarVisible: true,
navBarVisible: true,
navBarLeftDisabled: true,
navBarStyle: {
backgroundColor: 'red',
}
}
}
render() {
return (
<View style={{ flex: 1, backgroundColor: 'green' }}>
<Text>
{this.props.navState.frontCustomConfig.myCustomConfig}
</Text>
<TextInput style={{ height: 40, borderColor: 'blue', borderWidth: 1 }} value="Test tab bar visibility" />
<Button title="Tab1Scene2" onPress={() => this.props.navState.push('Tab1Scene2')} />
</View>
);
}
}
@scene('Tab1Scene2')
export class Tab1Scene2 extends React.Component {
static navConfig = {
tabAffinity: '1',
tabBarVisible: true,
navBarVisible: true,
};
render() {
return (
<View style={{ flex: 1 }}>
<Text>
Tab 1 scene 2
</Text>
<Button title="Tab1Scene3" onPress={() => this.props.navState.push('Tab1Scene3')} />
</View>
)
}
}
@scene('Tab1Scene3')
class Tab1Scene3 extends React.Component {
static navConfig = {
tabAffinity: '1',
tabBarVisible: true,
navBarVisible: true,
};
render() {
return (
<View style={{ flex: 1 }}>
<Text>
Tab 1 scene 3
</Text>
<Button title="Pop to scene 1" onPress={() => this.props.navState.popTo('Tab1Scene1')} />
<Button title="Pop three times" onPress={() => this.props.navState.pop(3)} />
</View>
);
}
}
export const CircularChild = (props) => {
return (
<View>
<Text>
{props.message}
</Text>
</View>
)
}
|
packages/watif-display/src/components/interactive-description.js | jwillesen/watif | import React from 'react'
import {string, element, func, arrayOf} from 'prop-types'
import Watext from './watext'
import VerbBar from './verb-bar'
import {verbShape} from '../property-shapes'
import './interactive-description.css'
export default class InteractiveDescription extends React.Component {
static propTypes = {
title: string,
emptyText: string,
watext: element,
verbs: arrayOf(verbShape),
onItemClick: func, // (item-id)
onVerbClick: func, // (item-id, verb-id)
}
static defaultProps = {
emptyText: 'No text',
}
watext() {
if (this.props.watext) {
return (
<div>
<Watext watext={this.props.watext} onItemClick={this.props.onItemClick} />
</div>
)
}
return <div styleName="no-text">{this.props.emptyText}</div>
}
render() {
return (
<div styleName="root">
<h2 styleName="heading">{this.props.title}</h2>
<div styleName="content">
{this.watext()}
<div styleName="verbs">
<VerbBar verbs={this.props.verbs} onVerbClick={this.props.onVerbClick} />
</div>
</div>
</div>
)
}
}
|
app/routes/index.js | vasanthk/redux-blog-example | import React from 'react';
import { Route } from 'react-router';
import App from './App';
import SignupRoute from './SignupRoute';
import LoginRoute from './LoginRoute';
import ProfileRoute from './ProfileRoute';
import NotFound from '../components/NotFound';
import redirectBackAfter from '../utils/redirectBackAfter';
import fillStore from '../utils/fillStore';
import DashboardRoute from './DashboardRoute';
import * as Posts from './Posts';
const routes = (
<Route component={App}>
<Route path="/signup" component={SignupRoute} />
<Route path="/login" component={LoginRoute} />
<Route path="/" component={Posts.List} />
<Route path="/posts/:id" component={Posts.View} />
<Route requireAuth>
<Route path="/profile" component={ProfileRoute} />
<Route path="/dashboard" component={DashboardRoute} />
<Route path="/dashboard/add" component={Posts.Edit} />
<Route path="/dashboard/edit/:id" component={Posts.Edit} />
</Route>
<Route path="*" component={NotFound} />
</Route>
);
function walk(routes, cb) {
cb(routes);
if (routes.childRoutes) {
routes.childRoutes.forEach(route => walk(route, cb));
}
return routes;
}
export default (store, client) => {
return walk(Route.createRouteFromReactElement(routes), route => {
route.onEnter = (nextState, transition) => {
const loggedIn = !!store.getState().auth.token;
if (route.requireAuth && !loggedIn) {
transition.to(...redirectBackAfter('/login', nextState));
} else if (client) {
fillStore(store, nextState, [route.component]);
}
};
});
};
|
node_modules/react-router/es6/IndexRoute.js | Win-Myint/ReactChallenge2 | import React from 'react';
import warning from './routerWarning';
import invariant from 'invariant';
import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils';
import { component, components, falsy } from './InternalPropTypes';
var func = React.PropTypes.func;
/**
* An <IndexRoute> is used to specify its parent's <Route indexRoute> in
* a JSX route config.
*/
var IndexRoute = React.createClass({
displayName: 'IndexRoute',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) {
/* istanbul ignore else: sanity check */
if (parentRoute) {
parentRoute.indexRoute = _createRouteFromReactElement(element);
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRoute> does not make sense at the root of your route config') : void 0;
}
}
},
propTypes: {
path: falsy,
component: component,
components: components,
getComponent: func,
getComponents: func
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRoute> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default IndexRoute; |
docs/src/examples/modules/Modal/Usage/ModalExampleCallbacks.js | Semantic-Org/Semantic-UI-React | import React from 'react'
import { Button, Grid, Label, Modal, Segment } from 'semantic-ui-react'
function exampleReducer(state, action) {
switch (action.type) {
case 'CLEAR_LOG':
return { ...state, log: [] }
case 'OPEN_MODAL':
return {
log: [
{
event: action.event,
date: new Date().toLocaleTimeString(),
name: action.name,
value: true,
},
...state.log,
],
open: true,
}
case 'CLOSE_MODAL':
return {
log: [
{
event: action.event,
date: new Date().toLocaleTimeString(),
name: action.name,
value: true,
},
...state.log,
],
open: false,
}
default:
throw new Error()
}
}
function ModalExampleCloseConfig() {
const [state, dispatch] = React.useReducer(exampleReducer, {
log: [],
open: false,
})
const { log, open } = state
return (
<Grid>
<Grid.Column width={4}>
<Modal
onOpen={(e) =>
dispatch({ event: e.type, name: 'onOpen', type: 'OPEN_MODAL' })
}
onClose={(e) =>
dispatch({ event: e.type, name: 'onClose', type: 'CLOSE_MODAL' })
}
open={open}
trigger={<Button>Open a modal</Button>}
>
<Modal.Header>Delete Your Account</Modal.Header>
<Modal.Content>
<p>Are you sure you want to delete your account</p>
</Modal.Content>
<Modal.Actions>
<Button
onClick={(e) =>
dispatch({
event: e.type,
name: 'onClick',
type: 'CLOSE_MODAL',
})
}
negative
>
No
</Button>
<Button
onClick={(e) =>
dispatch({
event: e.type,
name: 'onClick',
type: 'CLOSE_MODAL',
})
}
positive
>
Yes
</Button>
</Modal.Actions>
</Modal>
</Grid.Column>
<Grid.Column width={12}>
{log.length > 0 && (
<Segment attached='top' secondary>
{log.map((entry, i) => (
<pre key={i}>
[{entry.date}] {entry.name} (
{JSON.stringify({
e: { type: entry.event },
data: { open: entry.value },
})}
)
</pre>
))}
</Segment>
)}
<Segment attached={log.length > 0 ? 'bottom' : undefined} secondary>
<Label>Entries: {log.length}</Label>
<Button
compact
floated='right'
onClick={() => dispatch({ type: 'CLEAR_LOG' })}
size='tiny'
>
Clear
</Button>
</Segment>
</Grid.Column>
</Grid>
)
}
export default ModalExampleCloseConfig
|
cm19/ReactJS/your-first-react-app-exercises-master/exercise-16/complete/friends/Friends.entry.js | Brandon-J-Campbell/codemash | import React from 'react';
import getFriendsFromApi from './get-friends-from-api';
import Friends from './Friends';
export default class FriendsEntry extends React.Component {
state = {
friends: []
}
async componentDidMount() {
const friends = await getFriendsFromApi();
this.setState({
friends
});
}
render() {
return <Friends friends={this.state.friends} />;
}
}
|
pilgrim3/components/optionsTable.js | opendoor-labs/pilgrim3 | import React from 'react'
import { map } from 'lodash'
export default class OptionsTable extends React.Component {
optionRow(value, key) {
return (
<tr key={`${key}-${value}`}>
<th>{key}</th>
<td>{value.toString()}</td>
</tr>
);
}
render() {
if (!this.props.object) {
return (<span/>);
} else {
return (
<table className='table table-hover'>
<tbody>
{map(this.props.object.options, this.optionRow)}
</tbody>
</table>
);
}
}
}
|
src/svg-icons/image/linked-camera.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageLinkedCamera = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="14" r="3.2"/><path d="M16 3.33c2.58 0 4.67 2.09 4.67 4.67H22c0-3.31-2.69-6-6-6v1.33M16 6c1.11 0 2 .89 2 2h1.33c0-1.84-1.49-3.33-3.33-3.33V6"/><path d="M17 9c0-1.11-.89-2-2-2V4H9L7.17 6H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9h-5zm-5 10c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/>
</SvgIcon>
);
ImageLinkedCamera = pure(ImageLinkedCamera);
ImageLinkedCamera.displayName = 'ImageLinkedCamera';
export default ImageLinkedCamera;
|
app/assets/scripts/views/about.js | openaq/openaq.github.io | 'use strict';
import React from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';
import JoinFold from '../components/join-fold';
import SponsorList from '../components/sponsor-list';
import TeamList from '../components/team-list';
import content from '../../content/content.json';
import sponsors from '../../content/sponsors.json';
const teamData = {
advisoryBoard: _(content.advisoryBoard)
.values()
.sortBy(['order'])
.value(),
governingBoard: _(content.governingBoard)
.values()
.sortBy(['order'])
.value(),
team: _(content.team)
.values()
.sortBy(['order'])
.value()
};
var About = React.createClass({
displayName: 'About',
propTypes: {
},
render: function () {
return (
<section className='inpage'>
<header className='inpage__header'>
<div className='inner'>
<div className='inpage__headline'>
<h1 className='inpage__title'>About us</h1>
<div className='inpage__introduction'>
<p>Our mission is to fight air inequality by opening up air quality data and connecting a diverse global, grassroots community of individuals and organizations.</p>
</div>
</div>
</div>
<figure className='inpage__media inpage__media--cover media'>
<div className='media__item'>
<img src='/assets/graphics/content/view--about/cover--about.jpg' alt='Cover image' width='1440' height='712' />
</div>
</figure>
</header>
<div className='inpage__body'>
<section className='fold fold--intro' id='about-fold-intro'>
<div className='inner'>
<header className='fold__header'>
<h1 className='fold__title'>We are guided by principles</h1>
</header>
<ul className='principles-list'>
<li>
<article className='card card--principle'>
<div className='card__contents'>
<figure className='card__media'>
<div className='card__badge'>
<img src='/assets/graphics/layout/oaq-icon-illu-48-historical.svg' width='40' height='40' alt='Illustration' />
</div>
</figure>
<header className='card__header'>
<div className='card__headline'>
<h1 className='card__title'>Historical + Programmatic access</h1>
</div>
</header>
<div className='card__body'>
<div className='card__prose prose prose--responsive'>
<p>Giving air quality data a wider audience.</p>
</div>
</div>
</div>
</article>
</li>
<li>
<article className='card card--principle'>
<div className='card__contents'>
<figure className='card__media'>
<div className='card__badge'>
<img src='/assets/graphics/layout/oaq-icon-illu-48-opensource.svg' width='40' height='40' alt='Illustration' />
</div>
</figure>
<header className='card__header'>
<div className='card__headline'>
<h1 className='card__title'>Open source</h1>
</div>
</header>
<div className='card__body'>
<div className='card__prose prose prose--responsive'>
<p>Encouraging collaboration in the open.</p>
</div>
</div>
</div>
</article>
</li>
<li>
<article className='card card--principle'>
<div className='card__contents'>
<figure className='card__media'>
<div className='card__badge'>
<img src='/assets/graphics/layout/oaq-icon-illu-48-community.svg' width='40' height='40' alt='Illustration' />
</div>
</figure>
<header className='card__header'>
<div className='card__headline'>
<h1 className='card__title'>Community driven</h1>
</div>
</header>
<div className='card__body'>
<div className='card__prose prose prose--responsive'>
<p>Working to help each other do impactful work.</p>
</div>
</div>
</div>
</article>
</li>
</ul>
</div>
</section>
<section className='fold fold--type-a' id='about-fold-story'>
<div className='inner'>
<header className='fold__header'>
<h1 className='fold__title'>Our story</h1>
<div className='fold__teaser prose prose--responsive'>
<p>The idea for OpenAQ came from observing the impact of a lone air quality monitor producing open data, set up by the U.S. Embassy in Beijing.</p>
<p>It spurred OpenAQ co-founders, Christa Hasenkopf, an atmospheric scientist, and Joe Flasher, a software developer, to set up a small open air quality project in Ulaanbaatar along with Mongolian colleagues.</p>
<p>Eventually, they and a community of open data lovers from around the world decided to see what would happen if all of the world’s air quality data were made available for the public to explore.</p>
</div>
</header>
<figure className='fold__media'>
<aside className='aside-highlight'>
<div className='aside-highlight__contents'>
<div className='aside-highlight__prose'>
<p>What if all of the world’s air quality data were available to explore?</p>
</div>
</div>
</aside>
</figure>
</div>
</section>
<section className='fold fold--stacked' id='about-fold-main-board'>
<div className='inner'>
<header className='fold__header'>
<h1 className='fold__title'>Our Team</h1>
<div className='fold__teaser prose prose--responsive'>
<p>Our team is passionate about fighting air inequality with open data. If you would like to make an inquiry to the team, please reach out to <a href='mailto:[email protected]'>[email protected]</a></p>
</div>
</header>
<TeamList items={teamData.team} />
</div>
</section>
<section className='fold fold--stacked' id='about-fold-main-board'>
<div className='inner'>
<header className='fold__header'>
<h1 className='fold__title'>Our Board</h1>
<div className='fold__teaser prose prose--responsive'>
<p>The Governing Board oversees the legal and financial operations of OpenAQ. If you would like to make an inquiry to the board, please reach out to <a href='mailto:[email protected]'>[email protected]</a>.</p>
</div>
</header>
<TeamList items={teamData.governingBoard} />
</div>
</section>
<section className='fold fold--stacked' id='about-fold-advisory-board'>
<div className='inner'>
<header className='fold__header'>
<h1 className='fold__title'>Our Advisory Board</h1>
<div className='fold__teaser prose prose--responsive'>
<p>The Advisory Board consists of world-class leaders in air quality, public health, and open data. The board advises OpenAQ on its overall strategy.</p>
</div>
</header>
<TeamList items={teamData.advisoryBoard} />
</div>
</section>
<section className='fold fold--semi-light' id='about-fold-sponsors'>
<div className='inner'>
<header className='fold__header'>
<h1 className='fold__title'>Partners and Sponsors</h1>
</header>
<SponsorList items={sponsors} />
<footer className='fold__footer'>
<a href='mailto:[email protected]' className='sponsor-button' title='View page'><span>Become a sponsor</span></a>
</footer>
</div>
</section>
<section className='fold fold--type-b' id='about-fold-book'>
<div className='inner'>
<header className='fold__header'>
<h1 className='fold__title'>We are an open book</h1>
<div className='fold__teaser prose prose--responsive'>
<p>We value transparency so all our records are publicly available.</p>
<p className='fold__main-action'>
<a href='/assets/files/openaq-990-2019.pdf' target='_blank' className='button-book-download' title='Download'><span>Download 2019 Form 990</span></a>
</p>
</div>
</header>
<figure className='fold__media'>
<article className='card card--book'>
<a href='/assets/files/openaq-990-2019.pdf' target='_blank' className='card__contents' title='Download'>
<header className='card__header'>
<div className='card__headline'>
<p className='card__subtitle'>2019</p>
<h1 className='card__title'>Form 990</h1>
</div>
</header>
<figure className='card__media'>
<div className='card__thumb'>
<img src='/assets/graphics/content/view--about/card-book-media.jpg' width='724' height='348' alt='Card media' />
</div>
</figure>
<footer className='card__footer'>
<img src='/assets/graphics/layout/oaq-logo-col-pos.svg' alt='OpenAQ logotype' width='72' height='40' />
</footer>
</a>
</article>
</figure>
</div>
</section>
<JoinFold />
</div>
</section>
);
}
});
// /////////////////////////////////////////////////////////////////// //
// Connect functions
function selector (state) {
return {
};
}
function dispatcher (dispatch) {
return {
};
}
module.exports = connect(selector, dispatcher)(About);
|
actor-apps/app-web/src/app/components/modals/invite-user/InviteByLink.react.js | liruqi/actor-platform-v0.9 | import { assign } from 'lodash';
import React from 'react';
import Modal from 'react-modal';
import addons from 'react/addons';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import { Styles, FlatButton, Snackbar } from 'material-ui';
import ReactZeroClipboard from 'react-zeroclipboard';
import classnames from 'classnames';
import { KeyCodes } from 'constants/ActorAppConstants';
import ActorTheme from 'constants/ActorTheme';
import InviteUserByLinkActions from 'actions/InviteUserByLinkActions';
import InviteUserActions from 'actions/InviteUserActions';
import InviteUserStore from 'stores/InviteUserStore';
const ThemeManager = new Styles.ThemeManager();
const appElement = document.getElementById('actor-web-app');
Modal.setAppElement(appElement);
const {addons: { PureRenderMixin }} = addons;
const getStateFromStores = () => {
return {
isShown: InviteUserStore.isInviteWithLinkModalOpen(),
group: InviteUserStore.getGroup(),
inviteUrl: InviteUserStore.getInviteUrl()
};
};
@ReactMixin.decorate(IntlMixin)
@ReactMixin.decorate(PureRenderMixin)
class InviteByLink extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
this.state = assign({
isCopyButtonEnabled: false
}, getStateFromStores());
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
button: {
minWidth: 60
}
});
InviteUserStore.addChangeListener(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
}
componentWillUnmount() {
InviteUserStore.removeChangeListener(this.onChange);
document.removeEventListener('keydown', this.onKeyDown, false);
}
render() {
const { group } = this.state;
const { inviteUrl, isShown, isCopyButtonEnabled } = this.state;
const snackbarStyles = ActorTheme.getSnackbarStyles();
let groupName;
if (group !== null) {
groupName = <b>{group.name}</b>;
}
const copyButtonClassname = classnames('button button--blue pull-right', {
'hide': !isCopyButtonEnabled
});
return (
<Modal className="modal-new modal-new--invite-by-link"
closeTimeoutMS={150}
isOpen={isShown}
style={{width: 400}}>
<header className="modal-new__header">
<svg className="modal-new__header__icon icon icon--blue"
dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#back"/>'}}
onClick={this.onBackClick}/>
<h3 className="modal-new__header__title">
<FormattedMessage message={this.getIntlMessage('inviteByLinkModalTitle')}/>
</h3>
<div className="pull-right">
<FlatButton hoverColor="rgba(81,145,219,.17)"
label="Done"
labelStyle={{padding: '0 8px'}}
onClick={this.onClose}
secondary={true}
style={{marginTop: -6}}/>
</div>
</header>
<div className="modal-new__body">
<FormattedMessage groupName={groupName} message={this.getIntlMessage('inviteByLinkModalDescription')}/>
<textarea className="invite-url" onClick={this.onInviteLinkClick} readOnly row="3" value={inviteUrl}/>
</div>
<footer className="modal-new__footer">
<button className="button button--light-blue pull-left hide">
<FormattedMessage message={this.getIntlMessage('inviteByLinkModalRevokeButton')}/>
</button>
<ReactZeroClipboard onCopy={this.onInviteLinkCopied} onReady={this.onZeroclipboardReady} text={inviteUrl}>
<button className={copyButtonClassname}>
<FormattedMessage message={this.getIntlMessage('inviteByLinkModalCopyButton')}/>
</button>
</ReactZeroClipboard>
</footer>
<Snackbar autoHideDuration={3000}
message={this.getIntlMessage('inviteLinkCopied')}
ref="inviteLinkCopied"
style={snackbarStyles}/>
</Modal>
);
}
onClose = () => {
InviteUserByLinkActions.hide();
};
onBackClick = () => {
this.onClose();
InviteUserActions.show(this.state.group);
};
onInviteLinkClick = event => {
event.target.select();
};
onChange = () => {
this.setState(getStateFromStores());
};
onKeyDown = (event) => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
};
onInviteLinkCopied = () => {
this.refs.inviteLinkCopied.show();
};
onZeroclipboardReady = () => {
this.setState({isCopyButtonEnabled: true});
};
}
export default InviteByLink;
|
lib/components/Application.js | sljohnson32/networkr | import React, { Component } from 'react';
import firebase, { signIn, signOut } from '../firebase';
import { pick, map, extend } from 'lodash';
import WelcomeScreen from './WelcomeScreen';
import HomeScreen from './HomeScreen';
import moment from 'moment'
export default class Application extends Component {
constructor() {
super();
this.state = {
user: null,
contactDatabase: [],
contactzz: [],
};
}
componentDidMount() {
firebase.auth().onAuthStateChanged(user => {
this.createDatabaseRef(user)
});
}
createDatabaseRef(user) {
this.setState({
user,
contactDatabase: user ? firebase.database().ref(user.uid) : null,
},
() => {
this.createDatabaseListener(user);
}
);
}
createDatabaseListener(user) {
if (user) {
firebase.database().ref(user.uid).on('value', (snapshot) => {
const contactzz = snapshot.val() || {};
this.setState({
contactzz: map(contactzz, (val, key) => extend(val, { key })),
});
});
} else {
this.setState({
contactzz: [],
});
}
}
addNewContact(newContact) {
const newContactData = pick(newContact, 'contactID', 'existingContact','firstName', 'lastName', 'organization', 'email', 'socialFB', 'gitHub', 'twitter', 'followUp', 'notes', 'createdAt')
this.state.contactDatabase.child(newContact.contactID).set(newContactData);
}
editContact(updatedContact) {
const id = updatedContact.contactID;
this.state.contactDatabase.child(id).update(updatedContact);
}
render() {
const { user, contactzz } = this.state;
return (
<div className="Application">
<div className='header'>
<h1>Networkr</h1>
</div>
{ user ?
<HomeScreen
user={ user }
contactzz={ contactzz }
addNewContact={ this.addNewContact.bind(this) }
editContact={ this.editContact.bind(this) }
signOut={ signOut.bind(this) }
/> :
<WelcomeScreen
signIn={ signIn.bind(this) }
/> }
</div>
);
}
}
|
src/components/Background.js | shoegazer/shuffle-guru | import React from 'react'
import {connect} from 'react-redux'
@connect(state => ({
cover: state.track.current.cover
}))
class Background extends React.Component {
render() {
return pug`#background(style=${this.props.cover ? {backgroundImage: 'url(' + this.props.cover + ')'} : {}})`;
}
}
export default Background |
examples/Autocomplete.js | react-materialize/react-materialize | import React from 'react';
import Autocomplete from '../src/Autocomplete';
import Row from '../src/Row';
export default
<Row>
<Autocomplete
title='Company'
data={
{
'Apple': null,
'Microsoft': null,
'Google': 'http://placehold.it/250x250'
}
}
/>
</Row>;
|
examples/src/components/RemoteSelectField.js | nightwolfz/react-select | import React from 'react';
import Select from 'react-select';
var RemoteSelectField = React.createClass({
displayName: 'RemoteSelectField',
propTypes: {
hint: React.PropTypes.string,
label: React.PropTypes.string,
},
loadOptions (input, callback) {
input = input.toLowerCase();
var rtn = {
options: [
{ label: 'One', value: 'one' },
{ label: 'Two', value: 'two' },
{ label: 'Three', value: 'three' }
],
complete: true
};
if (input.slice(0, 1) === 'a') {
if (input.slice(0, 2) === 'ab') {
rtn = {
options: [
{ label: 'AB', value: 'ab' },
{ label: 'ABC', value: 'abc' },
{ label: 'ABCD', value: 'abcd' }
],
complete: true
};
} else {
rtn = {
options: [
{ label: 'A', value: 'a' },
{ label: 'AA', value: 'aa' },
{ label: 'AB', value: 'ab' }
],
complete: false
};
}
} else if (!input.length) {
rtn.complete = false;
}
setTimeout(function() {
callback(null, rtn);
}, 500);
},
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 asyncOptions={this.loadOptions} className="remote-example" />
{this.renderHint()}
</div>
);
}
});
module.exports = RemoteSelectField;
|
src/Parser/Mage/Frost/Modules/Items/Tier20_2set.js | enragednuke/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import Combatants from 'Parser/Core/Modules/Combatants';
import Analyzer from 'Parser/Core/Analyzer';
import HIT_TYPES from 'Parser/Core/HIT_TYPES';
import getDamageBonus from 'Parser/Mage/Shared/Modules/GetDamageBonus';
import ItemDamageDone from 'Main/ItemDamageDone';
const FROZEN_MASS_DAMAGE_BONUS = 0.2;
/**
* Frost Mage Tier20 2set
* Frozen Orb increases your critical strike damage by 20% for 10 sec.
*/
class Tier20_2set extends Analyzer {
static dependencies = {
combatants: Combatants,
};
damage = 0;
on_initialized() {
this.active = this.combatants.selected.hasBuff(SPELLS.FROST_MAGE_T20_2SET_BONUS_BUFF.id);
}
on_byPlayer_damage(event) {
if (event.hitType !== HIT_TYPES.CRIT) {
return;
}
if (this.combatants.selected.hasBuff(SPELLS.FROZEN_MASS.id)) {
this.damage += getDamageBonus(event, FROZEN_MASS_DAMAGE_BONUS);
}
}
item() {
return {
id: SPELLS.FROST_MAGE_T20_2SET_BONUS_BUFF.id,
icon: <SpellIcon id={SPELLS.FROST_MAGE_T20_2SET_BONUS_BUFF.id} />,
title: <SpellLink id={SPELLS.FROST_MAGE_T20_2SET_BONUS_BUFF.id} />,
result: <ItemDamageDone amount={this.damage} />,
};
}
}
export default Tier20_2set;
|
src/parser/druid/balance/modules/Abilities.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import CoreAbilities from 'parser/core/modules/Abilities';
import ISSUE_IMPORTANCE from 'parser/core/ISSUE_IMPORTANCE';
class Abilities extends CoreAbilities {
spellbook() {
const combatant = this.selectedCombatant;
return [
// Rotational Spells
{
spell: SPELLS.STARSURGE_MOONKIN,
category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
gcd: {
base: 1500,
},
timelineSortIndex: 2,
},
{
spell: SPELLS.STARFALL_CAST,
buffSpellId: SPELLS.STARFALL_CAST.id,
category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
gcd: {
base: 1500,
},
timelineSortIndex: 3,
},
{
spell: SPELLS.SOLAR_WRATH_MOONKIN,
category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
gcd: {
base: 1500,
},
timelineSortIndex: 4,
},
{
spell: SPELLS.LUNAR_STRIKE,
category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
gcd: {
base: 1500,
},
timelineSortIndex: 5,
},
{
spell: SPELLS.MOONFIRE,
buffSpellId: SPELLS.MOONFIRE_BEAR.id,
category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
gcd: {
base: 1500,
},
timelineSortIndex: 6,
},
{
spell: SPELLS.SUNFIRE_CAST,
buffSpellId: SPELLS.SUNFIRE.id,
category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
gcd: {
base: 1500,
},
timelineSortIndex: 7,
},
{
spell: SPELLS.STELLAR_FLARE_TALENT,
buffSpellId: SPELLS.STELLAR_FLARE_TALENT.id,
category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
enabled: combatant.hasTalent(SPELLS.STELLAR_FLARE_TALENT.id),
gcd: {
base: 1500,
},
timelineSortIndex: 8,
},
// Cooldowns
{
spell: SPELLS.INCARNATION_CHOSEN_OF_ELUNE_TALENT,
buffSpellId: SPELLS.INCARNATION_CHOSEN_OF_ELUNE_TALENT.id,
category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
cooldown: 180,
enabled: combatant.hasTalent(SPELLS.INCARNATION_CHOSEN_OF_ELUNE_TALENT.id),
gcd: {
base: 1500,
},
castEfficiency: {
suggestion: true,
recommendedEfficiency: 0.8,
},
timelineSortIndex: 9,
},
{
spell: SPELLS.CELESTIAL_ALIGNMENT,
buffSpellId: SPELLS.CELESTIAL_ALIGNMENT.id,
category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
cooldown: 180,
enabled: !combatant.hasTalent(SPELLS.INCARNATION_CHOSEN_OF_ELUNE_TALENT.id),
gcd: {
base: 1500,
},
castEfficiency: {
suggestion: true,
recommendedEfficiency: 0.8,
},
timelineSortIndex: 9,
},
{
spell: SPELLS.WARRIOR_OF_ELUNE_TALENT,
buffSpellId: SPELLS.WARRIOR_OF_ELUNE_TALENT.id,
category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
cooldown: 48,
enabled: combatant.hasTalent(SPELLS.WARRIOR_OF_ELUNE_TALENT.id),
castEfficiency: {
suggestion: true,
recommendedEfficiency: 0.8,
},
timelineSortIndex: 10,
},
{
spell: SPELLS.FORCE_OF_NATURE_TALENT,
category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
cooldown: 60,
enabled: combatant.hasTalent(SPELLS.FORCE_OF_NATURE_TALENT.id),
gcd: {
base: 1500,
},
castEfficiency: {
suggestion: true,
recommendedEfficiency: 0.8,
},
timelineSortIndex: 10,
},
{
spell: [SPELLS.NEW_MOON_TALENT, SPELLS.HALF_MOON, SPELLS.FULL_MOON],
category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
cooldown: 25,
enabled: combatant.hasTalent(SPELLS.NEW_MOON_TALENT.id),
gcd: {
base: 1500,
},
charges: 3,
castEfficiency: {
suggestion: true,
recommendedEfficiency: 0.95,
averageIssueEfficiency: 0.9,
majorIssueEfficiency: 0.85,
extraSuggestion: (
<>
Your <SpellLink id={SPELLS.NEW_MOON_TALENT.id} />, <SpellLink id={SPELLS.HALF_MOON.id} /> and <SpellLink id={SPELLS.FULL_MOON.id} /> cast efficiency can be improved, try keeping yourself at low Moon charges at all times; you should (almost) never be at max (3) charges.
</>
),
},
timelineSortIndex: 11,
},
{
spell: SPELLS.FURY_OF_ELUNE_TALENT,
buffSpellId: SPELLS.FURY_OF_ELUNE_TALENT.id,
category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
cooldown: 60,
enabled: combatant.hasTalent(SPELLS.FURY_OF_ELUNE_TALENT.id),
gcd: {
base: 1500,
},
castEfficiency: {
suggestion: true,
recommendedEfficiency: 0.8,
},
timelineSortIndex: 11,
},
//Utility
{
spell: SPELLS.INNERVATE,
category: Abilities.SPELL_CATEGORIES.UTILITY,
cooldown: 180,
gcd: {
base: 1500,
},
castEfficiency: {
suggestion: true,
recommendedEfficiency: 0.70,
averageIssueEfficiency: 0.50,
majorIssueEfficiency: 0.30,
},
timelineSortIndex: 12,
},
{
spell: SPELLS.BARKSKIN,
buffSpellId: SPELLS.BARKSKIN.id,
category: Abilities.SPELL_CATEGORIES.DEFENSIVE,
cooldown: 60,
castEfficiency: {
suggestion: true,
recommendedEfficiency: 0.50,
averageIssueEfficiency: 0.35,
majorIssueEfficiency: 0.25,
importance: ISSUE_IMPORTANCE.MINOR,
},
timelineSortIndex: 13,
},
{
spell: SPELLS.RENEWAL_TALENT,
category: Abilities.SPELL_CATEGORIES.DEFENSIVE,
cooldown: 90,
enabled: combatant.hasTalent(SPELLS.RENEWAL_TALENT.id),
timelineSortIndex: 14,
},
{
spell: SPELLS.TIGER_DASH_TALENT,
buffSpellId: SPELLS.TIGER_DASH_TALENT.id,
category: Abilities.SPELL_CATEGORIES.UTILITY,
cooldown: 45,
enabled: combatant.hasTalent(SPELLS.TIGER_DASH_TALENT.id),
gcd: {
base: 1500,
},
timelineSortIndex: 14,
},
{
spell: [SPELLS.WILD_CHARGE_TALENT, SPELLS.WILD_CHARGE_MOONKIN, SPELLS.WILD_CHARGE_CAT, SPELLS.WILD_CHARGE_BEAR, SPELLS.WILD_CHARGE_TRAVEL],
category: Abilities.SPELL_CATEGORIES.UTILITY,
cooldown: 15,
gcd: null,
enabled: combatant.hasTalent(SPELLS.WILD_CHARGE_TALENT.id),
timelineSortIndex: 14,
},
{
spell: SPELLS.MIGHTY_BASH_TALENT,
category: Abilities.SPELL_CATEGORIES.UTILITY,
cooldown: 50,
enabled: combatant.hasTalent(SPELLS.MIGHTY_BASH_TALENT.id),
gcd: {
base: 1500,
},
},
{
spell: SPELLS.MASS_ENTANGLEMENT_TALENT,
category: Abilities.SPELL_CATEGORIES.UTILITY,
cooldown: 30,
enabled: combatant.hasTalent(SPELLS.MASS_ENTANGLEMENT_TALENT.id),
gcd: {
base: 1500,
},
},
{
spell: SPELLS.TYPHOON,
category: Abilities.SPELL_CATEGORIES.UTILITY,
cooldown: 30,
enabled: combatant.hasTalent(SPELLS.TYPHOON_TALENT.id),
gcd: {
base: 1500,
},
},
{
spell: SPELLS.ENTANGLING_ROOTS,
category: Abilities.SPELL_CATEGORIES.UTILITY,
gcd: {
base: 1500,
},
},
{
spell: SPELLS.DASH,
buffSpellId: SPELLS.DASH.id,
category: Abilities.SPELL_CATEGORIES.UTILITY,
enabled: !combatant.hasTalent(SPELLS.TIGER_DASH_TALENT.id),
cooldown: 180,
gcd: {
base: 1500,
},
},
{
spell: SPELLS.SOLAR_BEAM,
category: Abilities.SPELL_CATEGORIES.UTILITY,
cooldown: 45,
},
{
spell: SPELLS.REMOVE_CORRUPTION,
category: Abilities.SPELL_CATEGORIES.UTILITY,
cooldown: 8,
gcd: {
base: 1500,
},
},
{
spell: SPELLS.REBIRTH,
category: Abilities.SPELL_CATEGORIES.UTILITY,
gcd: {
base: 1500,
},
},
{
spell: SPELLS.GROWL,
category: Abilities.SPELL_CATEGORIES.UTILITY,
cooldown: 8,
},
{
spell: SPELLS.BEAR_FORM,
buffSpellId: SPELLS.BEAR_FORM.id,
category: Abilities.SPELL_CATEGORIES.DEFENSIVE,
gcd: {
base: 1500,
},
},
{
spell: SPELLS.CAT_FORM,
buffSpellId: SPELLS.CAT_FORM.id,
category: Abilities.SPELL_CATEGORIES.UTILITY,
gcd: {
base: 1500,
},
},
{
spell: SPELLS.MOONKIN_FORM,
buffSpellId: SPELLS.MOONKIN_FORM.id,
category: Abilities.SPELL_CATEGORIES.UTILITY,
gcd: {
base: 1500,
},
},
{
spell: SPELLS.TRAVEL_FORM,
buffSpellId: SPELLS.TRAVEL_FORM.id,
category: Abilities.SPELL_CATEGORIES.UTILITY,
gcd: {
base: 1500,
},
},
{
spell: SPELLS.REGROWTH,
category: Abilities.SPELL_CATEGORIES.UTILITY,
gcd: {
base: 1500,
},
},
{
spell: SPELLS.FRENZIED_REGENERATION,
buffSpellId: SPELLS.FRENZIED_REGENERATION.id,
category: Abilities.SPELL_CATEGORIES.DEFENSIVE,
cooldown: 36,
gcd: {
base: 1500,
},
enabled: combatant.hasTalent(SPELLS.GUARDIAN_AFFINITY_TALENT_SHARED.id),
},
{
spell: SPELLS.SWIFTMEND,
category: Abilities.SPELL_CATEGORIES.DEFENSIVE,
enabled: combatant.hasTalent(SPELLS.RESTORATION_AFFINITY_TALENT.id),
gcd: {
base: 1500,
},
},
{
spell: SPELLS.REJUVENATION,
category: Abilities.SPELL_CATEGORIES.UTILITY,
enabled: combatant.hasTalent(SPELLS.RESTORATION_AFFINITY_TALENT.id),
gcd: {
base: 1500,
},
},
{
spell: SPELLS.WILD_GROWTH,
category: Abilities.SPELL_CATEGORIES.UTILITY,
enabled: combatant.hasTalent(SPELLS.RESTORATION_AFFINITY_TALENT.id),
gcd: {
base: 1500,
},
},
{
spell: SPELLS.HIBERNATE,
category: Abilities.SPELL_CATEGORIES.UTILITY,
gcd: {
base: 1500,
},
},
{
spell: SPELLS.SOOTHE,
category: Abilities.SPELL_CATEGORIES.UTILITY,
cooldown: 10,
gcd: {
base: 1500,
},
},
];
}
}
export default Abilities;
|
src/common/Icon.js | fyruna/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import BAD_ICONS from 'common/BAD_ICONS';
const Icon = ({ icon, className, ...others }) => {
if (!icon) {
return null;
}
icon = icon.replace('.jpg', '').replace(/-/g, '');
if (icon === 'petbattle_healthdown') {
// Blizzard seems to have forgotten to remove the dash for this one... or something
icon = 'petbattle_health-down';
}
if (icon === 'class_demonhunter') {
// Blizzard seems to have forgotten to remove the dash for this one too
icon = 'class_demon-hunter';
}
let baseURL = `//render-us.worldofwarcraft.com/icons/56`;
if (BAD_ICONS.includes(icon)) {
baseURL = `/img/Icons`;
}
return (
<img
src={`${baseURL}/${icon}.jpg`}
alt="" // Implementers should annotate these as desired, but it's usually just decorating the name of a spell/item so doesn't add anything and in fact makes copy-pasting uglier
className={`icon game ${className}`}
{...others}
/>
);
};
Icon.propTypes = {
icon: PropTypes.string.isRequired,
className: PropTypes.string,
};
Icon.defaultProps = {
className: '',
};
export default Icon;
|
web/react360/src/components/hocs/getDevice.js | JamesMillercus/Portfolio-Website | import { connect } from 'react-redux';
import { UserAgent } from '@quentin-sommer/react-useragent';
import { View } from 'react-360';
import React, { Component } from 'react';
import { fetchDeviceType } from './../../actions';
// export default GetDevice(connect(mapStateToProps, mapDispatchToProps)(ChildComponent));
export default (ChildComponent) => {
// export default connect(mapStateToProps, { fetchDeviceType })(ChildComponent) => {
class GetDevice extends Component {
renderDevice(deviceType) {
// fetch with deviceType
if (deviceType !== 'mobile' && deviceType !== 'tablet') this.props.fetchDeviceType('laptop');
else this.props.fetchDeviceType(deviceType);
return <ChildComponent {...this.props} />;
}
render() {
return (
<UserAgent returnFullParser>
{parser => (
<View>
{this.renderDevice(parser.getDevice().type)}
</View>
)}
</UserAgent>
);
}
}
return connect(mapStateToProps, { fetchDeviceType })(GetDevice);
};
// map the state of data called from fetchUsers to users[state.users]
function mapStateToProps(state) {
return {
deviceType: state.deviceType
};
}
|
src/AffixMixin.js | westonplatter/react-bootstrap | import React from 'react';
import domUtils from './utils/domUtils';
import EventListener from './utils/EventListener';
const AffixMixin = {
propTypes: {
offset: React.PropTypes.number,
offsetTop: React.PropTypes.number,
offsetBottom: React.PropTypes.number
},
getInitialState() {
return {
affixClass: 'affix-top'
};
},
getPinnedOffset(DOMNode) {
if (this.pinnedOffset) {
return this.pinnedOffset;
}
DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, '');
DOMNode.className += DOMNode.className.length ? ' affix' : 'affix';
this.pinnedOffset = domUtils.getOffset(DOMNode).top - window.pageYOffset;
return this.pinnedOffset;
},
checkPosition() {
let DOMNode, scrollHeight, scrollTop, position, offsetTop, offsetBottom,
affix, affixType, affixPositionTop;
// TODO: or not visible
if (!this.isMounted()) {
return;
}
DOMNode = React.findDOMNode(this);
scrollHeight = domUtils.getDocumentHeight();
scrollTop = window.pageYOffset;
position = domUtils.getOffset(DOMNode);
if (this.affixed === 'top') {
position.top += scrollTop;
}
offsetTop = this.props.offsetTop != null ?
this.props.offsetTop : this.props.offset;
offsetBottom = this.props.offsetBottom != null ?
this.props.offsetBottom : this.props.offset;
if (offsetTop == null && offsetBottom == null) {
return;
}
if (offsetTop == null) {
offsetTop = 0;
}
if (offsetBottom == null) {
offsetBottom = 0;
}
if (this.unpin != null && (scrollTop + this.unpin <= position.top)) {
affix = false;
} else if (offsetBottom != null && (position.top + DOMNode.offsetHeight >= scrollHeight - offsetBottom)) {
affix = 'bottom';
} else if (offsetTop != null && (scrollTop <= offsetTop)) {
affix = 'top';
} else {
affix = false;
}
if (this.affixed === affix) {
return;
}
if (this.unpin != null) {
DOMNode.style.top = '';
}
affixType = 'affix' + (affix ? '-' + affix : '');
this.affixed = affix;
this.unpin = affix === 'bottom' ?
this.getPinnedOffset(DOMNode) : null;
if (affix === 'bottom') {
DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, 'affix-bottom');
affixPositionTop = scrollHeight - offsetBottom - DOMNode.offsetHeight - domUtils.getOffset(DOMNode).top;
}
this.setState({
affixClass: affixType,
affixPositionTop
});
},
checkPositionWithEventLoop() {
setTimeout(this.checkPosition, 0);
},
componentDidMount() {
this._onWindowScrollListener =
EventListener.listen(window, 'scroll', this.checkPosition);
this._onDocumentClickListener =
EventListener.listen(domUtils.ownerDocument(this), 'click', this.checkPositionWithEventLoop);
},
componentWillUnmount() {
if (this._onWindowScrollListener) {
this._onWindowScrollListener.remove();
}
if (this._onDocumentClickListener) {
this._onDocumentClickListener.remove();
}
},
componentDidUpdate(prevProps, prevState) {
if (prevState.affixClass === this.state.affixClass) {
this.checkPositionWithEventLoop();
}
}
};
export default AffixMixin;
|
fields/types/url/UrlField.js | riyadhalnur/keystone | import React from 'react';
import Field from '../Field';
import { Button, FormInput } from 'elemental';
module.exports = Field.create({
displayName: 'URLField',
openValue () {
var href = this.props.value;
if (!href) return;
if (!/^(mailto\:)|(\w+\:\/\/)/.test(href)) {
href = 'http://' + href;
}
window.open(href);
},
renderLink () {
if (!this.props.value) return null;
return (
<Button type="link" onClick={this.openValue} className="keystone-relational-button" title={'Open ' + this.props.value + ' in a new tab'}>
<span className="octicon octicon-link" />
</Button>
);
},
wrapField () {
return (
<div style={{ position: 'relative' }}>
{this.renderField()}
{this.renderLink()}
</div>
);
},
renderValue () {
return <FormInput noedit onClick={this.openValue}>{this.props.value}</FormInput>;
}
});
|
app/components/Character.js | jeflores7/character-voting-app | import React from 'react';
import CharacterStore from '../stores/CharacterStore';
import CharacterActions from '../actions/CharacterActions';
class Character extends React.Component {
constructor(props) {
super(props);
this.state = CharacterStore.getState();
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
CharacterStore.listen(this.onChange);
CharacterActions.getCharacter(this.props.params.id);
$('.magnific-popup').magnificPopup({
type: 'image',
mainClass: 'mfp-zoom-in',
closeOnContentClick: true,
midClick: true,
zoom: {
enabled: true,
duration: 300
}
});
}
componentWillUnmount() {
CharacterStore.unlisten(this.onChange);
// Remove the classes set in the CharacterStore
$(document.body).removeClass();
}
componentDidUpdate(prevProps) {
// Fetch new character data when the URL path changes
if (prevProps.params.id !== this.props.params.id) {
CharacterActions.getCharacter(this.props.params.id);
}
}
onChange(state) {
this.setState(state);
}
render() {
return (
<div className='container'>
<div className='profile-img'>
<a className='magnific-popup' href={`https://image.eveonline.com/Character/${this.state.characterId}_1024.jpg`}>
<img src={`https://image.eveonline.com/Character/${this.state.characterId}_256.jpg`} />
</a>
</div>
<div className='profile-info clearfix'>
<h2><strong>{this.state.name}</strong></h2>
<h4 className='lead'>Race: <strong>{this.state.race}</strong></h4>
<h4 className='lead'>Bloodline: <strong>{this.state.bloodline}</strong></h4>
<h4 className='lead'>Gender: <strong>{this.state.gender}</strong></h4>
<button className='btn btn-transparent'
onClick={CharacterActions.report.bind(this, this.state.characterId)}
disabled={this.state.isReported}>
{this.state.isReported ? 'Reported' : 'Report Character'}
</button>
</div>
<div className='profile-stats clearfix'>
<ul>
<li><span className='stats-number'>{this.state.winLossRatio}</span>Winning Percentage</li>
<li><span className='stats-number'>{this.state.wins}</span> Wins</li>
<li><span className='stats-number'>{this.state.losses}</span> Losses</li>
</ul>
</div>
</div>
);
}
}
export default Character;
|
05_ES6/Code/fork-es6/app/components/InboxPane.js | sayar/ReactMVA | import React from 'react';
import InboxItem from './InboxItem';
import autoBind from 'react-autobind';
class InboxPane extends React.Component {
constructor(props) {
super(props);
autoBind(this);
}
renderConvoSum(human) {
return <InboxItem key={human} index={human} details={this.props.humans[human]} />;
}
render() {
return (
<div id="inbox-pane" className="column">
<h1>Inbox</h1>
{Object.keys(this.props.humans).map(this.renderConvoSum)}
</div>
)
}
};
export default InboxPane;
|
widgets/NoticeWidget.js | FaridSafi/react-native-gifted-form | import React from 'react';
import createReactClass from 'create-react-class';
import {
View,
Text
} from 'react-native';
var WidgetMixin = require('../mixins/WidgetMixin.js');
module.exports = createReactClass({
mixins: [WidgetMixin],
getDefaultProps() {
return {
type: 'NoticeWidget',
};
},
render() {
return (
<View>
<View style={this.getStyle('noticeRow')}>
<Text
style={this.getStyle('noticeTitle')}
{...this.props}
>
{this.props.title}
</Text>
</View>
</View>
);
},
defaultStyles: {
noticeRow: {
paddingBottom: 10,
paddingTop: 5,
paddingLeft: 10,
paddingRight: 10,
},
noticeTitle: {
fontSize: 13,
color: '#9b9b9b',
},
},
});
|
src/index.js | UnforbiddenYet/react-sleek-photo-gallery | import React from 'react';
import Gallery from './components/gallery';
import Preloader from './components/preloader';
import config from './config';
export default function GalleryApp({ images, thumbnailHeight = config.THUMBNAIL_HEIGHT, ...rest }) {
return (
<Preloader images={images} maxThumbnailHeight={thumbnailHeight}>
{loadedImages => (<Gallery
loadedImages={loadedImages}
images={images}
thumbnailHeight={thumbnailHeight}
{...rest}
/>)}
</Preloader>
);
}
|
analysis/deathknightblood/src/modules/talents/Voracious.js | anom0ly/WoWAnalyzer | import { formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import Analyzer from 'parser/core/Analyzer';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';
import TalentStatisticBox from 'parser/ui/TalentStatisticBox';
import React from 'react';
class Voracious extends Analyzer {
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.VORACIOUS_TALENT.id);
}
get uptime() {
return this.selectedCombatant.getBuffUptime(SPELLS.VORACIOUS.id) / this.owner.fightDuration;
}
get uptimeSuggestionThresholds() {
return {
actual: this.uptime,
isLessThan: {
minor: 0.95,
average: 0.9,
major: 0.8,
},
style: 'percentage',
};
}
statistic() {
return (
<TalentStatisticBox
talent={SPELLS.VORACIOUS_TALENT.id}
position={STATISTIC_ORDER.OPTIONAL(6)}
value={`${formatPercentage(this.uptime)} %`}
label="Voracious uptime"
/>
);
}
}
export default Voracious;
|
actor-apps/app-web/src/app/index.js | lzpfmh/actor-platform | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
import 'babel/polyfill';
import RouterContainer from 'utils/RouterContainer';
import crosstab from 'crosstab';
import React, { Component } from 'react';
import Router from 'react-router';
import ReactMixin from 'react-mixin';
import { intlData } from 'l18n';
import { IntlMixin } from 'react-intl';
import Raven from 'utils/Raven'; // eslint-disable-line
import isMobile from 'utils/IsMobile';
import { endpoints } from 'constants/ActorAppConstants'
import LoginActionCreators from 'actions/LoginActionCreators';
import LoginStore from 'stores/LoginStore';
import PreferencesStore from 'stores/PreferencesStore';
import Deactivated from 'components/Deactivated.react';
import Login from 'components/Login.react';
import Main from 'components/Main.react';
import JoinGroup from 'components/JoinGroup.react';
import Install from 'components/Install.react';
//import AppCache from 'utils/AppCache'; // eslint-disable-line
// Loading progress
import Pace from 'pace';
Pace.start({
ajax: false,
restartOnRequestAfter: false,
restartOnPushState: false
});
// Preload emoji spritesheet
import { preloadEmojiSheet } from 'utils/EmojiUtils'
preloadEmojiSheet();
const { DefaultRoute, Route, RouteHandler } = Router;
const ActorInitEvent = 'concurrentActorInit';
if (crosstab.supported) {
crosstab.on(ActorInitEvent, (msg) => {
if (msg.origin !== crosstab.id && window.location.hash !== '#/deactivated') {
window.location.assign('#/deactivated');
window.location.reload();
}
});
}
// Check for mobile device, and force users to install native apps.
if (isMobile() && window.location.hash !== '#/install') {
window.location.assign('#/install');
document.body.classList.add('overflow');
} else if (window.location.hash === '#/install') {
window.location.assign('/');
}
@ReactMixin.decorate(IntlMixin)
class App extends Component {
render() {
return <RouteHandler/>;
}
}
const initReact = () => {
const appRootElemet = document.getElementById('actor-web-app');
if (window.location.hash !== '#/deactivated') {
if (crosstab.supported) {
crosstab.broadcast(ActorInitEvent, {});
}
if (location.pathname === '/app/index.html') {
window.messenger = new window.actor.ActorApp(['ws://' + location.hostname + ':9080/']);
} else {
window.messenger = new window.actor.ActorApp(endpoints);
}
}
const routes = (
<Route handler={App} name="app" path="/">
<Route handler={Main} name="main" path="/im/:id"/>
<Route handler={JoinGroup} name="join" path="/join/:token"/>
<Route handler={Login} name="login" path="/auth"/>
<Route handler={Deactivated} name="deactivated" path="/deactivated"/>
<Route handler={Install} name="install" path="/install"/>
<DefaultRoute handler={Main}/>
</Route>
);
const router = Router.create(routes, Router.HashLocation);
RouterContainer.set(router);
router.run((Root) => React.render(<Root {...intlData}/>, appRootElemet));
if (window.location.hash !== '#/deactivated') {
if (LoginStore.isLoggedIn()) {
LoginActionCreators.setLoggedIn(router, {redirect: false});
}
}
};
window.jsAppLoaded = () => setTimeout(initReact, 0);
|
components/forms/Input.js | jebeck/nefelion | import React from 'react';
import PropTypes from 'prop-types';
import { Form } from 'semantic-ui-react';
import styled from 'styled-components';
import { errorText, formText } from 'utils/themes';
const Label = styled.label`
color: ${formText} !important;
`;
const InputError = styled.div`
color: ${errorText};
font-size: 0.92857143em;
min-height: 2.5rem;
padding-top: 0.25rem;
`;
const Input = ({
input,
label,
placeholder,
type,
meta: { active, dirty, error, invalid, touched },
}) => {
const shouldDisplayError = !active && error;
return (
<Form.Field required width={8}>
<Label>{label}</Label>
<Form.Input
{...input}
error={!active && dirty && invalid}
placeholder={placeholder}
type={type}
/>
<InputError context="form">
{shouldDisplayError && (
<span role="img" aria-label="prohibited emoji">
🚫 [error]:
</span>
)}
{shouldDisplayError && ` ${error}`}
</InputError>
</Form.Field>
);
};
Input.propTypes = {
input: PropTypes.object.isRequired,
label: PropTypes.string.isRequired,
meta: PropTypes.shape({
error: PropTypes.string,
touched: PropTypes.bool.isRequired,
}).isRequired,
placeholder: PropTypes.string,
type: PropTypes.string.isRequired,
};
export default Input;
|
node_modules/react-router-dom/es/Link.js | Aznachang/CompanyPersonelReactJS | 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; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import React from 'react';
import PropTypes from 'prop-types';
var isModifiedEvent = function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
};
/**
* The public API for rendering a history-aware <a>.
*/
var Link = function (_React$Component) {
_inherits(Link, _React$Component);
function Link() {
var _temp, _this, _ret;
_classCallCheck(this, Link);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.handleClick = function (event) {
if (_this.props.onClick) _this.props.onClick(event);
if (!event.defaultPrevented && // onClick prevented default
event.button === 0 && // ignore right clicks
!_this.props.target && // let browser handle "target=_blank" etc.
!isModifiedEvent(event) // ignore clicks with modifier keys
) {
event.preventDefault();
var history = _this.context.router.history;
var _this$props = _this.props,
replace = _this$props.replace,
to = _this$props.to;
if (replace) {
history.replace(to);
} else {
history.push(to);
}
}
}, _temp), _possibleConstructorReturn(_this, _ret);
}
Link.prototype.render = function render() {
var _props = this.props,
replace = _props.replace,
to = _props.to,
props = _objectWithoutProperties(_props, ['replace', 'to']); // eslint-disable-line no-unused-vars
var href = this.context.router.history.createHref(typeof to === 'string' ? { pathname: to } : to);
return React.createElement('a', _extends({}, props, { onClick: this.handleClick, href: href }));
};
return Link;
}(React.Component);
Link.propTypes = {
onClick: PropTypes.func,
target: PropTypes.string,
replace: PropTypes.bool,
to: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired
};
Link.defaultProps = {
replace: false
};
Link.contextTypes = {
router: PropTypes.shape({
history: PropTypes.shape({
push: PropTypes.func.isRequired,
replace: PropTypes.func.isRequired,
createHref: PropTypes.func.isRequired
}).isRequired
}).isRequired
};
export default Link; |
test/helpers/shallowRenderHelper.js | openciti/dinesafe6 | /**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
src/components/hoc/withProps.js | nobt-io/frontend | import React from 'react';
const withProps = additionalProps => Component => props => {
return <Component {...props} {...additionalProps} />;
};
export default withProps;
|
src/containers/App.js | brtx/friendlist | /* src/containers/App.js */
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import AddFriendInput from '../components/AddFriendInput';
import FriendList from '../components/FriendList';
import * as FriendsActions from '../actions/FriendsActions';
class App extends Component {
render() {
const { friendlist, dispatch } = this.props;
// Turns an object whose values are action creators, into an object with the same keys, but
// with every action creator wrapped into a dispatch call so they may be invoked directly.
const actions = bindActionCreators(FriendsActions, dispatch);
return (
<div>
<h1>The FriendList</h1>
<AddFriendInput addFriend={actions.addFriend} />
<FriendList friends={friendlist} />
</div>
);
}
}
// Maps which part of the Redux global state our component wants to receive as props.
function mapStateToProps(state) {
return {
friendlist: state.friends
}
}
// Connects the React App container to the Redux store.
export default connect(mapStateToProps)(App); |
src/debugger/Debugger.js | josdejong/insight | 'use strict';
import React, { Component } from 'react';
import Immutable from 'seamless-immutable';
import { cloneDeep, reduce, isEqual } from 'lodash';
import Timeline from './Timeline';
export default class Debugger extends Component {
constructor (props) {
super(props);
let now = new Date().valueOf();
this.state = {
// state for the Timeline
start: now - 5 * 1000,
end: now + 10 * 1000, // 10 sec
simulatedTime: now,
realTime: now,
groups: Immutable([]),
events: Immutable([])
};
this.component = null;
this.componentStates = [];
}
render() {
let items = this.state.events.map(event => {
let text = '?';
let popover = null;
if (event.type === 'network') {
text = event.method.toUpperCase() + ' ' + event.url;
popover = 'url: ' + event.method.toUpperCase() + ' ' + event.url + ', ' +
'duration: ' + Math.round(event.duration) + 'ms';
}
if (event.type === 'state') {
text = JSON.stringify(event.after);
popover = 'before: ' + JSON.stringify(event.before) +
', after: ' + JSON.stringify(event.after)
}
if (event.type === 'method') {
text = event.method;
popover = 'return value: ' + event.result;
}
return {
id: event.id,
group: event.name,
start: event.timestamp,
end: event.duration ? (event.timestamp + event.duration) : undefined,
text: text,
popover: popover
// TODO: workout popover information, show a nice table, or maybe better info in a side panel
}
});
return <div className="debugger">
<h1>Debugger</h1>
<div className="debugger-menu">
<input type="button" value="toggle orientation" onClick={this.toggleOrientation.bind(this)} />
</div>
<p>
The Timeline below shows network requests, method calls, and state changes over time.
</p>
<Timeline
start={this.state.start}
end={this.state.end}
simulatedTime={this.state.simulatedTime}
realTime={this.state.realTime}
groups={this.state.groups}
items={items}
onChange={this.handleTimelineChange.bind(this)}
onSimulatedTime={this.handleSimulatedTime.bind(this)} />
</div>;
}
monitorRestClient (restClient) {
this.setState({
groups: this.state.groups.concat([{name: 'network'}])
});
Object.keys(restClient)
.forEach(name => {
let originalMethod = restClient[name];
if (typeof originalMethod === 'function') {
restClient[name] = this.createMonitoredRestMethod(name, originalMethod);
}
});
}
/**
* Monitor changes in the state of a React Component
* @param {Component} component
* @param {Array.<string>} names The names of the variables in the state to be monitored
*/
monitorState (component, names) {
let debuggr = this;
this.component = component;
// add new groups to the timeline, one for each monitored state
let groups = names.map(name => {
return {name};
});
this.setState({
groups: this.state.groups.concat(groups)
});
// listen for changes in the state, and emit debugger events on changes
let original = (component.componentWillUpdate || function () {}).bind(component);
component.componentWillUpdate = (nextProps, nextState) => {
names.forEach(name => {
let before = component.state[name];
let after = nextState[name];
this.compareState(name, before, after);
});
original(nextProps, nextState);
};
// emit events for the current state
names.forEach(name => {
this.compareState(name, undefined, component.state[name]);
});
}
/**
* Monitor method calls of a React Component
* @param {Component} component
* @param {Array.<string>} methods The names of the methods to be monitored
*/
monitorMethods (component, methods) {
// add new groups to the timeline, one for each monitored state
//let groups = methods.map(method => {
// return {method};
//});
this.setState({
groups: this.state.groups.concat([{name: 'method'}])
});
// replace the methods with a monitored method
methods.forEach(name => {
let originalMethod = component[name].bind(component);
component[name] = this.createMonitoredMethod(name, originalMethod)
});
}
/**
* Compare whether a variable in a components state is changed and if so,
* emit a new debugger event.
* @param name
* @param before
* @param after
*/
compareState(name, before, after) {
let changed = !isEqual(before, after);
if (changed) {
let event = Immutable({
id: createId(),
type: 'state',
timestamp: Date.now(),
name: name,
before: cloneDeep(before),
after: cloneDeep(after)
});
this.addEvent(event);
console.log('state event', event);
}
}
createMonitoredRestMethod (name, originalMethod) {
let debuggr = this;
return function (url, body) {
let eventId = createId();
let start = Date.now();
let tempEvent = Immutable({
id: eventId,
type: 'network',
timestamp: start,
name: 'network',
method: name,
url: url,
body: body
});
debuggr.addEvent(tempEvent);
function finish (response) {
let end = Date.now();
let finalEvent = tempEvent.merge({
duration: end - start,
response: response
});
// replace the temp event with the final event
debuggr.updateEvent(finalEvent);
console.log('network event', finalEvent);
}
let result = originalMethod(url, body);
if (isPromise(result)) {
// in case of a promise, wait until resolved
return result
.then(function (response) {
finish(response);
return response;
})
.catch(function (err) {
finish(err);
throw err;
})
}
else {
finish();
return result;
}
}
}
// TODO: merge and generalize createMonitoredMethod and createMonitoredRestMethod
createMonitoredMethod (name, originalMethod) {
let debuggr = this;
return function () {
let start = Date.now();
// invoke the original method
let result = originalMethod(...arguments);
let end = Date.now();
let event = Immutable({
id: createId(),
type: 'method',
timestamp: start,
//duration: end - start, // TODO: are we interested in duration of a method call here?
name: 'method',
method: name,
// TODO: it's problematic to store events, cannot make them immutable, not stringifiable
//args: argumentsToArray(arguments),
result: result
// TODO: stack
});
console.log('method event', event);
setTimeout(() => {
debuggr.addEvent(event);
}, 0);
// TODO: if promise, await until it resolves and then finish the event
return result;
}
}
addEvent (event) {
this.setState({events: this.state.events.concat(event)});
}
updateEvent (event) {
this.setState({
events: this.state.events.map(e => {
return e.id === event.id ? event : e;
})
});
}
/**
* Store changed state of the Timeline in our state
* @param {{start: number, end: number, currentTime}} timelineState
*/
handleTimelineChange (timelineState) {
this.setState(timelineState);
}
handleSimulatedTime (simulatedTime) {
// TODO: implement time travel...
alert('And now the time travel magic should happen... coming soon');
}
// TODO: rework orientation, it changes the orientation of the app itself
toggleOrientation () {
if (document.body.className === 'horizontal') {
document.body.className = 'vertical';
}
else {
document.body.className = 'horizontal';
}
}
}
/**
* Convert an arguments "array" into a real Array
* @param {Arguments} args
* @return {Array}
*/
function argumentsToArray (args) {
return Array.prototype.slice.call(args);
}
function isPromise (obj) {
return obj &&
typeof obj['then'] === 'function' &&
typeof obj['catch'] === 'function';
}
function createId () {
return ++_counter;
}
let _counter = 0; |
src/parser/demonhunter/vengeance/modules/features/Checklist/Component.js | sMteX/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import Checklist from 'parser/shared/modules/features/Checklist';
import Rule from 'parser/shared/modules/features/Checklist/Rule';
import GenericCastEfficiencyRequirement from 'parser/shared/modules/features/Checklist/GenericCastEfficiencyRequirement';
import PreparationRule from 'parser/shared/modules/features/Checklist/PreparationRule';
import Requirement from 'parser/shared/modules/features/Checklist/Requirement';
class VengeanceDemonHunterChecklist extends React.PureComponent {
static propTypes = {
castEfficiency: PropTypes.object.isRequired,
combatant: PropTypes.shape({
hasTalent: PropTypes.func.isRequired,
hasTrinket: PropTypes.func.isRequired,
}).isRequired,
thresholds: PropTypes.object.isRequired,
};
render() {
const { combatant, castEfficiency, thresholds } = this.props;
const AbilityRequirement = props => (
<GenericCastEfficiencyRequirement
castEfficiency={castEfficiency.getCastEfficiencyForSpellId(props.spell)}
{...props}
/>
);
return (
<Checklist>
<Rule
name="Use your short cooldowns"
description={(
<>
These should generally always be on recharge to maximize DPS, HPS and efficiency.<br />
<a href="http://www.wowhead.com/vengeance-demon-hunter-rotation-guide#rotation-priority-list" target="_blank" rel="noopener noreferrer">More info.</a>
</>
)}
>
<AbilityRequirement spell={SPELLS.IMMOLATION_AURA.id} />
<AbilityRequirement spell={SPELLS.SIGIL_OF_FLAME_CONCENTRATED.id} />
{combatant.hasTalent(SPELLS.FRACTURE_TALENT.id) && <AbilityRequirement spell={SPELLS.FRACTURE_TALENT.id} />}
{combatant.hasTalent(SPELLS.FELBLADE_TALENT.id) && <AbilityRequirement spell={SPELLS.FELBLADE_TALENT.id} />}
{combatant.hasTalent(SPELLS.FEL_DEVASTATION_TALENT.id) && <AbilityRequirement spell={SPELLS.FEL_DEVASTATION_TALENT.id} />}
</Rule>
<Rule
name="Use your rotational defensive/healing abilities"
description={(
<>
Use these to block damage spikes and keep damage smooth to reduce external healing required.<br />
<a href="http://www.wowhead.com/vengeance-demon-hunter-rotation-guide#rotation-priority-list" target="_blank" rel="noopener noreferrer">More info.</a>
</>
)}
>
<Requirement
name={(
<>
<SpellLink id={SPELLS.DEMON_SPIKES.id} />
</>
)}
thresholds={thresholds.demonSpikes}
/>
{combatant.hasTalent(SPELLS.SPIRIT_BOMB_TALENT.id) && !combatant.hasTalent(SPELLS.FEED_THE_DEMON_TALENT.id) &&(
<Requirement
name={(
<>
<SpellLink id={SPELLS.SPIRIT_BOMB_TALENT.id} /> 4+ souls casts
</>
)}
thresholds={thresholds.spiritBombSoulsConsume}
/>
)}
{(!combatant.hasTalent(SPELLS.FEED_THE_DEMON_TALENT.id) && combatant.hasTalent(SPELLS.SPIRIT_BOMB_TALENT.id)) &&(
<Requirement
name={(
<>
<SpellLink id={SPELLS.SOUL_CLEAVE.id} /> souls consumed
</>
)}
thresholds={thresholds.soulCleaveSoulsConsumed}
/>
)}
{combatant.hasTalent(SPELLS.SOUL_BARRIER_TALENT.id) && <AbilityRequirement spell={SPELLS.SOUL_BARRIER_TALENT.id} />}
</Rule>
<Rule
name="Use your long defensive/healing cooldowns"
description={(
<>
Use these to mitigate large damage spikes or in emergency situations.<br />
<a href="http://www.wowhead.com/vengeance-demon-hunter-rotation-guide#rotation-priority-list" target="_blank" rel="noopener noreferrer">More info.</a>
</>
)}
>
<AbilityRequirement spell={SPELLS.METAMORPHOSIS_TANK.id} />
<AbilityRequirement spell={SPELLS.FIERY_BRAND.id} />
</Rule>
{(combatant.hasTalent(SPELLS.SPIRIT_BOMB_TALENT.id) || combatant.hasTalent(SPELLS.VOID_REAVER_TALENT.id)) && (
<Rule
name="Maintain your buffs and debuffs"
description={(
<>
It is important to maintain these as they contribute a large amount to your DPS and HPS.<br />
<a href="http://www.wowhead.com/vengeance-demon-hunter-rotation-guide#rotation-priority-list" target="_blank" rel="noopener noreferrer">More info.</a>
</>
)}
>
{combatant.hasTalent(SPELLS.SPIRIT_BOMB_TALENT.id) &&(
<Requirement
name={(
<>
<SpellLink id={SPELLS.FRAILTY_SPIRIT_BOMB_DEBUFF.id} /> debuff uptime
</>
)}
thresholds={thresholds.spiritBombFrailtyDebuff}
/>
)}
{combatant.hasTalent(SPELLS.VOID_REAVER_TALENT.id) &&(
<Requirement
name={(
<>
<SpellLink id={SPELLS.VOID_REAVER_TALENT.id} /> debuff uptime
</>
)}
thresholds={thresholds.voidReaverDebuff}
/>
)}
</Rule>
)}
<PreparationRule thresholds={thresholds} />
</Checklist>
);
}
}
export default VengeanceDemonHunterChecklist;
|
src/Duration.js | siiptuo/tiima-spa | import React from 'react';
import PropTypes from 'prop-types';
import { duration } from './filters';
export default class Duration extends React.Component {
static propTypes = {
startTime: PropTypes.instanceOf(Date),
endTime: PropTypes.instanceOf(Date),
};
constructor(props) {
super(props);
if (!this.props.endTime) {
this.interval = setInterval(() => {
this.forceUpdate();
}, 1000);
}
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<span>
{duration(
this.props.startTime,
this.props.endTime,
!this.props.endTime,
)}
</span>
);
}
}
|
public/src/containers/dnd/board.js | white87332/react-redux | import React, { Component } from 'react';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import PropTypes from 'prop-types';
import BoardSquare from './boardSquare';
import Knight from './knight';
@DragDropContext(HTML5Backend)
class Board extends Component
{
constructor(props, context)
{
super(props, context);
this.state = {};
}
renderSquare(i)
{
const x = i % 8;
const y = Math.floor(i / 8);
return (
<div key={i} style={{ width: '12.5%', height: '12.5%' }}>
<BoardSquare x={x} y={y}>
{this.renderPiece(x, y)}
</BoardSquare>
</div>
);
}
renderPiece(x, y)
{
const [knightX, knightY] = this.props.knightPosition;
if (x === knightX && y === knightY)
{
return <Knight />;
}
}
render()
{
const squares = [];
for (let i = 0; i < 64; i += 1)
{
squares.push(this.renderSquare(i));
}
return (
<div className="Board">
{squares}
</div>
);
}
}
Board.propTypes = {
knightPosition: PropTypes.array.isRequired
};
export default Board;
|
node_modules/react-bootstrap/es/PagerItem.js | Crisa221/Lista-Giocatori | 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 SafeAnchor from './SafeAnchor';
import createChainedFunction from './utils/createChainedFunction';
var propTypes = {
disabled: React.PropTypes.bool,
previous: React.PropTypes.bool,
next: React.PropTypes.bool,
onClick: React.PropTypes.func,
onSelect: React.PropTypes.func,
eventKey: React.PropTypes.any
};
var defaultProps = {
disabled: false,
previous: false,
next: false
};
var PagerItem = function (_React$Component) {
_inherits(PagerItem, _React$Component);
function PagerItem(props, context) {
_classCallCheck(this, PagerItem);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleSelect = _this.handleSelect.bind(_this);
return _this;
}
PagerItem.prototype.handleSelect = function handleSelect(e) {
var _props = this.props;
var disabled = _props.disabled;
var onSelect = _props.onSelect;
var eventKey = _props.eventKey;
if (onSelect || disabled) {
e.preventDefault();
}
if (disabled) {
return;
}
if (onSelect) {
onSelect(eventKey, e);
}
};
PagerItem.prototype.render = function render() {
var _props2 = this.props;
var disabled = _props2.disabled;
var previous = _props2.previous;
var next = _props2.next;
var onClick = _props2.onClick;
var className = _props2.className;
var style = _props2.style;
var props = _objectWithoutProperties(_props2, ['disabled', 'previous', 'next', 'onClick', 'className', 'style']);
delete props.onSelect;
delete props.eventKey;
return React.createElement(
'li',
{
className: classNames(className, { disabled: disabled, previous: previous, next: next }),
style: style
},
React.createElement(SafeAnchor, _extends({}, props, {
disabled: disabled,
onClick: createChainedFunction(onClick, this.handleSelect)
}))
);
};
return PagerItem;
}(React.Component);
PagerItem.propTypes = propTypes;
PagerItem.defaultProps = defaultProps;
export default PagerItem; |
examples/huge-apps/routes/Course/components/Nav.js | skevy/react-router | import React from 'react';
import { Link } from 'react-router';
import AnnouncementsRoute from '../routes/Announcements';
import AssignmentsRoute from '../routes/Assignments';
import GradesRoute from '../routes/Grades';
const styles = {};
styles.nav = {
borderBottom: '1px solid #aaa'
};
styles.link = {
display: 'inline-block',
padding: 10,
textDecoration: 'none',
};
styles.activeLink = Object.assign({}, styles.link, {
//color: 'red'
});
class Nav extends React.Component {
render () {
var { course } = this.props;
var pages = [
['announcements', 'Announcements'],
['assignments', 'Assignments'],
['grades', 'Grades'],
];
return (
<nav style={styles.nav}>
{pages.map((page, index) => (
<Link
key={page[0]}
activeStyle={index === 0 ?
Object.assign({}, styles.activeLink, { paddingLeft: 0 }) :
styles.activeLink}
style={index === 0 ?
Object.assign({}, styles.link, { paddingLeft: 0 }) :
styles.link }
to={`/course/${course.id}/${page[0]}`}
>{page[1]}</Link>
))}
</nav>
);
}
}
export default Nav;
|
example10/src/main.js | JoeTheDave/Talk-ReactUpAndRunning |
//main.js
import React from 'react';
import {render} from 'react-dom';
import ApplicationComponent from './components/ApplicationComponent';
render(<ApplicationComponent />, document.getElementById('app')); |
src/client/components/Notfound.js | matystl/shopping_list | import DocumentTitle from 'react-document-title';
import React from 'react';
import {Link} from 'react-router';
export default class NotFound extends React.Component {
render() {
return (
<DocumentTitle title={'Page Not Found'}>
<div>
<h1>
{`This page isn't available`}
</h1>
<p>
{'The link may be broken, or the page may have been removed.'}
</p>
<Link to="home">{'Continue here please.'}</Link>
</div>
</DocumentTitle>
);
}
}
|
src/ButtonToolbar.js | zanjs/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
const ButtonToolbar = React.createClass({
mixins: [BootstrapMixin],
getDefaultProps() {
return {
bsClass: 'button-toolbar'
};
},
render() {
let classes = this.getBsClassSet();
return (
<div
{...this.props}
role="toolbar"
className={classNames(this.props.className, classes)}>
{this.props.children}
</div>
);
}
});
export default ButtonToolbar;
|
src/svg-icons/navigation-arrow-drop-right.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../SvgIcon';
let NavigationArrowDropRight = (props) => (
<SvgIcon {...props}>
<path d="M9.5,7l5,5l-5,5V7z" />
</SvgIcon>
);
NavigationArrowDropRight = pure(NavigationArrowDropRight);
NavigationArrowDropRight.displayName = 'NavigationArrowDropRight';
NavigationArrowDropRight.muiName = 'SvgIcon';
export default NavigationArrowDropRight;
|
src/components/login/Login.js | nikolay-is/jsappproject | import React from 'react';
import Observer from '../../utilities/observer';
import ERR from '../../utilities/err';
import { userLogin } from '../../models/User';
import LoginUserForm from './Login-Userform-View';
import { getClientInfo } from '../../models/UserLog';
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: window.sessionStorage.getItem('userId'),
busy: false,
username: '',
password: ''
};
this.onChangeHandler = this.onChangeHandler.bind(this);
this.onSubmitHandler = this.onSubmitHandler.bind(this);
this.saveSession = this.saveSession.bind(this);
this.updateClientInfo = this.updateClientInfo.bind(this);
}
onChangeHandler(ev) {
let nextState = {};
nextState[ev.target.name] = ev.target.value;
this.setState(nextState);
ev.preventDefault();
}
onSubmitHandler(ev) {
this.setState({ busy: true });
userLogin(this.state.username, this.state.password)
.then(userData => {
this.saveSession(userData);
Observer.onSessionUpdate();
this.context.router.push('/');
})
.catch(err => {
console.error(err.status, err.statusText);
this.setState({
busy: false,
username: '',
password: ''
});
});
ev.preventDefault();
}
saveSession(userData) {
let userId = userData._id || undefined;
let userName = userData.username || undefined;
let authToken = userData._kmd.authtoken || undefined;
if ( !(userId && userName && authToken) )
return new Promise((resolve, reject) => reject(ERR.BAD_USER_DATA));
window.sessionStorage.setItem('userId', userId);
window.sessionStorage.setItem('userName', userName);
window.sessionStorage.setItem('authToken', authToken);
this.updateClientInfo(userId);
}
updateClientInfo(userId) {
getClientInfo('http://ip-api.com/json', userId)
.then(data => {
console.log(data);
})
.catch(err => {});
}
render() {
if (this.state.isLoggedIn) this.context.router.push('/');
return (
<div>
<h2>Login</h2>
<LoginUserForm
busy={this.state.busy}
username={this.state.username}
password={this.state.password}
onChange={this.onChangeHandler}
onSubmit={this.onSubmitHandler}
/>
</div>
);
}
}
Login.contextTypes = {
router: React.PropTypes.object
};
Login.propTypes = {}
Login.defaultProps = {}
export default Login;
|
src/components/App.js | mmapplebeck/react-redux-minesweeper | import React from 'react'
import Window from './Window'
import Menu from './Menu'
import Game from '../containers/Game'
import '../assets/spritesheet.png'
import '../style/app.scss'
import '../style/sprite.scss'
const getMenuItems = props => ([
{
label: 'Game',
groups: [[{
label: 'New',
onClick: props.resetGame
}],
[{
active: props.settings.id === 'beginner',
label: 'Beginner',
onClick: props.setBeginner
},
{
active: props.settings.id === 'intermediate',
label: 'Intermediate',
onClick: props.setIntermediate
},
{
active: props.settings.id === 'expert',
label: 'Expert',
onClick: props.setExpert
}]]
}
])
export default props => (
<Window title="React/Redux Minesweeper">
<Menu items={getMenuItems(props)}/>
<Game />
</Window>
) |
app/components/H2/index.js | AK33M/scalable-react | import React from 'react';
import styles from './styles.css';
function H2(props) {
return (
<h2 className={styles.heading2} {...props} />
);
}
export default H2;
|
docs/app/Examples/modules/Accordion/Types/AccordionExamplePanelsProp.js | mohammed88/Semantic-UI-React | import React from 'react'
import { Accordion } from 'semantic-ui-react'
import faker from 'faker'
import _ from 'lodash'
const panels = _.times(3, () => ({
title: faker.lorem.sentence(),
content: faker.lorem.paragraphs(),
}))
const AccordionExamplePanelsProp = () => (
<Accordion panels={panels} />
)
export default AccordionExamplePanelsProp
|
Realization/frontend/czechidm-core/src/components/advanced/ImageDropzone/ImageDropzone.js | bcvsolutions/CzechIdMng | import React from 'react';
import Well from '../../basic/Well/Well';
//
import * as Basic from '../../basic';
import { Dropzone } from '../../basic/Dropzone/Dropzone';
/**
* Advanced Dropzone component
* it will shows dropzone if there is no uploaded image yet
* otherwise it will show an image
*
* @author Petr Hanák
*/
class ImageDropzone extends Basic.AbstractContextComponent {
constructor(props, context) {
super(props, context);
this.state = {};
}
render() {
const { rendered, onDrop, children, showLoading, accept, ...others } = this.props;
//
if (!rendered) {
return null;
}
if (showLoading) {
return <Well showLoading/>;
}
//
return (
<div>
<Basic.Dropzone
accept={ accept }
onDrop={ onDrop }
children={ children && children.props.src ? children : undefined }
style={ children && children.props.src ? { margin: 0, padding: 0, border: 'none' } : ImageDropzone.defaultProps.style }
{...others}/>
</div>
);
}
}
ImageDropzone.propTypes = {
...Dropzone.propTypes
};
ImageDropzone.defaultProps = {
...Dropzone.defaultProps
};
export default ImageDropzone;
|
src/components/Radial.react.js | kelemen/kitematic | import React from 'react';
import classNames from 'classnames';
var Radial = React.createClass({
render: function () {
var percentage;
if ((this.props.progress !== null && this.props.progress !== undefined) && !this.props.spin && !this.props.error) {
percentage = (
<div className="percentage"></div>
);
} else {
percentage = <div></div>;
}
var classes = classNames({
'radial-progress': true,
'radial-spinner': this.props.spin,
'radial-negative': this.props.error,
'radial-thick': this.props.thick || false,
'radial-gray': this.props.gray || false,
'radial-transparent': this.props.transparent || false
});
return (
<div className={classes} data-progress={this.props.progress}>
<div className="circle">
<div className="mask full">
<div className="fill"></div>
</div>
<div className="mask half">
<div className="fill"></div>
<div className="fill fix"></div>
</div>
<div className="shadow"></div>
</div>
<div className="inset">
{percentage}
</div>
</div>
);
}
});
module.exports = Radial;
|
docs/src/app/components/pages/components/DatePicker/ExampleInline.js | nathanmarks/material-ui | import React from 'react';
import DatePicker from 'material-ui/DatePicker';
/**
* Inline Date Pickers are displayed below the input, rather than as a modal dialog.
*/
const DatePickerExampleInline = () => (
<div>
<DatePicker hintText="Portrait Inline Dialog" container="inline" />
<DatePicker hintText="Landscape Inline Dialog" container="inline" mode="landscape" />
</div>
);
export default DatePickerExampleInline;
|
src/admin/components/container/index.js | ccetc/platform | import React from 'react'
import _ from 'lodash'
import { connect } from 'react-redux'
import * as actions from './actions'
class Container extends React.Component {
static childContextTypes = {
container: React.PropTypes.object
}
static propTypes = {
onFetchResource: React.PropTypes.func
}
render() {
const { children } = this.props
return children
}
getChildContext() {
return {
container: {
fetch: this._fetchResources.bind(this),
refresh: this._refreshResources.bind(this),
clear: this._clearResources.bind(this),
params: this.props.params
}
}
}
_fetchResources(resources) {
_.forOwn(resources, (endpoint, prop) => {
this.props.onFetchResource(prop, endpoint)
})
}
_refreshResources(props) {
props = (_.isString(props)) ? [props] : props
props.map(prop => {
const endpoint = this.props.routes[prop]
if(endpoint) {
this.props.onFetchResource(prop, endpoint)
}
})
}
_clearResources(props) {
props.map(prop => {
this.props.onClearResource(prop)
})
}
}
const mapStateToProps = (state, props) => ({
routes: state.container.routes
})
const mapDispatchToProps = {
onFetchResource: actions.fetchResource,
onClearResource: actions.clearResource
}
export default connect(mapStateToProps, mapDispatchToProps)(Container)
|
frontend/components/dashboard/MenuUl.js | wpmg/wpcl_hd | import React from 'react';
import PropTypes from 'prop-types';
import MenuLi from './MenuLi';
const MenuChildComponent = (component, depth) => {
const childArray = [
<MenuLi
key={component.menuItem.path}
menuItem={component.menuItem}
auth={component.auth}
location={component.location}
depth={depth}
/>,
];
if (Object.prototype.hasOwnProperty.call(component.menuItem, 'children')) {
const childrenLength = component.menuItem.children.length;
for (let i = 0; i < childrenLength; i++) {
childArray.push(...MenuChildComponent({
auth: component.auth,
location: component.location,
menuItem: component.menuItem.children[i],
}, depth + 1));
}
}
return childArray;
};
const MenuUl = ({ auth, location, type, menuGroup }) => {
let htmlClass = '';
switch (type) {
case 'navbar':
htmlClass = 'navbar-nav ml-auto';
break;
case 'collapsable':
htmlClass = 'navbar-nav d-md-none';
break;
default:
htmlClass = 'nav-sidebar';
}
const menuItems = [];
const menuGroupLength = menuGroup.length;
for (let i = 0; i < menuGroupLength; i++) {
menuItems.push(...MenuChildComponent({
auth,
location,
menuItem: menuGroup[i],
}, 0));
}
if (menuItems.length > 0) {
return (
<ul className={htmlClass}>
{menuItems}
</ul>
);
}
return null;
};
MenuUl.propTypes = {
auth: PropTypes.shape({
authority: PropTypes.number.isRequired,
username: PropTypes.string.isRequired,
}).isRequired,
location: PropTypes.object.isRequired,
type: PropTypes.string.isRequired,
menuGroup: PropTypes.array.isRequired,
};
export default MenuUl;
|
examples/Examples.js | christiaanderidder/react-googlecharts | import React from 'react';
import GoogleChart from '../src/components/GoogleChart';
export default React.createClass({
getInitialState() {
return {
data: [],
options: {
curveType: 'function'
}
};
},
componentDidMount() {
window.setTimeout(() => {
this.setState({
data: [
['City', '2010 Population', '2000 Population'],
['New York City, NY', 8175000, 8008000],
['Los Angeles, CA', 3792000, 3694000],
['Chicago, IL', 2695000, 2896000],
['Houston, TX', 2099000, 1953000],
['Philadelphia, PA', 1526000, 1517000]
]
});
}, 2000);
},
render() {
return(
<div className="wrapper">
<GoogleChart type="material-line" data={this.state.data} options={this.state.options} />
<GoogleChart type="material-bar" data={this.state.data} options={this.state.options} />
<GoogleChart type="line" data={this.state.data} options={this.state.options} />
<GoogleChart type="bar" data={this.state.data} options={this.state.options} />
</div>
);
}
}); |
src/components/FooterBar/Responses/Favorite.js | welovekpop/uwave-web-welovekpop.club | import React from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import FavoritedIcon from '@material-ui/icons/Favorite';
import FavoriteIcon from '@material-ui/icons/FavoriteBorder';
import Button from './Button';
const enhance = translate();
const handleFavorite = onFavorite => (event) => {
const pos = event.target.getBoundingClientRect();
onFavorite({
x: pos.left,
y: pos.top,
});
};
const Favorite = ({
t,
onFavorite,
count,
disabled,
active,
}) => {
const CurrentIcon = active ? FavoritedIcon : FavoriteIcon;
return (
<Button
disabled={disabled}
tooltip={t('votes.favorite')}
onClick={handleFavorite(onFavorite)}
count={count}
>
<CurrentIcon className="ResponseButton-icon--favorite" />
</Button>
);
};
Favorite.propTypes = {
t: PropTypes.func.isRequired,
onFavorite: PropTypes.func.isRequired,
count: PropTypes.number.isRequired,
disabled: PropTypes.bool,
active: PropTypes.bool,
};
export default enhance(Favorite);
|
src/components/small-print.js | mozilla/donate.mozilla.org | import React from 'react';
import Link from './link.js';
import { FormattedHTMLMessage, FormattedMessage } from 'react-intl';
var Footer = React.createClass({
contextTypes: {
intl: React.PropTypes.object
},
render: function() {
var wireTransferLink = (<Link to={'/' + this.context.intl.locale + '/ways-to-give#wire'}>{this.context.intl.formatMessage({id: 'sepa_bacs'})}</Link>);
var checkLink = (<a href={'/' + this.context.intl.locale + '/ways-to-give#check'}>{this.context.intl.formatMessage({id: 'check'})}</a>);
var bitcoinLink = (<a href='https://wiki.mozilla.org/Donate_Bitcoin'>{this.context.intl.formatMessage({id: 'Bitcoin'})}</a>);
var privacyPolicyMessage = "privacy_policy_var_b";
if (this.props.frequency === "monthly") {
privacyPolicyMessage = "privacy_policy_var_b_monthly";
}
return (
<div className="row disclaimers">
<p className="full">
<FormattedHTMLMessage id={privacyPolicyMessage}/>
</p>
<p className="full">
<b><FormattedMessage
id='other_way_to_give_wire'
values={{
wireTransferLink,
checkLink,
bitcoinLink
}}
/></b>
</p>
<p className="full need-help">
<FormattedHTMLMessage id="problems_donating"/>
</p>
<p className="full donation-notice">
{this.context.intl.formatMessage({id: 'donation_notice_2'})}
</p>
</div>
);
}
});
module.exports = Footer;
|
src/React/CollapsibleControls/CollapsibleControlFactory/CompositeControl.js | Kitware/paraviewweb | import React from 'react';
import CollapsibleControlFactory from '.';
import CollapsibleWidget from '../../Widgets/CollapsibleWidget';
import CompositePipelineWidget from '../../Widgets/CompositePipelineWidget';
CollapsibleControlFactory.registerWidget(
'CompositeControl',
({ pipelineModel }) => (
<CollapsibleWidget title="Pipeline" key="CompositeControl_parent">
<CompositePipelineWidget key="CompositeControl" model={pipelineModel} />
</CollapsibleWidget>
)
);
|
src/components/Alert.js | kiyoshitaro/Instagram- | import React from 'react';
import { createAlert } from 'react-redux-alerts';
const MyAlert = ({message, close}) => (
<div className='myAlert'>
{message}
<button onClick={close}> Click to Dismiss me </button>
</div>
);
export default createAlert({
alertName: 'myAlert',
alertMessage: 'Because I am Batman'
})(MyAlert);
|
envkey-react/src/components/shared/broadcast_loader.js | envkey/envkey-app | import React from 'react'
const svgString = `<?xml version="1.0" encoding="utf-8"?>
<svg width='56px'
height='56px'
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100 100"
preserveAspectRatio="xMidYMid"
class="uil-blank">
<rect x="0"
y="0"
width="100"
height="100"
fill="none"
class="bk">
</rect>
<g transform="scale(0.55)">
<circle cx="30" cy="150" r="30" fill="#000">
<animate attributeName="opacity"
from="0"
to="1"
dur="1.1s"
begin="0"
repeatCount="indefinite"
keyTimes="0;0.5;1"
values="0;1;1">
</animate>
</circle>
<path d="M90,150h30c0-49.7-40.3-90-90-90v30C63.1,90,90,116.9,90,150z" fill="#000000">
<animate attributeName="opacity"
from="0"
to="1"
dur="1.1s"
begin="0.11000000000000001"
repeatCount="indefinite"
keyTimes="0;0.5;1"
values="0;1;1">
</animate>
</path>
<path d="M150,150h30C180,67.2,112.8,0,30,0v30C96.3,30,150,83.7,150,150z" fill="#000000">
<animate attributeName="opacity"
from="0"
to="1"
dur="1.1s"
begin="0.22000000000000003"
repeatCount="indefinite"
keyTimes="0;0.5;1"
values="0;1;1">
</animate>
</path>
</g>
</svg>`
export default function (){
return <span className="broadcast-loader"
dangerouslySetInnerHTML={{ __html: svgString }} />
}
|
src/utils/domUtils.js | roderickwang/react-bootstrap | import React from 'react';
import canUseDom from 'dom-helpers/util/inDOM';
import getOwnerDocument from 'dom-helpers/ownerDocument';
import getOwnerWindow from 'dom-helpers/ownerWindow';
import contains from 'dom-helpers/query/contains';
import activeElement from 'dom-helpers/activeElement';
import getOffset from 'dom-helpers/query/offset';
import offsetParent from 'dom-helpers/query/offsetParent';
import getPosition from 'dom-helpers/query/position';
import css from 'dom-helpers/style';
function ownerDocument(componentOrElement) {
let elem = React.findDOMNode(componentOrElement);
return getOwnerDocument((elem && elem.ownerDocument) || document);
}
function ownerWindow(componentOrElement) {
let doc = ownerDocument(componentOrElement);
return getOwnerWindow(doc);
}
//TODO remove in 0.26
function getComputedStyles(elem) {
return ownerDocument(elem).defaultView.getComputedStyle(elem, null);
}
/**
* Get the height of the document
*
* @returns {documentHeight: number}
*/
function getDocumentHeight() {
return Math.max(document.documentElement.offsetHeight, document.height, document.body.scrollHeight, document.body.offsetHeight);
}
/**
* Get an element's size
*
* @param {HTMLElement} elem
* @returns {{width: number, height: number}}
*/
function getSize(elem) {
let rect = {
width: elem.offsetWidth || 0,
height: elem.offsetHeight || 0
};
if (typeof elem.getBoundingClientRect !== 'undefined') {
let {width, height} = elem.getBoundingClientRect();
rect.width = width || rect.width;
rect.height = height || rect.height;
}
return rect;
}
export default {
canUseDom,
css,
getComputedStyles,
contains,
ownerWindow,
ownerDocument,
getOffset,
getDocumentHeight,
getPosition,
getSize,
activeElement,
offsetParent
};
|
src/components/EditorWidgets/Markdown/MarkdownPreview/index.js | Aloomaio/netlify-cms | import PropTypes from 'prop-types';
import React from 'react';
import { markdownToHtml } from 'EditorWidgets/Markdown/serializers';
const MarkdownPreview = ({ value, getAsset }) => {
if (value === null) {
return null;
}
const html = markdownToHtml(value, getAsset);
return <div className="nc-widgetPreview" dangerouslySetInnerHTML={{__html: html}}></div>;
};
MarkdownPreview.propTypes = {
getAsset: PropTypes.func.isRequired,
value: PropTypes.string,
};
export default MarkdownPreview;
|
src/views/NavigatorView/index.js | r1cebank/EventCore | import React from 'react';
// Include global
import { Views } from '../../global/globalIncludes';
import { Navigator, Platform } from 'react-native';
import { connect } from 'react-redux';
import Styles from './resources/styles';
class NavigatorView extends React.Component {
renderScene(route, navigator) {
// TODO: Later will add more stuff
if (route.allSessions) {
return (
<Views.SessionsCarouselView
{...route}
navigator={navigator}
/>
);
}
if (route.filter) {
return (
<Views.FilterScreenView navigator={navigator} />
);
}
return <Views.TabView navigator={navigator} />;
}
render() {
return (
<Navigator
ref="navigator"
style={Styles.container}
configureScene={(route) => {
switch (route.routeStack) {
case 'FloatFromRight': {
return Navigator.SceneConfigs.FloatFromRight;
}
case 'FloatFromBottom': {
if (Platform.OS === 'android') {
return Navigator.SceneConfigs.FloatFromBottomAndroid;
}
return Navigator.SceneConfigs.FloatFromBottom;
}
// TODO: Add more support for routeStack
default:
return Navigator.SceneConfigs.FloatFromBottom;
}
}}
initialRoute={{}}
renderScene={this.renderScene}
/>
);
}
}
function select(store) {
return {
tab: store.navigation.tab
};
}
module.exports = connect(select)(NavigatorView);
|
src/components/Header/Header.js | juliocanares/react-starter-kit | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react';
import styles from './Header.css';
import withStyles from '../../decorators/withStyles';
import Link from '../../utils/Link';
import Navigation from '../Navigation';
@withStyles(styles)
class Header {
render() {
return (
<div className="Header">
<div className="Header-container">
<a className="Header-brand" href="/" onClick={Link.handleClick}>
<img className="Header-brandImg" src={require('./logo-small.png')} width="38" height="38" alt="React" />
<span className="Header-brandTxt">Your Company</span>
</a>
<Navigation className="Header-nav" />
<div className="Header-banner">
<h1 className="Header-bannerTitle">React</h1>
<p className="Header-bannerDesc">Complex web apps made easy</p>
</div>
</div>
</div>
);
}
}
export default Header;
|
docs/src/app/components/pages/components/Dialog/ExampleCustomWidth.js | skarnecki/material-ui | import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
const customContentStyle = {
width: '100%',
maxWidth: 'none',
};
export default class DialogExampleCustomWidth extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false,
};
}
handleOpen = () => {
this.setState({open: true});
};
handleClose = () => {
this.setState({open: false});
};
render() {
const actions = [
<FlatButton
label="Cancel"
primary={true}
onTouchTap={this.handleClose}
/>,
<FlatButton
label="Submit"
primary={true}
onTouchTap={this.handleClose}
/>,
];
return (
<div>
<RaisedButton label="Dialog With Custom Width" onTouchTap={this.handleOpen} />
<Dialog
title="Dialog With Custom Width"
actions={actions}
modal={true}
contentStyle={customContentStyle}
open={this.state.open}
>
This dialog spans the entire width of the screen.
</Dialog>
</div>
);
}
}
|
src/svg-icons/action/room.js | xmityaz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionRoom = (props) => (
<SvgIcon {...props}>
<path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
</SvgIcon>
);
ActionRoom = pure(ActionRoom);
ActionRoom.displayName = 'ActionRoom';
ActionRoom.muiName = 'SvgIcon';
export default ActionRoom;
|
app/screens/social/feed.js | it-surya/hack-jeninvest | import React from 'react';
import {
FlatList,
View,
Image,
} from 'react-native';
import {
RkCard,
RkText, RkStyleSheet
} from 'react-native-ui-kitten';
import {Avatar} from '../../components/avatar';
import {SocialBar} from '../../components/socialBar';
import {data} from '../../data';
let moment = require('moment');
export class Feed extends React.Component {
static navigationOptions = {
title: 'Feed'.toUpperCase()
};
constructor(props) {
super(props);
this.data = data.getArticles('post');
}
_keyExtractor(post, index) {
return post.id;
}
_renderItem(info) {
return (
<RkCard style={styles.card}>
<View rkCardHeader>
<Avatar rkType='small'
style={styles.avatar}
img={info.item.user.photo}/>
<View>
<RkText rkType='header4'>{`${info.item.user.firstName} ${info.item.user.lastName}`}</RkText>
<RkText rkType='secondary2 hintColor'>{moment().add(info.item.time, 'seconds').fromNow()}</RkText>
</View>
</View>
<Image rkCardImg source={info.item.photo}/>
<View rkCardContent>
<RkText rkType='primary3'>{info.item.text}</RkText>
</View>
<View rkCardFooter>
<SocialBar/>
</View >
</RkCard>
)
}
render() {
return (
<FlatList data={this.data}
renderItem={this._renderItem}
keyExtractor={this._keyExtractor}
style={styles.container}/>
)
}
}
let styles = RkStyleSheet.create(theme => ({
container: {
backgroundColor: theme.colors.screen.scroll,
paddingVertical: 8,
paddingHorizontal: 10
},
card: {
marginVertical: 8,
},
avatar: {
marginRight: 16
}
})); |
Components/ProgressBar.web.js | tradle/tim |
import {
View,
StyleSheet
} from 'react-native'
import PropTypes from 'prop-types'
import React, { Component } from 'react';
const debug = require('debug')('tradle:app:progressbar')
class ProgressBar extends Component {
// static propTypes = {
// recipient: PropTypes.string.isRequired
// };
render() {
let { progress, width, color, height } = this.props
progress *= 10
return (
<View style={[styles.row, {borderColor: color, width: width}]}>
<View style={{flex: progress, backgroundColor: color, height: height}} />
<View style={{flex: 10 - progress, backgroundColor: '#ffffff', height: height}} />
</View>
)
}
}
var styles = StyleSheet.create({
row: {
justifyContent: 'center',
alignSelf: 'center',
flexDirection: 'row',
borderWidth: 1,
}
});
module.exports = ProgressBar
|
fields/types/number/NumberColumn.js | lastjune/keystone | import React from 'react';
import numeral from 'numeral';
import ItemsTableCell from '../../../admin/src/components/ItemsTableCell';
import ItemsTableValue from '../../../admin/src/components/ItemsTableValue';
var NumberColumn = React.createClass({
displayName: 'NumberColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
let value = this.props.data.fields[this.props.col.path];
if (!value || isNaN(value)) return null;
let formattedValue = (this.props.col.path === 'money') ? numeral(value).format('$0,0.00') : value;
return formattedValue;
},
render () {
return (
<ItemsTableCell>
<ItemsTableValue field={this.props.col.type}>
{this.renderValue()}
</ItemsTableValue>
</ItemsTableCell>
);
}
});
module.exports = NumberColumn;
|
src/containers/LiveHelp/index.js | TUIHackfridays/tuise-poc | import React from 'react'
const LiveHelp = () =>
<div>
The live help page
</div>
const styles = {
}
export default LiveHelp
|
templates/react-redux/app/containers/DevTools.js | grvcoelho/starhopper | import React from 'react'
import { createDevTools } from 'redux-devtools'
import LogMonitor from 'redux-devtools-log-monitor'
import DockMonitor from 'redux-devtools-dock-monitor'
export default createDevTools(
<DockMonitor
toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-w"
>
<LogMonitor />
</DockMonitor>
)
|
examples/nested/src/client/index.js | ericf/react-intl | import React from 'react';
import ReactDOM from 'react-dom';
import {addLocaleData, IntlProvider} from 'react-intl';
import enLocaleData from 'react-intl/locale-data/en';
import App from './components/app';
addLocaleData(enLocaleData);
const {locale, messages} = window.App;
ReactDOM.render(
<IntlProvider
locale={locale}
messages={messages.app}
>
<App getIntlMessages={(namespace) => messages[namespace]} />
</IntlProvider>,
document.getElementById('container')
);
|
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/StateNotDefinedButUsed.js | facebook/flow | // @flow
import React from 'react';
class MyComponent1 extends React.Component {
render() {
return this.state.children;
}
}
class MyComponent2 extends React.Component {
render() {
const state = {};
return state;
}
}
const expression1 = () =>
class extends React.Component {
render() {
return this.state.children;
}
}
const expression2 = () =>
class extends React.Component {
render() {
const state = {};
return state;
}
}
|
src/svg-icons/hardware/smartphone.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareSmartphone = (props) => (
<SvgIcon {...props}>
<path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"/>
</SvgIcon>
);
HardwareSmartphone = pure(HardwareSmartphone);
HardwareSmartphone.displayName = 'HardwareSmartphone';
HardwareSmartphone.muiName = 'SvgIcon';
export default HardwareSmartphone;
|
ui/mobile/src/screens/VitezoveKategorieScreen.js | ivosh/jcm2018 | import React from 'react';
import { Dimensions, StyleSheet, View } from 'react-native';
import moment from 'moment';
import VitezKategorie from '../components/VitezKategorie';
import PopisekKategorie from '../components/Popisek/PopisekKategorie';
const kategorie = {
pohlavi: 'muž',
typ: 'maraton',
vek: { min: 18, max: 30 }
};
const prvni = {
cas: moment.duration('PT4H15M32.45S'),
jmeno: 'Václav Zakouřil',
narozeni: 1945,
umisteni: 1
};
const druhy = {
cas: moment.duration('PT2H17M29.14S'),
jmeno: 'Roman Smeták',
narozeni: 1986,
umisteni: 2
};
const treti = {
cas: moment.duration('PT3H27M42.38S'),
jmeno: 'František Beran',
narozeni: 1974,
umisteni: 3
};
const VitezoveKategorieScreen = () => (
<View style={styles.container}>
<View style={styles.kategorieContainer}>
<View style={styles.kategorie}>
<PopisekKategorie {...kategorie} />
</View>
</View>
<View style={styles.vitezove}>
<VitezKategorie containerStyle={styles.vitez} {...treti} />
<VitezKategorie containerStyle={styles.vitez} {...prvni} />
<VitezKategorie containerStyle={styles.vitez} {...druhy} />
</View>
</View>
);
export default VitezoveKategorieScreen;
const styles = StyleSheet.create({
container: {
backgroundColor: '#fff',
flex: 1,
justifyContent: 'space-between',
paddingBottom: 10,
paddingTop: 30
},
kategorie: {
backgroundColor: '#b0ffb5',
borderRadius: 8,
borderWidth: 2,
padding: 8
},
kategorieContainer: {
alignItems: 'center',
marginBottom: 20,
marginTop: 10
},
vitez: {
margin: 10,
width: Dimensions.get('window').height / 3
},
vitezove: {
flexDirection: 'row',
justifyContent: 'space-evenly'
}
});
|
src/Login.js | budasuyasa/warungapp | /* @flow */
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
Image,
Alert,
AsyncStorage,
} from 'react-native';
import {
Button
} from 'react-native-elements';
import {
EndpointURL,
LocalStorage
} from './Config';
import { realmWarung } from './realm/RealmWarung';
import { createStore } from 'redux';
import { reducer, actionCreators } from './redux/LoginRedux';
const backgroundImage = require('./images/background.png');
const store = createStore(reducer);
const FBSDK = require('react-native-fbsdk');
const {
LoginButton,
AccessToken
} = FBSDK;
export default class Login extends Component {
static navigationOptions = {
title: 'Login',
};
state = {
};
initUser(token) {
console.log('Login: Get facebook user data');
fetch('https://graph.facebook.com/v2.5/me?fields=email,name,friends&access_token=' + token)
.then((response) => response.json())
.then((json) => {
console.log(token);
this._login(json.email, json.name, 'facebook', token);
})
.catch(() => {
reject('ERROR GETTING DATA FROM FACEBOOK')
})
}
_login = async (email, name, type, token) => {
console.log('Login to server...')
try {
console.log(EndpointURL.LOGIN);
const response = await fetch(EndpointURL.LOGIN, {
method: 'post',
headers: {'Content-Type':'application/x-www-form-urlencoded','Accept': 'application/json'},
body: `email=${email}&name=${name}&type=${type}&token=${token}`
});
const userData = await response.json();
console.log(userData);
this._saveLocalStorage(userData);
} catch (e) {
console.log(e);
this.setState({loading: false, error: true});
}
}
_saveLocalStorage = async (res) => {
console.log('Login: save user data to local storage');
try {
await AsyncStorage.setItem(LocalStorage.userAccessToken, res.userAccessToken);
await AsyncStorage.setItem(LocalStorage.userEmail, res.userEmail);
await AsyncStorage.setItem(LocalStorage.userName, res.userName);
await AsyncStorage.setItem(LocalStorage.isUserLogedIn, '1'); //set 1 untuk login
//Finish login screen
this.props.navigation.goBack();
} catch (e) {
console.log(e);
console.log('Failed to save local data');
}
//Save liked warung to realm
try {
console.log('Saving user preferences...');
console.log(res.likedWarung);
realmWarung.write(()=>{
res.likedWarung.forEach((values)=>{
realmWarung.create('Warungs', values, true);
});
});
} catch(e){
console.log(e);
}
}
render() {
return (
<Image source={backgroundImage} style={styles.bg} >
<View style={styles.container}>
<Text style={styles.text} >
Sign In untuk dapat mengulas dan menambahkan warung baru. Simpan warung yang kamu suka sekali untuk selamanya
</Text>
<LoginButton
publishPermissions={["publish_actions"]}
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
const { accessToken } = data;
this.initUser(accessToken);
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
</View>
</Image>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding:20
},
bg: {
flex: 1,
width: null,
height: null,
},
text: {
marginBottom: 20,
fontSize: 16,
fontWeight: 'bold',
color: 'white',
textAlign: 'center'
},
});
|
react-flux-mui/js/material-ui/src/svg-icons/device/screen-lock-rotation.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceScreenLockRotation = (props) => (
<SvgIcon {...props}>
<path d="M23.25 12.77l-2.57-2.57-1.41 1.41 2.22 2.22-5.66 5.66L4.51 8.17l5.66-5.66 2.1 2.1 1.41-1.41L11.23.75c-.59-.59-1.54-.59-2.12 0L2.75 7.11c-.59.59-.59 1.54 0 2.12l12.02 12.02c.59.59 1.54.59 2.12 0l6.36-6.36c.59-.59.59-1.54 0-2.12zM8.47 20.48C5.2 18.94 2.86 15.76 2.5 12H1c.51 6.16 5.66 11 11.95 11l.66-.03-3.81-3.82-1.33 1.33zM16 9h5c.55 0 1-.45 1-1V4c0-.55-.45-1-1-1v-.5C21 1.12 19.88 0 18.5 0S16 1.12 16 2.5V3c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1zm.8-6.5c0-.94.76-1.7 1.7-1.7s1.7.76 1.7 1.7V3h-3.4v-.5z"/>
</SvgIcon>
);
DeviceScreenLockRotation = pure(DeviceScreenLockRotation);
DeviceScreenLockRotation.displayName = 'DeviceScreenLockRotation';
DeviceScreenLockRotation.muiName = 'SvgIcon';
export default DeviceScreenLockRotation;
|
src/browser/lib/logRenderTime.js | jks8787/este-experimental-app | import Component from 'react-pure-render/component';
import React from 'react';
// When UI renders thousands components, it's useful to check render time.
// Example:
// @logRenderTime
// export default class App extends Component {}
export default function logRenderTime(BaseComponent) {
return class LogRenderTime extends Component {
componentWillUpdate() {
this.start = Date.now();
}
componentDidUpdate() {
const total = Date.now() - this.start;
console.log(`[ESTE] logRenderTime: ${total}ms`); // eslint-disable-line no-console, no-undef
}
render() {
return <BaseComponent {...this.props} />;
}
};
}
|
front/app/js/components/controls/Alert.js | nudoru/React-Starter-3 | import React from 'react';
import {css} from 'emotion';
import { withStyles, styleComponentPropTypes, createClassNameFromProps } from './common/StyleManager';
import {joinClasses, omit} from '../../utils/componentUtils';
import Link from './Anchor';
const componentStyle = css`
border-left-width: 5px;
`;
class BAlert extends React.PureComponent {
render() {
return (
<div className={joinClasses(createClassNameFromProps(this.props), componentStyle)} role="alert">{this.props.children}</div>
);
}
}
export const Alert = withStyles('alert')(BAlert);
export const AlertHeading = props => <h4
className='alert-heading'>{props.children}</h4>;
export const AlertLink = ({className, ...rest}) => {
let cleanedProps = omit(styleComponentPropTypes, rest);
return <Link
className={joinClasses('alert-link', className)} {...cleanedProps}/>;
};
export const AlertClose = (props) => <button type="button" className="close" data-dismiss="alert" aria-label="Close" {...props}>
<span aria-hidden="true">×</span>
</button>; |
src/js/components/Paragraph/stories/CustomThemed/Themed.js | HewlettPackard/grommet | import React from 'react';
import { Grommet, Paragraph } from 'grommet';
import { deepMerge } from 'grommet/utils';
import { grommet } from 'grommet/themes';
const customTheme = deepMerge(grommet, {
paragraph: {
font: {
family: 'Comic Sans MS',
},
},
});
export const Themed = () => (
<Grommet theme={customTheme}>
<Paragraph>
The font family for this paragraph is being defined by a custom theme.
</Paragraph>
</Grommet>
);
Themed.parameters = {
chromatic: { disable: true },
};
export default {
title: 'Type/Paragraph/Custom Themed/Themed',
};
|
frontend/src/components/player/ButtonMenu.js | OwenRay/Remote-MediaServer | import React, { Component } from 'react';
import { Button } from 'react-materialize';
class ButtonMenu extends Component {
shouldComponentUpdate() {
return false;
}
onSelect(item) {
this.props.onSelect(this.props.type, item.value);
}
render() {
const { items, type } = this.props;
if (!items || items.length <= 1) {
return (<div />);
}
return (
<Button
icon={{ video: 'videocam', audio: 'audiotrack', subtitles: 'subtitles' }[type]}
fab="vertical"
floating
>
<div className="collection">
{items.map(item =>
(<span className="collection-item" key={item.value} onClick={() => { this.onSelect(item); }}>
{item.label}
</span>))}
</div>
</Button>
);
}
}
export default ButtonMenu;
|
web_frontend/src/containers/DevTools/DevTools.js | suribit/Lucy25 | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor toggleVisibilityKey="ctrl-H"
changePositionKey="ctrl-Q">
<LogMonitor />
</DockMonitor>
);
|
app/views/Wedding.js | mziemer21/wedding | import React, { Component } from 'react';
import { Grid, Row, Col, Modal, Button } from 'react-bootstrap';
// images
import heart from '../assets/img/glyphicons/glyphicons_012_heart_b.png';
import bell from '../assets/img/glyphicons/glyphicons_333_bell_b.png';
import cake from '../assets/img/glyphicons/glyphicons_272_cake_b.png';
import beer from '../assets/img/glyphicons/glyphicons_274_beer_b.png';
import piano from '../assets/img/glyphicons/glyphicons_328_piano_b.png';
import airplane from '../assets/img/glyphicons/glyphicons_038_airplane_b.png';
import sun from '../assets/img/glyphicons/glyphicons_231_sun_b.png';
import fire from '../assets/img/glyphicons/glyphicons_022_fire_b.png';
import suitcase from '../assets/img/glyphicons/glyphicons_357_suitcase_b.png';
export default class Wedding extends Component {
constructor() {
super();
this.state = {
showModal: false
};
}
close() {
this.setState({ showModal: false });
}
open() {
this.setState({ showModal: true });
}
render() {
return (
<Grid>
<Row>
<Col sm={4}>
<h3>
<img src={heart} alt="Icon" />
When & Where
</h3>
<p>Our big day is on Friday, August 5th 2016 in Half Moon Bay, California. The ceremony will begin 4pm in the gardens of the Oceano Hotel and Spa, cocktail hour will follow, and the reception will take place in the Gatehouse next to the gardens.</p>
</Col>
<Col sm={4}>
<h3>
<img src={bell} alt="Icon" />
Ceremony
</h3>
<p>Our ceremony will start promptly at 4:00 pm. Sunglasses and sunscreen are advised as the ceremony will be near the Pacific Ocean.</p>
</Col>
<Col sm={4}>
<h3>
<img src={cake} alt="Icon" />
Reception
</h3>
<p>The reception will follow cocktail hour. The reception venue is booked until 11pm. We may go to nearby bars following the reception.</p>
</Col>
</Row>
<Row>
<Col sm={4}>
<h3>
<img src={beer} alt="Icon" />
Food & Drink
</h3>
<p>Cocktail hour will follow the ceremony where hors d'oeuvres, beer, and wine will be served. We will have a seated dinner (menus will be sent with the invitations). Cash bar will be provided with a signature bride and groom drink.</p>
</Col>
<Col sm={4}>
<h3>
<img src={piano} alt="Icon" />
Live Music
</h3>
<p>A String Trio will be performing at the ceremony and cocktail hour. A DJ will be at the reception.</p>
</Col>
<Col sm={4}>
<h3>
<img src={airplane} alt="Icon" />
Travel Info
</h3>
<p>If you will be flying from out of state, SFO & SJC are the nearest airports. Once you land there are many<a onClick={() => this.open()}> options</a> to get you to your <a href="https://www.google.com/maps/d/edit?mid=zAvDyE98WIgM.kr-wK2DRr-Fo&usp=sharing" target="_blank">destination</a>. However, if you choose to drive, ample parking is provided at the venue. </p>
<Modal show={this.state.showModal} onHide={() => this.close()}>
<Modal.Header closeButton>
<Modal.Title>Driving Options</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>If you would like to get a rental car from <a href="https://www.hertz.com/rentacar/reservation/" target="_blank">Hertz</a>, use CDP #77694 to get 25% off.</p>
<p>Alternativly if you don't want to drive, <a href="https://www.lyft.com/" target="_blank">Lyft</a> and <a href="https://www.uber.com/" target="_blank">Uber</a> are very popular in the bay area (and cheaper than a taxi). You can use lyft code MATTHEW930848, or Uber code 8vxu5 for $20.</p>
<div className="embed-responsive embed-responsive-4by3">
<iframe src="https://www.google.com/maps/d/embed?mid=zAvDyE98WIgM.kr-wK2DRr-Fo" className="embed-responsive-item"></iframe>
</div>
</Modal.Body>
<Modal.Footer>
<Button onClick={() => this.close()}>Close</Button>
</Modal.Footer>
</Modal>
</Col>
</Row>
<Row>
<Col sm={4}>
<h3>
<img src={sun} alt="Icon" />
Weather Forcast
</h3>
<p>The weather in Half Moon Bay is generally sunny and in the 70s. Please check the <a href="http://www.wunderground.com/cgi-bin/findweather/getForecast?query=pws:KCAHALFM22" target="_blank">local forecast</a> before leaving.</p>
</Col>
<Col sm={4}>
<h3>
<img src={fire} alt="Icon" />
Before & After
</h3>
<p>We highly recommend exploring Half Moon Bay and Pacifica. If you have time, San Francisco and Napa are great adventures as well. Yosemite is ~3.5 hours away. If enough people show interest, Kaitlin can book a Napa wine tour for everyone. A shuttle would pick us up at the Oceano Hotel. </p>
</Col>
<Col sm={4}>
<h3>
<img src={suitcase} alt="Icon" />
Stay With Us
</h3>
<p>We will be staying at the hotel and would love for you to join us. We have blocked off many rooms at our venue. Please call the <a href="http://www.oceanohalfmoonbay.com/" target="_blank">Oceano</a> and ask for the Leary Ziemer wedding. You will receive a discount by doing so. Alternatively, there are many <a href="http://www.kayak.com/hotels/Half-Moon-Bay,CA-c12087/2016-08-04/2016-08-07/2guests" target="_blank">hotels</a> and <a href="https://www.airbnb.com/s/Half-Moon-Bay--CA?checkin=08%2F04%2F2016&checkout=08%2F07%2F2016&guests=2&ss_id=80pw7km9" target="_blank">Airbnbs</a> nearby.</p>
</Col>
</Row>
</Grid>
);
}
}
|
src/containers/start/start.js | noahehall/udacity-trainschedule | import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Table } from 'reactabular';
import * as actionCreators from 'store/actions/index.js';
import * as dom from 'lib/dom.js';
import * as forms from 'components/forms/forms.js';
import * as time from 'lib/time.js';
// now using my github:noahehall/idb#isomorphic-imports
import Idbstore from 'serviceworkers/idb/idb';
import Popup from 'react-popup';
import React from 'react';
import ShowHistory from 'components/showhistory/showhistory';
import Stationinfo from 'components/stationinfo/stationinfo.js';
import styles from './start.css';
class Start extends React.Component {
static propTypes = {
appError: React.PropTypes.object.isRequired,
dispatch: React.PropTypes.object.isRequired,
randomSchedule: React.PropTypes.bool.isRequired,
schedules: React.PropTypes.object.isRequired,
stationInfo: React.PropTypes.object,
stations: React.PropTypes.object.isRequired,
urls: React.PropTypes.object.isRequired,
}
constructor (props) {
super(props);
this.state = {
departing: true,
m : time.moment(),
};
}
componentDidMount () {
// get stations
if (!this.props.randomSchedule)
this.props.dispatch.getBart({ type: 'stations', url: appFuncs.stationUrl() });
if (Idbstore) {
const db = new Idbstore();
// get all bart urls and hydrate store
db.getKeysMatching(undefined, 'http://api.bart.gov/')
.then((keysArray) => keysArray.forEach((key) => {
if (key.includes('http://api.bart.gov/api/sched.aspx'))
return this.props.dispatch.getBart({
hydrate: true,
type: 'schedules',
url: key,
});
if (key.includes('http://api.bart.gov/api/stn.aspx'))
return this.props.dispatch.getBart({
hydrate: true,
type: 'stationInfo',
url: key,
});
return null;
})
);
} else appFuncs.console('info')('db not found!');
}
componentWillReceiveProps (nextProps) {
// get initial schedule
if (!this.props.randomSchedule && !nextProps.randomSchedule) return this.getInitialSchedule(nextProps);
return false;
}
/**
* Gets a schedule on load
* @method getInitialSchedule
* @param {[type]} nextProps [description]
* @return {[type]} [description]
*/
getInitialSchedule = (nextProps) => {
try {
const latestStation = this.props.urls.stations[0];
const options = nextProps.stations.data[latestStation].stations[0].station.asMutable();
// get first and second stations
const
from = options[0],
scheduleConfigDepartBool = true,
to = options[1];
const
fromAbbr = from.abbr[0],
toAbbr = to.abbr[0];
// get random schedule
const url = appFuncs.scheduleUrl({
from: fromAbbr,
scheduleConfigDepartBool,
to: toAbbr,
});
if (this.props.schedules.data[url]) {
this.props.dispatch.urlCache('schedules', url);
this.props.dispatch.gotRandomSchedule(!this.props.randomSchedule);
} else {
this.props.dispatch.getBart({ type: 'schedules', url });
this.props.dispatch.gotRandomSchedule(!this.props.randomSchedule);
}
return true;
} catch (err) {
return false;
}
}
dateFormat = () =>
this.state.m.format(time.getDateFormat());
timeFormat = () =>
this.state.m.format(time.getTimeFormat());
/**
* Handle submission of get schedule form
* @method handleSubmit
* @param {[type]} e [description]
* @return {[type]} [description]
*/
handleSubmit = (e) => {
if (!e) return false;
if (e.preventDefault) e.preventDefault();
if (e.stopPropagation) e.stopPropagation();
const
scheduleConfigDepartBool = this.state.departing,
thisTarget = e.currentTarget || e;
const
arrive = thisTarget['arrive-station'].value,
dateTime = time.getBartTime(
`${this.state.m.format(time.getTodaysDate())}T${this.state.m.format(time.getRightNowTime())}`
),
depart = thisTarget['depart-station'].value,
options = thisTarget['stations-select'].options;
let
from,
fromAbbr,
to,
toAbbr;
try {
to = Array.from(options).find((opt) => opt.value === arrive);
from = Array.from(options).find((opt) => opt.value === depart);
fromAbbr = from.dataset.abbr;
toAbbr = to.dataset.abbr;
} catch (err) {
return this.props.dispatch.appError('The selected stations do not exist');
}
const
thisDate = dateTime.substring(0, dateTime.indexOf(' ')).trim(),
thisTime = dateTime.substring(dateTime.indexOf(' ')).trim();
const url = appFuncs.scheduleUrl({
date: thisDate,
from: fromAbbr,
scheduleConfigDepartBool,
time: thisTime,
to: toAbbr,
});
if (this.props.schedules.data[url])
return this.props.dispatch.urlCache('schedules', url);
return from && to ?
this.props.dispatch.getBart({
type: 'schedules',
url,
}) :
null;
}
/**
* handle submission of get stations form
* @method getStations
* @param {[type]} e [description]
* @return {[type]} [description]
*/
getStations = (e) => {
const latestStation = this.props.urls.stations[0];
if (e) {
e.preventDefault();
e.stopPropagation();
return latestStation === appFuncs.stationUrl() ?
false :
this.props.dispatch.getBart({ type: 'stations', url: appFuncs.stationUrl() });
}
let stations;
try {
stations = this.props.stations.data[latestStation].stations[0].station.map((station, idx) =>
<option
data-abbr={station.abbr}
data-address={station.address}
data-city={station.city}
data-county={station.county}
data-name={station.name}
data-state={station.state}
data-zipcode={station.zipcode}
key={`${station.abbr}${idx}`}
>
{station.name}
</option>
);
} catch (err) {
stations = 'Please click the button above to get stations';
}
return stations;
}
/**
* get a specific station
* @method getStation
* @param {[type]} e [description]
* @return {[type]} [description]
*/
getStation = (e) => {
e.stopPropagation();
e.preventDefault();
let abbr, url;
try {
const latestStation = this.props.urls.stations[0];
abbr = `${this.props.stations.data[latestStation].stations[0].station.find((station) =>
station.name[0] === e.currentTarget.value
).abbr[0] }`;
url = appFuncs.stationInfoUrl({ from: abbr });
} catch (err) {
abbr = abbr || '';
} finally {
if (url && this.props.stationInfo.data && this.props.stationInfo.data[url])
this.props.dispatch.urlCache('stationInfo', url);
else if (url)
this.props.dispatch.getBart({ type: 'stationInfo', url });
return dom.setNextInnerHtml(e.currentTarget, abbr);
}
}
/**
* Get more info about a station
* @method getMoreInfo
* @param {[type]} e [description]
* @return {[type]} [description]
*/
getMoreInfo = (e) => {
e.preventDefault();
e.stopPropagation();
if (!navigator || !navigator.onLine) return null;
let thisEl;
const
abbr = e.currentTarget.dataset.abbr,
stationinfo = {
abbr: undefined,
address: undefined,
city: undefined,
county: undefined,
name: undefined,
thisEl: undefined,
zipcode: undefined,
};
try {
const latestStation = this.props.urls.stations[0];
thisEl = this.props.stations.data[latestStation].stations[0].station.find((station) =>
station.abbr[0] === abbr
);
if (thisEl) {
stationinfo.name = thisEl.name[0];
stationinfo.abbr = thisEl.abbr[0];
stationinfo.city = thisEl.city[0];
stationinfo.county = thisEl.county[0];
stationinfo.zipcode = thisEl.zipcode[0];
stationinfo.address = thisEl.address[0];
}
} catch (err) {
// do nothing
}
if (abbr) {
const url = appFuncs.stationInfoUrl({ from: abbr });
let stationExtraInfo;
try {
stationExtraInfo = this.props.stationInfo.data[url];
} catch (err) {
stationExtraInfo = {};
}
if (!stationExtraInfo.uri)
this.props.dispatch.getBart({ type: 'stationInfo', url });
return Popup.create({
buttons: {
// left: ['cancel'],
right: [{
action: (popup) => popup.close(),
text: 'Ok',
// className: 'special-btn', // optional
}]
},
className: 'alert',
content: <Stationinfo {...stationinfo} stationExtraInfo={stationExtraInfo} /> || 'No information found',
title: stationinfo.name ? `${stationinfo.name} Station Information` : 'Bart Station Information',
});
}
return false;
}
/**
* flip schedule config type and possibly update schedule if both input controls have valid stations
* @method switchScheduleConfig
* @param {[type]} e [description]
* @return {[type]} [description]
*/
switchScheduleConfig = (e) => {
e.preventDefault();
e.stopPropagation();
this.setState({ departing: !this.state.departing });
}
/**
* returns renderable list
* @method getSavedSchedules
* @param {Array} allSchedules this.props.schedules.data.schedule[0].request[0].trip
* @return {HTMLElement|null} [description]
*/
getSavedSchedules = (allSchedules) => {
if (!Array.isArray(allSchedules) || !allSchedules.length) return null;
try {
const tableData = allSchedules.map((trip, idx) => ({
arriveAt: `${trip.$.destTimeMin} ${trip.$.destTimeDate}`,
duration: time.getDuration({
endDate: trip.$.destTimeDate,
endTime: trip.$.destTimeMin,
startDate: trip.$.origTimeDate,
startTime: trip.$.origTimeMin,
}),
id: idx,
leaveAt: `${trip.$.origTimeMin} ${trip.$.origTimeDate}`,
}));
const tableColumns = [
{ header: { label: 'Departure' }, property: 'leaveAt' },
{ header: { label: 'Arrival' }, property: 'arriveAt' },
{ header: { label: 'Duration' }, property: 'duration' },
];
return [
<section
className='fare'
key='01'
>
<sup>$</sup>{allSchedules[0].$.fare}
</section>,
<Table.Provider
className='striped'
columns={tableColumns}
key='02'
>
<Table.Header />
<Table.Body
rowKey='id'
rows={tableData}
/>
</Table.Provider>
];
} catch (err) {
appFuncs.console('error')(`error received in getSavedSchedules: ${err}`);
return null;
}
}
renderSchedules = ({
errMsg,
schedule,
stations,
status
}) => {
if (status !== 'SUCCESS' || errMsg) return null;
const formattedSchedules = this.getSavedSchedules(schedule);
return formattedSchedules ?
<div className='schedules'>
<section style={{ textAlign: 'center' }}>
{stations.origin && <div>From: {stations.origin}</div>}
{stations.destination && <div>To: {stations.destination}</div>}
</section>
{formattedSchedules}
</div> :
null;
}
renderErrors = (e) => e ? <h1>{e}</h1> : null;
handleClockChange = (m) =>
this.setState({ m: m });
handleClockSave = () =>
document.getElementsByClassName("m-input-moment")[0].style.display = 'none';
handleClockShowDate = () =>
document.getElementsByClassName("m-input-moment")[0].style.display = 'block';
handleClockShowTime = () =>
document.getElementsByClassName("m-input-moment")[0].style.display = 'block';
render () {
let
errMsg = '',
schedule = [],
stations = {},
status = '';
try {
errMsg = this.props.appError.msg;
schedule = this.props.schedules.data[this.props.urls.schedules[0]].schedule[0].request[0].trip;
stations = {
destination: this.props.schedules.data[this.props.urls.schedules[0]].destination[0],
origin: this.props.schedules.data[this.props.urls.schedules[0]].origin[0],
};
status = this.props.schedules.status;
} catch (err) {
// do nothing
}
return (
<div className='start'>
<style scoped type='text/css'>{styles}</style>
{this.renderErrors(errMsg)}
<section id='start-forms'>
{forms.makeStationForm({
departing: this.state.departing,
getStations: this.getStations,
hasStations: this.props.urls.stations.length,
switchScheduleConfig: this.switchScheduleConfig,
})}
{
this.props.stations.status === 'SUCCESS' &&
forms.makeScheduleForm({
dateFormat: this.dateFormat,
getMoreInfo: this.getMoreInfo,
getStation: this.getStation,
getStations: this.getStations,
handleClockChange: this.handleClockChange,
handleClockSave: this.handleClockSave,
handleClockShow: this.handleClockShowTime,
handleClockShowDate: this.handleClockShowDate,
handleSubmit: this.handleSubmit,
Popup,
thisMoment: this.state.m,
timeFormat: this.timeFormat,
})
}
</section>
<section>
{this.renderSchedules({
errMsg,
schedule,
stations,
status
})}
</section>
<ShowHistory
data={this.props.urls}
dispatch={this.props.dispatch}
type='schedules'
/>
</div>
);
}
}
const mapStateToProps = (state) =>
({
appError: state.appError,
randomSchedule: state.gotRandomSchedule,
schedules: state.gotSchedules,
stationInfo: state.gotStationInfo,
stations: state.gotStations,
urls: state.urlCache,
});
const mapDispatchToProps = (dispatch) =>
({
dispatch: bindActionCreators(actionCreators, dispatch),
});
export default connect(mapStateToProps, mapDispatchToProps)(Start);
|
src/website/app/Paragraph.js | mineral-ui/mineral-ui | /* @flow */
import styled from '@emotion/styled';
import React from 'react';
import type { StyledComponent } from '@emotion/styled-base/src/utils';
type Props = {
/* rendered chilren */
children: React$Node,
/* available font variants */
variant?: 'ui' | 'prose' | 'mouse'
};
const componentTheme = (baseTheme) => ({
Paragraph_color: baseTheme.color,
Paragraph_fontSize_mouse: baseTheme.fontSize_mouse,
Paragraph_fontSize_prose: baseTheme.fontSize_prose,
Paragraph_fontSize_ui: baseTheme.fontSize_ui,
Paragraph_lineHeight_normal: baseTheme.lineHeight,
Paragraph_lineHeight_prose: baseTheme.lineHeight_prose,
...baseTheme
});
const Root: StyledComponent<{ [key: string]: any }> = styled('p')(
({ variant, theme: baseTheme }) => {
let theme = componentTheme(baseTheme);
return {
color: theme.Paragraph_color,
fontSize: theme[`Paragraph_fontSize_${variant}`],
lineHeight:
variant === 'prose'
? theme.Paragraph_lineHeight_prose
: theme.Paragraph_lineHeight_normal
};
}
);
const Paragraph = (props: Props) => {
const { children, variant, ...restProps } = props;
return (
<Root variant={variant} {...restProps}>
{children}
</Root>
);
};
Paragraph.defaultProps = {
variant: 'ui'
};
export default Paragraph;
|
src/components/Match.js | kangarang/mp-react | import React from 'react'
export default(props) => {
const styles = {
container: {
minWidth: '48%',
display: 'flex',
justifyContent: 'space-around',
textAlign: "left",
padding: ".5em .5em 1em .5em"
},
wrapper: {
color: "#262626"
},
match: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
backgroundColor: "#fcfcfc",
borderRadius: '0 0 15px 15px',
border: '.15em solid #525252',
padding: '.5em 1em',
boxShadow: '0 0 .8em #525252'
},
majority: {
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-around',
},
picture: {
padding: ".5em .75em"
},
circle: {
display: 'flex',
justifyContent: "center",
width: '10em',
height: '10em',
overflow: 'hidden',
borderRadius: '50%',
border: '.3em solid #69c7c4',
boxShadow: '0 0 .8em .1em',
backgroundColor: "grey"
},
image: {
width: "auto",
height: '100%'
},
table: {
paddingLeft: ".5em"
},
rightTable: {
padding: "0 .5em"
},
bottom: {},
numbDiv: {
padding: "0.5em 0"
},
numbers: {
margin: 0,
padding: "0.1em 0"
},
buttonDiv: {
width: "100%",
display: "flex",
justifyContent: "space-around",
padding: ".25em 0"
},
noButt: {
backgroundColor: "#ed797a",
color: "white",
borderRadius: "5px",
border: '.08em solid #525252',
fontSize: "1.5em",
width: "4em",
height: "2em"
},
yesButt: {
backgroundColor: "#69c7c4",
color: "white",
borderRadius: "5px",
border: '.08em solid #525252',
fontSize: "1.5em",
width: "4em",
height: "2em"
}
}
return (
<div style={styles.container}>
<div style={styles.wrapper}>
<div style={styles.match}>
<div style={styles.majority}>
<div style={styles.picture}>
<div id="circle" style={styles.circle}>
<img style={styles.image} role='presentation' src={props.user.photo_url}></img>
</div>
</div>
<table style={styles.table}>
<tbody>
<tr>
<td>Name
</td>
<td style={styles.rightTable}>Private until matched</td>
</tr>
<tr>
<td>Age
</td>
<td style={styles.rightTable}>{props.user.age}</td>
</tr>
<tr>
<td>Location
</td>
<td style={styles.rightTable}>{props.user.location}</td>
</tr>
<tr>
<td>Gender
</td>
<td style={styles.rightTable}>{props.user.gender}</td>
</tr>
<tr>
<td>Height
</td>
<td style={styles.rightTable}>{props.user.height}</td>
</tr>
<tr>
<td>Ethnicity
</td>
<td style={styles.rightTable}>{props.user.ethnicity}</td>
</tr>
<tr>
<td>Body Type
</td>
<td style={styles.rightTable}>{props.user.body_type}</td>
</tr>
<tr>
<td>Profession
</td>
<td style={styles.rightTable}>{props.user.profession}</td>
</tr>
</tbody>
</table>
</div>
<div style={styles.bottom}>
<div style={styles.numbDiv}>
<p style={styles.numbers}>
{"You have " + props.events + " events in common with this person"}
</p>
<p style={styles.numbers}>
{"You have " + props.artists + " artists in common with this person"}
</p>
<p style={styles.numbers}>
{"Click 'Yes' to find out more!"}
</p>
</div>
<div style={styles.buttonDiv}>
<button onClick={e => props.noThanks(e, props.user.id)} style={styles.noButt}>NO</button>
<button onClick={e => props.yesPlease(e, props.user.id)} style={styles.yesButt}>YES</button>
</div>
</div>
</div>
</div>
</div>
)
};
|
node_modules/react-native-form-generator/src/lib/PickerComponent.android.js | paulunits/tiptap | 'use strict';
import React from 'react';
import ReactNative from 'react-native';
let { View, StyleSheet, TextInput, Text, Picker} = ReactNative;
import {Field} from '../lib/Field';
var PickerItem = Picker.Item;
export class PickerComponent extends React.Component{
constructor(props){
super(props);
this.state = {
value: props.value || props.label,
}
this.pickerMeasures = {};
}
setValue(value){
this.setState({value:value});
if(this.props.onChange) this.props.onChange(value);
if(this.props.onValueChange) this.props.onValueChange(value);
}
handleLayoutChange(e){
let {x, y, width, height} = {... e.nativeEvent.layout};
this.setState(e.nativeEvent.layout);
//e.nativeEvent.layout: {x, y, width, height}}}.
}
handleValueChange(value){
this.setState({value:(value && value!='')?value:this.props.label});
if(this.props.onChange) this.props.onChange(value);
if(this.props.onValueChange) this.props.onValueChange(value);
}
_scrollToInput (event) {
if (this.props.onFocus) {
let handle = ReactNative.findNodeHandle(this.refs.inputBox);
this.props.onFocus(
event,
handle
)
}
// this.refs.picker.measure(this.getPickerLayout.bind(this));
}
_togglePicker(event){
this.setState({isPickerVisible:!this.state.isPickerVisible});
//this._scrollToInput(event);
}
render(){
return(<View><Field
{...this.props}
ref='inputBox'
>
<View style={[
this.props.containerStyle]}
onLayout={this.handleLayoutChange.bind(this)}>
<Text style={this.props.labelStyle}>{this.props.label}</Text>
<Picker ref='picker'
{...this.props.pickerProps}
selectedValue={this.state.value}
onValueChange={this.handleValueChange.bind(this)}
>
{Object.keys(this.props.options).map((value) => (
<PickerItem
key={value}
value={value}
label={this.props.options[value]}
/>
), this)}
</Picker>
</View>
</Field>
</View>
)
}
}
let formStyles = StyleSheet.create({
form:{
},
alignRight:{
marginTop: 7, position:'absolute', right: 10
},
noBorder:{
borderTopWidth: 0,
borderBottomWidth: 0
},
separatorContainer:{
// borderTopColor: '#C8C7CC',
// borderTopWidth: 1,
paddingTop: 35,
borderBottomColor: '#C8C7CC',
borderBottomWidth: 1,
},
separator:{
paddingLeft: 10,
paddingRight: 10,
color: '#6D6D72',
paddingBottom: 7
},
fieldsWrapper:{
// borderTopColor: '#afafaf',
// borderTopWidth: 1,
},
horizontalContainer:{
flexDirection: 'row',
justifyContent: 'flex-start'
},
fieldContainer:{
borderBottomWidth: 1,
borderBottomColor: '#C8C7CC',
backgroundColor: 'white',
justifyContent: 'center',
height: 45
},
fieldValue:{
fontSize: 34/2,
paddingLeft: 10,
paddingRight: 10,
marginRight:10,
paddingTop: 4,
justifyContent: 'center',
color: '#C7C7CC'
},
fieldText:{
fontSize: 34/2,
paddingLeft: 10,
paddingRight: 10,
justifyContent: 'center',
lineHeight: 32
},
input:{
paddingLeft: 10,
paddingRight: 10,
},
helpTextContainer:{
marginTop:9,
marginBottom: 25,
paddingLeft: 20,
paddingRight: 20,
},
helpText:{
color: '#7a7a7a'
}
});
|
examples/huge-apps/routes/Course/routes/Assignments/components/Sidebar.js | darul75/react-router | import React from 'react';
import { Link } from 'react-router';
class Sidebar extends React.Component {
//static loadProps (params, cb) {
//cb(null, {
//assignments: COURSES[params.courseId].assignments
//});
//}
render () {
//var { assignments } = this.props;
var assignments = COURSES[this.props.params.courseId].assignments
return (
<div>
<h3>Sidebar Assignments</h3>
<ul>
{assignments.map(assignment => (
<li key={assignment.id}>
<Link to={`/course/${this.props.params.courseId}/assignments/${assignment.id}`}>
{assignment.title}
</Link>
</li>
))}
</ul>
</div>
);
}
}
export default Sidebar;
|
source/index.js | zorfling/checkin | import React from 'react';
import { render } from 'react-dom';
import createApp from './App';
const App = createApp(React);
const props = {
foo: 'yay!',
title: 'Title!'
};
render(
<App { ...props }></App>,
document.getElementById('root')
);
|
app/profile/Profile.js | ccfcheng/recommendation-app | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { setPath } from '../appReducer';
import Database from '../database/Database';
import { FIREBASE_URL } from '../appConstants';
import Avatar from 'material-ui/Avatar';
import { setUserProfile } from '../login/LoginReducer';
const DB = new Database(FIREBASE_URL);
class ProfileContainer extends Component {
constructor(props) {
super(props);
this.componentWillMount = this.componentWillMount.bind(this);
}
componentWillMount() {
// Grab user info from database, load into redux
this.props.dispatch(setPath('Profile'));
return DB.profile()
.then((profile) => {
this.props.dispatch(setUserProfile(profile));
});
}
render() {
return (
<Profile
createdAt={this.props.createdAt}
email={this.props.email}
firstName={this.props.firstName}
lastName={this.props.lastName}
profileImage={this.props.profileImage}
/>
);
}
}
class Profile extends Component {
render() {
const {
createdAt,
email,
firstName,
lastName,
profileImage,
} = this.props;
return (
<div style={styles.content}>
<div style={styles.image}>
<Avatar
src={profileImage}
size={100}
/>
</div>
<div style={styles.username}>
{firstName + ' ' + lastName}
</div>
<div style={styles.email}>
Contact: {email}
</div>
<div style={styles.createdAt}>
Joined on {createdAt}
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
createdAt: state.user.createdAt,
email: state.user.email,
firstName: state.user.firstName,
lastName: state.user.lastName,
profileImage: state.user.profileImage,
};
}
export default connect(mapStateToProps)(ProfileContainer);
const styles = {
content: {
marginTop: '54px',
textAlign: 'center',
},
username: {
padding: '0.5em 0em',
fontSize: '1.5em',
fontWeight: 'bold',
},
email: {
padding: '0.5em 0em',
fontSize: '1em',
},
createdAt: {
padding: '0.5em 0em',
fontStyle: 'italic',
fontSize: '0.75em',
},
image: {
padding: '1em 0em',
}
};
|
src/index.js | noedlm/png-site | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
src/components/subcharts/WordFrequencyScatterPlot.js | nbuechler/ample-affect-exhibit | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import d3 from 'd3';
import { connect } from 'react-redux';
import DivListGroup from '../groups/DivListGroup'
import { Table, Alert } from 'react-bootstrap';
import { selectActivityDataset, fetchDataIfNeeded } from '../../actions/actions';
import SimpleScatterPlot from '../d3chartsv2/SimpleScatterPlot'
import BinScatterPlot from '../d3chartsv2/BinScatterPlot'
import BarChart from '../d3charts/BarChart'
class WordFrequencyScatterPlot extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const { dispatch } = this.props;
// dispatch(fetchDataIfNeeded('nlp-stats', '5000'));
}
render () {
// const { data, isFetching, lastUpdated } = this.props;
function prepareBinPlot(graph) {
let result = [],
key_prefix = '';
if (graph == '-') {
key_prefix = '';
} else {
key_prefix = graph + '_';
}
result.push(JSON.parse(localStorage.getItem('lastEmotion'))['order-1'][key_prefix + 'order_fdist'])
result.push(JSON.parse(localStorage.getItem('lastEmotion'))['order-2'][key_prefix + 'order_fdist'])
result.push(JSON.parse(localStorage.getItem('lastEmotion'))['order-3'][key_prefix + 'order_fdist'])
result.push(JSON.parse(localStorage.getItem('lastEmotion'))['order_1_and_2'][key_prefix + 'order_fdist'])
result.push(JSON.parse(localStorage.getItem('lastEmotion'))['order_1_and_3'][key_prefix + 'order_fdist'])
result.push(JSON.parse(localStorage.getItem('lastEmotion'))['order_2_and_3'][key_prefix + 'order_fdist'])
result.push(JSON.parse(localStorage.getItem('lastEmotion'))['all_orders'][key_prefix + 'order_fdist'])
return result;
}
function prepareBinPlotComplete(a, b, c) {
let result = [],
numOrders = a.length;
// The assumption is that each graph has the same number of orders.
for (var i = 0; i < numOrders; i++) {
result.push(a[i].concat(b[i]).concat(c[i]))
}
return result;
}
const naturalBinData = prepareBinPlot('natural');
const stemmerBinData = prepareBinPlot('stemmer');
const lemmaBinData = prepareBinPlot('lemma');
const allBinData = prepareBinPlotComplete(naturalBinData, stemmerBinData, lemmaBinData);
let rawData = allBinData,
processedData = [],
datapoint = {},
counter = 0;
for (let i of rawData) {
for (let j of i) {
datapoint = {
"word": j[0][0],
"pos": j[0][1],
"count": j[1],
"bin": counter,
}
processedData.push(datapoint)
}
counter++
}
let data = processedData;
// d3.max(<data>) should have the data with the greatest point
let maxYValue = d3.max(data, function(d) {
return +d.count;
})
let small_graph_height = 8*12
let large_graph_height = 8*50 - 4
return (
<div>
<div className="radiant--graph-wrapper">
<div style={{width: "100px"}}>
<BinScatterPlot
graphId={0}
title={'Unprocessed Freq. Dist.'}
distinctColors={false}
modulus={1}
fillColors={['none']}
data={naturalBinData}
heightPixel={small_graph_height}
widthPercent={'100'}
graphSize={'sm'}
paddingPixel={'10'}
maxYValue={maxYValue}
pointRadius={'3'}/>
<BinScatterPlot
graphId={1}
title={'Stemmed Freq. Dist.'}
distinctColors={false}
modulus={1}
fillColors={['none']}
data={stemmerBinData}
heightPixel={small_graph_height}
widthPercent={'100'}
graphSize={'sm'}
paddingPixel={'10'}
maxYValue={maxYValue}
pointRadius={'3'}/>
<BinScatterPlot
graphId={2}
title={'Lemmatized Freq. Dist.'}
distinctColors={false}
modulus={1}
fillColors={['none']}
data={lemmaBinData}
heightPixel={small_graph_height}
widthPercent={'100'}
graphSize={'sm'}
paddingPixel={'10'}
maxYValue={maxYValue}
pointRadius={'3'}/>
</div>
<div style={{width: "550px"}}>
<div style={{margin: '6 10 0 10'}}>
<BinScatterPlot
graphId={3}
title={'Synonyms Frequency Distribution'}
titleSize={'20'}
distinctColors={false}
modulus={1}
fillColors={['none']}
data={allBinData}
heightPixel={large_graph_height}
widthPercent={'100'}
graphSize={'md'}
paddingPixel={'50'}
maxYValue={maxYValue}
pointRadius={'12'}/>
</div>
</div>
</div>
{/*
<div className="radiant--graph-wrapper">
<div className="radiant--key-cell">
<div className="radiant--key-cell_color-swatch here radiant--key-cell_color-swatch_prep"></div>
Preposition
</div>
<div className="radiant--key-cell">
<div className="radiant--key-cell_color-swatch radiant--key-cell_color-swatch_noun"></div>
Noun
</div>
<div className="radiant--key-cell">
<div className="radiant--key-cell_color-swatch radiant--key-cell_color-swatch_adj"></div>
Adjective
</div>
<div className="radiant--key-cell">
<div className="radiant--key-cell_color-swatch radiant--key-cell_color-swatch_verb"></div>
Verb
</div>
<div className="radiant--key-cell">
<div className="radiant--key-cell_color-swatch radiant--key-cell_color-swatch_other"></div>
Other
</div>
</div>
*/}
<div className="radiant--key-text radiant--graph-wrapper">
Each of the columns represents a particular set of synonyms. The first column
represents the synonyms of the {this.props.emotionName}. The second column
represents the synonyms of the first columns synonyms. The pattern continues.
'I-II Words' are words that exist in both the 'I Words' and 'II Words' groups.
Similarly, 'II-III Words','II-III Words', and 'I-II--III Words' are groups
where a word exists in n-number of groups.
<br></br>
<br></br>
The graph depicts a frequency distribution of the words associated with {this.props.emotionName}.
Multiple words with the same frequency are represented as a more opaque cell.
By contrast, a single word with a frequency is represented by a transparent cell.
Color represents the part of speech.
Cells representing words with more than one part of speech are the average color value.
</div>
</div>
);
}
}
// StatsChart.propTypes = {
// data: PropTypes.array.isRequired,
// isFetching: PropTypes.bool.isRequired,
// lastUpdated: PropTypes.number,
// dispatch: PropTypes.func.isRequired
// };
//
// function mapStateToProps(state) {
// const { dataByDataset } = state;
// const {
// isFetching,
// lastUpdated,
// items: data
// } = dataByDataset['nlp-stats'] || {
// isFetching: true,
// items: []
// };
//
// return {
// data,
// isFetching,
// lastUpdated
// };
// }
// export default connect(mapStateToProps)(WordFrequencyScatterPlot);
export default WordFrequencyScatterPlot;
|
packages/slate-html-serializer/test/serialize/inline-with-data.js | ashutoshrishi/slate | /** @jsx h */
import React from 'react'
import h from '../helpers/h'
export const rules = [
{
serialize(obj, children) {
if (obj.object == 'block' && obj.type == 'paragraph') {
return React.createElement('p', {}, children)
}
if (obj.object == 'inline' && obj.type == 'link') {
return React.createElement(
'a',
{ href: obj.data.get('href') },
children
)
}
},
},
]
export const input = (
<value>
<document>
<paragraph>
<link href="https://google.com">one</link>
</paragraph>
</document>
</value>
)
export const output = `
<p><a href="https://google.com">one</a></p>
`.trim()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.