path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/components/display_message.js | santhoshml/Bookbild-UI | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Link } from 'react-router-dom';
import DisplayIOIList from './display_IOI_list';
import { appendToMsgList, getMsgListAction, fetchAllContactsToMessageAction, postNewMsgAction } from '../actions/index';
import * as actionCreators from '../actions/index';
import lsUtils from '../utils/ls_utils';
import cUtils from '../utils/common_utils';
import msgUtils from '../utils/message_utils';
import constants from '../utils/constants';
import NavBar from './sidebar';
import Header from './header';
import Autosuggest from 'react-bootstrap-autosuggest';
import dateFormat from 'dateformat';
import ScrollArea from 'react-scrollbar';
import Text from 'react-format-text';
import { CircleLoader } from 'react-spinners';
class DisplayMessage extends Component{
constructor(props){
super(props);
this.handleNewContentChange = this.handleNewContentChange.bind(this);
this.handleToChange = this.handleToChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleNewMsgLinkSubmit = this.handleNewMsgLinkSubmit.bind(this);
}
componentWillMount() {
let user = lsUtils.getValue(constants.KEY_USER_OBJECT);
let company = lsUtils.getValue(constants.KEY_COMPANY_OBJECT);
this.setState({
user : user,
company : company,
activeMessageId : null,
loading : true
});
}
componentWillReceiveProps(nextProps){
if(nextProps.isComposeNewMsg && nextProps.isComposeNewMsg !== this.state.isComposeNewMsg){
this.props.fetchAllContactsToMessageAction();
this.setState({
isComposeNewMsg : nextProps.isComposeNewMsg,
loading : false
});
} else if(nextProps.activeMessageId && nextProps.activeMessageId !== this.state.activeMessageId){
this.props.getMsgListAction(nextProps.activeMessageId);
this.setState({
activeMessageId : nextProps.activeMessageId,
loading : false
});
}
}
handleToChange(value) {
this.setState({
to : value
});
}
handleNewContentChange(event) {
this.setState({
newContent : event.target.value
});
}
handleNewMsgLinkSubmit(event){
event.preventDefault();
let props = {
toId : msgUtils.getContactId(this.state.to, this.props.contactList),
msg : this.state.newContent,
fromId : this.state.user.contactId,
contactCompanyMap : {}
};
props.contactCompanyMap[props.fromId] = this.state.user.companyId;
props.contactCompanyMap[props.toId] = msgUtils.getCompanyId(props.toId, this.props.contactList);
this.props.postNewMsgAction(props)
this.props.resetComposeNewMessage();
}
// user is replying to the old msg
handleSubmit(event) {
let that = this;
event.preventDefault();
let props = {
messageId : this.props.activeMessageId,
msg : this.state.newContent,
fromId : this.state.user.contactId
};
this.props.appendToMsgList(props)
.then(() => {
that.props.getMsgListAction(that.props.activeMessageId);
});
this.setState({
newContent : ''
});
}
displayEachPreviousMsg(){
return this.props.messages.msgList.map((msg)=>{
if(msg.fromId === this.state.user.contactId){
return(
<div key={new Date().getTime() * Math.random()} style={{display: 'block', textAlign: 'right', width : 'inherit', position : 'relative'}}>
<div style={{padding: '10px', fontSize : '13px'}}>
{this.props.convContactMap[msg.fromId]} says ({dateFormat(msg.timestamp, 'hh:MM tt, mmm dd')})...
</div>
<div style={{padding: '10px', margin: '5px', borderRadius : '25px', background: '#F5F5F5', textAlign: 'left'}}>
{this.getFormattedText(msg.msg)}
</div>
<br/>
</div>
);
} else {
return(
<div key={new Date().getTime() * Math.random()} style={{display: 'block', textAlign: 'left', width : 'inherit', position : 'relative'}}>
<div style={{padding: '10px', fontSize : '13px'}}>
{this.props.convContactMap[msg.fromId]} says ({dateFormat(msg.timestamp, 'hh:MM tt, mmm dd')})...
</div>
<div style={{padding: '10px', margin: '5px', borderRadius : '25px', border : '2px solid #F5F5F5'}}>
{this.getFormattedText(msg.msg)}
</div>
<br/>
</div>
);
}
})
}
getFormattedText(msg){
return (<Text>{msg}</Text>);
}
displayPreviousMsgs(){
return (
<ScrollArea
speed={0.8}
className="area"
contentClassName="content"
horizontal={false}
style={{height : '350px', backgroundColor : 'white'}}
smoothScrolling = {true}
>
{this.props.messages ? this.displayEachPreviousMsg.bind(this) : ''}
</ScrollArea>
);
}
displayMessageBody(){
if(this.props.isComposeNewMsg){
return(
<div>
<div className="body-header">New Message</div>
<hr style={{marginTop:'15px', marginBottom:'0px'}}/>
<form onSubmit={this.handleNewMsgLinkSubmit}>
<div>
<Autosuggest
datalist = {this.props.nameDropdownList}
placeholder="Start typing the name..."
onChange = {this.handleToChange}
value = {this.state.to}
/>
</div>
<div>
<textArea
rows = "17"
style={{width : '100%', fontSize:'15px', fontWeight:'400'}}
placeholder = "your content will showup here..."
name="pastContent"
value = {''}
disabled />
</div>
<div>
<textArea
rows = "10"
style={{width : '100%', fontSize:'15px', fontWeight:'400', resize:'none'}}
name="newContent"
value = {this.state.newContent}
onChange = {this.handleNewContentChange}
placeholder = "Write a message here to reply ..."
/>
</div>
<div>
<input
style = {{float:"right", paddingLeft: "20px", paddingRight: "20px", marginRight:"20px", paddingTop: "10px"}}
type="submit"
name="buttonArea"
value="Send"/>
</div>
</form>
</div>
);
} else {
return(
<div>
<div><span className="body-header">{this.props.contactName}</span>, <span className="body-header-companyName">{this.props.companyName}</span></div>
<hr style={{marginTop:'15px', marginBottom:'0px'}}/>
<form onSubmit={this.handleSubmit}>
<div>
{this.displayPreviousMsgs()}
</div>
<hr style={{marginTop:'0px', marginBottom:'0px'}}/>
<div>
<textArea
rows = "10"
style={{width : '100%', fontSize:'15px', fontWeight:'400', resize:'none'}}
name="newContent"
value = {this.state.newContent}
onChange = {this.handleNewContentChange}
placeholder = "Write a message here to reply ..."
/>
</div>
<div>
<input
style = {{float:"right", paddingLeft: "20px", paddingRight: "20px", marginRight:"20px", marginTop: "10px"}}
type="submit"
name="buttonArea"
value="Send"/>
</div>
</form>
</div>
);
}
}
render(){
return(
<div style={{float : 'right', width : '70%', height : '700px', border : '1px solid black'}}>
{this.displayMessageBody()}
</div>
);
}
}
function mapStateToProps(state) {
let rObject = {};
if(state.contactList.contactList){
let nameDropdownList = [];
let ctList = state.contactList.contactList;
if(ctList && ctList.length > 0){
for(let i=0; i< ctList.length; i++){
let contact = ctList[i];
nameDropdownList.push(contact.fullName+'<'+contact.companyName+'>');
}
}
rObject.nameDropdownList = nameDropdownList;
rObject.contactList = state.contactList.contactList;
}
if(state.messages.messages){
rObject.messages = state.messages.messages;
}
if(state.messages.convContactMap){
rObject.convContactMap = state.messages.convContactMap;
}
return rObject;
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
fetchAllContactsToMessageAction : fetchAllContactsToMessageAction,
postNewMsgAction : postNewMsgAction,
getMsgListAction : getMsgListAction,
appendToMsgList : appendToMsgList
}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(DisplayMessage);
|
app/containers/HomePage/index.js | ReelTalkers/reeltalk-web | /*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*/
import React from 'react'
import Relay from 'react-relay'
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer('http://localhost:8000/graphql')
)
import { connect } from 'react-redux'
import { push } from 'react-router-redux'
import shouldPureComponentUpdate from 'react-pure-render/function'
import ViewerRoute from '../../routes/ViewerRoute'
import { createSelector } from 'reselect'
import {
selectRepos,
selectLoading,
selectError
} from 'containers/App/selectors'
import {
selectUsername
} from './selectors'
import BrowsePage from 'containers/BrowsePage'
// import styles from './styles.css'
export class HomePage extends React.Component {
shouldComponentUpdate = shouldPureComponentUpdate
/**
* Changes the route
*
* @param {string} route The route we want to go to
*/
openRoute = (route) => {
this.props.changeRoute(route)
}
render() {
return (
<Relay.RootContainer
Component={BrowsePage}
route={new ViewerRoute()}
/>
)
}
}
HomePage.propTypes =
{ changeRoute: React.PropTypes.func
, loading: React.PropTypes.bool
, error: React.PropTypes.oneOfType(
[ React.PropTypes.object
, React.PropTypes.bool
])
}
function mapDispatchToProps(dispatch) {
return {
changeRoute: (url) => dispatch(push(url))
, dispatch
}
}
// Wrap the component to inject dispatch and state into it
export default connect(createSelector(
selectRepos(),
selectUsername(),
selectLoading(),
selectError(),
(repos, username, loading, error) => ({ repos, username, loading, error })
), mapDispatchToProps)(HomePage)
|
src/components/SearchBar.js | gshackles/react-demo-beerlist | import React, { Component } from 'react';
class SearchBar extends Component {
constructor(props) {
super(props);
this._keyChange = this._keyChange.bind(this);
}
_keyChange(event) {
const searchKey = event.target.value;
this.props.searchHandler(searchKey);
}
render() {
return (
<div>
<input type="text" onChange={this._keyChange} autoFocus="true" placeholder="beer or brewery name" />
</div>
);
}
}
SearchBar.propTypes = {
searchHandler: React.PropTypes.func.isRequired
};
export default SearchBar; |
docs/src/CodeExample.js | jamon/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]
);
}
}
|
manager/src/components/common/RefreshIcon.js | victorditadi/IQApp | import React, { Component } from 'react';
import { Text, TouchableOpacity } from 'react-native';
import { Icon } from 'native-base';
const RefreshIcon = () => {
return (
<TouchableOpacity>
<Icon name='ios-mail' style={Styles.iconStyle}/>
</TouchableOpacity>
)
}
const Styles = {
iconStyle: {
fontSize: 130,
color: '#737373'
}
};
export { RefreshIcon } ;
|
app/javascript/mastodon/features/lists/components/new_list_form.js | gol-cha/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { changeListEditorTitle, submitListEditor } from '../../../actions/lists';
import IconButton from '../../../components/icon_button';
import { defineMessages, injectIntl } from 'react-intl';
const messages = defineMessages({
label: { id: 'lists.new.title_placeholder', defaultMessage: 'New list title' },
title: { id: 'lists.new.create', defaultMessage: 'Add list' },
});
const mapStateToProps = state => ({
value: state.getIn(['listEditor', 'title']),
disabled: state.getIn(['listEditor', 'isSubmitting']),
});
const mapDispatchToProps = dispatch => ({
onChange: value => dispatch(changeListEditorTitle(value)),
onSubmit: () => dispatch(submitListEditor(true)),
});
export default @connect(mapStateToProps, mapDispatchToProps)
@injectIntl
class NewListForm extends React.PureComponent {
static propTypes = {
value: PropTypes.string.isRequired,
disabled: PropTypes.bool,
intl: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
};
handleChange = e => {
this.props.onChange(e.target.value);
}
handleSubmit = e => {
e.preventDefault();
this.props.onSubmit();
}
handleClick = () => {
this.props.onSubmit();
}
render () {
const { value, disabled, intl } = this.props;
const label = intl.formatMessage(messages.label);
const title = intl.formatMessage(messages.title);
return (
<form className='column-inline-form' onSubmit={this.handleSubmit}>
<label>
<span style={{ display: 'none' }}>{label}</span>
<input
className='setting-text'
value={value}
disabled={disabled}
onChange={this.handleChange}
placeholder={label}
/>
</label>
<IconButton
disabled={disabled || !value}
icon='plus'
title={title}
onClick={this.handleClick}
/>
</form>
);
}
}
|
actor-apps/app-web/src/app/components/common/Banner.react.js | hmoraes/actor-platform | import React from 'react';
import BannerActionCreators from 'actions/BannerActionCreators';
class Banner extends React.Component {
constructor(props) {
super(props);
if (window.localStorage.getItem('banner_jump') === null) {
BannerActionCreators.show();
}
}
onClose = () => {
BannerActionCreators.hide();
};
onJump = (os) => {
BannerActionCreators.jump(os);
this.onClose();
};
render() {
return (
<section className="banner">
<p>
Welcome to <b>Actor Network</b>! Check out our <a href="//actor.im/ios" onClick={this.onJump.bind(this, 'IOS')} target="_blank">iPhone</a> and <a href="//actor.im/android" onClick={this.onJump.bind(this, 'ANDROID')} target="_blank">Android</a> apps!
</p>
<a className="banner__hide" onClick={this.onClose}>
<i className="material-icons">close</i>
</a>
</section>
);
}
}
export default Banner;
|
src/js/components/Button/stories/Active.js | HewlettPackard/grommet | import React from 'react';
import { Add } from 'grommet-icons';
import { Box, Button, Text } from 'grommet';
export const Active = () => (
<Box pad="large" gap="large">
{/* Out of the Box Button */}
<Box align="center">
<Button hoverIndicator="light-1" onClick={() => {}} active>
{/* When Button include children, it is treated as plain */}
<Box pad="small" direction="row" align="center" gap="small">
<Add />
<Text>Add</Text>
</Box>
</Button>
</Box>
</Box>
);
export default {
title: 'Controls/Button/Active',
};
|
src/components/IndexProduct.js | BinaryCool/LaceShop | require('styles/IndexProduct.scss');
import React from 'react';
import ContentTitle from './ContentTitle.js';
import ContentTitle2 from './ContentTitle2.js';
import IndexProductsItem from './IndexProductsItem.js';
import {URL_LOAD_USER,URL_LOAD_CLIENTPICTYPE_VENDER,URL_LOAD_VENDERPICTYPE_VENDER} from '../utils/URLs.js';
import { connect } from 'react-redux';
import { ajaxRequest, getAdress ,LOAD_NOW_SUCCESS, LOAD_FINDHOT_SUCCESS, LOAD_BIGSIDE_SUCCESS, LOAD_SMALLSIDE_SUCCESS,
LOAD_LINING_SUCCESS, LOAD_EYELASH_SUCCESS, LOAD_USER_SUCCESS,LOAD_CLIENTTYPE_SUCCESS,LOAD_VENDERTYPE_SUCCESS} from '../actions';
export default class IndexProduct extends React.Component {
constructor(props) {
super(props);
this.state = {ourname:null};
this.picType = null;
// this.types = [];
this.flag = true;
this.getUserCallback = this.getUserCallback.bind(this);
this.getMao = this.getMao.bind(this);
}
/**
* 获取用户后的回调函数
*/
getUserCallback(user){
if(user.userType == 1){//档口
this.props.ajaxRequest(URL_LOAD_CLIENTPICTYPE_VENDER, LOAD_CLIENTTYPE_SUCCESS, {
userId:user.userId,
});
}else if(user.userType ==2){//产家
this.props.ajaxRequest(URL_LOAD_VENDERPICTYPE_VENDER, LOAD_VENDERTYPE_SUCCESS, {
userId:user.userId,
});
}
}
componentWillMount(){
const { indexName,type } =this.props.params;
let indexNames = indexName;
if(indexName){
let index = indexName.indexOf('.');
if(index > 0) {
indexNames = indexName.substring(0, index);
}
this.state.ourname = indexNames
}
this.props.getAdress(this.state.ourname);
this.props.ajaxRequest(URL_LOAD_USER, LOAD_USER_SUCCESS, {
indexName: indexNames,
type: type,
}, null, this.getUserCallback);
}
goto(category){
if(category == 1){
window.location.href ='#linging'
}else if(category == 2){
window.location.href ='#bigSize'
}else if(category == 3){
window.location.href ='#smallSize'
}else if(category == 4){
window.location.href ='#eyeslash';
}
}
getMao(){
if(this.picType ){
return (
this.picType.map((picCategory,index)=>
{
return (picCategory.categoryName =="面料"? <button onClick={this.goto.bind(this,1)}>面料</button>:
(picCategory.categoryName =="大边")? <button onClick={this.goto.bind(this,2)}>大边</button>:
(picCategory.categoryName =="小边")? <button onClick={this.goto.bind(this,3)}>小边</button>:
(picCategory.categoryName =="睫毛")? <button onClick={this.goto.bind(this,4)}>睫毛</button>:"" )
}
)
)
}
}
render() {
console.log("===this.props.user===",this.props.user)
if(this.props.picClientType.length>0){
this.picType = this.props.picClientType
}else if(this.props.picVenderType.length>0){
this.picType = this.props.picVenderType
}
return (
<div className="content">
<div className="container">
<div className = "allAnchor">
{this.getMao()}
</div>
<div className = "newSomething">
<span className = "iconfont icon-zuixin fire" ></span>
<ContentTitle title="最近新增" className = "fireName" pics={this.props.nowPic}/>
<IndexProductsItem orderBy="1" category="0" pics={this.props.nowPic} user={this.props.user} successType ={LOAD_NOW_SUCCESS}/>
</div>
<div className = "hotSomething">
<span className = "iconfont icon-redu news"></span>
<ContentTitle title="店铺热搜" pics={this.props.hotPic}/>
<IndexProductsItem user={this.props.user} pics={this.props.hotPic} orderBy="2" category="0" successType={LOAD_FINDHOT_SUCCESS}/>
</div>
<a name = 'linging'></a>
<ContentTitle2 title="面料" pics={this.props.liningPic}/>
<IndexProductsItem user={this.props.user} pics={this.props.liningPic} orderBy="0" category="4" successType={LOAD_LINING_SUCCESS}/>
<a name = 'bigSize'></a>
<ContentTitle2 title="大边" pics={this.props.bigSidePic}/>
<IndexProductsItem user={this.props.user} pics={this.props.bigSidePic} orderBy="0" category="2" successType={LOAD_BIGSIDE_SUCCESS} />
<a name = 'smallSize'></a>
<ContentTitle2 title="小边" pics={this.props.smallSidePic}/>
<IndexProductsItem user={this.props.user} pics={this.props.smallSidePic} orderBy="0" category="1" successType={LOAD_SMALLSIDE_SUCCESS} />
<a name = "eyeslash"></a>
<ContentTitle2 title="睫毛" pics={this.props.eyeslashPic}/>
<IndexProductsItem user={this.props.user} pics={this.props.eyeslashPic} orderBy="0" category="3" successType={LOAD_EYELASH_SUCCESS}/>
</div>
</div>
);
}
}
function mapStateToProps(state, ownProps) {
return {
user: state.user,
nowPic: state.nowPic,
hotPic: state.hotPic,
bigSidePic: state.bigSidePic,
smallSidePic: state.smallSidePic,
liningPic: state.liningPic,
eyeslashPic: state.eyeslashPic,
picClientType : state.picClientType,
picVenderType : state.picVenderType,
}
}
export default connect(mapStateToProps, {
ajaxRequest,
getAdress,
})(IndexProduct) |
src/svg-icons/image/looks-4.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageLooks4 = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4 14h-2v-4H9V7h2v4h2V7h2v10z"/>
</SvgIcon>
);
ImageLooks4 = pure(ImageLooks4);
ImageLooks4.displayName = 'ImageLooks4';
ImageLooks4.muiName = 'SvgIcon';
export default ImageLooks4;
|
src/components/app.js | eUstundag/react_redux_skeleton | import React from 'react';
import { Component } from 'react';
import BarComponent from '../containers/index'
export default class App extends Component {
render() {
return (
<BarComponent />
);
}
} |
app/components/AddDish.js | rondobley/meal-planner | import React from 'react';
import ReactDOM from 'react-dom';
import AddDishStore from '../stores/AddDishStore';
import AddDishActions from '../actions/AddDishActions';
class AddDish extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.state.dishName = '';
this.state.helpBlock = '';
this.state.modalFormValidationState = '';
this.state.isAdded = false;
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
AddDishStore.listen(this.onChange);
$('#addDishModal').on('shown.bs.modal', function() {
$(".form-group input").focus();
});
}
componentWillUnmount() {
AddDishStore.unlisten(this.onChange);
}
componentWillUpdate() {
if(this.state.isAdded) {
$('#addDishModal').modal('hide');
}
}
onChange(state) {
this.setState(state);
}
handleSubmit(e) {
e.preventDefault();
var dishName = this.state.dishName.trim();
if(!dishName) {
AddDishActions.invalidDishName();
ReactDOM.findDOMNode(this.refs.dishNameInput).focus();
} else {
AddDishActions.addDish(dishName);
}
}
render() {
let button = <button type='submit' className='btn btn-primary'>Add Dish</button>;
return (
<form onSubmit={this.handleSubmit.bind(this)}>
<div className={'form-group ' + this.state.modalFormValidationState}>
<label className='control-label'>Dish Name</label>
<input type='text' className='form-control' ref='dishNameInput' value={this.state.dishName}
onChange={AddDishActions.updateDishNameInput} autoFocus/>
<span className='help-block'>{this.state.helpBlock}</span>
</div>
{button}
</form>
);
}
}
export default AddDish;
|
src/graphs/lineChart.js | dat2/plottr | import React from 'react';
import randomColor from 'randomcolor';
import GraphSvg from '../utils/graphSvg';
import XAxis from '../utils/xAxis';
import YAxis from '../utils/yAxis';
import { domain, flatten, sort, uniq } from '../utils/functions';
const svgWidth = 800,
svgHeight = 450,
svgPadding = { top: 10, bottom: 10, left: 10, right: 10 },
chartWidth = (svgWidth - svgPadding.left - svgPadding.right),
chartHeight = (svgHeight - svgPadding.top - svgPadding.bottom);
export default function LineChart({ data: { data = [] }, graph: { } = {} } = {}) {
let xs = data.map(d => d.x);
let yss = data.map(d => d.ys);
const [, xMax] = domain(xs);
const [, yMax] = domain(flatten(yss));
const xScale = chartWidth / xMax;
const yScale = chartHeight / yMax;
const points = yss.map((ys, i) => ({ ys: ys.map(y => y * yScale), x: xs[i] * xScale }));
// in case users give us an empty array
const colours = data.length && data[0].ys.length ?
randomColor({ count: data[0].ys.length, luminosity: 'light' }) :
[];
const yTicks = sort(uniq(flatten(yss)), (a, b) => a - b);
// TODO plottr-info-circle needs an on:hover
return (
<GraphSvg width={svgWidth} height={svgHeight} padding={svgPadding}>
<g id='lines'>
{
points.map(({ x, ys }, i) =>
ys.map((y, yI) => (
<g key={yI}>
<line
x1={ i > 0 ? points[i-1].x : points[i].x }
x2={ x }
y1={ chartHeight - (i > 0 ? points[i-1].ys[yI] : points[i].ys[yI]) }
y2={ chartHeight - y }
key={ yI }
stroke={ colours[yI] }></line>
<circle
cx={ x }
cy={ chartHeight - y }
r='2'
fill={ colours[yI] }
stroke='transparent'
className='plottr-info-circle'
/>
</g>
))
)
}
</g>
<g id='axis'>
<XAxis xs={xs} xScale={xScale} chartWidth={chartWidth} chartHeight={chartHeight} tickSize={svgPadding.bottom / 2} textSize={svgPadding.bottom / 2} />
<YAxis ys={yTicks} yScale={yScale} chartWidth={chartWidth} chartHeight={chartHeight} tickSize={svgPadding.left / 2} textSize={svgPadding.left / 2} />
</g>
</GraphSvg>
);
}
|
src/routes/Home/components/WelcomeDialog.js | synchu/schema | import PropTypes from 'prop-types';
import React from 'react';
import { Dialog, Switch, Button } from 'react-toolbox'
import classes from './HomeView.scss'
export const WelcomeDialog = (props) => {
const { welcomeActive, handleWelcome } = props
let switchValue = !welcomeActive
return (
<Dialog
active={welcomeActive}
onEscKeyDown={() => handleWelcome(false, 'from_dlg')}
onOverlayClick={() => handleWelcome(false, 'from_dlg')}
title='Welcome to SchemA'
>
<p>SchemA is <a href='http://diyguitaramps.prophpbb.com/' target='_blank'>http://diyguitaramps.prophpbb.com/</a> supported
(mostly) guitar tube amps schematics, layouts, build photos and other useful documents archive.
<br />In order to provide this archive application functionality, we do store some data on your local device. Should you disagree, please, leave this web page.
<br />Please, make sure to read our privacy policy and terms of use to find out more.</p>
<Switch theme={classes}
checked={switchValue}
label='Do not show again'
onChange={(e, value) => handleWelcome(!e, 'from_switch')} />
<Button style={{ display: 'flex', marginLeft: 'auto' }} accent label='Close' onClick={() => handleWelcome(false, 'from_dlg')} />
</Dialog>
)
}
WelcomeDialog.propTypes = {
welcomeActive: PropTypes.bool,
handleWelcome: PropTypes.func.isRequired
}
export default WelcomeDialog
|
app/Resources/js/startup/home.js | ryota-murakami/tweet-pick | import React from 'react'
import { Provider } from 'react-redux'
import App from '../containers/home'
import ReactOnRails from 'react-on-rails'
const mainNode = () => {
const store = ReactOnRails.getStore('homeStore')
const reactComponent = (
<Provider store={store}>
<App/>
</Provider>
)
return reactComponent
}
export default mainNode
|
components/ItemTooltip.js | hobinjk/illuminate | import React from 'react';
import statsApi from '../static/stats';
import { connectToStores } from 'fluxible-addons-react';
import ItemTooltipStore from '../stores/ItemTooltipStore';
class ItemTooltip extends React.Component {
render() {
if (!this.props.item || !this.props.anchor) {
var style = {
display: 'none'
};
return <div style={style}></div>;
}
console.log('anchor', this.props.anchor);
let stats = this.props.item.stats;
let statKeys = Object.keys(stats);
let statDescriptions = statKeys.map(modifierKey => {
let name = statsApi.getModifierName(modifierKey);
let value = stats[modifierKey]
let sign = '+';
if (value < 0) {
sign = '-';
}
return <p className="item-stat">{sign}{value} {name}</p>
});
var bounds = this.props.anchor.getBoundingClientRect();
var style = {
top: bounds.top + bounds.height,
left: bounds.left
};
return <div className="tooltip item-icon-tooltip" style={style}>
{this.props.item.name}
{statDescriptions}
</div>;
}
}
ItemTooltip = connectToStores(ItemTooltip, [ItemTooltipStore], (context, props) => {
let store = context.getStore(ItemTooltipStore);
return {
anchor: store.getAnchor(),
item: store.getItem()
}
});
export default ItemTooltip;
|
app/components/Logo/index.js | BeautifulTrouble/beautifulrising-client | /**
*
* Logo
*
*/
import React from 'react';
import styled from 'styled-components';
import { Link } from 'react-router';
import { injectIntl } from 'react-intl';
import messages from './messages';
const Title = styled.h1`
position: absolute;
background-color: ${props=>props.withBg ? 'white' : 'transparent'};
top: ${props=> props.top || '0' };
left: 50%;
margin: 0;
transform: translate(-50%, 0);
@media(max-width: 1320px) {
}
@media(max-width: 970px) {
top: ${props=> props.top || '-15px' };
img {
width: 170px;
}
}
`;
class Logo extends React.Component {
render() {
const {formatMessage} = this.props.intl;
const language = this.props.intl.locale;
const lang = formatMessage(messages.logoLanguage);
if (this.props.isReversed !== undefined && this.props.isReversed) {
return (
<Title withBg={this.props.withBg} top={this.props.top} left={this.props.left} lang={language}>
<Link to='/'><img alt={`assets/images/logo-reverse-${lang}.png`} src={require(`assets/images/logo-reverse-${lang}.png`)} /></Link>
</Title>
);
} else {
return (
<Title withBg={this.props.withBg} top={this.props.top} left={this.props.left} lang={language}>
<Link to='/'><img src={require(`assets/images/logo-${lang}.png`)} /></Link>
</Title>
);
}
}
}
Logo.propTypes = {
};
export default injectIntl(Logo);
|
src/components/Move.js | tobice/flux-lumines | import React from 'react';
import PureComponent from './PureComponent.js';
export default class Move extends PureComponent {
render() {
return (
<g transform={'translate(' + this.props.x + ' ' + this.props.y + ')'}>
{this.props.children}
</g>
);
}
} |
popup/components/RecepientsList.js | tkorakas/gmail-lists | import React, { Component } from 'react';
import cleanSpecialCharactersAndRemoveSpaces from '../../utils/StringHelpers';
import IconButton from '@material-ui/core/IconButton';
import Input from '@material-ui/core/Input';
import ArrowBack from '@material-ui/icons/ArrowBack';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import AppBar from '@material-ui/core/AppBar';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import DeleteIcon from '@material-ui/icons/Delete';
import Divider from '@material-ui/core/Divider';
const styles = {
menuButton: {
marginLeft: -14,
marginRight: 4,
},
};
export default class RecipientsList extends Component {
constructor(props) {
super(props);
const item = cleanSpecialCharactersAndRemoveSpaces(this.props.item);
const storageKey = `gmail_lists_${item}`;
this.state = {
items: [],
storageKey,
};
this.addItem = this.addItem.bind(this);
this.deleteItem = this.deleteItem.bind(this);
this.saveToChromeStorage = this.saveToChromeStorage.bind(this);
this.loadLists = this.loadLists.bind(this);
}
componentDidMount() {
this.loadLists();
}
/**
* Load email for the current list.
*/
loadLists() {
chrome.storage.sync.get(this.state.storageKey, (data) => {
this.setState({
items: data[this.state.storageKey] !== undefined ? data[this.state.storageKey] : [],
})
});
}
/**
* Add new list.
*/
addItem(e) {
if (e.key === 'Enter') {
const newRecipient = this.text.value.trim();
// Check if list name already exists.
if (!this.state.items.includes(newRecipient) && newRecipient !== '') {
// Add new item to array and save to chrome storage and update state.
const items = [...this.state.items, newRecipient];
this.saveToChromeStorage(items, true);
}
this.text.value = '';
}
}
/**
* Delete an item from the list.
*/
deleteItem(e, item) {
e.preventDefault();
e.stopPropagation();
// Remove item from array and save to chrome storage and update state.
const items = this.state.items.filter((i) => i !== item);
this.saveToChromeStorage(items);
}
/**
* Set items to chrome storage and update local state.
*
* @param items
* Array with string items.
* @param isNewItem
* Check if is new item to scroll.
*/
saveToChromeStorage(items, isNewItem = false) {
let objectToSave = {};
objectToSave[this.state.storageKey] = items;
chrome.storage.sync.set(objectToSave, () => {
this.setState({
items,
}, () => {
if (isNewItem) {
// Scroll to last item.
this.list.scrollTop += 30 * (this.state.items.length);
}
});
});
}
render() {
return (
<div className="app-list">
<AppBar position="static">
<Toolbar>
<IconButton
style={styles.menuButton}
aria-label="Back"
onClick={() => this.props.changePage()}
>
<ArrowBack />
</IconButton>
<Typography variant="title" color="inherit">
{this.props.item}
</Typography>
</Toolbar>
</AppBar>
<Input placeholder="Recipient email" style={{ marginTop: 16, paddingLeft: 4 }} fullWidth={true} inputRef={c => this.text = c} type="email" autoFocus={true} onKeyPress={this.addItem} />
<List ref={(c) => this.list = c} component="nav">
{this.state.items.map(item => {
return (
<React.Fragment key={item + '_fragment'} >
<ListItem style={{paddingTop: 0, paddingBottom: 0}}>
<ListItemText primary={item} title={item} />
<IconButton
className="delete-button"
aria-label="More"
onClick={(e) => this.deleteItem(e, item)}
>
<DeleteIcon />
</IconButton>
</ListItem>
<Divider />
</React.Fragment>
);
})}
</List>
</div>
);
}
}
|
packages/mineral-ui-icons/src/IconLaptopWindows.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 IconLaptopWindows(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M20 18v-1c1.1 0 1.99-.9 1.99-2L22 5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2v1H0v2h24v-2h-4zM4 5h16v10H4V5z"/>
</g>
</Icon>
);
}
IconLaptopWindows.displayName = 'IconLaptopWindows';
IconLaptopWindows.category = 'hardware';
|
react-flux-mui/js/material-ui/docs/src/app/components/pages/components/FlatButton/ExampleComplex.js | pbogdan/react-flux-mui | import React from 'react';
import FlatButton from 'material-ui/FlatButton';
import FontIcon from 'material-ui/FontIcon';
import ActionAndroid from 'material-ui/svg-icons/action/android';
const styles = {
uploadButton: {
verticalAlign: 'middle',
},
uploadInput: {
cursor: 'pointer',
position: 'absolute',
top: 0,
bottom: 0,
right: 0,
left: 0,
width: '100%',
opacity: 0,
},
};
const FlatButtonExampleComplex = () => (
<div>
<FlatButton
label="Choose an Image"
labelPosition="before"
style={styles.uploadButton}
containerElement="label"
>
<input type="file" style={styles.uploadInput} />
</FlatButton>
<FlatButton
label="Label before"
labelPosition="before"
primary={true}
icon={<ActionAndroid />}
/>
<FlatButton
href="https://github.com/callemall/material-ui"
target="_blank"
label="GitHub Link"
secondary={true}
icon={<FontIcon className="muidocs-icon-custom-github" />}
/>
</div>
);
export default FlatButtonExampleComplex;
|
src/components/interaction-surface.js | ronlobo/building-os-charts | import React from 'react';
import d3 from 'd3';
import Events from 'events/events';
import getHeight from 'decorators/get-height';
import getMouseCoords from 'decorators/get-mouse-coords';
import getTranslate from 'decorators/get-translate';
import getWidth from 'decorators/get-width';
import setStateFromProps from 'decorators/set-state-from-props';
@getHeight
@getMouseCoords
@getTranslate
@getWidth
@setStateFromProps
export default class InteractionSurface extends React.Component {
static propTypes = {
dispatcher: React.PropTypes.object.isRequired,
height: React.PropTypes.number.isRequired,
tickWidth: React.PropTypes.number.isRequired,
width: React.PropTypes.number.isRequired,
x: React.PropTypes.number.isRequired,
y: React.PropTypes.number.isRequired,
}
static defaultProps = {
dispatcher: d3.dispatch(),
height: 0,
tickWidth: 0,
width: 0,
x: 0,
y: 0,
}
state = {
height: 0,
transform: '',
width: 0,
}
componentDidMount() {
this.addEventListeners();
}
componentWillUnmount() {
this.removeEventListeners();
}
setStateFromProps(props) {
this.setState({
height: this.getHeight(props.height),
transform: this.getTranslate(props.x, props.y),
width: this.getWidth(props.width),
});
}
addEventListeners() {
const node = React.findDOMNode(this);
d3.select(node)
.on(Events.MOUSE_MOVE, this.dispatchMouseMove.bind(this))
.on(Events.MOUSE_OUT, this.dispatchMouseOut.bind(this));
}
dispatchMouseMove() {
const node = React.findDOMNode(this);
const mouse = this.getMouseCoords(node);
this.props.dispatcher[Events.MOUSE_MOVE]({
activeIndex: Math.floor(mouse[0] / this.props.tickWidth),
type: Events.MOUSE_MOVE,
x: mouse[0],
y: mouse[1],
});
}
dispatchMouseOut() {
const node = React.findDOMNode(this);
const mouse = this.getMouseCoords(node);
this.props.dispatcher[Events.MOUSE_OUT]({
activeIndex: -1,
type: Events.MOUSE_OUT,
x: mouse[0],
y: mouse[1],
});
}
removeEventListeners() {
const node = React.findDOMNode(this);
d3.select(node)
.on(Events.MOUSE_MOVE, null)
.on(Events.MOUSE_OUT, null);
}
render() {
return (
<g
className={'interaction-surface'}
transform={this.state.transform}>
<rect
height={this.state.height}
style={{visibility: 'hidden'}}
width={this.state.width} />
</g>
);
}
}
|
src/HstWbInstaller.Imager.GuiApp/ClientApp/src/pages/Convert.js | henrikstengaard/hstwb-installer | import React from 'react'
import {get, isNil, set} from "lodash";
import Box from "@mui/material/Box";
import Title from "../components/Title";
import Grid from "@mui/material/Grid";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import TextField from "../components/TextField";
import BrowseSaveDialog from "../components/BrowseSaveDialog";
import Stack from "@mui/material/Stack";
import RedirectButton from "../components/RedirectButton";
import Button from "../components/Button";
import BrowseOpenDialog from "../components/BrowseOpenDialog";
import ConfirmDialog from "../components/ConfirmDialog";
const initialState = {
confirmOpen: false,
sourcePath: null,
destinationPath: null
}
export default function Convert() {
const [state, setState] = React.useState({...initialState})
const {
confirmOpen,
sourcePath,
destinationPath
} = state
const handleChange = ({name, value}) => {
set(state, name, value)
setState({...state})
}
const handleCancel = () => {
setState({...initialState})
}
const handleConvert = async () => {
const response = await fetch('api/convert', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: `Converting file '${sourcePath}' to file '${destinationPath}'`,
sourcePath,
destinationPath
})
});
if (!response.ok) {
console.error('Failed to convert')
}
}
const handleConfirm = async (confirmed) => {
setState({
...state,
confirmOpen: false
})
if (!confirmed) {
return
}
await handleConvert()
}
const convertDisabled = isNil(sourcePath) || isNil(destinationPath)
return (
<Box>
<ConfirmDialog
id="confirm-convert"
open={confirmOpen}
title="Convert"
description={`Do you want to convert file '${sourcePath}' to file '${destinationPath}'?`}
onClose={async (confirmed) => await handleConfirm(confirmed)}
/>
<Title
text="Convert"
description="Convert image file from one format to another."
/>
<Grid container spacing="2" direction="row" alignItems="center" sx={{mt: 2}}>
<Grid item xs={12} lg={6}>
<TextField
id="source-path"
label={
<div style={{display: 'flex', alignItems: 'center', verticalAlign: 'bottom'}}>
<FontAwesomeIcon icon="file" style={{marginRight: '5px'}} /> Source image file
</div>
}
value={sourcePath || ''}
endAdornment={
<BrowseOpenDialog
id="browse-source-path"
title="Select source image file"
onChange={(path) => handleChange({
name: 'sourcePath',
value: path
})}
/>
}
onChange={(event) => handleChange({
name: 'sourcePath',
value: get(event, 'target.value'
)
})}
/>
</Grid>
</Grid>
<Grid container spacing="2" direction="row" alignItems="center" sx={{mt: 2}}>
<Grid item xs={12} lg={6}>
<TextField
id="destination-path"
label={
<div style={{display: 'flex', alignItems: 'center', verticalAlign: 'bottom'}}>
<FontAwesomeIcon icon="file" style={{marginRight: '5px'}} /> Destination image file
</div>
}
value={destinationPath || ''}
endAdornment={
<BrowseSaveDialog
id="browse-destination-path"
title="Select destination image file"
onChange={(path) => handleChange({
name: 'destinationPath',
value: path
})}
/>
}
onChange={(event) => handleChange({
name: 'destinationPath',
value: get(event, 'target.value'
)
})}
/>
</Grid>
</Grid>
<Grid container spacing="2" direction="row" alignItems="center" sx={{mt: 2}}>
<Grid item xs={12} lg={6}>
<Box display="flex" justifyContent="flex-end">
<Stack direction="row" spacing={2} sx={{mt: 2}}>
<RedirectButton
path="/"
icon="ban"
onClick={async () => handleCancel()}
>
Cancel
</RedirectButton>
<Button
disabled={convertDisabled}
icon="exchange-alt"
onClick={async () => handleChange({
name: 'confirmOpen',
value: true
})}
>
Start convert
</Button>
</Stack>
</Box>
</Grid>
</Grid>
</Box>
)
} |
frontend/app_v2/src/common/icons/Twitter.js | First-Peoples-Cultural-Council/fv-web-ui | import React from 'react'
import PropTypes from 'prop-types'
function Twitter({ styling }) {
return (
<svg
viewBox="0 0 512 512"
xmlns="http://www.w3.org/2000/svg"
fillRule="evenodd"
clipRule="evenodd"
strokeLinejoin="round"
strokeMiterlimit="2"
fill="none"
stroke="currentColor"
className={styling}
>
<title>Twitter</title>
<path d="M449.446,0c34.525,0 62.554,28.03 62.554,62.554l0,386.892c0,34.524 -28.03,62.554 -62.554,62.554l-386.892,0c-34.524,0 -62.554,-28.03 -62.554,-62.554l0,-386.892c0,-34.524 28.029,-62.554 62.554,-62.554l386.892,0Zm-253.927,424.544c135.939,0 210.268,-112.643 210.268,-210.268c0,-3.218 0,-6.437 -0.153,-9.502c14.406,-10.421 26.973,-23.448 36.935,-38.314c-13.18,5.824 -27.433,9.809 -42.452,11.648c15.326,-9.196 26.973,-23.602 32.49,-40.92c-14.252,8.429 -30.038,14.56 -46.896,17.931c-13.487,-14.406 -32.644,-23.295 -53.946,-23.295c-40.767,0 -73.87,33.104 -73.87,73.87c0,5.824 0.613,11.494 1.992,16.858c-61.456,-3.065 -115.862,-32.49 -152.337,-77.241c-6.284,10.881 -9.962,23.601 -9.962,37.088c0,25.594 13.027,48.276 32.95,61.456c-12.107,-0.307 -23.448,-3.678 -33.41,-9.196l0,0.92c0,35.862 25.441,65.594 59.311,72.49c-6.13,1.686 -12.72,2.606 -19.464,2.606c-4.751,0 -9.348,-0.46 -13.946,-1.38c9.349,29.426 36.628,50.728 68.965,51.341c-25.287,19.771 -57.164,31.571 -91.8,31.571c-5.977,0 -11.801,-0.306 -17.625,-1.073c32.337,21.15 71.264,33.41 112.95,33.41Z" />
</svg>
)
}
// PROPTYPES
const { string } = PropTypes
Twitter.propTypes = {
styling: string,
}
export default Twitter
|
techCurriculum/ui/solutions/4.5/src/App.js | AnxChow/EngineeringEssentials-group | /**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
import React from 'react';
import Title from './components/Title';
import Card from './components/Card';
import CardForm from './components/CardForm';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cards: [
{
author: 'John Smith',
text: 'React is so cool!'
},
{
author: 'Jane Doe',
text: 'I use React for all my projects!'
}
]
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit() {
}
render() {
const cards = this.state.cards.map((card, index) => (
<Card author={card.author}
text={card.text}
key={index} />
));
return (
<div id='app-body'>
<div id='left-panel'>
<Title />
{ cards }
</div>
<CardForm onSubmit={this.handleSubmit} />
</div>
);
}
}
export default App;
|
app/react-icons/fa/font.js | scampersand/sonos-front | import React from 'react';
import IconBase from 'react-icon-base';
export default class FaFont extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m17.7 12.5l-3.8 10q0.7 0 3 0.1t3.6 0q0.4 0 1.3 0-2-5.7-4.1-10.1z m-16.2 24.6l0-1.7q0.6-0.2 1.3-0.3t1.3-0.2 1.1-0.4 1-0.6 0.7-1.1l5.2-13.8 6.3-16.1h2.9q0.1 0.3 0.2 0.4l4.6 10.7q0.7 1.8 2.3 5.8t2.6 6.1q0.3 0.8 1.3 3.2t1.6 3.8q0.4 1 0.8 1.3 0.4 0.3 1.9 0.6t1.9 0.5q0.1 0.8 0.1 1.3 0 0.1 0 0.3t0 0.2q-1.4 0-4.2-0.1t-4.3-0.2q-1.7 0-4.8 0.1t-4 0.2q0-0.9 0.1-1.7l3-0.6q0 0 0.2-0.1t0.4-0.1 0.3-0.1 0.3-0.1 0.3-0.2 0.2-0.3 0-0.3q0-0.3-0.6-2.1t-1.7-4-0.9-2.2l-10-0.1q-0.6 1.3-1.7 4.4t-1.2 3.6q0 0.5 0.3 0.9t1 0.5 1.1 0.3 1.3 0.2 0.9 0.1q0 0.4 0 1.3 0 0.2 0 0.6-1.3 0-3.9-0.2t-3.9-0.3q-0.2 0-0.6 0.1t-0.5 0.1q-1.8 0.3-4.2 0.3z"/></g>
</IconBase>
);
}
}
|
src/components/Markup.js | NuCivic/react-dashboard | import React, { Component } from 'react';
import Registry from '../utils/Registry';
import BaseComponent from './BaseComponent';
import Card from './Card';
import { isArray } from 'lodash';
export default class Markup extends BaseComponent {
getContent() {
if (this.props.data && isArray(this.props.data) && this.props.data.length > 0) {
return this.props.data[0];
};
if (this.props.data && !isArray(this.props.data)) {
return this.props.data;
};
if (this.props.content) {
return this.props.content;
}
return '';
}
render() {
return (
<Card {...this.state.cardVariables}>
<div dangerouslySetInnerHTML={ {__html: this.getContent()}}></div>
</Card>
)
}
}
Registry.set('Markup', Markup);
|
components/footer/footer_test.js | BrontosaurusTails/Sovereign | import React from 'react';
import reactDom from 'react-dom/server';
import test from 'tape';
import dom from 'cheerio';
import Footer from './index.js';
const render = reactDom.renderToStaticMarkup;
test('Footer component', assert => {
const msg = 'should render 1 link';
const el = <Footer />;
const $ = dom.load(render(el));
const actual = $('a').length;
const expected = 1;
assert.same(actual, expected, msg);
assert.end();
});
|
src/InputGroupAddon.js | dozoisch/react-bootstrap | import classNames from 'classnames';
import React from 'react';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
class InputGroupAddon extends React.Component {
render() {
const { className, ...props } = this.props;
const [bsProps, elementProps] = splitBsProps(props);
const classes = getClassSet(bsProps);
return (
<span
{...elementProps}
className={classNames(className, classes)}
/>
);
}
}
export default bsClass('input-group-addon', InputGroupAddon);
|
src/react.js | tchon/redux | import React from 'react';
import createAll from './components/createAll';
export const { Provider, Connector, provide, connect } = createAll(React);
|
resources/assets/javascript/components/plantsViewContainer.js | colinjeanne/garden | import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { createPlant, editPlant, updatePlant } from '../actions/plantActions';
import {
filterPlants,
selectPlant,
sortPlants } from '../actions/navigationActions';
import PlantsViewPage from './plantsViewPage';
import React from 'react';
const mapStateToProps = state => {
let selectedPlant = state.plants.dirty.find(
plant => plant.name === state.plants.selectedPlantName);
if (!selectedPlant) {
selectedPlant = state.plants.plants.find(
plant => plant.name === state.plants.selectedPlantName);
}
return {
editing: state.plantsView.editing,
plants: state.plants.plants,
selectedPlant: selectedPlant,
visiblePlantNames: state.plants.visibleByName
};
};
const handleEditPlant = (editing, selectedPlant) =>
editPlant(editing, selectedPlant.name);
const mapDispatchToProps = dispatch => {
return bindActionCreators({
onAddPlant: createPlant,
onEdit: handleEditPlant,
onFilterPlants: filterPlants,
onSelectPlant: selectPlant,
onSortPlants: sortPlants,
onUpdatePlant: updatePlant
},
dispatch);
};
export default connect(mapStateToProps, mapDispatchToProps)(PlantsViewPage); |
app/javascript/mastodon/features/getting_started/index.js | palon7/mastodon | import React from 'react';
import Column from '../ui/components/column';
import ColumnLink from '../ui/components/column_link';
import ColumnSubheading from '../ui/components/column_subheading';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
heading: { id: 'getting_started.heading', defaultMessage: 'Getting started' },
home_timeline: { id: 'tabs_bar.home', defaultMessage: 'Home' },
notifications: { id: 'tabs_bar.notifications', defaultMessage: 'Notifications' },
public_timeline: { id: 'navigation_bar.public_timeline', defaultMessage: 'Federated timeline' },
navigation_subheading: { id: 'column_subheading.navigation', defaultMessage: 'Navigation' },
settings_subheading: { id: 'column_subheading.settings', defaultMessage: 'Settings' },
community_timeline: { id: 'navigation_bar.community_timeline', defaultMessage: 'Local timeline' },
preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' },
follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' },
sign_out: { id: 'navigation_bar.logout', defaultMessage: 'Logout' },
favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' },
blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' },
mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' },
info: { id: 'navigation_bar.info', defaultMessage: 'Extended information' },
});
const mapStateToProps = state => ({
me: state.getIn(['accounts', state.getIn(['meta', 'me'])]),
columns: state.getIn(['settings', 'columns']),
});
@connect(mapStateToProps)
@injectIntl
export default class GettingStarted extends ImmutablePureComponent {
static propTypes = {
intl: PropTypes.object.isRequired,
me: ImmutablePropTypes.map.isRequired,
columns: ImmutablePropTypes.list,
multiColumn: PropTypes.bool,
};
render () {
const { intl, me, columns, multiColumn } = this.props;
let navItems = [];
if (multiColumn) {
if (!columns.find(item => item.get('id') === 'HOME')) {
navItems.push(<ColumnLink key='0' icon='home' text={intl.formatMessage(messages.home_timeline)} to='/timelines/home' />);
}
if (!columns.find(item => item.get('id') === 'NOTIFICATIONS')) {
navItems.push(<ColumnLink key='1' icon='bell' text={intl.formatMessage(messages.notifications)} to='/notifications' />);
}
if (!columns.find(item => item.get('id') === 'COMMUNITY')) {
navItems.push(<ColumnLink key='2' icon='users' text={intl.formatMessage(messages.community_timeline)} to='/timelines/public/local' />);
}
if (!columns.find(item => item.get('id') === 'PUBLIC')) {
navItems.push(<ColumnLink key='3' icon='globe' text={intl.formatMessage(messages.public_timeline)} to='/timelines/public' />);
}
}
navItems = navItems.concat([
<ColumnLink key='4' icon='star' text={intl.formatMessage(messages.favourites)} to='/favourites' />,
]);
if (me.get('locked')) {
navItems.push(<ColumnLink key='5' icon='users' text={intl.formatMessage(messages.follow_requests)} to='/follow_requests' />);
}
navItems = navItems.concat([
<ColumnLink key='6' icon='volume-off' text={intl.formatMessage(messages.mutes)} to='/mutes' />,
<ColumnLink key='7' icon='ban' text={intl.formatMessage(messages.blocks)} to='/blocks' />,
]);
return (
<Column icon='asterisk' heading={intl.formatMessage(messages.heading)} hideHeadingOnMobile>
<div className='getting-started__wrapper'>
<ColumnSubheading text={intl.formatMessage(messages.navigation_subheading)} />
{navItems}
<ColumnSubheading text={intl.formatMessage(messages.settings_subheading)} />
<ColumnLink icon='book' text={intl.formatMessage(messages.info)} href='/about/more' />
<ColumnLink icon='cog' text={intl.formatMessage(messages.preferences)} href='/settings/preferences' />
<ColumnLink icon='sign-out' text={intl.formatMessage(messages.sign_out)} href='/auth/sign_out' method='delete' />
</div>
<div className='getting-started__footer scrollable optionally-scrollable'>
<div className='static-content getting-started'>
<p>
<a href='https://github.com/tootsuite/documentation/blob/master/Using-Mastodon/FAQ.md' rel='noopener' target='_blank'><FormattedMessage id='getting_started.faq' defaultMessage='FAQ' /></a> • <a href='https://github.com/tootsuite/documentation/blob/master/Using-Mastodon/User-guide.md' rel='noopener' target='_blank'><FormattedMessage id='getting_started.userguide' defaultMessage='User Guide' /></a> • <a href='https://github.com/tootsuite/documentation/blob/master/Using-Mastodon/Apps.md' rel='noopener' target='_blank'><FormattedMessage id='getting_started.appsshort' defaultMessage='Apps' /></a>
</p>
<p>
<FormattedMessage
id='getting_started.open_source_notice'
defaultMessage='Mastodon is open source software. You can contribute or report issues on GitHub at {github}.'
values={{ github: <a href='https://github.com/tootsuite/mastodon' rel='noopener' target='_blank'>tootsuite/mastodon</a> }}
/>
</p>
</div>
</div>
</Column>
);
}
}
|
src/index.js | BurntCaramel/react-pending | import React from 'react';
function requiredPropTypesMustExist(props, { propTypes, displayName }) {
Object.keys(propTypes).every(propName => propTypes[propName](props, propName, displayName) == null);
}
export default function pending(NotReadyComponent) {
return (hasLoaded = requiredPropTypesMustExist) => (ReadyComponent, ErrorComponent) => (props) => {
if (props.error) {
return <ErrorComponent { ...props } />;
}
else if (hasLoaded(props, ReadyComponent)) {
return <ReadyComponent { ...props } />;
}
else {
return <NotReadyComponent />;
}
}
}
|
src/routes.js | mozilla/advocacy.mozilla.org | /* eslint-disable no-unused-vars */
import React from 'react';
/* eslint-disable no-unused-vars */
import { Route, IndexRedirect, Redirect, IndexRoute } from 'react-router';
var locales = Object.keys(require('../public/locales.json'));
function redirect(locale) {
return function(state, replace) {
var pageType;
switch(state.location.pathname.slice(-1)){
case '2':
pageType = 'direct';
break;
case '3':
pageType = 'hybrid';
break;
default:
pageType = 'social';
}
if (state.location.query.video) {
replace("/" + locale + `/encrypt/${pageType}/${state.location.query.video}`);
} else {
replace({
pathname: "/" + locale + `/encrypt/${pageType}/1`,
query: state.location.query
});
}
}
}
function indexDirect(locale) {
return function(state, replace) {
if(state.location.query.video){
replace("/" + locale + `/encrypt/social/${state.location.query.video}`);
} else {
replace({
pathname: "/" + locale + `/encrypt/codemoji/1`,
query: state.location.query
});
}
}
}
function buildRoutes() {
var routes = [];
locales.forEach(function(locale) {
routes.push(
<Route key={locale} path={locale}>
<IndexRoute component={require(`./pages/home.js`)}/>
<Route path="open-web-fellows">
<IndexRedirect to="overview"/>
<Route path="overview" component={require('./pages/open-web-fellows/overview.js')}/>
<Route path="fellows2017" component={require(`./pages/open-web-fellows/fellows2017.js`)}/>
<Route path="fellows2016" component={require(`./pages/open-web-fellows/fellows2016.js`)}/>
<Route path="fellows2015" component={require(`./pages/open-web-fellows/fellows2015.js`)}/>
<Route path="info" component={require(`./pages/open-web-fellows/info.js`)}/>
<Redirect from="*" to={"/" + locale + "/open-web-fellows/fellows2016"} />
</Route>
<Route path="stay-secure">
<IndexRoute component={require(`./pages/stay-secure.js`)}/>
<Route path="thank-you" component={require(`./pages/stay-secure-thank-you.js`)}/>
<Redirect from="*" to={"/" + locale + "/stay-secure/"} />
</Route>
<Route path="encrypt-hard-drive">
<IndexRoute component={require(`./pages/encrypt-hard-drive/encrypt-hard-drive.js`)}/>
<Route path="thank-you" component={require(`./pages/encrypt-hard-drive/encrypt-hard-drive-thank-you.js`)}/>
<Redirect from="*" to={"/" + locale + "/encrypt-hard-drive/"} />
</Route>
<Route path="maker-party/activities">
<Route path="post-crimes" component={require(`./pages/maker-party/activities/post-crimes.js`)}/>
<Route path="meme-around" component={require(`./pages/maker-party/activities/meme-around.js`)}/>
<Route path="contribute-to-the-commons" component={require(`./pages/maker-party/activities/contribute-to-the-commons.js`)}/>
<Route path="combined-maker-party-activities" component={require(`./pages/maker-party/activities/combined-maker-party-activities.js`)}/>
</Route>
<Route path="net-neutrality">
<IndexRoute component={require(`./pages/net-neutrality/call-page.js`)}/>
<Route path='call-now' component={require(`./pages/net-neutrality/call-now.js`)}/>
<Route path='share' component={require(`./pages/net-neutrality/share.js`)}/>
<Route path='petition' component={require(`./pages/net-neutrality/petition.js`)}/>
<Redirect from="*" to={"/" + locale + "/net-neutrality/"} />
</Route>
<Redirect from="net-neutrality-comments" to={"/" + locale + "/net-neutrality/"} />
<Redirect from="net-neutrality-comments-simple" to={"/" + locale + "/net-neutrality/"} />
<Route path="safety">
<IndexRoute component={require(`./pages/safety/safety.js`)}/>
<Route path=":video" component={require(`./pages/safety/safety.js`)}/>
<Redirect from="*" to={"/" + locale + "/safety/"} />
</Route>
<Route path="encrypt">
<IndexRoute onEnter={indexDirect(locale)} />
<Route path="signup" component={require(`./pages/encrypt/signup.js`)}/>
<Route path="signupa" component={require(`./pages/encrypt/signup-a.js`)}/>
<Route path="signupb" component={require(`./pages/encrypt/signup-b.js`)}/>
<Route path="signupc" component={require(`./pages/encrypt/signup-c.js`)}/>
<Route path="blanka" component={require(`./pages/encrypt/signup-blank.js`)}/>
<Route path="signup-complete" component={require(`./pages/encrypt/signup-complete.js`)}/>
<Route path="hybrida" component={require(`./pages/encrypt/hybrid-2-a.js`)}/>
<Route path="hybridb" component={require(`./pages/encrypt/hybrid-2-b.js`)}/>
<Route path="hybridc" component={require(`./pages/encrypt/hybrid-2-c.js`)}/>
<Route path=":type/:video" component={require('./pages/encrypt/pageType.js')}/>
<Redirect from="direct" to={"/" + locale + "/encrypt/direct/1"} />
<Redirect from="social" to={"/" + locale + "/encrypt/social/1"} />
<Redirect from="hybrid" to={"/" + locale + "/encrypt/hybrid/1"} />
<Redirect from="codemoji" to={"/" + locale + "/encrypt/codemoji/2"} />
<Redirect from="codemoji-b" to={"/" + locale + "/encrypt/codemoji-b/2"} />
<Route path="2" onEnter={redirect(locale)} />
<Route path="3" onEnter={redirect(locale)} />
<Redirect from="*" to={"/" + locale + "/encrypt/"} />
</Route>
</Route>
);
});
if (routes.length === 0) {
console.error("No locale routes were constructed!");
}
["en-US", "es"].forEach(function(locale) {
routes.push(
<Route key={locale + "-privacynotincluded"} path={locale}>
<Route path="privacynotincluded">
<IndexRoute galleryPosition="bottom" component={require(`./pages/buyers-guide/home.js`)}/>
<Route path="why-we-made" component={require(`./pages/buyers-guide/why-we-made.js`)}/>
<Route path="categories" galleryPosition="middle" component={require(`./pages/buyers-guide/home.js`)}/>
<Route path="category">
<Route path=":category" component={require(`./pages/buyers-guide/category.js`)}/>
<Route path=":category/:item" component={require(`./pages/buyers-guide/item.js`)}/>
</Route>
<Redirect from="*" to={"/" + locale + "/privacynotincluded/"} />
</Route>
</Route>
);
});
return routes;
}
// just need to handle / redirect now
module.exports = <Route path="/">{ buildRoutes() }</Route>;
|
hw7-frontend/src/components/main/main.js | MinZhou2016/comp531 | import React, { Component } from 'react';
import HeadLine from './headline';
import Followers from './following';
import ArticlesView from '../article/articlesView';
const Main = () =>{
return (
<div className="main container-fluid">
<div className="row">
<div className="col-lg-3 col-md-4">
<HeadLine />
<Followers />
</div>
<div className="col-lg-8 col-md-8">
<ArticlesView />
</div>
</div>
</div>
)
}
export default Main;
|
actor-apps/app-web/src/app/components/modals/InviteUser.react.js | changjiashuai/actor-platform | import _ from 'lodash';
import React from 'react';
import Modal from 'react-modal';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import { Styles, FlatButton } from 'material-ui';
import ActorTheme from 'constants/ActorTheme';
import ActorClient from 'utils/ActorClient';
import { KeyCodes } from 'constants/ActorAppConstants';
import InviteUserActions from 'actions/InviteUserActions';
import InviteUserByLinkActions from 'actions/InviteUserByLinkActions';
import ContactStore from 'stores/ContactStore';
import InviteUserStore from 'stores/InviteUserStore';
import ContactItem from './invite-user/ContactItem.react';
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return ({
contacts: ContactStore.getContacts(),
group: InviteUserStore.getGroup(),
isOpen: InviteUserStore.isModalOpen()
});
};
const hasMember = (group, userId) =>
undefined !== _.find(group.members, (c) => c.peerInfo.peer.id === userId);
@ReactMixin.decorate(IntlMixin)
class InviteUser extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
this.state = _.assign({
search: ''
}, getStateFromStores());
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
button: {
minWidth: 60
}
});
InviteUserStore.addChangeListener(this.onChange);
ContactStore.addChangeListener(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
}
componentWillUnmount() {
InviteUserStore.removeChangeListener(this.onChange);
ContactStore.removeChangeListener(this.onChange);
document.removeEventListener('keydown', this.onKeyDown, false);
}
onChange = () => {
this.setState(getStateFromStores());
};
onClose = () => {
InviteUserActions.hide();
};
onContactSelect = (contact) => {
ActorClient.inviteMember(this.state.group.id, contact.uid);
};
onInviteUrlByClick = () => {
InviteUserByLinkActions.show(this.state.group);
InviteUserActions.hide();
};
onKeyDown = (event) => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
};
onSearchChange = (event) => {
this.setState({search: event.target.value});
};
render() {
const contacts = this.state.contacts;
const isOpen = this.state.isOpen;
let contactList = [];
if (isOpen) {
_.forEach(contacts, (contact, i) => {
const name = contact.name.toLowerCase();
if (name.includes(this.state.search.toLowerCase())) {
if (!hasMember(this.state.group, contact.uid)) {
contactList.push(
<ContactItem contact={contact} key={i} onSelect={this.onContactSelect}/>
);
} else {
contactList.push(
<ContactItem contact={contact} key={i} member/>
);
}
}
}, this);
}
if (contactList.length === 0) {
contactList.push(
<li className="contacts__list__item contacts__list__item--empty text-center">
<FormattedMessage message={this.getIntlMessage('inviteModalNotFound')}/>
</li>
);
}
return (
<Modal className="modal-new modal-new--invite contacts"
closeTimeoutMS={150}
isOpen={isOpen}
style={{width: 400}}>
<header className="modal-new__header">
<a className="modal-new__header__icon material-icons">person_add</a>
<h4 className="modal-new__header__title">
<FormattedMessage message={this.getIntlMessage('inviteModalTitle')}/>
</h4>
<div className="pull-right">
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Done"
labelStyle={{padding: '0 8px'}}
onClick={this.onClose}
secondary={true}
style={{marginTop: -6}}/>
</div>
</header>
<div className="modal-new__body">
<div className="modal-new__search">
<i className="material-icons">search</i>
<input className="input input--search"
onChange={this.onSearchChange}
placeholder={this.getIntlMessage('inviteModalSearch')}
type="search"
value={this.state.search}/>
</div>
<a className="link link--blue" onClick={this.onInviteUrlByClick}>
<i className="material-icons">link</i>
{this.getIntlMessage('inviteByLink')}
</a>
</div>
<div className="contacts__body">
<ul className="contacts__list">
{contactList}
</ul>
</div>
</Modal>
);
}
}
export default InviteUser;
|
src/components/Editor/EditorToolbar.js | ryanbaer/busy | import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl, FormattedMessage } from 'react-intl';
import { Button, Tooltip, Menu, Dropdown, Icon } from 'antd';
import './EditorToolbar.less';
const tooltip = (description, shortcut) =>
(<span>
{description}
<br />
<b>
{shortcut}
</b>
</span>);
const EditorToolbar = ({ intl, onSelect }) => {
const menu = (
<Menu onClick={e => onSelect(e.key)}>
<Menu.Item key="h1">
<h1><FormattedMessage id="heading_1" defaultMessage="Heading 1" /></h1>
</Menu.Item>
<Menu.Item key="h2">
<h2><FormattedMessage id="heading_2" defaultMessage="Heading 2" /></h2>
</Menu.Item>
<Menu.Item key="h3">
<h3><FormattedMessage id="heading_3" defaultMessage="Heading 3" /></h3>
</Menu.Item>
<Menu.Item key="h4">
<h4><FormattedMessage id="heading_4" defaultMessage="Heading 4" /></h4>
</Menu.Item>
<Menu.Item key="h5">
<h5><FormattedMessage id="heading_5" defaultMessage="Heading 5" /></h5>
</Menu.Item>
<Menu.Item key="h6">
<h6><FormattedMessage id="heading_6" defaultMessage="Heading 6" /></h6>
</Menu.Item>
</Menu>
);
return (
<div className="EditorToolbar">
<Dropdown overlay={menu}>
<Button className="EditorToolbar__button">
<i className="iconfont icon-fontsize" /> <Icon type="down" />
</Button>
</Dropdown>
<Tooltip title={tooltip(intl.formatMessage({ id: 'bold', defaultMessage: 'Add bold' }), 'Ctrl+b')}>
<Button className="EditorToolbar__button" onClick={() => onSelect('b')}>
<i className="iconfont icon-bold" />
</Button>
</Tooltip>
<Tooltip title={tooltip(intl.formatMessage({ id: 'italic', defaultMessage: 'Add italic' }), 'Ctrl+i')}>
<Button className="EditorToolbar__button" onClick={() => onSelect('i')}>
<i className="iconfont icon-italic" />
</Button>
</Tooltip>
<Tooltip title={tooltip(intl.formatMessage({ id: 'quote', defaultMessage: 'Add quote' }), 'Ctrl+q')}>
<Button className="EditorToolbar__button" onClick={() => onSelect('q')}>
<i className="iconfont icon-q1" />
</Button>
</Tooltip>
<Tooltip title={tooltip(intl.formatMessage({ id: 'link', defaultMessage: 'Add link' }), 'Ctrl+k')}>
<Button className="EditorToolbar__button" onClick={() => onSelect('link')}>
<i className="iconfont icon-link" />
</Button>
</Tooltip>
<Tooltip title={tooltip(intl.formatMessage({ id: 'image', defaultMessage: 'Add image' }), 'Ctrl+m')}>
<Button className="EditorToolbar__button" onClick={() => onSelect('image')}>
<i className="iconfont icon-picture" />
</Button>
</Tooltip>
</div>
);
};
EditorToolbar.propTypes = {
intl: PropTypes.shape().isRequired,
onSelect: PropTypes.func,
};
EditorToolbar.defaultProps = {
onSelect: () => {},
};
export default injectIntl(EditorToolbar);
|
docs/src/app/components/pages/components/Subheader/Page.js | hai-cea/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import subheaderReadmeText from './README';
import listExampleChatCode from '!raw!../List/ExampleChat';
import ListExampleChat from '../List/ExampleChat';
import listExampleFoldersCode from '!raw!../List/ExampleFolders';
import ListExampleFolders from '../List/ExampleFolders';
import gridListExampleSimpleCode from '!raw!../GridList/ExampleSimple';
import GridListExampleSimple from '../GridList/ExampleSimple';
import subheaderCode from '!raw!material-ui/Subheader/Subheader';
const descriptions = {
simpleList: 'Subheader used in a simple [List](/#/components/list).',
inset: 'Inset Subheader used in a [List](/#/components/list).',
simpleGridList: 'Subheader used in a [GridList](/#/components/grid-list).',
};
const SubheaderPage = () => (
<div>
<Title render={(previousTitle) => `Subheader - ${previousTitle}`} />
<MarkdownElement text={subheaderReadmeText} />
<CodeExample
title="Simple Usage with List"
description={descriptions.simpleList}
code={listExampleChatCode}
>
<ListExampleChat />
</CodeExample>
<CodeExample
title="Inset Example"
description={descriptions.inset}
code={listExampleFoldersCode}
>
<ListExampleFolders />
</CodeExample>
<CodeExample
title="Simple Usage with GridList"
description={descriptions.simpleGridList}
code={gridListExampleSimpleCode}
>
<GridListExampleSimple />
</CodeExample>
<PropTypeDescription code={subheaderCode} />
</div>
);
export default SubheaderPage;
|
docs/pages/system/basics.js | lgollut/material-ui | import React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown';
const pageFilename = 'system/basics';
const requireDemo = require.context('docs/src/pages/system/basics', false, /\.(js|tsx)$/);
const requireRaw = require.context(
'!raw-loader!../../src/pages/system/basics',
false,
/\.(js|md|tsx)$/,
);
// Run styled-components ref logic
// https://github.com/styled-components/styled-components/pull/2998
requireDemo.keys().map(requireDemo);
export default function Page({ demos, docs }) {
return <MarkdownDocs demos={demos} docs={docs} requireDemo={requireDemo} />;
}
Page.getInitialProps = () => {
const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw });
return { demos, docs };
};
|
static/src/components/islands/IslandDoubleTree.js | Firazenics/finalreckoningbot | // @flow
// jscs:disable maximumLineLength
import React from 'react';
type Props = {
paused: boolean
};
export default ({paused}: Props): React.Element => (
<svg className={`island double-tree ${paused ? 'paused' : ''}`} xmlns="http://www.w3.org/2000/svg" width="259" height="221">
<g fill="none" fill-rule="evenodd">
<path fill="#FFE6A7" d="M1.5012 93.2279v57.903l118.413 68.367 136.734-78.942v-57.903L1.5012 93.2279z"/>
<path fill="#EDD194" d="M118.8135 88.3652v130.5l1.101.633 136.734-78.942v-57.903l-137.835 5.712z"/>
<path stroke="#5E4634" strokeWidth="3" d="M256.6494 82.6514v57.906l-136.734 78.942-118.416-68.367v-57.906" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#C7E082" d="M1.5012 93.2279v20.403l118.413 68.37 136.734-78.945v-20.403L1.5012 93.2279z"/>
<path fill="#B0CC64" d="M119.8134 88.3235v93.618l.102.06 136.734-78.945v-20.406l-136.836 5.673z"/>
<path stroke="#5E4634" strokeWidth="3" d="M256.6494 85.6514v17.406l-136.734 78.942-118.416-68.367v-20.406" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#B7D86F" d="M1.5012 93.2279l118.413 68.367 136.734-78.942-118.413-68.367-136.734 78.942z"/>
<path stroke="#5E4634" strokeWidth="3" d="M119.9151 161.5949L1.4991 93.2279l136.734-78.945 118.416 68.37-136.734 78.942zm0 0v57.906m40.3041-133.1865v3.249M64.0125 70.3532v3.249M51.0297 87.9395v3.249m129.3258-36.8352v3.249m-11.6466 37.7511v3.249" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#FFE6A7" d="M103.3476 88.2344v20.922c0 2.115 4.155 3.831 9.282 3.831s9.282-1.716 9.282-3.831v-20.922h-18.564z"/>
<path fill="#EDD194" d="M113.4228 88.2344v24.72c4.749-.168 8.49-1.794 8.49-3.798v-20.922h-8.49z"/>
<path stroke="#5E4634" strokeWidth="3" d="M103.3476 88.2344v20.922c0 2.115 4.155 3.831 9.282 3.831s9.282-1.716 9.282-3.831v-20.922h-18.564z" strokeLinecap="round" strokeLinejoin="round"/>
<g className="stretch">
<path fill="#C3F270" d="M117.0579 5.3135l28.392 77.583c1.35 3.69.078 7.899-3.216 10.044-4.755 3.093-13.617 6.492-29.604 6.492-15.984 0-24.846-3.399-29.604-6.492-3.291-2.145-4.566-6.354-3.216-10.044l28.392-77.583c1.509-4.125 7.347-4.125 8.856 0"/>
<path fill="#B7D86F" d="M145.4496 82.8977l-28.392-77.583c-1.509-4.128-7.344-4.128-8.856 0l-2.265 6.186 24.549 67.083c1.353 3.69.078 7.899-3.216 10.041-4.755 3.093-13.617 6.495-29.604 6.495-4.647 0-8.676-.294-12.195-.78 5.148 2.637 13.575 5.094 27.159 5.094 15.987 0 24.849-3.402 29.604-6.495 3.294-2.142 4.566-6.351 3.216-10.041"/>
<path stroke="#5E4634" strokeWidth="3" d="M117.0579 5.3135l28.392 77.583c1.35 3.69.078 7.899-3.216 10.044-4.755 3.093-13.617 6.492-29.604 6.492-15.984 0-24.846-3.399-29.604-6.492-3.291-2.145-4.566-6.354-3.216-10.044l28.392-77.583c1.509-4.125 7.347-4.125 8.856 0z" strokeLinecap="round" strokeLinejoin="round"/>
</g>
<path fill="#FFE6A7" d="M198.6108 72.7844v14.484c0 1.464 2.877 2.652 6.426 2.652 3.549 0 6.426-1.188 6.426-2.652v-14.484h-12.852z"/>
<path fill="#EDD194" d="M205.407 72.7841v17.121c3.372-.081 6.054-1.227 6.054-2.637v-14.484h-6.054z"/>
<path stroke="#5E4634" strokeWidth="3" d="M198.6108 72.7844v14.484c0 1.464 2.877 2.652 6.426 2.652 3.549 0 6.426-1.188 6.426-2.652v-14.484h-12.852z" strokeLinecap="round" strokeLinejoin="round"/>
<g className="stretch">
<path fill="#C3F270" d="M208.8558 33.2786l15.096 42.288c.408 1.146-.09 2.424-1.185 2.952-2.796 1.344-8.613 3.546-16.737 3.546-8.121 0-13.938-2.202-16.734-3.546-1.095-.528-1.596-1.806-1.188-2.952l15.096-42.288c.948-2.655 4.704-2.655 5.652 0"/>
<path fill="#B7D86F" d="M223.9518 75.5681l-15.096-42.288c-.948-2.658-4.704-2.658-5.652 0l-.603 1.689 12.351 34.599c.408 1.143-.09 2.424-1.185 2.949-2.796 1.344-8.613 3.546-16.737 3.546-3.339 0-6.261-.381-8.772-.912l-.15.417c-.408 1.143.093 2.424 1.188 2.949 2.796 1.344 8.613 3.546 16.734 3.546 8.124 0 13.941-2.202 16.737-3.546 1.095-.525 1.593-1.806 1.185-2.949"/>
<path stroke="#5E4634" strokeWidth="3" d="M208.8558 33.2786l15.096 42.288c.408 1.146-.09 2.424-1.185 2.952-2.796 1.344-8.613 3.546-16.737 3.546-8.121 0-13.938-2.202-16.734-3.546-1.095-.528-1.596-1.806-1.188-2.952l15.096-42.288c.948-2.655 4.704-2.655 5.652 0z" strokeLinecap="round" strokeLinejoin="round"/>
</g>
<path fill="#EBEBEB" d="M158.1633 53.3873h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338"/>
<path stroke="#5E4634" strokeWidth="3" d="M158.1633 53.3873h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338z" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#EBEBEB" d="M145.9809 122.915h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338"/>
<path stroke="#5E4634" strokeWidth="3" d="M145.9809 122.915h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338z" strokeLinecap="round" strokeLinejoin="round"/>
</g>
</svg>
);
|
actor-apps/app-web/src/app/components/activity/ActivityHeader.react.js | boyley/actor-platform | import React from 'react';
import ReactMixin from 'react-mixin';
import addons from 'react/addons';
const {addons: { PureRenderMixin }} = addons;
@ReactMixin.decorate(PureRenderMixin)
class ActivityHeader extends React.Component {
static propTypes = {
close: React.PropTypes.func,
title: React.PropTypes.string
};
constructor(props) {
super(props);
}
render() {
const title = this.props.title;
const close = this.props.close;
let headerTitle;
if (typeof title !== 'undefined') {
headerTitle = <span className="activity__header__title">{title}</span>;
}
return (
<header className="activity__header toolbar">
<a className="activity__header__close material-icons" onClick={close}>clear</a>
{headerTitle}
</header>
);
}
}
export default ActivityHeader;
|
tests/baselines/reference/reactDefaultPropsInferenceSuccess.js | nojvek/TypeScript | //// [reactDefaultPropsInferenceSuccess.tsx]
/// <reference path="/.lib/react16.d.ts" />
import React from 'react';
interface BaseProps {
when?: ((value: string) => boolean) | "a" | "b";
error?: boolean;
}
interface Props extends BaseProps {
}
class FieldFeedback<P extends Props = BaseProps> extends React.Component<P> {
static defaultProps = {
when: () => true
};
render() {
return <div>Hello</div>;
}
}
// OK
const Test1 = () => <FieldFeedback when={value => !!value} />;
// Error: Void not assignable to boolean
const Test2 = () => <FieldFeedback when={value => console.log(value)} />;
class FieldFeedbackBeta<P extends Props = BaseProps> extends React.Component<P> {
static defaultProps: BaseProps = {
when: () => true
};
render() {
return <div>Hello</div>;
}
}
// OK
const Test1a = () => <FieldFeedbackBeta when={value => !!value} error>Hah</FieldFeedbackBeta>;
// Error: Void not assignable to boolean
const Test2a = () => <FieldFeedbackBeta when={value => console.log(value)} error>Hah</FieldFeedbackBeta>;
interface MyPropsProps extends Props {
when: (value: string) => boolean;
}
class FieldFeedback2<P extends MyPropsProps = MyPropsProps> extends FieldFeedback<P> {
static defaultProps = {
when: () => true
};
render() {
this.props.when("now"); // OK, always defined
return <div>Hello</div>;
}
}
// OK
const Test3 = () => <FieldFeedback2 when={value => !!value} />;
// Error: Void not assignable to boolean
const Test4 = () => <FieldFeedback2 when={value => console.log(value)} />;
// OK
const Test5 = () => <FieldFeedback2 />;
//// [reactDefaultPropsInferenceSuccess.js]
"use strict";
/// <reference path="react16.d.ts" />
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
exports.__esModule = true;
var react_1 = __importDefault(require("react"));
var FieldFeedback = /** @class */ (function (_super) {
__extends(FieldFeedback, _super);
function FieldFeedback() {
return _super !== null && _super.apply(this, arguments) || this;
}
FieldFeedback.prototype.render = function () {
return react_1["default"].createElement("div", null, "Hello");
};
FieldFeedback.defaultProps = {
when: function () { return true; }
};
return FieldFeedback;
}(react_1["default"].Component));
// OK
var Test1 = function () { return react_1["default"].createElement(FieldFeedback, { when: function (value) { return !!value; } }); };
// Error: Void not assignable to boolean
var Test2 = function () { return react_1["default"].createElement(FieldFeedback, { when: function (value) { return console.log(value); } }); };
var FieldFeedbackBeta = /** @class */ (function (_super) {
__extends(FieldFeedbackBeta, _super);
function FieldFeedbackBeta() {
return _super !== null && _super.apply(this, arguments) || this;
}
FieldFeedbackBeta.prototype.render = function () {
return react_1["default"].createElement("div", null, "Hello");
};
FieldFeedbackBeta.defaultProps = {
when: function () { return true; }
};
return FieldFeedbackBeta;
}(react_1["default"].Component));
// OK
var Test1a = function () { return react_1["default"].createElement(FieldFeedbackBeta, { when: function (value) { return !!value; }, error: true }, "Hah"); };
// Error: Void not assignable to boolean
var Test2a = function () { return react_1["default"].createElement(FieldFeedbackBeta, { when: function (value) { return console.log(value); }, error: true }, "Hah"); };
var FieldFeedback2 = /** @class */ (function (_super) {
__extends(FieldFeedback2, _super);
function FieldFeedback2() {
return _super !== null && _super.apply(this, arguments) || this;
}
FieldFeedback2.prototype.render = function () {
this.props.when("now"); // OK, always defined
return react_1["default"].createElement("div", null, "Hello");
};
FieldFeedback2.defaultProps = {
when: function () { return true; }
};
return FieldFeedback2;
}(FieldFeedback));
// OK
var Test3 = function () { return react_1["default"].createElement(FieldFeedback2, { when: function (value) { return !!value; } }); };
// Error: Void not assignable to boolean
var Test4 = function () { return react_1["default"].createElement(FieldFeedback2, { when: function (value) { return console.log(value); } }); };
// OK
var Test5 = function () { return react_1["default"].createElement(FieldFeedback2, null); };
|
src/website/app/demos/Link/Link/examples/children.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import _Link from '../../../../../../library/Link';
const Link = (props: {}) => <_Link target="_blank" {...props} />;
export default {
id: 'children',
title: 'Children',
description: 'A Link will render any children.',
scope: { Link },
source: `
<Link href="http://example.com">
<img alt="gradient placeholder" src="/images/125x125.png" />
</Link>`
};
|
examples/react-es6/CheckboxWithLabel.js | dylanham/jest | import React from 'react';
class CheckboxWithLabel extends React.Component {
constructor(props) {
super(props);
this.state = {isChecked: false};
// since auto-binding is disabled for React's class model
// we can prebind methods here
// http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding
this.onChange = this.onChange.bind(this);
}
onChange() {
this.setState({isChecked: !this.state.isChecked});
}
render() {
return (
<label>
<input
type="checkbox"
checked={this.state.isChecked}
onChange={this.onChange}
/>
{this.state.isChecked ? this.props.labelOn : this.props.labelOff}
</label>
);
}
}
export default CheckboxWithLabel;
|
src/containers/Login/index.js | Dominic-Preap/react-admin | // MODULES
import React, { Component } from 'react';
import { compose, bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import { Container, Row, Col, CardGroup, Card, CardBlock, Button, Form, Alert } from 'reactstrap';
// COMPONENTS
import renderField from '../../components/Input/renderField';
// ACTIONS
//import * as actions from './actions';
import { validate, shouldAsyncValidate } from '../../utils';
class Login extends Component {
componentDidMount() {}
onSubmit(values) {
const { requestLogin, history } = this.props.actions;
requestLogin(values);
}
render() {
const { handleSubmit, message } = this.props;
return (
<div className="app flex-row align-items-center">
<Container>
<Row className="justify-content-center">
<Col md="6">
<Form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<CardGroup className="mb-0">
<Card className="p-4">
<CardBlock className="card-body">
<h1>Login</h1>
<p className="text-muted">Sign In to your account</p>
{message ? <Alert color="danger">{message}</Alert> : ''}
<Field type="text" label="Email" name="email" component={renderField} />
<Field type="password" label="Password" name="password" component={renderField} />
<Button color="primary" className="px-4" type="submit">
Login
</Button>
</CardBlock>
</Card>
</CardGroup>
</Form>
</Col>
</Row>
</Container>
</div>
);
}
}
const asyncValidate = (values) => validate(values, { email: 'email|required', password: 'required' });
//const mapDispatchToProps = (dispatch) => ({ actions: bindActionCreators(actions, dispatch) });
const mapStateToProps = ({ authUser }) => ({
initialValues: { email: '', password: '' },
message: authUser.message
});
export default compose(
connect(mapStateToProps),
reduxForm({ form: 'LoginForm', asyncValidate, shouldAsyncValidate })
)(Login);
|
src/Wrapper/index.js | christianalfoni/ducky-components | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import styles from './styles.css';
function Wrapper(props) {
return (
<div
className={classNames(styles.wrapper, {
[styles[props.size]]: props.size,
[props.className]: props.className
})}
onClick={props.onClick}
style={props.style}
>
{props.children}
</div>
);
}
Wrapper.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
onClick: PropTypes.func,
size: PropTypes.oneOf(['standard', 'side-bottom', 'side', 'narrow', 'slim',
'short', 'midget', 'squat', 'slender', 'large', 'large-no-top']),
style: PropTypes.object
};
export default Wrapper;
|
src/svg-icons/content/add-circle-outline.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentAddCircleOutline = (props) => (
<SvgIcon {...props}>
<path d="M13 7h-2v4H7v2h4v4h2v-4h4v-2h-4V7zm-1-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/>
</SvgIcon>
);
ContentAddCircleOutline = pure(ContentAddCircleOutline);
ContentAddCircleOutline.displayName = 'ContentAddCircleOutline';
ContentAddCircleOutline.muiName = 'SvgIcon';
export default ContentAddCircleOutline;
|
frontend/app/index.js | petr/gqlclans | import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import thunkMiddleware from 'redux-thunk'
import { ApolloProvider } from 'react-apollo'
import ApolloClient from 'apollo-client-preset'
import { createStore, applyMiddleware, compose } from 'redux'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import App from 'components/App'
import rootReducer from 'reducers'
import 'stylesheets/styles.scss'
const enhancer = compose(applyMiddleware(thunkMiddleware))
const store = createStore(rootReducer, {}, enhancer)
const client = new ApolloClient()
const app = (store) => (
<Provider store={store}>
<ApolloProvider client={client}>
<MuiThemeProvider>
<App />
</MuiThemeProvider>
</ApolloProvider>
</Provider>
)
ReactDOM.render(
app(store),
document.getElementById('app'),
)
|
docs/src/app/components/pages/components/Card/ExampleExpandable.js | frnk94/material-ui | import React from 'react';
import {Card, CardActions, CardHeader, CardText} from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
const CardExampleExpandable = () => (
<Card>
<CardHeader
title="Without Avatar"
subtitle="Subtitle"
actAsExpander={true}
showExpandableButton={true}
/>
<CardActions>
<FlatButton label="Action1" />
<FlatButton label="Action2" />
</CardActions>
<CardText expandable={true}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi.
Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque.
Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio.
</CardText>
</Card>
);
export default CardExampleExpandable;
|
src/components/LevelSelection.js | jtak93/phaser-practice | import React, { Component } from 'react';
import { Grid, Button, Container, Image, Divider } from 'semantic-ui-react'
const LevelSelection = (props) => {
return (
<div>
<Container fluid>
<Button onClick={props.onBackToMainMenu} icon='reply' />
</Container>
<Divider hidden />
<Grid columns={3}>
<Grid.Row>
<Grid.Column>
<Button onClick={props.onStart.bind(null, 1)}>Level 1</Button>
</Grid.Column>
<Grid.Column>
<Button>Level 2</Button>
</Grid.Column>
<Grid.Column>
<Button>Level 3</Button>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<Button>Level 4</Button>
</Grid.Column>
<Grid.Column>
<Button>Level 5</Button>
</Grid.Column>
<Grid.Column>
<Button>Level 6</Button>
</Grid.Column>
</Grid.Row>
</Grid>
</div>
)
}
export default LevelSelection;
|
src/containers/DevTools/DevTools.js | TracklistMe/client-react | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor toggleVisibilityKey="ctrl-H"
changePositionKey="ctrl-Q">
<LogMonitor />
</DockMonitor>
);
|
src/app/configure/routes.js | michael-wolfenden/webpack2-react-starter | import React from 'react'
import { Route } from 'react-router'
import Shell from 'components/Shell'
export default (
<Route path="/" component={Shell} />
)
|
src/examples/App.js | iporaitech/react-to-mdl | import React from 'react';
import {
Router,
Route,
IndexRoute,
browserHistory
} from 'react-router';
import AppLayout from './AppLayout';
import ButtonsPage from './pages/Buttons';
import CardsPage from './pages/Cards';
import ListsPage from './pages/Lists';
import LoadingPage from './pages/Loading';
import TextfieldsPage from './pages/Textfields';
const Index = (props) => {
return <h1>react-to-mdl Examples</h1>
}
const App = (props) => {
return (
<Router history={browserHistory}>
<Route path="/" component={AppLayout} >
<IndexRoute component={Index} />
<Route path="buttons" component={ButtonsPage} />
<Route path="cards" component={CardsPage} />
<Route path="lists" component={ListsPage} />
<Route path="loading" component={LoadingPage} />
<Route path="textfields" component={TextfieldsPage} />
</Route>
</Router>
)
}
export default App;
|
node_modules/native-base/Components/Widgets/Switch.js | tedsf/tiptap | /* @flow */
'use strict';
import React from 'react';
import {Switch} from 'react-native';
import NativeBaseComponent from '../Base/NativeBaseComponent';
import computeProps from '../../Utils/computeProps';
export default class SwitchNB extends NativeBaseComponent {
getInitialStyle() {
return {
switch: {
}
}
}
prepareRootProps() {
var defaultProps = {
style: this.getInitialStyle().switch
};
return computeProps(this.props, defaultProps);
}
render() {
return(
<Switch {...this.prepareRootProps()}/>
);
}
}
|
js/components/listSwipe/index.js | onderveli/EmlakAPP | import React, { Component } from 'react';
import { Container, Header, Title, Content, Button, Icon, Text, Left, Right, Body, List, ListItem } from 'native-base';
import styles from './styles';
const datas = [
{
route: 'BasicListSwipe',
text: 'Single SwipeRow',
},
{
route: 'MultiListSwipe',
text: 'Multiple List Swipe',
},
];
class ListSwipe extends Component {
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button transparent onPress={() => this.props.navigation.navigate('DrawerOpen')}>
<Icon name="menu" />
</Button>
</Left>
<Body>
<Title>List Swipe</Title>
</Body>
<Right />
</Header>
<Content scrollEnabled={false} contentContainerStyle={{ flex: 1 }}>
<List
dataArray={datas}
renderRow={data =>
<ListItem button onPress={() => this.props.navigation.navigate(data.route)}>
<Text>
{data.text}
</Text>
<Right>
<Icon name="arrow-forward" />
</Right>
</ListItem>}
/>
</Content>
</Container>
);
}
}
export default ListSwipe;
|
static-src/src/js/AlbumLabel.js | chrisbay/library.kdhx.org | import React from 'react';
import {addHeader} from './csrf';
class AlbumLabelSheet extends React.Component {
constructor(props) {
super(props);
this.state = {
albums: []
};
}
componentDidMount() {
let headers = addHeader();
fetch('/albums/labels-to-print/', {
headers: headers,
credentials: "include"
})
.then(response => response.json())
.then((json) => {
const albums = json.map(a => ({
'id': a['pk'],
'artist': a['fields']['artist'][0],
'title': a['fields']['title'],
'label': a['fields']['labels'].join(' / '),
'created': a['fields']['created'],
'fileUnder': a['fields']['artist'][1],
'colorLeft': a['fields']['genre'][1],
'colorRight': a['fields']['genre'][2],
'hidden': false
}));
this.setState({albums: albums});
});
}
addBlank(beforeId) {
const albums = [];
this.state.albums.forEach((a) => {
if (a.id == beforeId) {
albums.push({'id': 'blank-'+a.id, 'hidden': false})
}
albums.push(a);
});
this.setState({albums: albums});
}
removeLabel(id) {
let hideLabel = function() {
const albums = this.state.albums.map((a) => {
if (a.id == id) {
a.hidden = true;
return a;
}
return a;
});
this.setState({albums: albums});
};
if ((''+id).includes('blank')) {
(hideLabel.bind(this))(id);
} else {
let headers = addHeader();
fetch('/albums/toggle/print/'+id, {
headers: headers,
credentials: "include",
method: 'POST'
})
.then(response => response.json())
.then((json) => {
// TODO - add error handling
(hideLabel.bind(this))(id);
});
}
}
renderLabel(data) {
if (data.hidden) return '';
let dateCreated = new Date(data.created);
let dateStr = dateCreated.getFullYear() + '-' + dateCreated.getMonth() + '-' + dateCreated.getDate();
return (<AlbumLabel
id={data.id}
key={data.id}
artist={data.artist}
title={data.title}
label={data.label}
created={dateStr}
fileUnder={data.fileUnder}
colorLeft={data.colorLeft}
colorRight={data.colorRight}
removeHandler={this.removeLabel.bind(this)}
addHandler={this.addBlank.bind(this)} />);
}
render() {
return <div className="row">{this.state.albums.map(this.renderLabel.bind(this))}</div>;
}
}
class AlbumLabel extends React.Component {
constructor(props) {
super(props);
this.state = {
id: props.id,
artist: props.artist,
title: props.title,
label: props.label,
created: props.created,
fileUnder: props.fileUnder,
colorLeft: props.colorLeft,
colorRight: props.colorRight
};
}
remove() {
this.props.removeHandler(this.state.id);
}
addBlank() {
this.props.addHandler(this.state.id);
}
render() {
if ((''+this.state.id).includes('blank')) {
return (
<div className="col-4 label" id={this.state.id}>
<div className="label-text ui-widget-content">
<div className="label-controls">
<a className="no-print add-label-control" href="#" onClick={this.addBlank.bind(this)}>
<i className="fa fa-plus-circle" aria-hidden="true"></i>
</a>
<a className="no-print remove-label-control" href="#" onClick={this.remove.bind(this)}>
<i className='fa fa-times-circle' aria-hidden='true'></i>
</a>
</div>
</div>
</div>
);
}
return (
<div className="col-4 label" id={this.state.id}>
<div className="label-text ui-widget-content">
<div className="info-block">
<div>{this.props.created}</div>
<strong>{this.props.fileUnder}</strong>
</div>
<div className="color-block">
<div style={{backgroundColor: '#'+this.props.colorLeft}}></div>
<div style={{backgroundColor: '#'+this.props.colorRight}}></div>
</div>
<div className="label-row">
<strong>{this.props.artist}</strong>
</div>
<div className="label-row">
{this.props.title}
</div>
<div className="label-row">
{this.props.label}
</div>
<div className="label-controls">
<a className="no-print add-label-control" href="#" onClick={this.addBlank.bind(this)}>
<i className="fa fa-plus-circle" aria-hidden="true"></i>
</a>
<a className="no-print remove-label-control" href="#" onClick={this.remove.bind(this)}>
<i className='fa fa-times-circle' aria-hidden='true'></i>
</a>
</div>
</div>
</div>
)
}
}
module.exports.AlbumLabel = AlbumLabel;
module.exports.AlbumLabelSheet = AlbumLabelSheet; |
app/javascript/mastodon/components/status.js | palon7/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Avatar from './avatar';
import AvatarOverlay from './avatar_overlay';
import RelativeTimestamp from './relative_timestamp';
import DisplayName from './display_name';
import StatusContent from './status_content';
import StatusActionBar from './status_action_bar';
import { FormattedMessage } from 'react-intl';
import emojify from '../emoji';
import escapeTextContentForBrowser from 'escape-html';
import ImmutablePureComponent from 'react-immutable-pure-component';
import scheduleIdleTask from '../features/ui/util/schedule_idle_task';
import { MediaGallery, VideoPlayer } from '../features/ui/util/async-components';
// We use the component (and not the container) since we do not want
// to use the progress bar to show download progress
import Bundle from '../features/ui/components/bundle';
import getRectFromEntry from '../features/ui/util/get_rect_from_entry';
export default class Status extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map,
account: ImmutablePropTypes.map,
wrapped: PropTypes.bool,
onReply: PropTypes.func,
onFavourite: PropTypes.func,
onReblog: PropTypes.func,
onDelete: PropTypes.func,
onOpenMedia: PropTypes.func,
onOpenVideo: PropTypes.func,
onBlock: PropTypes.func,
me: PropTypes.number,
boostModal: PropTypes.bool,
autoPlayGif: PropTypes.bool,
muted: PropTypes.bool,
intersectionObserverWrapper: PropTypes.object,
index: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
listLength: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};
state = {
isExpanded: false,
isIntersecting: true, // assume intersecting until told otherwise
isHidden: false, // set to true in requestIdleCallback to trigger un-render
}
// Avoid checking props that are functions (and whose equality will always
// evaluate to false. See react-immutable-pure-component for usage.
updateOnProps = [
'status',
'account',
'wrapped',
'me',
'boostModal',
'autoPlayGif',
'muted',
'listLength',
]
updateOnStates = ['isExpanded']
shouldComponentUpdate (nextProps, nextState) {
if (!nextState.isIntersecting && nextState.isHidden) {
// It's only if we're not intersecting (i.e. offscreen) and isHidden is true
// that either "isIntersecting" or "isHidden" matter, and then they're
// the only things that matter (and updated ARIA attributes).
return this.state.isIntersecting || !this.state.isHidden || nextProps.listLength !== this.props.listLength;
} else if (nextState.isIntersecting && !this.state.isIntersecting) {
// If we're going from a non-intersecting state to an intersecting state,
// (i.e. offscreen to onscreen), then we definitely need to re-render
return true;
}
// Otherwise, diff based on "updateOnProps" and "updateOnStates"
return super.shouldComponentUpdate(nextProps, nextState);
}
componentDidMount () {
if (!this.props.intersectionObserverWrapper) {
// TODO: enable IntersectionObserver optimization for notification statuses.
// These are managed in notifications/index.js rather than status_list.js
return;
}
this.props.intersectionObserverWrapper.observe(
this.props.id,
this.node,
this.handleIntersection
);
this.componentMounted = true;
}
componentWillUnmount () {
if (this.props.intersectionObserverWrapper) {
this.props.intersectionObserverWrapper.unobserve(this.props.id, this.node);
}
this.componentMounted = false;
}
handleIntersection = (entry) => {
if (this.node && this.node.children.length !== 0) {
// save the height of the fully-rendered element
this.height = getRectFromEntry(entry).height;
}
this.setState((prevState) => {
if (prevState.isIntersecting && !entry.isIntersecting) {
scheduleIdleTask(this.hideIfNotIntersecting);
}
return {
isIntersecting: entry.isIntersecting,
isHidden: false,
};
});
}
hideIfNotIntersecting = () => {
if (!this.componentMounted) {
return;
}
// When the browser gets a chance, test if we're still not intersecting,
// and if so, set our isHidden to true to trigger an unrender. The point of
// this is to save DOM nodes and avoid using up too much memory.
// See: https://github.com/tootsuite/mastodon/issues/2900
this.setState((prevState) => ({ isHidden: !prevState.isIntersecting }));
}
handleRef = (node) => {
this.node = node;
}
handleClick = () => {
if (!this.context.router) {
return;
}
const { status } = this.props;
this.context.router.history.push(`/statuses/${status.getIn(['reblog', 'id'], status.get('id'))}`);
}
handleAccountClick = (e) => {
if (this.context.router && e.button === 0) {
const id = Number(e.currentTarget.getAttribute('data-id'));
e.preventDefault();
this.context.router.history.push(`/accounts/${id}`);
}
}
handleExpandedToggle = () => {
this.setState({ isExpanded: !this.state.isExpanded });
};
renderLoadingMediaGallery () {
return <div className='media_gallery' style={{ height: '110px' }} />;
}
renderLoadingVideoPlayer () {
return <div className='media-spoiler-video' style={{ height: '110px' }} />;
}
render () {
let media = null;
let statusAvatar;
// Exclude intersectionObserverWrapper from `other` variable
// because intersection is managed in here.
const { status, account, intersectionObserverWrapper, index, listLength, wrapped, ...other } = this.props;
const { isExpanded, isIntersecting, isHidden } = this.state;
if (status === null) {
return null;
}
if (!isIntersecting && isHidden) {
return (
<article ref={this.handleRef} data-id={status.get('id')} aria-posinset={index} aria-setsize={listLength} tabIndex='0' style={{ height: `${this.height}px`, opacity: 0, overflow: 'hidden' }}>
{status.getIn(['account', 'display_name']) || status.getIn(['account', 'username'])}
{status.get('content')}
</article>
);
}
if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') {
let displayName = status.getIn(['account', 'display_name']);
if (displayName.length === 0) {
displayName = status.getIn(['account', 'username']);
}
const displayNameHTML = { __html: emojify(escapeTextContentForBrowser(displayName)) };
return (
<article className='status__wrapper' ref={this.handleRef} data-id={status.get('id')} aria-posinset={index} aria-setsize={listLength} tabIndex='0'>
<div className='status__prepend'>
<div className='status__prepend-icon-wrapper'><i className='fa fa-fw fa-retweet status__prepend-icon' /></div>
<FormattedMessage id='status.reblogged_by' defaultMessage='{name} boosted' values={{ name: <a onClick={this.handleAccountClick} data-id={status.getIn(['account', 'id'])} href={status.getIn(['account', 'url'])} className='status__display-name muted'><strong dangerouslySetInnerHTML={displayNameHTML} /></a> }} />
</div>
<Status {...other} wrapped status={status.get('reblog')} account={status.get('account')} />
</article>
);
}
if (status.get('media_attachments').size > 0 && !this.props.muted) {
if (status.get('media_attachments').some(item => item.get('type') === 'unknown')) {
} else if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
media = (
<Bundle fetchComponent={VideoPlayer} loading={this.renderLoadingVideoPlayer} >
{Component => <Component media={status.getIn(['media_attachments', 0])} sensitive={status.get('sensitive')} onOpenVideo={this.props.onOpenVideo} />}
</Bundle>
);
} else {
media = (
<Bundle fetchComponent={MediaGallery} loading={this.renderLoadingMediaGallery} >
{Component => <Component media={status.get('media_attachments')} sensitive={status.get('sensitive')} height={110} onOpenMedia={this.props.onOpenMedia} autoPlayGif={this.props.autoPlayGif} />}
</Bundle>
);
}
}
if (account === undefined || account === null) {
statusAvatar = <Avatar src={status.getIn(['account', 'avatar'])} staticSrc={status.getIn(['account', 'avatar_static'])} size={48} />;
}else{
statusAvatar = <AvatarOverlay staticSrc={status.getIn(['account', 'avatar_static'])} overlaySrc={account.get('avatar_static')} />;
}
return (
<article aria-posinset={index} aria-setsize={listLength} className={`status ${this.props.muted ? 'muted' : ''} status-${status.get('visibility')}`} data-id={status.get('id')} tabIndex={wrapped ? null : '0'} ref={this.handleRef}>
<div className='status__info'>
<a href={status.get('url')} className='status__relative-time' target='_blank' rel='noopener'><RelativeTimestamp timestamp={status.get('created_at')} /></a>
<a onClick={this.handleAccountClick} target='_blank' data-id={status.getIn(['account', 'id'])} href={status.getIn(['account', 'url'])} className='status__display-name'>
<div className='status__avatar'>
{statusAvatar}
</div>
<DisplayName account={status.get('account')} />
</a>
</div>
<StatusContent status={status} onClick={this.handleClick} expanded={isExpanded} onExpandedToggle={this.handleExpandedToggle} />
{media}
<StatusActionBar {...this.props} />
</article>
);
}
}
|
src/docs/utils/RestWatchDoc.js | grommet/grommet-docs | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import DocsArticle from '../../components/DocsArticle';
export default class RestWatchDoc extends Component {
render () {
var inline = [
'var requestId = RestWatch.start(\'/rest/index/resources\', params,\n ' +
'this._onResponse);'
].join('\n');
var example = [
'var Component = React.createClass({',
' ...',
' _onUpdate: function (result) {',
' this.setState({result: result});',
' },',
' _getData: function () {',
' this._request = RestWatch.start(\'/rest/index/resources\',',
' this.state.options.params, this._onUpdate);',
' },',
' ...',
'});'
].join('\n');
var message = [
'{',
' id: <id string>,',
' url: <url string>,',
' params: <params object>',
'}'
].join('\n');
var response = [
'{',
' id: <id string>,',
' result: <result object>',
'}'
].join('\n');
return (
<DocsArticle title='RestWatch'>
<section>
<p>Attempts to use WebSocket to receive asynchronous updates
of changes in responses to REST calls.
If WebSocket is not available, it falls back to polling
REST requests to the server every 10 seconds.
For asynchronous WebSocket support, it relies on the server
side supporting web sockets and supporting the interaction
protocol used by RestWatch.</p>
<pre><code className='javascript'>{inline}</code></pre>
<p>WebSocket messages sent to the server are JSON and look like
this:</p>
<pre><code className='javascript'>{message}</code></pre>
<p>The server should respond with JSON messages that look like
this:</p>
<pre><code className='javascript'>{response}</code></pre>
<p>When messages are received from the server, the
<code>result</code> will be sent to the callback that was passed
to <code>start()</code>.</p>
<p>RestWatch is resilient to the server restarting. If the
connection is lost, RestWatch will poll every five seconds trying
to re-establish the connection. When the connection is restored,
all active watching is automatically resumed.</p>
</section>
<section>
<h2>Methods</h2>
<dl>
<dt><code>initialize</code></dt>
<dd>Initiate a connection to the server. This is optional as
the <code>start()</code> method will perform this if needed.</dd>
<dt><code>start (url, params, function (result) {})</code></dt>
<dd>Start watching the response to the REST request defined
by the specified url and parameters. When updates are received,
the handler function is called with the data returned from
the server.
This returns an opaque requestId object that must be used for
corresponding calls to <code>stop()</code>.</dd>
<dt><code>stop (requestId)</code></dt>
<dd>Stop watching the response to the REST request defined
by the specified url and parameters.</dd>
</dl>
</section>
<section>
<h2>Example</h2>
<pre><code className='javascript'>
{example}
</code></pre>
</section>
</DocsArticle>
);
}
};
|
src/components/dialogs/HelpDialog.js | ello/webapp | /* eslint-disable max-len */
import React from 'react'
import { DismissButton } from '../../components/buttons/Buttons'
import { SHORTCUT_KEYS } from '../../constants/application_types'
import { css, media } from '../../styles/jss'
import * as s from '../../styles/jso'
import { dialogStyle as baseDialogStyle } from './Dialog'
const dialogStyle = css({ maxWidth: 440 }, s.colorBlack, s.bgcWhite, media(s.minBreak2, { minWidth: 440 }))
const headingStyle = css(
s.mb30,
{ paddingLeft: 60, lineHeight: 1 },
s.fontSize18,
media(s.minBreak2, s.fontSize24),
)
const textWrapperStyle = css(s.relative, s.mb0, { paddingLeft: 60 })
const textStyle = css(
s.absolute,
{
left: 0,
width: 50,
height: 22,
lineHeight: '22px',
borderRadius: 11,
color: '#535353',
backgroundColor: '#e8e8e8',
},
s.fontSize12,
s.center,
)
const HelpDialog = () =>
(<div className={`${baseDialogStyle} ${dialogStyle}`}>
<h2 className={headingStyle}>Key Commands</h2>
<p className={textWrapperStyle}><span className={`${textStyle} ${s.monoRegularCSS}`}>{SHORTCUT_KEYS.EDITORIAL}</span> Navigate to editorial</p>
<p className={textWrapperStyle}><span className={`${textStyle} ${s.monoRegularCSS}`}>{SHORTCUT_KEYS.ARTIST_INVITES}</span> Navigate to artist invites</p>
<p className={textWrapperStyle}><span className={`${textStyle} ${s.monoRegularCSS}`}>{SHORTCUT_KEYS.DISCOVER}</span> Navigate to discover</p>
<p className={textWrapperStyle}><span className={`${textStyle} ${s.monoRegularCSS}`}>{SHORTCUT_KEYS.SEARCH}</span> Navigate to search</p>
<p className={textWrapperStyle}><span className={`${textStyle} ${s.monoRegularCSS}`}>{SHORTCUT_KEYS.FOLLOWING}</span> Navigate to following</p>
<p className={textWrapperStyle}><span className={`${textStyle} ${s.monoRegularCSS}`}>{SHORTCUT_KEYS.NOTIFICATIONS}</span> View notifications</p>
<p className={textWrapperStyle}><span className={`${textStyle} ${s.monoRegularCSS}`}>{SHORTCUT_KEYS.TOGGLE_LAYOUT}</span> Toggle grid mode for main content</p>
<p className={textWrapperStyle}><span className={`${textStyle} ${s.monoRegularCSS}`}>{SHORTCUT_KEYS.OMNIBAR}</span> Focus post editor</p>
<p className={textWrapperStyle}><span className={`${textStyle} ${s.monoRegularCSS}`}>ESC</span> Close modal or alerts</p>
<p className={textWrapperStyle}><span className={`${textStyle} ${s.monoRegularCSS}`}>{SHORTCUT_KEYS.FULLSCREEN}</span> Toggle fullscreen within a post editor</p>
<p className={textWrapperStyle}><span className={`${textStyle} ${s.monoRegularCSS}`}>{SHORTCUT_KEYS.DT_GRID_TOGGLE}</span> Toggle layout grid</p>
<p className={textWrapperStyle}><span className={`${textStyle} ${s.monoRegularCSS}`}>{SHORTCUT_KEYS.DT_GRID_CYCLE}</span> Toggle between horizontal and vertical grid</p>
<p className={textWrapperStyle}><span className={`${textStyle} ${s.monoRegularCSS}`}>{SHORTCUT_KEYS.HELP}</span> Show this help modal</p>
<DismissButton />
</div>)
export default HelpDialog
|
src/svg-icons/device/signal-wifi-3-bar-lock.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalWifi3BarLock = (props) => (
<SvgIcon {...props}>
<path opacity=".3" d="M12 3C5.3 3 .8 6.7.4 7l3.2 3.9L12 21.5l3.5-4.3v-2.6c0-2.2 1.4-4 3.3-4.7.3-.1.5-.2.8-.2.3-.1.6-.1.9-.1.4 0 .7 0 1 .1L23.6 7c-.4-.3-4.9-4-11.6-4z"/><path d="M23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16zm-10 5.5l3.5-4.3v-2.6c0-2.2 1.4-4 3.3-4.7C17.3 9 14.9 8 12 8c-4.8 0-8 2.6-8.5 2.9"/>
</SvgIcon>
);
DeviceSignalWifi3BarLock = pure(DeviceSignalWifi3BarLock);
DeviceSignalWifi3BarLock.displayName = 'DeviceSignalWifi3BarLock';
DeviceSignalWifi3BarLock.muiName = 'SvgIcon';
export default DeviceSignalWifi3BarLock;
|
frontend/blueprints/view/files/__root__/views/__name__View/__name__View.js | qurben/mopidy-jukebox | import React from 'react'
type Props = {
};
export class <%= pascalEntityName %> extends React.Component {
props: Props;
render () {
return (
<div></div>
)
}
}
export default <%= pascalEntityName %>
|
src/client/handlers/MessagesHandler.js | janicduplessis/imessage-client | import React from 'react';
import StyleSheet from 'react-style';
import {branch} from 'baobab-react/decorators';
import MessageList from '../components/MessageList';
import SendBox from '../components/SendBox';
import MessageActions from '../actions/MessageActions';
import UIActions from '../actions/UIActions';
@branch({
facets: {
messages: 'visibleMessages',
convo: 'currentConvo',
},
})
class MessagesHandler extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
let {convo} = this.props;
if(convo) {
UIActions.title(convo.name);
}
UIActions.backButton(true);
}
componentWillUnmount() {
UIActions.title(null);
UIActions.backButton(false);
}
render() {
return (
<div style={styles.container}>
<MessageList messages={this.props.messages} />
<SendBox style={styles.sendbox} onMessage={this._sendMessage.bind(this)} />
</div>
);
}
_sendMessage(message) {
let convo = this.props.convo;
MessageActions.send({
id: 'tmp_' + Math.random(),
author: 'me',
text: message,
convoName: convo.name,
convoId: convo.id,
fromMe: true,
});
}
}
const styles = StyleSheet.create({
container: {
display: 'flex',
flexDirection: 'column',
right: 0,
bottom: 0,
},
sendbox: {
position: 'absolute',
left: 12,
right: 12,
bottom: 0,
},
});
export default MessagesHandler;
|
dashboard/components/progress.js | vinnyhuang/fw-dev-dashboard | import React, { Component } from 'react';
import { ProgressBar } from 'react-bootstrap';
export default class Progress extends Component {
render() {
return (
<div className="progressBar">
<div className="title">
<strong>{ this.props.name }</strong>
</div>
<div className="container">
<div className="progressPercent">
{ this.props.data + "%"}
</div>
<div className="barContainer">
<ProgressBar active now={ this.props.data } />
</div>
</div>
<div className="handle">
<div className="handleIcon"/>
</div>
</div>
)
}
} |
src/js/index.js | nestalk/toggl-report-react | import React from 'react';
import { Provider, connect } from 'react-redux';
import { render } from 'react-dom';
import configureStore from './configureStore';
import indexReducer from './reducers/indexReducer';
import '../css/main.css';
import {getStorageData} from './actions';
import Report from './components/reportComponent';
import Filter from './components/filterComponent';
const store = configureStore(indexReducer);
store.dispatch(getStorageData());
render(
<Provider store={store}>
<section>
<h1>Toggl Report Using React.js</h1>
<Filter />
<Report />
</section>
</Provider>,
document.getElementById('app')
);
|
src/components/5-ScopedAnimations/ScopedAnimationsDemo.js | AgtLucas/css-modules-playground | import ScopedAnimations from './ScopedAnimations';
import React from 'react';
import js from '!!raw!./ScopedAnimations.js';
import css from '!!raw!./ScopedAnimations.css';
import animationsCss from '!!raw!shared/styles/animations.css';
import Snippet from 'shared/Snippet/Snippet';
export default class ScopedAnimationsDemo extends React.Component {
render() {
const files = [
{ name: 'ScopedAnimations.js', source: js },
{ name: 'ScopedAnimations.css', source: css },
{ name: 'shared/styles/animations.css', source: animationsCss }
];
return (
<Snippet files={files}>
<ScopedAnimations />
</Snippet>
);
}
};
|
packages/components/src/VirtualizedList/CellDatetime/CellDatetime.component.js | Talend/ui | import PropTypes from 'prop-types';
import React from 'react';
import classnames from 'classnames';
import isEqual from 'lodash/isEqual';
import pick from 'lodash/pick';
import distanceInWordsToNow from 'date-fns/distance_in_words_to_now';
import format from 'date-fns/format';
import isValid from 'date-fns/is_valid';
import parse from 'date-fns/parse';
import { withTranslation } from 'react-i18next';
import { date as dateUtils } from '@talend/utils';
import I18N_DOMAIN_COMPONENTS from '../../constants';
import getDefaultT from '../../translate';
import getLocale from '../../i18n/DateFnsLocale/locale';
import styles from './CellDatetime.scss';
import TooltipTrigger from '../../TooltipTrigger';
const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss';
export function computeValue(cellData, columnData, t) {
const isDateValid = isValid(parse(cellData));
if (isDateValid) {
if (cellData && columnData.mode === 'ago') {
return distanceInWordsToNow(cellData, {
addSuffix: true,
locale: getLocale(t),
});
} else if (columnData.mode === 'format') {
if (columnData.timeZone) {
return dateUtils.formatToTimeZone(cellData, columnData.pattern || DATE_TIME_FORMAT, {
timeZone: columnData.timeZone,
locale: getLocale(t),
});
}
return format(cellData, columnData.pattern || DATE_TIME_FORMAT, { locale: getLocale(t) });
}
}
return cellData;
}
export function getTooltipLabel(cellData, columnData, t) {
if (typeof columnData.getTooltipLabel === 'function') {
return columnData.getTooltipLabel(cellData);
}
if (columnData.mode === 'ago') {
let tooltipLabel = '';
if (columnData.timeZone) {
tooltipLabel = dateUtils.formatToTimeZone(cellData, columnData.pattern || DATE_TIME_FORMAT, {
timeZone: columnData.timeZone,
locale: getLocale(t),
});
} else {
tooltipLabel = format(cellData, columnData.pattern || DATE_TIME_FORMAT, { locale: getLocale(t) });
}
return tooltipLabel;
}
return columnData.tooltipLabel;
}
/**
* Cell renderer that displays text + icon
*/
export class CellDatetimeComponent extends React.Component {
shouldComponentUpdate(nextProps) {
const watch = Object.keys(CellDatetimeComponent.propTypes.columnData);
return (
this.props.cellData !== nextProps.cellData ||
!isEqual(pick(this.props.columnData, watch), pick(nextProps.columnData, watch))
);
}
render() {
const { cellData, columnData, t } = this.props;
const computedValue = computeValue(cellData, columnData, t);
const tooltipLabel = getTooltipLabel(cellData, columnData, t);
const cell = (
<div className={classnames('cell-datetime-container', styles['cell-datetime-container'])}>
{computedValue}
</div>
);
return (
<TooltipTrigger
label={tooltipLabel || computedValue}
tooltipPlacement={columnData.tooltipPlacement || 'top'}
>
{cell}
</TooltipTrigger>
);
}
}
CellDatetimeComponent.displayName = 'VirtualizedList(CellDatetime)';
CellDatetimeComponent.propTypes = {
// The cell value : props.rowData[props.dataKey]
cellData: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
// Column data
columnData: PropTypes.shape({
tooltipPlacement: PropTypes.string,
tooltipLabel: PropTypes.string,
mode: PropTypes.string.isRequired,
pattern: PropTypes.string,
getTooltipLabel: PropTypes.func,
}).isRequired,
t: PropTypes.func,
};
CellDatetimeComponent.defaultProps = {
t: getDefaultT(),
};
export default withTranslation(I18N_DOMAIN_COMPONENTS)(CellDatetimeComponent);
|
examples/data-fetch/pages/preact.js | arunoda/next.js |
import React from 'react'
import Link from 'next/link'
import 'isomorphic-fetch'
export default class MyPage extends React.Component {
static async getInitialProps () {
// eslint-disable-next-line no-undef
const res = await fetch('https://api.github.com/repos/developit/preact')
const json = await res.json()
return { stars: json.stargazers_count }
}
render () {
return (
<div>
<p>Preact has {this.props.stars} ⭐️</p>
<Link prefetch href='/'><a>I bet next has more stars (?)</a></Link>
</div>
)
}
}
|
node_modules/react-bootstrap/es/PageHeader.js | premcool/getmydeal | 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 PageHeader = function (_React$Component) {
_inherits(PageHeader, _React$Component);
function PageHeader() {
_classCallCheck(this, PageHeader);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
PageHeader.prototype.render = function render() {
var _props = this.props,
className = _props.className,
children = _props.children,
props = _objectWithoutProperties(_props, ['className', 'children']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement(
'div',
_extends({}, elementProps, {
className: classNames(className, classes)
}),
React.createElement(
'h1',
null,
children
)
);
};
return PageHeader;
}(React.Component);
export default bsClass('page-header', PageHeader); |
src/components/RunButton.js | jenca-cloud/jenca-gui | import React from 'react'
export default function RunButton(props) {
function handleClick(e){
if(e) e.preventDefault()
props.handleRun(props.app)
}
return (
<div>
<button onClick={handleClick} className="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">
{props.title}
</button>
</div>
)
}
|
src/containers/Layout/index.js | LamouchiMS/adintel | import React from 'react';
import injectTapEventPlugin from 'react-tap-event-plugin';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import {fade} from 'material-ui/utils/colorManipulator';
import {
cyan700,
grey600,
yellowA100,
yellowA200,
yellowA400,
white,
fullWhite
} from 'material-ui/styles/colors';
import styles from './Layout.css';
injectTapEventPlugin();
const muiTheme = getMuiTheme({
palette: {
primary1Color: '#303030',
primary2Color: cyan700,
primary3Color: grey600,
accent1Color: yellowA200,
accent2Color: yellowA400,
accent3Color: yellowA100,
textColor: fullWhite,
secondaryTextColor: fade(fullWhite, 0.7),
alternateTextColor: white,
canvasColor: '#303030',
borderColor: fade(fullWhite, 0.3),
disabledColor: fade(fullWhite, 0.3),
pickerHeaderColor: fade(fullWhite, 0.12),
clockCircleColor: fade(fullWhite, 0.12)
}
});
import Header from '../../components/Header';
import Footer from '../../components/Footer';
import AppContainer from '../../containers/AppContainer';
const Layout = (props) => (
<MuiThemeProvider muiTheme={muiTheme}>
<div className={styles.app}>
<Header/>
<div className={styles.appContent}>
{props.children}
</div>
<Footer/>
</div>
</MuiThemeProvider>
);
export default Layout;
|
src/Col.js | roderickwang/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import styleMaps from './styleMaps';
import CustomPropTypes from './utils/CustomPropTypes';
const Col = React.createClass({
propTypes: {
/**
* The number of columns you wish to span
*
* for Extra small devices Phones (<768px)
*
* class-prefix `col-xs-`
*/
xs: React.PropTypes.number,
/**
* The number of columns you wish to span
*
* for Small devices Tablets (≥768px)
*
* class-prefix `col-sm-`
*/
sm: React.PropTypes.number,
/**
* The number of columns you wish to span
*
* for Medium devices Desktops (≥992px)
*
* class-prefix `col-md-`
*/
md: React.PropTypes.number,
/**
* The number of columns you wish to span
*
* for Large devices Desktops (≥1200px)
*
* class-prefix `col-lg-`
*/
lg: React.PropTypes.number,
/**
* Move columns to the right
*
* for Extra small devices Phones
*
* class-prefix `col-xs-offset-`
*/
xsOffset: React.PropTypes.number,
/**
* Move columns to the right
*
* for Small devices Tablets
*
* class-prefix `col-sm-offset-`
*/
smOffset: React.PropTypes.number,
/**
* Move columns to the right
*
* for Medium devices Desktops
*
* class-prefix `col-md-offset-`
*/
mdOffset: React.PropTypes.number,
/**
* Move columns to the right
*
* for Large devices Desktops
*
* class-prefix `col-lg-offset-`
*/
lgOffset: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Extra small devices Phones
*
* class-prefix `col-xs-push-`
*/
xsPush: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Small devices Tablets
*
* class-prefix `col-sm-push-`
*/
smPush: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Medium devices Desktops
*
* class-prefix `col-md-push-`
*/
mdPush: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Large devices Desktops
*
* class-prefix `col-lg-push-`
*/
lgPush: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Extra small devices Phones
*
* class-prefix `col-xs-pull-`
*/
xsPull: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Small devices Tablets
*
* class-prefix `col-sm-pull-`
*/
smPull: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Medium devices Desktops
*
* class-prefix `col-md-pull-`
*/
mdPull: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Large devices Desktops
*
* class-prefix `col-lg-pull-`
*/
lgPull: React.PropTypes.number,
/**
* You can use a custom element for this component
*/
componentClass: CustomPropTypes.elementType
},
getDefaultProps() {
return {
componentClass: 'div'
};
},
render() {
let ComponentClass = this.props.componentClass;
let classes = {};
Object.keys(styleMaps.SIZES).forEach(function (key) {
let size = styleMaps.SIZES[key];
let prop = size;
let classPart = size + '-';
if (this.props[prop]) {
classes['col-' + classPart + this.props[prop]] = true;
}
prop = size + 'Offset';
classPart = size + '-offset-';
if (this.props[prop] >= 0) {
classes['col-' + classPart + this.props[prop]] = true;
}
prop = size + 'Push';
classPart = size + '-push-';
if (this.props[prop] >= 0) {
classes['col-' + classPart + this.props[prop]] = true;
}
prop = size + 'Pull';
classPart = size + '-pull-';
if (this.props[prop] >= 0) {
classes['col-' + classPart + this.props[prop]] = true;
}
}, this);
return (
<ComponentClass {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</ComponentClass>
);
}
});
export default Col;
|
src/templates/feeds/components/Comments.js | PatrickHai/react-client-changers | import React from 'react';
class Comments extends React.Component{
render(){
let saying = this.props.saying;
return (
<div className="comments">
<div className="com_title">
<span className="likes">赞 {saying.likes}</span>
<span className="coms">评论 {saying.coms}</span>
<div className="line_title"></div>
</div>
{
saying.comments.map((comment) => {
return <div className="comment" key={Math.random()}>
<div className="layout_box box-center-v">
<div className="img_wrap_com">
<img src={comment.profile_photo} /></div>
<div className="box_col_com">
<p>
<span>{comment.name}</span>
{
comment.icons.map((icon) => {
return <img src={icon} className="icon_R_com" key={Math.random()}/>
})
}
</p>
<span className="S_txt1 txt_xs">
{comment.time} {comment.location}
</span>
</div>
</div>
<div className="S_txt1 comment_text">{comment.text}</div>
<div className="line"></div>
</div>
})
}
</div>
)
}
}
export default Comments; |
src/js/components/Heading/stories/CustomThemed/Extend.js | grommet/grommet | import React from 'react';
import { Grommet, Heading } from 'grommet';
import { deepMerge } from 'grommet/utils';
import { grommet } from 'grommet/themes';
const letterSpace = {
1: {
small: '-1px',
medium: '-1.22px',
large: '-1.45px',
},
2: {
small: '-0.47px',
medium: '-0.57px',
large: '-0.7px',
},
3: {
small: '-0.42px',
medium: '-0.47px',
large: '-0.47px',
},
};
const letterSpacing = ({ level, size }) =>
level && size ? `letter-spacing: ${letterSpace[level][size]}` : '';
const customTheme = deepMerge(grommet, {
heading: { extend: (props) => `${letterSpacing(props)}` },
});
export const Extend = () => (
<Grommet theme={customTheme}>
<Heading level="1" size="large">
This is using the extend property on Heading
</Heading>
<Heading level="2" size="medium">
This is using the extend property on Heading
</Heading>
<Heading level="3" size="small">
This is using the extend property on Heading
</Heading>
</Grommet>
);
export default {
title: 'Type/Heading/Custom Themed/Extend',
};
|
client/react/frontpage/components/EventList.js | uclaradio/uclaradio | // EventList.js
// list of events in events tab of frontpage
import React from 'react';
import { connect } from 'react-redux';
import { updateEvents, fetchUpdatedEvents } from '../actions/events';
import { Link } from 'react-router';
// Common Elements
import RectImage from '../../common/RectImage';
import Loader from './Loader';
// styling
require('./EventList.scss');
const defaultColor = 'grey';
const colors = {
'Ticket Giveaway': '#3c84cc', // blue
'UCLA Radio Presents': '#098440', // green
'Campus Event': '#842b78', // magenta
'Local Event': '#cca437', // orange
};
const defaultEventPic = '/img/radio.png';
/**
Content of events page
@prop eventGroups: list of groups of event objects, each with a title (months)
@prop fetching: currently fetching objects
@prop updateEvents: callback action to fetch updated events from server
* */
const EventList = React.createClass({
componentWillMount() {
this.props.updateEvents();
},
render() {
// describe colors with events legend
const legend = Object.keys(colors).map(eventType => (
<div className="colorKeyLabel" key={eventType}>
<span>{eventType}</span>
<div
className="dot"
style={{ backgroundColor: getBackgroundColor(eventType) }}
/>
</div>
));
return (
<div className="eventsTab">
{this.props.fetching && this.props.eventGroups.length == 0 ? (
<Loader />
) : (
<div>
<div className="colorKey">{legend}</div>
{this.props.eventGroups.map(month => (
<div className="monthEvents" key={month.title}>
<h1>{month.title}</h1>
<div className="allEvents">
{month.events.map(event => {
const start = formatDate(event.start);
const eventColor = getBackgroundColor(event.type);
return (
<div className="event" key={event.id}>
<Link to={`/events/${event.id}`}>
<RectImage src={event.image || defaultEventPic} />
<div className="overlayWrapper">
<div
className="overlay"
style={{ backgroundColor: eventColor }}
>
<p className="eventDate">{start}</p>
<div className="eventOverlay">
<p className="bandName">{event.host}</p>
<p className="separator">
. . . . .
. . . .
</p>
<p className="venue">{event.location}</p>
</div>
</div>
<div className="hoverOverlay">
<p className="enterLabel">
click for more details
</p>
</div>
</div>
</Link>
</div>
);
})}
</div>
</div>
))}
</div>
)}
</div>
);
},
});
var getBackgroundColor = function(type) {
return colors[type] || defaultColor;
};
// Useful if we revert to google calendar
// var getBandName = function(desc){
// return desc.substring(0, desc.indexOf("@") - 1);
// };
// var getVenue = function(desc){
// return desc.substring(desc.indexOf("@") + 2);
// };
var formatDate = function(dateString) {
const date = new Date(dateString);
return date.getDate();
};
const eventGroupsFromState = state => {
if (!state.events || !state.groups) {
return [];
}
// convert groups' event ids to event objects
const eventGroups = [];
for (let groupIndex = 0; groupIndex < state.groups.length; groupIndex++) {
const stateGroup = state.groups[groupIndex];
const newGroup = {
title: stateGroup.title,
events: [],
};
for (
let eventIndex = 0;
eventIndex < stateGroup.eventIDs.length;
eventIndex++
) {
const event = state.events[stateGroup.eventIDs[eventIndex]];
if (event) {
newGroup.events.push(event);
}
}
eventGroups.push(newGroup);
}
return eventGroups;
};
const mapStateToProps = state => ({
eventGroups: eventGroupsFromState(state.events),
fetching: state.events.fetching,
});
const mapDispatchToProps = dispatch => ({
updateEvents: () => {
fetchUpdatedEvents(dispatch);
},
});
export default connect(mapStateToProps, mapDispatchToProps)(EventList);
|
src/svg-icons/editor/border-left.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorBorderLeft = (props) => (
<SvgIcon {...props}>
<path d="M11 21h2v-2h-2v2zm0-4h2v-2h-2v2zm0-12h2V3h-2v2zm0 4h2V7h-2v2zm0 4h2v-2h-2v2zm-4 8h2v-2H7v2zM7 5h2V3H7v2zm0 8h2v-2H7v2zm-4 8h2V3H3v18zM19 9h2V7h-2v2zm-4 12h2v-2h-2v2zm4-4h2v-2h-2v2zm0-14v2h2V3h-2zm0 10h2v-2h-2v2zm0 8h2v-2h-2v2zm-4-8h2v-2h-2v2zm0-8h2V3h-2v2z"/>
</SvgIcon>
);
EditorBorderLeft = pure(EditorBorderLeft);
EditorBorderLeft.displayName = 'EditorBorderLeft';
EditorBorderLeft.muiName = 'SvgIcon';
export default EditorBorderLeft;
|
node_modules/react-router/modules/RouteUtils.js | FrancoCotter/ReactWeatherApp | import React from 'react'
import warning from './routerWarning'
function isValidChild(object) {
return object == null || React.isValidElement(object)
}
export function isReactChildren(object) {
return isValidChild(object) || (Array.isArray(object) && object.every(isValidChild))
}
function checkPropTypes(componentName, propTypes, props) {
componentName = componentName || 'UnknownComponent'
for (const propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
const error = propTypes[propName](props, propName, componentName)
/* istanbul ignore if: error logging */
if (error instanceof Error)
warning(false, error.message)
}
}
}
function createRoute(defaultProps, props) {
return { ...defaultProps, ...props }
}
export function createRouteFromReactElement(element) {
const type = element.type
const route = createRoute(type.defaultProps, element.props)
if (type.propTypes)
checkPropTypes(type.displayName || type.name, type.propTypes, route)
if (route.children) {
const 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) {
const routes = []
React.Children.forEach(children, function (element) {
if (React.isValidElement(element)) {
// Component classes may have a static create* method.
if (element.type.createRouteFromReactElement) {
const 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
}
|
local-cli/templates/HelloNavigation/views/welcome/WelcomeText.android.js | jevakallio/react-native | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
} from 'react-native';
export default class WelcomeText extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
This app shows the basics of navigating between a few screens,
working with ListView and handling text input.
</Text>
<Text style={styles.instructions}>
Modify any files to get started. For example try changing the
file views/welcome/WelcomeText.android.js.
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu.
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
padding: 20,
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 16,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 12,
},
});
|
examples/async-data/app.js | christianv/react-autocomplete | import React from 'react'
import Autocomplete from '../../lib/index'
import { getStates, matchStateToTerm, sortStates, styles, fakeRequest } from '../utils'
let App = React.createClass({
getInitialState () {
return {
unitedStates: getStates(),
loading: false
}
},
render () {
return (
<div>
<h1>Async Data</h1>
<p>
Autocomplete works great with async data by allowing you to pass in
items. The <code>onChange</code> event provides you the value to make
a server request with, then change state and pass in new items, it will
attempt to autocomplete the first one.
</p>
<Autocomplete
ref="autocomplete"
items={this.state.unitedStates}
getItemValue={(item) => item.name}
onSelect={(value, item) => {
// set the menu to only the selected item
this.setState({ unitedStates: [ item ] })
// or you could reset it to a default list again
// this.setState({ unitedStates: getStates() })
}}
onChange={(event, value) => {
this.setState({loading: true})
fakeRequest(value, (items) => {
this.setState({ unitedStates: items, loading: false })
})
}}
renderItem={(item, isHighlighted) => (
<div
style={isHighlighted ? styles.highlightedItem : styles.item}
key={item.abbr}
id={item.abbr}
>{item.name}</div>
)}
/>
</div>
)
}
})
React.render(<App/>, document.getElementById('container'))
|
src/index.js | christineoo/reddit-gallery | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import ToolboxApp from 'react-toolbox/lib/app';
import Root from './containers/Root';
import configureStore from './store/configureStore'
import 'babel-polyfill';
const store = configureStore()
ReactDOM.render(<Root store={store} />, document.getElementById('root'));
//ReactDOM.render((<ToolboxApp><App /></ToolboxApp>), document.getElementById('root'));
|
packages/storybook/examples/core/TextInput.stories.js | iCHEF/gypcrete | import React from 'react';
import { action } from '@storybook/addon-actions';
import TextInput, { PureTextInput } from '@ichef/gypcrete/src/TextInput';
import DebugBox from 'utils/DebugBox';
export default {
title: '@ichef/gypcrete|TextInput',
component: PureTextInput,
subcomponents: {
'rowComp()': TextInput,
},
};
export function BasicUsage() {
return (
<div>
<DebugBox>
<TextInput label="Label" onChange={action('change')} />
</DebugBox>
<DebugBox>
<TextInput
align="reverse"
label="Controlled input"
value="Input Value"
onChange={action('change')}
/>
</DebugBox>
<DebugBox>
<TextInput
label="Uncontrolled input"
defaultValue="Input Value"
onChange={action('change')}
/>
</DebugBox>
<DebugBox>
<TextInput
label="Error input"
defaultValue="Input Value"
status="error"
onChange={action('change')}
/>
</DebugBox>
<DebugBox>
<TextInput
readOnly
label="Read-only input"
value="Input Value"
/>
</DebugBox>
<DebugBox>
<TextInput
disabled
label="Disabled input"
value="Input Value"
onChange={action('change')}
/>
</DebugBox>
</div>
);
}
export function MultiLines() {
return (
<div>
<DebugBox>
<TextInput
multiLine
label="Controlled Textarea"
value={'Controlled input\nin multiple lines'}
onChange={action('change')}
/>
</DebugBox>
</div>
);
}
export function PostFix() {
return (
<DebugBox>
<TextInput
label="Disk Size"
value="3.1415926"
postfix="TB"
onChange={action('change')}
/>
</DebugBox>
);
}
export function CustomRendering() {
return (
<DebugBox>
<TextInput
label="Pick a color"
defaultValue="#d94e41"
renderInput={inputProps => (
<input type="color" {...inputProps} />
)}
onChange={action('change')}
/>
</DebugBox>
);
}
|
webpack/__mocks__/foremanReact/components/common/EmptyState/DefaultEmptyState.js | theforeman/foreman_discovery | import React from 'react';
import { useDispatch } from 'react-redux';
import { push } from 'connected-react-router';
import { Button } from '@patternfly/react-core';
import EmptyStatePattern from './EmptyStatePattern';
import { defaultEmptyStatePropTypes } from './EmptyStatePropTypes';
const DefaultEmptyState = props => {
const {
icon,
iconType,
header,
description,
documentation,
action,
secondaryActions,
} = props;
const dispatch = useDispatch();
const actionButtonClickHandler = ({ url, onClick }) => {
if (onClick) onClick();
else if (url) dispatch(push(url));
};
const ActionButton = action ? (
<Button
component="a"
onClick={() => actionButtonClickHandler(action)}
variant="primary"
>
{action.title}
</Button>
) : null;
const SecondaryButton = secondaryActions
? secondaryActions.map(({ title, url, onClick }) => (
<Button
component="a"
key={`sec-button-${title}`}
onClick={() => actionButtonClickHandler({ url, onClick })}
variant="secondary"
>
{title}
</Button>
))
: null;
return (
<EmptyStatePattern
icon={icon}
iconType={iconType}
header={header}
description={description}
documentation={documentation}
action={ActionButton}
secondaryActions={SecondaryButton}
/>
);
};
DefaultEmptyState.propTypes = defaultEmptyStatePropTypes;
DefaultEmptyState.defaultProps = {
icon: 'add-circle-o',
secondaryActions: [],
iconType: 'pf',
};
export default DefaultEmptyState;
|
src/svg-icons/action/markunread-mailbox.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionMarkunreadMailbox = (props) => (
<SvgIcon {...props}>
<path d="M20 6H10v6H8V4h6V0H6v6H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2z"/>
</SvgIcon>
);
ActionMarkunreadMailbox = pure(ActionMarkunreadMailbox);
ActionMarkunreadMailbox.displayName = 'ActionMarkunreadMailbox';
ActionMarkunreadMailbox.muiName = 'SvgIcon';
export default ActionMarkunreadMailbox;
|
src/abstract/base.js | tychotatitscheff/poseidon-ui | /* @flow */
/* eslint-disable no-console, no-var, vars-on-top */
// Shamelessly taken from https://github.com/este/este/blob/master/src/client/components/component.react.js
import React from 'react';
import shallowEqual from 'react-pure-render/shallowEqual';
var diff; // eslint-disable-line no-var
if (process.env.NODE_ENV === 'development') {
diff = require('immutablediff');
}
type State = { // eslint-disable-line block-scoped-var
fileContent: string;
}
class BaseComponent extends React.Component {
// In order to provide optimisation we are going to make base components be pure render.
// Hence we are going to use react-pure-render from Dan Abramov
// But we should care that nobody use react-pure-render for stateful component like router one
// See https://github.com/gaearon/react-pure-render#known-issues
shouldComponentUpdate(nextProps: {filePath: string;}, nextState: ?State): bool {
// Custom pure render if the components has a router context
if (this.context.router) {
var changed = this.pureComponentLastPath !== this.context.router.getCurrentPath();
this.pureComponentLastPath = this.context.router.getCurrentPath();
if (changed) return true;
}
// Call react-pure-render in order to see if react should update
var shouldUpdate =
!shallowEqual(this.props, nextProps) ||
!shallowEqual(this.state, nextState);
// This will be only loaded in DEV
if (shouldUpdate && process.env.NODE_ENV === 'development') {
this.logShouldUpdateComponents(nextProps, nextState);
}
return shouldUpdate;
}
// Helper to check which component was changed and why.
logShouldUpdateComponents(nextProps: {filePath: string;}, nextState: ?State) {
var name = this.constructor.displayName || this.constructor.name;
console.log(`${name} shouldUpdate`);
var propsDiff = diff(this.props, nextProps).toJS();
var stateDiff = diff(this.state, nextState).toJS();
if (propsDiff.length) {
console.log('props', propsDiff);
}
if (stateDiff.length) {
console.log('state', stateDiff);
}
}
render() {
return <div/>;
}
}
BaseComponent.contextTypes = {
router: React.PropTypes.func,
posTheme: React.PropTypes.object
};
export default BaseComponent;
|
src/svg-icons/av/subtitles.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvSubtitles = (props) => (
<SvgIcon {...props}>
<path d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM4 12h4v2H4v-2zm10 6H4v-2h10v2zm6 0h-4v-2h4v2zm0-4H10v-2h10v2z"/>
</SvgIcon>
);
AvSubtitles = pure(AvSubtitles);
AvSubtitles.displayName = 'AvSubtitles';
AvSubtitles.muiName = 'SvgIcon';
export default AvSubtitles;
|
src/Parser/Druid/Restoration/Modules/Features/Clearcasting.js | hasseboulen/WoWAnalyzer | import React from 'react';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import { formatPercentage } from 'common/format';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import Wrapper from 'common/Wrapper';
import SPELLS from 'common/SPELLS';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
const debug = false;
class Clearcasting extends Analyzer {
static dependencies = {
combatants: Combatants,
};
// With MoC, there's no actual indication in the events that you have it...
// In fact the Clearcasting buff doesn't show with stacks.
// You'll appear as casting Regrowths without the buff disappating, and then on the 3rd Regrowth it goes away.
hasMoC;
procsPerCC;
totalProcs = 0;
expiredProcs = 0;
overwrittenProcs = 0;
usedProcs = 0;
availableProcs = 0; // number of free regrowths remaining in current Clearcast. Usually 1, but becomes 3 with MoC.
nonCCRegrowths = 0;
totalRegrowths = 0;
on_initialized() {
this.hasMoC = this.combatants.selected.hasTalent(SPELLS.MOMENT_OF_CLARITY_TALENT_RESTORATION.id);
this.procsPerCC = this.hasMoC ? 3 : 1;
}
on_byPlayer_applybuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.CLEARCASTING_BUFF.id) {
return;
}
debug && console.log(`Clearcasting applied @${this.owner.formatTimestamp(event.timestamp)} - ${this.procsPerCC} procs remaining`);
this.totalProcs += this.procsPerCC;
this.availableProcs = this.procsPerCC;
}
// refreshbuff does show without MoC, but doesn't show with it.... at least I can get overwrites when player doesn't have it...
on_byPlayer_refreshbuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.CLEARCASTING_BUFF.id) {
return;
}
debug && console.log(`Clearcasting refreshed @${this.owner.formatTimestamp(event.timestamp)} - overwriting ${this.availableProcs} procs - ${this.procsPerCC} procs remaining`);
this.totalProcs += this.procsPerCC;
this.overwrittenProcs += this.availableProcs;
this.availableProcs = this.procsPerCC;
}
on_byPlayer_removebuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.CLEARCASTING_BUFF.id) {
return;
}
debug && console.log(`Clearcasting expired @${this.owner.formatTimestamp(event.timestamp)} - ${this.availableProcs} procs expired`);
if (this.availableProcs < 0) { // there was an invisible refresh after some but not all the MoC charges consumed...
debug && console.log(`There was an invisible refresh after some but not all MoC charges consumed ... setting available to 0...`);
this.availableProcs = 0;
}
this.expiredProcs += this.availableProcs;
this.availableProcs = 0;
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.REGROWTH.id) {
return;
}
this.totalRegrowths += 1;
if (this.combatants.selected.hasBuff(SPELLS.CLEARCASTING_BUFF.id)) {
this.availableProcs -= 1;
this.usedProcs += 1;
debug && console.log(`Regrowth w/CC cast @${this.owner.formatTimestamp(event.timestamp)} - ${this.availableProcs} procs remaining`);
} else {
this.nonCCRegrowths += 1;
}
}
get wastedProcs() {
return this.expiredProcs + this.overwrittenProcs;
}
get clearcastingUtilPercent() {
const util = this.usedProcs / this.totalProcs;
return (util > 1) ? 1 : util; // invisible refresh + MoC can make util greater than 100% ... in that case clamp to 100%
}
get hadInvisibleRefresh() {
return this.usedProcs > this.totalProcs;
}
get clearcastingUtilSuggestionThresholds() {
return {
actual: this.clearcastingUtilPercent,
isLessThan: {
minor: 0.90,
average: 0.50,
major: 0.25,
},
style: 'percentage',
};
}
get nonCCRegrowthsPerMinute() {
return this.nonCCRegrowths / (this.owner.fightDuration / 60000);
}
get nonCCRegrowthsSuggestionThresholds() {
return {
actual: this.nonCCRegrowthsPerMinute,
isGreaterThan: {
minor: 0,
average: 1,
major: 3,
},
style: 'number',
};
}
suggestions(when) {
when(this.clearcastingUtilSuggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<Wrapper>Your <SpellLink id={SPELLS.CLEARCASTING_BUFF.id} /> procs should be used quickly so they do not get overwritten or expire.</Wrapper>)
.icon(SPELLS.CLEARCASTING_BUFF.icon)
.actual(`You missed ${this.wastedProcs} out of ${this.totalProcs} (${formatPercentage(1 - this.clearcastingUtilPercent, 1)}%) of your free regrowth procs`)
.recommended(`<${Math.round(formatPercentage(1 - recommended, 1))}% is recommended`);
});
when(this.nonCCRegrowthsSuggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<Wrapper><SpellLink id={SPELLS.REGROWTH.id} /> is a very inefficient spell to cast without a <SpellLink id={SPELLS.CLEARCASTING_BUFF.id} /> proc. It should only be cast when your target is about to die and you do not have <SpellLink id={SPELLS.SWIFTMEND.id} /> available.</Wrapper>)
.icon(SPELLS.REGROWTH.icon)
.actual(`You cast ${this.nonCCRegrowthsPerMinute.toFixed(1)} Regrowths per minute without a Clearcasting proc.`)
.recommended(`${recommended.toFixed(1)} CPM is recommended`);
});
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.CLEARCASTING_BUFF.id} />}
value={`${formatPercentage(this.clearcastingUtilPercent, 1)} %`}
label="Clearcasting Util"
tooltip={`Clearcasting procced <b>${this.totalProcs} free Regrowths</b>
<ul>
<li>Used: <b>${this.usedProcs} ${this.hadInvisibleRefresh ? '*' : ''}</b></li>
${this.hadInvisibleRefresh ? '' : `<li>Overwritten: <b>${this.overwrittenProcs}</b></li>`}
<li>Expired: <b>${this.expiredProcs}</b></li>
</ul>
<b>${this.nonCCRegrowths} of your Regrowths were cast without a Clearcasting proc</b>.
Using a clearcasting proc as soon as you get it should be one of your top priorities.
Even if it overheals you still get that extra mastery stack on a target and the minor HoT.
Spending your GCD on a free spell also helps with mana management in the long run.<br />
${this.hadInvisibleRefresh ? `<i>* Mark of Clarity can sometimes 'invisibly refresh', which can make your total procs show as lower than you actually got. Basically, you invisibly overwrote some number of procs, but we aren't able to see how many.</i>` : ''}`}
/>
);
}
statisticOrder = STATISTIC_ORDER.CORE(20);
}
export default Clearcasting;
|
app/javascript/mastodon/features/compose/containers/warning_container.js | narabo/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { connect } from 'react-redux';
import Warning from '../components/warning';
import { createSelector } from 'reselect';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { OrderedSet } from 'immutable';
const getMentionedUsernames = createSelector(state => state.getIn(['compose', 'text']), text => text.match(/(?:^|[^\/\w])@([a-z0-9_]+@[a-z0-9\.\-]+)/ig));
const getMentionedDomains = createSelector(getMentionedUsernames, mentionedUsernamesWithDomains => {
return OrderedSet(mentionedUsernamesWithDomains !== null ? mentionedUsernamesWithDomains.map(item => item.split('@')[2]) : []);
});
const mapStateToProps = state => {
const mentionedUsernames = getMentionedUsernames(state);
const mentionedUsernamesWithDomains = getMentionedDomains(state);
return {
needsLeakWarning: (state.getIn(['compose', 'privacy']) === 'private' || state.getIn(['compose', 'privacy']) === 'direct') && mentionedUsernames !== null,
mentionedDomains: mentionedUsernamesWithDomains,
needsLockWarning: state.getIn(['compose', 'privacy']) === 'private' && !state.getIn(['accounts', state.getIn(['meta', 'me']), 'locked']),
};
};
const WarningWrapper = ({ needsLeakWarning, needsLockWarning, mentionedDomains }) => {
if (needsLockWarning) {
return <Warning message={<FormattedMessage id='compose_form.lock_disclaimer' defaultMessage='Your account is not {locked}. Anyone can follow you to view your follower-only posts.' values={{ locked: <a href='/settings/profile'><FormattedMessage id='compose_form.lock_disclaimer.lock' defaultMessage='locked' /></a> }} />} />;
} else if (needsLeakWarning) {
return (
<Warning
message={<FormattedMessage
id='compose_form.privacy_disclaimer'
defaultMessage='Your private status will be delivered to mentioned users on {domains}. Do you trust {domainsCount, plural, one {that server} other {those servers}}? Post privacy only works on Mastodon instances. If {domains} {domainsCount, plural, one {is not a Mastodon instance} other {are not Mastodon instances}}, there will be no indication that your post is private, and it may be boosted or otherwise made visible to unintended recipients.'
values={{ domains: <strong>{mentionedDomains.join(', ')}</strong>, domainsCount: mentionedDomains.size }}
/>}
/>
);
}
return null;
};
WarningWrapper.propTypes = {
needsLeakWarning: PropTypes.bool,
needsLockWarning: PropTypes.bool,
mentionedDomains: ImmutablePropTypes.orderedSet.isRequired,
};
export default connect(mapStateToProps)(WarningWrapper);
|
samples/index.js | aratakokubun/cursor-hijack | import React from 'react';
import { render } from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import cjk from '../index';
import App from './app'
let store = createStore(cjk.Reducers);
let rootElement = document.getElementById('app')
render(
<Provider store={store}>
<div>
<App />
</div>
</Provider>,
rootElement
) |
src/Glyphicon.js | xuorig/react-bootstrap | import React from 'react';
import classNames from 'classnames';
const Glyphicon = React.createClass({
propTypes: {
/**
* bootstrap className
* @private
*/
bsClass: React.PropTypes.string,
/**
* An icon name. See e.g. http://getbootstrap.com/components/#glyphicons
*/
glyph: React.PropTypes.string.isRequired,
/**
* Adds 'form-control-feedback' class
* @private
*/
formControlFeedback: React.PropTypes.bool
},
getDefaultProps() {
return {
bsClass: 'glyphicon',
formControlFeedback: false
};
},
render() {
let className = classNames(this.props.className, {
[this.props.bsClass]: true,
['glyphicon-' + this.props.glyph]: true,
['form-control-feedback']: this.props.formControlFeedback
});
return (
<span {...this.props} className={className}>
{this.props.children}
</span>
);
}
});
export default Glyphicon;
|
src/selectable-group.js | leopoldjoy/react-selectable | import React from 'react';
import ReactDOM from 'react-dom';
import isNodeInRoot from './nodeInRoot';
import getBoundsForNode from './getBoundsForNode';
import doObjectsCollide from './doObjectsCollide';
class SelectableGroup extends React.Component {
constructor (props) {
super(props);
this.state = {
isBoxSelecting: false,
boxWidth: 0,
boxHeight: 0
}
this._mouseDownData = null;
this._registry = [];
// Used to prevent actions from firing twice on devices that are both click and touch enabled
this._mouseDownStarted = false;
this._mouseMoveStarted = false;
this._mouseUpStarted = false;
this._openSelector = this._openSelector.bind(this);
this._mouseDown = this._mouseDown.bind(this);
this._mouseUp = this._mouseUp.bind(this);
this._selectElements = this._selectElements.bind(this);
this._registerSelectable = this._registerSelectable.bind(this);
this._unregisterSelectable = this._unregisterSelectable.bind(this);
this._desktopEventCoords = this._desktopEventCoords.bind(this);
}
getChildContext () {
return {
selectable: {
register: this._registerSelectable,
unregister: this._unregisterSelectable
}
};
}
componentDidMount () {
ReactDOM.findDOMNode(this).addEventListener('mousedown', this._mouseDown);
ReactDOM.findDOMNode(this).addEventListener('touchstart', this._mouseDown);
}
/**
* Remove global event listeners
*/
componentWillUnmount () {
ReactDOM.findDOMNode(this).removeEventListener('mousedown', this._mouseDown);
ReactDOM.findDOMNode(this).removeEventListener('touchstart', this._mouseDown);
}
_registerSelectable (key, domNode) {
this._registry.push({key, domNode});
}
_unregisterSelectable (key) {
this._registry = this._registry.filter(data => data.key !== key);
}
/**
* Called while moving the mouse with the button down. Changes the boundaries
* of the selection box
*/
_openSelector (e) {
if(this._mouseMoveStarted) return;
this._mouseMoveStarted = true;
e = this._desktopEventCoords(e);
const w = Math.abs(this._mouseDownData.initialW - e.pageX);
const h = Math.abs(this._mouseDownData.initialH - e.pageY);
this.setState({
isBoxSelecting: true,
boxWidth: w,
boxHeight: h,
boxLeft: Math.min(e.pageX, this._mouseDownData.initialW),
boxTop: Math.min(e.pageY, this._mouseDownData.initialH)
}, () => {
this._mouseMoveStarted = false;
});
}
/**
* Called when a user presses the mouse button. Determines if a select box should
* be added, and if so, attach event listeners
*/
_mouseDown (e) {
if(this._mouseDownStarted) return;
this._mouseDownStarted = true;
this._mouseUpStarted = false;
e = this._desktopEventCoords(e);
const node = ReactDOM.findDOMNode(this);
let collides, offsetData, distanceData;
ReactDOM.findDOMNode(this).addEventListener('mouseup', this._mouseUp);
ReactDOM.findDOMNode(this).addEventListener('touchend', this._mouseUp);
// Right clicks
if(e.which === 3 || e.button === 2) return;
if(!isNodeInRoot(e.target, node)) {
offsetData = getBoundsForNode(node);
collides = doObjectsCollide(
{
top: offsetData.top,
left: offsetData.left,
bottom: offsetData.offsetHeight,
right: offsetData.offsetWidth
},
{
top: e.pageY,
left: e.pageX,
offsetWidth: 0,
offsetHeight: 0
}
);
if(!collides) return;
}
this._mouseDownData = {
boxLeft: e.pageX,
boxTop: e.pageY,
initialW: e.pageX,
initialH: e.pageY
};
e.preventDefault();
ReactDOM.findDOMNode(this).addEventListener('mousemove', this._openSelector);
ReactDOM.findDOMNode(this).addEventListener('touchmove', this._openSelector);
}
/**
* Called when the user has completed selection
*/
_mouseUp (e) {
if(this._mouseUpStarted) return;
this._mouseUpStarted = true;
this._mouseDownStarted = false;
ReactDOM.findDOMNode(this).removeEventListener('mousemove', this._openSelector);
ReactDOM.findDOMNode(this).removeEventListener('mouseup', this._mouseUp);
ReactDOM.findDOMNode(this).removeEventListener('touchmove', this._openSelector);
ReactDOM.findDOMNode(this).removeEventListener('touchend', this._mouseUp);
if(!this._mouseDownData) return;
return this._selectElements(e);
}
/**
* Selects multiple children given x/y coords of the mouse
*/
_selectElements (e) {
this._mouseDownData = null;
const currentItems = [],
selectbox = ReactDOM.findDOMNode(this.refs.selectbox),
{tolerance} = this.props;
if(!selectbox) return;
this._registry.forEach(itemData => {
if(itemData.domNode && doObjectsCollide(selectbox, itemData.domNode, tolerance)) {
currentItems.push(itemData.key);
}
});
this.setState({
isBoxSelecting: false,
boxWidth: 0,
boxHeight: 0
});
this.props.onSelection(currentItems);
}
/**
* Used to return event object with desktop (non-touch) format of event
* coordinates, regardless of whether the action is from mobile or desktop.
*/
_desktopEventCoords (e){
if(e.pageX==undefined || e.pageY==undefined){ // Touch-device
e.pageX = e.targetTouches[0].pageX;
e.pageY = e.targetTouches[0].pageY;
}
return e;
}
/**
* Renders the component
* @return {ReactComponent}
*/
render () {
const boxStyle = {
left: this.state.boxLeft,
top: this.state.boxTop,
width: this.state.boxWidth,
height: this.state.boxHeight,
zIndex: 9000,
position: this.props.fixedPosition ? 'fixed' : 'absolute',
cursor: 'default'
};
const spanStyle = {
backgroundColor: 'transparent',
border: '1px dashed #999',
width: '100%',
height: '100%',
float: 'left'
};
return (
<this.props.component {...this.props}>
{this.state.isBoxSelecting &&
<div style={boxStyle} ref="selectbox"><span style={spanStyle}></span></div>
}
{this.props.children}
</this.props.component>
);
}
}
SelectableGroup.propTypes = {
/**
* Event that will fire when items are selected. Passes an array of keys
*/
onSelection: React.PropTypes.func,
/**
* The component that will represent the Selectable DOM node
*/
component: React.PropTypes.node,
/**
* Amount of forgiveness an item will offer to the selectbox before registering
* a selection, i.e. if only 1px of the item is in the selection, it shouldn't be
* included.
*/
tolerance: React.PropTypes.number,
/**
* In some cases, it the bounding box may need fixed positioning, if your layout
* is relying on fixed positioned elements, for instance.
* @type boolean
*/
fixedPosition: React.PropTypes.bool
};
SelectableGroup.defaultProps = {
onSelection: () => {},
component: 'div',
tolerance: 0,
fixedPosition: false
};
SelectableGroup.childContextTypes = {
selectable: React.PropTypes.object
};
export default SelectableGroup;
|
src/components/D3Bars.js | guzmonne/gux-d3-react | import React from 'react'
import T from 'prop-types'
import {DELAY} from '../variables.js'
const d3 = Object.assign({},
require('d3-selection'),
require('d3-transition')
)
class D3Bars extends React.Component {
componentDidMount() {
this.draw()
}
componentDidUpdate() {
this.draw()
}
draw = () => {
const {
data,
height,
xScale,
yScale,
xAccesor,
yAccesor,
barClassName,
barWidth,
fill,
} = this.props
const t = d3.transition().duration(DELAY)
const bars = (
d3.select(this.container)
.selectAll('.' + barClassName)
.data(data, xAccesor)
)
// Exit
bars.exit()
.transition(t)
.attr('y', height)
.attr('height', 0)
.remove()
// Update
bars
.transition(t)
.attr('y', d => yScale(yAccesor(d)))
.attr('height', d => height - yScale(yAccesor(d)))
.attr('x', d => xScale(xAccesor(d)))
.attr('width', d => barWidth
? barWidth(d)
: xScale.bandwidth && xScale.bandwidth())
// Enter
bars
.enter()
.append('rect')
.attr('class', barClassName)
.attr('y', height)
.attr('height', 0)
.attr('x', d => xScale(xAccesor(d)))
.attr('width', d => barWidth
? barWidth(d)
: xScale.bandwidth && xScale.bandwidth())
.attr('fill', fill)
.transition(t)
.attr('y', d => yScale(yAccesor(d)))
.attr('height', d => height - yScale(yAccesor(d)))
}
render() {
const {className} = this.props
return (
<g className={className} ref={c => this.container = c}></g>
)
}
}
D3Bars.propTypes = {
className: T.string,
barClassName: T.string,
data: T.array,
height: T.number,
xScale: T.func,
yScale: T.func,
xAccesor: T.func,
yAccesor: T.func,
barWidth: T.func,
fill: T.string,
}
D3Bars.defaultProps = {
className: 'rd3__bars',
barClassName: 'rd3__bar',
fill: 'steelblue',
}
export default D3Bars
|
src/components/Logo/index.js | dramich/twitchBot | import React, { Component } from 'react';
import TimelineMax from 'gsap/src/minified/TimelineMax.min';
/* component styles */
import { styles } from './styles.scss';
export default class Logo extends Component {
constructor(props) {
super(props);
this.state = {
logo: new TimelineMax,
hatson: new TimelineMax,
animating: true,
};
}
componentDidMount() {
const shrink = new TimelineMax;
shrink.to('#hhh', 0, { scale: 0.25 })
.to('#aaa', 0, { scale: 0.25 })
.to('#ttt', 0, { scale: 0.25 })
.to('#sss', 0, { scale: 0.25 })
.to('#ooo', 0, { scale: 0.25 })
.to('#nnn', 0, { scale: 0.25 });
setTimeout(() => { this.logoAnimate().forward(); }, 1500);
}
logoAnimate() {
const forward = () => {
this.state.logo.to('#mouth', 2, { rotation: 270, x: 5, y: -4, transformOrigin: '10px 5px' })
.to('.eyes', 2, { rotation: 90, x: 41, y: -4 }, '-=2')
.to('#left_ball', 0.75, { opacity: 0, x: 5, y: -45 }, '-=1.15')
.to('#right_ball', 0.75, { opacity: 0, x: 25, y: -35 }, '-=0.8')
.duration(1.5)
.eventCallback('onReverseComplete', () => { setTimeout(() => { this.state.logo.timeScale(2.5).play(); }, 300); });
this.state.hatson
.to('#hhh', 0.75, { opacity: 100, scale: 1.8, y: 4 })
.to('#aaa', 0.75, { opacity: 100, scale: 1.7, x: 12, y: 3 }, '-=0.5')
.to('#ttt', 0.75, { opacity: 100, scale: 1.7, x: 22, y: -0.65 }, '-=0.5')
.to('#sss', 0.75, { opacity: 100, scale: 1.7, x: 32, y: 3 }, '-=0.5')
.to('#ooo', 0.75, { opacity: 100, scale: 1.7, x: 42, y: 3 }, '-=0.5')
.to('#nnn', 0.75, { opacity: 100, scale: 1.7, x: 54, y: 3 }, '-=0.5')
.duration(1.5)
.eventCallback('onReverseComplete', () => { setTimeout(() => { this.state.hatson.timeScale(2.5).play(); }, 300); })
.eventCallback('onComplete', () => { this.setState({ animating: false }); });
};
const rewind = () => {
if (!this.state.animating) {
this.setState({ animating: true });
this.state.logo
.timeScale(3)
.reverse(0);
this.state.hatson
.timeScale(3)
.reverse(0);
}
};
return {
forward,
rewind,
};
}
render() {
return (
<div className={`${styles}`}>
<span className="logo-holder">
<svg className="logo" width="60" height="60" viewBox="-2 -2 64 74" onMouseEnter={() => { this.logoAnimate().rewind(); }}>
<g className="eyes">
<line id="left_eye" fill="none" stroke="#ffffff" strokeWidth="3" stroke-miterlimit="10" x1="12.5" y1="8.9" x2="24.3" y2="8.9" />
<line id="right_eye" fill="none" stroke="#ffffff" strokeWidth="3" stroke-miterlimit="10" x1="35.8" y1="8.9" x2="47.7" y2="8.9" />
<path
id="left_ball" fill="#FF1D25" stroke="#FF1D25" strokeWidth="1.35" stroke-miterlimit="10" d="M14.9,10.3c0,1.9,1.4,3.5,3,3.8
c1.9,0.3,4.1-1.4,4.1-3.8"
/>
<path
id="right_ball" fill="#FF1D25" stroke="#FF1D25" strokeWidth="1.35" stroke-miterlimit="10" d="M38.1,10.3c0,1.9,1.4,3.5,3,3.8
c1.9,0.3,4.1-1.4,4.1-3.8"
/>
</g>
<path
id="mouth" fill="none" stroke="#ffffff" strokeWidth="5" stroke-miterlimit="10" d="M46.1,47.6c0.3-1.3,1.2-5.4-0.7-9.9
c-1.7-4.2-4.9-6.4-5.8-7.1c-0.6-0.4-1.7-1.2-3.6-1.9c-0.7-0.3-3.6-1.3-7.4-1c-1.3,0.1-4.6,0.4-8,2.5c-1,0.6-3.2,2-4.9,4.6
c-1.6,2.3-1.9,4.5-2.2,5.7c-0.6,3-0.3,5.7,0.1,7.2"
/>
</svg>
<span>
<svg className="hatson" width="124.5" height="60" viewBox="0 0 200 100">
<g className="letters">
<path
id="hhh"
opacity="0"
fill="none" stroke="#FF1D25" strokeWidth="2.5" stroke-miterlimit="10" d="M12.7,26.6c0.3-0.5,0.7-1.2,1.5-1.8
c0.8-0.6,1.5-0.9,2.1-1c1.2-0.3,2.1-0.3,2.6-0.3c0.6,0,1.5,0.1,2.5,0.6c0.4,0.2,1.1,0.5,1.7,1.2c0.2,0.2,0.7,0.8,1,1.7
c0.2,0.6,0.3,1.1,0.3,1.4c0.1,0.4,0.1,0.8,0.1,1.1c0,0.2,0,0.4,0,1.1c0,0.4,0,0.6,0,1c0,0.1,0,0.3,0,0.6c0,0.4,0,0.7,0,0.9
c0,0.6,0,0.8,0,1.5c0,0.7,0,1.2,0,1.6c0,0.8,0,2,0,4"
/>
<path
id="aaa"
opacity="0"
strokeWidth="2"
fill="#FF1D25" stroke="#FF1D25"
d="M42.2,36.9c0,0.6,0,1.3,0.1,2c0.1,0.7,0.1,1.3,0.2,1.8h-0.8c0-0.2-0.1-0.5-0.1-0.9c0-0.4-0.1-0.7-0.1-1.1
c0-0.4-0.1-0.8-0.1-1.1c0-0.4,0-0.7,0-0.9h-0.1c-0.5,1.5-1.3,2.7-2.5,3.4c-1.2,0.7-2.5,1.1-3.9,1.1c-0.7,0-1.4-0.1-2-0.3
c-0.7-0.2-1.3-0.5-1.8-0.9c-0.5-0.4-1-0.9-1.3-1.5c-0.3-0.6-0.5-1.3-0.5-2.2c0-1.2,0.3-2.2,0.9-2.9c0.6-0.7,1.4-1.3,2.3-1.7
c0.9-0.4,1.9-0.7,3-0.8c1.1-0.1,2-0.2,2.9-0.2h3v-1.4c0-1.9-0.5-3.3-1.5-4.1c-1-0.9-2.3-1.3-3.9-1.3c-1,0-2,0.2-2.8,0.6
c-0.9,0.4-1.7,0.9-2.3,1.5l-0.4-0.6c0.8-0.7,1.7-1.2,2.7-1.6c1-0.4,2-0.5,2.9-0.5c1.9,0,3.5,0.5,4.6,1.5c1.1,1,1.7,2.6,1.7,4.7
V36.9z M41.4,31.5h-2.6c-0.9,0-1.9,0.1-3,0.2c-1,0.1-2,0.3-2.8,0.7c-0.9,0.3-1.6,0.8-2.1,1.5c-0.6,0.6-0.8,1.5-0.8,2.6
c0,0.8,0.2,1.4,0.5,2c0.3,0.5,0.7,1,1.2,1.3c0.5,0.3,1,0.6,1.6,0.7c0.6,0.1,1.1,0.2,1.6,0.2c1.3,0,2.3-0.2,3.1-0.7
c0.8-0.5,1.5-1.1,2-1.8c0.5-0.7,0.9-1.5,1.1-2.4c0.2-0.9,0.3-1.7,0.3-2.6V31.5z"
/>
<path
id="ttt"
opacity="0"
strokeWidth="2"
fill="#FF1D25" stroke="#FF1D25"
d="M54.6,41c-0.4,0.1-0.8,0.1-1.1,0.1c-1.3,0-2.3-0.4-2.8-1.1c-0.6-0.7-0.8-1.7-0.8-2.8V24.5h-3.7v-0.7h3.7v-5h0.8v5h5v0.7
h-5v12.8c0,1.2,0.3,2,0.8,2.5c0.6,0.5,1.3,0.8,2.3,0.8c0.7,0,1.3-0.1,1.9-0.3l0.1,0.6C55.3,40.9,55,41,54.6,41z"
/>
<path
id="sss"
opacity="0"
strokeWidth="2"
fill="#FF1D25" stroke="#FF1D25"
d="M69.9,36.3c0,0.8-0.1,1.4-0.4,2c-0.3,0.6-0.7,1.1-1.2,1.5c-0.5,0.4-1.1,0.7-1.8,1c-0.7,0.2-1.4,0.3-2.1,0.3
c-1.3,0-2.4-0.2-3.4-0.7c-1-0.5-1.9-1.2-2.5-2.1l0.7-0.4c1.2,1.7,3,2.6,5.3,2.6c0.5,0,1.1-0.1,1.6-0.3c0.6-0.2,1.1-0.4,1.5-0.8
c0.5-0.3,0.8-0.8,1.1-1.3c0.3-0.5,0.4-1.1,0.4-1.8c0-0.8-0.2-1.4-0.5-1.9c-0.4-0.5-0.8-0.9-1.3-1.2c-0.5-0.3-1.1-0.5-1.8-0.7
c-0.7-0.2-1.3-0.4-1.8-0.5c-0.6-0.2-1.2-0.4-1.7-0.6c-0.5-0.2-1-0.5-1.4-0.8c-0.4-0.3-0.7-0.7-1-1.2c-0.2-0.5-0.4-1.1-0.4-1.8
s0.1-1.4,0.4-1.9c0.3-0.5,0.7-1,1.2-1.3c0.5-0.4,1.1-0.6,1.7-0.8c0.6-0.2,1.3-0.3,1.9-0.3c2.3,0,4,0.8,5.2,2.5l-0.7,0.4
c-0.6-0.7-1.2-1.3-1.9-1.6c-0.7-0.4-1.6-0.5-2.6-0.5c-0.5,0-1,0.1-1.5,0.2c-0.5,0.1-1,0.3-1.4,0.6c-0.4,0.3-0.8,0.7-1.1,1.1
c-0.3,0.5-0.4,1-0.4,1.7c0,0.7,0.1,1.3,0.4,1.8c0.2,0.4,0.6,0.8,1,1.1c0.4,0.3,0.9,0.5,1.5,0.7c0.6,0.2,1.2,0.4,2,0.5
c0.7,0.2,1.3,0.4,1.9,0.6c0.6,0.2,1.2,0.5,1.7,0.9c0.5,0.3,0.9,0.8,1.1,1.3C69.7,34.9,69.9,35.5,69.9,36.3z"
/>
<path
id="ooo"
opacity="0"
strokeWidth="2"
fill="#FF1D25" stroke="#FF1D25"
d="M91.9,32.2c0,1.3-0.2,2.5-0.6,3.6c-0.4,1.1-1,2.1-1.8,2.9c-0.8,0.8-1.7,1.4-2.8,1.9c-1.1,0.4-2.3,0.7-3.6,0.7
c-1.3,0-2.5-0.2-3.6-0.7c-1.1-0.4-2-1.1-2.8-1.9c-0.8-0.8-1.4-1.8-1.8-2.9c-0.4-1.1-0.6-2.3-0.6-3.6s0.2-2.5,0.6-3.6
c0.4-1.1,1-2,1.8-2.8c0.8-0.8,1.7-1.4,2.8-1.8c1.1-0.4,2.3-0.7,3.6-0.7c1.3,0,2.5,0.2,3.6,0.7c1.1,0.4,2,1.1,2.8,1.8
c0.8,0.8,1.4,1.7,1.8,2.8C91.7,29.7,91.9,30.9,91.9,32.2z M91.1,32.2c0-1.1-0.2-2.2-0.6-3.2c-0.4-1-0.9-1.9-1.6-2.6
c-0.7-0.7-1.6-1.3-2.5-1.8c-1-0.4-2.1-0.6-3.4-0.6c-1.3,0-2.4,0.2-3.4,0.6c-1,0.4-1.8,1-2.5,1.8c-0.7,0.7-1.2,1.6-1.6,2.6
c-0.4,1-0.6,2.1-0.6,3.2c0,1.2,0.2,2.2,0.6,3.2c0.4,1,0.9,1.9,1.6,2.6c0.7,0.7,1.5,1.3,2.5,1.8c1,0.4,2.1,0.7,3.4,0.7
c1.3,0,2.4-0.2,3.4-0.7c1-0.4,1.8-1,2.5-1.8c0.7-0.7,1.2-1.6,1.6-2.6C90.9,34.4,91.1,33.3,91.1,32.2z"
/>
<path
id="nnn"
opacity="0"
strokeWidth="2"
fill="#FF1D25" stroke="#FF1D25"
d="M100,26.1c0.5-0.6,1-1.1,1.6-1.6c0.6-0.4,1.2-0.8,1.9-1c0.7-0.2,1.4-0.3,2.1-0.3c1.2,0,2.2,0.2,3,0.6
c0.8,0.4,1.4,1,1.9,1.7c0.5,0.7,0.8,1.5,1,2.3c0.2,0.9,0.3,1.7,0.3,2.6v10.2h-0.8V30.5c0-0.7-0.1-1.4-0.2-2.2
c-0.1-0.8-0.4-1.5-0.8-2.1c-0.4-0.6-1-1.2-1.6-1.6c-0.7-0.4-1.6-0.6-2.6-0.6c-0.9,0-1.8,0.2-2.6,0.6c-0.8,0.4-1.5,0.9-2.1,1.6
c-0.6,0.7-1.1,1.6-1.4,2.6c-0.4,1-0.5,2.2-0.5,3.5v8.5h-0.8V28c0-0.3,0-0.6,0-1c0-0.4,0-0.8,0-1.2c0-0.4,0-0.8-0.1-1.2
c0-0.4,0-0.7-0.1-0.9h0.8c0,0.2,0,0.6,0.1,0.9c0,0.4,0,0.8,0,1.2c0,0.4,0,0.8,0,1.3c0,0.4,0,0.8,0,1.1h0.1
C99.2,27.4,99.5,26.7,100,26.1z"
/>
</g>
</svg>
</span>
</span>
</div>
);
}
}
|
es/components/PlaylistManager/Import/ImportPanelHeader.js | welovekpop/uwave-web-welovekpop.club | import _jsx from "@babel/runtime/helpers/builtin/jsx";
import cx from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import Tooltip from "@material-ui/core/es/Tooltip";
import IconButton from "@material-ui/core/es/IconButton";
import CloseIcon from "@material-ui/icons/es/Close";
var enhance = translate();
var _ref2 =
/*#__PURE__*/
_jsx(CloseIcon, {});
var ImportPanelHeader = function ImportPanelHeader(_ref) {
var t = _ref.t,
className = _ref.className,
children = _ref.children,
onClosePanel = _ref.onClosePanel;
return _jsx("div", {
className: cx('ImportPanelHeader', className)
}, void 0, _jsx("div", {
className: "ImportPanelHeader-content"
}, void 0, children), _jsx(Tooltip, {
title: t('close'),
placement: "top"
}, void 0, _jsx(IconButton, {
onClick: onClosePanel
}, void 0, _ref2)));
};
ImportPanelHeader.propTypes = process.env.NODE_ENV !== "production" ? {
className: PropTypes.string,
children: PropTypes.node,
t: PropTypes.func.isRequired,
onClosePanel: PropTypes.func.isRequired
} : {};
export default enhance(ImportPanelHeader);
//# sourceMappingURL=ImportPanelHeader.js.map
|
js/components/episode.js | frequencyasia/website | import React from 'react';
import $ from 'jquery';
import fecha from 'fecha';
import i18next from 'i18next';
import Constants from './../constants';
import EpisodeCard from './episodeCard';
module.exports = React.createClass({
propTypes: {
slug: React.PropTypes.string.isRequired,
showSlug: React.PropTypes.string.isRequired,
nowPlayingSlug: React.PropTypes.string.isRequired,
},
getInitialState: function getInitialState() {
return {
name: '',
image_path: 'placeholder.png',
description: '',
episodes: [],
};
},
componentDidMount: function componentDidMount() {
document.title = `${i18next.t('show')} | ${i18next.t('freqAsia')}`;
$.getJSON(Constants.API_URL + 'shows/' + this.props.showSlug)
.done((data) => {
for (let i = 0; i < data.episodes.length; i++) {
const item = data.episodes[i];
item.date = fecha.format(new Date(item.start_time), 'dddd / MMMM D YYYY');
}
this.setState(data);
document.title = `${this.state.name} | ${i18next.t('freqAsia')}`;
});
},
renderSidebar: function renderSidebar() {
const style = { backgroundImage: `url(/static/files/${this.state.image_path})` };
return (
<aside className="c-show__sidebar">
<div className="c-show__sidebar__image" style={ style }></div>
<h1 className="c-show__sidebar__title">{ this.state.name }</h1>
<div dangerouslySetInnerHTML={ { __html: this.state.description } } />
</aside>
);
},
renderEpisodeCards: function renderEpisodeCards() {
return this.state.episodes.map((episode) => {
return <EpisodeCard key={ episode.slug } nowPlayingSlug={ this.props.nowPlayingSlug } { ...episode } />;
});
},
render: function render() {
return (
<section className="c-show">
{ this.renderSidebar() }
<section className="c-show__episodes">{ this.renderEpisodeCards() }</section>
</section>
);
},
});
|
web/src/containers/Exchange.js | xiyanxiyan10/quant | import { ResetError } from '../actions';
import { ExchangeList, ExchangePut, ExchangeDelete } from '../actions/exchange';
import React from 'react';
import { connect } from 'react-redux';
import { Button, Table, Modal, Form, Input, Select, notification } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
class Exchange extends React.Component {
constructor(props) {
super(props);
this.state = {
messageErrorKey: '',
selectedRowKeys: [],
pagination: {
pageSize: 12,
current: 1,
total: 0,
},
info: {},
infoModalShow: false,
};
this.reload = this.reload.bind(this);
this.onSelectChange = this.onSelectChange.bind(this);
this.handleTableChange = this.handleTableChange.bind(this);
this.handleDelete = this.handleDelete.bind(this);
this.handleInfoShow = this.handleInfoShow.bind(this);
this.handleInfoSubmit = this.handleInfoSubmit.bind(this);
this.handleInfoCancel = this.handleInfoCancel.bind(this);
}
componentWillReceiveProps(nextProps) {
const { dispatch } = this.props;
const { messageErrorKey, pagination } = this.state;
const { exchange } = nextProps;
if (!messageErrorKey && exchange.message) {
this.setState({
messageErrorKey: 'exchangeError',
});
notification['error']({
key: 'exchangeError',
message: 'Error',
description: String(exchange.message),
onClose: () => {
if (this.state.messageErrorKey) {
this.setState({ messageErrorKey: '' });
}
dispatch(ResetError());
},
});
}
pagination.total = exchange.total;
this.setState({ pagination });
}
componentWillMount() {
this.order = 'id';
this.reload();
}
componentWillUnmount() {
notification.destroy();
}
reload() {
const { pagination } = this.state;
const { dispatch } = this.props;
dispatch(ExchangeList(pagination.pageSize, pagination.current, this.order));
}
onSelectChange(selectedRowKeys) {
this.setState({ selectedRowKeys });
}
handleTableChange(newPagination, filters, sorter) {
const { pagination } = this.state;
if (sorter.field) {
this.order = `${sorter.field} ${sorter.order.replace('end', '')}`;
} else {
this.order = 'id';
}
pagination.current = newPagination.current;
this.setState({ pagination });
this.reload();
}
handleDelete() {
Modal.confirm({
title: 'Are you sure to delete ?',
onOk: () => {
const { dispatch } = this.props;
const { selectedRowKeys, pagination } = this.state;
if (selectedRowKeys.length > 0) {
dispatch(ExchangeDelete(
selectedRowKeys,
pagination.pageSize,
pagination.current,
this.order
));
this.setState({ selectedRowKeys: [] });
}
},
iconType: 'exclamation-circle',
});
}
handleInfoShow(info) {
if (!info.id) {
info = {
id: 0,
name: '',
type: '',
accessKey: '',
secretKey: '',
};
}
this.setState({ info, infoModalShow: true });
}
handleInfoSubmit() {
this.props.form.validateFields((errors, values) => {
if (errors) {
return;
}
const { dispatch } = this.props;
const { info, pagination } = this.state;
const req = {
id: info.id,
name: values.name,
type: values.type,
accessKey: values.accessKey,
secretKey: values.secretKey,
};
dispatch(ExchangePut(req, pagination.pageSize, pagination.current, this.order));
this.setState({ infoModalShow: false });
this.props.form.resetFields();
});
}
handleInfoCancel() {
this.setState({ infoModalShow: false });
this.props.form.resetFields();
}
render() {
const { selectedRowKeys, pagination, info, infoModalShow } = this.state;
const { exchange } = this.props;
const { getFieldDecorator } = this.props.form;
const columns = [{
title: 'Name',
dataIndex: 'name',
sorter: true,
render: (v, r) => <a onClick={this.handleInfoShow.bind(this, r)}>{String(v)}</a>,
}, {
title: 'Type',
dataIndex: 'type',
sorter: true,
}, {
title: 'CreatedAt',
dataIndex: 'createdAt',
sorter: true,
render: (v) => v.toLocaleString(),
}, {
title: 'UpdatedAt',
dataIndex: 'updatedAt',
sorter: true,
render: (v) => v.toLocaleString(),
}];
const formItemLayout = {
labelCol: { span: 7 },
wrapperCol: { span: 12 },
};
const rowSelection = {
selectedRowKeys,
onChange: this.onSelectChange,
};
return (
<div>
<div className="table-operations">
<Button type="primary" onClick={this.reload}>Reload</Button>
<Button type="ghost" onClick={this.handleInfoShow}>Add</Button>
<Button disabled={selectedRowKeys.length <= 0} onClick={this.handleDelete}>Delete</Button>
</div>
<Table rowKey="id"
columns={columns}
dataSource={exchange.list}
rowSelection={rowSelection}
pagination={pagination}
loading={exchange.loading}
onChange={this.handleTableChange}
/>
<Modal closable
maskClosable={false}
width="50%"
title={info.name ? `Exchange - ${info.name}` : 'New Exchange'}
visible={infoModalShow}
footer=""
onCancel={this.handleInfoCancel}
>
<Form horizontal>
<FormItem
{...formItemLayout}
label="Name"
>
{getFieldDecorator('name', {
rules: [{ required: true }],
initialValue: info.name,
})(
<Input />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="Type"
>
{getFieldDecorator('type', {
rules: [{ required: true }],
initialValue: info.type,
})(
<Select disabled={info.id > 0}>
{exchange.types.map((v, i) => <Option key={i} value={v}>{v}</Option>)}
</Select>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="AccessKey"
>
{getFieldDecorator('accessKey', {
rules: [{ required: true }],
initialValue: info.accessKey,
})(
<Input />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="SecretKey"
>
{getFieldDecorator('secretKey', {
rules: [{ required: true }],
initialValue: info.secretKey,
})(
<Input />
)}
</FormItem>
<Form.Item wrapperCol={{ span: 12, offset: 7 }} style={{ marginTop: 24 }}>
<Button type="primary" onClick={this.handleInfoSubmit} loading={exchange.loading}>Submit</Button>
</Form.Item>
</Form>
</Modal>
</div>
);
}
}
const mapStateToProps = (state) => ({
user: state.user,
exchange: state.exchange,
});
export default Form.create()(connect(mapStateToProps)(Exchange));
|
sb-admin-seed-react/src/vendor/recharts/demo/component/TextDemo.js | Gigasz/tropical-bears | import React, { Component } from 'react';
import { Text } from 'recharts';
class TextDemo extends Component {
state = {
exampleText: 'This is really long text',
x: 0,
y: 0,
width: 300,
height: 200,
angle: 0,
scaleToFit: false,
textAnchor: 'start',
verticalAnchor: 'start',
fontSize: '1em',
fontFamily: 'Arial',
lineHeight: '1em',
showAnchor: true,
resizeSvg: true,
};
render() {
const styles = {
exampleText: {
width: 200,
},
range: {
marginLeft: 25,
width: 275,
},
svg: {
height: 200,
display: 'block',
border: '1px solid #aaa',
marginBottom: 10,
},
};
return (
<div>
<h2>Demo</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text
x={this.state.x}
y={this.state.y}
width={this.state.width}
textAnchor={this.state.textAnchor}
verticalAnchor={this.state.verticalAnchor}
lineHeight={this.state.lineHeight}
scaleToFit={this.state.scaleToFit}
angle={this.state.angle}
style={{ fontSize: this.state.fontSize, fontFamily: this.state.fontFamily }}
>
{this.state.exampleText}
</Text>
{ this.state.showAnchor && <circle cx={this.state.x} cy={this.state.y} r="2" fill="red" /> }
</svg>
<div>
text:
<input
type="text"
style={styles.exampleText}
value={this.state.exampleText}
onChange={e => this.setState({ exampleText: e.target.value })}
/>
</div>
<div>
x: <input type="text" value={this.state.x} onChange={e => this.setState({ x: Number(e.target.value) })} />
y: <input type="text" value={this.state.y} onChange={e => this.setState({ y: Number(e.target.value) })} />
</div>
<div>
width:
<input
type="range"
style={styles.range}
min="25" max="300"
value={this.state.width}
onChange={e => this.setState({ width: Number(e.target.value) })}
/> {this.state.width}
</div>
<div>
textAnchor:
<label>
<input
type="radio"
value="start"
onChange={e => this.setState({ textAnchor: e.target.value })}
checked={this.state.textAnchor === 'start'}
/> start
</label>
<label>
<input
type="radio"
value="middle"
onChange={e => this.setState({ textAnchor: e.target.value })}
checked={this.state.textAnchor === 'middle'}
/> middle
</label>
<label>
<input
type="radio"
value="end"
onChange={e => this.setState({ textAnchor: e.target.value })}
checked={this.state.textAnchor === 'end'}
/> end
</label>
</div>
<div>
verticalAnchor:
<label>
<input
type="radio"
value="start"
onChange={e => this.setState({ verticalAnchor: e.target.value })}
checked={this.state.verticalAnchor === 'start'}
/> start
</label>
<label>
<input
type="radio"
value="middle"
onChange={e => this.setState({ verticalAnchor: e.target.value })}
checked={this.state.verticalAnchor === 'middle'}
/> middle
</label>
<label>
<input
type="radio"
value="end"
onChange={e => this.setState({ verticalAnchor: e.target.value })}
checked={this.state.verticalAnchor === 'end'}
/> end
</label>
</div>
<div>
fontSize:
<input
type="text"
value={this.state.fontSize}
onChange={e => this.setState({ fontSize: e.target.value })}
/>
</div>
<div>
fontFamily:
<input
type="text"
value={this.state.fontFamily}
onChange={e => this.setState({ fontFamily: e.target.value })}
/>
</div>
<div>
lineHeight:
<input
type="text"
value={this.state.lineHeight}
onChange={e => this.setState({ lineHeight: e.target.value })}
/>
</div>
<div>
angle:
<input
type="range"
min="0" max="360"
value={this.state.angle}
onChange={e => this.setState({ angle: Number(e.target.value) })}
/>
</div>
<div>
<label>
scaleToFit:
<input
type="checkbox"
onChange={e => this.setState({ scaleToFit: !this.state.scaleToFit })}
checked={this.state.scaleToFit}
/>
</label>
</div>
<div>
<label>
show anchor:
<input
type="checkbox"
onChange={e => this.setState({ showAnchor: !this.state.showAnchor })}
checked={this.state.showAnchor}
/>
</label>
</div>
<div>
<label>
resize svg (container):
<input
type="checkbox"
onChange={e => this.setState({ resizeSvg: !this.state.resizeSvg })}
checked={this.state.resizeSvg}
/>
</label>
</div>
<hr />
<h2>Simple</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={0} width={this.state.width} verticalAnchor="start">
{this.state.exampleText}
</Text>
</svg>
<h2>Centered</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={this.state.width / 2} width={this.state.width} verticalAnchor="start" textAnchor="middle">
{this.state.exampleText}
</Text>
</svg>
<h2>Right-aligned</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={this.state.width} width={this.state.width} verticalAnchor="start" textAnchor="end">
{this.state.exampleText}
</Text>
</svg>
<h2>Line height</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={0} width={this.state.width} verticalAnchor="start" lineHeight="2em">
{this.state.exampleText}
</Text>
</svg>
<h2>Styled text (fontWeight)</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={0} width={this.state.width} verticalAnchor="start" style={{ fontWeight: 900 }}>
{this.state.exampleText}
</Text>
</svg>
<h2>Styled (fontSize px)</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={0} width={this.state.width} verticalAnchor="start" style={{ fontSize: '24px' }}>
{this.state.exampleText}
</Text>
</svg>
<h2>Styled (fontSize em)</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={0} width={this.state.width} verticalAnchor="start" style={{ fontSize: '1.5em' }}>
{this.state.exampleText}
</Text>
</svg>
<h2>Styled (fontSize rem)</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={0} width={this.state.width} verticalAnchor="start" style={{ fontSize: '1.5rem' }}>
{this.state.exampleText}
</Text>
</svg>
<h2>Styled (fontSize %)</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={0} width={this.state.width} verticalAnchor="start" style={{ fontSize: '150%' }}>
{this.state.exampleText}
</Text>
</svg>
<h2>Fit</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text width={this.state.width} verticalAnchor="start" scaleToFit>
{this.state.exampleText}
</Text>
</svg>
</div>
);
}
}
export default TextDemo;
|
client/src/components/screenshots/takeButton/TakeButton.js | DjLeChuck/recalbox-manager | import React from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
const TakeButton = ({ t, working, onClick }) => (
<Button bsStyle="success" onClick={onClick}>
{working &&
<Glyphicon glyph="refresh" className="glyphicon-spin" />
} {t('Faire une capture')}
</Button>
);
TakeButton.propTypes = {
t: PropTypes.func.isRequired,
working: PropTypes.bool.isRequired,
onClick: PropTypes.func.isRequired,
};
TakeButton.defaultProps = {
onClick: () => {},
};
export default translate()(TakeButton);
|
src/svg-icons/action/shopping-cart.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionShoppingCart = (props) => (
<SvgIcon {...props}>
<path d="M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z"/>
</SvgIcon>
);
ActionShoppingCart = pure(ActionShoppingCart);
ActionShoppingCart.displayName = 'ActionShoppingCart';
ActionShoppingCart.muiName = 'SvgIcon';
export default ActionShoppingCart;
|
src/pages/404.js | DarylRodrigo/DarylRodrigo.github.io | import React from 'react';
import Layout from '../components/common/layout';
const NotFoundPage = () => (
<Layout>
<h1>NOT FOUND</h1>
<p>Not a valid URL</p>
</Layout>
);
export default NotFoundPage;
|
src/containers/Home/UserInfo.js | pmg1989/lms_mobile | import React from 'react'
import PropTypes from 'prop-types'
import { renderBgImage } from 'utils/tools'
import styles from './UserInfo.less'
const UserInfo = ({ avatar, firstName, school }) => {
return (
<div className={styles.user_box} style={renderBgImage(avatar)}>
<div className={styles.thumb_box}>
<img src={avatar} alt="thumb" />
<span className={styles.name}>{firstName}</span>
</div>
<div className={styles.area_name}>{school}</div>
</div>
)
}
UserInfo.propTypes = {
avatar: PropTypes.string.isRequired,
firstName: PropTypes.string.isRequired,
school: PropTypes.string.isRequired,
}
export default UserInfo
|
fields/types/Field.js | concoursbyappointment/keystoneRedux | import classnames from 'classnames';
import evalDependsOn from '../utils/evalDependsOn.js';
import React from 'react';
import { findDOMNode } from 'react-dom';
import { FormField, FormInput, FormNote } from '../../admin/client/App/elemental';
import blacklist from 'blacklist';
import CollapsedFieldLabel from '../components/CollapsedFieldLabel';
function isObject (arg) {
return Object.prototype.toString.call(arg) === '[object Object]';
}
function validateSpec (spec) {
if (!spec) spec = {};
if (!isObject(spec.supports)) {
spec.supports = {};
}
if (!spec.focusTargetRef) {
spec.focusTargetRef = 'focusTarget';
}
return spec;
}
var Base = module.exports.Base = {
getInitialState () {
return {};
},
getDefaultProps () {
return {
adminPath: Keystone.adminPath,
inputProps: {},
labelProps: {},
valueProps: {},
size: 'full',
};
},
getInputName (path) {
// This correctly creates the path for field inputs, and supports the
// inputNamePrefix prop that is required for nested fields to work
return this.props.inputNamePrefix
? `${this.props.inputNamePrefix}[${path}]`
: path;
},
valueChanged (event) {
this.props.onChange({
path: this.props.path,
value: event.target.value,
});
},
shouldCollapse () {
return this.props.collapse && !this.props.value;
},
shouldRenderField () {
if (this.props.mode === 'create') return true;
return !this.props.noedit;
},
focus () {
if (!this.refs[this.spec.focusTargetRef]) return;
findDOMNode(this.refs[this.spec.focusTargetRef]).focus();
},
renderNote () {
if (!this.props.note) return null;
return <FormNote html={this.props.note} />;
},
renderField () {
const { autoFocus, value, inputProps } = this.props;
return (
<FormInput {...{
...inputProps,
autoFocus,
autoComplete: 'off',
name: this.getInputName(this.props.path),
onChange: this.valueChanged,
ref: 'focusTarget',
value,
}} />
);
},
renderValue () {
return <FormInput noedit>{this.props.value}</FormInput>;
},
renderUI () {
var wrapperClassName = classnames(
'field-type-' + this.props.type,
this.props.className,
{ 'field-monospace': this.props.monospace }
);
return (
<FormField htmlFor={this.props.path} label={this.props.label} className={wrapperClassName} cropLabel>
<div className={'FormField__inner field-size-' + this.props.size}>
{this.shouldRenderField() ? this.renderField() : this.renderValue()}
</div>
{this.renderNote()}
</FormField>
);
},
};
var Mixins = module.exports.Mixins = {
Collapse: {
componentWillMount () {
this.setState({
isCollapsed: this.shouldCollapse(),
});
},
componentDidUpdate (prevProps, prevState) {
if (prevState.isCollapsed && !this.state.isCollapsed) {
this.focus();
}
},
uncollapse () {
this.setState({
isCollapsed: false,
});
},
renderCollapse () {
if (!this.shouldRenderField()) return null;
return (
<FormField>
<CollapsedFieldLabel onClick={this.uncollapse}>+ Add {this.props.label.toLowerCase()}</CollapsedFieldLabel>
</FormField>
);
},
},
};
module.exports.create = function (spec) {
spec = validateSpec(spec);
var field = {
spec: spec,
displayName: spec.displayName,
mixins: [Mixins.Collapse],
statics: {
getDefaultValue: function (field) {
return field.defaultValue || '';
},
},
render () {
if (!evalDependsOn(this.props.dependsOn, this.props.values)) {
return null;
}
if (this.state.isCollapsed) {
return this.renderCollapse();
}
return this.renderUI();
},
};
if (spec.statics) {
Object.assign(field.statics, spec.statics);
}
var excludeBaseMethods = {};
if (spec.mixins) {
spec.mixins.forEach(function (mixin) {
Object.keys(mixin).forEach(function (name) {
if (Base[name]) {
excludeBaseMethods[name] = true;
}
});
});
}
Object.assign(field, blacklist(Base, excludeBaseMethods));
Object.assign(field, blacklist(spec, 'mixins', 'statics'));
if (Array.isArray(spec.mixins)) {
field.mixins = field.mixins.concat(spec.mixins);
}
return React.createClass(field);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.