path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
test/js/release_test/PhysicsGroupTest.js | viromedia/viro | /**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import {
ViroScene,
ViroBox,
ViroMaterials,
ViroNode,
ViroImage,
ViroVideo,
ViroFlexView,
ViroUtils,
ViroText,
ViroQuad,
ViroSkyBox,
ViroSphere,
Viro3DObject,
ViroButton,
ViroSpinner,
ViroOmniLight,
ViroAnimations,
ViroDirectionalLight,
ViroController,
} from 'react-viro';
var createReactClass = require('create-react-class');
var LocalButtonImage = require("./res/icon_live.jpg");
var ReleaseMenu = require("./ReleaseMenu.js");
var GroupTestBasicPhysics = createReactClass({
getInitialState() {
return {
physicsEnabled:false,
gravityEnabled:false,
drawBounds:false,
toggleDraggable:false,
reset:false
};
},
togglePhysicsBody(tag){
return () => {
console.log("Click numeric tag: " + tag);
if (tag == 1){
this.setState({
physicsEnabled:!this.state.physicsEnabled
});
} else if (tag ==2){
this.setState({
gravityEnabled:!this.state.gravityEnabled
});
} else if (tag ==3){
this.setState({
drawBounds:!this.state.drawBounds
});
} else if (tag ==4){
this.setState({
toggleDraggable:!this.state.toggleDraggable
});
}
}
},
onDrag(objectTag){
return (dragtoPos, source) => {
console.log("GroupTest: " + objectTag+ " onDrag dragtoPos" +
dragtoPos[0] +","+ dragtoPos[1]+","+ dragtoPos[2]);
}
},
onReset(){
let that = this;
this.setState({
reset:true
});
setTimeout(function(){
that.setState({
reset:false
});
}, 500);
},
render: function() {
if (this.state.reset){
return (<ViroScene />);
}
return (
<ViroScene physicsWorld={{gravity:[0,-9.81,0],drawBounds:this.state.drawBounds}}>
<ReleaseMenu sceneNavigator={this.props.sceneNavigator}/>
<ViroNode position={[4 , -1, -3]} transformBehaviors={["billboard"]}>
<ViroText fontSize={35} style={styles.centeredText}
position={[0,2, 0]} width={4} height ={2} maxLines={3}
color={this.state.physicsEnabled ? '#0000ff' : '#ffffff'}
text={"Toggle PhysicsBody"} onClick={this.togglePhysicsBody(1)}/>
<ViroText fontSize={35} style={styles.centeredText}
position={[0,1, 0]} width={4} height ={2} maxLines={3}
color={this.state.gravityEnabled ? '#0000ff' : '#ffffff'}
text={"Toggle Gravity"} onClick={this.togglePhysicsBody(2)}/>
<ViroText fontSize={35} style={styles.centeredText}
position={[0,0, 0]} width={4} height ={2} maxLines={3}
color={this.state.drawBounds ? '#0000ff' : '#ffffff'}
text={"Toggle Collision Lines"} onClick={this.togglePhysicsBody(3)}/>
<ViroText fontSize={35} style={styles.centeredText}
position={[0,-1, 0]} width={4} height ={2} maxLines={3}
color={this.state.toggleDraggable ? '#0000ff' : '#ffffff'}
text={"Toggle Interactivity"} onClick={this.togglePhysicsBody(4)}/>
<ViroText fontSize={35} style={styles.centeredText}
position={[0,-2, 0]} width={4} height ={2} maxLines={3}
text={"Hard Reset."} onClick={this.onReset}/>
</ViroNode>
<ViroBox
physicsBody={{
type:'Static',
restitution:0.4
}}
position={[0, -6, -8]}
scale={[30,1,30]}
materials={["box2"]}
rotation={[0,0,0]}
height={1}
width={1}
length={1}
/>
<ViroNode position={[0.8 , 0, -3.5]} >
<Viro3DObject source={require('../res/heart.obj')}
scale={[1.8, 1.8, 1.8]}
position={[-3.2, 2.5, -4.5]}
materials={["heart"]}
type="OBJ"
onDrag={this.state.toggleDraggable ? this.onDrag("Viro3DObject") : undefined}
physicsBody={this.state.physicsEnabled?
{type:'Dynamic', mass:1, enabled:true, useGravity:this.state.gravityEnabled}:undefined}
/>
<ViroBox
position={[-1, 1, 0]}
scale={[0.4, 0.4, 0.4]}
materials={["redColor","blue","redColor","blue","redColor","blue"]}
height={1}
width={1}
length={1}
onDrag={this.state.toggleDraggable ? this.onDrag("ViroBox") : undefined}
physicsBody={this.state.physicsEnabled?
{type:'Dynamic', mass:1, enabled:true, useGravity:this.state.gravityEnabled}:undefined}
/>
<ViroButton
position={[0, 1, 0]}
scale={[0.2, 0.2, 0.1]}
source={LocalButtonImage}
hoverSource={LocalButtonImage}
clickSource={LocalButtonImage}
onDrag={this.state.toggleDraggable ? this.onDrag("ViroButton") : undefined}
physicsBody={this.state.physicsEnabled?
{ shape:{type:'Box', params:[0.2,0.2,0.05]}, type:'Dynamic', mass:1, enabled:true, useGravity:this.state.gravityEnabled}:undefined}
/>
<ViroFlexView
position={[1, 1, 0]}
scale={[0.3, 0.3, 0.1]}
materials={["redColor"]}
width={1}
height={1}
onDrag={this.state.toggleDraggable ? this.onDrag("ViroFlexView") : undefined}
physicsBody={this.state.physicsEnabled?
{type:'Dynamic', mass:1, enabled:true, shape:{type:'Box', params:[0.3,0.3,0.01]},
useGravity:this.state.gravityEnabled}:undefined}
/>
<ViroImage
width={1} height={1}
format="RGBA8" mipmap={true}
position={[-2, 0, 0]}
scale={[0.5, 0.5, 0.1]}
onDrag={this.state.toggleDraggable ? this.onDrag("ViroImage") : undefined}
physicsBody={this.state.physicsEnabled?
{type:'Dynamic', mass:1, enabled:true, useGravity:this.state.gravityEnabled}:undefined}
resizeMode="ScaleToFill"
imageClipMode="ClipToBounds"
source={{uri: "https://upload.wikimedia.org/wikipedia/commons/7/74/Earth_poster_large.jpg"}}/>
<ViroNode
position={[-1, 0, 0]}
scale={[0.5, 0.5, 0.1]}
onDrag={this.state.toggleDraggable ? this.onDrag("ViroNode") : undefined}
physicsBody={this.state.physicsEnabled?
{type:'Dynamic', mass:1, enabled:true, shape:{type:'box', params:[0.6,0.6,0.2]},
useGravity:this.state.gravityEnabled}:undefined}
rotation={[0,0,0]}>
<ViroText
style={styles.baseTextTwo}
text="This is a text in a ViroNode" />
</ViroNode>
<ViroSphere
position={[0, 0, 0]}
scale={[0.3, 0.3, 0.3]}
widthSegmentCount={5}
heightSegmentCount={5}
radius={1}
onDrag={this.state.toggleDraggable ? this.onDrag("ViroSphere") : undefined}
physicsBody={this.state.physicsEnabled?
{type:'Dynamic', mass:1, enabled:true, useGravity:this.state.gravityEnabled}:undefined}
materials={["redColor"]}
/>
<ViroSpinner
onDrag={this.state.toggleDraggable ? this.onDrag("ViroSpinner") : undefined}
physicsBody={this.state.physicsEnabled?
{type:'Dynamic', mass:1, enabled:true, shape:{type:'Box', params:[0.4,0.4,0.2]}, useGravity:this.state.gravityEnabled}:undefined}
position={[1, 0, 0]}
scale={[0.3, 0.3, 0.1]}/>
<ViroQuad
onDrag={this.state.toggleDraggable ? this.onDrag("ViroQuad") : undefined}
physicsBody={this.state.physicsEnabled?
{type:'Dynamic', mass:1, enabled:true, useGravity:this.state.gravityEnabled}:undefined}
position={[-2, -1, 0]}
scale={[0.5, 0.5, 0.1]}
materials={["redColor"]}
width={1}
height={1}/>
<ViroText
onDrag={this.state.toggleDraggable ? this.onDrag("ViroText") : undefined}
physicsBody={this.state.physicsEnabled?
{type:'Dynamic', mass:1, enabled:true, useGravity:this.state.gravityEnabled}:undefined}
position={[-0.5, -1.7, 0]}
width={2} height ={2}
style={styles.baseTextTwo}
text={"This is a Viro Text"}/>
<ViroVideo
onDrag={this.state.toggleDraggable ? this.onDrag("ViroVideo") : undefined}
physicsBody={this.state.physicsEnabled?
{type:'Dynamic', mass:1, enabled:true, useGravity:this.state.gravityEnabled}:undefined}
position={[0 , -1,0]}
scale={[0.1, 0.1, 0.1]}
height={4} width={4}
rotation={[0,0,-45]}
loop={false}
source={{"uri":"https://s3-us-west-2.amazonaws.com/viro/Climber1Top.mp4"}} />
<ViroNode
scale={[0.2, 0.2, 0.2]}
position={[3, -1, 0]}
onDrag={this.state.toggleDraggable ? this.onDrag("CompoundNode") : undefined}
physicsBody={this.state.physicsEnabled?
{type:'Dynamic', mass:1, enabled:true, restitution:1, shape:{type:'Compound'},
useGravity:this.state.gravityEnabled}:undefined}
rotation={[0,0,-90]}>
<ViroBox
position={[-0.5,0,0]}
scale={[1, 1, 1]}
materials={'blue'}
height={1} width={1} length={1}
/>
<ViroBox
position={[0.5,0,0]}
scale={[1, 1, 1]}
materials={'blue'}
height={1} width={1} length={1}
/>
<ViroBox
position={[-1.5,0,0]}
scale={[1, 1, 1]}
materials={'blue'}
height={1} width={1} length={1}
/>
<ViroBox
position={[0,-0.5,0]}
scale={[1, 1, 1]}
materials={'blue'}
height={1} width={1} length={1}
/>
<ViroBox
position={[0,-1.5,0]}
scale={[1, 1, 1]}
materials={'blue'}
height={1} width={1} length={1}
/>
<ViroBox
position={[0,-2.5,0]}
scale={[1, 1, 1]}
materials={'blue'}
height={1} width={1} length={1}
/>
</ViroNode>
</ViroNode>
<ViroOmniLight
position={[0, 0, 0]}
color={"#ffffff"}
attenuationStartDistance={30}
attenuationEndDistance={40}/>
</ViroScene>
);
},
});
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
elementText: {
fontFamily: 'HelveticaNeue-Medium',
fontSize: 30,
color: '#ffffff',
textAlign: 'center',
},
baseTextTwo: {
fontFamily: 'Arial',
color: '#ffffff',
flex: 1,
},
centeredText: {
fontFamily: 'Arial',
flex: 1,
},
});
ViroMaterials.createMaterials({
redColor: {
shininess: 2.0,
diffuseColor: "#ff0000"
},
box2: {
shininess : 2.0,
diffuseColor: "#F0F099",
},
blue: {
shininess: 2.0,
diffuseColor: "#0000ff"
},
heart: {
lightingModel: "Phong",
diffuseTexture: require('../res/heart_d.jpg'),
},
});
module.exports = GroupTestBasicPhysics;
|
lib/components/displayConversation.js | jksmall0631/shoot-da-breeze | import React from 'react';
import DisplayMessage from './DisplayMessage';
const DisplayConversation = ({messages, userMessages, reverse})=>{
if(userMessages) {
if(reverse){
return (
<ul className="message-container">
{userMessages.reverse().map((message) => {
return (<DisplayMessage key={message.id} timestamp={message.id} title={message.title} user={message.user} />)
})
}
</ul>
)
}
return (
<ul className="message-container">
{userMessages.map((message) => {
return (<DisplayMessage key={message.id} timestamp={message.id} title={message.title} user={message.user} />)
})
}
</ul>
)
}
else if(messages.length > 0) {
if(reverse){
return (
<ul className="message-container">
{messages.reverse().map((message) => {
return (<DisplayMessage key={message.id} timestamp={message.id} title={message.title} user={message.user} />)
})
}
</ul>
)
}
return (
<ul className="message-container">
{messages.map((message) => {
return (<DisplayMessage key={message.id} timestamp={message.id} title={message.title} user={message.user} message={message}/>)
})
}
</ul>
)
}
return(
<div>
<h1></h1>
</div>
)
}
export default DisplayConversation;
|
source/containers/ContentPage/index.js | mikey1384/twin-kle | import React from 'react';
import PropTypes from 'prop-types';
import { Route, Switch } from 'react-router-dom';
import NotFound from 'components/NotFound';
import { css } from 'emotion';
import { mobileMaxWidth } from 'constants/css';
import Content from './Content';
ContentPage.propTypes = {
match: PropTypes.object.isRequired
};
export default function ContentPage({ match }) {
return (
<div
className={css`
width: 100%;
display: flex;
justify-content: center;
margin-top: 1rem;
margin-bottom: 1rem;
padding-bottom: 20rem;
`}
>
<section
className={css`
width: 65%;
@media (max-width: ${mobileMaxWidth}) {
width: 100%;
min-height: 100vh;
}
`}
>
<Switch>
<Route exact path={`${match.url}/:contentId`} component={Content} />
<Route component={NotFound} />
</Switch>
</section>
</div>
);
}
|
react-ui/src/components/shared/GenericLoader.js | EdwinJow/truthindata | import React, { Component } from 'react';
import '../../css/shared/generic-loader.min.css';
class GenericLoader extends Component {
constructor(props) {
super(props);
this.state = {
open: props.open
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.open !== this.state.open) {
this.setState({ open: nextProps.open });
}
}
render() {
return (
<div id="generic-loader" className={this.state.open ? '' : 'hidden' }>
<div className="center-element">
<img src={require("../../images/loaders/ripple.svg")} alt="loader"/>
</div>
</div>
);
}
}
export default GenericLoader;
|
src/svg-icons/notification/do-not-disturb.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationDoNotDisturb = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8 0-1.85.63-3.55 1.69-4.9L16.9 18.31C15.55 19.37 13.85 20 12 20zm6.31-3.1L7.1 5.69C8.45 4.63 10.15 4 12 4c4.42 0 8 3.58 8 8 0 1.85-.63 3.55-1.69 4.9z"/>
</SvgIcon>
);
NotificationDoNotDisturb = pure(NotificationDoNotDisturb);
NotificationDoNotDisturb.displayName = 'NotificationDoNotDisturb';
NotificationDoNotDisturb.muiName = 'SvgIcon';
export default NotificationDoNotDisturb;
|
beta/frontend-frameworks/calculator/src/main.js | GregoryGoncalves/freecodecamp | /*
Author: Selhar
Date: 2017
Contact: [email protected]
License: GPL
*/
import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import Index from './components/indexComponent';
import store from './store';
const css = require('./main.scss');
render(
<Provider store={store}>
<Index />
</Provider>,
document.getElementById('main')
); |
node_modules/react-router/es6/IndexRoute.js | laere/country-news | 'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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 warning from 'warning';
import invariant from 'invariant';
import React, { Component } from 'react';
import { createRouteFromReactElement } from './RouteUtils';
import { component, components, falsy } from './PropTypes';
var func = React.PropTypes.func;
/**
* An <IndexRoute> is used to specify its parent's <Route indexRoute> in
* a JSX route config.
*/
var IndexRoute = (function (_Component) {
_inherits(IndexRoute, _Component);
function IndexRoute() {
_classCallCheck(this, IndexRoute);
_Component.apply(this, arguments);
}
/* istanbul ignore next: sanity check */
IndexRoute.prototype.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) : undefined;
};
return IndexRoute;
})(Component);
IndexRoute.propTypes = {
path: falsy,
component: component,
components: components,
getComponent: func,
getComponents: func
};
IndexRoute.createRouteFromReactElement = function (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') : undefined;
}
};
export default IndexRoute; |
src/js/ui/components/tabMenu.js | hiddentao/heartnotes | import _ from 'lodash';
import React from 'react';
import Classnames from 'classnames';
var Tab = React.createClass({
propTypes: {
data: React.PropTypes.object.isRequired,
onSelect: React.PropTypes.func.isRequired,
active: React.PropTypes.bool,
attention: React.PropTypes.object,
},
render: function() {
let classes = {
'tab': true,
active: !!this.props.active,
attention: null,
};
let attention = null;
if (this.props.attention) {
attention = (
<div className="attention">{this.props.attention}</div>
);
}
return (
<div className={Classnames(classes)} onClick={this._onClick}>
{attention}
<div className="text">{this.props.data.desc}</div>
</div>
);
},
_onClick: function() {
this.props.onSelect(this.props.data);
},
});
module.exports = React.createClass({
propTypes: {
items: React.PropTypes.array.isRequired,
selectedItem: React.PropTypes.string.isRequired,
onSelect: React.PropTypes.func.isRequired,
className: React.PropTypes.string,
},
getDefaultProps: function() {
return {
className: null,
}
},
render: function() {
let { items, className, selectedItem } = this.props;
var primaryLinks = [];
items.forEach((item) => {
let attention = null;
if (item.showIf) {
if (!item.showIf.call(this)) {
return;
}
}
if (item.attention) {
attention = item.attention.call(this);
}
primaryLinks.push(
<Tab
key={item.id}
data={item}
active={item.id === this.props.selectedItem}
attention={attention}
onSelect={this.props.onSelect} />
);
});
let classes = Classnames('tab-menu', className);
return (
<div className={classes}>
{primaryLinks}
</div>
);
},
});
|
src/components/LandingStatic/LandingNavItems.js | ortonomy/flingapp-frontend | import React from 'react';
// library dependencies
import { Link } from 'react-router-dom';
// styles
import styles from './LandingNav.module.css';
const LandingNavItems = ({ items, ...props}) => {
return (
<div className={styles.NavBarNavItems}>
{
items && items.map( (item, i) => {
return (
<div key={i}>
{ item.href ? (<Link to={item.href} ><span>{item.text}</span></Link>) : (<span>{item.text}</span>)}
</div>
)
})
}
</div>
);
}
export default LandingNavItems; |
components/person-view.js | pho3nixf1re/followupboss-example | import React from 'react';
import isEmpty from 'lodash/isEmpty';
import State from 'lib/state';
import {actions as peopleActions} from 'lib/reactions/people';
import Person from 'components/person';
const PersonView = React.createClass({
propTypes: {
state: React.PropTypes.object,
params: React.PropTypes.shape({
id: React.PropTypes.string
}).isRequired
},
componentDidMount() {
let { data, loading, params } = this.props;
let noActivePerson = isEmpty(data) && !loading;
let { id } = params;
if (noActivePerson || data.id != id) {
State.trigger(peopleActions.SET_ACTIVE_PERSON, { id: id });
}
},
render() {
let { data, loading } = this.props.state.activePerson;
return <Person person={data} loading={loading} />;
}
});
export default PersonView;
|
docs/src/app/components/pages/get-started/ServerRendering.js | mtsandeep/material-ui | import React from 'react';
import Title from 'react-title-component';
import MarkdownElement from '../../MarkdownElement';
import serverRenderingText from './server-rendering.md';
const ServerRendering = () => (
<div>
<Title render={(previousTitle) => `Server Rendering - ${previousTitle}`} />
<MarkdownElement text={serverRenderingText} />
</div>
);
export default ServerRendering;
|
client/components/HomePage.js | GO345724/pair-programming | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as problemsActions from '../actions/problemsActions';
import * as userActions from '../actions/userActions.js';
import ChooseUserName from './ChooseUserName';
import ProblemsList from './ProblemsList';
class HomePage extends Component {
constructor(props) {
super(props);
this.chooseUserName = this.chooseUserName.bind(this);
}
componentDidMount() {
if (this.props.problems.length == 0) {
this.props.actions.getProblems();
}
}
chooseUserName(userName) {
this.props.actions.assignUserName(userName);
}
render() {
return(
<div>
<ChooseUserName userName={this.props.userName} chooseUserName={this.chooseUserName} />
<ProblemsList problems={this.props.problems} />
</div>
)
}
}
HomePage.propTypes = {
userName: PropTypes.string.isRequired,
problems: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired
}
const mapStateToProps = state => {
return {problems: state.problems, userName: state.currentUser}
}
const mapDispatchToProps = dispatch => {
return {actions: bindActionCreators(Object.assign(userActions, problemsActions), dispatch)}
}
export default connect(mapStateToProps, mapDispatchToProps)(HomePage);
|
src/routes/hat/Hat.js | macdja38/pvpsite | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import { fabric } from 'fabric-webpack';
import Layout from '../../components/Layout';
import s from './Hat.css';
class Hat extends Component {
static propTypes = {
user: PropTypes.object,
userId: PropTypes.string,
userHash: PropTypes.string,
};
constructor({ user, userId, userHash }) {
super({ user, userId, userHash });
}
componentDidMount() {
let id;
let hash;
if (this.props.userId) {
id = this.props.userId;
} else if (this.props.user) {
id = this.props.user.id;
}
if (this.props.userHash) {
hash = this.props.userHash;
} else if (this.props.user) {
hash = this.props.user.avatar;
}
// const hatURL = 'https://cdn.discordapp.com/attachments/116405078889332743/119653981776642049/hat.png';
// const avatarURL = `https://discordapp.com/api/users/${id}/avatars/${hash}.jpg`;
const hatURL = '/api/v1/attachments/116405078889332743/119653981776642049/hat.png';
const avatarURL = `/api/v1/avatar/${id}/${hash}/`;
var canvas = new fabric.Canvas("profilePicArea");
canvas.setHeight(256).setWidth(256).setZoom(2);
fabric.util.loadImage("${avatarURL}", function(avatarImageElement, error) {
canvas.setBackgroundImage(new fabric.Image(avatarImageElement), (avatarImage) => {
canvas.renderAll.call(canvas);
fabric.util.loadImage("${hatURL}", function(hatImageElement, error) {
var hatImage = new fabric.Image(hatImageElement).scaleToWidth(100).set({
angle: 15,
borderColor: "#2c2f33",
cornerColor: "#2c2f33",
cornerSize: 9,
left: 45,
top: -35
})
canvas.add(hatImage);
});
}, {
width: 128,
height: 128,
originX: 0,
originY: 0
});
});
var downloadButton = document.getElementById("downloadButton");
downloadButton.addEventListener("click", () => {
downloadButton.href = canvas.toDataURL({
format: "jpeg",
height: 256,
multiplier: 0.5,
width: 256
});
downloadButton.download = "avatar.jpg";
}, false);
}
render() {
let id;
let hash;
if (this.props.userId) {
id = this.props.userId;
} else if (this.props.user) {
id = this.props.user.id;
}
if (this.props.userHash) {
hash = this.props.userHash;
} else if (this.props.user) {
hash = this.props.user.avatar;
}
// const hatURL = 'https://cdn.discordapp.com/attachments/116405078889332743/119653981776642049/hat.png';
// const avatarURL = `https://discordapp.com/api/users/${id}/avatars/${hash}.jpg`;
const hatURL = '/api/v1/attachments/116405078889332743/119653981776642049/hat.png';
const avatarURL = `/api/v1/avatar/${id}/${hash}/`;
return (
<Layout user={this.props.user}>
<div className={s.root}>
<div className={s.container}>
<h1 className={s.title}>PvPCraft Discord bot.</h1>
<p>
<canvas
id="profilePicArea"
style={{ position: 'absolute', width: '256px', height: '256px', left: 0, top: 0 }}
width="256" height="256"
/>
<input id="downloadButton" type="button" />
</p>
</div>
</div>
</Layout>
);
}
}
export default withStyles(s)(Hat);
|
src/React/Widgets/NumberSliderWidget/example/index.js | Kitware/paraviewweb | import 'normalize.css';
import React from 'react';
import ReactDOM from 'react-dom';
import NumberSliderWidget from 'paraviewweb/src/React/Widgets/NumberSliderWidget';
class ColorField extends React.Component {
constructor(props) {
super(props);
this.state = {
r: 30,
g: 60,
b: 90,
};
// Bind callback
this.updateVal = this.updateVal.bind(this);
this.drawColor = this.drawColor.bind(this);
}
componentDidMount() {
this.drawColor();
}
componentDidUpdate() {
this.drawColor();
}
updateVal(e) {
const which = e.target.name;
const newVal = e.target.value;
const toUpdate = {};
toUpdate[which] = newVal;
this.setState(toUpdate);
}
drawColor() {
const ctx = this.canvas.getContext('2d');
const width = ctx.canvas.width;
const height = ctx.canvas.height;
ctx.fillStyle = `rgb(${this.state.r}, ${this.state.g}, ${this.state.b})`;
ctx.rect(0, 0, width, height);
ctx.fill();
}
render() {
const [r, g, b] = [this.state.r, this.state.g, this.state.b];
return (
<section style={{ margin: '20px' }}>
<NumberSliderWidget
value={r}
max="255"
min="0"
onChange={this.updateVal}
name="r"
/>
<NumberSliderWidget
value={g}
max="255"
min="0"
onChange={this.updateVal}
name="g"
/>
<NumberSliderWidget
value={b}
max="255"
min="0"
onChange={this.updateVal}
name="b"
/>
<canvas
ref={(c) => {
this.canvas = c;
}}
width="50"
height="50"
/>
</section>
);
}
}
ReactDOM.render(<ColorField />, document.querySelector('.content'));
|
frontend/src/components/popup/ProductDetails.js | jirkae/BeerCheese | import React from 'react';
import { Modal, ModalBody, Container, Row, Col } from 'reactstrap';
export default props => {
return (
<Modal isOpen={true} toggle={props.hideModals}>
<ModalBody>
<Container>
<Row>
<Col>
<Row>
{props.data.name}
</Row>
<Row>
<img
src="https://placeholdit.imgix.net/~text?txtsize=33&txt=318%C3%97180&w=318&h=180"
alt="Card cap"
/>
</Row>
<Row>
{props.data.price}
</Row>
</Col>
<Col>
{props.data.description}
</Col>
</Row>
</Container>
</ModalBody>
</Modal>
);
};
|
resource/js/components/Page/PageBody.js | kyonmm/crowi | import React from 'react';
export default class PageBody extends React.Component {
constructor(props) {
super(props);
this.crowiRenderer = window.crowiRenderer; // FIXME
this.getMarkupHTML = this.getMarkupHTML.bind(this);
}
getMarkupHTML() {
let body = this.props.pageBody;
if (body === '') {
body = this.props.page.revision.body;
}
return { __html: this.crowiRenderer.render(body) };
}
render() {
const parsedBody = this.getMarkupHTML();
return (
<div
className="content"
dangerouslySetInnerHTML={parsedBody}
/>
);
}
}
PageBody.propTypes = {
page: React.PropTypes.object.isRequired,
pageBody: React.PropTypes.string,
};
PageBody.defaultProps = {
page: {},
pageBody: '',
};
|
packages/material-ui-icons/src/CheckCircle.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let CheckCircle = props =>
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" />
</SvgIcon>;
CheckCircle = pure(CheckCircle);
CheckCircle.muiName = 'SvgIcon';
export default CheckCircle;
|
src/svg-icons/notification/sync.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationSync = (props) => (
<SvgIcon {...props}>
<path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"/>
</SvgIcon>
);
NotificationSync = pure(NotificationSync);
NotificationSync.displayName = 'NotificationSync';
NotificationSync.muiName = 'SvgIcon';
export default NotificationSync;
|
Realization/frontend/czechidm-core/src/components/basic/Table/LinkCell.js | bcvsolutions/CzechIdMng | import React from 'react';
import { Link } from 'react-router-dom';
import pathToRegexp from 'path-to-regexp';
import _ from 'lodash';
//
import { SecurityManager } from '../../../redux';
import DefaultCell from './DefaultCell';
import Popover from '../Popover/Popover';
import Button from '../Button/Button';
// TODO: Localization service could not be accessed directly (advadced component)
import { LocalizationService } from '../../../services';
const TARGET_PARAMETER = '_target';
/**
* Fills href parameter values from ginen rowData / entity object.
*
* @param {string} to href
* @param {object} rowData entity
* @return {string} formated href
*
* @author Radek Tomiška
*/
function _resolveToWithParameters(to, rowData, target) {
const parameterNames = pathToRegexp.parse(to);
parameterNames.forEach(parameter => {
if (parameter && parameter.name === TARGET_PARAMETER && target) {
const targetValue = DefaultCell.getPropertyValue(rowData, target);
if (targetValue) {
to = to.replace(`:${TARGET_PARAMETER}`, targetValue);
}
}
});
const thingPath = pathToRegexp.compile(to);
return thingPath(rowData);
}
function _linkFunction(to, rowIndex, data, event) {
if (event) {
event.preventDefault();
}
if (to) {
to({ rowIndex, data, event });
}
}
/**
* Renders cell with link and text content.
* Parametrs are automatically propagated from table / row / column
* @param number rowIndex
* @param array[json] input data
* @param property column key
* @param to - router link
* @param className className
* @param title - html title
* @param target - optional entity property could be used as `_target` property in `to` property.
* @param access - link could be accessed, if current user has access to target agenda. Otherwise propertyValue without link is rendered.
* @param props other optional properties
*
* @author Radek Tomiška
*/
const LinkCell = ({ rowIndex, data, property, to, href, className, title, target, access, ...props }) => {
const propertyValue = DefaultCell.getPropertyValue(data[rowIndex], property);
const accessItems = (access && !Array.isArray(access)) ? [access] : access;
// when is property and accessItems null, then return only default cell
if (!propertyValue) {
return <DefaultCell { ...props }/>;
}
// construct html link href
let _href = '#';
if (_.isFunction(to) && href) {
if (_.isFunction(href)) {
_href = href({ data, rowIndex, property});
} else {
_href = href;
}
}
//
return (
<DefaultCell { ...props }>
{
(accessItems && !SecurityManager.hasAccess(accessItems))
?
<span>
{
SecurityManager.isDenyAll(accessItems)
?
propertyValue
:
<Popover
level="warning"
title={ LocalizationService.i18n('security.access.link.denied') }
value={
<span>
{
[...accessItems.map((accessItem) => {
if (SecurityManager.hasAccess(accessItem)) {
return null;
}
return (
<div>
{/* TODO: make appropriate enum and refactor security service etc. */}
<strong>{ LocalizationService.i18n(`enums.AccessTypeEnum.${accessItem.type}`) }</strong>
{
!accessItem.authorities
||
<span>
: <div>{ accessItem.authorities.join(', ') }</div>
</span>
}
</div>
);
}).values()]
}
</span>
}>
<Button level="link" style={{ padding: 0 }}>{ propertyValue }</Button>
</Popover>
}
</span>
:
<span>
{
_.isFunction(to)
?
<Link
to={ _href }
onClick={ _linkFunction.bind(this, to, rowIndex, data) }
title={ title }>
{ propertyValue }
</Link>
:
<Link to={ _resolveToWithParameters(to, data[rowIndex], target) } title={ title } className={ className }>
{ propertyValue }
</Link>
}
</span>
}
</DefaultCell>
);
};
export default LinkCell;
|
geonode/contrib/monitoring/frontend/src/components/molecules/ws-service-select/index.js | timlinux/geonode | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import DropDownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';
import actions from './actions';
const mapStateToProps = (state) => ({
services: state.wsServices.response,
selected: state.wsService.service,
});
@connect(mapStateToProps, actions)
class WSServiceSelect extends React.Component {
static propTypes = {
selected: PropTypes.string,
services: PropTypes.object,
getServices: PropTypes.func.isRequired,
setService: PropTypes.func.isRequired,
}
constructor(props) {
super(props);
this.handleServiceSelect = (event, index, value) => {
this.props.setService(value);
};
}
componentWillMount() {
this.props.getServices();
}
componentWillReceiveProps(nextProps) {
if (this.props.selected) {return;}
const services = nextProps.services;
if (services && services.ows_services && services.ows_services.length > 0) {
this.props.setService(services.ows_services[0].name);
}
}
render() {
const items = this.props.services
? this.props.services.ows_services.map(service => (
<MenuItem
key={service.name}
value={service.name}
primaryText={service.name}
/>
))
: [];
return (
<DropDownMenu
value={this.props.selected}
onChange={this.handleServiceSelect}
>
{items}
</DropDownMenu>
);
}
}
export default WSServiceSelect;
|
docs/src/CodeExample.js | HorizonXP/react-bootstrap | import React from 'react';
export default class CodeExample extends React.Component {
render() {
return (
<pre className="cm-s-solarized cm-s-light">
<code>
{this.props.codeText}
</code>
</pre>
);
}
componentDidMount() {
if (CodeMirror === undefined) {
return;
}
CodeMirror.runMode(
this.props.codeText,
this.props.mode,
React.findDOMNode(this).children[0]
);
}
}
|
packages/mineral-ui-icons/src/IconNearMe.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconNearMe(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M21 3L3 10.53v.98l6.84 2.65L12.48 21h.98L21 3z"/>
</g>
</Icon>
);
}
IconNearMe.displayName = 'IconNearMe';
IconNearMe.category = 'maps';
|
packages/cf-component-label/example/basic/component.js | mdno/mdno.github.io | import React from 'react';
import { Label } from 'cf-component-label';
const LabelComponent = () => (
<p>
<Label type="default">Default</Label>
<Label type="info">Info</Label>
<Label type="success">Success</Label>
<Label type="warning">Warning</Label>
<Label type="error">Error</Label>
</p>
);
export default LabelComponent;
|
mla_game/front-end/javascript/components/partials/menu_footer.js | WGBH/FixIt | import React from 'react'
import Modal from 'react-modal'
import { PopupCenter } from '../../helpers'
import { patchData } from '../../helpers'
class MenuFooter extends React.Component {
constructor(){
super()
this.setModal = this.setModal.bind(this)
this.closeModal = this.closeModal.bind(this)
this.sharePopUp = this.sharePopUp.bind(this)
this.pushComplete = this.pushComplete.bind(this)
this.state = {
modalOpen:false
}
}
setModal(){
let open = this.state.modalOpen
if(open) {
this.setState({modalOpen:false})
} else {
this.setState({modalOpen:true})
}
}
closeModal(){
this.setState({modalOpen:false})
}
sharePopUp(url, id, ){
PopupCenter(url, id, '600', '500')
}
pushComplete(){
if(this.props.endOfRound) {
let user = this.props.user,
data ={
"completed":this.props.endOfRound
}
patchData(`/api/profile/${user}/completed/`, data)
this.props.updateScore(this.props.gameScore)
} else {
return false
}
}
componentDidMount(){
this.pushComplete()
}
render(){
return(
<div className="share-block">
<span className="social-label">Share:</span>
<ul>
<li>
<button onClick={() => this.sharePopUp('https://www.facebook.com/sharer/sharer.php?u=http%3A//fixit.americanarchive.org/', 'Facebook_Share')}>
<svg xmlns="http://www.w3.org/2000/svg" id="Layer_1" data-name="Layer 1" viewBox="0 0 200 200">
<path className="background" fill="#6d6e71" d="M100 0a100 100 0 1 0 100 100A100 100 0 0 0 100 0z"/>
<path fill="#fff" d="M124.44 67.46H113.3c-4.44 0-5.37 1.86-5.37 6.55v10.3h16.5l-1.72 16.83h-14.75V160H83.17v-58.9h-16.5V84.3h16.5V64.86c0-14.88 7.68-22.65 25-22.65h16.27z"/>
</svg>
</button>
</li>
<li>
<button onClick={() => this.sharePopUp("https://twitter.com/home?status=I'm%20helping%20make%20public%20media's%20archive%20accessible%20by%20playing%20%40amarchivepub's%20FIX%20IT%20game.%20Join%20me%3A%20http%3A//fixit.americanarchive.org%20%23fixitaapb", 'Twitter_Share')}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<path className="background" fill="#6d6e71" d="M100 0a100 100 0 1 0 100 100A100 100 0 0 0 100 0z"/>
<path fill="#fff" d="M150.4 81.58c1.5 33.93-23.4 71.75-67.4 71.75a66.25 66.25 0 0 1-36.34-10.84 47.12 47.12 0 0 0 35.1-10 23.82 23.82 0 0 1-22.16-16.77 23.4 23.4 0 0 0 10.7-.4 24.07 24.07 0 0 1-19-24A23.35 23.35 0 0 0 62 94.4a24.4 24.4 0 0 1-7.34-32.2 66.93 66.93 0 0 0 48.87 25.2c-3.46-15.08 7.8-29.62 23.1-29.62a23.5 23.5 0 0 1 17.37 7.6 46.8 46.8 0 0 0 15-5.84 24.15 24.15 0 0 1-10.43 13.34 46.67 46.67 0 0 0 13.6-3.8 48.06 48.06 0 0 1-11.82 12.5z" className="cls-2"/>
</svg>
</button>
</li>
<li>
<button onClick={() => this.sharePopUp("https://www.linkedin.com/shareArticle?mini=true&url=http%3A//fixit.americanarchive.org/&title=FIX%20IT&summary=I'm%20helping%20make%20public%20media's%20archive%20accessible%20by%20playing%20%40amarchivepub's%20FIX%20IT%20game.%20Join%20me%3A%20http%3A//fixit.americanarchive.org%20%23fixitaapb&source=", 'Linkedin_Share')}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<circle className="background" fill="#6d6e71" cx="100" cy="100" r="100"/>
<path fill="#fff" d="M50.37 79.5h22.38v72H50.37zm11.2-9.85a13 13 0 1 1 13-13 13 13 0 0 1-13 13zm95.03 81.85h-22.4v-35c0-8.34-.15-19.08-11.63-19.08-11.65 0-13.44 9.1-13.44 18.5v35.62H86.8v-72h21.46v9.84h.3c3-5.66 10.3-11.63 21.18-11.63 22.66 0 26.85 14.92 26.85 34.3z" className="cls-2"/>
</svg>
</button>
</li>
</ul>
<a className="terms-link js-terms-link" onClick={() => this.setModal()} href="#js-terms-dialog">Terms of Use</a>
<Modal
isOpen={this.state.modalOpen}
onRequestClose={this.closeModal}
contentLabel="Terms And Conditions"
className="modal-content"
overlayClassName="modal-overlay"
>
<h1>Terms and Conditions</h1>
<button className='modal-close' onClick={this.closeModal}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500">
<title>Close Modal</title>
<path d="M403.1 108.9c-81.2-81.2-212.9-81.2-294.2 0s-81.2 212.9 0 294.2c81.2 81.2 212.9 81.2 294.2 0s81.2-213 0-294.2zm-12.3 281.9c-74.3 74.3-195.3 74.3-269.6 0-74.3-74.3-74.3-195.3 0-269.6s195.3-74.3 269.6 0c74.4 74.3 74.4 195.3 0 269.6z"/>
<path d="M340.2 160l-84.4 84.2-84-83.8-11.8 11.8 84 83.8-84 83.8 11.8 11.8 84-83.8 84.4 84.2 11.8-11.8-84.4-84.2 84.4-84.2"/>
</svg>
</button>
<p>THE FOLLOWING TERMS AND CONDITIONS GOVERN YOUR USE OF THE SITE. PLEASE READ THESE TERMS OF USE CAREFULLY BEFORE USING THIS SITE.</p>
<p>WGBH Educational Foundation (“WGBH”), on behalf of the American Archive of Public Broadcasting, which is a collaboration between WGBH and the Library of Congress, has created and maintains this FIX IT website (the “Site”). This Site is governed by the <a href="http://americanarchive.org/legal/tou" target="_blank">Terms of Use</a> (the “Terms”) and <a href="http://americanarchive.org/legal/privacy" target="_blank">Privacy Policy</a> (the “Policy”) of the American Archive for Public Broadcasting located at <a href="http://americanarchive.org/" target="_blank">americanarchive.org</a>. By using the Site you agree to be bound by the Terms and Policy. If you do not agree to the Term and Policy you must exit the Site and you may not use the Site or any of its features. Your acceptance of the Terms upon your first visit to the Site constitutes acceptance to the Terms on all of your subsequent visits to the Site.</p>
<p>In addition to the Terms and the Policy, the following additional terms shall apply to the Site (the “Supplemental Terms”). In the event of any conflict between the Supplemental Terms and the Terms or the Policy, then the Supplemental Terms shall take priority, with all other provisions of the Terms and the Policy remaining in full effect.</p>
<h2>A. Registration</h2>
<p>You accept all responsibility for the use of any third party login function or API that you use to register for the Site and consent to information sharing by and between the providers of such services and WGBH which may include your name and contact information. You are solely responsible for all activities that occur through your account. You further acknowledge that you may receive emails pertaining to promotional suggested topics for FIX IT games.</p>
<h2>B. Restrictions on Use of Site and Content</h2>
<ol>
<li>You must be at least thirteen (13) years of age to register for the Site and to submit any User Generated Content (defined by the Terms and below).</li>
<li>You agree that use of the Site’s features and transcription games results in the creation of derivative works and that all rights associated with such transcription and results of said games remains the sole property of WGBH, the contributing station, or other rights holder for the material being transcribed.</li>
</ol>
<h2>C. User Generated Content (UGC):</h2>
<ol>
<li>You acknowledge that WGBH, the contributing station, or other rights holder for the material being transcribed as determined by WGBH, is the owner of all content generated through your use of the transcription games located on the site (“User Generated Content” or “UGC”) and that you may not control WGBH’s use of the content. WGBH is not obligated to use your UGC.</li>
<li>You acknowledge that WGBH assumes no responsibility or liability arising from UGC that unreasonably differs from the source material, or for any error, defamation, libel, omission, obscenity, danger or inaccuracy contained in the same.</li>
<li>You agree to use reasonable effort to ensure accuracy in your use of the transcription games which shall include utilizing the provided instructions for the same, and shall not use the games and UGC as an avenue to engage in any behavior which may be off-topic, contains personal attacks or expletives or is otherwise abusive, threatening, unlawful, harassing, discriminatory, libelous, obscene, false, pornographic, that infringes on the rights of a third party, or as a means of advertising or promoting any off topic matter.</li>
</ol>
<h2>D. Links to Third Party Sites </h2>
<p>This site contains links to affiliated and unaffiliated websites. Such sites are subject to their own terms and conditions. Please review the terms and conditions specific to each website that you intend to make use of and make sure you comply with the applicable rules. You agree that WGBH shall have no liability for damaged, broken, or misleading links. Links are provided for convenience only and WGBH makes no representation or warranty and bears no responsibility for accuracy or content of any externally linked site. Your use of such sites is at your sole risk.</p>
</Modal>
</div>
)
}
}
export default MenuFooter |
src/routes/error/index.js | peeyush1234/react-nodejs-skeleton | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import ErrorPage from './ErrorPage';
export default {
path: '/error',
action({ error }) {
return {
title: error.name,
description: error.message,
component: <ErrorPage error={error} />,
status: error.status || 500,
};
},
};
|
src/front/js/routes.js | raccoon-app/ui-kit | import React from 'react';
import { Route } from 'react-router';
import { IndexRoute } from 'react-router';
import Auth from './containers/Auth';
import ProjectSelection from './containers/ProjectSelection';
import Project from './containers/Project';
export default () => (
<Route path="/" >
<IndexRoute component={Auth} />
<Route path="projects" component={ProjectSelection} />
<Route path="project/:id" component={Project} />
</Route>
);
|
src/svg-icons/navigation/subdirectory-arrow-right.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationSubdirectoryArrowRight = (props) => (
<SvgIcon {...props}>
<path d="M19 15l-6 6-1.42-1.42L15.17 16H4V4h2v10h9.17l-3.59-3.58L13 9l6 6z"/>
</SvgIcon>
);
NavigationSubdirectoryArrowRight = pure(NavigationSubdirectoryArrowRight);
NavigationSubdirectoryArrowRight.displayName = 'NavigationSubdirectoryArrowRight';
NavigationSubdirectoryArrowRight.muiName = 'SvgIcon';
export default NavigationSubdirectoryArrowRight;
|
src/containers/Asians/Published/Debaters/DebaterRoster/SmallDebaterRoster.js | westoncolemanl/tabbr-web | import React from 'react'
import { connect } from 'react-redux'
import List, {
ListItem,
ListItemText
} from 'material-ui/List'
import Paper from 'material-ui/Paper'
export default connect(mapStateToProps)(({
debaters,
teamsById,
institutionsById
}) => {
debaters.sort((a, b) => {
if (
teamsById[a.team] &&
teamsById[b.team]
) {
if (
institutionsById[teamsById[a.team].institution] &&
institutionsById[teamsById[b.team].institution]
) {
if (institutionsById[teamsById[a.team].institution].name > institutionsById[teamsById[b.team].institution].name) return 1
if (institutionsById[teamsById[a.team].institution].name < institutionsById[teamsById[b.team].institution].name) return -1
}
if (teamsById[a.team].name > teamsById[b.team].name) return 1
if (teamsById[a.team].name < teamsById[b.team].name) return -1
}
if (a.firstName > b.firstName) return 1
if (a.firstName < b.firstName) return -1
return 0
})
return (
<Paper>
<List>
{debaters.map(debater =>
<ListItem
key={debater._id}
>
<ListItemText
primary={`${debater.firstName} ${debater.lastName}`}
secondary={`${teamsById[debater.team].name} (${institutionsById[teamsById[debater.team].institution].name})`}
/>
</ListItem>
)}
</List>
</Paper>
)
})
function mapStateToProps (state, ownProps) {
return {
debaters: Object.values(state.debaters.data),
teamsById: state.teams.data,
institutionsById: state.institutions.data
}
}
|
src/svg-icons/editor/insert-link.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorInsertLink = (props) => (
<SvgIcon {...props}>
<path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"/>
</SvgIcon>
);
EditorInsertLink = pure(EditorInsertLink);
EditorInsertLink.displayName = 'EditorInsertLink';
EditorInsertLink.muiName = 'SvgIcon';
export default EditorInsertLink;
|
node_modules/react-router/es/RouteUtils.js | vietvd88/developer-crawler | 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; };
import React from 'react';
function isValidChild(object) {
return object == null || React.isValidElement(object);
}
export function isReactChildren(object) {
return isValidChild(object) || Array.isArray(object) && object.every(isValidChild);
}
function createRoute(defaultProps, props) {
return _extends({}, defaultProps, props);
}
export function createRouteFromReactElement(element) {
var type = element.type;
var route = createRoute(type.defaultProps, element.props);
if (route.children) {
var childRoutes = createRoutesFromReactChildren(route.children, route);
if (childRoutes.length) route.childRoutes = childRoutes;
delete route.children;
}
return route;
}
/**
* Creates and returns a routes object from the given ReactChildren. JSX
* provides a convenient way to visualize how routes in the hierarchy are
* nested.
*
* import { Route, createRoutesFromReactChildren } from 'react-router'
*
* const routes = createRoutesFromReactChildren(
* <Route component={App}>
* <Route path="home" component={Dashboard}/>
* <Route path="news" component={NewsFeed}/>
* </Route>
* )
*
* Note: This method is automatically used when you provide <Route> children
* to a <Router> component.
*/
export function createRoutesFromReactChildren(children, parentRoute) {
var routes = [];
React.Children.forEach(children, function (element) {
if (React.isValidElement(element)) {
// Component classes may have a static create* method.
if (element.type.createRouteFromReactElement) {
var route = element.type.createRouteFromReactElement(element, parentRoute);
if (route) routes.push(route);
} else {
routes.push(createRouteFromReactElement(element));
}
}
});
return routes;
}
/**
* Creates and returns an array of routes from the given object which
* may be a JSX route, a plain object route, or an array of either.
*/
export function createRoutes(routes) {
if (isReactChildren(routes)) {
routes = createRoutesFromReactChildren(routes);
} else if (routes && !Array.isArray(routes)) {
routes = [routes];
}
return routes;
} |
project/src/pages/Page/components/PageLayout/PageLayout.js | boldr/boldr | // @flow
import React from 'react';
import type { Node } from 'react';
import { Footer, Container } from '@boldr/ui/Layout';
import styled from 'styled-components';
import View from '@boldr/ui/View';
import Navigation from '../Navigation';
import type { CurrentUser, RouterLocation, MenuType } from '../../../../types/boldr';
const ContentWrapper = styled.main`
width: 100%;
height: 100%;
min-height: 100%;
padding-top: 52px;
padding-bottom: 70px;
`;
type Props = {
currentUser: CurrentUser,
location: RouterLocation,
onClickLogout: () => void,
menu: MenuType,
children: Node,
token: string,
};
const PageLayout = (props: Props) => {
return (
<View>
<Navigation
location={props.location}
onLogout={props.onClickLogout}
token={props.token}
currentUser={props.currentUser}
menu={props.menu}
/>
<ContentWrapper>{props.children}</ContentWrapper>
<Footer id="footer">
<Container>Footer</Container>
</Footer>
</View>
);
};
export default PageLayout;
|
packages/examples-counter/src/containers/CounterApp.js | kastigar/borex | import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Counter from '../components/Counter';
import * as CounterActions from '../actions/CounterActions';
class CounterApp extends Component {
render() {
const { counter, dispatch } = this.props;
return (
<Counter counter={counter}
{...bindActionCreators(CounterActions, dispatch)} />
);
}
}
function select(state) {
return {
counter: state.counter
};
}
export default connect(select)(CounterApp);
|
src/components/shell/index.js | datea/datea-webapp-react | import React from 'react';
import {inject} from 'mobx-react';
import {RouterView} from 'mobx-state-router';
import Main from '../main';
import HeadMeta from '../head-meta';
import DateoFormModal from '../dateo-form-modal';
import {MarkerDefs} from '../marker';
import ViewMap from './viewMap';
const Shell = ({store}) =>
<Main>
<HeadMeta />
<RouterView routerStore={store.router} viewMap={ViewMap} />
<DateoFormModal />
<svg height="0" width="0" style={{padding:0, margin: 0, position: 'absolute'}}>
<MarkerDefs />
</svg>
</Main>
export default inject('store')(Shell);
|
app/js/public_keys/connected_public_key_list.js | yock/forte-gui | import React from 'react';
import { connect } from 'react-redux';
import PublicKeyList from './public_key_list';
const deletePublicKey = (id) => {
return {
type: 'DELETE_PUBLIC_KEY',
publicKeyId: id
}
}
const mapStateToProps = (state) => {
return {
publicKeys: state.publicKeys
}
}
const mapDispatchToProps = (dispatch) => {
return {
onDeleteClick(id) {
return dispatch(deletePublicKey(id));
}
}
}
const ConnectedPublicKeyList = connect(
mapStateToProps,
mapDispatchToProps
)(PublicKeyList);
export default ConnectedPublicKeyList;
|
src/Pagination.js | PeterDaveHello/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import PaginationButton from './PaginationButton';
import CustomPropTypes from './utils/CustomPropTypes';
import SafeAnchor from './SafeAnchor';
const Pagination = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
activePage: React.PropTypes.number,
items: React.PropTypes.number,
maxButtons: React.PropTypes.number,
ellipsis: React.PropTypes.bool,
first: React.PropTypes.bool,
last: React.PropTypes.bool,
prev: React.PropTypes.bool,
next: React.PropTypes.bool,
onSelect: React.PropTypes.func,
/**
* You can use a custom element for the buttons
*/
buttonComponentClass: CustomPropTypes.elementType
},
getDefaultProps() {
return {
activePage: 1,
items: 1,
maxButtons: 0,
first: false,
last: false,
prev: false,
next: false,
ellipsis: true,
buttonComponentClass: SafeAnchor,
bsClass: 'pagination'
};
},
renderPageButtons() {
let pageButtons = [];
let startPage, endPage, hasHiddenPagesAfter;
let {
maxButtons,
activePage,
items,
onSelect,
ellipsis,
buttonComponentClass
} = this.props;
if(maxButtons){
let hiddenPagesBefore = activePage - parseInt(maxButtons / 2);
startPage = hiddenPagesBefore > 1 ? hiddenPagesBefore : 1;
hasHiddenPagesAfter = startPage + maxButtons <= items;
if(!hasHiddenPagesAfter){
endPage = items;
startPage = items - maxButtons + 1;
if(startPage < 1){
startPage = 1;
}
} else {
endPage = startPage + maxButtons - 1;
}
} else {
startPage = 1;
endPage = items;
}
for(let pagenumber = startPage; pagenumber <= endPage; pagenumber++){
pageButtons.push(
<PaginationButton
key={pagenumber}
eventKey={pagenumber}
active={pagenumber === activePage}
onSelect={onSelect}
buttonComponentClass={buttonComponentClass}>
{pagenumber}
</PaginationButton>
);
}
if(maxButtons && hasHiddenPagesAfter && ellipsis){
pageButtons.push(
<PaginationButton
key='ellipsis'
disabled
buttonComponentClass={buttonComponentClass}>
<span aria-label='More'>...</span>
</PaginationButton>
);
}
return pageButtons;
},
renderPrev() {
if(!this.props.prev){
return null;
}
return (
<PaginationButton
key='prev'
eventKey={this.props.activePage - 1}
disabled={this.props.activePage === 1}
onSelect={this.props.onSelect}
buttonComponentClass={this.props.buttonComponentClass}>
<span aria-label='Previous'>‹</span>
</PaginationButton>
);
},
renderNext() {
if(!this.props.next){
return null;
}
return (
<PaginationButton
key='next'
eventKey={this.props.activePage + 1}
disabled={this.props.activePage >= this.props.items}
onSelect={this.props.onSelect}
buttonComponentClass={this.props.buttonComponentClass}>
<span aria-label='Next'>›</span>
</PaginationButton>
);
},
renderFirst() {
if(!this.props.first){
return null;
}
return (
<PaginationButton
key='first'
eventKey={1}
disabled={this.props.activePage === 1 }
onSelect={this.props.onSelect}
buttonComponentClass={this.props.buttonComponentClass}>
<span aria-label='First'>«</span>
</PaginationButton>
);
},
renderLast() {
if(!this.props.last){
return null;
}
return (
<PaginationButton
key='last'
eventKey={this.props.items}
disabled={this.props.activePage >= this.props.items}
onSelect={this.props.onSelect}
buttonComponentClass={this.props.buttonComponentClass}>
<span aria-label='Last'>»</span>
</PaginationButton>
);
},
render() {
return (
<ul
{...this.props}
className={classNames(this.props.className, this.getBsClassSet())}>
{this.renderFirst()}
{this.renderPrev()}
{this.renderPageButtons()}
{this.renderNext()}
{this.renderLast()}
</ul>
);
}
});
export default Pagination;
|
examples/demo3.js | seolheehwang/seolhee | import React from 'react';
import ReactDOM from 'react-dom';
import Gallery from '../src/Gallery';
class Demo3 extends React.Component {
constructor(props){
super(props);
this.state = {
images: this.props.images
};
}
render () {
return (
<div style={{
display: "block",
minHeight: "1px",
width: "100%",
border: "1px solid #ddd",
overflow: "auto"}}>
<Gallery
images={this.state.images}
enableLightbox={false}
enableImageSelection={false}/>
</div>
);
}
}
Demo3.propTypes = {
images: React.PropTypes.arrayOf(
React.PropTypes.shape({
src: React.PropTypes.string.isRequired,
thumbnail: React.PropTypes.string.isRequired,
srcset: React.PropTypes.array,
caption: React.PropTypes.string,
thumbnailWidth: React.PropTypes.number.isRequired,
thumbnailHeight: React.PropTypes.number.isRequired
})
).isRequired
};
Demo3.defaultProps = {
images: shuffleArray([
{
src: "https://c2.staticflickr.com/9/8817/28973449265_07e3aa5d2e_b.jpg",
thumbnail: "https://c2.staticflickr.com/9/8817/28973449265_07e3aa5d2e_n.jpg",
thumbnailWidth: 320,
thumbnailHeight: 174,
caption: "After Rain (Jeshu John - designerspics.com)"
},
{
src: "https://c6.staticflickr.com/9/8890/28897154101_a8f55be225_b.jpg",
thumbnail: "https://c6.staticflickr.com/9/8890/28897154101_a8f55be225_n.jpg",
thumbnailWidth: 320,
thumbnailHeight: 183,
caption: "37H (gratispgraphy.com)"
},
{
src: "https://c7.staticflickr.com/9/8106/28941228886_86d1450016_b.jpg",
thumbnail: "https://c7.staticflickr.com/9/8106/28941228886_86d1450016_n.jpg",
thumbnailWidth: 271,
thumbnailHeight: 320,
caption: "Orange Macro (Tom Eversley - isorepublic.com)"
},
{
src: "https://c6.staticflickr.com/9/8342/28897193381_800db6419e_b.jpg",
thumbnail: "https://c6.staticflickr.com/9/8342/28897193381_800db6419e_n.jpg",
thumbnailWidth: 320,
thumbnailHeight: 213,
caption: "201H (gratisography.com)"
},
{
src: "https://c8.staticflickr.com/9/8104/28973555735_ae7c208970_b.jpg",
thumbnail: "https://c8.staticflickr.com/9/8104/28973555735_ae7c208970_n.jpg",
thumbnailWidth: 320,
thumbnailHeight: 213,
caption: "Flower Interior Macro (Tom Eversley - isorepublic.com)"
},
{
src: "https://c1.staticflickr.com/9/8707/28868704912_cba5c6600e_b.jpg",
thumbnail: "https://c1.staticflickr.com/9/8707/28868704912_cba5c6600e_n.jpg",
thumbnailWidth: 320,
thumbnailHeight: 213,
caption: "Man on BMX (Tom Eversley - isorepublic.com)"
},
{
src: "https://c4.staticflickr.com/9/8578/28357117603_97a8233cf5_b.jpg",
thumbnail: "https://c4.staticflickr.com/9/8578/28357117603_97a8233cf5_n.jpg",
thumbnailWidth: 320,
thumbnailHeight: 213,
caption: "Ropeman - Thailand (Tom Eversley - isorepublic.com)"
},
{
src: "https://c1.staticflickr.com/9/8056/28354485944_148d6a5fc1_b.jpg",
thumbnail: "https://c1.staticflickr.com/9/8056/28354485944_148d6a5fc1_n.jpg",
thumbnailWidth: 257,
thumbnailHeight: 320,
caption: "A photo by 贝莉儿 NG. (unsplash.com)"
}
])
};
ReactDOM.render(<Demo3 />, document.getElementById('demo3'));
|
js/messages/Post.js | andrej-kolic/A1terEg0 | import React from 'react';
import moment from 'moment'
import createLogger from '../logger';
const log = createLogger('components.Post');
export default class Post extends React.Component {
constructor(props) {
super(props);
this.state = { dateDescription: this.getDateDescription() };
}
getDateDescription = () => moment(this.props.message.createdAt * 1000).fromNow();
componentDidMount() {
this.timerId = setInterval(
() => this.setState({ dateDescription: this.getDateDescription() }),
30000
);
}
componentWillUnmount() {
log.debug('componentWillUnmount');
clearInterval(this.timerId);
}
render() {
const highlightStyle = this.props.highlight ? styles.highlight : {};
const highlightArrowStyle = this.props.highlight ? styles.highlightArrow : {};
return (
<div>
<div style={styles.container}>
<img src={this.props.viewer.avatar} style={styles.avatar} />
<div style={{ ...styles.arrow, ...highlightArrowStyle }} />
<div style={styles.messageContainer}>
<span
style={{ ...styles.message, ...highlightStyle }}>{this.props.message.content}</span>
</div>
<button
onClick={() => this.props.onStartEditing(this.props.message)}
className="fa fa-pencil"
style={{ ...styles.messageButton, ...styles.messageButtonEdit }}
>
</button>
<button
onClick={() => this.props.onDelete(this.props.message)}
className="fa fa-times fa-2x"
style={styles.messageButton}
>
</button>
</div>
<div style={styles.timestamp}>{this.state.dateDescription}</div>
</div>
);
}
}
const styles = {
container: {
display: 'flex',
marginTop: 20,
},
avatar: {
width: 44,
height: 44,
marginRight: 5,
borderRadius: 22,
},
messageContainer: {
flex: 'auto',
},
arrow: {
border: '7px solid transparent',
borderRightColor: 'white',
alignSelf: 'flex-start',
marginTop: 7,
},
message: {
display: 'inline-block',
padding: 10,
backgroundColor: 'white',
borderRadius: 4,
alignSelf: 'center',
fontSize: 16,
color: '#555',
wordWrap: 'break-word',
overflow: 'hidden',
},
timestamp: {
paddingLeft: 61,
fontSize: 12,
color: '#999',
},
highlight: {
backgroundColor: '#ffff91',
},
highlightArrow: {
borderRightColor: '#ffff91',
},
messageButton: {
border: 0,
background: 'none',
marginLeft: 10,
opacity: 0.4,
fontSize: 16,
borderWidth: 1,
borderStyle: 'dotted',
width: 26,
height: 26,
borderRadius: 13,
},
messageButtonEdit: {}
};
|
node_modules/react-bootstrap/es/MediaList.js | Chen-Hailin/iTCM.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 MediaList = function (_React$Component) {
_inherits(MediaList, _React$Component);
function MediaList() {
_classCallCheck(this, MediaList);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
MediaList.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('ul', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return MediaList;
}(React.Component);
export default bsClass('media-list', MediaList); |
src/svg-icons/av/snooze.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvSnooze = (props) => (
<SvgIcon {...props}>
<path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm-3-9h3.63L9 15.2V17h6v-2h-3.63L15 10.8V9H9v2z"/>
</SvgIcon>
);
AvSnooze = pure(AvSnooze);
AvSnooze.displayName = 'AvSnooze';
AvSnooze.muiName = 'SvgIcon';
export default AvSnooze;
|
src/client/components/Html.js | BhumiSukhadiya/React_Project_Repo | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import serialize from 'serialize-javascript';
class Html extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
styles: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string.isRequired,
cssText: PropTypes.string.isRequired,
}).isRequired),
scripts: PropTypes.arrayOf(PropTypes.string.isRequired),
// eslint-disable-next-line react/forbid-prop-types
state: PropTypes.object,
children: PropTypes.string.isRequired,
};
static defaultProps = {
styles: [],
scripts: [],
state: null,
};
render() {
const { title, description, styles, scripts, state, children } = this.props;
return (
<html className="no-js" lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<title>{title}</title>
<meta name="description" content={description} />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="apple-touch-icon" href="apple-touch-icon.png" />
<link rel="stylesheet" href="app.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
{styles.map(style =>
<style
key={style.id}
id={style.id}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: style.cssText }}
/>,
)}
</head>
<body>
<div
id="app"
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: children }}
/>
{state && (
<script
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html:
`window.APP_STATE=${serialize(state, { isJSON: true })}` }}
/>
)}
{scripts.map(script => <script key={script} src={script} />)}
</body>
</html>
);
}
}
export default Html;
|
reflux-app/components/Status/PassiveStatus.js | Orientsoft/conalog-front | import React from 'react'
import { FormattedMessage } from 'react-intl';
let message = require('antd/lib/message')
let TimePicker = require('antd/lib/time-picker')
let Switch = require('antd/lib/switch')
let Tag = require('antd/lib/tag')
let Modal = require('antd/lib/modal')
let Icon = require('antd/lib/icon')
import AppActions from '../../actions/AppActions'
import AppStore from '../../stores/AppStore'
import constants from '../../const'
import _ from 'lodash'
class PassiveStatus extends React.Component {
constructor(props) {
super(props)
this.state = {
passiveStatusList: [],
passiveStatusListAll:[],
messageModal:false,
messageContent:'',
passiveStatus:[]
}
}
componentDidMount() {
this.unsubscribe = AppStore.listen(function(state) {
this.setState(state)
}.bind(this))
AppActions.getPassiveStatusList()
// start to get passive collector list in loop
this.loop = setInterval(function() {
AppActions.getPassiveStatusList()
}, constants.STATUS_REFRESH_INTERVAL)
}
componentWillUnmount() {
// stop list loop
clearInterval(this.loop)
if (_.isFunction(this.unsubscribe))
this.unsubscribe();
}
setPassiveSwitch(switcher) {
let id = this["data-id"]
// console.log('setPassiveSwitch', {id: id, switch: switcher, category: 'passive'})
AppActions.setCollectorSwitch({id: id, switch: switcher, category: 'passive'})
}
showAllStatus(index, e){
let id = e.target.getAttribute("data-id")
this.setState({
messageModal:true,
messageContent:this.state.passiveStatusListAll[index].status.lastActivity.data
})
}
showPartStatus(index, e){
this.setState({
messageModal:false
})
}
render() {
// render status list
let createPassiveStatus = (line, index) => {
// line = { _id, name, ts, type, trigger, cmd, param, host, status }
// status = { runningFlag, lastActivity }
// lastActivity = { ts, success[, stdout, stderr] }
let passiveStatus
// console.log('PassiveStatus::render', line.status)
let date = new Date(line.ts)
date = date.toLocaleString()
let idx = _.indexOf(this.state.passiveStatusChecklist, line._id)
// console.log('createPassiveStatus', this.state.passiveStatusChecklist, line._id, idx)
let triggerDate = new Date(parseInt(line.trigger))
// create status columns
let lastActivityTs
let lastActivityMsg
let execCount
let operation
if (line.status.runningFlag) {
execCount = line.status.lastActivity.execCounter
lastActivityTs = new Date(parseInt(line.status.lastActivity.ts)).toLocaleString()
switch (line.status.lastActivity.status) {
case 'Success':
if(line.status.lastActivity.data){
lastActivityMsg = <td> <Tag color="green"> stdout </Tag><Tag onClick={this.showAllStatus.bind(this, index)} color="green"> + </Tag> { line.status.lastActivity.data.toString() } </td>
}else if (line.status.lastActivity.stderr){
lastActivityMsg = <td> <Tag color="red"> stderr </Tag> { line.status.lastActivity.stderr.toString() } </td>
}
break
case 'Error':
if(line.status.lastActivity.data){
lastActivityMsg = <td> <Tag color="red"> stderr </Tag><Tag onClick={this.showAllStatus.bind(this, index)} color="red"> + </Tag> { line.status.lastActivity.data.toString() } </td>
}
break
default:
lastActivityMsg = <td> <Tag color="yellow"> Pending </Tag> </td>
break
}
operation = <Switch data-id={line._id}
data-switch={false}
defaultChecked={true}
onChange={this.setPassiveSwitch}
size="small" />
}
else {
execCount = 0
lastActivityTs = 'N/A'
lastActivityMsg = <td> <Tag color="yellow"> N/A </Tag> </td>
operation = <Switch data-id={line._id}
data-switch={true}
defaultChecked={false}
onChange={this.setPassiveSwitch}
size="small" />
}
if (idx == -1)
passiveStatus = <tr key={ index }>
<td>{ line.name }</td>
<td>{ date }</td>
<td>{ line.type }</td>
<td>{ (line.cmd == '') ? 'N/A' : line.cmd }</td>
<td>{ line.param }</td>
<td>{ line.host }</td>
<td>{ execCount }</td>
<td>{ lastActivityTs }</td>
{ lastActivityMsg }
<td>{ operation }</td>
</tr>
else
passiveStatus = <tr key={ index }>
<td>{ line.name }</td>
<td>{ date }</td>
<td>{ line.type }</td>
<td>{ (line.cmd == '') ? 'N/A' : line.cmd }</td>
<td>{ line.param }</td>
<td>{ line.host }</td>
<td>{ execCount }</td>
<td>{ lastActivityTs }</td>
{ lastActivityMsg }
<td>{ operation }</td>
</tr>
return passiveStatus
}
let passiveStatusTable = this.state.passiveStatusList.map(createPassiveStatus.bind(this))
return (
<div>
<Modal
title = "Last Activity Message"
visible = {this.state.messageModal}
onOk = {this.showPartStatus.bind(this)}
onCancel = {this.showPartStatus.bind(this)}
footer = {null}
className = 'statusModal'
>
{this.state.messageContent}
</Modal>
<div className=" p-b-10 p-t-10">
<table id="demo-custom-toolbar" data-toggle="table"
data-toolbar="#demo-delete-row"
data-search="true"
data-show-refresh="true"
data-show-toggle="true"
data-show-columns="true"
data-sort-name="id"
data-page-list="[5, 10, 20]"
data-page-size="5"
data-pagination="true" data-show-pagination-switch="true" className="table table-bordered table-hover">
<thead>
<tr>
<th data-field="name" data-sortable="true"><FormattedMessage id="name"/></th>
<th data-field="date" data-sortable="true" data-formatter="dateFormatter"><FormattedMessage id="date"/></th>
<th data-field="amount" data-align="center" data-sortable="true" data-sorter=""><FormattedMessage id="types"/></th>
<th data-field="cmd" data-align="center" data-sortable="true" data-sorter=""><FormattedMessage id="command"/></th>
<th data-field="parameter" data-align="center" data-sortable="true" data-sorter=""><FormattedMessage id="para"/></th>
<th data-field="host" data-align="center" data-sortable="true" data-sorter=""><FormattedMessage id="host"/></th>
<th data-field="execCount" data-align="center" data-sortable="true" data-sorter=""><FormattedMessage id="execCount"/></th>
<th data-field="lastTs" data-align="center" data-sortable="true" data-sorter=""><FormattedMessage id="lastActivityTime"/></th>
<th data-field="lastMsg" data-align="center" data-sortable="true" data-sorter=""><FormattedMessage id="lastActivityMessage"/></th>
<th data-field="operation" data-align="center" data-sortable="true" data-sorter=""><FormattedMessage id="operation"/></th>
</tr>
</thead>
<tbody>
{ passiveStatusTable }
</tbody>
</table>
</div>
</div>
)
}
}
PassiveStatus.propTypes = {
}
PassiveStatus.defaultProps = {
}
export default PassiveStatus
|
src/modals/AddContact.js | galaxyfeeder/sschat-client | import React from 'react';
import ReactModal from 'react-modal';
class AddContact extends React.Component {
constructor (props){
super(props);
this.handleClose = this.handleClose.bind(this);
this.handleCancel = this.handleCancel.bind(this);
this.handleFileChange = this.handleFileChange.bind(this);
this.handleTextChange = this.handleTextChange.bind(this);
this.handleNameChange = this.handleNameChange.bind(this);
this.state = {
pub_key: undefined,
name: undefined
}
}
handleClose (e){
this.setState({pub_key: '', name: ''});
this.props.handleAddContact(this.state.pub_key, this.state.name);
}
handleCancel (e){
this.setState({pub_key: '', name: ''});
this.props.handleAddContact(undefined, undefined);
}
handleFileChange (e){
const fileToRead = e.target.files[0];
let reader = new FileReader();
reader.readAsBinaryString(fileToRead);
reader.onload = (event) => {
this.setState({pub_key: event.target.result});
};
reader.onerror = (event) => {};
}
handleTextChange (e){
this.setState({pub_key: e.target.value});
}
handleNameChange (e){
this.setState({name: e.target.value});
}
render (){
return (
<ReactModal isOpen={this.props.showModal}
contentLabel="Add new contact"
style={{
content: {
width: '35%',
height: '50%',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)'
}
}}>
<h2>Add new contact</h2>
<div className="form-group">
<label>Contact name</label>
<input className="form-control" type="text" onChange={this.handleNameChange} value={this.state.name} />
</div>
<div className="form-group">
<label>Public key (text or file)</label>
<textarea className="form-control" onChange={this.handleTextChange} value={this.state.pub_key} rows={9}/>
</div>
<div className="form-group">
<input type="file" onChange={this.handleFileChange} />
</div>
<button className="btn btn-success" onClick={this.handleClose}>Add this contact</button>
<button className="btn btn-primary" onClick={this.handleCancel}>Cancel</button>
</ReactModal>
);
}
}
export default AddContact;
|
src/svg-icons/device/battery-90.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBattery90 = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h10V5.33z"/><path d="M7 8v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8H7z"/>
</SvgIcon>
);
DeviceBattery90 = pure(DeviceBattery90);
DeviceBattery90.displayName = 'DeviceBattery90';
DeviceBattery90.muiName = 'SvgIcon';
export default DeviceBattery90;
|
bench/pages/stateless-big.js | dizlexik/next.js | import React from 'react'
export default () => {
return (
<ul>
{items()}
</ul>
)
}
const items = () => {
var out = new Array(10000)
for (let i = 0; i < out.length; i++) {
out[i] = <li key={i}>This is row {i + 1}</li>
}
return out
}
|
src/svg-icons/content/unarchive.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentUnarchive = (props) => (
<SvgIcon {...props}>
<path d="M20.55 5.22l-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.15.55L3.46 5.22C3.17 5.57 3 6.01 3 6.5V19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.49-.17-.93-.45-1.28zM12 9.5l5.5 5.5H14v2h-4v-2H6.5L12 9.5zM5.12 5l.82-1h12l.93 1H5.12z"/>
</SvgIcon>
);
ContentUnarchive = pure(ContentUnarchive);
ContentUnarchive.displayName = 'ContentUnarchive';
ContentUnarchive.muiName = 'SvgIcon';
export default ContentUnarchive;
|
packages/react-error-overlay/src/containers/StackFrameCodeBlock.js | peopleticker/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* @flow */
import React from 'react';
import CodeBlock from '../components/CodeBlock';
import { applyStyles } from '../utils/dom/css';
import { absolutifyCaret } from '../utils/dom/absolutifyCaret';
import type { ScriptLine } from '../utils/stack-frame';
import { primaryErrorStyle, secondaryErrorStyle } from '../styles';
import generateAnsiHTML from '../utils/generateAnsiHTML';
import codeFrame from 'babel-code-frame';
type StackFrameCodeBlockPropsType = {|
lines: ScriptLine[],
lineNum: number,
columnNum: ?number,
contextSize: number,
main: boolean,
|};
// Exact type workaround for spread operator.
// See: https://github.com/facebook/flow/issues/2405
type Exact<T> = $Shape<T>;
function StackFrameCodeBlock(props: Exact<StackFrameCodeBlockPropsType>) {
const { lines, lineNum, columnNum, contextSize, main } = props;
const sourceCode = [];
let whiteSpace = Infinity;
lines.forEach(function(e) {
const { content: text } = e;
const m = text.match(/^\s*/);
if (text === '') {
return;
}
if (m && m[0]) {
whiteSpace = Math.min(whiteSpace, m[0].length);
} else {
whiteSpace = 0;
}
});
lines.forEach(function(e) {
let { content: text } = e;
const { lineNumber: line } = e;
if (isFinite(whiteSpace)) {
text = text.substring(whiteSpace);
}
sourceCode[line - 1] = text;
});
const ansiHighlight = codeFrame(
sourceCode.join('\n'),
lineNum,
columnNum == null ? 0 : columnNum - (isFinite(whiteSpace) ? whiteSpace : 0),
{
forceColor: true,
linesAbove: contextSize,
linesBelow: contextSize,
}
);
const htmlHighlight = generateAnsiHTML(ansiHighlight);
const code = document.createElement('code');
code.innerHTML = htmlHighlight;
absolutifyCaret(code);
const ccn = code.childNodes;
// eslint-disable-next-line
oLoop: for (let index = 0; index < ccn.length; ++index) {
const node = ccn[index];
const ccn2 = node.childNodes;
for (let index2 = 0; index2 < ccn2.length; ++index2) {
const lineNode = ccn2[index2];
const text = lineNode.innerText;
if (text == null) {
continue;
}
if (text.indexOf(' ' + lineNum + ' |') === -1) {
continue;
}
// $FlowFixMe
applyStyles(node, main ? primaryErrorStyle : secondaryErrorStyle);
// eslint-disable-next-line
break oLoop;
}
}
return <CodeBlock main={main} codeHTML={code.innerHTML} />;
}
export default StackFrameCodeBlock;
|
app/javascript/flavours/glitch/features/favourited_statuses/index.js | glitch-soc/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { debounce } from 'lodash';
import { fetchFavouritedStatuses, expandFavouritedStatuses } from 'flavours/glitch/actions/favourites';
import Column from 'flavours/glitch/features/ui/components/column';
import ColumnHeader from 'flavours/glitch/components/column_header';
import { addColumn, removeColumn, moveColumn } from 'flavours/glitch/actions/columns';
import StatusList from 'flavours/glitch/components/status_list';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
heading: { id: 'column.favourites', defaultMessage: 'Favourites' },
});
const mapStateToProps = state => ({
statusIds: state.getIn(['status_lists', 'favourites', 'items']),
isLoading: state.getIn(['status_lists', 'favourites', 'isLoading'], true),
hasMore: !!state.getIn(['status_lists', 'favourites', 'next']),
});
export default @connect(mapStateToProps)
@injectIntl
class Favourites extends ImmutablePureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
statusIds: ImmutablePropTypes.list.isRequired,
intl: PropTypes.object.isRequired,
columnId: PropTypes.string,
multiColumn: PropTypes.bool,
hasMore: PropTypes.bool,
isLoading: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchFavouritedStatuses());
}
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('FAVOURITES', {}));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
setRef = c => {
this.column = c;
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandFavouritedStatuses());
}, 300, { leading: true })
render () {
const { intl, statusIds, columnId, multiColumn, hasMore, isLoading } = this.props;
const pinned = !!columnId;
const emptyMessage = <FormattedMessage id='empty_column.favourited_statuses' defaultMessage="You don't have any favourite posts yet. When you favourite one, it will show up here." />;
return (
<Column bindToDocument={!multiColumn} ref={this.setRef} name='favourites' label={intl.formatMessage(messages.heading)}>
<ColumnHeader
icon='star'
title={intl.formatMessage(messages.heading)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
showBackButton
/>
<StatusList
trackScroll={!pinned}
statusIds={statusIds}
scrollKey={`favourited_statuses-${columnId}`}
hasMore={hasMore}
isLoading={isLoading}
onLoadMore={this.handleLoadMore}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
/>
</Column>
);
}
}
|
src/index.js | td-ui/td-ui.github.io | /**
* @Author: Zhengfeng.Yao <yzf>
* @Date: 2017-06-08 15:14:16
* @Last modified by: yzf
* @Last modified time: 2017-06-08 15:14:19
*/
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, match, useRouterHistory } from 'react-router';
import { createHistory } from 'history';
import { createElement, getRoutes } from './utils';
import docs from './d.DOCS';
const { pathname, search, hash } = window.location;
const location = `${pathname}${search}${hash}`;
const routes = getRoutes(docs);
const basename = '/';
match({ routes, location, basename }, () => {
const router =
(<Router
history={useRouterHistory(createHistory)({ basename })}
routes={routes}
createElement={createElement}
/>);
ReactDOM.render(
router,
document.getElementById('app')
);
});
window.docs = docs;
|
app/javascript/mastodon/features/account_timeline/components/header.js | pfm-eyesightjp/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import InnerHeader from '../../account/components/header';
import ActionBar from '../../account/components/action_bar';
import MissingIndicator from '../../../components/missing_indicator';
import ImmutablePureComponent from 'react-immutable-pure-component';
export default class Header extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map,
me: PropTypes.number.isRequired,
onFollow: PropTypes.func.isRequired,
onBlock: PropTypes.func.isRequired,
onMention: PropTypes.func.isRequired,
onReport: PropTypes.func.isRequired,
onMute: PropTypes.func.isRequired,
onBlockDomain: PropTypes.func.isRequired,
onUnblockDomain: PropTypes.func.isRequired,
};
static contextTypes = {
router: PropTypes.object,
};
handleFollow = () => {
this.props.onFollow(this.props.account);
}
handleBlock = () => {
this.props.onBlock(this.props.account);
}
handleMention = () => {
this.props.onMention(this.props.account, this.context.router.history);
}
handleReport = () => {
this.props.onReport(this.props.account);
}
handleMute = () => {
this.props.onMute(this.props.account);
}
handleBlockDomain = () => {
const domain = this.props.account.get('acct').split('@')[1];
if (!domain) return;
this.props.onBlockDomain(domain, this.props.account.get('id'));
}
handleUnblockDomain = () => {
const domain = this.props.account.get('acct').split('@')[1];
if (!domain) return;
this.props.onUnblockDomain(domain, this.props.account.get('id'));
}
render () {
const { account, me } = this.props;
if (account === null) {
return <MissingIndicator />;
}
return (
<div className='account-timeline__header'>
<InnerHeader
account={account}
me={me}
onFollow={this.handleFollow}
/>
<ActionBar
account={account}
me={me}
onBlock={this.handleBlock}
onMention={this.handleMention}
onReport={this.handleReport}
onMute={this.handleMute}
onBlockDomain={this.handleBlockDomain}
onUnblockDomain={this.handleUnblockDomain}
/>
</div>
);
}
}
|
envkey-react/src/components/env_manager/env_cell/traits/flashable_cell.js | envkey/envkey-app | import React from 'react'
import h from "lib/ui/hyperscript_with_helpers"
import Flashable from 'components/shared/traits/flashable'
const FlashableCell = Cell => class extends Flashable(Cell) {
_renderCellContents(){
return super._renderCellContents().concat([
this._renderFlash()
])
}
}
export default FlashableCell |
src/example/FluxOnly/FluxOnly.js | halhenke/component-router | import React from 'react';
import {Store, Url, Actions} from '../..';
import styles from './FluxOnly.css';
const Switch = React.createClass({
getInitialState() {
return Store.getQuery();
},
componentDidMount() {
this.unsubscribe =
Store.subscribe(this.onChange);
},
componentWillUnmount() {
this.unsubscribe();
},
switchComponents() {
let query = 'Nothing';
if ('switchBlock' in this.state) {
query = this.state.switchBlock;
}
return query;
},
onChange() {
this.setState(Store.getQuery());
},
render() {
return (
<div className={styles.content}>
<p>Current state is: {this.switchComponents()} Clicked</p>
</div>
);
}
});
const FluxWithUrls = React.createClass({
render() {
return (
<div className={styles.fluxonly}>
<div>
<h2>Using component-router Urls</h2>
</div>
<div>
<Url query={{switchBlock: 'First'}}>
Render First Component
</Url>
<Url query={{switchBlock: 'Second'}}>
Render Second Component
</Url>
<Switch />
</div>
</div>
);
}
});
const PureFlux = React.createClass({
getInitialState() {
return Store.getQuery();
},
componentDidMount() {
this.unsubscribe =
Store.subscribe(this.onChange);
},
componentWillUnmount() {
this.unsubscribe();
},
onChange() {
this.setState(Store.getQuery());
},
onClick(newVal) {
return event => {
event.preventDefault();
Store.dispatch(Actions.navigateTo({pathname: '/', query: newVal}));
};
},
activeClass({switchBlock: val}) {
let cName = '';
if (this.state.switchBlock === val) {
cName = 'active';
}
return cName;
},
render() {
const first = {switchBlock: 'First'};
const second = {switchBlock: 'Second'};
return (
<div className={styles.fluxonly}>
<div>
<h2>Using only anchor elements</h2>
</div>
<div>
<button className={this.activeClass(first)} onClick={this.onClick(first)}>
Render First Component
</button>
<button className={this.activeClass(second)} onClick={this.onClick(second)}>
Render Second Component
</button>
<Switch />
</div>
</div>
);
}
});
const CompoundFlux = React.createClass({
componentWillUnmount() {
Store.dispatch(Actions.removeParam({namespace: 'switchBlock'}));
},
render() {
return (
<div>
<h1>Switch Components by subscribing directly to the Flux Store</h1>
<div>
<FluxWithUrls />
</div>
<div className={styles.container}>
<PureFlux />
</div>
</div>
);
}
});
export default CompoundFlux;
|
app/javascript/flavours/glitch/util/react_router_helpers.js | Kirishima21/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { Switch, Route } from 'react-router-dom';
import ColumnLoading from 'flavours/glitch/features/ui/components/column_loading';
import BundleColumnError from 'flavours/glitch/features/ui/components/bundle_column_error';
import BundleContainer from 'flavours/glitch/features/ui/containers/bundle_container';
// Small wrapper to pass multiColumn to the route components
export class WrappedSwitch extends React.PureComponent {
render () {
const { multiColumn, children } = this.props;
return (
<Switch>
{React.Children.map(children, child => React.cloneElement(child, { multiColumn }))}
</Switch>
);
}
}
WrappedSwitch.propTypes = {
multiColumn: PropTypes.bool,
children: PropTypes.node,
};
// Small Wraper to extract the params from the route and pass
// them to the rendered component, together with the content to
// be rendered inside (the children)
export class WrappedRoute extends React.Component {
static propTypes = {
component: PropTypes.func.isRequired,
content: PropTypes.node,
multiColumn: PropTypes.bool,
componentParams: PropTypes.object,
}
static defaultProps = {
componentParams: {},
};
renderComponent = ({ match }) => {
const { component, content, multiColumn, componentParams } = this.props;
return (
<BundleContainer fetchComponent={component} loading={this.renderLoading} error={this.renderError}>
{Component => <Component params={match.params} multiColumn={multiColumn} {...componentParams}>{content}</Component>}
</BundleContainer>
);
}
renderLoading = () => {
return <ColumnLoading />;
}
renderError = (props) => {
return <BundleColumnError {...props} />;
}
render () {
const { component: Component, content, ...rest } = this.props;
return <Route {...rest} render={this.renderComponent} />;
}
}
|
src/packages/@ncigdc/modern_components/CancerDistributionBarChart/CancerDistributionBarChart.js | NCI-GDC/portal-ui | // @flow
import React from 'react';
import { compose, withState } from 'recompose';
import { sortBy, sum, get } from 'lodash';
import withRouter from '@ncigdc/utils/withRouter';
import { Row, Column } from '@ncigdc/uikit/Flex';
import DownloadVisualizationButton from '@ncigdc/components/DownloadVisualizationButton';
import { withTheme } from '@ncigdc/theme';
import BarChart from '@ncigdc/components/Charts/BarChart';
import FilteredStackedBarChart from '@ncigdc/components/Charts/FilteredStackedBarChart';
import wrapSvg from '@ncigdc/utils/wrapSvg';
import ExploreLink from '@ncigdc/components/Links/ExploreLink';
import ProjectsLink from '@ncigdc/components/Links/ProjectsLink';
import { IGroupFilter } from '@ncigdc/utils/filters/types';
import { cnvColors } from '@ncigdc/utils/filters/prepared/significantConsequences';
import { renderToString } from 'react-dom/server';
import { makeFilter, replaceFilters } from '@ncigdc/utils/filters';
import ExploreSSMLink from '@ncigdc/components/Links/ExploreSSMLink';
type TProps = {
style: Object,
filters: ?IGroupFilter,
cases: {
total: {
project__project_id: {
buckets: Array<{
key: string,
doc_count: number,
}>,
},
},
filtered: {
project__project_id: {
buckets: Array<{
key: string,
doc_count: number,
}>,
},
},
},
ssms: {
hits: {
total: number,
},
},
aggregations: Object,
theme: Object,
push: Function,
ChartTitle: ReactClass<{}>,
};
const CHART_HEIGHT = 295;
const CHART_MARGINS = {
bottom: 75,
left: 55,
right: 50,
top: 20,
};
export type TChartTitleProps = {
cases: number,
projects: Array<{ project_id: string }>,
ssms: number,
filters: any,
};
const DefaultChartTitle = ({
type = 'mutations',
cases = 0,
projects = [],
ssms = 0,
filters,
}: TChartTitleProps) => {
return (
<div
style={{
textTransform: 'uppercase',
padding: '0 2rem',
}}
>
{type === 'cnvs' ? (
<span>
<ExploreLink
query={{
searchTableTab: 'cases',
filters,
}}
>
{cases.toLocaleString()}
</ExploreLink>
{' '}
cases affected by
{' '}
{ssms.toLocaleString()}
{' '}
cnv events across
{' '}
</span>
) : (
<span>
<ExploreSSMLink filters={filters} searchTableTab="cases">
{cases.toLocaleString()}
</ExploreSSMLink>
{' '}
cases affected by
{' '}
<ExploreSSMLink filters={filters} searchTableTab="mutations">
{ssms.toLocaleString()}
</ExploreSSMLink>
{' '}
mutations across
{' '}
</span>
)}
<ProjectsLink
query={{
filters: {
op: 'and',
content: [
{
op: 'in',
content: {
field: 'projects.project_id',
value: projects.map(p => p.project_id),
},
},
],
},
}}
>
{projects.length.toLocaleString()}
</ProjectsLink>
projects
</div>
);
};
const initalCnv = {
gain: true,
// amplification: true,
loss: true, // shallow_loss: true,
// deep_loss: true,
};
export default compose(
withRouter,
withTheme,
withState('cnv', 'setCnv', initalCnv),
withState('collapsed', 'setCollapsed', false),
)(
(
{
viewer: { explore: { cases, ssms } },
theme,
push,
ChartTitle = DefaultChartTitle,
filters,
chartType,
cnv,
setCnv,
type,
}: TProps = {},
) => {
let cnvFiltered = {};
let cnvCancerDistData = [];
let cnvChartData = [];
const cnvColumns = ['gain', 'loss']; // ['amplification', 'gain', 'shallowLoss', 'deepLoss'];
if (chartType !== 'ssm') {
cnvColumns.map(cnvType => cases[cnvType].project__project_id.buckets.map(
b => (cnvFiltered = {
...cnvFiltered,
[b.key]: {
...cnvFiltered[b.key],
[cnvType]: b.doc_count,
},
}),
),);
cnvCancerDistData = Object.keys(cnvFiltered).map(p => {
return {
// deep_loss: cnvFiltered[p]['deepLoss'] || 0,
loss: cnvFiltered[p].loss || 0, // shallowLoss
gain: cnvFiltered[p].gain || 0,
// amplification: cnvFiltered[p]['amplification'] || 0,
project_id: p,
num_cases_total: cases.cnvTotal.project__project_id.buckets.filter(
f => f.key === p,
)[0].doc_count,
};
});
cnvChartData = sortBy(
cnvCancerDistData,
d => -cnvColors.reduce(
(acc, f) => acc + d[f.key] / d.num_cases_total * cnv[f.key],
0,
),
)
.slice(0, 20)
.map(d => ({
symbol: d.project_id,
// deep_loss: d.deep_loss / d.num_cases_total * 100,
loss: d.loss / d.num_cases_total * 100, // shallow_loss: d.shallow_loss
gain: d.gain / d.num_cases_total * 100,
// amplification: d.amplification / d.num_cases_total * 100,
total: d.num_cases_total,
onClick: () => push(`/projects/${d.project_id}`),
tooltips: cnvColors.reduce(
(acc, f) => ({
...acc,
[f.key]: (
<span>
{d[f.key].toLocaleString()}
Case
{d[f.key] > 1 ? 's ' : ' '}
Affected in
{' '}
<b>{d.project_id}</b>
<br />
{d[f.key].toLocaleString()}
/
{d.num_cases_total.toLocaleString()}
(
{(d[f.key] / d.num_cases_total * 100).toFixed(2)}
%)
</span>
),
}),
0,
),
}));
}
const chartStyles = {
xAxis: {
stroke: theme.greyScale4,
textFill: theme.greyScale3,
},
yAxis: {
stroke: theme.greyScale4,
textFill: theme.greyScale3,
},
bars: { fill: theme.secondary },
tooltips: {
fill: '#fff',
stroke: theme.greyScale4,
textFill: theme.greyScale3,
},
};
const mutationCancerDistData = (cases.filtered || {
project__project_id: { buckets: [] },
}).project__project_id.buckets.map(b => {
const casesByProjects = cases.total.project__project_id.buckets.filter(
f => f.key === b.key,
);
const totalCasesByProject =
casesByProjects.length > 0 ? casesByProjects[0].doc_count : 0;
return {
freq: b.doc_count / totalCasesByProject,
project_id: b.key,
num_affected_cases: b.doc_count,
num_cases_total: totalCasesByProject,
};
});
const mutationChartData = sortBy(mutationCancerDistData, d => -d.freq)
.slice(0, 20)
.map(d => ({
label: d.project_id,
value: d.freq * 100,
onClick: () => push(`/projects/${d.project_id}`),
tooltip: (
<span>
{d.num_affected_cases.toLocaleString()}
Case
{d.num_affected_cases > 1 ? 's ' : ' '}
Affected in
{' '}
<b>{d.project_id}</b>
<br />
{d.num_affected_cases.toLocaleString()}
/
{d.num_cases_total.toLocaleString()}
(
{(d.freq * 100).toFixed(2)}
%)
</span>
),
}));
const Legends = () => (
<Row
style={{
display: 'flex',
justifyContent: 'center',
}}
>
{cnvColors.map(f => (
<label key={f.key} style={{ paddingRight: '10px' }}>
<span
onClick={() => setCnv({
...cnv,
[f.key]: !cnv[f.key],
})}
style={{
color: f.color,
textAlign: 'center',
border: '2px solid',
height: '18px',
width: '18px',
cursor: 'pointer',
display: 'inline-block',
marginRight: '6px',
marginTop: '3px',
verticalAlign: 'middle',
lineHeight: '16px',
}}
>
{cnv[f.key] ? '✓' : <span> </span>}
</span>
{f.name}
</label>
))}
</Row>
);
return (
<div>
<Row style={{ width: '100%' }}>
{mutationChartData.length >= 5 && (
<span style={{ width: chartType !== 'ssm' ? '50%' : '100%' }}>
<Column style={{ padding: '0 0 0 2rem' }}>
<Row
style={{
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<ChartTitle
cases={sum(
mutationCancerDistData.map(d => d.num_affected_cases),
)}
filters={filters}
projects={mutationCancerDistData}
ssms={get(ssms, 'hits.total', 0)}
/>
<DownloadVisualizationButton
data={mutationChartData.map(d => ({
label: d.label,
value: d.value,
}))}
noText
slug="cancer-distribution-bar-chart"
style={{ marginRight: '2rem' }}
svg={() => wrapSvg({
selector: '#cancer-distribution svg',
title: 'Cancer Distribution',
})}
tooltipHTML="Download image or data"
/>
</Row>
<BarChart
data={mutationChartData}
height={CHART_HEIGHT}
margin={CHART_MARGINS}
styles={chartStyles}
yAxis={{ title: '% of Cases Affected' }}
/>
</Column>
</span>
)}
{chartType !== 'ssm' &&
cnvChartData.length >= 5 && (
<span style={{ width: '50%' }}>
<Column style={{ padding: '0 0 0 2rem' }}>
<Row
style={{
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<ChartTitle
cases={cases.cnvTestedByGene.total}
filters={replaceFilters(
makeFilter([
{
field: 'cases.available_variation_data',
value: 'cnv',
},
]),
filters,
)}
projects={cnvCancerDistData}
ssms={cases.cnvAll.total}
type="cnvs"
/>
<DownloadVisualizationButton
data={cnvChartData.map(d => ({
symbol: d.symbol,
// amplification: d.amplification,
gain: d.gain,
loss: d.loss, // shallow_loss: d.shallow_loss
// deep_loss: d.deep_loss,
total: d.total,
}))}
noText
slug="cancer-distribution-bar-chart"
style={{ marginRight: '2rem' }}
svg={() => wrapSvg({
selector: '.test-stacked-bar-chart svg',
title: 'CNV Distribution',
legends: renderToString(<Legends />),
})}
tooltipHTML="Download image or data"
/>
</Row>
<Column>
<FilteredStackedBarChart
colors={cnvColors.reduce(
(acc, f) => ({
...acc,
[f.key]: f.color,
}),
0,
)}
data={cnvChartData}
displayFilters={cnv}
height={200}
margin={CHART_MARGINS}
styles={chartStyles}
yAxis={{ title: '% of Cases Affected' }}
/>
<Legends />
</Column>
</Column>
</span>
)}
</Row>
</div>
);
},
);
|
src/main/resources/public/js/components/CSVReader.js | SICTIAM/ozwillo-portal | import React from 'react';
import PropTypes from 'prop-types';
import Tools from "../util/tools";
import { i18n } from "../config/i18n-config"
export default class CSVReader extends React.Component {
constructor() {
super();
this._tools = new Tools();
}
state = {
error: null,
fileName: ""
};
componentDidMount(){
this.props.fileName ? this.setState({fileName: this.props.fileName}) : null;
}
cleanInput = () => {
this.inputFile.value = "";
this.setState({fileName: ""});
};
_sanitizeEmailArray = (emailArray) => {
return emailArray.filter(email => this._tools.checkEmail(email));
};
_parseCSVData = (value) => {
let resultArray = value.trim().split(/[\r\n]+/g);
resultArray.filter(elm => elm !== "");
resultArray = this._sanitizeEmailArray(resultArray);
this.props.onFileRead(resultArray);
};
_extractData = (e) => {
let reader = new FileReader();
let files = e.target.files;
//check if that is a real csv
try {
if (files && files.length > 0 && files[0].name.match('.csv')) {
this._extractFileName();
this.props.onFileReading();
reader.onload = () => {
this._parseCSVData(reader.result)
};
reader.readAsText(files[0]);
this.setState({error: null})
} else if(files && files.length > 0) {
this.setState({error: i18n._('error.msg.csv-file-required')});
this.cleanInput();
}
} catch (e) {
this.cleanInput();
this.setState({error: e});
}
};
_extractFileName = () => {
const fileName = this.inputFile.value.split(/.*[\/|\\]/).pop();
this.setState({fileName: fileName})
return fileName;
};
render() {
const {error, fileName} = this.state;
const {requiered} = this.props;
return (
<div className={"csv-reader"}>
<label className="label btn btn-default" htmlFor="fileSelect">
{i18n._("organization.desc.choose-file")}
</label>
<p>
{fileName}
</p>
<input ref={inputFile => this.inputFile = inputFile}
className={"field"} required={requiered}
id="fileSelect" type="file"
accept=".csv" onChange={this._extractData}/>
{error && <div className={"csv-error"}>{error}</div>}
</div>
)
}
}
CSVReader.propTypes = {
onFileRead: PropTypes.func,
onFileReading: PropTypes.func,
fileName: PropTypes.string,
};
|
example/examples/AnimatedViews.js | ksincennes/react-native-maps | import React from 'react';
import {
StyleSheet,
View,
Dimensions,
Animated,
} from 'react-native';
import MapView from 'react-native-maps';
import PanController from './PanController';
import PriceMarker from './AnimatedPriceMarker';
const screen = Dimensions.get('window');
const ASPECT_RATIO = screen.width / screen.height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
const ITEM_SPACING = 10;
const ITEM_PREVIEW = 10;
const ITEM_WIDTH = screen.width - (2 * ITEM_SPACING) - (2 * ITEM_PREVIEW);
const SNAP_WIDTH = ITEM_WIDTH + ITEM_SPACING;
const ITEM_PREVIEW_HEIGHT = 150;
const SCALE_END = screen.width / ITEM_WIDTH;
const BREAKPOINT1 = 246;
const BREAKPOINT2 = 350;
const ONE = new Animated.Value(1);
function getMarkerState(panX, panY, scrollY, i) {
const xLeft = (-SNAP_WIDTH * i) + (SNAP_WIDTH / 2);
const xRight = (-SNAP_WIDTH * i) - (SNAP_WIDTH / 2);
const xPos = -SNAP_WIDTH * i;
const isIndex = panX.interpolate({
inputRange: [xRight - 1, xRight, xLeft, xLeft + 1],
outputRange: [0, 1, 1, 0],
extrapolate: 'clamp',
});
const isNotIndex = panX.interpolate({
inputRange: [xRight - 1, xRight, xLeft, xLeft + 1],
outputRange: [1, 0, 0, 1],
extrapolate: 'clamp',
});
const center = panX.interpolate({
inputRange: [xPos - 10, xPos, xPos + 10],
outputRange: [0, 1, 0],
extrapolate: 'clamp',
});
const selected = panX.interpolate({
inputRange: [xRight, xPos, xLeft],
outputRange: [0, 1, 0],
extrapolate: 'clamp',
});
const translateY = Animated.multiply(isIndex, panY);
const translateX = panX;
const anim = Animated.multiply(isIndex, scrollY.interpolate({
inputRange: [0, BREAKPOINT1],
outputRange: [0, 1],
extrapolate: 'clamp',
}));
const scale = Animated.add(ONE, Animated.multiply(isIndex, scrollY.interpolate({
inputRange: [BREAKPOINT1, BREAKPOINT2],
outputRange: [0, SCALE_END - 1],
extrapolate: 'clamp',
})));
// [0 => 1]
let opacity = scrollY.interpolate({
inputRange: [BREAKPOINT1, BREAKPOINT2],
outputRange: [0, 1],
extrapolate: 'clamp',
});
// if i === index: [0 => 0]
// if i !== index: [0 => 1]
opacity = Animated.multiply(isNotIndex, opacity);
// if i === index: [1 => 1]
// if i !== index: [1 => 0]
opacity = opacity.interpolate({
inputRange: [0, 1],
outputRange: [1, 0],
});
let markerOpacity = scrollY.interpolate({
inputRange: [0, BREAKPOINT1],
outputRange: [0, 1],
extrapolate: 'clamp',
});
markerOpacity = Animated.multiply(isNotIndex, markerOpacity).interpolate({
inputRange: [0, 1],
outputRange: [1, 0],
});
const markerScale = selected.interpolate({
inputRange: [0, 1],
outputRange: [1, 1.2],
});
return {
translateY,
translateX,
scale,
opacity,
anim,
center,
selected,
markerOpacity,
markerScale,
};
}
class AnimatedViews extends React.Component {
constructor(props) {
super(props);
const panX = new Animated.Value(0);
const panY = new Animated.Value(0);
const scrollY = panY.interpolate({
inputRange: [-1, 1],
outputRange: [1, -1],
});
const scrollX = panX.interpolate({
inputRange: [-1, 1],
outputRange: [1, -1],
});
const scale = scrollY.interpolate({
inputRange: [0, BREAKPOINT1],
outputRange: [1, 1.6],
extrapolate: 'clamp',
});
const translateY = scrollY.interpolate({
inputRange: [0, BREAKPOINT1],
outputRange: [0, -100],
extrapolate: 'clamp',
});
const markers = [
{
id: 0,
amount: 99,
coordinate: {
latitude: LATITUDE,
longitude: LONGITUDE,
},
},
{
id: 1,
amount: 199,
coordinate: {
latitude: LATITUDE + 0.004,
longitude: LONGITUDE - 0.004,
},
},
{
id: 2,
amount: 285,
coordinate: {
latitude: LATITUDE - 0.004,
longitude: LONGITUDE - 0.004,
},
},
];
const animations = markers.map((m, i) =>
getMarkerState(panX, panY, scrollY, i));
this.state = {
panX,
panY,
animations,
index: 0,
canMoveHorizontal: true,
scrollY,
scrollX,
scale,
translateY,
markers,
region: new Animated.Region({
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}),
};
}
componentDidMount() {
const { region, panX, panY, scrollX, markers } = this.state;
panX.addListener(this.onPanXChange);
panY.addListener(this.onPanYChange);
region.stopAnimation();
region.timing({
latitude: scrollX.interpolate({
inputRange: markers.map((m, i) => i * SNAP_WIDTH),
outputRange: markers.map(m => m.coordinate.latitude),
}),
longitude: scrollX.interpolate({
inputRange: markers.map((m, i) => i * SNAP_WIDTH),
outputRange: markers.map(m => m.coordinate.longitude),
}),
duration: 0,
}).start();
}
onStartShouldSetPanResponder(e) {
// we only want to move the view if they are starting the gesture on top
// of the view, so this calculates that and returns true if so. If we return
// false, the gesture should get passed to the map view appropriately.
const { panY } = this.state;
const { pageY } = e.nativeEvent;
const topOfMainWindow = ITEM_PREVIEW_HEIGHT + panY.__getValue();
const topOfTap = screen.height - pageY;
return topOfTap < topOfMainWindow;
}
onMoveShouldSetPanResponder(e) {
const { panY } = this.state;
const { pageY } = e.nativeEvent;
const topOfMainWindow = ITEM_PREVIEW_HEIGHT + panY.__getValue();
const topOfTap = screen.height - pageY;
return topOfTap < topOfMainWindow;
}
onPanXChange({ value }) {
const { index } = this.state;
const newIndex = Math.floor(((-1 * value) + (SNAP_WIDTH / 2)) / SNAP_WIDTH);
if (index !== newIndex) {
this.setState({ index: newIndex });
}
}
onPanYChange({ value }) {
const { canMoveHorizontal, region, scrollY, scrollX, markers, index } = this.state;
const shouldBeMovable = Math.abs(value) < 2;
if (shouldBeMovable !== canMoveHorizontal) {
this.setState({ canMoveHorizontal: shouldBeMovable });
if (!shouldBeMovable) {
const { coordinate } = markers[index];
region.stopAnimation();
region.timing({
latitude: scrollY.interpolate({
inputRange: [0, BREAKPOINT1],
outputRange: [
coordinate.latitude,
coordinate.latitude - (LATITUDE_DELTA * 0.5 * 0.375),
],
extrapolate: 'clamp',
}),
latitudeDelta: scrollY.interpolate({
inputRange: [0, BREAKPOINT1],
outputRange: [LATITUDE_DELTA, LATITUDE_DELTA * 0.5],
extrapolate: 'clamp',
}),
longitudeDelta: scrollY.interpolate({
inputRange: [0, BREAKPOINT1],
outputRange: [LONGITUDE_DELTA, LONGITUDE_DELTA * 0.5],
extrapolate: 'clamp',
}),
duration: 0,
}).start();
} else {
region.stopAnimation();
region.timing({
latitude: scrollX.interpolate({
inputRange: markers.map((m, i) => i * SNAP_WIDTH),
outputRange: markers.map(m => m.coordinate.latitude),
}),
longitude: scrollX.interpolate({
inputRange: markers.map((m, i) => i * SNAP_WIDTH),
outputRange: markers.map(m => m.coordinate.longitude),
}),
duration: 0,
}).start();
}
}
}
onRegionChange(/* region */) {
// this.state.region.setValue(region);
}
render() {
const {
panX,
panY,
animations,
canMoveHorizontal,
markers,
region,
} = this.state;
return (
<View style={styles.container}>
<PanController
style={styles.container}
vertical
horizontal={canMoveHorizontal}
xMode="snap"
snapSpacingX={SNAP_WIDTH}
yBounds={[-1 * screen.height, 0]}
xBounds={[-screen.width * (markers.length - 1), 0]}
panY={panY}
panX={panX}
onStartShouldSetPanResponder={this.onStartShouldSetPanResponder}
onMoveShouldSetPanResponder={this.onMoveShouldSetPanResponder}
>
<MapView.Animated
provider={this.props.provider}
style={styles.map}
region={region}
onRegionChange={this.onRegionChange}
>
{markers.map((marker, i) => {
const {
selected,
markerOpacity,
markerScale,
} = animations[i];
return (
<MapView.Marker
key={marker.id}
coordinate={marker.coordinate}
>
<PriceMarker
style={{
opacity: markerOpacity,
transform: [
{ scale: markerScale },
],
}}
amount={marker.amount}
selected={selected}
/>
</MapView.Marker>
);
})}
</MapView.Animated>
<View style={styles.itemContainer}>
{markers.map((marker, i) => {
const {
translateY,
translateX,
scale,
opacity,
} = animations[i];
return (
<Animated.View
key={marker.id}
style={[styles.item, {
opacity,
transform: [
{ translateY },
{ translateX },
{ scale },
],
}]}
/>
);
})}
</View>
</PanController>
</View>
);
}
}
AnimatedViews.propTypes = {
provider: MapView.ProviderPropType,
};
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
},
itemContainer: {
backgroundColor: 'transparent',
flexDirection: 'row',
paddingHorizontal: (ITEM_SPACING / 2) + ITEM_PREVIEW,
position: 'absolute',
// top: screen.height - ITEM_PREVIEW_HEIGHT - 64,
paddingTop: screen.height - ITEM_PREVIEW_HEIGHT - 64,
// paddingTop: !ANDROID ? 0 : screen.height - ITEM_PREVIEW_HEIGHT - 64,
},
map: {
backgroundColor: 'transparent',
...StyleSheet.absoluteFillObject,
},
item: {
width: ITEM_WIDTH,
height: screen.height + (2 * ITEM_PREVIEW_HEIGHT),
backgroundColor: 'red',
marginHorizontal: ITEM_SPACING / 2,
overflow: 'hidden',
borderRadius: 3,
borderColor: '#000',
},
});
module.exports = AnimatedViews;
|
examples/web/client/src/components/RequestsQueue.js | jevakallio/redux-offline | import React from 'react';
import { connect } from 'react-redux';
function RequestsQueue({ actions }) {
if (actions.length === 0) {
return <p>There are no requests</p>;
}
return (
<ul>
{actions.map(action => (
<li key={action.meta.transaction}>
<span>{action.type}</span>
<span>#{action.meta.transaction}</span>
</li>
))}
</ul>
);
}
function mapStateToProps(state) {
return {
actions: state.offline.outbox
};
}
const ConnectedComponent = connect(mapStateToProps)(RequestsQueue);
export { RequestsQueue as RawComponent };
export default ConnectedComponent;
|
src/components/TimeAndSalary/common/DashBoardTable.js | goodjoblife/GoodJobShare | import React from 'react';
import PropTypes from 'prop-types';
import R from 'ramda';
import Table from 'common/table/Table';
import { InfoButton } from 'common/Modal';
import styles from '../TimeAndSalaryBoard/TimeAndSalaryBoard.module.css';
import {
getCompany,
getJobTitle,
getFrequency,
getWeekWorkTime,
getSalary,
formatWage,
formatDate,
getAboutThisJobButton,
} from './formatter';
const DashBoardTable = ({
data,
postProcessRows,
toggleInfoSalaryModal,
toggleInfoTimeModal,
toggleAboutThisJobModal,
}) => (
<Table
className={styles.latestTable}
data={data}
primaryKey="_id"
postProcessRows={postProcessRows}
>
<Table.Column
className={styles.colCompany}
title="公司名稱"
dataField={getCompany}
>
公司名稱
</Table.Column>
<Table.Column
className={styles.colCompany}
title="職稱"
dataField={getJobTitle}
>
職稱
<span className="table-sector">廠區/門市/分公司</span>
</Table.Column>
<Table.Column
className={styles.colWeekTime}
title="一週總工時"
dataField={getWeekWorkTime}
>
一週總工時
</Table.Column>
<Table.Column
className={styles.colFrequency}
title="加班頻率"
dataField={getFrequency}
>
加班頻率
</Table.Column>
<Table.Column
className={styles.colSalary}
title="薪資"
dataField={getSalary}
alignRight
>
薪資
</Table.Column>
<Table.Column
className={styles.colHourly}
title="估計時薪"
dataField={R.compose(
formatWage,
R.prop('estimated_hourly_wage'),
)}
alignRight
>
<InfoButton onClick={toggleInfoSalaryModal}>估計時薪</InfoButton>
</Table.Column>
<Table.Column
className={styles.colDataTime}
title="參考時間"
dataField={R.compose(
formatDate,
R.prop('data_time'),
)}
>
<InfoButton onClick={toggleInfoTimeModal}>參考時間</InfoButton>
</Table.Column>
<Table.Column
className={styles.colAboutThisJob}
title="關於此工作"
dataField={getAboutThisJobButton(toggleAboutThisJobModal)}
/>
</Table>
);
DashBoardTable.propTypes = {
data: PropTypes.array.isRequired,
postProcessRows: PropTypes.func.isRequired,
toggleInfoSalaryModal: PropTypes.func.isRequired,
toggleInfoTimeModal: PropTypes.func.isRequired,
toggleAboutThisJobModal: PropTypes.func.isRequired,
};
export default DashBoardTable;
|
src/svg-icons/action/view-quilt.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionViewQuilt = (props) => (
<SvgIcon {...props}>
<path d="M10 18h5v-6h-5v6zm-6 0h5V5H4v13zm12 0h5v-6h-5v6zM10 5v6h11V5H10z"/>
</SvgIcon>
);
ActionViewQuilt = pure(ActionViewQuilt);
ActionViewQuilt.displayName = 'ActionViewQuilt';
ActionViewQuilt.muiName = 'SvgIcon';
export default ActionViewQuilt;
|
node_modules/semantic-ui-react/src/elements/Step/StepContent.js | SuperUncleCat/ServerMonitoring | import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import {
childrenUtils,
createShorthand,
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
import StepDescription from './StepDescription'
import StepTitle from './StepTitle'
/**
* A step can contain a content.
*/
function StepContent(props) {
const { children, className, description, title } = props
const classes = cx('content', className)
const rest = getUnhandledProps(StepContent, props)
const ElementType = getElementType(StepContent, props)
if (!childrenUtils.isNil(children)) {
return <ElementType {...rest} className={classes}>{children}</ElementType>
}
return (
<ElementType {...rest} className={classes}>
{createShorthand(StepTitle, val => ({ title: val }), title)}
{createShorthand(StepDescription, val => ({ description: val }), description)}
</ElementType>
)
}
StepContent._meta = {
name: 'StepContent',
parent: 'Step',
type: META.TYPES.ELEMENT,
}
StepContent.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for StepDescription. */
description: customPropTypes.itemShorthand,
/** Shorthand for StepTitle. */
title: customPropTypes.itemShorthand,
}
export default StepContent
|
packages/material-ui-icons/src/EvStation.js | AndriusBil/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let EvStation = props =>
<SvgIcon {...props}>
<path d="M19.77 7.23l.01-.01-3.72-3.72L15 4.56l2.11 2.11c-.94.36-1.61 1.26-1.61 2.33 0 1.38 1.12 2.5 2.5 2.5.36 0 .69-.08 1-.21v7.21c0 .55-.45 1-1 1s-1-.45-1-1V14c0-1.1-.9-2-2-2h-1V5c0-1.1-.9-2-2-2H6c-1.1 0-2 .9-2 2v16h10v-7.5h1.5v5c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5V9c0-.69-.28-1.32-.73-1.77zM18 10c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zM8 18v-4.5H6L10 6v5h2l-4 7z" />
</SvgIcon>;
EvStation = pure(EvStation);
EvStation.muiName = 'SvgIcon';
export default EvStation;
|
chrome/extension/window/index.js | theaidem/reachext | import React from 'react'
import { render } from 'react-dom'
import Root from './Root'
window.addEventListener('load', () => {
chrome.storage.local.get(null, (store) => {
render(<Root />, document.querySelector('#root'))
})
})
|
appsrc/js/plaster-app.js | esonderegger/plaster | import React from 'react';
import Podcast from './podcast.js';
import Snackbar from 'material-ui/Snackbar';
import Dialog from 'material-ui/Dialog';
import LinearProgress from 'material-ui/LinearProgress';
import FlatButton from 'material-ui/FlatButton';
import WelcomeScreen from './welcome-screen.js';
import PlasterUpdater from './plaster-updater.js';
export default class PlasterApp extends React.Component {
constructor(props) {
super(props);
this.state = {
podcastPath: '',
snackbarOpen: false,
snackbarMessage: '',
snackbarDuration: 4000,
errorOpen: false,
errorMessage: '',
enableAutoUpdates: false
};
this.goHome = this.goHome.bind(this);
this.setSnackbar = this.setSnackbar.bind(this);
this.snackbarClose = this.snackbarClose.bind(this);
this.setError = this.setError.bind(this);
this.errorClose = this.errorClose.bind(this);
this.updatePodcastPath = this.updatePodcastPath.bind(this);
}
componentDidMount() {
var pathFromLocalStorage = localStorage.getItem('podcastDirectory');
if (pathFromLocalStorage && pathFromLocalStorage !== 'null') {
this.setState({podcastPath: pathFromLocalStorage});
}
}
updatePodcastPath(p) {
this.setState({podcastPath: p});
localStorage.setItem('podcastDirectory', p);
}
goHome() {
this.setState({podcastPath: ''});
localStorage.setItem('podcastDirectory', null);
}
setSnackbar(message, duration) {
this.setState({
snackbarOpen: true,
snackbarMessage: message,
snackbarDuration: duration
});
}
snackbarClose() {
this.setState({
snackbarOpen: false
});
}
setError(message) {
this.setState({
errorOpen: true,
errorMessage: message
});
}
errorClose() {
this.setState({
errorOpen: false
});
}
render() {
var mainWindow = (
<WelcomeScreen
updatePodcastPath={this.updatePodcastPath}
setSnackbar={this.setSnackbar}
setError={this.setError}
/>
);
if (this.state.podcastPath) {
mainWindow = (
<Podcast
directory={this.state.podcastPath}
goHome={this.goHome}
setSnackbar={this.setSnackbar}
setError={this.setError}
/>
);
}
const errorActions = [
<FlatButton
label="Ok"
primary={true}
onTouchTap={this.errorClose}
/>
];
var snackbarProgress = (
<div style={{
width: '2em',
display: 'inline-block',
position: 'relative',
top: '-3px',
left: '-9px'
}}>
<LinearProgress mode="indeterminate" />
</div>
);
var snackbarJsx = (
<div>
{this.state.snackbarDuration ? null : snackbarProgress}
<span>{this.state.snackbarMessage}</span>
</div>
);
return (
<div className="plaster-app">
{mainWindow}
<Snackbar
open={this.state.snackbarOpen}
message={snackbarJsx}
autoHideDuration={this.state.snackbarDuration}
onRequestClose={this.snackbarClose}
/>
<Dialog
actions={errorActions}
modal={false}
open={this.state.errorOpen}
onRequestClose={this.errorClose}
>{this.state.errorMessage}</Dialog>
{this.state.enableAutoUpdates ? <PlasterUpdater /> : null}
</div>
);
}
}
|
src/svg-icons/av/radio.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvRadio = (props) => (
<SvgIcon {...props}>
<path d="M3.24 6.15C2.51 6.43 2 7.17 2 8v12c0 1.1.89 2 2 2h16c1.11 0 2-.9 2-2V8c0-1.11-.89-2-2-2H8.3l8.26-3.34L15.88 1 3.24 6.15zM7 20c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm13-8h-2v-2h-2v2H4V8h16v4z"/>
</SvgIcon>
);
AvRadio = pure(AvRadio);
AvRadio.displayName = 'AvRadio';
AvRadio.muiName = 'SvgIcon';
export default AvRadio;
|
docs/src/Anchor.js | albertojacini/react-bootstrap | import React from 'react';
const Anchor = React.createClass({
propTypes: {
id: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
])
},
render() {
return (
<a id={this.props.id} href={'#' + this.props.id} className="anchor">
<span className="anchor-icon">#</span>
{this.props.children}
</a>
);
}
});
export default Anchor;
|
src/svg-icons/image/filter-2.js | jacklam718/react-svg-iconx | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFilter2 = (props) => (
<SvgIcon {...props}>
<path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zm-4-4h-4v-2h2c1.1 0 2-.89 2-2V7c0-1.11-.9-2-2-2h-4v2h4v2h-2c-1.1 0-2 .89-2 2v4h6v-2z"/>
</SvgIcon>
);
ImageFilter2 = pure(ImageFilter2);
ImageFilter2.displayName = 'ImageFilter2';
ImageFilter2.muiName = 'SvgIcon';
export default ImageFilter2;
|
app/components/Button.js | jmcolella/unique-twitter-followers | import React from 'react';
import { Link } from 'react-router';
const Button = ( props ) => (
<Link to={ props.link }>
<button
type='button'
>
{ props.children }
</button>
</Link>
);
Button.propTypes = {
link: React.PropTypes.string.isRequired,
children: React.PropTypes.string.isRequired
}
export default Button;
|
server/boot/a-react.js | lawrence34/freecodecamp | import React from 'react';
import Router from 'react-router';
import Fetchr from 'fetchr';
import Location from 'react-router/lib/Location';
import debugFactory from 'debug';
import { app$ } from '../../common/app';
import { RenderToString } from 'thundercats-react';
const debug = debugFactory('freecc:react-server');
// add routes here as they slowly get reactified
// remove their individual controllers
const routes = [
'/hikes',
'/hikes/*',
'/jobs'
];
export default function reactSubRouter(app) {
var router = app.loopback.Router();
routes.forEach(function(route) {
router.get(route, serveReactApp);
});
app.use(router);
function serveReactApp(req, res, next) {
const services = new Fetchr({ req });
const location = new Location(req.path, req.query);
// returns a router wrapped app
app$(location)
// if react-router does not find a route send down the chain
.filter(function({ initialState }) {
if (!initialState) {
debug('react tried to find %s but got 404', location.pathname);
return next();
}
return !!initialState;
})
.flatMap(function({ initialState, AppCat }) {
// call thundercats renderToString
// prefetches data and sets up it up for current state
debug('rendering to string');
return RenderToString(
AppCat(null, services),
React.createElement(Router, initialState)
);
})
// makes sure we only get one onNext and closes subscription
.flatMap(function({ data, markup }) {
debug('react rendered');
res.expose(data, 'data');
// now render jade file with markup injected from react
return res.render$('layout-react', { markup: markup });
})
.subscribe(
function(markup) {
debug('jade rendered');
res.send(markup);
},
next
);
}
}
|
app/containers/FeaturePage/index.js | mmaedel/react-boilerplate | /*
* FeaturePage
*
* List all the features
*/
import React from 'react';
import Helmet from 'react-helmet';
import messages from './messages';
import { FormattedMessage } from 'react-intl';
import H1 from 'components/H1';
import List from './List';
import ListItem from './ListItem';
import ListItemTitle from './ListItemTitle';
export default class FeaturePage extends React.Component { // eslint-disable-line react/prefer-stateless-function
// Since state and props are static,
// there's no need to re-render this component
shouldComponentUpdate() {
return false;
}
render() {
return (
<div>
<Helmet
title="Feature Page"
meta={[
{ name: 'description', content: 'Feature page of React.js Boilerplate application' },
]}
/>
<H1>
<FormattedMessage {...messages.header} />
</H1>
<List>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.scaffoldingHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.scaffoldingMessage} />
</p>
</ListItem>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.feedbackHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.feedbackMessage} />
</p>
</ListItem>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.routingHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.routingMessage} />
</p>
</ListItem>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.networkHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.networkMessage} />
</p>
</ListItem>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.intlHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.intlMessage} />
</p>
</ListItem>
</List>
</div>
);
}
}
|
webpack/landing.js | CDCgov/SDP-Vocabulary-Service | require("styles/master.scss");
require("bootstrap-sass/assets/javascripts/bootstrap.js");
import 'react-dates/initialize';
import 'react-dates/lib/css/_datepicker.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { hashHistory, Router, Route, IndexRoute } from 'react-router';
import DashboardContainer from './containers/DashboardContainer';
import ResponseSetShowContainer from './containers/response_sets/ResponseSetShowContainer';
import SectionShowContainer from './containers/sections/SectionShowContainer';
import QuestionShowContainer from './containers/questions/QuestionShowContainer';
import ResponseSetEditContainer from './containers/response_sets/ResponseSetEditContainer';
import QuestionEditContainer from './containers/questions/QuestionEditContainer';
import SurveyEditContainer from './containers/surveys/SurveyEditContainer';
import SurveyImportContainer from './containers/surveys/SurveyImportContainer';
import SurveyDedupeContainer from './containers/surveys/SurveyDedupeContainer';
import SectionEditContainer from './containers/sections/SectionEditContainer';
import SurveyShowContainer from './containers/surveys/SurveyShowContainer';
import TermsOfService from './containers/TermsOfService';
import Help from './containers/Help';
import FHIRDoc from './components/FHIRDoc';
import AdminPanel from './containers/AdminPanel';
import App from './containers/App';
import AuthenticatedRoutes from './containers/AuthenticatedRoutes';
import AdminRoutes from './containers/AdminRoutes';
import ErrorPage, {GenericError, Forbidden403, NotFound404} from './containers/ErrorPages';
import store from './store/configure_store';
import {logPageViewed} from './utilities/AdobeAnalytics';
ReactDOM.render(
<Provider store={store}>
<Router history={hashHistory} onUpdate={logPageViewed}>
<Route path='/' component={App}>
<IndexRoute component={DashboardContainer} />
<Route component={AdminRoutes}>
<Route path='/admin' component={AdminPanel} />
</Route>
<Route component={AuthenticatedRoutes}>
<Route path='/sections/new' component={SectionEditContainer} />
<Route path='/sections/:sectionId/:action' component={SectionEditContainer} />
<Route path='/responseSets/new' component={ResponseSetEditContainer} />
<Route path='/responseSets/:rsId/:action' component={ResponseSetEditContainer} />
<Route path='/questions/new' component={QuestionEditContainer} />
<Route path='/questions/:qId/:action' component={QuestionEditContainer} />
<Route path='/surveys/new' component={SurveyEditContainer} />
<Route path='/surveys/import' component={SurveyImportContainer} />
<Route path='/surveys/:surveyId/dedupe' component={SurveyDedupeContainer} />
<Route path='/surveys/:surveyId/:action' component={SurveyEditContainer} />
</Route>
<Route path='/termsOfService' component={TermsOfService}/>
<Route path='/help' component={Help}/>
<Route path='/fhirDoc' component={FHIRDoc}/>
<Route path='/sections/:sectionId' component={SectionShowContainer} />
<Route path='/responseSets/:rsId' component={ResponseSetShowContainer} />
<Route path='/questions/:qId' component={QuestionShowContainer} />
<Route path='/surveys/:surveyId' component={SurveyShowContainer} />
<Route path='/errors/' component={ErrorPage} >
<Route path='403' component={Forbidden403} />
<Route path='404' component={NotFound404} />
<Route path='*' component={GenericError} />
</Route>
</Route>
</Router>
</Provider>, document.getElementById("app"));
|
es/components/sidebar/panel-element-editor/element-editor.js | cvdlab/react-planner | var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Map, fromJS } from 'immutable';
import AttributesEditor from './attributes-editor/attributes-editor';
import { GeometryUtils, MathUtils } from '../../../utils/export';
import * as SharedStyle from '../../../shared-style';
import convert from 'convert-units';
import { MdContentCopy, MdContentPaste } from 'react-icons/md';
var PRECISION = 2;
var attrPorpSeparatorStyle = {
margin: '0.5em 0.25em 0.5em 0',
border: '2px solid ' + SharedStyle.SECONDARY_COLOR.alt,
position: 'relative',
height: '2.5em',
borderRadius: '2px'
};
var headActionStyle = {
position: 'absolute',
right: '0.5em',
top: '0.5em'
};
var iconHeadStyle = {
float: 'right',
margin: '-3px 4px 0px 0px',
padding: 0,
cursor: 'pointer',
fontSize: '1.4em'
};
var ElementEditor = function (_Component) {
_inherits(ElementEditor, _Component);
function ElementEditor(props, context) {
_classCallCheck(this, ElementEditor);
var _this = _possibleConstructorReturn(this, (ElementEditor.__proto__ || Object.getPrototypeOf(ElementEditor)).call(this, props, context));
_this.state = {
attributesFormData: _this.initAttrData(_this.props.element, _this.props.layer, _this.props.state),
propertiesFormData: _this.initPropData(_this.props.element, _this.props.layer, _this.props.state)
};
_this.updateAttribute = _this.updateAttribute.bind(_this);
return _this;
}
_createClass(ElementEditor, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
if (this.state.attributesFormData.hashCode() !== nextState.attributesFormData.hashCode() || this.state.propertiesFormData.hashCode() !== nextState.propertiesFormData.hashCode() || this.props.state.clipboardProperties.hashCode() !== nextProps.state.clipboardProperties.hashCode()) return true;
return false;
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(_ref) {
var element = _ref.element,
layer = _ref.layer,
state = _ref.state;
var prototype = element.prototype,
id = element.id;
var scene = this.props.state.get('scene');
var selectedLayer = scene.getIn(['layers', scene.get('selectedLayer')]);
var selected = selectedLayer.getIn([prototype, id]);
if (selectedLayer.hashCode() !== layer.hashCode()) this.setState({
attributesFormData: this.initAttrData(element, layer, state),
propertiesFormData: this.initPropData(element, layer, state)
});
}
}, {
key: 'initAttrData',
value: function initAttrData(element, layer, state) {
element = _typeof(element.misc) === 'object' ? element.set('misc', new Map(element.misc)) : element;
switch (element.prototype) {
case 'items':
{
return new Map(element);
}
case 'lines':
{
var v_a = layer.vertices.get(element.vertices.get(0));
var v_b = layer.vertices.get(element.vertices.get(1));
var distance = GeometryUtils.pointsDistance(v_a.x, v_a.y, v_b.x, v_b.y);
var _unit = element.misc.get('_unitLength') || this.context.catalog.unit;
var _length = convert(distance).from(this.context.catalog.unit).to(_unit);
return new Map({
vertexOne: v_a,
vertexTwo: v_b,
lineLength: new Map({ length: distance, _length: _length, _unit: _unit })
});
}
case 'holes':
{
var line = layer.lines.get(element.line);
var _layer$vertices$get = layer.vertices.get(line.vertices.get(0)),
x0 = _layer$vertices$get.x,
y0 = _layer$vertices$get.y;
var _layer$vertices$get2 = layer.vertices.get(line.vertices.get(1)),
x1 = _layer$vertices$get2.x,
y1 = _layer$vertices$get2.y;
var lineLength = GeometryUtils.pointsDistance(x0, y0, x1, y1);
var startAt = lineLength * element.offset - element.properties.get('width').get('length') / 2;
var _unitA = element.misc.get('_unitA') || this.context.catalog.unit;
var _lengthA = convert(startAt).from(this.context.catalog.unit).to(_unitA);
var endAt = lineLength - lineLength * element.offset - element.properties.get('width').get('length') / 2;
var _unitB = element.misc.get('_unitB') || this.context.catalog.unit;
var _lengthB = convert(endAt).from(this.context.catalog.unit).to(_unitB);
return new Map({
offset: element.offset,
offsetA: new Map({
length: MathUtils.toFixedFloat(startAt, PRECISION),
_length: MathUtils.toFixedFloat(_lengthA, PRECISION),
_unit: _unitA
}),
offsetB: new Map({
length: MathUtils.toFixedFloat(endAt, PRECISION),
_length: MathUtils.toFixedFloat(_lengthB, PRECISION),
_unit: _unitB
})
});
}
case 'areas':
{
return new Map({});
}
default:
return null;
}
}
}, {
key: 'initPropData',
value: function initPropData(element, layer, state) {
var catalog = this.context.catalog;
var catalogElement = catalog.getElement(element.type);
var mapped = {};
for (var name in catalogElement.properties) {
mapped[name] = new Map({
currentValue: element.properties.has(name) ? element.properties.get(name) : fromJS(catalogElement.properties[name].defaultValue),
configs: catalogElement.properties[name]
});
}
return new Map(mapped);
}
}, {
key: 'updateAttribute',
value: function updateAttribute(attributeName, value) {
var _this2 = this;
var attributesFormData = this.state.attributesFormData;
switch (this.props.element.prototype) {
case 'items':
{
attributesFormData = attributesFormData.set(attributeName, value);
break;
}
case 'lines':
{
switch (attributeName) {
case 'lineLength':
{
var v_0 = attributesFormData.get('vertexOne');
var v_1 = attributesFormData.get('vertexTwo');
var _GeometryUtils$orderV = GeometryUtils.orderVertices([v_0, v_1]),
_GeometryUtils$orderV2 = _slicedToArray(_GeometryUtils$orderV, 2),
v_a = _GeometryUtils$orderV2[0],
v_b = _GeometryUtils$orderV2[1];
var v_b_new = GeometryUtils.extendLine(v_a.x, v_a.y, v_b.x, v_b.y, value.get('length'), PRECISION);
attributesFormData = attributesFormData.withMutations(function (attr) {
attr.set(v_0 === v_a ? 'vertexTwo' : 'vertexOne', v_b.merge(v_b_new));
attr.set('lineLength', value);
});
break;
}
case 'vertexOne':
case 'vertexTwo':
{
attributesFormData = attributesFormData.withMutations(function (attr) {
attr.set(attributeName, attr.get(attributeName).merge(value));
var newDistance = GeometryUtils.verticesDistance(attr.get('vertexOne'), attr.get('vertexTwo'));
attr.mergeIn(['lineLength'], attr.get('lineLength').merge({
'length': newDistance,
'_length': convert(newDistance).from(_this2.context.catalog.unit).to(attr.get('lineLength').get('_unit'))
}));
});
break;
}
default:
{
attributesFormData = attributesFormData.set(attributeName, value);
break;
}
}
break;
}
case 'holes':
{
switch (attributeName) {
case 'offsetA':
{
var line = this.props.layer.lines.get(this.props.element.line);
var orderedVertices = GeometryUtils.orderVertices([this.props.layer.vertices.get(line.vertices.get(0)), this.props.layer.vertices.get(line.vertices.get(1))]);
var _orderedVertices = _slicedToArray(orderedVertices, 2),
_orderedVertices$ = _orderedVertices[0],
x0 = _orderedVertices$.x,
y0 = _orderedVertices$.y,
_orderedVertices$2 = _orderedVertices[1],
x1 = _orderedVertices$2.x,
y1 = _orderedVertices$2.y;
var alpha = GeometryUtils.angleBetweenTwoPoints(x0, y0, x1, y1);
var lineLength = GeometryUtils.pointsDistance(x0, y0, x1, y1);
var widthLength = this.props.element.properties.get('width').get('length');
var halfWidthLength = widthLength / 2;
var lengthValue = value.get('length');
lengthValue = Math.max(lengthValue, 0);
lengthValue = Math.min(lengthValue, lineLength - widthLength);
var xp = (lengthValue + halfWidthLength) * Math.cos(alpha) + x0;
var yp = (lengthValue + halfWidthLength) * Math.sin(alpha) + y0;
var offset = GeometryUtils.pointPositionOnLineSegment(x0, y0, x1, y1, xp, yp);
var endAt = MathUtils.toFixedFloat(lineLength - lineLength * offset - halfWidthLength, PRECISION);
var offsetUnit = attributesFormData.getIn(['offsetB', '_unit']);
var offsetB = new Map({
length: endAt,
_length: convert(endAt).from(this.context.catalog.unit).to(offsetUnit),
_unit: offsetUnit
});
attributesFormData = attributesFormData.set('offsetB', offsetB).set('offset', offset);
var offsetAttribute = new Map({
length: MathUtils.toFixedFloat(lengthValue, PRECISION),
_unit: value.get('_unit'),
_length: MathUtils.toFixedFloat(convert(lengthValue).from(this.context.catalog.unit).to(value.get('_unit')), PRECISION)
});
attributesFormData = attributesFormData.set(attributeName, offsetAttribute);
break;
}
case 'offsetB':
{
var _line = this.props.layer.lines.get(this.props.element.line);
var _orderedVertices2 = GeometryUtils.orderVertices([this.props.layer.vertices.get(_line.vertices.get(0)), this.props.layer.vertices.get(_line.vertices.get(1))]);
var _orderedVertices3 = _slicedToArray(_orderedVertices2, 2),
_orderedVertices3$ = _orderedVertices3[0],
_x = _orderedVertices3$.x,
_y = _orderedVertices3$.y,
_orderedVertices3$2 = _orderedVertices3[1],
_x2 = _orderedVertices3$2.x,
_y2 = _orderedVertices3$2.y;
var _alpha = GeometryUtils.angleBetweenTwoPoints(_x, _y, _x2, _y2);
var _lineLength = GeometryUtils.pointsDistance(_x, _y, _x2, _y2);
var _widthLength = this.props.element.properties.get('width').get('length');
var _halfWidthLength = _widthLength / 2;
var _lengthValue = value.get('length');
_lengthValue = Math.max(_lengthValue, 0);
_lengthValue = Math.min(_lengthValue, _lineLength - _widthLength);
var _xp = _x2 - (_lengthValue + _halfWidthLength) * Math.cos(_alpha);
var _yp = _y2 - (_lengthValue + _halfWidthLength) * Math.sin(_alpha);
var _offset = GeometryUtils.pointPositionOnLineSegment(_x, _y, _x2, _y2, _xp, _yp);
var startAt = MathUtils.toFixedFloat(_lineLength * _offset - _halfWidthLength, PRECISION);
var _offsetUnit = attributesFormData.getIn(['offsetA', '_unit']);
var offsetA = new Map({
length: startAt,
_length: convert(startAt).from(this.context.catalog.unit).to(_offsetUnit),
_unit: _offsetUnit
});
attributesFormData = attributesFormData.set('offsetA', offsetA).set('offset', _offset);
var _offsetAttribute = new Map({
length: MathUtils.toFixedFloat(_lengthValue, PRECISION),
_unit: value.get('_unit'),
_length: MathUtils.toFixedFloat(convert(_lengthValue).from(this.context.catalog.unit).to(value.get('_unit')), PRECISION)
});
attributesFormData = attributesFormData.set(attributeName, _offsetAttribute);
break;
}
default:
{
attributesFormData = attributesFormData.set(attributeName, value);
break;
}
};
break;
}
default:
break;
}
this.setState({ attributesFormData: attributesFormData });
this.save({ attributesFormData: attributesFormData });
}
}, {
key: 'updateProperty',
value: function updateProperty(propertyName, value) {
var propertiesFormData = this.state.propertiesFormData;
propertiesFormData = propertiesFormData.setIn([propertyName, 'currentValue'], value);
this.setState({ propertiesFormData: propertiesFormData });
this.save({ propertiesFormData: propertiesFormData });
}
}, {
key: 'reset',
value: function reset() {
this.setState({ propertiesFormData: this.initPropData(this.props.element, this.props.layer, this.props.state) });
}
}, {
key: 'save',
value: function save(_ref2) {
var propertiesFormData = _ref2.propertiesFormData,
attributesFormData = _ref2.attributesFormData;
if (propertiesFormData) {
var properties = propertiesFormData.map(function (data) {
return data.get('currentValue');
});
this.context.projectActions.setProperties(properties);
}
if (attributesFormData) {
switch (this.props.element.prototype) {
case 'items':
{
this.context.projectActions.setItemsAttributes(attributesFormData);
break;
}
case 'lines':
{
this.context.projectActions.setLinesAttributes(attributesFormData);
break;
}
case 'holes':
{
this.context.projectActions.setHolesAttributes(attributesFormData);
break;
}
}
}
}
}, {
key: 'copyProperties',
value: function copyProperties(properties) {
this.context.projectActions.copyProperties(properties);
}
}, {
key: 'pasteProperties',
value: function pasteProperties() {
this.context.projectActions.pasteProperties();
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
var _state = this.state,
propertiesFormData = _state.propertiesFormData,
attributesFormData = _state.attributesFormData,
_context = this.context,
projectActions = _context.projectActions,
catalog = _context.catalog,
translator = _context.translator,
_props = this.props,
appState = _props.state,
element = _props.element;
return React.createElement(
'div',
null,
React.createElement(AttributesEditor, {
element: element,
onUpdate: this.updateAttribute,
attributeFormData: attributesFormData,
state: appState
}),
React.createElement(
'div',
{ style: attrPorpSeparatorStyle },
React.createElement(
'div',
{ style: headActionStyle },
React.createElement(
'div',
{ title: translator.t('Copy'), style: iconHeadStyle, onClick: function onClick(e) {
return _this3.copyProperties(element.properties);
} },
React.createElement(MdContentCopy, null)
),
appState.get('clipboardProperties') && appState.get('clipboardProperties').size ? React.createElement(
'div',
{ title: translator.t('Paste'), style: iconHeadStyle, onClick: function onClick(e) {
return _this3.pasteProperties();
} },
React.createElement(MdContentPaste, null)
) : null
)
),
propertiesFormData.entrySeq().map(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
propertyName = _ref4[0],
data = _ref4[1];
var currentValue = data.get('currentValue'),
configs = data.get('configs');
var _catalog$getPropertyT = catalog.getPropertyType(configs.type),
Editor = _catalog$getPropertyT.Editor;
return React.createElement(Editor, {
key: propertyName,
propertyName: propertyName,
value: currentValue,
configs: configs,
onUpdate: function onUpdate(value) {
return _this3.updateProperty(propertyName, value);
},
state: appState,
sourceElement: element,
internalState: _this3.state
});
})
);
}
}]);
return ElementEditor;
}(Component);
export default ElementEditor;
ElementEditor.propTypes = {
state: PropTypes.object.isRequired,
element: PropTypes.object.isRequired,
layer: PropTypes.object.isRequired
};
ElementEditor.contextTypes = {
projectActions: PropTypes.object.isRequired,
catalog: PropTypes.object.isRequired,
translator: PropTypes.object.isRequired
}; |
docs/src/pages/layout/MediaQuery.js | AndriusBil/material-ui | // @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import compose from 'recompose/compose';
import { withStyles } from 'material-ui/styles';
import withWidth from 'material-ui/utils/withWidth';
import Typography from 'material-ui/Typography';
const styles = theme => ({
root: {
padding: theme.spacing.unit,
[theme.breakpoints.up('md')]: {
backgroundColor: theme.palette.primary[500],
},
[theme.breakpoints.down('md')]: {
backgroundColor: theme.palette.secondary.A400,
},
},
});
function MediaQuery(props) {
const classes = props.classes;
return (
<div className={classes.root}>
<Typography type="subheading">{`Current width: ${props.width}`}</Typography>
</div>
);
}
MediaQuery.propTypes = {
classes: PropTypes.object.isRequired,
width: PropTypes.string.isRequired,
};
export default compose(withStyles(styles), withWidth())(MediaQuery);
|
blueocean-material-icons/src/js/components/svg-icons/content/backspace.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ContentBackspace = (props) => (
<SvgIcon {...props}>
<path d="M22 3H7c-.69 0-1.23.35-1.59.88L0 12l5.41 8.11c.36.53.9.89 1.59.89h15c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-3 12.59L17.59 17 14 13.41 10.41 17 9 15.59 12.59 12 9 8.41 10.41 7 14 10.59 17.59 7 19 8.41 15.41 12 19 15.59z"/>
</SvgIcon>
);
ContentBackspace.displayName = 'ContentBackspace';
ContentBackspace.muiName = 'SvgIcon';
export default ContentBackspace;
|
app/components/List/index.js | aditigoel23/React-Car-App | import React from 'react';
import Ul from './Ul';
import Wrapper from './Wrapper';
function List(props) {
const ComponentToRender = props.component;
let content = (<div></div>);
// If we have items, render them
if (props.items) {
content = props.items.map((item, index) => (
<ComponentToRender key={`item-${index}`} item={item} />
));
} else {
// Otherwise render a single component
content = (<ComponentToRender />);
}
return (
<Wrapper>
<Ul>
{content}
</Ul>
</Wrapper>
);
}
List.propTypes = {
component: React.PropTypes.func.isRequired,
items: React.PropTypes.array,
};
export default List;
|
docs/src/App.js | byumark/react-table | import React from 'react'
//
import ReactStory, { defaultProps } from 'react-story'
import './stories/utils/prism.css'
import '../../react-table.css'
import Readme from './stories/Readme.js'
import Simple from './stories/Simple.js'
import CellRenderers from './stories/CellRenderers.js'
import DefaultSorting from './stories/DefaultSorting.js'
import CustomSorting from './stories/CustomSorting.js'
import CustomWidths from './stories/CustomWidths.js'
import CustomComponentProps from './stories/CustomComponentProps.js'
import ServerSide from './stories/ServerSide.js'
import SubComponents from './stories/SubComponents.js'
import Pivoting from './stories/Pivoting.js'
import PivotingSubComponents from './stories/PivotingSubComponents.js'
import OneHundredKRows from './stories/OneHundredKRows.js'
import FunctionalRendering from './stories/FunctionalRendering.js'
import CustomExpanderPosition from './stories/CustomExpanderPosition.js'
import NoDataText from './stories/NoDataText.js'
import Footers from './stories/Footers.js'
import Filtering from './stories/Filtering.js'
import ControlledTable from './stories/ControlledTable.js'
import PivotingOptions from './stories/PivotingOptions.js'
import EditableTable from './stories/EditableTable.js'
export default class App extends React.Component {
render () {
return (
<ReactStory
style={{
display: 'block',
width: '100%',
height: '100%'
}}
pathPrefix='story/'
StoryWrapper={(props) => (
<defaultProps.StoryWrapper
css={{
padding: 0
}}
>
<a
href='//github.com/tannerlinsley/react-table'
style={{
display: 'block',
textAlign: 'center',
borderBottom: 'solid 3px #cccccc'
}}
>
<img
src='//npmcdn.com/react-table/media/Banner.png'
alt='React Table Logo'
style={{
width: '100px'
}}
/>
</a>
<div
{...props}
style={{
padding: '10px'
}}
/>
</defaultProps.StoryWrapper>
)}
stories={[
{ name: 'Readme', component: Readme },
{ name: 'Simple Table', component: Simple },
{ name: 'Cell Renderers & Custom Components', component: CellRenderers },
{ name: 'Default Sorting', component: DefaultSorting },
{ name: 'Custom Sorting', component: CustomSorting },
{ name: 'Custom Column Widths', component: CustomWidths },
{ name: 'Custom Component Props', component: CustomComponentProps },
{ name: 'Server-side Data', component: ServerSide },
{ name: 'Sub Components', component: SubComponents },
{ name: 'Pivoting & Aggregation', component: Pivoting },
{ name: 'Pivoting & Aggregation w/ Sub Components', component: PivotingSubComponents },
{ name: '100k Rows w/ Pivoting & Sub Components', component: OneHundredKRows },
{ name: 'Pivoting Options', component: PivotingOptions },
{ name: 'Functional Rendering', component: FunctionalRendering },
{ name: 'Custom Expander Position', component: CustomExpanderPosition },
{ name: 'Custom "No Data" Text', component: NoDataText },
{ name: 'Footers', component: Footers },
{ name: 'Custom Filtering', component: Filtering },
{ name: 'Controlled Component', component: ControlledTable },
{ name: 'Editable Table', component: EditableTable }
]}
/>
)
}
}
|
src/components/comment.js | josebigio/PodCast | import React, { Component } from 'react';
import CountIcon from './count-icon'
import ReplyList from './reply-list';
class Comment extends Component {
constructor(props) {
super(props);
this.state = {
selected:false
}
}
handleClick() {
this.setState({
selected:!this.state.selected
});
}
render() {
const { comment, showReplies } = this.props;
const { snippet, replies } = comment;
const { likeCount, textDisplay, authorDisplayName } = snippet.topLevelComment.snippet;
return <li className="list-group-item comment-list-group-item clickable" onClick={this.handleClick.bind(this)}>
<h6>{authorDisplayName}</h6>
<div dangerouslySetInnerHTML={{ __html: textDisplay }} />
<CountIcon count={likeCount} color="#ffaaff" radius="30px" />
{this.state.selected && <ReplyList replies={replies.comments} />}
</li>
}
}
export default Comment; |
client/js/components/widget-create.js | ericwgreene/relay-practice | import React from 'react';
import PropTypes from 'prop-types';
import { createFragmentContainer, graphql } from 'react-relay';
import { WidgetForm } from './widget-form';
import { insertWidget } from '../mutations/insert-widget-mutation';
export class WidgetCreate extends React.Component {
static propTypes = {
router: PropTypes.shape({
push: PropTypes.func,
}),
viewer: PropTypes.object,
relay: PropTypes.shape({
environment: PropTypes.object.isRequired,
}).isRequired,
};
constructor(props) {
super(props);
this.addWidget = this.addWidget.bind(this);
}
addWidget(widget) {
insertWidget(
// provided by relay import
this.props.relay.environment,
// normal widget object provided by widget form
widget,
// viewer prop which was populated by the graphql query defined
// in widgets-app-container
this.props.viewer,
).then(() => {
this.props.router.push('/');
});
}
render() {
return <section>
<WidgetForm onSave={this.addWidget} />
</section>;
}
}
export const WidgetCreateContainer = createFragmentContainer(WidgetCreate, graphql`
fragment widgetCreate_viewer on Viewer { id }
`); |
app/components/Contact.js | leckman/purlpal | import React from 'react';
import { connect } from 'react-redux'
import { submitContactForm } from '../actions/contact';
import Messages from './Messages';
class Contact extends React.Component {
constructor(props) {
super(props);
this.state = { name: '', email: '', message: '' };
}
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
handleSubmit(event) {
event.preventDefault();
this.props.dispatch(submitContactForm(this.state.name, this.state.email, this.state.message));
}
render() {
return (
<div className="container">
<div className="panel">
<div className="panel-heading">
<h3 className="panel-title">Contact Form</h3>
</div>
<div className="panel-body">
<Messages messages={this.props.messages}/>
<form onSubmit={this.handleSubmit.bind(this)} className="form-horizontal">
<div className="form-group">
<label htmlFor="name" className="col-sm-2">Name</label>
<div className="col-sm-8">
<input type="text" name="name" id="name" className="form-control" value={this.state.name} onChange={this.handleChange.bind(this)} autoFocus/>
</div>
</div>
<div className="form-group">
<label htmlFor="email" className="col-sm-2">Email</label>
<div className="col-sm-8">
<input type="email" name="email" id="email" className="form-control" value={this.state.email} onChange={this.handleChange.bind(this)}/>
</div>
</div>
<div className="form-group">
<label htmlFor="message" className="col-sm-2">Body</label>
<div className="col-sm-8">
<textarea name="message" id="message" rows="7" className="form-control" value={this.state.message} onChange={this.handleChange.bind(this)}></textarea>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-8">
<button type="submit" className="btn btn-success">Send</button>
</div>
</div>
</form>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
messages: state.messages
};
};
export default connect(mapStateToProps)(Contact);
|
react-demos/undo_redo/src/index.js | konvajs/site | import React, { Component } from 'react';
import { createRoot } from 'react-dom/client';
import { Stage, Layer, Rect, Text } from 'react-konva';
let history = [
{
x: 20,
y: 20,
},
];
let historyStep = 0;
class App extends Component {
state = {
position: history[0],
};
handleUndo = () => {
if (historyStep === 0) {
return;
}
historyStep -= 1;
const previous = history[historyStep];
this.setState({
position: previous,
});
};
handleRedo = () => {
if (historyStep === history.length - 1) {
return;
}
historyStep += 1;
const next = history[historyStep];
this.setState({
position: next,
});
};
handleDragEnd = (e) => {
history = history.slice(0, historyStep + 1);
const pos = {
x: e.target.x(),
y: e.target.y(),
};
history = history.concat([pos]);
historyStep += 1;
this.setState({
position: pos,
});
};
render() {
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Text text="undo" onClick={this.handleUndo} />
<Text text="redo" x={40} onClick={this.handleRedo} />
<Rect
x={this.state.position.x}
y={this.state.position.y}
width={50}
height={50}
fill="black"
draggable
onDragEnd={this.handleDragEnd}
/>
</Layer>
</Stage>
);
}
}
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<App />);
|
client/trello/src/app/routes/home/routes/boardView/components/Forms/CreateCard/CreateCard.js | Madmous/Trello-Clone | import React from 'react';
import { Field, reduxForm } from 'redux-form';
import FontAwesome from 'react-fontawesome';
import PropTypes from 'prop-types';
import './CreateCard.css';
const propTypes = {
isCreateCardFormOpen: PropTypes.bool.isRequired,
boardViewActions: PropTypes.object.isRequired
}
function CreateCard(props) {
const focusOnForm = isFocusOnForm => {
if (isFocusOnForm) {
props.boardViewActions.focusOnBoard();
} else {
props.boardViewActions.blurOnBoard();
}
}
const { boardViewActions, handleSubmit } = props;
return (
<div
className="Create-Card-Form"
tabIndex="0"
onFocus={() => { focusOnForm(true) }}
onBlur={() => { focusOnForm(false) }}
>
<form onSubmit={ handleSubmit }>
<Field
className="Create-Card-Form-CardTitle"
autoFocus={true}
type="text"
name="name"
value=""
placeholder="Add a card…"
component="input"
dir="auto"
/>
<div className="Create-Card-Form-Footer">
<button type="submit" className="Create-Card-Form-SubmitButton">Save</button>
<FontAwesome
name="times"
size="2x"
className="Create-Card-Form-Header-Close-Button"
onClick={ () => boardViewActions.closeCreateCardForm() }
/>
</div>
</form>
</div>
);
}
CreateCard.propTypes = propTypes;
export default reduxForm({ form: 'createCardForm' })(CreateCard);
|
src/client/songs/songlinklazy.react.js | steida/songary | import Component from '../components/component.react';
import React from 'react';
import SongLink from '../songs/songlink.react';
import listenSong from './listensong';
@listenSong
export default class SongLinkLazy extends Component {
static propTypes = {
actions: React.PropTypes.object.isRequired,
params: React.PropTypes.object.isRequired,
song: React.PropTypes.object
}
render() {
const {song} = this.props;
if (!song) return null;
return (
<SongLink song={song} />
);
}
}
|
client/src/components/dashboard/Account.js | no-stack-dub-sack/alumni-network | import { connect } from 'react-redux';
import { connectScreenSize } from 'react-screen-size';
import { mapScreenSizeToProps } from '../Navbar';
import React from 'react';
import styled from 'styled-components';
import { addFlashMessage, clearFlashMessage } from '../../actions/flashMessages';
import { Button, Modal } from 'semantic-ui-react';
import { deleteUser, logoutUser } from '../../actions/user';
const Input = styled.input`
width: 100%;
border: 1px solid rgba(5,5,5,0.25);
padding: 4px 6px !important;
font-size: 22px !important;
`;
const ConfirmModal = ({ open, input, handleInput, deleteUser, close }) => {
return (
<Modal open={open} size="small">
<Modal.Header style={{ background: 'rgb(225,225,225)' }}>
<h1>
<span>
<i className="red warning sign icon" />
{'Type your username to confirm:'}
</span>
</h1>
</Modal.Header>
<Modal.Content>
<form onSubmit={deleteUser}>
<Input
autoComplete='off'
autoFocus
id="deleteInput"
onChange={handleInput}
type="text"
value={input} />
</form>
</Modal.Content>
<Modal.Actions style={{ textAlign: 'center' }}>
<Button
color="red"
content='Delete Account'
icon='remove'
labelPosition='right'
onClick={deleteUser} />
<Button
color="green"
content='Nevermind'
icon='undo'
labelPosition='right'
onClick={close}
positive />
</Modal.Actions>
</Modal>
);
};
class Account extends React.Component {
state = {
flashMessageCleared: false,
input: '',
modal: false,
}
componentWillMount() {
/* bit of a hack here in CWM, just manually removing this node
from dom (if it exists), since there should never be a flash
message rendered when first rendering this route. This will
only need to happen if user does not manually clear whatever
flash message is there before switching routes. */
document.getElementsByClassName('flashMessage')[0] &&
document.getElementsByClassName('flashMessage')[0].remove();
}
componentDidMount = () => {
document.addEventListener('click', this.handleClick);
}
componentWillUnmount = () => {
document.removeEventListener('click', this.handleClick)
}
// 'close' is className of close icon in flash message
handleClick = (e) => {
e.target.classList.contains('close')
? this.setState({ flashMessageCleared: true })
: this.setState({ flashMessageCleared: false });
}
deleteUser = (e) => {
if (e) e.preventDefault();
const { input } = this.state;
this.setState({ input: '' });
if (input === this.props.user) {
deleteUser().then(res => {
this.props.logoutUser();
this.props.clearFlashMessage();
this.props.addFlashMessage({
text: {
header: 'Your account has been deleted.',
message: 'Goodbye!'
},
type: 'error',
});
this.props.history.push('/login');
}).catch(err => {
this.props.addFlashMessage({
text: {
header: 'Something went wrong...',
message: 'Hmmm...'
},
type: 'error',
});
})
} else {
this.toggleModal();
this.props.addFlashMessage({
text: {
header: 'Delete User Error.',
message: `You must enter your username
correctly if you want to delete your account.`
},
type: 'error',
});
}
}
handleInput = (e) => this.setState({ input: e.target.value });
toggleModal = () => this.setState({ modal: !this.state.modal });
render() {
const { isDesktop } = this.props.screen;
const { flashMessageCleared } = this.state;
/* handles margins when flash messages are rendered and also
when subsequently removed. handleClick and flashMessageCleared
state of this component are all related to this. */
const Container = styled.div`
margin-top: ${document.getElementsByClassName('flashMessage').length > 0
&& !flashMessageCleared
? '53px' : isDesktop
? '200px': '175px' } !important;
`;
return (
<Container className="ui main text center aligned container">
<div className='ui segment' style={{ padding: '25px' }}>
<h1 className="ui header">
{`Account Settings for: ${this.props.user}`}
</h1>
<button className="ui red button" onClick={this.toggleModal}>
{'Delete My Account'}
</button>
<br /><br />
<p>{'This cannot be undone.'}</p>
<ConfirmModal
close={this.toggleModal}
deleteUser={this.deleteUser}
handleInput={this.handleInput}
input={this.state.input}
open={this.state.modal} />
</div>
</Container>
);
}
};
const mapStateToProps = (state) => ({
user: state.user.username
});
const dispatchProps = {
addFlashMessage,
clearFlashMessage,
logoutUser
};
export default connectScreenSize(mapScreenSizeToProps)(
connect(mapStateToProps, dispatchProps)(Account)
);
|
src/components/MessageText.js | twhite96/checkyoself | /* jshint ignore: start */
import React from 'react';
import { Message } from 'reactbulma';
import '../smde-editor.css';
class MessageText extends React.Component {
render() {
return (
<React.Fragment>
<div className="fit pad-bottom">
<Message className="change-body body-styles">
<Message.Body>
<h2>
Hey!
<span role="img" aria-label="wave-emoji-brown">
👋🏾
</span>
</h2>
<p>
This is Check Yo Self, an app to check the{' '}
<span className="highlight">grammar and spelling</span> of your{' '}
<span className="highlight">markdown blog posts</span>.
</p>
</Message.Body>
</Message>
</div>
<div className="fit">
<Message className="change-danger body-styles change-text">
<Message.Body>
<div className="content">
FAQ:
<ol>
<li>
Is my data on your server somewhere?<br />
In an upcoming release, I am going to be using Firebase to
sync and store your texts so that in case you come back and
want to have your data persisted, it will be there. See the
Privacy Policy for more.
</li>
<li>
Does this cost anything?<br />
Nope. It is free. If you like it you can buy me a{' '}
<a href="https://www.paypal.me/codenewb/5">coffee</a>.
</li>
<li>
How can I delete no longer needed texts?<br />
Selecting and hitting backspace!
</li>
</ol>
</div>
</Message.Body>
</Message>
</div>
</React.Fragment>
);
}
}
export default MessageText;
|
tests/react_native_tests/test_data/native_code/ReusableComponents/app/components/UserConnect/component.js | ibhubs/sketch-components | /**
* @flow
*/
import React from 'react'
import PropTypes from 'prop-types'
import { observer } from 'mobx-react/native'
import styles from './styles'
import Button from '@rn/commons/app/components/VIButton/VIButton'
import styled from 'styled-components/native'
import { Text } from 'react-native'
import { View } from 'react-native'
const UserConnect = (props) => (
<UserConnectStyledView>
<Text
style={styles.peterStyle}
>{props.name}</Text>
<Text
style={styles.oceanographerStyle}
>{props.job}</Text>
<Button
buttonStyle={styles.group2ButtonStyle}
onPress={props.onClick}
textStyle={styles.group2TextStyle}
title={props.buttonName}
/>
</UserConnectStyledView>
)
export const UserConnectStyledView = styled.View`
alignItems: center;
backgroundColor: rgba(248, 248, 248, 1.0);
borderRadius: 24;
elevation: 2;
flexDirection: column;
height: 117.0;
justifyContent: center;
marginLeft: 118.0;
marginTop: 112.0;
overflow: hidden;
shadowColor: rgba(0, 0, 0, 0.5);
shadowOffset: {'height': 2, 'width': 2};
shadowOpacity: 1;
shadowRadius: 3;
width: 125.0;
`
export default observer(UserConnect) |
client/src/javascript/components/icons/ChevronLeftIcon.js | jfurrow/flood | import React from 'react';
import BaseIcon from './BaseIcon';
export default class ChevronLeftIcon extends BaseIcon {
render() {
return (
<svg className={`icon icon--chevron-left ${this.props.className}`} viewBox={this.getViewBox()}>
<polygon points="41.34 1.2 47.35 7.21 24.6 29.96 47.42 52.79 41.41 58.8 12.58 29.96 41.34 1.2" />
</svg>
);
}
}
|
src/components/ArrowBottom/ArrowBottom.js | Zoomdata/nhtsa-dashboard-2.2 | import styles from './ArrowBottom.css';
import React from 'react';
const ArrowBottom = ({
hoodAction,
arrowVisibility
}) => {
const arrowBottomStyles = {
display: 'none'
};
return (
<div
className={
hoodAction === 'OPEN_HOOD' ?
styles.active :
styles.normal
}
style={
arrowVisibility === 'HIDE_ARROW' ?
arrowBottomStyles :
null
}
>
</div>
)
};
export default ArrowBottom;
|
src/components/App.js | yingray/create-react-redux-app | import React from 'react'
import Header from './Header'
const App = ({ children }) =>
<div>
<Header />
<div>
{children}
</div>
</div>
export default App
|
App/Containers/AllComponentsScreen.js | okmttdhr/YoutuVote | // @flow
// An All Components Screen is a great way to dev and quick-test components
import React from 'react';
import { Platform, View, ScrollView, Text, Image } from 'react-native';
import { Images } from '../Themes';
import styles from './Styles/AllComponentsScreenStyle';
// Components to show examples (only real point of merge conflict)
import '../Components/AlertMessage';
import '../Components/ButtonDefault';
import '../Components/RoundedButton';
import '../Components/DrawerButton';
// import '../Components/MapCallout'
// Examples Render Engine
import ExamplesRegistry from '../Services/ExamplesRegistry';
class AllComponentsScreen extends React.Component {
renderAndroidWarning() {
if (Platform.OS === 'android') {
return (
<Text style={styles.sectionText}>
Android only: Animations are slow? You are probably running the app in debug mode.
It will run more smoothly once your app will be built.
</Text>
);
}
return null;
}
render() {
return (
<View style={styles.mainContainer}>
<Image source={Images.background} style={styles.backgroundImage} resizeMode="stretch" />
<ScrollView style={styles.container}>
<View style={styles.section}>
{this.renderAndroidWarning()}
<Text style={styles.sectionText}>
Sometimes called a 'Style Guide', or 'Pattern Library', Examples Screen is filled with usage examples
of fundamental components for a given application. Use this merge-friendly way for your team
to show/use/test components. Examples are registered inside each component's file for quick changes and usage identification.
</Text>
<Text style={styles.subtitle} >
All components that register examples will be rendered below:
</Text>
</View>
{ExamplesRegistry.render()}
</ScrollView>
</View>
);
}
}
export default AllComponentsScreen;
|
app/index.js | foysalit/runkeeper-desktop | import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router } from 'react-router';
import routes from './routes';
import configureStore from './store/configureStore';
import './app.css';
const store = configureStore();
render(
<Provider store={store}>
<Router>
{routes}
</Router>
</Provider>,
document.getElementById('root')
);
if (process.env.NODE_ENV !== 'production') {
// Use require because imports can't be conditional.
// In production, you should ensure process.env.NODE_ENV
// is envified so that Uglify can eliminate this
// module and its dependencies as dead code.
// require('./createDevToolsWindow')(store);
}
|
src/svg-icons/image/timelapse.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageTimelapse = (props) => (
<SvgIcon {...props}>
<path d="M16.24 7.76C15.07 6.59 13.54 6 12 6v6l-4.24 4.24c2.34 2.34 6.14 2.34 8.49 0 2.34-2.34 2.34-6.14-.01-8.48zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/>
</SvgIcon>
);
ImageTimelapse = pure(ImageTimelapse);
ImageTimelapse.displayName = 'ImageTimelapse';
ImageTimelapse.muiName = 'SvgIcon';
export default ImageTimelapse;
|
src/svg-icons/maps/place.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsPlace = (props) => (
<SvgIcon {...props}>
<path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
</SvgIcon>
);
MapsPlace = pure(MapsPlace);
MapsPlace.displayName = 'MapsPlace';
MapsPlace.muiName = 'SvgIcon';
export default MapsPlace;
|
src/svg-icons/image/panorama.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImagePanorama = (props) => (
<SvgIcon {...props}>
<path d="M23 18V6c0-1.1-.9-2-2-2H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2zM8.5 12.5l2.5 3.01L14.5 11l4.5 6H5l3.5-4.5z"/>
</SvgIcon>
);
ImagePanorama = pure(ImagePanorama);
ImagePanorama.displayName = 'ImagePanorama';
export default ImagePanorama;
|
src/fluxtable/NewServerActionStateManager.js | MirekSz/avem | import React, { Component } from 'react';
import ContainersStore from './container/ContainersStore';
import {LoadAllContainers} from './container/ContainersActionCreator';
var NewServerActionStateManager = React.createClass({
componentDidMount(){
var store = this.props.store;
store.addListener(this.storeChanged);
},
componentWillUnmount(){
var store = this.props.store;
store.removeListener(this.storeChanged);
},
render: function () {
return null;
},
storeChanged(action){
var data = this.props.store.getActiveElements();
var length = data.length;
if (length >= 5) {
$("#newContainer").addClass('disabled');
} else {
$("#newContainer").removeClass('disabled');
}
}
});
export default NewServerActionStateManager;
|
src/svg-icons/editor/border-clear.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorBorderClear = (props) => (
<SvgIcon {...props}>
<path d="M7 5h2V3H7v2zm0 8h2v-2H7v2zm0 8h2v-2H7v2zm4-4h2v-2h-2v2zm0 4h2v-2h-2v2zm-8 0h2v-2H3v2zm0-4h2v-2H3v2zm0-4h2v-2H3v2zm0-4h2V7H3v2zm0-4h2V3H3v2zm8 8h2v-2h-2v2zm8 4h2v-2h-2v2zm0-4h2v-2h-2v2zm0 8h2v-2h-2v2zm0-12h2V7h-2v2zm-8 0h2V7h-2v2zm8-6v2h2V3h-2zm-8 2h2V3h-2v2zm4 16h2v-2h-2v2zm0-8h2v-2h-2v2zm0-8h2V3h-2v2z"/>
</SvgIcon>
);
EditorBorderClear = pure(EditorBorderClear);
EditorBorderClear.displayName = 'EditorBorderClear';
EditorBorderClear.muiName = 'SvgIcon';
export default EditorBorderClear;
|
src/svg-icons/content/content-copy.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentContentCopy = (props) => (
<SvgIcon {...props}>
<path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
</SvgIcon>
);
ContentContentCopy = pure(ContentContentCopy);
ContentContentCopy.displayName = 'ContentContentCopy';
ContentContentCopy.muiName = 'SvgIcon';
export default ContentContentCopy;
|
src/SplitButton.js | albertojacini/react-bootstrap | import React from 'react';
import BootstrapMixin from './BootstrapMixin';
import Button from './Button';
import Dropdown from './Dropdown';
import SplitToggle from './SplitToggle';
class SplitButton extends React.Component {
render() {
let {
children,
title,
onClick,
target,
href,
// bsStyle is validated by 'Button' component
bsStyle, // eslint-disable-line
...props } = this.props;
let { disabled } = props;
let button = (
<Button
onClick={onClick}
bsStyle={bsStyle}
disabled={disabled}
target={target}
href={href}
>
{title}
</Button>
);
return (
<Dropdown {...props}>
{button}
<SplitToggle
aria-label={title}
bsStyle={bsStyle}
disabled={disabled}
/>
<Dropdown.Menu>
{children}
</Dropdown.Menu>
</Dropdown>
);
}
}
SplitButton.propTypes = {
...Dropdown.propTypes,
...BootstrapMixin.propTypes,
/**
* @private
*/
onClick() {},
target: React.PropTypes.string,
href: React.PropTypes.string,
/**
* The content of the split button.
*/
title: React.PropTypes.node.isRequired
};
SplitButton.defaultProps = {
disabled: false,
dropup: false,
pullRight: false
};
SplitButton.Toggle = SplitToggle;
export default SplitButton;
|
blueocean-material-icons/src/js/components/svg-icons/social/mood.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const SocialMood = (props) => (
<SvgIcon {...props}>
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/>
</SvgIcon>
);
SocialMood.displayName = 'SocialMood';
SocialMood.muiName = 'SvgIcon';
export default SocialMood;
|
monkey/monkey_island/cc/ui/src/components/attack/techniques/T1041.js | guardicore/monkey | import React from 'react';
import ReactTable from 'react-table';
import {ScanStatus} from './Helpers';
import MitigationsComponent from './MitigationsComponent';
class T1041 extends React.Component {
constructor(props) {
super(props);
}
static getC2Columns() {
return ([{
Header: 'Data exfiltration channels',
columns: [
{Header: 'Source', id: 'src', accessor: x => x.src, style: {'whiteSpace': 'unset'}},
{Header: 'Destination', id: 'dst', accessor: x => x.dst, style: {'whiteSpace': 'unset'}}
]
}])
}
render() {
return (
<div>
<div>{this.props.data.message_html}</div>
<br/>
{this.props.data.status === ScanStatus.USED ?
<ReactTable
columns={T1041.getC2Columns()}
data={this.props.data.command_control_channel}
showPagination={false}
defaultPageSize={this.props.data.command_control_channel.length}
/> : ''}
<MitigationsComponent mitigations={this.props.data.mitigations}/>
</div>
);
}
}
export default T1041;
|
src/auth/Credentials.js | BushrootPDX/app | import React from 'react';
import styled from 'styled-components';
const Form = styled.form`
text-align: center;
label {
display: block;
}
label, button {
padding: 5px;
}
`;
export default ({ submit}) => (
<Form onSubmit={e => {
e.preventDefault();
const { elements } = e.target;
const data = Object.keys(elements).reduce((obj, key) => {
obj[key] = elements[key].value;
return obj;
}, {});
submit(data);
}}>
<label>email: <input name="email"/></label>
<label>password: <input type="password" name="password"/></label>
<button>Sign in!</button>
</Form>
); |
src/components/Game.js | vgamula/poisoning | import React, { Component } from 'react';
import {gameStep} from 'bl';
class Cell extends Component {
render() {
const isInfected = this.props.data.infected;
const isHealing = this.props.data.infected && this.props.data.ticks > 6;
let style = {
backgroundColor: 'green',
};
if (isInfected) {
style.backgroundColor = 'red';
}
if (isHealing) {
style.backgroundColor = 'blue';
}
return <td width='10' height='10' style={style}></td>
}
}
class Row extends Component {
render() {
return <tr>{this.props.data.map((x, i) => <Cell data={x} key={i} />)}</tr>
}
}
export default class extends Component {
constructor(props) {
super(props);
this.state = {
data: props.data,
step: 0
};
}
render() {
let sterStyle = {
'font-size': 16 + 'px',
'text-align': 'center',
'border': 1 + 'px solid #E81515',
'borderRadius': 5 + 'px',
'background-color': '#CBF3C4',
'padding': 20 + 'px',
};
let tableStyle = {
'margin': 0 + ' auto',
}
return (
<div>
<p style={sterStyle}>
{`Step ${this.state.step}`}
</p>
<table style={tableStyle}>
<tbody>
{this.state.data.map((x, i) => <Row data={x} key={i} />)}
</tbody>
</table>
</div>
);
}
componentWillUnmount() {
clearTimeout(this.gameTimer);
}
componentDidMount() {
this.gameTimer = setInterval(() => {
this.setState({
data: gameStep(this.state.data),
step: this.state.step + 1
});
}, 500);
}
}
|
react/features/base/react/components/native/NavigateSectionListEmptyComponent.js | gpolitis/jitsi-meet | // @flow
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { translate } from '../../../i18n';
import { Icon, IconMenuDown } from '../../../icons';
import styles from './styles';
type Props = {
/**
* The translate function.
*/
t: Function,
};
/**
* Implements a React Native {@link Component} that is to be displayed when the
* list is empty.
*
* @augments Component
*/
class NavigateSectionListEmptyComponent extends Component<Props> {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const { t } = this.props;
return (
<View style = { styles.pullToRefresh }>
<Text style = { styles.pullToRefreshText }>
{ t('sectionList.pullToRefresh') }
</Text>
<Icon
src = { IconMenuDown }
style = { styles.pullToRefreshIcon } />
</View>
);
}
}
export default translate(NavigateSectionListEmptyComponent);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.