path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
app/javascript/mastodon/features/direct_timeline/index.js
|
salvadorpla/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import { mountConversations, unmountConversations, expandConversations } from '../../actions/conversations';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { connectDirectStream } from '../../actions/streaming';
import ConversationsListContainer from './containers/conversations_list_container';
const messages = defineMessages({
title: { id: 'column.direct', defaultMessage: 'Direct messages' },
});
export default @connect()
@injectIntl
class DirectTimeline extends React.PureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
columnId: PropTypes.string,
intl: PropTypes.object.isRequired,
hasUnread: PropTypes.bool,
multiColumn: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('DIRECT', {}));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
componentDidMount () {
const { dispatch } = this.props;
dispatch(mountConversations());
dispatch(expandConversations());
this.disconnect = dispatch(connectDirectStream());
}
componentWillUnmount () {
this.props.dispatch(unmountConversations());
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
setRef = c => {
this.column = c;
}
handleLoadMore = maxId => {
this.props.dispatch(expandConversations({ maxId }));
}
render () {
const { intl, hasUnread, columnId, multiColumn, shouldUpdateScroll } = this.props;
const pinned = !!columnId;
return (
<Column ref={this.setRef} label={intl.formatMessage(messages.title)}>
<ColumnHeader
icon='envelope'
active={hasUnread}
title={intl.formatMessage(messages.title)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
/>
<ConversationsListContainer
trackScroll={!pinned}
scrollKey={`direct_timeline-${columnId}`}
timelineId='direct'
onLoadMore={this.handleLoadMore}
emptyMessage={<FormattedMessage id='empty_column.direct' defaultMessage="You don't have any direct messages yet. When you send or receive one, it will show up here." />}
shouldUpdateScroll={shouldUpdateScroll}
/>
</Column>
);
}
}
|
src/header/Header.js
|
tsengkasing/LottoStar
|
/**
* Created by Think on 2017/5/17.
*/
import React from 'react';
import { Link } from 'react-router-dom';
import Paper from 'material-ui/Paper';
// import AutoComplete from 'material-ui/AutoComplete';
import Sign from './sign/Sign';
import Auth from '../Auth';
import './Header.css';
import logo from './lottostar.png';
export default class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false,
data_source: [],
username: 'nobody',
to_login: true,
redirect: null,
};
window.__clear = this.handleSignOut;
}
handleUpdateInput = (value) => {
this.setState({
data_source: [
value,
value + value,
value + value + value,
],
});
};
handleRequestClose = () => {
this.setState({ open: false });
};
handleSign = (tab) => {
this.refs.sign.handleOpen(tab);
};
handleRefreshStatus = () => {
let user_info = Auth.getUserInfo();
let to_login = user_info.to_login;
this.setState({
username: to_login ? 'nobody' : user_info.username,
to_login: to_login,
})
};
handleSignOut = () => {
Auth.clearUserInfo();
this.handleRefreshStatus();
// window.location.pathname = '/';
};
componentDidMount() {
this.handleRefreshStatus();
}
render() {
return (
<div className="header__background">
<Paper>
<div className="header-menu-container edge">
<div className="header-menu-welcome"><Link className="link" to="/">欢迎来到乐透星!</Link></div>
<div className="header-menu-control">
{this.state.to_login ? <div className="header-menu-item" style={{color: '#3399ff'}}
onClick={() =>this.handleSign(true)}>请登录</div> : null}
{this.state.to_login ? <div className="header-menu-item"
onClick={() =>this.handleSign(false)}>免费注册</div> : null}
{this.state.to_login ? null : <div className="header-menu-item">
<Link className="link" to="/home">{this.state.username}</Link></div>}
{this.state.to_login ? null : <div className="header-menu-item">
<Link className="link" to="/pay">购物车</Link></div>}
{this.state.to_login ? null : <div className="header-menu-item"
onClick={this.handleSignOut}>注销</div>}
</div>
</div>
</Paper>
<div className="header__bar edge">
<div className="header-logo">
<Link className="link" to="/" style={{display: 'flex', alignItems: 'center'}}>
<img src={logo} style={{width: 64}} alt="logo" />
<span style={{color: 'white', fontSize: 24}}>Lotto Star</span>
</Link>
</div>
{/*<div className="header__search">*/}
{/*<AutoComplete*/}
{/*hintText={<span style={{color: 'rgba(255, 255, 255, 0.3)'}}>请输入要搜索的商品</span>}*/}
{/*dataSource={this.state.data_source}*/}
{/*onUpdateInput={this.handleUpdateInput}*/}
{/*/>*/}
{/*</div>*/}
</div>
<Sign ref="sign" success={this.handleRefreshStatus} />
</div>
);
}
}
|
src/parser/priest/holy/modules/talents/60/ShiningForce.js
|
sMteX/WoWAnalyzer
|
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import TalentStatisticBox, { STATISTIC_ORDER } from 'interface/others/TalentStatisticBox';
import React from 'react';
// Example Log: /report/NcKyHD94nrj31tG2/10-Mythic+Zek'voz+-+Kill+(9:35)/3-旧时印月
class ShiningForce extends Analyzer {
shiningForceCasts = 0;
shiningForceHits = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.SHINING_FORCE_TALENT.id);
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.SHINING_FORCE_TALENT.id) {
this.shiningForceCasts++;
}
}
on_byPlayer_applydebuff(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.SHINING_FORCE_TALENT.id) {
this.shiningForceHits++;
}
}
statistic() {
return (
<TalentStatisticBox
talent={SPELLS.SHINING_FORCE_TALENT.id}
value={`${this.shiningForceHits} Knock Back(s)`}
position={STATISTIC_ORDER.CORE(4)}
/>
);
}
}
export default ShiningForce;
|
src/scenes/Booking/index.js
|
galsen0/hair-dv-front
|
/**
* Created by diop on 06/05/2017.
*/
import React from 'react';
import { Grid } from 'semantic-ui-react';
import ReservationCard from './components/ReservationCard/index';
import StepsReservation from './components/StepsReservation';
import CSSModules from 'react-css-modules';
import styles from './styles.scss';
class BookingContainer extends React.Component {
render(){
return (
<div styleName="BookingContainer">
<div className="textCentered">
<StepsReservation/>
<br/><br/>
<Grid columns="equal" verticalAlign={'top'}>
<Grid.Row>
<Grid.Column width={8} textAlign={"center"}>
{ this.props.children }
</Grid.Column>
<Grid.Column width={6}>
<ReservationCard/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
</Grid.Row>
</Grid>
</div>
</div>
);
}
}
export default CSSModules(BookingContainer, styles);
|
src/components/Icon/Banana.js
|
tehkaiyu/bananas
|
import React from 'react';
function Banana() {
return (
<svg
version="1.1"
className="icon-banana"
x="0px"
y="0px"
viewBox="0 0 208.6 334.7"
xmlSpace="preserve"
>
<g>
<path
fill="#DCAB2C"
d="M24.8,174.7c2.8,31.3,9.4,61.6,25.1,89.2c11.5,20,26.3,37.3,45.4,50.5c13.8,9.5,29.4,11.5,45.5,8.2
c6.2-1.3,12-4.9,18.8-3.6c1.9-1.3,1.7-2.9,0.5-4.5c-1.1-1.4-1.6-3.1-3-4.3c-0.7-0.4-1.3-0.9-2-1.3c-33-5.3-59.9-20.3-77.5-49.6
c-13.3-22.2-19.9-46.7-23.7-72c-1.8-12-2.4-24.2-2.7-36.3c-0.1-2.5,0-5.2-3.4-5.8c-2.4,0.4-3.2,2.4-4.3,4.3
c-4.6,8.6-9.2,17.4-17.6,23.2C25.2,173.2,24.9,173.9,24.8,174.7z"
/>
<path
fill="#FDE057"
d="M163.8,294.1c-11.5-14.9-20.4-31.4-31-46.8c-1.5-2.2-3-4.3-4.5-6.5c-1.6-1.9-0.9-3.6,0.6-5.2
c3.3-6.9,8.3-12.8,11.9-19.5c8.6-15.9,13.6-32.5,9.7-50.7c-2.9-13.5-10.5-23.6-23.4-29.1c-4.9-2-10.2-3.1-15.4-0.3
c-0.4,0.5-0.5,1-0.4,1.6c0.8,2,2.5,2.6,4.3,2.4c4.4-0.5,8.2,1.1,11.8,3.4c13.2,6.8,17.8,18.5,18.2,32.6c0.4,18.6-7,34.3-17.8,48.7
c-2.8,3.8-4.4,3.7-6.5-0.4c-8.4-16.8-14.7-34.2-14.4-53.4c0.1-7.5,2.3-14,6.6-20c1.5-2.1,3.7-3.9,3.6-6.9c-0.8-2.6-2.8-3.1-5.1-2.6
c-4.3,1-8.8,1.4-12.7,3.8c-1.3,0.8-2.7,2-4.5,1.2c-3.5,0.5-4.3,4.1-6.8,5.7c-2.8,5.5-4.3,11.6-6.1,17.5c-0.4,2.6-2,4.8-2.7,7.3
c-0.1,16.3,4,31.8,11.3,46.2c8.9,17.7,17.7,35.5,31,50.5c9.2,10.4,19.9,19.1,31.3,27c1.7,1.2,3.5,1.9,5.6,1.6
C164.6,300,165,299.3,163.8,294.1z"
/>
<path
fill="#FCF4C6"
d="M96.4,139.1c3.1-13.1,5.9-26.3,11.3-38.8c3.9-9.2,8.4-18.1,14.8-25.9c14.4-17.6,24.2-37.7,32-58.9
c2.4-6.6-5.7-16.6-12.8-15.5C135.7,1,130,2.9,124.2,4.3c-7.7,3.6-14.2,8.7-19.7,15.2c-1.2,1.4-2.7,2.4-2.9,4.4c0,0.5,0.1,1,0.4,1.4
c1.3,1.5,2.8,1.1,4,0c8.3-7.3,18.1-12.1,26-16.5c-7.5,3.9-16.6,8.9-24.8,15.3c-6.5,6.2-11.7,13.8-19.5,18.7
c-0.4,0.4-0.7,0.8-0.9,1.3c-1.1,4-2.9,7.8-4.9,11.4c-1.5,6.1-4.9,11.4-7,17.3c-2.6,7.2-3.7,14.7-4.3,22.3c-0.1,1.4,0,2.6,1.1,3.6
c2.8,1.1,3-1.2,3.6-2.8c6.6-20.1,18.4-36.9,32.5-52.4c4.4-4.8,9.5-8.8,14.2-13.1c5.6-5.6,11.1-11.3,16-15.1
c-6.5,5.4-13.7,12.6-20.6,20.1C107.3,49.9,96.4,63.7,90,80.3c-4.6,11.9-8.5,23.9-10.5,36.5c-0.5,3.1-2,5.9-3.4,8.8
c-0.2,0.9-0.2,1.7-0.2,2.6c-0.1,3.2-0.5,6.4-0.4,9.7c0.1,2,0.2,3.9,1.9,5.3c1.5,0.8,2.8,0.8,4.1-0.4c2.1-9.1,2.9-18.6,5.8-27.4
c4.2-12.7,9-25.1,16.5-36.4c2.3-3.4,5.8-5.5,8.2-8.6c10.3-12.9,19.9-26.3,28.5-40.5c1.6-2.4,2.8-5.1,4.4-7.5
c1.3-1.2,1.5-3.2,2.7-4.4c-1.4,1.4-1.4,3.7-3.2,4.8c-1.4,2.6-2.7,5.3-4.4,7.7c-4,6.6-8.1,13.1-12.6,19.4c-1.9,7-7.5,11.3-12.1,16.3
c-0.4,0.4-0.7,0.8-1.1,1.3c-5.7,7.8-8.4,17-11.8,25.8c-5,13.2-9,26.8-11.2,40.9c-0.3,1.6-0.2,3.3,0.2,5
C93.1,140.9,94.7,140.3,96.4,139.1z"
/>
<path
fill="#F2E4AA"
d="M12.7,172.4c2.2,2.5,4.9,2.9,7.9,1.8c5.2-2.5,7.9-7.4,11.1-11.7c7.3-9.9,13.3-20.6,15.9-32.8
c1.4-6.5,5.4-11.8,8.2-17.6c0.1-0.6,0.1-1.1,0-1.7c-2.3-4.3-6.5-6.3-10.6-8.3c-0.6,0-1.2,0-1.7,0.2c-7,4.1-11.6,10.2-13.8,17.8
c-3.7,12.5-7.4,24.9-12,37.1c-1.4,3.7-3,7.3-4.5,11C12.6,169.6,12.2,170.9,12.7,172.4z"
/>
<path
fill="#F2E4AA"
d="M4.6,160.7c1.4,3.3,3.1,6.3,5.6,8.8c2.9,0.8,3.2-1.6,3.9-3.3c5.3-12.9,11-25.7,13.7-39.6
c1.6-8.5,5.6-16.1,12.3-22c1.3-1.1,2.9-2.3,2.7-4.5c-0.8-3.5-4-4-6.7-4.9c-3.3-1-6.7-1.3-10.2-1c-0.6,0-1.2,0.2-1.8,0.5
c-4.9,4.4-7.3,10.3-9.4,16.2c-5.2,14.5-8.3,29.5-10.1,44.8C4.4,157.4,4.5,159.1,4.6,160.7z"
/>
<path
fill="#F2E4AA"
d="M102.8,24.4c6.7-6,12.1-13.5,20-18.2c0.6-0.4,0.9-1.3,1.4-2c-12.8,2.7-22.9,10-31.8,19.2
c-7.6,7.9-14.7,16.1-21.6,24.6c-2.4,0-3.9,1.5-5.2,3.4C58,63.4,51.4,75.9,46.5,89.2c-0.8,2.1-0.9,4.2-0.9,6.3
c0.4,1.6,1.4,2.5,3.1,2.6c4.3-1.4,4.5-5.9,6.3-9c4.8-8.5,9.3-17.2,14.8-25.3c8.3-12.2,17.6-23.5,28.3-33.7
C99.9,28.3,101.6,26.6,102.8,24.4z"
/>
<path
fill="#FBCF35"
d="M10.5,82c1,2.2,2.6,3.7,5.1,2.7c2.2-0.9,1.5-3,1.4-4.8c-1-12.8,0.2-25.1,6.3-36.7c1.9-3.6,4.5-6.5,7.2-9.5
c0.3-4-2.7-3.6-4.8-3c-2.4,0.7-4.8,0.6-7.2,0.7c-5,3.4-7.7,8.6-9.5,13.9c-3.3,9.8-4.3,20-1.2,30.2C8.5,77.8,9.2,80,10.5,82z"
/>
<path
fill="#FBF3C5"
d="M8.7,76.2c-2-9.9-2.5-19.8,1.1-29.5c2-5.2,4.6-9.9,9.2-13.4c4.6-1.8,9-4.5,14-5.4c8.2-6.2,23.5,2.5,25.2,12
c0.4,2.1,0.2,4.3,1.5,6.3c0.4,0.4,0.9,0.7,1.4,0.8c3.3,0.7,6.8,2.4,8.9-2c-2.5-12.7-9.9-21.3-22.3-25c-12.2-3.7-22.9-0.1-30.9,9.7
C5.3,43.6,1.8,59.4,7.5,76.8C8.2,77.3,8.6,77.1,8.7,76.2z"
/>
<path
fill="#FCF4C6"
d="M127,130.4c-2.4-0.5-4.7,0-6.9,1c0.2,1.2,1,1.6,2.1,1.8c17.1,2.9,26,13.9,29.6,30.1c0.5,2.3,0.9,4.6,1,6.9
c1.3,12.6-1.5,24.4-7.2,35.6c-0.8,1.5-1.2,3.1-1.7,4.7c-0.2,0.5-0.5,0.9-0.8,1.2c-1.3,2.2-2.3,4.5-3.6,6.7
c-0.2,0.4-0.5,0.8-0.8,1.2c-2,4-4.6,7.6-7.4,11c-0.3,0.5-0.4,0.9-0.5,1.5c0.8,3.6,2.7,2,4.3,0.8c3.8-3,7.4-6.4,9.9-10.4
c7-11.3,12.8-23.3,15.4-36.5c0.3-1.3,0.3-2.6,0.5-4c1.3-9,0.8-17.8-1.6-26.6c-3.8-13.8-13.3-21.3-26.9-24.2
C130.6,130.9,128.9,129.9,127,130.4z"
/>
<path
fill="#FBF3C5"
d="M128.5,240.2c11.9-6.3,19.9-16.5,26.2-27.9c8.5-15.4,12.2-32,9.6-49.5c-1.9-12.8-7.8-23.3-20.5-28.5
c-0.5-0.5-1-0.9-1.7-0.5c-0.8,0.4-0.7,1-0.1,1.5c0.5,0.4,1.1,0.8,1.6,1.1c13.3,8.6,16.8,21.7,17,36.4c0,2.5-0.2,4.9-0.3,7.4
c-2.3,19.7-11.2,36.3-24.5,50.7c-1.6,1.7-3.1,3.3-5.4,4.3C128.6,235.7,125.6,237.2,128.5,240.2z"
/>
<path
fill="#C5D140"
d="M163.8,294.1c-1,3.2-2.6,5.8-6.1,6.7c-1.3,1-0.8,2,0.1,2.9c7,5.4,15,8.4,23.4,10.6
c6.6,1.8,13.2,3.7,19.4,6.5c3.9-0.2,5.7-2.1,5.2-6.1c1.7-3.8,0.1-5.1-3.7-5.9C188.6,306.1,175.5,302,163.8,294.1z"
/>
<path
fill="#F1E3AA"
d="M23.6,88.7c-7.9,7.7-12.7,17.4-17.2,27.2c-4.2,9.2-6.8,18.8-6.4,29c0.2,4.7,0.8,9.3,3.2,13.4
c2.4-1.6,2.2-4.1,2.5-6.6c2.1-19.8,6.6-38.9,17.7-55.8c0.2-0.5,0.5-1.1,0.7-1.6C24.3,92.4,25.3,90.4,23.6,88.7z"
/>
<path
fill="#FCF4C6"
d="M111.9,136.5c17.1-2.8,31.1,9.7,35.7,24c5.6,17.6,2,34.1-5.8,50.2c-4.3,8.8-9.7,17-16,24.5
c1.7,1.7,1.7,1.6,3.3,0.5c1.8-1.2,1.6-3.6,3.2-4.9l0,0c2.9-3.6,6-7.1,8.5-11.1l0,0c1.8-2.2,2.7-4.8,4.2-7.1l0,0
c6.6-12.8,10.2-26.3,9-40.8c-1-10-3.7-19.5-10.5-27.2c-7.9-8.9-17.3-14.2-29.7-10.9c-0.8,0.4-1.6,0.8-2.4,1.2
C110.5,136,110.9,136.4,111.9,136.5z"
/>
<path
fill="#DFC77A"
d="M69.9,45c-2.9,0.2-5.8,0.4-8.7,0.7c-1.1,0.6-2,1.3-2.1,2.6c-0.9,8.7-5.8,15.7-9.8,23
c-3,5.4-5.2,11.1-6.7,17.1c-0.5,2-0.4,3.9,0.2,5.8c0.9,1.5,2.2,2.2,3.9,1.3c6-16.8,14-32.7,24.1-47.4C70.5,47.1,70.2,46.1,69.9,45z
"
/>
<path
fill="#F2DD8E"
d="M54.6,111.5c-2.8,4.3-6,8.5-7.1,13.6c-3.9,17.8-13.3,32.6-24.8,46.3c-0.7,0.9-1.4,1.8-2.1,2.8
c1.4,0.2,2.8,0.3,4.2,0.5c0.4-0.3,0.7-0.5,1.1-0.8c12.4-12.2,20.2-27.2,25.7-43.5c1.5-4.4,3.6-8.6,6.3-12.4
c1.3-1.8,2.6-3.5,1.5-5.9C58,110.5,56.4,110.5,54.6,111.5z"
/>
<path
fill="#8F9D2E"
d="M155.4,311.6c1.5,2.4,4.8,3.8,4.3,7.4c9.7,0.6,18.8,3.7,28,6.2c2.8,0.8,4.3,2.8,5.9,5
c0.9,1.2,1,3.4,3.4,2.9c4.3-1.9,3.1-5.5,2.7-8.9c-9.1-5.8-18.9-9.5-29.4-11.4c-2.9-0.5-5.9-1.1-8.8-1.8
C159.4,310.4,157.2,309.7,155.4,311.6z"
/>
<path
fill="#DEA921"
d="M44.1,93.6c0.4-10,5.2-18.5,9.9-26.9c3.7-6.6,6.7-13.4,7.2-21c-0.2-0.2-0.4-0.3-0.6-0.4
c-1.2-1-2.3-0.8-3.4,0.2c-0.3,6.9-2.3,13.3-6.4,19c-5.7,7.9-8.3,17.2-11.6,26.2c-0.6,0.3-0.8,0.7-0.6,1.3
C39.8,94.5,41.6,95.1,44.1,93.6z"
/>
<path
fill="#F2DD8E"
d="M42.1,100.5c-9.1,7.7-14.6,17.4-16.3,29.4c-1.3,8.9-4.7,17.3-8.5,25.5c-2.3,4.8-3.2,10.2-7,14.2
c0.5,1.3,1.3,2.2,2.4,2.9c7-14.9,12.7-30.4,16.7-46.4c2.4-9.5,7.1-17.1,15.1-22.8c0.9-1.4,0.1-2.2-1-2.9
C43,100.2,42.6,100.3,42.1,100.5z"
/>
<path
fill="#FCEDA6"
d="M113.6,133.8c21.6,0.5,34.4,11.5,38.4,33c0.3,1.5,0.5,2.9,0.8,4.4c1.7,0.6,1.8-0.3,1.5-1.6
c-1-20-14.9-37.2-34.1-38.2C117.7,131.5,115.5,132.4,113.6,133.8z"
/>
<path
fill="#F2DE90"
d="M22.9,94.9c-10.2,16.3-16,34.1-17.9,53.2c-0.3,3.5-0.4,7-1.8,10.3c0.5,0.8,0.9,1.6,1.4,2.4
c2.2-5.6,2.7-11.6,3.5-17.5c2.6-17,6.9-33.4,16.7-47.8C24.4,94.7,23.8,94.5,22.9,94.9z"
/>
<path
fill="#F0CF49"
d="M95.1,147.2c5.2,0,10.1-2.1,15.1-3c1.9-0.4,3.8-1.6,5.8-0.3c4.9,1.3,9.1-0.4,13.3-2.7
c-5.4-3.8-11.9-2.5-17.8-3.9c-2-1.9-3.4,0.5-5.1,0.7c-4.1,1.9-7.2,5-10.6,7.8C95.2,146.1,95,146.6,95.1,147.2z"
/>
<path
fill="#FCF0B0"
d="M132.2,230.9c-2.5,1-3.4,4.3-6.5,4.4c-2.8,4.1-2.5,4.6,2.5,5.6c0.2-0.2,0.3-0.4,0.3-0.6
c-0.1-2.2,1.7-3.1,3-4.3c12.5-11.1,20.7-25.1,26.5-40.5c1.9-4.9,2.6-10.3,2.6-15.6c-0.9,0.2-0.7,1.4-1.5,1.7
c-2.5,19.4-11.4,35.6-24.6,49.6C133.3,232.3,133.2,232.3,132.2,230.9z"
/>
<path
fill="#FACE37"
d="M57.2,45.5c1.1-0.1,2.3-0.1,3.4-0.2c0-14.7-14.9-24.8-29-19.7c0.7,2.6,2.5,3.2,4.9,2.9
c4.3-0.6,8.5,0.1,12.5,2C54.9,33.7,56.3,39.4,57.2,45.5z"
/>
<path
fill="#FAECA8"
d="M159.2,181.4c0.5-0.6,1-1.1,1.5-1.7c2-17.5-0.8-33.2-16.6-44c-0.4-0.3-0.6-0.7-1-1.1
c0.2-0.2,0.5-0.4,0.7-0.6c-5.2-3.2-10.9-4-16.8-3.8c5.7,1.7,11.4,3.2,16.6,6.6c11.7,7.8,15.4,19.4,16.1,32.5
C159.9,173.5,159.4,177.5,159.2,181.4z"
/>
<path
fill="#EEBE2C"
d="M49,30.3c-5.2-3.7-11.6-3.3-17.4-4.8c-5.1,1.2-9.1,4.1-12.6,7.8c3.8,0.7,7.7-2.5,11.4,0.4
C36.1,29.6,42.1,27.7,49,30.3z"
/>
<path
fill="#41231C"
d="M198.6,324.2c-0.5,2.9-1.1,5.9-1.6,8.8c3.3,3.3,5.6,1.2,7.5-1.6c1.1-1.7,1.5-3.9,2.2-5.9
c-1.6-2.5-2.5-5.7-6.5-5.2C198.4,321.2,197.7,322.4,198.6,324.2z"
/>
<path
fill="#EFE0A5"
d="M95.1,147.2c0.2-0.5,0.4-0.9,0.6-1.4c0.2-2.2,0.4-4.4,0.6-6.7c-1.3,0-2.7,0-4,0c-0.7-0.4-1.5-0.4-2.3-0.1
c-0.8,0.4-1.3,1-1.5,1.8c-0.8,2.7-1.5,5.5-1.2,8.3c0.2,1.8,0.4,3.8,2.9,3.9C91.9,151.1,93.5,149.2,95.1,147.2z"
/>
<path
fill="#5C3B33"
d="M201,320.8c1.7,1.9,2.4,4.8,5.6,4.8c1.4-4.1,2.6-8.3,1.5-13.1c-1,1-1.6,1.6-2.3,2.3
c-1.6,1.6-3.1,3.3-4.7,4.9C200.7,320,200.7,320.4,201,320.8z"
/>
<path
fill="#FAF1C3"
d="M23.6,88.7c-0.4,1.7-0.8,3.4-0.4,5.2c0.1,0.1,0.3,0.3,0.4,0.3c4.5-1.1,8.7-3.1,12.5-5.6
C31.4,84.7,28.4,84.7,23.6,88.7z"
/>
<path
fill="#FAEBA4"
d="M36.1,88.6c-5.1-0.1-8.9,3-12.9,5.3c-0.1,0.3-0.2,0.6-0.3,1c0.7,0.2,1.3,0.4,2,0.6c0.4,0.1,0.7,0.2,1.1,0.2
c2.1-1,4.3-1.3,6.6-1.3c2.6,0,5.3-0.4,6.2-3.6c0,0,0.4-0.1,0.4-0.1C38.1,90,37.1,89.3,36.1,88.6z"
/>
<path
fill="#E8D79F"
d="M8.7,76.2c-0.4,0.2-0.8,0.4-1.2,0.6c0.3,2.1,1.3,3.9,3.1,5.2C9.9,80.1,9.3,78.1,8.7,76.2z"
/>
<path
fill="#F7ECB5"
d="M106.3,138c1.7-0.2,3.4-0.5,5.1-0.7c0.2-0.3,0.3-0.5,0.5-0.7c-0.3-0.5-0.5-1-0.8-1.5
C109.3,135.6,107.4,136.2,106.3,138z"
/>
<path
fill="#FBCF35"
d="M157.8,303c0-0.7-0.1-1.4-0.1-2.1c-22.6-14.7-41.1-33.1-53.7-57.2c-6.8-13-14-25.7-18.4-39.8
c-2.7-8.7-3-17.7-4.3-26.5c1.1-4.6,0.4-9.1,0-13.7c-0.5-4.9-1.3-9.8-0.8-14.7c0.3-2.7-0.4-4.9-2.3-6.8c-0.1-4.5-0.2-9.1-0.4-13.6
c-1.8-2.4-4.3-2-6.8-1.7c-5.1,0.5-9.9,2.7-15.1,2.8c-4.1,3.3-6,8-8.2,12.5c-0.6,1.2-0.6,2.5,0.4,3.7c0.9,1.5,0.7,3.2,0.7,4.9
c0.2,32.4,5.6,63.9,18.3,93.9c13.4,31.4,36,52.5,68.8,62.5c4.1,1.3,8.3,2.4,12.5,3.6c2.2,0.6,4.2,0.8,6.3-0.2
C160.1,309.6,161.1,307.4,157.8,303z"
/>
<path
fill="#F2E4AA"
d="M48,145.8c2.9-5.1,5.5-10.4,9.1-15.1c6.3-3.4,10-8.8,12.4-15.3c-2-3.5-6-1.5-8.7-3c-0.5,0-1,0.1-1.5,0.5
c-5.4,5.3-8.3,11.9-10.7,18.9c-4.8,13.9-10.9,27.2-20.8,38.3c-1,1.1-2.3,2-1.8,3.8c5.3-2,8.4-6.4,11.4-10.8
C41.1,157.5,44.4,151.6,48,145.8z"
/>
<path
fill="#9FB43D"
d="M157.8,303c0.7,3.2-0.7,5.5-3.2,7.3c0.2,0.4,0.5,0.8,0.7,1.3c8.1,2,16.1,4,24.2,6
c5.2,1.3,10.1,3.4,14.4,6.7c1.8,1.3,3.1,1.7,4.6-0.1c0.8-1.2,1.6-2.3,2.4-3.5c0-0.3,0.1-0.7,0.1-1c-2.1-2.3-4.7-3.5-7.6-4.4
c-11.2-3.4-22.8-5.6-32.8-12.1C159.8,302.6,158.8,302.7,157.8,303z"
/>
<path
fill="#EFD98C"
d="M90.3,153.1c-1.4-4.2,0.2-8.4-0.5-12.6c-2.7-3.1-5-0.9-7.3,0.7c-0.2,0.5-0.5,1-0.7,1.5
c-2.2,3.6-1.5,7.7-1.5,11.5c0,4.4,0.4,8.8,0.7,13.2c0.1,1.4,0,3.1,2,3.4C84.8,164.6,87.7,158.9,90.3,153.1z"
/>
<path
fill="#F0E1AB"
d="M83.1,170.7c-1.9-6.6-0.9-13.3-0.7-20c0.1-2.8,0.3-5.6,0.5-8.3c-0.5-0.6-1.1-0.8-1.8-0.3
c-1,0-2,0.1-2.9,0.1c-0.1,11.8,1.8,23.5,3.2,35.2C83.7,175.6,82.4,172.9,83.1,170.7z"
/>
<path
fill="#FCEEAB"
d="M119.4,35.5c7.9-9.1,16.5-17.4,25.3-25.7c-8.9,5-15.8,12.4-23.3,18.9c-5.5,3.8-9.6,9-14,13.9
C99.2,52,90.9,61.3,85.2,72.5c-3.5,6.9-7,13.8-9.3,21.2c-0.8,2.3-1,4.8-2.7,6.7c-1,2-1.4,4.1-2,6.2c-1.2,3.8,1.3,6.3,2.9,9.2
c1.2,1.4,2.5,2.5,4.5,1.4c1.9-4.9,2.9-10.1,4.2-15.1c6.1-23.8,18.6-44.2,34.1-62.9C117.8,38,119.2,37.2,119.4,35.5z"
/>
<path
fill="#FCEEAB"
d="M83.3,141.6c2.2-0.4,4.3-0.8,6.5-1.2c0.4-0.2,0.8-0.4,1.3-0.5c1.5-13.1,5-25.7,9.1-38.2
c4-12.3,9.5-24,17.3-34.5l0,0c3.5-4,6.6-8.2,9.5-12.6c0.8-1.2,2.2-2.2,1.6-3.9c4.3-6.7,8.6-13.3,12.2-20.5c0.7-0.9,0.3-1.2-0.7-1.2
c-8.5,14-18.6,26.9-29.2,39.4c-8.3,8.9-13.2,19.7-17.8,30.7c-4.9,12-8.5,24.4-10.4,37.3C82.4,138.2,81.8,140.1,83.3,141.6z"
/>
<path
fill="#F2E4AA"
d="M72.7,99c0.4-11.9,3-23.4,7.4-34.4c1.2-3.1,2.4-6.2,3.4-9.4c-1.5-3.1-2.5-0.2-3.1,0.5
c-2.2,2.5-3.8,5.4-5.3,8.4c-6.2,12-13.6,23.5-16.6,37c0.5,3.5,4.5,3.2,5.9,5.6c1.9,0.9,3.8,1.9,5.9,2.5c1.3-0.2,1.5-1.3,1.8-2.4
C72.7,104.3,73.7,101.7,72.7,99z"
/>
<path
fill="#F2DE93"
d="M88.7,44.3c0.3,0.1,0.6,0.1,0.8,0.2c2.6-3.6,5.8-6.6,8.4-10.1c0.9-1.8,3.3-3.2,1.8-5.7
c-4.6,0.4-6.7,4.4-9.4,7.2c-13.7,14-24.2,30.3-32.9,47.8c-2.4,4.9-5.6,9.4-6.6,15c0.2,0.9,0.7,1.6,1.4,2.2c1.3,1.1,2.7,1.4,4.3,0.9
c2.8-1.5,2.6-4.7,3.6-7.1c7.1-15.9,15.1-31.2,25.4-45.2C86.8,47.7,87.3,45.8,88.7,44.3z"
/>
<path
fill="#EEBF2C"
d="M77.7,117.3c-0.7-1-1.4-2-2.2-3.1c-2.6-1.4-5.1-2.6-6.6,1.4c-4.9,4.3-8.8,9.4-11.9,15.1
c2.9,1.7,5.7-0.2,8.5-0.5c4.1-0.4,8.1-1.1,12.1-1.7c0.2-0.6,0.4-1.3,0.6-1.9C78.8,123.5,80.4,120.2,77.7,117.3z"
/>
<path
fill="#FDF7D6"
d="M77.7,117.3c0.2,3.1,0.5,6.2,0.7,9.3c2.5-2.9,2-6.6,2.6-9.9c4.9-29.3,17.7-54.8,36.7-77.3
c0.9-1.1,2.3-2.1,1.8-3.9c-20,21.7-33.8,46.7-40.7,75.4C78.2,113,78,115.2,77.7,117.3z"
/>
<path
fill="#FDF7D6"
d="M83.3,141.6c3.6-26.5,12.3-51.1,27.6-73.2c-3.2,0.7-4.1,3.7-5.7,5.8c-6.8,9.2-11.2,19.5-15.4,30.1
c-4.2,10.6-6.4,21.6-8.3,32.8c-0.3,1.6-0.3,3.3-0.4,4.9c0.6,0.1,1.2,0.2,1.8,0.3C83,142.1,83.1,141.9,83.3,141.6z"
/>
<path
fill="#FDF7D7"
d="M72.7,99c-0.4,2.6-0.8,5.3-1.2,7.9c0.2,0.6,0.5,0.6,1,0.3c0.7-2.2,1.3-4.5,2-6.7c1.8-1.8,1.1-4.7,2.8-6.5
c5.7-19.4,17-35.4,30.2-50.3c4.5-5.1,9.2-10,13.8-15c-4.8,0.7-6.7,5.1-9.5,8c-7.5,7.5-14.5,15.6-20.7,24.3
C82.8,72.7,76.9,85.4,72.7,99z"
/>
<path
fill="#F3E6B6"
d="M52.1,98.2c10.5-25,23.7-48.2,43.8-66.8c1.1-1,2.4-1.8,3.6-2.7c2.3,0.1,3.4-0.9,3-3.3
c0.1-0.3,0.2-0.6,0.3-1c-10.3,6.5-17.9,15.6-25.2,25.1C66.3,64.3,57.2,80.5,49.3,97.3c-0.3,0.2-0.5,0.4-0.5,0.7
c0,0.3,0,0.4,0.1,0.5C50.1,99.4,51.1,99,52.1,98.2z"
/>
<path
fill="#F3E6B8"
d="M88.7,44.3c-8.4,8.5-13.8,19-19.5,29.2c-4.9,8.6-9.3,17.5-12.6,27c0.7,1.2,1.7,1.5,2.9,0.9
c5-16.3,13.5-30.8,22.3-45.2c0.3-0.5,1-0.6,1.6-1C85.9,51.9,87.5,48.2,88.7,44.3z"
/>
<path
fill="#FDF6D4"
d="M117.4,67.2c-6.5,6.1-9.8,14.2-13.4,22c-6.4,13.9-10.5,28.7-13,43.8c-0.4,2.3-0.6,4.6,0,6.9
c0.4-0.2,0.9-0.5,1.3-0.7c2.9-21.4,8.9-41.9,18.9-61.2C113.2,74.3,115.4,70.8,117.4,67.2z"
/>
<path
fill="#FCEFAC"
d="M102.6,25.4c-1,1.1-2,2.2-3,3.3c-0.9,1.8-1.8,3.7-2.6,5.5c5-1.5,7.8-5.7,11.1-9.2
c9.5-7.8,20.2-13.7,31.3-19c-3.3,0.2-6.1,1.6-8.9,3C120.7,13.7,111.9,20,102.6,25.4z"
/>
<path
fill="#FDF6D3"
d="M107.9,24.9c-3.7,3.1-7.4,6.2-11.1,9.2c-2.4,3.5-6.1,6-7.3,10.4c6.1-6,12.2-12.1,18.2-18.2
C108.1,26.1,107.9,25.4,107.9,24.9z"
/>
<path
fill="#FDF6D4"
d="M128.5,50.7c-3.7,5.5-7.4,11-11.1,16.5C122.1,62.4,127.6,58.1,128.5,50.7z"
/>
<path
fill="#FCF0B4"
d="M145.1,22.2c2.8-2.5,4.3-6,6.1-9.2C147.6,15,146.4,18.6,145.1,22.2L145.1,22.2z"
/>
<path
fill="#FCF0B4"
d="M140,29.1c0.2,0.4,0.4,0.8,0.7,1.2c2.1-2.3,3.4-5.2,4.4-8.1c0,0,0,0,0,0C142.7,23.9,141.9,26.9,140,29.1z"
/>
<path
fill="#FCF4C6"
d="M59.6,101.4c-1-0.3-2-0.6-2.9-0.9c-1.3-0.3-2.5-0.7-3.8-1c-2.9,0.5-7-1.2-7.4,4c2.8,2.7,5.7,5.5,9.3,7
c5,0.3,9.4-1.8,11-5.3C64,103.4,61.8,102.4,59.6,101.4z"
/>
<path
fill="#FCEDA6"
d="M65.8,105.3c-4.1,0.9-7.5,3-11,5.3c-0.1,0.3-0.2,0.6-0.2,0.9c1.6,0.4,3.1,0.9,4.7,1.3
c0.3,0.1,0.7,0.2,1,0.2c3.9-0.1,8,0.3,9.7-4.5C69,106.9,67.6,105.9,65.8,105.3z"
/>
<path
fill="#FCEDA5"
d="M45.5,103.5c2-2.2,5.1-2.3,7.4-4c-0.2-0.4-0.5-0.9-0.7-1.3c-1,0-2.1,0.1-3.1,0.1c-3-1.8-5.3-1.8-5.9,2.4
c0.5,0.9,0.9,1.7,1.4,2.6C44.8,103.3,45.1,103.4,45.5,103.5z"
/>
<path
fill="#FCF4C5"
d="M43.1,100.7c1.7-1.4,3.6-2.5,5.9-2.4c0.1-0.3,0.2-0.6,0.3-0.9c-0.9-0.6-1.8-1.2-2.6-1.8
c-1.1-0.3-2.1-0.8-2.6-1.9c-1.8-0.9-3.6-1.9-5.4-2.8c-4.3,1.4-9.4,1-12.8,4.9c5.8,0.3,11.2,1.8,16.2,4.8
C42.5,100.6,42.8,100.6,43.1,100.7z"
/>
<path
fill="#FCEFAE"
d="M154.3,169.6c-0.5,0.5-1,1.1-1.5,1.6c1.4,13-0.9,25.4-6.5,37.2c-0.6,1.3-1,2.8-1.5,4.2
C152.6,199.3,156.2,185.1,154.3,169.6z"
/>
<path
fill="#FCF0B1"
d="M140.7,219.8c-3.3,3.4-6.3,6.9-8.5,11.1C136,227.9,138.9,224.3,140.7,219.8z"
/>
<path
fill="#FCEFAE"
d="M144.8,212.7c-2.1,2-3.3,4.5-4.2,7.1C143,218,144.1,215.4,144.8,212.7z"
/>
<path
fill="#FCF3C4"
d="M70,108.5c-3.4,1.1-6.9,2.1-9.7,4.5c2.4,2.5,5.6,2.3,8.7,2.5c2.1-0.9,4.2-1.6,6.6-1.4
c-1.6-2.1-2.9-4.3-3.1-7c-0.3-0.1-0.7-0.2-1-0.3C71,107.5,70.5,108,70,108.5z"
/>
<path
fill="#FCF3C4"
d="M77.3,94c-1.9,1.7-2.1,4.2-2.8,6.5C76.4,98.8,76.6,96.3,77.3,94z"
/>
</g>
</svg>
);
}
export default Banana;
|
test/FormGroupSpec.js
|
RichardLitt/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import FormGroup from '../src/FormGroup';
import {shouldWarn} from './helpers';
describe('FormGroup', function() {
it('renders children', function() {
let instance = ReactTestUtils.renderIntoDocument(
<FormGroup>
<span className='child1' />
<span className='child2' />
</FormGroup>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'child1'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'child2'));
});
it('renders with form-group class', function() {
let instance = ReactTestUtils.renderIntoDocument(
<FormGroup>
<span />
</FormGroup>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group'));
});
it('renders form-group with sm or lg class when bsSize is small or large', function () {
let instance = ReactTestUtils.renderIntoDocument(
<FormGroup bsSize="small">
<span />
</FormGroup>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group-sm'));
instance = ReactTestUtils.renderIntoDocument(
<FormGroup bsSize="large">
<span />
</FormGroup>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group-lg'));
});
// This test case must come first, since the error only gets logged once.
it('throws no warning without bsSize when standalone', function () {
ReactTestUtils.renderIntoDocument(
<FormGroup standalone />
);
// Warning thrown above would lead to failure from index.
});
it('throws warning about bsSize when standalone', function () {
ReactTestUtils.renderIntoDocument(
<FormGroup standalone bsSize="large" />
);
shouldWarn('Failed propType: bsSize');
});
it('renders no form-group class when standalone', function() {
let instance = ReactTestUtils.renderIntoDocument(
<FormGroup standalone>
<span />
</FormGroup>
);
assert.equal(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'form-group').length, 0);
});
it('renders no form-group-* class when standalone', function () {
let instance = ReactTestUtils.renderIntoDocument(
<FormGroup standalone bsSize="large" />
);
assert.equal(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'form-group').length, 0);
assert.equal(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'form-group-lg').length, 0);
});
[{
className: 'has-feedback',
props: { hasFeedback: true }
}, {
className: 'has-success',
props: { bsStyle: 'success' }
}, {
className: 'has-warning',
props: { bsStyle: 'warning' }
}, {
className: 'has-error',
props: { bsStyle: 'error' }
}, {
className: 'custom-group',
props: { groupClassName: 'custom-group' }
}
].forEach(function(testCase) {
it(`does not render ${testCase.className} class`, function() {
let instance = ReactTestUtils.renderIntoDocument(
<FormGroup>
<span />
</FormGroup>
);
assert.equal(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, testCase.className).length, 0);
});
it(`renders with ${testCase.className} class`, function() {
let instance = ReactTestUtils.renderIntoDocument(
<FormGroup {...testCase.props}>
<span />
</FormGroup>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, testCase.className));
});
});
});
|
src/components/TextInputCSSModules/TextInputCSSModules.js
|
patchygreen/ps-react-patchygreen
|
import React from 'react';
import PropTypes from 'prop-types';
import Label from '../Label';
import styles from './textInput.css';
/** Text input with integrated label to enforce consistency in layout, error display, label placement */
function TextInputCSSModules({htmlId, name, label, type = 'text', required = false, onChange, placeholder, value, error, children, ...props}) {
return (
<div className={styles.fieldset}>
<Label htmlFor={htmlId} label={label} required={required} />
<input
id={htmlId}
type={type}
name={name}
placeholder={placeholder}
value={value}
onChange={onChange}
className={error && styles.inputError}
{...props}
/>
{children}
{error && <div className={styles.error}>{error}</div>}
</div>
);
};
TextInputCSSModules.propTypes = {
/** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */
htmlId: PropTypes.string.isRequired,
/** Input name. Recommend setting this to match object's property so a single change handler can be used.*/
name: PropTypes.string.isRequired,
/** Input label. */
label: PropTypes.string.isRequired,
/** Input type */
type: PropTypes.oneOf(['text', 'number', 'password']),
/** Mark label with asterisk if set to true */
required: PropTypes.bool,
/** Function to call onChange */
onChange: PropTypes.func.isRequired,
/** Placeholder to display when empty. */
placeholder: PropTypes.string,
/** Value */
value: PropTypes.any,
/** String to display when error occurs */
error: PropTypes.string,
/** Child component to display next to the input */
children: PropTypes.node
};
export default TextInputCSSModules;
|
Paths/React/05.Building Scalable React Apps/9-react-boilerplate-building-scalable-apps-m9-exercise-files/Before/app/app.js
|
phiratio/Pluralsight-materials
|
/**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
import 'babel-polyfill';
/* eslint-disable import/no-unresolved */
// Load the manifest.json file and the .htaccess file
import '!file?name=[name].[ext]!./manifest.json';
import 'file?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved */
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import useScroll from 'react-router-scroll';
import LanguageProvider from 'containers/LanguageProvider';
import configureStore from './store';
// Import i18n messages
import { translationMessages } from './i18n';
// Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder
import 'sanitize.css/sanitize.css';
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);
// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
import { selectLocationState } from 'containers/App/selectors';
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: selectLocationState(),
});
// Set up the router, wrapping all Routes in the App component
import App from 'containers/App';
import createRoutes from './routes';
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
};
const render = (translatedMessages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={translatedMessages}>
<Router
history={history}
routes={rootRoute}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(useScroll())
}
/>
</LanguageProvider>
</Provider>,
document.getElementById('app')
);
};
// Hot reloadable translation json files
if (module.hot) {
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept('./i18n', () => {
render(translationMessages);
});
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
Promise.all([
System.import('intl'),
System.import('intl/locale-data/jsonp/en.js'),
]).then(() => render(translationMessages));
} else {
render(translationMessages);
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
import { install } from 'offline-plugin/runtime';
install();
|
ui/src/pages/PeopleManagePage/IfiEditor/index.js
|
LearningLocker/learninglocker
|
import React from 'react';
import PropTypes from 'prop-types';
import { compose, setPropTypes, defaultProps } from 'recompose';
import IfiAccountEditor from './IfiAccountEditor';
import IfiMboxEditor from './IfiMboxEditor';
import IfiMboxShaEditor from './IfiMboxShaEditor';
import IfiOpenIdEditor from './IfiOpenIdEditor';
const enhance = compose(
setPropTypes({
identifierType: PropTypes.oneOf(['mbox', 'mbox_sha1sum', 'openid', 'account']).isRequired,
value: PropTypes.any.isRequired,
onChange: PropTypes.func.isRequired,
onSave: PropTypes.func.isRequired,
refFirstInput: PropTypes.func,
}),
defaultProps({
refFirstInput: () => { },
})
);
const render = ({ identifierType, value, onChange, onSave, refFirstInput }) => {
switch (identifierType) {
case 'account': return (
<IfiAccountEditor
value={value}
onChange={onChange}
onSave={onSave}
refHomePageInput={refFirstInput} />
);
case 'mbox': return (
<IfiMboxEditor
value={value}
onChange={onChange}
onSave={onSave}
refValueInput={refFirstInput} />
);
case 'openid': return (
<IfiOpenIdEditor
value={value}
onChange={onChange}
onSave={onSave}
refValueInput={refFirstInput} />
);
case 'mbox_sha1sum': return (
<IfiMboxShaEditor
value={value}
onChange={onChange}
onSave={onSave}
refValueInput={refFirstInput} />
);
default: return (
<span>Unknown identifier type {identifierType}</span>
);
}
};
export default enhance(render);
|
Magistrate/client/components/roles/roleSelector.js
|
Pondidum/Magistrate
|
import React from 'react'
import SelectorDialog from '../SelectorDialog'
var RoleSelector = React.createClass({
open() {
this.refs.dialog.open();
},
render() {
return (
<SelectorDialog
name="Roles"
collectionUrl="/api/roles/all"
ref="dialog"
{...this.props}
/>
);
}
});
export default RoleSelector
|
packages/@lyra/form-builder/src/FormBuilder.js
|
VegaPublish/vega-studio
|
import PropTypes from 'prop-types'
import React from 'react'
import {FormBuilderInput} from './FormBuilderInput'
import FormBuilderContext from './FormBuilderContext'
// Todo: consider deprecating this in favor of <FormBuilderContext ...><FormBuilderInput .../></FormBuilderContext>
export default class FormBuilder extends React.Component {
static createPatchChannel = FormBuilderContext.createPatchChannel
static propTypes = {
value: PropTypes.any,
schema: PropTypes.object.isRequired,
type: PropTypes.object.isRequired,
path: PropTypes.array,
onChange: PropTypes.func.isRequired,
patchChannel: PropTypes.shape({
onPatch: PropTypes.func
}).isRequired,
resolveInputComponent: PropTypes.func.isRequired,
resolvePreviewComponent: PropTypes.func.isRequired
}
static defaultProps = {
value: undefined
}
render() {
const {
schema,
value,
type,
path = [],
onChange,
resolveInputComponent,
resolvePreviewComponent,
patchChannel
} = this.props
if (!schema) {
throw new TypeError('You must provide a schema to <FormBuilder (...)')
}
return (
<FormBuilderContext
schema={schema}
value={value}
resolveInputComponent={resolveInputComponent}
resolvePreviewComponent={resolvePreviewComponent}
patchChannel={patchChannel}
>
<FormBuilderInput
path={path}
value={value}
type={type}
onChange={onChange}
level={0}
isRoot
/>
</FormBuilderContext>
)
}
}
|
app/javascript/mastodon/components/load_pending.js
|
primenumber/mastodon
|
import React from 'react';
import { FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
export default class LoadPending extends React.PureComponent {
static propTypes = {
onClick: PropTypes.func,
count: PropTypes.number,
}
render() {
const { count } = this.props;
return (
<button className='load-more load-gap' onClick={this.props.onClick}>
<FormattedMessage id='load_pending' defaultMessage='{count, plural, one {# new item} other {# new items}}' values={{ count }} />
</button>
);
}
}
|
Tests/Components/FullButtonTest.js
|
tk1cntt/KanjiMaster
|
import test from 'ava'
import React from 'react'
import FullButton from '../../App/Components/FullButton'
import { shallow } from 'enzyme'
test('component exists', t => {
const wrapper = shallow(<FullButton onPress={() => {}} text='hi' />)
t.is(wrapper.length, 1) // exists
})
test('component structure', t => {
const wrapper = shallow(<FullButton onPress={() => {}} text='hi' />)
t.is(wrapper.name(), 'TouchableOpacity') // the right root component
t.is(wrapper.children().length, 1) // has 1 child
t.is(wrapper.children().first().name(), 'Text') // that child is Text
})
test('onPress', t => {
let i = 0 // i guess i could have used sinon here too... less is more i guess
const onPress = () => i++
const wrapper = shallow(<FullButton onPress={onPress} text='hi' />)
t.is(wrapper.prop('onPress'), onPress) // uses the right handler
t.is(i, 0)
wrapper.simulate('press')
t.is(i, 1)
})
|
resources/assets/js/components/lista-tipos/containers/ListaTipos.js
|
Uminks/Restaurant-Manager
|
import React, { Component } from 'react';
import RenderTipos from '../components/RenderTipos';
import ListaPlatos from '../../lista-platos/containers/ListaPlatos';
function ListaTipos(props) {
return (
<div id="inicio" className="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<ul>
{
props.lista.map((menu) => {
return(
<RenderTipos
{...menu}
key={menu.id}
handleDelete = {props.handleDelete}
handleShowPlatos = {props.handleShowPlatos}
/>
)
})
}
</ul>
<ListaPlatos platos={props.platos}/>
</div>
);
}
export default ListaTipos;
|
blueocean-material-icons/src/js/components/svg-icons/image/tonality.js
|
jenkinsci/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const ImageTonality = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.94-.49-7-3.85-7-7.93s3.05-7.44 7-7.93v15.86zm2-15.86c1.03.13 2 .45 2.87.93H13v-.93zM13 7h5.24c.25.31.48.65.68 1H13V7zm0 3h6.74c.08.33.15.66.19 1H13v-1zm0 9.93V19h2.87c-.87.48-1.84.8-2.87.93zM18.24 17H13v-1h5.92c-.2.35-.43.69-.68 1zm1.5-3H13v-1h6.93c-.04.34-.11.67-.19 1z"/>
</SvgIcon>
);
ImageTonality.displayName = 'ImageTonality';
ImageTonality.muiName = 'SvgIcon';
export default ImageTonality;
|
src/components/listButton/index.js
|
jiriKuba/Calculatic
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, View, StyleSheet } from 'react-native';
class ListButton extends Component {
render() {
const { buttonTitle, onListButtonPress } = this.props;
return (
<View style={styles.listButton}>
<Button title={buttonTitle}
onPress={onListButtonPress} />
</View>
);
}
}
ListButton.propTypes = {
onListButtonPress: PropTypes.func.isRequired,
buttonTitle: PropTypes.string.isRequired,
};
const styles = StyleSheet.create({
listButton: {
marginTop: 10,
},
});
export default ListButton;
|
src/components/episode_detail.js
|
renedaniel/Viewer
|
import React from 'react';
import {Row, Col, MediaBox} from 'react-materialize';
import Loading from './loading';
const EpisodeDetail = ({episode}) => {
if (!episode) {
return <Loading error={false} />;
}
const titulo = episode.title_episode;
const descripcion = episode.description_large;
const imgUrl = episode.image_still;
const duracion = episode.duration;
const anio = episode.year;
const rating = episode.rating_code;
return (
<Row>
<div id="video" />
<Col s={12}>
<h3 className="titulo-episodio" >{titulo}</h3>
</Col>
<Col s={12}>
<img src={imgUrl} className="responsive-img episode" alt="Imagen preview"/>
</Col>
<Col s={12} className="left-align">
<Col s={12}>
<p>{duracion} || {anio} || {rating}</p>
</Col>
<Col s={12}>
<p>{descripcion}</p>
</Col>
</Col>
</Row>
);
};
export default EpisodeDetail;
|
app/containers/App.js
|
renjithgr/bootbar
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import downloadFile from '../actions/download';
export class App extends Component {
componentDidMount() {
console.log(this.props);
// this.props.loadInitialData();
}
downloadFile() {
this.props.downloadFile();
}
render() {
return (
<button onClick={ this.downloadFile.bind(this) }> DOWNLOAD </button>
);
}
}
const mapStateToProps = (state) => {
console.log(state);
return {};
// return {
// dataLoaded: state.dataLoaded,
// tabs: state.configData ? state.configData.tabs : null
// };
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
downloadFile: () => dispatch(downloadFile())
};
};
const AppConnectedContainer = connect(mapStateToProps, mapDispatchToProps)(App);
export default AppConnectedContainer;
export { mapStateToProps, mapDispatchToProps };
|
pkg/ui/src/components/Header.js
|
matt-deboer/kuill
|
import React from 'react'
import AppBar from 'material-ui/AppBar'
import { Toolbar, ToolbarGroup, ToolbarSeparator } from 'material-ui/Toolbar'
import { grey200, grey300, grey800, blueA200 } from 'material-ui/styles/colors'
import { typography } from 'material-ui/styles'
import { Link } from 'react-router-dom'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import { routerActions } from 'react-router-redux'
import { clearErrors, clearLatestError } from '../state/actions/errors'
import { invalidateSession } from '../state/actions/session'
import { objectEmpty } from '../comparators'
import Avatar from 'react-avatar'
import Badge from 'material-ui/Badge'
import IconButton from 'material-ui/IconButton'
import IconError from 'material-ui/svg-icons/action/info'
import RaisedButton from 'material-ui/FlatButton'
import Popover from 'material-ui/Popover'
import Menu from 'material-ui/Menu'
import MenuItem from 'material-ui/MenuItem'
import IconLogout from 'material-ui/svg-icons/action/power-settings-new'
import IconFilters from 'material-ui/svg-icons/content/filter-list'
import { defaultFetchParams } from '../utils/request-utils'
import Breadcrumbs from './Breadcrumbs'
import ErrorsDialog from './ErrorsDialog'
import FiltersDialog from './FiltersDialog'
import Snackbar from 'material-ui/Snackbar'
import './Header.css'
const mapStateToProps = function(store) {
return {
user: store.session.user,
errors: store.errors.errors,
latestError: store.errors.latestError,
location: store.routing.location,
editing: store.resources.editing,
selectedNamespaces: store.usersettings.selectedNamespaces,
selectedKinds: store.usersettings.selectedKinds,
}
}
const mapDispatchToProps = function(dispatch) {
return {
clearError: function(error) {
dispatch(clearErrors(error))
},
clearAllErrors: function(errors) {
dispatch(clearErrors(...errors))
},
navigateHome: function() {
dispatch(routerActions.push('/'))
},
invalidateSession: function() {
dispatch(invalidateSession())
},
clearLatestError: function() {
dispatch(clearLatestError())
},
}
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps) (
class Header extends React.Component {
constructor(props) {
super(props)
this.state = {
open: false,
profileOpen: false,
filtersOpen: false,
latestErrorOpen: !!props.latestError,
latestError: props.latestError,
location: props.location,
}
this.handleLatestErrorRequestClose = this.handleLatestErrorRequestClose.bind(this)
this.handleProfileTouchTap = this.handleProfileTouchTap.bind(this)
this.handleOpenFilters = this.handleOpenFilters.bind(this)
this.handleCloseFilters = this.handleCloseFilters.bind(this)
this.requestVersion().then(version=> {
this.setState({version: version})
})
}
handleLatestErrorRequestClose = () => {
this.setState({
latestErrorOpen: false,
})
this.props.clearLatestError()
}
handleOpen = () => {
this.setState({
open: true,
profileOpen: false,
})
}
handleClose = () => {
this.setState({open: false})
}
handleOpenFilters = () => {
this.setState({
open: false,
filtersOpen: true,
profileOpen: false,
})
}
handleCloseFilters = () => {
this.setState({filtersOpen: false})
}
handleProfileTouchTap = (event) => {
// This prevents ghost click.
event.preventDefault();
this.setState({
profileOpen: true,
profileAnchor: event.currentTarget,
})
}
requestVersion = async () => {
return fetch('/version', defaultFetchParams
).then(resp => {
if (resp.ok) {
return resp.text()
}
}).then(version => {
if (version) {
let parts = version.split(/-|\+/)
version = parts.slice(0,2).join('-')
if (parts.length > 2) {
version += '+'
}
}
return version
})
}
handleProfileRequestClose = () => {
this.setState({profileOpen: false})
}
handleLogout = () => {
this.props.invalidateSession()
this.setState({
profileOpen: false,
filtersOpen: false,
open: false,
})
}
componentWillReceiveProps = (props) => {
let nextState = {}
if (this.state.open && props.errors.length === 0) {
nextState.open = false
}
if (props.latestError !== this.state.latestError) {
nextState.latestError = props.latestError
if (!props.editing) {
nextState.latestErrorOpen = !!props.latestError
}
}
if (props.location !== this.state.location) {
nextState.previousLocation = this.state.location
nextState.location = props.location
}
if (Object.keys(nextState).length > 0) {
this.setState(nextState)
}
}
shouldComponentUpdate = (nextProps, nextState) => {
return nextProps.latestError !== this.props.latestError
|| nextProps.errors.length !== this.props.errors.length
|| nextProps.user !== this.props.user
|| nextProps.location.pathname !== this.props.location.pathname
|| nextState.open !== this.state.open
|| nextState.latestErrorOpen !== this.state.latestErrorOpen
|| nextState.previousLocation !== this.state.previousLocation
|| nextState.profileOpen !== this.state.profileOpen
|| nextState.filtersOpen !== this.state.filtersOpen
}
render() {
const styles = {
appBar: {
position: 'fixed',
top: 0,
overflow: 'hidden',
maxHeight: 57,
width: '100%',
paddingLeft: 40,
paddingRight: 30,
backgroundColor: grey800,
},
menu: {
backgroundColor: 'transparent',
color: grey200,
fontSize: 18,
fontWeight: 600,
},
menuButtonLabel: {
textTransform: 'none',
color: grey300,
},
iconsRightContainer: {
marginLeft: 20
},
name: {
fontSize: '18px',
color: typography.textFullWhite,
lineHeight: '58px',
backgroundColor: grey800,
height: 56,
overflow: 'none',
},
avatar: {
marginRight: 10,
},
snackbar: {
right: 10,
top: 65,
transform: 'translate3d(0px, 0px, 0px)',
transition: '-webkit-transform 225ms cubic-bezier(0, 0, 0.2, 1) 0ms',
bottom: 'auto',
left: 'auto',
zIndex: 15000,
},
logo: {
backgroundImage: `url(${require('../images/logo_small.png')})`,
backgroundSize: '70px 27px',
backgroundPosition: '15px 10px',
backgroundRepeat: 'no-repeat',
backgroundColor: 'rgb(33,33,33)',
height: 55,
borderTop: '3px solid rgb(41, 121, 255)',
textAlign: 'right',
fontSize: 14,
color: 'rgb(180,180,180)',
lineHeight: '60px',
paddingRight: 15,
},
profileMenu: {
background: 'white',
padding: 0,
display: 'block'
},
}
let { props } = this
let { selectedNamespaces, selectedKinds } = props
let filtersActive = !objectEmpty(selectedNamespaces) || !objectEmpty(selectedKinds)
return (
<AppBar
iconStyleLeft={{marginTop: 8, marginRight: 4, marginLeft: -10}}
iconElementLeft={
<Link to={'/'}>
<RaisedButton
icon={<Avatar
src={require('../images/kubernetes-logo.svg')}
size={30}
style={{background: 'transparent', marginTop: -4}}
/>}
style={{marginTop: 4}}
className={'menu-button'}
labelStyle={styles.menuButtonLabel}
data-rh={'Home'}
data-rh-at={'bottom'}
data-rh-cls={'menu-button-rh'}
/>
</Link>
}
style={{...props.styles, ...styles.appBar}}
title={
<Toolbar style={{...styles.menu}}>
<ToolbarGroup firstChild={true}>
<ToolbarSeparator className="separator-bar"/>
{
props.menu.map(menuItem =>
<Link to={menuItem.link} key={menuItem.name} id={`goto-${menuItem.link.replace(/^([^\w]*)([\w-]+)(.*)$/,'$2')}`}>
<RaisedButton
label={menuItem.name}
icon={menuItem.icon}
className={'menu-button'}
labelStyle={styles.menuButtonLabel}
data-rh={menuItem.name}
data-rh-at={'bottom'}
data-rh-cls={'menu-button-rh'}
/>
</Link>)
}
<ToolbarSeparator className="separator-bar"/>
<RaisedButton
label={'Filters'}
icon={<IconFilters/>}
className={`menu-button filters${filtersActive ? ' active':''}`}
labelStyle={styles.menuButtonLabel}
data-rh={`Filters${filtersActive ? ' (active)' : '' }`}
data-rh-at={'bottom'}
data-rh-cls={'menu-button-rh'}
onTouchTap={this.handleOpenFilters}
/>
{props.location.pathname !== '/' &&
<ToolbarSeparator className="separator-bar"/>
}
{props.location.pathname !== '/' &&
<Breadcrumbs location={props.location} previousLocation={this.state.previousLocation}/>
}
</ToolbarGroup>
<ToolbarGroup lastChild={true}>
{props.errors.length > 0 &&
<Badge
badgeContent={props.errors.length}
primary={true}
badgeStyle={{top: 32, right: 16, height: 18, width: 18, zIndex: 2}}
>
<IconButton
iconStyle={{height: 36, width: 36}}
onTouchTap={this.handleOpen}
data-rh={'Dashboard Errors'}
data-rh-at={'bottom'}
>
<IconError />
</IconButton>
</Badge>
}
<RaisedButton
className="profile"
label={props.user}
labelPosition="before"
onTouchTap={this.handleProfileTouchTap}
icon={<Avatar email={props.user} name={props.user} color={blueA200} round={true} size={32} style={styles.avatar}/>}
labelStyle={{textTransform: 'none', color: '#9e9e9e'}}
style={{margin: 0}}
/>
<Popover
open={this.state.profileOpen}
anchorEl={this.state.profileAnchor}
onRequestClose={this.handleProfileRequestClose}
anchorOrigin={{horizontal: 'right', vertical: 'bottom'}}
targetOrigin={{horizontal: 'right', vertical: 'top'}}
style={{backgroundColor: 'rgb(33,33,33)'}}
zDepth={4}
>
<Menu
desktop={false}
className={'profile-menu'}
style={styles.profileMenu}
>
<MenuItem primaryText="Log out"
leftIcon={<IconLogout/>}
onTouchTap={this.handleLogout}
className={'logout'}
/>
</Menu>
<div style={styles.logo}>
{this.state.version}
</div>
</Popover>
</ToolbarGroup>
</Toolbar>
}>
<ErrorsDialog open={this.state.open} handleClose={this.handleClose}/>
<FiltersDialog open={this.state.filtersOpen && this.props.user}
handleClose={this.handleCloseFilters}/>
<Snackbar
className="error-bar"
style={styles.snackbar}
open={this.state.latestErrorOpen}
message={!!this.props.latestError ? this.props.latestError.message : ''}
autoHideDuration={5000}
onRequestClose={this.handleLatestErrorRequestClose}
action={!!this.props.latestError ? this.props.latestError.retry.text : ''}
onActionTouchTap={!!this.props.latestError ? this.props.latestError.retry.action : null}
/>
</AppBar>
)
}
}))
|
src/app/core/atoms/icon/icons/graph.js
|
blowsys/reservo
|
import React from 'react'; const Graph = (props) => <svg {...props} viewBox="0 0 24 24"><g><g><polygon points="8.42072818 16 19 16 19 18 5 18 5 7 7 7 7 14.5923011 11.9914126 9.60088846 13.9794087 11.5888846 18.2754001 7.29289322 19.6896137 8.70710678 13.9794087 14.4173117 11.9914126 12.4293156"/></g></g></svg>; export default Graph;
|
jenkins-design-language/src/js/components/material-ui/svg-icons/image/filter-9.js
|
alvarolobato/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const ImageFilter9 = (props) => (
<SvgIcon {...props}>
<path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zM15 5h-2c-1.1 0-2 .89-2 2v2c0 1.11.9 2 2 2h2v2h-4v2h4c1.1 0 2-.89 2-2V7c0-1.11-.9-2-2-2zm0 4h-2V7h2v2z"/>
</SvgIcon>
);
ImageFilter9.displayName = 'ImageFilter9';
ImageFilter9.muiName = 'SvgIcon';
export default ImageFilter9;
|
react/src/containers/AncestryApp/SerializedAncestry/index.js
|
sinfin/folio
|
import React from 'react'
function SerializedItem ({ item, index }) {
const prefix = `ancestry[${index + 1}]`
const name = (field) => `${prefix}[${field}]`
return (
<div>
<input type='hidden' name={name('id')} value={item.id} />
<input type='hidden' name={name('position')} value={index + 1} />
<input type='hidden' name={name('parent_id')} value={item.parentId || ''} />
</div>
)
}
const flatItems = (items) => {
const flat = []
const get = (item, parentId) => {
flat.push({ ...item, parentId })
item.children.forEach((child) => get(child, item.id))
}
items.forEach((item) => get(item, null))
return flat
}
function SerializedAncestry ({ ancestry }) {
let i = -1
const index = () => { i++; return i }
return (
<div hidden>
{flatItems(ancestry.items).map((item) => (
<SerializedItem
key={item.id}
item={item}
index={index()}
/>
))}
</div>
)
}
export default SerializedAncestry
|
src/components/ImageSlider/index.js
|
jiangxy/react-antd-admin
|
import React from 'react';
import './index.less';
/**
* 图片走马灯, 基本是抄的这个: https://github.com/xiaolin/react-image-gallery
* 写样式真是太痛苦了...臣妾真的做不到啊...
*/
class ImageSlider extends React.PureComponent {
state = {
previousIndex: 0,
currentIndex: 0,
};
componentWillMount() {
this.navButton = (
<span key="navigation">
<button type="button" className="image-gallery-left-nav" onClick={this.slideLeft}/>
<button type="button" className="image-gallery-right-nav" onClick={this.slideRight}/>
</span>
);
}
componentWillReceiveProps() {
// 每次从外界传新的图片过来时, 都要还原状态
this.state.currentIndex = 0;
this.state.previousIndex = 0;
}
/**
* 滑动到指定index
*/
slideToIndex(index) {
const {currentIndex} = this.state;
const slideCount = this.props.items.length - 1;
let nextIndex = index;
if (index < 0) {
nextIndex = slideCount;
} else if (index > slideCount) {
nextIndex = 0;
}
this.setState({
previousIndex: currentIndex,
currentIndex: nextIndex,
});
}
slideLeft = () => this.slideToIndex(this.state.currentIndex - 1);
slideRight = () => this.slideToIndex(this.state.currentIndex + 1);
/**
* 将传入的item(一张图片)转换为react元素
*/
renderItem(item) {
return (
<div className="image-gallery-image">
<img src={item.url} alt={item.alt}/>
{ item.description && <span className="image-gallery-description">{item.description}</span> }
</div>
);
}
/*下面这3个方法真心是改不动...css真的苦手...*/
_getAlignmentClassName(index) {
// LEFT, and RIGHT alignments are necessary for lazyLoad
let {currentIndex} = this.state;
let alignment = '';
const LEFT = 'left';
const CENTER = 'center';
const RIGHT = 'right';
switch (index) {
case (currentIndex - 1):
alignment = ` ${LEFT}`;
break;
case (currentIndex):
alignment = ` ${CENTER}`;
break;
case (currentIndex + 1):
alignment = ` ${RIGHT}`;
break;
}
if (this.props.items.length >= 3) {
if (index === 0 && currentIndex === this.props.items.length - 1) {
// set first slide as right slide if were sliding right from last slide
alignment = ` ${RIGHT}`;
} else if (index === this.props.items.length - 1 && currentIndex === 0) {
// set last slide as left slide if were sliding left from first slide
alignment = ` ${LEFT}`;
}
}
return alignment;
}
_getTranslateXForTwoSlide(index) {
// For taking care of infinite swipe when there are only two slides
// 这个offsetPercentage本来是state中的, 但其实根本没用到, 固定是0
// 从state中删除后, 不想改这个方法的代码, 索性直接给个默认值
const {currentIndex, offsetPercentage = 0, previousIndex} = this.state;
const baseTranslateX = -100 * currentIndex;
let translateX = baseTranslateX + (index * 100) + offsetPercentage;
// keep track of user swiping direction
if (offsetPercentage > 0) {
this.direction = 'left';
} else if (offsetPercentage < 0) {
this.direction = 'right';
}
// when swiping make sure the slides are on the correct side
if (currentIndex === 0 && index === 1 && offsetPercentage > 0) {
translateX = -100 + offsetPercentage;
} else if (currentIndex === 1 && index === 0 && offsetPercentage < 0) {
translateX = 100 + offsetPercentage;
}
if (currentIndex !== previousIndex) {
// when swiped move the slide to the correct side
if (previousIndex === 0 && index === 0 &&
offsetPercentage === 0 && this.direction === 'left') {
translateX = 100;
} else if (previousIndex === 1 && index === 1 &&
offsetPercentage === 0 && this.direction === 'right') {
translateX = -100;
}
} else {
// keep the slide on the correct slide even when not a swipe
if (currentIndex === 0 && index === 1 &&
offsetPercentage === 0 && this.direction === 'left') {
translateX = -100;
} else if (currentIndex === 1 && index === 0 &&
offsetPercentage === 0 && this.direction === 'right') {
translateX = 100;
}
}
return translateX;
}
_getSlideStyle(index) {
const {currentIndex, offsetPercentage = 0} = this.state;
const {items} = this.props;
const baseTranslateX = -100 * currentIndex;
const totalSlides = items.length - 1;
// calculates where the other slides belong based on currentIndex
let translateX = baseTranslateX + (index * 100) + offsetPercentage;
// adjust zIndex so that only the current slide and the slide were going
// to is at the top layer, this prevents transitions from flying in the
// background when swiping before the first slide or beyond the last slide
let zIndex = 1;
if (index === currentIndex) {
zIndex = 3;
} else if (index === this.state.previousIndex) {
zIndex = 2;
} else if (index === 0 || index === totalSlides) {
zIndex = 0;
}
if (items.length > 2) {
if (currentIndex === 0 && index === totalSlides) {
// make the last slide the slide before the first
translateX = -100 + offsetPercentage;
} else if (currentIndex === totalSlides && index === 0) {
// make the first slide the slide after the last
translateX = 100 + offsetPercentage;
}
}
// Special case when there are only 2 items with infinite on
if (items.length === 2) {
translateX = this._getTranslateXForTwoSlide(index);
}
const translate3d = `translate3d(${translateX}%, 0, 0)`;
return {
WebkitTransform: translate3d,
MozTransform: translate3d,
msTransform: translate3d,
OTransform: translate3d,
transform: translate3d,
zIndex: zIndex,
transition: 'transform 450ms ease-out', // 这个450ms本来是props中传过来的, 这里写死了
};
}
render() {
const {currentIndex} = this.state;
const slides = [];
const bullets = [];
// 准备数据
this.props.items.forEach((item, index) => {
const alignment = this._getAlignmentClassName(index);
const slide = (
<div key={index} className={`image-gallery-slide${alignment}`} style={this._getSlideStyle(index)}>
{this.renderItem(item)}
</div>
);
slides.push(slide);
bullets.push(
<button key={index} type="button" className={`image-gallery-bullet ${currentIndex === index ? 'active' : ''}`}
onClick={e => this.slideToIndex(index)}/>
);
});
const slideWrapper = (
<div className="image-gallery-slide-wrapper">
{/*左右切换按钮*/}
{this.props.items.length > 1 && this.navButton}
{/*图片*/}
<div className="image-gallery-slides">
{slides}
</div>
{/*下方圆点*/}
{this.props.items.length > 1 &&
<div className="image-gallery-bullets">
<ul className="image-gallery-bullets-container">
{bullets}
</ul>
</div>}
{/*右上角index*/}
{this.props.items.length > 1 &&
<div className="image-gallery-index">
<span className="image-gallery-index-current">{this.state.currentIndex + 1}</span>
<span className="image-gallery-index-separator">{' / '}</span>
<span className="image-gallery-index-total">{this.props.items.length}</span>
</div>}
</div>
);
return (
<section className="image-gallery">
<div className="image-gallery-content">
{slideWrapper}
</div>
</section>
);
}
}
ImageSlider.propTypes = {
// 要显示的图片数组, 例子: [{url:aaa, alt:bbb, description:ccc}]
items: React.PropTypes.array.isRequired,
};
ImageSlider.defaultProps = {
items: [],
};
export default ImageSlider;
|
node_modules/react-router/es6/RouterContext.js
|
SlateRobotics/slate-website
|
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
import invariant from 'invariant';
import React from 'react';
import deprecateObjectProperties from './deprecateObjectProperties';
import getRouteParams from './getRouteParams';
import { isReactChildren } from './RouteUtils';
import warning from './routerWarning';
var _React$PropTypes = React.PropTypes;
var array = _React$PropTypes.array;
var func = _React$PropTypes.func;
var object = _React$PropTypes.object;
/**
* A <RouterContext> renders the component tree for a given router state
* and sets the history object and the current location in context.
*/
var RouterContext = React.createClass({
displayName: 'RouterContext',
propTypes: {
history: object,
router: object.isRequired,
location: object.isRequired,
routes: array.isRequired,
params: object.isRequired,
components: array.isRequired,
createElement: func.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
createElement: React.createElement
};
},
childContextTypes: {
history: object,
location: object.isRequired,
router: object.isRequired
},
getChildContext: function getChildContext() {
var _props = this.props;
var router = _props.router;
var history = _props.history;
var location = _props.location;
if (!router) {
process.env.NODE_ENV !== 'production' ? warning(false, '`<RouterContext>` expects a `router` rather than a `history`') : undefined;
router = _extends({}, history, {
setRouteLeaveHook: history.listenBeforeLeavingRoute
});
delete router.listenBeforeLeavingRoute;
}
if (process.env.NODE_ENV !== 'production') {
location = deprecateObjectProperties(location, '`context.location` is deprecated, please use a route component\'s `props.location` instead. http://tiny.cc/router-accessinglocation');
}
return { history: history, location: location, router: router };
},
createElement: function createElement(component, props) {
return component == null ? null : this.props.createElement(component, props);
},
render: function render() {
var _this = this;
var _props2 = this.props;
var history = _props2.history;
var location = _props2.location;
var routes = _props2.routes;
var params = _props2.params;
var components = _props2.components;
var element = null;
if (components) {
element = components.reduceRight(function (element, components, index) {
if (components == null) return element; // Don't create new children; use the grandchildren.
var route = routes[index];
var routeParams = getRouteParams(route, params);
var props = {
history: history,
location: location,
params: params,
route: route,
routeParams: routeParams,
routes: routes
};
if (isReactChildren(element)) {
props.children = element;
} else if (element) {
for (var prop in element) {
if (element.hasOwnProperty(prop)) props[prop] = element[prop];
}
}
if (typeof components === 'object') {
var elements = {};
for (var key in components) {
if (components.hasOwnProperty(key)) {
// Pass through the key as a prop to createElement to allow
// custom createElement functions to know which named component
// they're rendering, for e.g. matching up to fetched data.
elements[key] = _this.createElement(components[key], _extends({
key: key }, props));
}
}
return elements;
}
return _this.createElement(components, props);
}, element);
}
!(element === null || element === false || React.isValidElement(element)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The root route must render a single element') : invariant(false) : undefined;
return element;
}
});
export default RouterContext;
|
src/svg-icons/device/screen-lock-landscape.js
|
mtsandeep/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceScreenLockLandscape = (props) => (
<SvgIcon {...props}>
<path d="M21 5H3c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-2 12H5V7h14v10zm-9-1h4c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1v-1c0-1.11-.9-2-2-2-1.11 0-2 .9-2 2v1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1zm.8-6c0-.66.54-1.2 1.2-1.2.66 0 1.2.54 1.2 1.2v1h-2.4v-1z"/>
</SvgIcon>
);
DeviceScreenLockLandscape = pure(DeviceScreenLockLandscape);
DeviceScreenLockLandscape.displayName = 'DeviceScreenLockLandscape';
DeviceScreenLockLandscape.muiName = 'SvgIcon';
export default DeviceScreenLockLandscape;
|
assets/javascript/components/app/header.js
|
colinjeanne/learning-site
|
import Constants from '../../constants/constants';
import React from 'react';
import TabbedNavigation from './tabbedNavigation';
import UserButton from './userButton';
const header = props => {
const navigationElement = (
<TabbedNavigation
id="mainNavigation"
onSelect={props.onTabSelected}
selectedPage={props.selectedPage}
tabs={Constants.navigationPages} />
);
const navigation = props.isSignedIn ? navigationElement : undefined;
return (
<header>
<h1>Isaac's Learning Site</h1>
<span>
{navigation}
<UserButton
displayName={props.displayName}
isSignedIn={props.isSignedIn}
onClick={props.onUserMenuClick}
toggled={props.selectedPage === Constants.pages.PROFILE} />
</span>
</header>
)};
header.propTypes = {
displayName: React.PropTypes.string,
isSignedIn: React.PropTypes.bool,
onTabSelected: React.PropTypes.func.isRequired,
onUserMenuClick: React.PropTypes.func.isRequired,
selectedPage: React.PropTypes.string
};
export default header;
|
admin/client/App/screens/Item/index.js
|
snowkeeper/keystone
|
/**
* Item View
*
* This is the item view, it is rendered when users visit a page of a specific
* item. This mainly renders the form to edit the item content in.
*/
import React from 'react';
import { Container, Spinner } from 'elemental';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import { listsByKey } from '../../../utils/lists';
import CreateForm from '../../shared/CreateForm';
import EditForm from './components/EditForm';
import EditFormHeader from './components/EditFormHeader';
import RelatedItemsList from './components/RelatedItemsList/RelatedItemsList';
// import FlashMessages from '../../shared/FlashMessages';
import {
selectItem,
loadItemData,
} from './actions';
import {
selectList,
} from '../List/actions';
var ItemView = React.createClass({
displayName: 'ItemView',
contextTypes: {
router: React.PropTypes.object.isRequired,
},
getInitialState () {
return {
createIsOpen: false,
};
},
componentDidMount () {
// When we directly navigate to an item without coming from another client
// side routed page before, we need to select the list before initializing the item
// We also need to update when the list id has changed
if (!this.props.currentList || this.props.currentList.id !== this.props.params.listId) {
this.props.dispatch(selectList(this.props.params.listId));
}
this.initializeItem(this.props.params.itemId);
},
componentWillReceiveProps (nextProps) {
// We've opened a new item from the client side routing, so initialize
// again with the new item id
if (nextProps.params.itemId !== this.props.params.itemId) {
this.props.dispatch(selectList(nextProps.params.listId));
this.initializeItem(nextProps.params.itemId);
}
},
// Initialize an item
initializeItem (itemId) {
this.props.dispatch(selectItem(itemId));
this.props.dispatch(loadItemData());
},
// Called when a new item is created
onCreate (item) {
// Hide the create form
this.toggleCreateModal(false);
// Redirect to newly created item path
const list = this.props.currentList;
this.context.router.push(`${Keystone.adminPath}/${list.path}/${item.id}`);
},
// Open and close the create new item modal
toggleCreateModal (visible) {
this.setState({
createIsOpen: visible,
});
},
// Render this items relationships
renderRelationships () {
const { relationships } = this.props.currentList;
const keys = Object.keys(relationships);
if (!keys.length) return;
return (
<div className="Relationships">
<Container>
<h2>Relationships</h2>
{keys.map(key => {
const relationship = relationships[key];
const refList = listsByKey[relationship.ref];
const { currentList, params, relationshipData, drag } = this.props;
return (
<RelatedItemsList
key={relationship.path}
list={currentList}
refList={refList}
relatedItemId={params.itemId}
relationship={relationship}
items={relationshipData[relationship.path]}
dragNewSortOrder={drag.newSortOrder}
dispatch={this.props.dispatch}
/>
);
})}
</Container>
</div>
);
},
// Handle errors
handleError (error) {
const detail = error.detail;
if (detail) {
// Item not found
if (detail.name === 'CastError'
&& detail.path === '_id') {
return (
<Container>
<p>Item not found!</p>
<Link to={`${Keystone.adminPath}/${this.props.routeParams.listId}`}>
Go to list
</Link>
</Container>
);
}
}
if (error.message) {
// Server down + possibly other errors
if (error.message === 'Internal XMLHttpRequest Error') {
return (
<Container>
<p>We encountered some network problems, please try refreshing!</p>
</Container>
);
}
}
return (<p>Error!</p>);
},
render () {
// If we don't have any data yet, show the loading indicator
if (!this.props.ready) {
return (
<div className="centered-loading-indicator" data-screen-id="item">
<Spinner size="md" />
</div>
);
}
// When we have the data, render the item view with it
return (
<div data-screen-id="item">
{(this.props.error) ? this.handleError(this.props.error) : (
<div>
<Container>
<EditFormHeader
list={this.props.currentList}
data={this.props.data}
toggleCreate={this.toggleCreateModal}
/>
<CreateForm
list={this.props.currentList}
isOpen={this.state.createIsOpen}
onCancel={() => this.toggleCreateModal(false)}
onCreate={(item) => this.onCreate(item)}
/>
<EditForm
list={this.props.currentList}
data={this.props.data}
dispatch={this.props.dispatch}
router={this.context.router}
/>
</Container>
{this.renderRelationships()}
</div>
)}
</div>
);
},
});
module.exports = connect((state) => ({
data: state.item.data,
loading: state.item.loading,
ready: state.item.ready,
error: state.item.error,
currentList: state.lists.currentList,
relationshipData: state.item.relationshipData,
drag: state.item.drag,
}))(ItemView);
|
web/src/js/__tests__/components/ContentView/ContentViewSpec.js
|
vhaupert/mitmproxy
|
import React from 'react'
import renderer from 'react-test-renderer'
import TestUtils from 'react-dom/test-utils'
import { Provider } from 'react-redux'
import { ViewServer, ViewImage, PureViewServer, Edit } from '../../../components/ContentView/ContentViews'
import { TFlow, TStore } from '../../ducks/tutils'
import mockXMLHttpRequest from 'mock-xmlhttprequest'
global.XMLHttpRequest = mockXMLHttpRequest
let tflow = new TFlow()
describe('ViewImage Component', () => {
let viewImage = renderer.create(<ViewImage flow={tflow} message={tflow.response}/>),
tree = viewImage.toJSON()
it('should render correctly', () => {
expect(tree).toMatchSnapshot()
})
})
describe('ViewServer Component', () => {
let store = TStore(),
setContentViewDescFn = jest.fn(),
setContentFn = jest.fn()
it('should render correctly and connect to state', () => {
let provider = renderer.create(
<Provider store={store}>
<ViewServer
setContentViewDescription={setContentViewDescFn}
setContent={setContentFn}
flow={tflow}
message={tflow.response}
/>
</Provider>),
tree = provider.toJSON()
expect(tree).toMatchSnapshot()
let viewServer = renderer.create(
<PureViewServer
showFullContent={true}
maxLines={10}
setContentViewDescription={setContentViewDescFn}
setContent={setContentViewDescFn}
flow={tflow}
message={tflow.response}
content={JSON.stringify({lines: [['k1', 'v1']]})}
/>
)
tree = viewServer.toJSON()
expect(tree).toMatchSnapshot()
})
it('should handle componentWillReceiveProps', () => {
// case of fail to parse content
let viewSever = TestUtils.renderIntoDocument(
<PureViewServer
showFullContent={true}
maxLines={10}
setContentViewDescription={setContentViewDescFn}
setContent={setContentViewDescFn}
flow={tflow}
message={tflow.response}
content={JSON.stringify({lines: [['k1', 'v1']]})}
/>
)
viewSever.componentWillReceiveProps({...viewSever.props, content: '{foo' })
let e = ''
try {JSON.parse('{foo') } catch(err){ e = err.message}
expect(viewSever.data).toEqual({ description: e, lines: [] })
})
})
describe('Edit Component', () => {
it('should render correctly', () => {
let edit = renderer.create(<Edit
content="foo"
onChange={jest.fn}
flow={tflow}
message={tflow.response}
/>),
tree = edit.toJSON()
expect(tree).toMatchSnapshot()
})
})
|
src/backward/Widgets/CardSwiper.js
|
chaitanya0bhagvan/NativeBase
|
/* @flow */
import React from 'react';
import clamp from 'clamp';
import { Animated, PanResponder } from 'react-native';
import NativeBaseComponent from '../Base/NativeBaseComponent';
import { View } from './View';
const SWIPE_THRESHOLD = 120;
export default class CardSwiper extends NativeBaseComponent {
constructor(props) {
super(props);
this.state = {
pan: new Animated.ValueXY(),
enter: new Animated.Value(0.5),
};
}
componentDidMount() {
this._animateEntrance();
}
_animateEntrance() {
Animated.spring(
this.state.enter,
{ toValue: 1, friction: 8 }
).start();
}
componentWillMount() {
this._panResponder = PanResponder.create({
onMoveShouldSetResponderCapture: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderGrant: (e, gestureState) => {
this.state.pan.setOffset({ x: this.state.pan.x._value, y: this.state.pan.y._value });
this.state.pan.setValue({ x: 0, y: 0 });
},
onPanResponderMove: Animated.event([
null, { dx: this.state.pan.x, dy: this.state.pan.y },
]),
onPanResponderRelease: (e, { vx, vy }) => {
this.state.pan.flattenOffset();
let velocity;
if (vx >= 0) {
velocity = clamp(vx, 3, 5);
} else if (vx < 0) {
velocity = clamp(vx * -1, 3, 5) * -1;
}
if (Math.abs(this.state.pan.x._value) > SWIPE_THRESHOLD) {
if (velocity > 0) {
this.props.onSwipeRight();
} else {
this.props.onSwipeLeft();
}
Animated.decay(this.state.pan, {
velocity: { x: velocity, y: vy },
deceleration: 0.98,
}).start(this._resetState.bind(this));
} else {
Animated.spring(this.state.pan, {
toValue: { x: 0, y: 0 },
friction: 4,
}).start();
}
},
});
}
_resetState() {
this.state.pan.setValue({ x: 0, y: 0 });
this.state.enter.setValue(0);
this._animateEntrance();
}
render() {
const { pan, enter } = this.state;
const [translateX, translateY] = [pan.x, pan.y];
const rotate = pan.x.interpolate({ inputRange: [-300, 0, 300], outputRange: ['-30deg', '0deg', '30deg'] });
const opacity = pan.x.interpolate({ inputRange: [-150, 0, 150], outputRange: [0.5, 1, 0.5] });
const scale = enter;
const animatedCardStyles = { transform: [{ translateX }, { translateY }, { rotate }, { scale }], opacity };
return (
<View ref={c => this._root = c}>
<Animated.View style={animatedCardStyles} {...this._panResponder.panHandlers} >
{this.props.children}
</Animated.View>
</View>
);
}
}
|
assets/jqwidgets/demos/react/app/grid/defaultfunctionality/app.js
|
juannelisalde/holter
|
import React from 'react';
import ReactDOM from 'react-dom';
import JqxGrid from '../../../jqwidgets-react/react_jqxgrid.js';
class App extends React.Component {
render() {
let source =
{
datatype: 'xml',
datafields: [
{ name: 'ProductName', type: 'string' },
{ name: 'QuantityPerUnit', type: 'int' },
{ name: 'UnitPrice', type: 'float' },
{ name: 'UnitsInStock', type: 'float' },
{ name: 'Discontinued', type: 'bool' }
],
root: 'Products',
record: 'Product',
id: 'ProductID',
url: '../sampledata/products.xml'
};
let cellsrenderer = (row, columnfield, value, defaulthtml, columnproperties, rowdata) => {
if (value < 20) {
return '<span style="margin: 4px; float: ' + columnproperties.cellsalign + '; color: #ff0000;">' + value + '</span>';
}
else {
return '<span style="margin: 4px; float: ' + columnproperties.cellsalign + '; color: #008000;">' + value + '</span>';
}
}
let dataAdapter = new $.jqx.dataAdapter(source);
let columns =
[
{ text: 'Product Name', columngroup: 'ProductDetails', datafield: 'ProductName', width: 250 },
{ text: 'Quantity per Unit', columngroup: 'ProductDetails', datafield: 'QuantityPerUnit', cellsalign: 'right', align: 'right', width: 200 },
{ text: 'Unit Price', columngroup: 'ProductDetails', datafield: 'UnitPrice', align: 'right', cellsalign: 'right', cellsformat: 'c2', width: 200 },
{ text: 'Units In Stock', datafield: 'UnitsInStock', cellsalign: 'right', cellsrenderer: cellsrenderer, width: 100 },
{ text: 'Discontinued', columntype: 'checkbox', datafield: 'Discontinued' }
];
let columngroups =
[
{ text: 'Product Details', align: 'center', name: 'ProductDetails' }
];
return (
<JqxGrid
width={850} source={dataAdapter} pageable={true}
sortable={true} altrows={true} enabletooltips={true}
autoheight={true} editable={true} columns={columns}
selectionmode={'multiplecellsadvanced'} columngroups={columngroups}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/svg-icons/action/alarm-on.js
|
kasra-co/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAlarmOn = (props) => (
<SvgIcon {...props}>
<path d="M22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm-1.46-5.47L8.41 12.4l-1.06 1.06 3.18 3.18 6-6-1.06-1.06-4.93 4.95z"/>
</SvgIcon>
);
ActionAlarmOn = pure(ActionAlarmOn);
ActionAlarmOn.displayName = 'ActionAlarmOn';
ActionAlarmOn.muiName = 'SvgIcon';
export default ActionAlarmOn;
|
src/shared/components/Products/ProductsTblPage.js
|
Grace951/ReactAU
|
import React from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import update from 'immutability-helper';
import {productEditColDetail} from '../../Data/General';
import { ImageLoader } from '../Shared/ImageLoader';
import { SortableTbl } from '../Shared/SortableTbl';
import { routeBaseLink } from '../../Data/RouteData';
import BaseProductDeleteComponent from "../Admin/AdminEditDelete";
import StarsRated from '../Shared/StarsRated';
import Favorite from '../Products/Details/Favorite';
import HeartToggle from '../Shared/HeartToggle';
import { loadProducts, changeProductType } from '../..//actions/productsActions';
import connectDataFetchers from '../../lib/connectDataFetchers.jsx';
const BaseProductTblImageComponent = (props) =>
{
return (
<td style={{width: '170px', minWidth: '170px', backgroundColor: '#fff'}} >
<Link to={props.rowData.edit?`/admin/productChange/${props.rowData._id}`:routeBaseLink[props.productType] + props.rowData._id}>
<ImageLoader src={props.tdData} minHeight="100px"
alt={`${props.rowData.brand} - ${props.productType} - ${props.rowData.type} - ${props.rowData.name}`}
title={`${props.rowData.brand} - ${props.productType} - ${props.rowData.type} - ${props.rowData.name}`}
/>
</Link>
</td>
);
};
BaseProductTblImageComponent.propTypes = {
tdData: React.PropTypes.string,
rowData: React.PropTypes.object,
productType: React.PropTypes.string.isRequired,
};
const BaseProductEditComponent = (props) =>
{
return (
<td >
<Link to={`${props.rowData.edit}${props.rowData._id}`}>
<input type="button" className="btn btn-warning" value="Edit"/>
</Link>
</td>
);
};
BaseProductEditComponent.propTypes = {
rowData: React.PropTypes.object,
};
let ProductsTblPage = class ProductsTblPage extends React.Component{
constructor(props) {
super(props);
this.state = {
gridView : !!(props.device.phone || props.device.mobile),
manualSetGV : false
};
this.setGridListView = this.setGridListView.bind(this);
this.handleResize = this.handleResize.bind(this);
}
componentDidMount() {
let {match, dispatch} = this.props ;
let productType = match.params.product || match.params.cat || "DVR";
window.addEventListener('resize', this.handleResize, false);
dispatch(changeProductType(productType));
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.match && this.props.match && prevProps.match.params && this.props.match.params
&& (prevProps.match.params.product != this.props.match.params.product)){
let {match, dispatch} = this.props ;
let productType = match.params.product || match.params.cat || "DVR";
dispatch(changeProductType(productType));
}
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
}
handleResize(){
let {device} = this.props;
let gv = window.outerWidth < 736 || (device.phone || device.mobile);
if (!this.state.manualSetGV && gv !== this.state.gridView){
this.setState( {
gridView: gv,
manualSetGV: false
});
}
}
setGridListView(e){
let gridView = e.target.getAttribute("data-view")==="grid";
this.setState( {
gridView:gridView,
manualSetGV: true
});
}
render () {
let {match, edit, products, editBaseLink, ajaxState, actions, routes, device} = this.props ;
let ProductsTbl = match.params.ProductsTbl || "All";
let productType = match.params.product || match.params.cat || "DVR";
let filtered = products;
if (ProductsTbl && ProductsTbl !== "All"){
filtered = products.filter( item => {
return item.type == ProductsTbl
|| item.brand == ProductsTbl;
});
}
let mobile = !!(device.phone || device.mobile);
let viewSettingStyle = {display: mobile ?"none":"block"};
if ( !productType || filtered === []){
return (<div/>);
}
let col = [], tHead =[];
let obj = filtered[0];
let data = [...filtered];
for (let item of data) {
if (item.images && item.images[0]){
item.imageUrl= item.images[0];
delete item.images;
}
if(edit){
item.edit = editBaseLink;
}
if(this.props.delete){
item.delete = "";
}
}
tHead.push( "Image");
col.push("imageUrl");
for (let prop in obj) {
let iMap = productEditColDetail.filter((item)=>item.db === prop ).pop();
if ( !iMap || iMap.db === '_id' || iMap.db === 'imageUrl' ){
continue;
}
if ( (productType == "DVR" || productType == "NVR" ) && (iMap.db === 'remote' || iMap.db === 'backup')){
continue;
}
tHead.push( (iMap && iMap.desc) || "");
col.push(prop);
}
if(edit){
tHead.push("Edit");
col.push("edit");
}
if(this.props.delete){
tHead.push("Delete");
col.push("delete");
}
// console.log(Metadata[this.props.productType]);
return (
<div className="loading-wrap">
<div className={`ajax-loading-big ${ajaxState > 0?'fade-show':'fade-hide'}`} ><img src="/build/img/ajax-loader.gif" alt=""/></div>
{ productType != "ALARM" &&
<ul className="app-view" style={viewSettingStyle}>
<li className="hiddenView fa fa-th-list btn-list" data-view="list" onClick={this.setGridListView}>
<div className="bubble ">list view</div>
</li>
<li className="hiddenView fa fa-th btn-list" data-view="grid" onClick={this.setGridListView}>
<div className="bubble ">grid view</div>
</li>
</ul>
}
{ productType != "ALARM" &&
<div className="list-container" style={{display: this.state.gridView?"none":"block"}}>
<SortableTbl tblData={data}
tHead={tHead}
customTd={[
{custd: BaseProductTblImageComponent, keyItem: "imageUrl"},
{custd: BaseProductEditComponent, keyItem: "edit"},
{custd: BaseProductDeleteComponent, keyItem: "delete"}
]}
dKey={col} keyId="_id"
productType={productType}
actions={actions}
params={match.params}/>
</div>
}
<div className="grid-container" style={{display: productType != "ALARM"?(this.state.gridView?"block":"none"):"block"}}>
{data.map((item, id)=>{
let c = 0;
item.stars && (c = (Math.round((item.stars.totalStars / item.stars.voteCount) * 100) / 100));
return (
<div key={id} className="col-sm-6 col-md-4 Grid">
<div className="block-wrap">
<Link to={edit?`/admin/productChange/${item._id}`:`/products/${productType}/spec/${item._id}`}>
<div className="block">
<div className="">
<ImageLoader
src={item.imageUrl}
minHeight= "200px"
alt={`${item.brand} - ${productType} - ${item.type} - ${item.name}`}
title={`${item.brand} - ${productType} - ${item.type} - ${item.name}`}
/>
</div>
<div className="title">
<span className="favorite"><i className="fa fa-heart" style={{color: "#CC3300"}}/> {item.favorite || 0}</span>
<span className="rate"><StarsRated count={c}/></span>
<p className="model ellipsis ">{item.name}</p>
<p className="brand ellipsis ">{item.brand} - {item.type}</p>
</div>
</div>
</Link>
</div>
</div>);
})}
</div>
</div>
);
}
};
ProductsTblPage.propTypes = {
productType: React.PropTypes.string,
actions: React.PropTypes.object,
match: React.PropTypes.object,
editBaseLink: React.PropTypes.string,
delete: React.PropTypes.bool,
edit: React.PropTypes.bool,
products: React.PropTypes.array,
routes: React.PropTypes.array,
ajaxState: React.PropTypes.number,
device: React.PropTypes.object.isRequired
};
function mapStateToProps(state, ownProps) {
return {
device: state.device,
products: state.products,
ajaxState: state.ajaxCallsInProgress
};
}
ProductsTblPage = connect(mapStateToProps)(
connectDataFetchers(ProductsTblPage, [ loadProducts]));
export default ProductsTblPage;
|
modules/gui/src/app/home/body/process/recipe/indexChange/indexChangeImageLayer.js
|
openforis/sepal
|
import {MapAreaLayout} from 'app/home/map/mapAreaLayout'
import {VisualizationSelector} from 'app/home/map/imageLayerSource/visualizationSelector'
import {compose} from 'compose'
import {getAvailableBands} from './bands'
import {getPreSetVisualizations} from './visualizations'
import {msg} from 'translate'
import PropTypes from 'prop-types'
import React from 'react'
const defaultLayerConfig = {
panSharpen: false
}
class _IndexChangeImageLayer extends React.Component {
render() {
const {layer, map} = this.props
return (
<MapAreaLayout
layer={layer}
form={this.renderImageLayerForm()}
map={map}
/>
)
}
renderImageLayerForm() {
const {recipe, source, layerConfig = {}} = this.props
const availableBands = getAvailableBands(recipe)
const preSetOptions = getPreSetVisualizations(recipe)
.filter(({bands}) => availableBands[bands[0]])
.map(visParams => {
const band = visParams.bands[0]
return {...availableBands[band], value: band, visParams}
})
const options = [{
label: msg('process.indexChange.layers.imageLayer.preSets'),
options: preSetOptions
}]
return (
<VisualizationSelector
source={source}
recipe={recipe}
presetOptions={options}
selectedVisParams={layerConfig.visParams}
/>
)
}
}
export const IndexChangeImageLayer = compose(
_IndexChangeImageLayer
)
IndexChangeImageLayer.defaultProps = {
layerConfig: defaultLayerConfig
}
IndexChangeImageLayer.propTypes = {
recipe: PropTypes.object.isRequired,
source: PropTypes.object.isRequired,
layer: PropTypes.object,
layerConfig: PropTypes.object,
map: PropTypes.object
}
|
src/FlatButton/FlatButton.spec.js
|
igorbt/material-ui
|
/* eslint-env mocha */
import React from 'react';
import {shallow} from 'enzyme';
import {assert} from 'chai';
import FlatButton from './FlatButton';
import getMuiTheme from '../styles/getMuiTheme';
import ActionAndroid from '../svg-icons/action/android';
describe('<FlatButton />', () => {
const muiTheme = getMuiTheme();
const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});
const flatButtonTheme = muiTheme.flatButton;
const testChildren = <div className="unique">Hello World</div>;
it('renders an enhanced button', () => {
const wrapper = shallowWithContext(
<FlatButton>Button</FlatButton>
);
assert.ok(wrapper.is('EnhancedButton'));
});
it('renders children', () => {
const wrapper = shallowWithContext(
<FlatButton>{testChildren}</FlatButton>
);
assert.ok(wrapper.contains(testChildren), 'should contain the children');
});
it('passes props to the enhanced button', () => {
const props = {
ariaLabel: 'Say hello world',
disabled: true,
href: 'http://google.com',
name: 'Hello World',
};
const wrapper = shallowWithContext(
<FlatButton {...props}>Button</FlatButton>
);
assert.ok(wrapper.is('EnhancedButton'));
assert.ok(wrapper.is(props));
});
it('renders a label with an icon before', () => {
const wrapper = shallowWithContext(
<FlatButton
icon={<span className="test-icon" />}
label="Hello"
/>
);
const icon = wrapper.children().at(0);
const label = wrapper.children().at(1);
assert.ok(icon.is('span'));
assert.ok(icon.hasClass('test-icon'));
assert.ok(label.is('FlatButtonLabel'));
assert.strictEqual(label.node.props.label, 'Hello', 'says hello');
});
it('renders a label with an icon after', () => {
const wrapper = shallowWithContext(
<FlatButton
icon={<span className="test-icon" />}
label="Hello"
labelPosition="before"
/>
);
const icon = wrapper.children().at(1);
const label = wrapper.children().at(0);
assert.ok(icon.is('span'));
assert.ok(icon.hasClass('test-icon'));
assert.ok(label.is('FlatButtonLabel'));
assert.strictEqual(label.node.props.label, 'Hello', 'says hello');
});
it('colors the button the primary theme color', () => {
const wrapper = shallowWithContext(
<FlatButton
label="Button"
icon={<span className="test-icon" />}
primary={true}
/>
);
const icon = wrapper.children().at(0);
assert.ok(wrapper.is('EnhancedButton'));
assert.ok(wrapper.is({
style: {
color: flatButtonTheme.primaryTextColor,
},
}));
assert.ok(icon.is('span'));
assert.ok(icon.is({color: flatButtonTheme.primaryTextColor}));
});
it('colors the icon with the passed color in prop', () => {
const color = 'white';
const wrapper = shallowWithContext(
<FlatButton
backgroundColor="#a4c639"
hoverColor="#8AA62F"
icon={<ActionAndroid color={color} />}
/>
);
const icon = wrapper.find('ActionAndroid');
assert.strictEqual(icon.prop('color'), color, 'icon should have same color as that of color prop');
});
it('colors the button the secondary theme color', () => {
const wrapper = shallowWithContext(
<FlatButton secondary={true} icon={<span className="test-icon" />}>Button</FlatButton>
);
assert.ok(wrapper.is('EnhancedButton'));
assert.ok(wrapper.is({
style: {
color: flatButtonTheme.secondaryTextColor,
},
}));
});
it('overrides hover and background color styles via props', () => {
const wrapper = shallowWithContext(
<FlatButton
backgroundColor="rgba(159,159,159)"
hoverColor="yellow"
label="Button"
/>
);
assert.ok(wrapper.is({
style: {
backgroundColor: 'rgba(159,159,159)',
},
}), 'should have the custom background color');
wrapper.setState({hovered: true});
assert.ok(wrapper.is({
style: {
backgroundColor: 'yellow',
},
}), 'should have the custom hover background color');
});
it('overrides the ripple color via props', () => {
const wrapper = shallowWithContext(
<FlatButton rippleColor="yellow" label="Button" />
);
assert.strictEqual(wrapper.node.props.focusRippleColor, 'yellow', 'should be yellow');
assert.strictEqual(wrapper.node.props.touchRippleColor, 'yellow', 'should be yellow');
});
describe('validateLabel', () => {
const validateLabel = FlatButton.propTypes.label;
it('should throw when using wrong label', () => {
assert.strictEqual(validateLabel({}, 'label', 'FlatButton').message,
'Required prop label or children or icon was not specified in FlatButton.',
'should return an error'
);
});
it('should not throw when using a valid label', () => {
assert.strictEqual(validateLabel({
label: 0,
}, 'label', 'FlatButton'), undefined);
});
});
describe('hover state', () => {
it('should reset the hover state when disabled', () => {
const wrapper = shallowWithContext(
<FlatButton label="foo" />
);
wrapper.simulate('mouseEnter');
assert.strictEqual(wrapper.state().hovered, true, 'should respond to the event');
wrapper.setProps({
disabled: true,
});
assert.strictEqual(wrapper.state().hovered, false, 'should reset the state');
});
});
describe('props: icon', () => {
it('should keep the style set on the icon', () => {
const wrapper = shallowWithContext(
<FlatButton icon={<ActionAndroid style={{foo: 'bar'}} />} />
);
assert.strictEqual(wrapper.find(ActionAndroid).props().style.foo, 'bar');
});
});
describe('props: other', () => {
it('should spread other properties to the root element', () => {
const wrapper = shallowWithContext(
<FlatButton target="_blank" label="Button" />
);
assert.strictEqual(wrapper.props().target, '_blank', 'should be _blank');
});
});
});
|
client/src/js/routes/routes.js
|
ziyadparekh/relay-services
|
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from 'components/App';
import FuelSavingsPage from 'containers/FuelSavingsPage';
import AuthContainer from 'containers/AuthContainer';
// import AboutPage from './components/AboutPage.js';
// import NotFoundPage from './components/NotFoundPage.js';
export default (
<Route path='/' component={App}>
<IndexRoute component={AuthContainer} />
</Route>
);
|
web/src/js/__tests__/components/Modal/OptionSpec.js
|
ddworken/mitmproxy
|
import React from 'react'
import renderer from 'react-test-renderer'
import { Options, ChoicesOption } from '../../../components/Modal/Option'
describe('BooleanOption Component', () => {
let BooleanOption = Options['bool'],
onChangeFn = jest.fn(),
booleanOption = renderer.create(
<BooleanOption value={true} onChange={onChangeFn}/>
),
tree = booleanOption.toJSON()
it('should render correctly', () => {
expect(tree).toMatchSnapshot()
})
it('should handle onChange', () => {
let input = tree.children[0].children[0],
mockEvent = { target: { checked: true }}
input.props.onChange(mockEvent)
expect(onChangeFn).toBeCalledWith(mockEvent.target.checked)
})
})
describe('StringOption Component', () => {
let StringOption = Options['str'],
onChangeFn = jest.fn(),
stringOption = renderer.create(
<StringOption value="foo" onChange={onChangeFn}/>
),
tree = stringOption.toJSON()
it('should render correctly', () => {
expect(tree).toMatchSnapshot()
})
it('should handle onChange', () => {
let mockEvent = { target: { value: 'bar' }}
tree.props.onChange(mockEvent)
expect(onChangeFn).toBeCalledWith(mockEvent.target.value)
})
})
describe('NumberOption Component', () => {
let NumberOption = Options['int'],
onChangeFn = jest.fn(),
numberOption = renderer.create(
<NumberOption value={1} onChange={onChangeFn}/>
),
tree = numberOption.toJSON()
it('should render correctly', () => {
expect(tree).toMatchSnapshot()
})
it('should handle onChange', () => {
let mockEvent = {target: { value: '2'}}
tree.props.onChange(mockEvent)
expect(onChangeFn).toBeCalledWith(2)
})
})
describe('ChoiceOption Component', () => {
let onChangeFn = jest.fn(),
choiceOption = renderer.create(
<ChoicesOption value='a' choices={['a', 'b', 'c']} onChange={onChangeFn}/>
),
tree = choiceOption.toJSON()
it('should render correctly', () => {
expect(tree).toMatchSnapshot()
})
it('should handle onChange', () => {
let mockEvent = { target: {value: 'b'} }
tree.props.onChange(mockEvent)
expect(onChangeFn).toBeCalledWith(mockEvent.target.value)
})
})
describe('StringOption Component', () => {
let onChangeFn = jest.fn(),
StringSequenceOption = Options['sequence of str'],
stringSequenceOption = renderer.create(
<StringSequenceOption value={['a', 'b']} onChange={onChangeFn}/>
),
tree = stringSequenceOption.toJSON()
it('should render correctly', () => {
expect(tree).toMatchSnapshot()
})
it('should handle onChange', () => {
let mockEvent = { target: {value: 'a\nb\nc\n'}}
tree.props.onChange(mockEvent)
expect(onChangeFn).toBeCalledWith(['a', 'b', 'c', ''])
})
})
|
app/javascript/mastodon/features/followers/index.js
|
alarky/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import LoadingIndicator from '../../components/loading_indicator';
import {
fetchAccount,
fetchFollowers,
expandFollowers,
} from '../../actions/accounts';
import { ScrollContainer } from 'react-router-scroll';
import AccountContainer from '../../containers/account_container';
import Column from '../ui/components/column';
import HeaderContainer from '../account_timeline/containers/header_container';
import LoadMore from '../../components/load_more';
import ColumnBackButton from '../../components/column_back_button';
import ImmutablePureComponent from 'react-immutable-pure-component';
const mapStateToProps = (state, props) => ({
accountIds: state.getIn(['user_lists', 'followers', Number(props.params.accountId), 'items']),
hasMore: !!state.getIn(['user_lists', 'followers', Number(props.params.accountId), 'next']),
});
@connect(mapStateToProps)
export default class Followers extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
accountIds: ImmutablePropTypes.list,
hasMore: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchAccount(Number(this.props.params.accountId)));
this.props.dispatch(fetchFollowers(Number(this.props.params.accountId)));
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) {
this.props.dispatch(fetchAccount(Number(nextProps.params.accountId)));
this.props.dispatch(fetchFollowers(Number(nextProps.params.accountId)));
}
}
handleScroll = (e) => {
const { scrollTop, scrollHeight, clientHeight } = e.target;
if (scrollTop === scrollHeight - clientHeight && this.props.hasMore) {
this.props.dispatch(expandFollowers(Number(this.props.params.accountId)));
}
}
handleLoadMore = (e) => {
e.preventDefault();
this.props.dispatch(expandFollowers(Number(this.props.params.accountId)));
}
render () {
const { accountIds, hasMore } = this.props;
let loadMore = null;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
if (hasMore) {
loadMore = <LoadMore onClick={this.handleLoadMore} />;
}
return (
<Column>
<ColumnBackButton />
<ScrollContainer scrollKey='followers'>
<div className='scrollable' onScroll={this.handleScroll}>
<div className='followers'>
<HeaderContainer accountId={this.props.params.accountId} />
{accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)}
{loadMore}
</div>
</div>
</ScrollContainer>
</Column>
);
}
}
|
third_party/blink/perf_tests/speedometer/resources/todomvc/architecture-examples/react-redux/src/components/TodoItem.spec.js
|
scheib/chromium
|
import React from 'react'
import TestUtils from 'react-addons-test-utils'
import TodoItem from './TodoItem'
import TodoTextInput from './TodoTextInput'
const setup = ( editing = false ) => {
const props = {
todo: {
id: 0,
text: 'Use Redux',
completed: false
},
editTodo: jest.fn(),
deleteTodo: jest.fn(),
completeTodo: jest.fn()
}
const renderer = TestUtils.createRenderer()
renderer.render(
<TodoItem {...props} />
)
let output = renderer.getRenderOutput()
if (editing) {
const label = output.props.children.props.children[1]
label.props.onDoubleClick({})
output = renderer.getRenderOutput()
}
return {
props: props,
output: output,
renderer: renderer
}
}
describe('components', () => {
describe('TodoItem', () => {
it('initial render', () => {
const { output } = setup()
expect(output.type).toBe('li')
expect(output.props.className).toBe('')
const div = output.props.children
expect(div.type).toBe('div')
expect(div.props.className).toBe('view')
const [ input, label, button ] = div.props.children
expect(input.type).toBe('input')
expect(input.props.checked).toBe(false)
expect(label.type).toBe('label')
expect(label.props.children).toBe('Use Redux')
expect(button.type).toBe('button')
expect(button.props.className).toBe('destroy')
})
it('input onChange should call completeTodo', () => {
const { output, props } = setup()
const input = output.props.children.props.children[0]
input.props.onChange({})
expect(props.completeTodo).toBeCalledWith(0)
})
it('button onClick should call deleteTodo', () => {
const { output, props } = setup()
const button = output.props.children.props.children[2]
button.props.onClick({})
expect(props.deleteTodo).toBeCalledWith(0)
})
it('label onDoubleClick should put component in edit state', () => {
const { output, renderer } = setup()
const label = output.props.children.props.children[1]
label.props.onDoubleClick({})
const updated = renderer.getRenderOutput()
expect(updated.type).toBe('li')
expect(updated.props.className).toBe('editing')
})
it('edit state render', () => {
const { output } = setup(true)
expect(output.type).toBe('li')
expect(output.props.className).toBe('editing')
const input = output.props.children
expect(input.type).toBe(TodoTextInput)
expect(input.props.text).toBe('Use Redux')
expect(input.props.editing).toBe(true)
})
it('TodoTextInput onSave should call editTodo', () => {
const { output, props } = setup(true)
output.props.children.props.onSave('Use Redux')
expect(props.editTodo).toBeCalledWith(0, 'Use Redux')
})
it('TodoTextInput onSave should call deleteTodo if text is empty', () => {
const { output, props } = setup(true)
output.props.children.props.onSave('')
expect(props.deleteTodo).toBeCalledWith(0)
})
it('TodoTextInput onSave should exit component from edit state', () => {
const { output, renderer } = setup(true)
output.props.children.props.onSave('Use Redux')
const updated = renderer.getRenderOutput()
expect(updated.type).toBe('li')
expect(updated.props.className).toBe('')
})
})
})
|
app/javascript/mastodon/features/blocks/index.js
|
RobertRence/Mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import LoadingIndicator from '../../components/loading_indicator';
import { ScrollContainer } from 'react-router-scroll';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import AccountContainer from '../../containers/account_container';
import { fetchBlocks, expandBlocks } from '../../actions/blocks';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
heading: { id: 'column.blocks', defaultMessage: 'Blocked users' },
});
const mapStateToProps = state => ({
accountIds: state.getIn(['user_lists', 'blocks', 'items']),
});
@connect(mapStateToProps)
@injectIntl
export default class Blocks extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
accountIds: ImmutablePropTypes.list,
intl: PropTypes.object.isRequired,
};
componentWillMount () {
this.props.dispatch(fetchBlocks());
}
handleScroll = (e) => {
const { scrollTop, scrollHeight, clientHeight } = e.target;
if (scrollTop === scrollHeight - clientHeight) {
this.props.dispatch(expandBlocks());
}
}
render () {
const { intl, accountIds } = this.props;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
return (
<Column icon='ban' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<ScrollContainer scrollKey='blocks'>
<div className='scrollable' onScroll={this.handleScroll}>
{accountIds.map(id =>
<AccountContainer key={id} id={id} />
)}
</div>
</ScrollContainer>
</Column>
);
}
}
|
src/routes/error/ErrorPage.js
|
LeraSavchenko/Maysternia
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './ErrorPage.css';
class ErrorPage extends React.Component {
static propTypes = {
error: PropTypes.shape({
name: PropTypes.string.isRequired,
message: PropTypes.string.isRequired,
stack: PropTypes.string.isRequired,
}).isRequired,
};
render() {
if (__DEV__) {
const { error } = this.props;
return (
<div>
<h1>{error.name}</h1>
<p>{error.message}</p>
<pre>{error.stack}</pre>
</div>
);
}
return (
<div>
<h1>Error</h1>
<p>Sorry, a critical error occurred on this page.</p>
</div>
);
}
}
export { ErrorPage as ErrorPageWithoutStyle };
export default withStyles(s)(ErrorPage);
|
js/react-base-64/src/components/Base64Form.js
|
mhfa/bacon
|
import React, { Component } from 'react';
import base64 from 'base-64';
class Base64Form extends Component {
constructor(){
super();
this.state = {
processedVal: "",
formVal: "",
};
}
render() {
const test = 'test';
const placeholder = `this a ${test}`;
return (
<div className="Base64Form">
<h1>Base64Form</h1>
<textarea
rows="4"
cols="50"
placeholder={placeholder}
onChange={this._changeHandlerForm}
value={this.state.formVal}
/>
<br />
<button onClick={this._clickProcessText} id="encode">Encode text to Base 64</button>
<button onClick={this._clickProcessText} id="decode">Decode Base 64 to text</button>
<div>
<h2>Result</h2>
<p>{this.state.processedVal}</p>
</div>
</div>
);
}
_clickProcessText = (e) => {
let result = "";
// Debug
console.log("Form clicked", e.target.id);
if(e.target.id === "encode") {
console.log("We are encoding");
result = base64.encode(this.state.formVal);
}
else if(e.target.id === "decode") {
result = base64.decode(this.state.formVal);
}
this.setState({
processedVal: result,
});
}
_changeHandlerForm = (e) => {
this.setState({
formVal: e.target.value,
});
}
}
export default Base64Form;
|
docs/src/scenes/Home/index.js
|
directlyio/redink
|
import React from 'react';
import { Gist } from 'components';
import styles from './styles.scss';
const Home = () => (
<div className={styles.wrapper}>
<h1 className="heading">
RethinkDB model layer that makes complex business-logic easy
</h1>
<p className="paragraph">
Redink provides some simple abtractions that make performing complex relationial operations
easy.
</p>
<Gist id="dylnslck/4d4a86b1b58f859479dbe2c17a3c65e2" />
</div>
);
export default Home;
|
src/svg-icons/editor/insert-emoticon.js
|
w01fgang/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorInsertEmoticon = (props) => (
<SvgIcon {...props}>
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/>
</SvgIcon>
);
EditorInsertEmoticon = pure(EditorInsertEmoticon);
EditorInsertEmoticon.displayName = 'EditorInsertEmoticon';
EditorInsertEmoticon.muiName = 'SvgIcon';
export default EditorInsertEmoticon;
|
public/client/routes/overview/containers/overview.js
|
Concorda/concorda-dashboard
|
'use strict'
import React from 'react'
import {connect} from 'react-redux'
export const Overview = React.createClass({
render () {
return (
<div className="page container-fluid">
<div className="row middle-xs page-heading">
<h2 className="col-xs-12 col-sm-6">Overview</h2>
</div>
</div>
)
}
})
export default connect((state) => {
return {
}
})(Overview)
|
examples/sidebar/app.js
|
etiennetremel/react-router
|
import React from 'react';
import { Router, Route, Link } from 'react-router';
import data from './data';
var Category = React.createClass({
render() {
var category = data.lookupCategory(this.props.params.category);
return (
<div>
<h1>{category.name}</h1>
{this.props.children || (
<p>{category.description}</p>
)}
</div>
);
}
});
var CategorySidebar = React.createClass({
render() {
var category = data.lookupCategory(this.props.params.category);
return (
<div>
<Link to="/">◀︎ Back</Link>
<h2>{category.name} Items</h2>
<ul>
{category.items.map((item, index) => (
<li key={index}>
<Link to={`/category/${category.name}/${item.name}`}>{item.name}</Link>
</li>
))}
</ul>
</div>
);
}
});
var Item = React.createClass({
render() {
var { category, item } = this.props.params;
var menuItem = data.lookupItem(category, item);
return (
<div>
<h1>{menuItem.name}</h1>
<p>${menuItem.price}</p>
</div>
);
}
});
var Index = React.createClass({
render() {
return (
<div>
<h1>Sidebar</h1>
<p>
Routes can have multiple components, so that all portions of your UI
can participate in the routing.
</p>
</div>
);
}
});
var IndexSidebar = React.createClass({
render() {
return (
<div>
<h2>Categories</h2>
<ul>
{data.getAll().map((category, index) => (
<li key={index}>
<Link to={`/category/${category.name}`}>{category.name}</Link>
</li>
))}
</ul>
</div>
);
}
});
var App = React.createClass({
render() {
var { children } = this.props;
return (
<div>
<div className="Sidebar">
{children ? children.sidebar : <IndexSidebar />}
</div>
<div className="Content">
{children ? children.content : <Index />}
</div>
</div>
);
}
});
React.render((
<Router>
<Route path="/" component={App}>
<Route path="category/:category" components={{content: Category, sidebar: CategorySidebar}}>
<Route path=":item" component={Item} />
</Route>
</Route>
</Router>
), document.getElementById('example'));
|
src/components/Comment.js
|
afonsobarros/reactnd-project-readable
|
import React, { Component } from 'react';
import { connect } from 'react-redux'
import themeDefault from '../theme-default';
import { Button, TextField } from 'material-ui';
import { updateNewComment, resetNewComment, showSnackbar } from '../actions/appState'
import { addComment } from '../actions/comments'
import * as ReadableAPI from '../utils/ReadableAPI';
class Comment extends Component {
updateCommentTimeout = 0;
updateComment = (prop, value) => {
let comment = this.props.newComment;
comment[prop] = value;
this.props.updateNewComment({ newComment: comment });
this.forceUpdate();
};
handleMenuClose = () => {
this.props.closeDialogueCategories();
};
saveComment = () => {
let comment = this.props.newComment;
comment.author = this.props.user.userName;
comment.parentId = this.props.target.id;
ReadableAPI.addComment(comment)
.then(res => {
this.props.addComment({ newComment: comment });
this.props.resetNewComment();
this.forceUpdate();
this.props.showSnackbar('Comment added');
})
};
render() {
const { onRequestClose, newComment } = this.props;
const isDisabled = newComment.body === '';
return (
<div style={themeDefault.actionsDiv}>
<span style={themeDefault.flexGrow}>
<TextField
multiline
required
label="Add a comment"
helperText="Please don't be a troll..."
rowsMax="4"
style={themeDefault.inputFullActions}
onChange={(event) => this.updateComment('body', event.target.value)}
value={newComment.body}
/>
</span>
<Button raised onClick={onRequestClose} color="primary" style={themeDefault.raisedButton}>
cancel
</Button>
<Button raised color="accent" disabled={isDisabled} onClick={this.saveComment} style={themeDefault.raisedButton}>
send
</Button>
</div>
);
};
}
function mapStateToProps(state) {
return {
user: state.user,
newComment: state.appState.newComment
}
}
function mapDispatchToProps(dispatch) {
return {
updateNewComment: (comment) => dispatch(updateNewComment(comment)),
addComment: (comment) => dispatch(addComment(comment)),
resetNewComment: () => dispatch(resetNewComment()),
showSnackbar: (message) => dispatch(showSnackbar({ message })),
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Comment);
|
src/svg-icons/av/videocam.js
|
mtsandeep/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvVideocam = (props) => (
<SvgIcon {...props}>
<path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"/>
</SvgIcon>
);
AvVideocam = pure(AvVideocam);
AvVideocam.displayName = 'AvVideocam';
AvVideocam.muiName = 'SvgIcon';
export default AvVideocam;
|
node_modules/react-router/es/Redirect.js
|
Snatch-M/fesCalendar
|
import React from 'react';
import invariant from 'invariant';
import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils';
import { formatPattern } from './PatternUtils';
import { falsy } from './InternalPropTypes';
var _React$PropTypes = React.PropTypes,
string = _React$PropTypes.string,
object = _React$PropTypes.object;
/**
* A <Redirect> is used to declare another URL path a client should
* be sent to when they request a given URL.
*
* Redirects are placed alongside routes in the route configuration
* and are traversed in the same manner.
*/
/* eslint-disable react/require-render-return */
var Redirect = React.createClass({
displayName: 'Redirect',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element) {
var route = _createRouteFromReactElement(element);
if (route.from) route.path = route.from;
route.onEnter = function (nextState, replace) {
var location = nextState.location,
params = nextState.params;
var pathname = void 0;
if (route.to.charAt(0) === '/') {
pathname = formatPattern(route.to, params);
} else if (!route.to) {
pathname = location.pathname;
} else {
var routeIndex = nextState.routes.indexOf(route);
var parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1);
var pattern = parentPattern.replace(/\/*$/, '/') + route.to;
pathname = formatPattern(pattern, params);
}
replace({
pathname: pathname,
query: route.query || location.query,
state: route.state || location.state
});
};
return route;
},
getRoutePattern: function getRoutePattern(routes, routeIndex) {
var parentPattern = '';
for (var i = routeIndex; i >= 0; i--) {
var route = routes[i];
var pattern = route.path || '';
parentPattern = pattern.replace(/\/*$/, '/') + parentPattern;
if (pattern.indexOf('/') === 0) break;
}
return '/' + parentPattern;
}
},
propTypes: {
path: string,
from: string, // Alias for path
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Redirect> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default Redirect;
|
app/pages/index.js
|
kswOok/rankList
|
/**
* Created by kswook on 01/03/2017.
*/
import React from 'react';
import {render} from 'react-dom';
import '../app.css'
import Index from '../component/Index.js'
render(<Index/>, document.getElementById('content'));
|
src/svg-icons/communication/screen-share.js
|
ArcanisCz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationScreenShare = (props) => (
<SvgIcon {...props}>
<path d="M20 18c1.1 0 1.99-.9 1.99-2L22 6c0-1.11-.9-2-2-2H4c-1.11 0-2 .89-2 2v10c0 1.1.89 2 2 2H0v2h24v-2h-4zm-7-3.53v-2.19c-2.78 0-4.61.85-6 2.72.56-2.67 2.11-5.33 6-5.87V7l4 3.73-4 3.74z"/>
</SvgIcon>
);
CommunicationScreenShare = pure(CommunicationScreenShare);
CommunicationScreenShare.displayName = 'CommunicationScreenShare';
CommunicationScreenShare.muiName = 'SvgIcon';
export default CommunicationScreenShare;
|
src/index.js
|
AlexanderAA/conceptnet
|
import 'babel-polyfill'
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyMiddleware, createStore } from 'redux';
import { createLogger } from 'redux-logger'
import thunkMiddleware from 'redux-thunk';
import rootReducer from './reducers';
import App from './components/app'
const logger = createLogger();
const createStoreWithMiddleware = applyMiddleware(thunkMiddleware, logger)(createStore);
const store = createStoreWithMiddleware(rootReducer);
const render = () => {
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
};
render();
|
src/components/ChatApp/MessageComposer.react.js
|
DeveloperAlfa/chat.susi.ai
|
import * as Actions from '../../actions/';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Send from 'material-ui/svg-icons/content/send';
import Mic from 'material-ui/svg-icons/av/mic';
import UserPreferencesStore from '../../stores/UserPreferencesStore';
import MessageStore from '../../stores/MessageStore';
import IconButton from 'material-ui/IconButton';
import injectTapEventPlugin from 'react-tap-event-plugin';
import VoiceRecognition from './VoiceRecognition';
import Modal from 'react-modal';
import ReactFitText from 'react-fittext';
import Close from 'material-ui/svg-icons/navigation/close';
import TextareaAutosize from 'react-textarea-autosize';
injectTapEventPlugin();
let ENTER_KEY_CODE = 13;
let UP_KEY_CODE = 38;
let DOWN_KEY_CODE = 40;
const style = {
mini: true,
bottom: '14px',
right: '5px',
position: 'absolute',
};
const iconStyles = {
color: '#fff',
fill: 'currentcolor',
height: '40px',
width: '40px',
marginTop: '20px',
userSelect: 'none',
transition: 'all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms'
}
const closingStyle = {
position: 'absolute',
zIndex: 120000,
fill: '#444',
width: '20px',
height: '20px',
right: '0px',
top: '0px',
cursor: 'pointer'
}
class MessageComposer extends Component {
constructor(props) {
super(props);
this.state = {
text: '',
start: false,
stop: false,
open: false,
result: '',
animate: false,
rows: 1,
recognizing: false,
currentArrowIndex:0// store the index for moving through messages using key
};
this.rowComplete = 0;
this.numberoflines = 0;
if (props.dream !== '') {
this.state = { text: 'dream ' + props.dream }
}
}
onStart = () => {
this.setState({
result: '',
start: true,
stop: false,
open: true,
animate: true
})
}
onSpeechStart = () => {
this.setState({
recognizing: true
});
}
onEnd = () => {
this.setState({
start: false,
stop: false,
open: false,
animate: false,
color: '#000',
recognizing: false
});
let voiceResponse = false;
if (this.props.speechOutputAlways || this.props.speechOutput) {
voiceResponse = true;
}
this.Button = <Mic />;
if (this.state.result) {
Actions.createMessage(this.state.result, this.props.threadID, voiceResponse);
}
}
speakDialogClose = () => {
this.setState({
open: false,
start: false,
stop: false
});
}
onResult = ({ interimTranscript, finalTranscript }) => {
if (interimTranscript === undefined) {
let result = finalTranscript;
this.setState({
result: result,
color: '#ccc'
});
}
else {
let result = interimTranscript;
this.setState({
result: result,
color: '#ccc'
})
if (finalTranscript) {
result = finalTranscript;
this.setState({
result: result,
color: '#000'
})
this.speakDialogClose();
}
}
}
componentWillMount() {
let micInputSetting = UserPreferencesStore.getMicInput();
if (micInputSetting) {
// Getting the Speech Recognition to test whether possible
const SpeechRecognition = window.SpeechRecognition
|| window.webkitSpeechRecognition
|| window.mozSpeechRecognition
|| window.msSpeechRecognition
|| window.oSpeechRecognition
// Setting buttons accordingly
if (SpeechRecognition != null) {
this.Button = <Mic />
this.speechRecog = true;
}
else {
this.Button = <Send />;
this.speechRecog = false;
}
}
else {
this.Button = <Send />;
this.speechRecog = false;
}
}
componentDidUpdate() {
let micInputSetting = UserPreferencesStore.getMicInput();
if (micInputSetting) {
// Getting the Speech Recognition to test whether possible
const SpeechRecognition = window.SpeechRecognition
|| window.webkitSpeechRecognition
|| window.mozSpeechRecognition
|| window.msSpeechRecognition
|| window.oSpeechRecognition
// Setting buttons accordingly
if (SpeechRecognition != null) {
this.Button = <Mic />
this.speechRecog = true;
}
else {
this.Button = <Send />;
this.speechRecog = false;
}
}
else {
this.Button = <Send />;
this.speechRecog = false;
}
}
componentDidMount() {
}
render() {
return (
<div className="message-composer" >
{this.state.start && (
<VoiceRecognition
onStart={this.onStart}
onspeechend={this.onspeechend}
onResult={this.onResult}
onEnd={this.onEnd}
onSpeechStart={this.onSpeechStart}
continuous={true}
lang="en-US"
stop={this.state.stop}
/>
)}
<div className="textBack" style={{ backgroundColor: this.props.textarea }}>
{/* TextareaAutosize node package used to get
the auto sizing feature of the chat message composer */}
<TextareaAutosize
className='scroll'
id='scroll'
minRows={1}
maxRows={5}
placeholder="Type a message..."
value={this.state.text}
onChange={this._onChange.bind(this)}
onKeyDown={this._onKeyDown.bind(this)}
ref={(textarea) => { this.nameInput = textarea; }}
style={{ background: this.props.textarea, color: this.props.textcolor, lineHeight: '15px' }}
autoFocus={this.props.focus}
/>
</div>
<IconButton
className="send_button"
iconStyle={{
fill: this.props.micColor,
margin: '1px 0px 1px 0px'
}}
onTouchTap={this._onClickButton.bind(this)}
style={style}>
{this.Button}
</IconButton>
<Modal
isOpen={this.state.open}
className="Modal"
contentLabel="Speak Now"
overlayClassName="Overlay">
<div className='voice-response'>
<ReactFitText compressor={0.5} minFontSize={12} maxFontSize={26}>
<h1 style={{ color: this.state.color }} className='voice-output'>
{this.state.result !== '' ? this.state.result :
'Speak Now...'}
</h1>
</ReactFitText>
<div className={this.state.animate ? 'mic-container active' : 'mic-container'}>
<Mic style={iconStyles} />
</div>
<Close style={closingStyle} onTouchTap={this.speakDialogClose} />
</div>
</Modal>
</div>
);
}
_onClickButton() {
if (this.state.text === '') {
if (this.speechRecog) {
this.setState({ start: true })
}
else {
this.setState({ start: false })
}
}
else {
let text = this.state.text.trim();
if (text) {
let EnterAsSend = UserPreferencesStore.getEnterAsSend();
if (!EnterAsSend) {
text = text.split('\n').join(' ');
}
Actions.createMessage(text, this.props.threadID, this.props.speechOutputAlways);
}
if (this.speechRecog) {
this.Button = <Mic />
}
this.setState({ text: '',currentArrowIndex:0 });
}
setTimeout(function(){
if(this.state.recognizing === false) {
this.speakDialogClose();
}
}.bind(this),5000);
}
_onChange(event, value) {
if (this.speechRecog) {
if (event.target.value !== '') {
this.Button = <Send />
}
else {
this.Button = <Mic />
}
}
else {
this.Button = <Send />
}
this.setState({ text: event.target.value,currentArrowIndex:0 });
}
_onKeyDown(event) {
if (event.keyCode === ENTER_KEY_CODE && !event.shiftKey) {
let EnterAsSend = UserPreferencesStore.getEnterAsSend();
if (EnterAsSend) {
event.preventDefault();
let text = this.state.text.trim();
text = text.replace(/\n|\r\n|\r/g, ' ');
if (text) {
Actions.createMessage(text, this.props.threadID, this.props.speechOutputAlways);
}
this.setState({ text: '',currentArrowIndex:0 });
if (this.speechRecog) {
this.Button = <Mic />
}
}
}
else if(event.keyCode===UP_KEY_CODE){
event.preventDefault();
const messages=MessageStore.getAllForCurrentThread();
let currentArrowIndex = this.state.currentArrowIndex;
let curIndex=0;
for(let i=messages.length-1;i>=0;i--){
let obj=messages[i];
if(obj.authorName==='You'){
if(curIndex===currentArrowIndex){
this.setState({text:obj.text,currentArrowIndex:currentArrowIndex+1});
currentArrowIndex++;
break;
}
curIndex++;
}
}
this.setState({currentArrowIndex});
}
else if(event.keyCode===DOWN_KEY_CODE){
event.preventDefault();
const messages=MessageStore.getAllForCurrentThread();
let currentArrowIndex = this.state.currentArrowIndex;
let curIndex=0;
if(currentArrowIndex<=1){
// empty text field
this.setState({text:'',currentArrowIndex:0})
}
else{
for(let i=messages.length-1;i>=0;i--){
let obj=messages[i];
if(obj.authorName==='You'){
if(curIndex===currentArrowIndex-2){
this.setState({text:obj.text,currentArrowIndex:currentArrowIndex+1});
currentArrowIndex--;
break;
}
curIndex++;
}
}
this.setState({currentArrowIndex});
}
}
}
};
MessageComposer.propTypes = {
threadID: PropTypes.string.isRequired,
dream: PropTypes.string,
textarea: PropTypes.string,
textcolor: PropTypes.string,
speechOutput: PropTypes.bool,
speechOutputAlways: PropTypes.bool,
micColor: PropTypes.string,
focus: PropTypes.bool,
};
export default MessageComposer;
|
assets/javascripts/kitten/components/structure/cards/team-card/components/image.js
|
KissKissBankBank/kitten
|
import React from 'react'
import classNames from 'classnames'
import PropTypes from 'prop-types'
import COLORS from '../../../../../constants/colors-config'
import styled from 'styled-components'
const imageHeight = 378
const imageWidth = 252
const StyledTeamCardImage = styled(({ styled, backgroundSource, ...props }) => (
<div {...props} />
))`
background-image: url(${({ backgroundSource }) => backgroundSource});
background-color: ${COLORS.background1};
background-size: cover;
background-position: center;
background-repeat: no-repeat;
width: 100%;
padding-bottom: ${(imageHeight / imageWidth) * 100 + '%'};
${({ style }) => style}
`
export const TeamCardImage = ({ src, title, style, className, ...props }) => {
return (
<StyledTeamCardImage
{...props}
backgroundSource={src}
title={title}
className={classNames(className, 'k-u-margin-bottom-double')}
style={style}
/>
)
}
TeamCardImage.propTypes = {
src: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
}
|
src/views/Home/HomeView.js
|
dfala/high-club
|
import React from 'react'
import { connect } from 'react-redux'
import { actions as counterActions } from '../../redux/modules/counter'
import styles from './HomeView.scss'
import TopNav from '../../components/Top-Nav/Top-Nav'
// We define mapStateToProps where we'd normally use
// the @connect decorator so the data requirements are clear upfront, but then
// export the decorated component after the main class definition so
// the component can be tested w/ and w/o being connected.
// See: http://rackt.github.io/redux/docs/recipes/WritingTests.html
const mapStateToProps = (state) => ({
counter: state.counter
})
export class HomeView extends React.Component {
static propTypes = {
counter: React.PropTypes.number.isRequired,
doubleAsync: React.PropTypes.func.isRequired,
increment: React.PropTypes.func.isRequired
}
render () {
return (
<div className='container text-center'>
<TopNav />
</div>
)
}
}
export default connect(mapStateToProps, counterActions)(HomeView)
|
src/svg-icons/action/favorite.js
|
spiermar/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionFavorite = (props) => (
<SvgIcon {...props}>
<path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
</SvgIcon>
);
ActionFavorite = pure(ActionFavorite);
ActionFavorite.displayName = 'ActionFavorite';
ActionFavorite.muiName = 'SvgIcon';
export default ActionFavorite;
|
examples/universal/server/server.js
|
edge/redux
|
/* eslint-disable no-console, no-use-before-define */
import path from 'path'
import Express from 'express'
import qs from 'qs'
import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import webpackConfig from '../webpack.config'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { Provider } from 'react-redux'
import configureStore from '../common/store/configureStore'
import App from '../common/containers/App'
import { fetchCounter } from '../common/api/counter'
const app = new Express()
const port = 3000
// Use this middleware to set up hot module reloading via webpack.
const compiler = webpack(webpackConfig)
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath }))
app.use(webpackHotMiddleware(compiler))
// This is fired every time the server side receives a request
app.use(handleRender)
function handleRender(req, res) {
// Query our mock API asynchronously
fetchCounter(apiResult => {
// Read the counter from the request, if provided
const params = qs.parse(req.query)
const counter = parseInt(params.counter, 10) || apiResult || 0
// Compile an initial state
const initialState = { counter }
// Create a new Redux store instance
const store = configureStore(initialState)
// Render the component to a string
const html = renderToString(
<Provider store={store}>
<App />
</Provider>
)
// Grab the initial state from our Redux store
const finalState = store.getState()
// Send the rendered page back to the client
res.send(renderFullPage(html, finalState))
})
}
function renderFullPage(html, initialState) {
return `
<!doctype html>
<html>
<head>
<title>Redux Universal Example</title>
</head>
<body>
<div id="app">${html}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}
</script>
<script src="/static/bundle.js"></script>
</body>
</html>
`
}
app.listen(port, (error) => {
if (error) {
console.error(error)
} else {
console.info(`==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`)
}
})
|
src/containers/ServiceBookingRangePage.js
|
onlinebooking/booking-frontend
|
import React from 'react';
import ErrorAlert from '../components/ErrorAlert';
import InvalidBookPeriod from '../components/InvalidBookPeriod';
import { connect } from 'react-redux';
import Spinner from '../components/Spinner';
import BookingSteps from '../components/BookingSteps';
import BookingRange from '../components/BookingRange';
import { getBookedRange } from '../selectors/bookings';
import { find, isEqual, isArray } from 'lodash';
import moment from 'moment';
import { replace } from 'react-router-redux';
import {
book,
setBookingCalendarDate,
setBookingRange,
loadBookingRanges
} from '../actions/booking';
function loadData(props) {
const { rangeStart, rangeEnd, shopDomainName, serviceId } = props.params;
const start = moment(rangeStart, moment.ISO_8601, true);
const end = moment(rangeEnd, moment.ISO_8601, true);
if (start.isValid() && end.isValid()) {
props.setBookingCalendarDate(start.format('YYYY-MM-DD'));
props.setBookingRange({ start: rangeStart, end: rangeEnd });
props.loadBookingRanges({ loadSingleDay: true });
} else {
props.replace(`/${shopDomainName}/booking/${serviceId}`);
}
}
class ServiceBookingRangePage extends React.Component {
componentWillMount() {
loadData(this.props);
}
componentWillReceiveProps(nextProps) {
if (nextProps.params.shopDomainName !== this.props.params.shopDomainName ||
nextProps.params.serviceId !== this.props.params.serviceId ||
nextProps.params.rangeStart !== this.props.params.rangeStart ||
nextProps.params.rangeEnd !== this.props.params.rangeEnd) {
loadData(nextProps);
}
}
changeDateUrl() {
const { bookingDate, shop, service } = this.props;
return `/${shop.domain_name}/booking/${service.id}?date=${bookingDate}`;
}
changeRangeUrl() {
const { bookingDate, shop, service } = this.props;
return `/${shop.domain_name}/booking/${service.id}/at/${bookingDate}`;
}
render() {
const { range, requestedRange, fetchingRangeError, isFetchingRange } = this.props;
// Not yet a requested range
if (!requestedRange) {
return <Spinner fullpage><div>Carico la disponibilità richiesta</div></Spinner>;
}
// Error while fetching range
if (fetchingRangeError) {
return this.renderFetchingRangeError();
}
// Loading for range, no data to show yet so show a spinner!
if (isFetchingRange && !range) {
return <Spinner fullpage><div>Carico la disponibilità richiesta</div></Spinner>;
}
// No loading no range, invalid range!
if (!isFetchingRange && !range) {
return this.renderInvalidRange();
}
// Ok, we have a valid range to book!
return this.renderBookingRange();
}
renderBookingRange() {
const {
range,
isFetchingRange,
isSavingBook,
bookingDate,
bookedRange,
savingBookError,
book,
user,
service,
} = this.props;
const {schema, uiSchema } = service['booking_options_schema'];
const opacity = isFetchingRange ? '0.5' : '1';
return (
<div className="container-fluid">
<BookingSteps step={3} />
<div style={{opacity}}>
<BookingRange
range={range}
schema={schema||{}}
uiSchema={uiSchema||{}}
date={bookingDate}
loading={isSavingBook}
error={savingBookError}
bookedRange={bookedRange}
onConfirmBooking={book}
changeDateUrl={this.changeDateUrl()}
changeRangeUrl={this.changeRangeUrl()}
user={user}
/>
</div>
</div>
);
}
renderFetchingRangeError() {
const { fetchingRangeError } = this.props;
return (
<ErrorAlert
title={'Errore nel recupero della disponibilità richiesta.'}
{...fetchingRangeError}
/>
);
}
renderInvalidRange() {
const { isDateBookable, bookingDate, requestedRange } = this.props;
return <InvalidBookPeriod
date={bookingDate}
range={requestedRange}
isDateBookable={isDateBookable}
changeDateUrl={this.changeDateUrl()}
changeRangeUrl={this.changeRangeUrl()}
/>;
}
}
function mapStateToProps(state) {
const bookingDate = state.booking.calendarDate;
const requestedRange = state.booking.book.range;
const rangeItems = state.booking.ranges.items;
// Check if day of requested range is bookable
const isDateBookable = isArray(rangeItems[bookingDate]);
// Search for requested range in ranges of his day
const range = isDateBookable
? find(rangeItems[bookingDate], range => isEqual(range, requestedRange))
: null;
const user = state.auth.user;
return {
range,
requestedRange,
bookingDate,
isDateBookable,
isFetchingRange: state.booking.ranges.isFetching,
fetchingRangeError: state.booking.ranges.error,
isSavingBook: state.booking.book.isSaving,
savingBookError: state.booking.book.error,
bookedRange: getBookedRange(state),
user,
};
}
export default connect(mapStateToProps, {
replace,
setBookingCalendarDate,
setBookingRange,
loadBookingRanges,
book,
}, undefined, { pure: false })(ServiceBookingRangePage);
|
src/Base.js
|
zscaiosi/front-petdevice
|
import React, { Component } from 'react';
import { Switch, Route } from 'react-router-dom';
import Login from './components/acesso/LoginComponent';
import CadastroWraper from './components/acesso/CadastroComponent';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
import Home from './components/scenes/HomeScene';
class Base extends Component {
render() {
return (
<div className="col-md-12">
{localStorage.getItem("login") === null ? <Redirect to="/" /> : (JSON.parse(localStorage.getItem("login")).login.postLoginSuccess !== null ? <Redirect to="/home/cliente" /> : <Redirect to="/" />)}
<Switch>
<Route exact path="/" component={Login} />
<Route path="/cadastrar" component={CadastroWraper} />
<Route path="/home" component={Home} />
</Switch>
</div>
)
// return (
// <div id="base-container" >
// { localStorage.getItem("login") === null ? <Redirect to="/" /> : (JSON.parse(localStorage.getItem("login")).login.postLoginSuccess !== null ? <Redirect to="/home/cliente" /> : <Redirect to="/" />) }
// <section style={{flexDirection: 'column', display: 'flex', height: '100%', width: '100%'}} >
// <Route path="/home" component={Header} />
// { /*Header SEMPRE estará presente*/ }
// </section>
// </div>
// );
}
}
const mapStateToProps = (state) => {
return {
user: state.login.postLoginSuccess !== null ? state.login.postLoginSuccess.user : state.login.postLoginSuccess
}
}
export default connect(mapStateToProps, null)(Base);
|
js/components/AppNavigator/SceneContainer.js
|
c-h-/universal-native-boilerplate
|
import React from 'react';
import PropTypes from 'prop-types';
import {
View,
StyleSheet,
} from 'react-native';
const styles = StyleSheet.create({
container: {
flexGrow: 1,
},
});
const SceneContainer = (props) => {
const {
children,
} = props;
return (
<View style={styles.container}>
{children}
</View>
);
};
SceneContainer.propTypes = {
children: PropTypes.any,
};
export default SceneContainer;
|
packages/rmw-shell/src/pages/Roles/index.js
|
TarikHuber/react-most-wanted
|
import AccountBoxIcon from '@mui/icons-material/AccountBox'
import Avatar from '@mui/material/Avatar'
import Divider from '@mui/material/Divider'
import ListItem from '@mui/material/ListItem'
import ListItemAvatar from '@mui/material/ListItemAvatar'
import ListItemText from '@mui/material/ListItemText'
import React from 'react'
import { ListPage } from '../../containers/Page'
import { useNavigate } from 'react-router-dom'
import { useIntl } from 'react-intl'
const fields = [
{
name: 'name',
label: 'Name',
},
{
name: 'description',
label: 'Description',
},
]
const Row = ({ data, index, style }) => {
const { name = '', description = '', key } = data
const navigate = useNavigate()
return (
<div key={key} style={style}>
<ListItem
button
alignItems="flex-start"
style={{ height: 72 }}
onClick={() => {
navigate(`/roles/${key}/main`)
}}
>
<ListItemAvatar>
<Avatar>
<AccountBoxIcon />
</Avatar>
</ListItemAvatar>
<ListItemText primary={name} secondary={description} />
</ListItem>
<Divider variant="inset" />
</div>
)
}
export default function () {
const intl = useIntl()
const navigate = useNavigate()
return (
<ListPage
fields={fields}
path="roles"
createGrant="create_role"
Row={Row}
listProps={{ itemSize: 72 }}
getPageProps={() => {
return {
pageTitle: intl.formatMessage({
id: 'roles',
defaultMessage: 'Roles',
}),
}
}}
onCreateClick={() => {
navigate('/create_role')
}}
/>
)
}
|
src/Home.js
|
marzolfb/rn-art-d3-examples
|
/*
Copyright 2016 Capital One Services, LLC
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.
*/
'use strict'
import React, { Component } from 'react';
import { Text, View } from 'react-native'
class Home extends Component {
render() {
return (
<View>
<Text>Swipe from left to view menu of examples</Text>
</View>
);
}
}
export default Home;
|
src/components/Pager.js
|
jade-press/jadepress-react-spa
|
import React from 'react'
import { Link } from 'react-router'
import { createUrl, host, publicRoute, maxLink, pageSize } from '../common/constants'
import RPager from 'react-pagenav'
export default class Pager extends React.Component {
constructor (props) {
super(props)
}
unitRender() {
return (unit, index) => {
let {query, pathname} = this.props.location
let span = unit.isPager
?<span aria-hidden={true} dangerouslySetInnerHTML={ {__html: unit.html} } />
:<span dangerouslySetInnerHTML={ {__html: unit.html} } />
let sr = unit.isPager
?<span className="sr-only" dangerouslySetInnerHTML={ {__html: unit.srHtml} } />
:null
let url = {
pathname,
query: {
...query,
page: (unit.page === 1
?undefined
:unit.page)
}
}
return (
<li key={index} className={'page-item ' + unit.class}>
<Link className="page-link" to={url} aria-label={unit.ariaLabel}>
{span}
{sr}
</Link>
</li>
)
}
}
onSearch(e) {
e.preventDefault()
browserHistory.push(`/s?title=${this.state.title}`)
}
render () {
let {query} = this.props.location
let {total, post} = this.props
let state = {
page: parseInt(query.page || 1, 10),
maxLink,
pageSize,
total,
unitRender: this.unitRender.bind(this)()
}
return total > pageSize
?<RPager {...state} />
:null
}
}
|
src/components/common/picgrid.js
|
liuyuanquan/kankan
|
import React from 'react';
import polyfill from 'babel-polyfill';
class PicGrid extends React.Component {
constructor(props) {
super();
this.props = props;
this.state = {
rowNum: this.props.content.rowNum,
columnNumPerRow: this.props.content.columnNumPerRow,
currentRow: 0,
rowWidth: null
}
}
componentWillMount() {
let itemNumPerColumn = this.props.content.itemNumPerColumn;
let sum = this.props.content.sum;
let columnNumPerRow, rowNum;
let innerWidth = window.innerWidth;
if (innerWidth >= 1420) {
columnNumPerRow = this.props.content.columnNumPerRow;
} else if (innerWidth < 1420 & innerWidth >= 1180) {
columnNumPerRow = this.props.content.columnNumPerRow - 1;
} else {
columnNumPerRow = this.props.content.columnNumPerRow - 2;
}
rowNum = sum % (itemNumPerColumn * columnNumPerRow) === 0 ? sum / (itemNumPerColumn * columnNumPerRow) : Math.ceil(sum / (itemNumPerColumn * columnNumPerRow));
this.setState({
rowNum: rowNum,
columnNumPerRow: columnNumPerRow,
currentRow: 0,
rowWidth: null
});
}
componentDidMount() {
this.setState({
rowNum: this.state.rowNum,
columnNumPerRow: this.state.columnNumPerRow,
currentRow: this.state.currentRow,
rowWidth: this.refs.container.clientWidth
});
window.addEventListener('resize', () => {
let itemNumPerColumn = this.props.content.itemNumPerColumn;
let sum = this.props.content.sum;
let columnNumPerRow, rowNum;
let innerWidth = window.innerWidth;
if (innerWidth >= 1420) {
columnNumPerRow = this.props.content.columnNumPerRow;
} else if (innerWidth < 1420 & innerWidth >= 1180) {
columnNumPerRow = this.props.content.columnNumPerRow - 1;
} else {
columnNumPerRow = this.props.content.columnNumPerRow - 2;
}
rowNum = sum % (itemNumPerColumn * columnNumPerRow) === 0 ? sum / (itemNumPerColumn * columnNumPerRow) : Math.ceil(sum / (itemNumPerColumn * columnNumPerRow));
this.setState({
rowNum: rowNum,
columnNumPerRow: columnNumPerRow,
currentRow: this.state.currentRow,
rowWidth: this.refs.container.clientWidth
});
}, false);
}
switchPrev(e) {
let currentRow = this.state.currentRow - 1;
this.setState({
rowNum: this.state.rowNum,
columnNumPerRow: this.state.columnNumPerRow,
currentRow: currentRow,
rowWidth: this.refs.container.clientWidth
});
}
switchNext(e) {
let currentRow = this.state.currentRow + 1;
this.setState({
rowNum: this.state.rowNum,
columnNumPerRow: this.state.columnNumPerRow,
currentRow: currentRow,
rowWidth: this.refs.container.clientWidth
});
}
render() {
let image = this.props.content.image;
let title = this.props.content.title;
let desc = this.props.content.desc;
let extra = this.props.content.extra;
let rowNum = this.state.rowNum;
let columnNumPerRow = this.state.columnNumPerRow;
let itemNumPerColumn = this.props.content.itemNumPerColumn;
let sum = this.props.content.sum;
let type = this.props.content.type;
let switchFlag = this.props.content.switch;
let arr1 = Array.from({length: rowNum}, (value, index) => index);
let arr2 = Array.from({length: columnNumPerRow}, (value, index) => index);
let arr3 = Array.from({length: itemNumPerColumn}, (value, index) => index);
return (
<div className='contentbox4' ref='container'>
{
arr1.map((item1, index1, arr1) => {
return <div className='row' key={index1} style={{transform: `translate3d(${this.state.currentRow * -this.state.rowWidth}px, 0px, 0px)`}}>
{
arr2.map((item2, index2, arr2) => {
return (index1 * columnNumPerRow + index2 + 1) * itemNumPerColumn <= sum ? <div className='column' key={index2}>
{
arr3.map((item3, index3, arr3) => {
return <div className='item' key={index3}>
<a className='picbox'>
<img src={image[index3 + index2 * itemNumPerColumn + index1 * columnNumPerRow]} alt={title[index3 + index2 * itemNumPerColumn + index1 * columnNumPerRow]} width='220'/>
{
type !== 1 ? <div className='maskbox'>
{
type === 2 ? <div><span className='title title2'>{title[index3 + index2 * itemNumPerColumn + index1 * columnNumPerRow]}</span>
<span className='extra extra2'>{desc[index3 + index2 * itemNumPerColumn + index1 * columnNumPerRow]}</span>
<span className='drama'>{extra[index3 + index2 * itemNumPerColumn + index1 * columnNumPerRow]}</span>
</div> : <span className='extra extra1'>{desc[index3 + index2 * itemNumPerColumn + index1 * columnNumPerRow]}</span>
}
</div> : <span className='drama'>{extra[index3 + index2 * itemNumPerColumn + index1 * columnNumPerRow]}</span>
}
</a>
{
type !== 2 ? <div className='textbox1'>
{
type === 3 ? <span className='score'>{extra[index3 + index2 * itemNumPerColumn + index1 * columnNumPerRow]}</span> :
<span className='extra'>{desc[index3 + index2 * itemNumPerColumn + index1 * columnNumPerRow]}</span>
}
<a href="javascript:;" className='title title1' title={title[index3 + index2 * itemNumPerColumn + index1 * columnNumPerRow]}>{title[index3 + index2 * itemNumPerColumn + index1 * columnNumPerRow]}</a>
</div> : null
}
</div>
})
}
</div> : null
})
}
</div>
})
}
{
switchFlag ? <div>
<a className='switchimg switchL' href='javascript:;' onClick={this.switchPrev.bind(this)} style={{display: this.state.currentRow === 0 ? 'none' : 'block'}}></a>
<a className='switchimg switchR' href='javascript:;' onClick={this.switchNext.bind(this)} style={{display: this.state.currentRow === this.state.rowNum - 1 ? 'none' : 'block'}}></a>
</div> : null
}
</div>
)
}
}
export default PicGrid;
|
app/view/recommend_detail.js
|
togayther/react-stock
|
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import * as RecommendAction from '../action/recommend';
import Container from '../component/container';
import {
Article
} from 'react-weui';
class RecommendDetailApp extends React.Component {
constructor () {
super();
}
componentDidMount(){
this.getRecommendInfo();
}
getRecommendInfo(){
let id = this.props.location.query.id;
let { recommends } = this.props;
let recommendInfo = null;
if(recommends && recommends.results && recommends.results.length){
for(let i =0 ,len = recommends.results.length; i < len; i++){
let recommendItem = recommends.results[i];
if (recommendItem.id === id) {
recommendInfo = recommendItem;
break;
}
}
}
return recommendInfo;
}
render() {
let recommendInfo = this.getRecommendInfo();
return (
<Container { ...this.props}
titleEnabled = { true }
returnEnabled = { true }
menuEnabled = { false }
sidebarEnabled = { true }>
<Article>
<section>
<h2 className="title">{ recommendInfo.title }</h2>
<section>
<p dangerouslySetInnerHTML={{__html: recommendInfo.content}}>
</p>
</section>
</section>
</Article>
</Container>
);
}
}
export default connect(state => ({
recommends : state.recommend
}), dispatch => ({
recommendAction : bindActionCreators(RecommendAction, dispatch)
}))(RecommendDetailApp);
|
ui/js/pages/user/User.js
|
ericsoderberg/pbc-web
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import Show from '../../components/Show';
import Section from '../../components/Section';
import Text from '../../components/Text';
import Image from '../../components/Image';
const UserContentsBase = (props) => {
const { session } = props;
const user = props.item;
let image;
if (user.image) {
image = <Image image={user.image} avatar={true} />;
}
let text;
if (user.text) {
text = (
<Section full={false} align="start">
<Text text={user.text} />
</Section>
);
}
let associated;
if (session && (session.userId.administrator || session.userId._id === user._id)) {
associated = [
<Link key="forms"
className="associated-link"
to={`/forms?userId=${encodeURIComponent(user._id)}&userId-name=${user.name}`}>
Forms
</Link>,
<Link key="payments"
className="associated-link"
to={`/payments?userId=${user._id}&userId-name=${user.name}`}>
Payments
</Link>,
];
if (session.userId.administrator) {
associated.push(
<Link key="email"
className="associated-link"
to={`/email-lists?addresses.address=${user.email}&addresses-name=${user.email}`}>
Email Lists
</Link>,
);
}
associated = (
<div className="associated">
{associated}
</div>
);
}
return (
<div>
<Section full={false}>
<div>
<div className="user__summary">
{image}
<div className="user__heading">
<h1>{user.name}</h1>
<a href={`mailto:${user.email}`}>{user.email}</a>
</div>
</div>
</div>
</Section>
{text}
{associated}
</div>
);
};
UserContentsBase.propTypes = {
item: PropTypes.object.isRequired,
session: PropTypes.shape({
userId: PropTypes.shape({
administrator: PropTypes.bool,
domainIds: PropTypes.arrayOf(PropTypes.string),
}),
}),
};
UserContentsBase.defaultProps = {
session: undefined,
};
const select = state => ({
session: state.session,
});
const UserContents = connect(select)(UserContentsBase);
export default class User extends Show {}
User.defaultProps = {
category: 'users',
Contents: UserContents,
};
|
public/js/src/component/icons/Download.js
|
Lucifier129/isomorphism-react-file-system
|
import React from 'react'
import Icon from './Icon'
export default class Download extends React.Component {
render() {
return <Icon {...this.props} type="icon-file-download" name="Download" />
}
}
|
src/shared/HeroPicker/HeroTile.js
|
kashisau/enroute
|
/**
* HeroTile.js
*/
import React from 'react';
import './HeroTile.scss';
import classnames from 'classnames';
class HeroTile extends React.Component {
constructor(props) {
super(props);
this.state = {
active: false
};
this.changeArticle = this.changeArticle.bind(this);
}
changeArticle(e) {
e.stopPropagation();
e.nativeEvent.stopImmediatePropagation();
e.nativeEvent.preventDefault();
this.props.changeArticle(this.props.articleIndex);
return false;
}
render() {
return <div className={classnames("HeroTile", { "is-active": this.state.active })}><a
href={`/article/${this.props.article.slug}`}
title={`Read article '${this.props.article.title}'`}
onMouseOver={() => this.setState({ active: true })}
onMouseOut={() => this.setState({ active: false })}
onClick={this.changeArticle}
>{this.props.article.title}</a></div>
}
}
export default HeroTile;
|
src/containers/App.js
|
spencerkordecki/initiative-tracker
|
import React, { Component } from 'react';
import InputRow from '../components/InputRow';
import Table from '../components/Table';
import '../styles/index.scss';
const initialState = {
characters: []
};
class App extends Component {
constructor(props) {
super(props);
this.state = initialState;
}
/**
* Adds a character to the app's state based on the parameters passed in.
*/
handleSubmit = (characterName, initiative, hitPoints) => {
this.setState({
characters: [
...this.state.characters,
{
characterName: characterName,
initiative: initiative,
hitPoints: hitPoints
}
]
});
};
/**
* Removes a character from the table based on the character's index from where the
* button was clicked.
*/
removeCharacter = (index, event) => {
let characters = [...this.state.characters];
characters.splice(index, 1);
this.setState({ characters });
};
render() {
return (
<div className="app">
<InputRow onSubmit={this.handleSubmit} />
<br />
<Table
characters={this.state.characters}
removeCharacter={this.removeCharacter}
/>
</div>
);
}
}
export default App;
|
docs/app/Examples/collections/Table/Variations/TableExampleFixedLine.js
|
mohammed88/Semantic-UI-React
|
import React from 'react'
import { Table } from 'semantic-ui-react'
const TableExampleFixedLine = () => {
return (
<Table celled fixed singleLine>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>Status</Table.HeaderCell>
<Table.HeaderCell>Description</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>John</Table.Cell>
<Table.Cell>Approved</Table.Cell>
<Table.Cell
title={
[
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore',
'et dolore magna aliqua.',
].join(' ')
}
>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua.
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Jamie</Table.Cell>
<Table.Cell>Approved</Table.Cell>
<Table.Cell>Shorter description</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Jill</Table.Cell>
<Table.Cell>Denied</Table.Cell>
<Table.Cell>Shorter description</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
)
}
export default TableExampleFixedLine
|
app/containers/Admin/Messages/index.js
|
code4romania/monitorizare-vot-votanti-client
|
import React from 'react';
import MessagesStats from './components/MessagesStats';
import MessageTypeSelector from './components/MessageTypeSelector';
export class Messages extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<div>
<MessagesStats />
<MessageTypeSelector />
</div>
);
}
}
|
src/modules/texts/layouts/ReadingLayout/ReadingLayout.js
|
cltk/cltk_frontend
|
import React from 'react';
import classnames from 'classnames';
import { withRouter } from 'react-router';
import ReadingHeaderContainer from '../../containers/ReadingHeaderContainer';
import Footer from '../../../../components/navigation/Footer';
import CommentaryPanelContainer from '../../../commentary/containers/CommentaryPanelContainer';
import DefinitionsPanelContainer from '../../../definitions/containers/DefinitionsPanelContainer';
class ReadingLayout extends React.Component {
constructor(props) {
super(props);
// TODO: move this to redux store
this.state = {
showEntities: false,
showDefinitions: false,
showMedia: false,
showCommentary: false,
showTranslations: false,
showAnnotations: false,
showRelatedPassages: false,
showScansion: false,
};
}
render() {
const readingClassName = classnames('clearfix', {
'with-entities': this.state.showEntities,
'with-left-panel': this.state.showDefinitions,
'with-media': this.state.showMedia,
'with-right-panel': this.state.showCommentary || this.state.showTranslations,
'with-right-metadata': (
this.state.showMedia ||
this.state.showEntities ||
this.state.showAnnotations ||
this.state.showRelatedPassages
),
'with-scansion': this.state.showScansion,
});
return (
<div className="cltk-layout reading-layout">
<ReadingHeaderContainer
params={this.props.router.params}
/>
<main className={readingClassName}>
{this.props.children}
</main>
<DefinitionsPanelContainer />
<CommentaryPanelContainer />
<Footer />
</div>
);
}
}
export default withRouter(ReadingLayout);
|
cheesecakes/plugins/content-type-builder/admin/src/components/PluginLeftMenuLink/index.js
|
strapi/strapi-examples
|
/**
*
* PluginLeftMenuLink
* - Required props:
* - {object} Link
*
* - Optionnal props:
* - {function} renderCustomLink : overrides the behavior of the link
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import { NavLink } from 'react-router-dom';
import styles from './styles.scss';
class PluginLeftMenuLink extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
if (this.props.renderCustomLink) return this.props.renderCustomLink(this.props, styles);
const icon = this.props.customIcon || this.props.link.icon;
return (
<li className={styles.pluginLeftMenuLink}>
<NavLink className={styles.link} to={`/plugins/${this.props.basePath}/${this.props.link.name}`} activeClassName={styles.linkActive}>
<div>
<i className={`fa ${icon}`} />
</div>
<span>{this.props.link.name}</span>
</NavLink>
</li>
);
}
}
PluginLeftMenuLink.propTypes = {
basePath: PropTypes.string,
customIcon: PropTypes.string,
link: PropTypes.object.isRequired,
renderCustomLink: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.func,
]),
};
PluginLeftMenuLink.defaultProps = {
basePath: '',
customIcon: '',
renderCustomLink: false,
};
export default PluginLeftMenuLink;
|
opentech/static_src/src/app/src/components/FullScreenLoadingPanel/index.js
|
OpenTechFund/WebApp
|
import React from 'react'
import LoadingPanel from '@components/LoadingPanel'
import './styles.scss';
const FullScreenLoadingPanel = () => (
<div className="full-screen-loading-panel">
<LoadingPanel />
</div>
);
export default FullScreenLoadingPanel;
|
src/parser/warrior/fury/modules/azerite/RecklessFlurry.js
|
fyruna/WoWAnalyzer
|
import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import { formatNumber, formatPercentage, formatThousands } from 'common/format';
import TraitStatisticBox from 'interface/others/TraitStatisticBox';
import SPELLS from 'common/SPELLS';
import { SELECTED_PLAYER } from 'parser/core/EventFilter';
import SpellUsable from 'parser/shared/modules/SpellUsable';
const COOLDOWN_REDUCTION = 100;
class RecklessFlurry extends Analyzer {
static dependencies = {
spellUsable: SpellUsable,
};
recklessFlurryDamage = 0;
effectiveReduction = 0;
wastedReduction = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTrait(SPELLS.RECKLESS_FLURRY.id);
if(!this.active) {
return;
}
this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(SPELLS.RECKLESS_FLURRY_DAMAGE), this.onRecklessFlurry);
}
onRecklessFlurry(event) {
this.recklessFlurryDamage += event.amount + (event.absorbed || 0);
if (!this.spellUsable.isOnCooldown(SPELLS.RECKLESSNESS.id)) {
this.wastedReduction += COOLDOWN_REDUCTION;
} else {
const effectiveReduction = this.spellUsable.reduceCooldown(SPELLS.RECKLESSNESS.id, COOLDOWN_REDUCTION);
this.effectiveReduction += effectiveReduction;
this.wastedReduction += COOLDOWN_REDUCTION - effectiveReduction;
}
}
get damagePercentage() {
return this.owner.getPercentageOfTotalDamageDone(this.recklessFlurryDamage);
}
statistic() {
return (
<TraitStatisticBox
trait={SPELLS.RECKLESS_FLURRY.id}
value={`${formatNumber(this.effectiveReduction / 1000)}s Recklessness CDR`}
tooltip={<>Reckless Flurry did <strong>{formatThousands(this.recklessFlurryDamage)} ({formatPercentage(this.damagePercentage)}%)</strong> damage, with {formatNumber(this.wastedReduction / 1000)}s of wasted Recklessness CDR.</>}
/>
);
}
}
export default RecklessFlurry;
|
src/components/Link.js
|
leoasis/state-router
|
import React from 'react';
export default class Link extends React.Component {
static contextTypes = {
store: React.PropTypes.object,
renderUrl: React.PropTypes.func,
};
render() {
return <a href={this.calculateUrl()} onClick={this.handleClick.bind(this)}>
{this.props.children}
</a>;
}
handleClick(ev) {
ev.preventDefault();
this.props.onFollow();
}
calculateUrl() {
const {store} = this.context;
store.dispatch({type: 'ROUTE_LINK_START'});
this.props.onFollow();
const nextState = store.getState();
store.dispatch({type: 'ROUTE_LINK_END'});
return this.context.renderUrl(nextState);
}
}
|
src/articles/2017-01-31-UnlistedLogs/index.js
|
ronaldpereira/WoWAnalyzer
|
import React from 'react';
import { Zerotorescue } from 'CONTRIBUTORS';
import RegularArticle from 'interface/news/RegularArticle';
export const title = "A note about unlisted logs";
export default (
<RegularArticle
title={title}
publishedAt="2017-01-31"
publishedBy={Zerotorescue}
>
Because Warcraft Logs offers no way to access private logs through the API, your logs must either be unlisted or public if you want to analyze them. If your guild has private logs you will have to <a href="https://www.warcraftlogs.com/help/start/">upload your own logs</a> or change the existing logs to the <i>unlisted</i> privacy option instead.<br /><br />
Do note that due to a restrictive API request limit we have to aggressively cache all API requests we send to Warcraft Logs. This means that once you run a log through the analyzer, the (secret) link for that log will continue to be accessible even if you change the original log (back) to the private privacy option on Warcraft Logs. Only the fights that you accessed will remain cached indefinitely.<br /><br />
We will never share links to unlisted or private (analyzed) logs, nor include them recognizably in any public lists.
</RegularArticle>
);
|
actor-apps/app-web/src/app/components/common/AvatarItem.react.js
|
taimur97/actor-platform
|
import React from 'react';
import classNames from 'classnames';
class AvatarItem extends React.Component {
static propTypes = {
image: React.PropTypes.string,
placeholder: React.PropTypes.string.isRequired,
size: React.PropTypes.string,
title: React.PropTypes.string.isRequired
};
constructor(props) {
super(props);
}
render() {
const title = this.props.title;
const image = this.props.image;
const size = this.props.size;
let placeholder,
avatar;
let placeholderClassName = classNames('avatar__placeholder', `avatar__placeholder--${this.props.placeholder}`);
let avatarClassName = classNames('avatar', {
'avatar--tiny': size === 'tiny',
'avatar--small': size === 'small',
'avatar--medium': size === 'medium',
'avatar--big': size === 'big',
'avatar--huge': size === 'huge',
'avatar--square': size === 'square'
});
placeholder = <span className={placeholderClassName}>{title[0]}</span>;
if (image) {
avatar = <img alt={title} className="avatar__image" src={image}/>;
}
return (
<div className={avatarClassName}>
{avatar}
{placeholder}
</div>
);
}
}
export default AvatarItem;
|
src/components/comments/VoteButton.js
|
streamr-app/streamr-web
|
import React from 'react'
import cx from 'classnames'
export default ({
isSignedIn,
numVotes,
userHasVoted,
onUpvote,
onUnvote
}) => {
return (
<div
className={cx('vote-button', { active: userHasVoted, disabled: !isSignedIn })}
onClick={() => (isSignedIn && userHasVoted) ? onUnvote() : onUpvote()}
>
<i className='fa fa-thumbs-up' />
<span>{numVotes}</span>
</div>
)
}
|
test/components/Counter.spec.js
|
MitchLillie/brewhome
|
/* eslint no-unused-expressions: 0 */
import { expect } from 'chai';
import { spy } from 'sinon';
import React from 'react';
import {
renderIntoDocument,
scryRenderedDOMComponentsWithTag,
findRenderedDOMComponentWithClass,
Simulate
} from 'react-addons-test-utils';
import Counter from '../../app/components/Counter';
function setup() {
const actions = {
increment: spy(),
incrementIfOdd: spy(),
incrementAsync: spy(),
decrement: spy()
};
const component = renderIntoDocument(<Counter counter={1} {...actions} />);
return {
component,
actions,
buttons: scryRenderedDOMComponentsWithTag(component, 'button').map(button => button),
p: findRenderedDOMComponentWithClass(component, 'counter')
};
}
describe('Counter component', () => {
it('should display count', () => {
const { p } = setup();
expect(p.textContent).to.match(/^1$/);
});
it('first button should call increment', () => {
const { buttons, actions } = setup();
Simulate.click(buttons[0]);
expect(actions.increment.called).to.be.true;
});
it('second button should call decrement', () => {
const { buttons, actions } = setup();
Simulate.click(buttons[1]);
expect(actions.decrement.called).to.be.true;
});
it('third button should call incrementIfOdd', () => {
const { buttons, actions } = setup();
Simulate.click(buttons[2]);
expect(actions.incrementIfOdd.called).to.be.true;
});
it('fourth button should call incrementAsync', () => {
const { buttons, actions } = setup();
Simulate.click(buttons[3]);
expect(actions.incrementAsync.called).to.be.true;
});
});
|
src/svg-icons/hardware/phone-iphone.js
|
mmrtnz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwarePhoneIphone = (props) => (
<SvgIcon {...props}>
<path d="M15.5 1h-8C6.12 1 5 2.12 5 3.5v17C5 21.88 6.12 23 7.5 23h8c1.38 0 2.5-1.12 2.5-2.5v-17C18 2.12 16.88 1 15.5 1zm-4 21c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4.5-4H7V4h9v14z"/>
</SvgIcon>
);
HardwarePhoneIphone = pure(HardwarePhoneIphone);
HardwarePhoneIphone.displayName = 'HardwarePhoneIphone';
HardwarePhoneIphone.muiName = 'SvgIcon';
export default HardwarePhoneIphone;
|
examples/tex/js/app.js
|
davidchang/draft-js
|
/**
* Copyright (c) 2013-present, Facebook, Inc. All rights reserved.
*
* This file provided by Facebook is for non-commercial testing and evaluation
* purposes only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
'use strict';
import 'babel/polyfill';
import TeXEditorExample from './components/TeXEditorExample';
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<TeXEditorExample />,
document.getElementById('target')
);
|
src/containers/gameScreen/index.js
|
jiriKuba/Calculatic
|
import React, { Component } from 'react';
import GameScreen from '../../components/screens/gameScreen/';
export default class GameScreenContainer extends Component {
render() {
const { onMainScreen, onGameResultScreen } = this.props;
return (
<GameScreen onMainScreen = {onMainScreen}
onGameResultScreen = {onGameResultScreen} />
);
}
}
|
src/js/components/Prompt.js
|
opsdroid/opsdroid-desktop
|
'use strict';
//////
// Imports
import React from 'react';
import ReactDOM from 'react-dom';
export default class Prompt extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
showTooltip: false,
}
this.checkForEnter = this.checkForEnter.bind(this);
this.handleInput = this.handleInput.bind(this);
this.handleSend = this.handleSend.bind(this);
}
render() {
return (
<div id="prompt">
<input type="text" ref={(input) => { this.textInput = input; }} id="input" placeholder="say something..." onChange={this.handleInput} onKeyUp={this.checkForEnter} value={this.state.input} />
<input type="submit" id="send" value="Send" onClick={this.handleSend} />
<span id="status-indicator" onClick={this.props.toggleConnectionSettings} className={this.props.connected ? "active" : "inactive"}>
<span id="status-indicator-tooltip" className={this.state.showTooltip ? "active" : "inactive"}>
{this.props.connected ? "connected" : "disconnected"}
</span>
</span>
</div>
);
}
componentDidMount() {
this.focus();
}
focus() {
this.textInput.focus();
}
handleInput(event) {
this.setState({input: event.target.value});
}
handleSend() {
if (this.props.connected){
this.props.sendUserMessage(this.state.input);
this.setState({input: ''});
} else {
this.flashTooltip();
}
this.focus();
}
flashTooltip(){
this.setState({showTooltip: true});
setTimeout(() => {
this.setState({showTooltip: false})
}, 1000);
}
checkForEnter(event) {
event.preventDefault();
if (event.keyCode == 13) {
this.handleSend();
}
}
}
|
actor-apps/app-web/src/app/components/modals/create-group/Form.react.js
|
x303597316/actor-platform
|
import _ from 'lodash';
import Immutable from 'immutable';
import keymirror from 'keymirror';
import React from 'react';
import { Styles, TextField, FlatButton } from 'material-ui';
import CreateGroupActionCreators from 'actions/CreateGroupActionCreators';
import ContactStore from 'stores/ContactStore';
import ContactItem from './ContactItem.react';
import ActorTheme from 'constants/ActorTheme';
const ThemeManager = new Styles.ThemeManager();
const STEPS = keymirror({
NAME_INPUT: null,
CONTACTS_SELECTION: null
});
class CreateGroupForm extends React.Component {
static displayName = 'CreateGroupForm'
static childContextTypes = {
muiTheme: React.PropTypes.object
};
state = {
step: STEPS.NAME_INPUT,
selectedUserIds: new Immutable.Set()
}
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
textField: {
textColor: 'rgba(0,0,0,.87)',
focusColor: '#68a3e7',
backgroundColor: 'transparent',
borderColor: '#68a3e7'
}
});
}
render() {
let stepForm;
switch (this.state.step) {
case STEPS.NAME_INPUT:
stepForm = (
<form className="group-name" onSubmit={this.onNameSubmit}>
<div className="modal-new__body">
<TextField className="login__form__input"
floatingLabelText="Group name"
fullWidth
onChange={this.onNameChange}
value={this.state.name}/>
</div>
<footer className="modal-new__footer text-right">
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Add members"
secondary={true}
type="submit"/>
</footer>
</form>
);
break;
case STEPS.CONTACTS_SELECTION:
let contactList = _.map(ContactStore.getContacts(), (contact, i) => {
return (
<ContactItem contact={contact} key={i} onToggle={this.onContactToggle}/>
);
});
stepForm = (
<form className="group-members" onSubmit={this.onMembersSubmit}>
<div className="count">{this.state.selectedUserIds.size} Members</div>
<div className="modal-new__body">
<ul className="contacts__list">
{contactList}
</ul>
</div>
<footer className="modal-new__footer text-right">
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Create group"
secondary={true}
type="submit"/>
</footer>
</form>
);
break;
}
return stepForm;
}
onContactToggle = (contact, isSelected) => {
if (isSelected) {
this.setState({selectedUserIds: this.state.selectedUserIds.add(contact.uid)});
} else {
this.setState({selectedUserIds: this.state.selectedUserIds.remove(contact.uid)});
}
}
onNameChange = event => {
event.preventDefault();
this.setState({name: event.target.value});
}
onNameSubmit = event => {
event.preventDefault();
if (this.state.name) {
let name = this.state.name.trim();
if (name.length > 0) {
this.setState({step: STEPS.CONTACTS_SELECTION});
}
}
}
onMembersSubmit =event => {
event.preventDefault();
CreateGroupActionCreators.createGroup(this.state.name, null, this.state.selectedUserIds.toJS());
}
}
export default CreateGroupForm;
|
src/routes.js
|
johnnyvf24/hellochess-v2
|
import React from 'react';
import {Route, IndexRoute} from 'react-router';
import App from './containers/app';
import Login from './components/auth/login';
import Live from './containers/live';
import Profile from './containers/user/profile';
import RequireAuth from './components/auth/require_auth';
import Leaderboard from './containers/user/leaderboard';
import TosPrivacy from './components/terms_of_service_privacy';
import PlayerList from './containers/user/player_list';
export default (
<Route path="/" component={App} >
<IndexRoute to="/" component={Login} />
<Route path="/live" component={RequireAuth(Live)} />
<Route path="/profile/:id" component={Profile} />
<Route path="/leaderboard" component={Leaderboard} />
<Route path="/tosandprivacy" component={TosPrivacy} />
<Route path="/players" component={PlayerList} />
</Route>
);
|
src/components/Nav.js
|
EmilNordling/poesk
|
import React from 'react'
import styled from 'styled-components'
import { NavLink as Link } from 'react-router-dom'
import { colors } from '../constants'
const Nav = styled.nav`
display: flex;
justify-content: center;
`
const NavLink = styled(Link)`
margin: 0 12px;
font-size: 1.8rem;
text-decoration: none;
color: ${colors.gray700};
&:hover,
&:focus {
color: ${colors.gray900};
}
&.${props => props.activeClassName} {
color: ${colors.gray900};
text-decoration: line-through;
}
`
export default () => (
<Nav>
<NavLink exact to="/" activeClassName="active">
Home
</NavLink>
<NavLink to="/about" activeClassName="active">
About
</NavLink>
</Nav>
)
|
lib/factory.js
|
Kitware/arctic-viewer
|
/* global XMLHttpRequest window */
import MagicLensImageBuilder from 'paraviewweb/src/Rendering/Image/MagicLensImageBuilder';
import PixelOperatorImageBuilder from 'paraviewweb/src/Rendering/Image/PixelOperatorImageBuilder';
import ChartViewer from 'paraviewweb/src/React/Viewers/ChartViewer';
import GenericViewer from 'paraviewweb/src/React/Viewers/ImageBuilderViewer';
import GeometryViewer from 'paraviewweb/src/React/Viewers/GeometryViewer';
import MultiViewerWidget from 'paraviewweb/src/React/Viewers/MultiLayoutViewer';
import ProbeViewerWidget from 'paraviewweb/src/React/Viewers/Probe3DViewer';
import ViewerSelector from 'paraviewweb/src/React/Widgets/ButtonSelectorWidget';
import contains from 'mout/src/array/contains';
import extractURL from 'mout/src/queryString/parse';
import merge from 'mout/src/object/merge';
import React from 'react';
import ReactDOM from 'react-dom';
import viewerBuilder from './types';
import ArcticListViewer from './viewer';
// React UI map
const ReactClassMap = {
ArcticListViewer,
ChartViewer,
GenericViewer,
GeometryViewer,
MultiViewerWidget,
ProbeViewerWidget,
ViewerSelector,
};
let buildViewerForEnsemble = false;
let configOverwrite = {};
// ----------------------------------------------------------------------------
export function getJSON(url, callback) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.responseType = 'text';
xhr.onload = function onLoad(e) {
if (this.status === 200) {
callback(null, JSON.parse(xhr.response));
return;
}
callback(new Error(e), xhr);
};
xhr.onerror = function onError(e) {
callback(e, xhr);
};
xhr.send();
}
// ----------------------------------------------------------------------------
function createImageBuilderCallback(renderers, methodToCall) {
return function callback(data, envelope) {
let count = renderers.length;
while (count) {
count -= 1;
const renderer = renderers[count];
renderer[methodToCall](data);
}
};
}
// ----------------------------------------------------------------------------
function createQueryDataModelCallback(datasets, args) {
return function callback(data, envelope) {
let count = datasets.length;
const argName = data.name;
const argValue = data.value;
const datasetToUpdate = [];
if (args.indexOf(argName) !== -1) {
while (count) {
count -= 1;
const dataset = datasets[count];
if (dataset.getValue(argName) !== argValue) {
dataset.setValue(argName, argValue);
datasetToUpdate.push(dataset);
}
}
}
setImmediate(() => {
while (datasetToUpdate.length) {
datasetToUpdate.pop().fetchData();
}
});
};
}
// ----------------------------------------------------------------------------
export function bindDatasets(bindConfig, renderers) {
bindConfig.forEach((binding) => {
const datasets = [];
const rendererList = [];
Object.keys(renderers).forEach((name) => {
if (binding.datasets.indexOf(name) !== -1) {
rendererList.push(renderers[name].builder || renderers[name].painter);
if (renderers[name].builder) {
datasets.push(renderers[name].builder.queryDataModel);
}
}
});
const callbackFn = createQueryDataModelCallback(
datasets,
binding.arguments
);
datasets.forEach((queryDataModel) => {
queryDataModel.onStateChange(callbackFn);
});
// Bind image builder properties
if (binding.other) {
binding.other.forEach((rendererBinding) => {
const rendererCallback = createImageBuilderCallback(
rendererList,
rendererBinding.setter
);
rendererList.forEach((renderer) =>
renderer[rendererBinding.listener](rendererCallback)
);
});
}
// Bind image builder models
if (binding.bind) {
binding.bind.forEach((modelName) => {
const bindList = rendererList
.map((i) => i[modelName])
.filter((i) => !!i);
if (bindList.length) {
bindList[0].bind(bindList);
}
});
}
});
}
// ----------------------------------------------------------------------------
export function createOperators(operatorConfig, renderers) {
operatorConfig.forEach((operator) => {
// Create Pixel Operator
const pixelOperator = new PixelOperatorImageBuilder(
operator.operation,
operator.datasets
);
pixelOperator.name = operator.name; // Used for pixel operator if any
// Register PixelOperator
renderers[operator.name] = {
builder: pixelOperator,
name: operator.name,
};
});
// Bind each image builder after all have been created
operatorConfig.forEach((operator) => {
const pixelOperator = renderers[operator.name].builder;
// Generic callback to push data into the PixelOperator
function pushDataToPixelOperator(data, envelope) {
pixelOperator.updateData(data.builder.name, data);
}
// Listen to all datasets that PixelOperator care about
operator.datasets.forEach((name) =>
renderers[name].builder.onImageReady(pushDataToPixelOperator)
);
});
}
// ----------------------------------------------------------------------------
export function createViewer(url, callback) {
const pathItems = url.split('/');
const basepath = `${pathItems.slice(0, pathItems.length - 1).join('/')}/`;
getJSON('/config.json', (configErr, config_) => {
let config = Object.assign({}, config_, configOverwrite);
if (configErr) {
config = {};
}
// Merge config with URL parameters as well
config = merge(config, extractURL(window.location.href));
// Update configuration if we build for ensemble
if (buildViewerForEnsemble) {
config.ensemble = true;
}
getJSON(url, (error, data) => {
const dataType = data.type;
let queryDataModel = null;
let ready = 0;
if (contains(dataType, 'ensemble-dataset')) {
const renderers = {};
const expected = data.Ensemble.datasets.length;
// Let the factory know to not build everything
buildViewerForEnsemble = true;
data.Ensemble.datasets.forEach((ds) => {
createViewer(basepath + ds.data, (viewer) => {
ready += 1;
if (viewer.ui === 'ViewerSelector') {
renderers[ds.name] = {
builder: viewer.list[0].imageBuilder,
name: ds.name,
queryDataModel: viewer.list[0].queryDataModel,
};
viewer.list[0].imageBuilder.name = ds.name;
while (viewer.list.length > 1) {
viewer.list.pop().destroy();
}
} else {
renderers[ds.name] = {
builder: viewer.imageBuilder,
name: ds.name,
queryDataModel: viewer.queryDataModel,
};
viewer.imageBuilder.name = ds.name; // Used for pixel operator if any
}
if (!queryDataModel) {
queryDataModel = viewer.queryDataModel;
}
if (ready === expected) {
// Apply binding if any
bindDatasets(data.Ensemble.binding || [], renderers);
// Create pixel operators if any
createOperators(data.Ensemble.operators || [], renderers);
// Ready for UI deployment
callback({ renderers, queryDataModel, ui: 'MultiViewerWidget' });
}
});
});
} else if (contains(dataType, 'arctic-viewer-list')) {
// Show dataset listing
callback({
ui: 'ArcticListViewer',
list: data.list,
basePath: '/data/',
});
} else if (config.MagicLens && !config.ensemble) {
viewerBuilder(basepath, data, config, (background) => {
if (background.allowMagicLens) {
viewerBuilder(basepath, data, config, (viewer) => {
const defaultSynchList = ['phi', 'theta', 'n_pos', 'time'];
background.imageBuilder.queryDataModel.link(
viewer.imageBuilder.queryDataModel,
defaultSynchList,
true
);
viewer.imageBuilder.queryDataModel.link(
background.imageBuilder.queryDataModel,
defaultSynchList,
true
);
viewer.imageBuilder = new MagicLensImageBuilder(
viewer.imageBuilder,
background.imageBuilder
);
callback(viewer);
});
} else {
config.MagicLens = false;
callback(background);
}
});
} else if (viewerBuilder(basepath, data, config, callback)) {
// We are good to go
}
});
});
}
// ----------------------------------------------------------------------------
export function createUI(viewer, container, callback) {
if (viewer.bgColor && viewer.ui !== 'MultiViewerWidget') {
container.style[
viewer.bgColor.indexOf('gradient') !== -1
? 'background'
: 'background-color'
] =
viewer.bgColor;
}
// Make sure we trigger a render when the UI is mounted
setImmediate(() => {
const renderers = viewer.renderers || {};
Object.keys(renderers).forEach((name) => {
if (renderers[name].builder && renderers[name].builder.update) {
renderers[name].builder.update();
}
});
if (viewer.imageBuilder && viewer.imageBuilder.update) {
viewer.imageBuilder.update();
}
});
// Unmount any previously mounted React component
ReactDOM.unmountComponentAtNode(container);
if (viewer.ui === 'ReactComponent') {
ReactDOM.render(viewer.component, container, callback);
} else {
ReactDOM.render(
React.createElement(ReactClassMap[viewer.ui], viewer),
container,
callback
);
}
}
// ----------------------------------------------------------------------------
export function updateConfig(newConf = {}) {
configOverwrite = newConf;
}
|
__tests__/MenuOption-test.js
|
instea/react-native-popup-menu
|
import React from 'react';
import { TouchableHighlight, View, Text } from 'react-native';
import { render, normalizeStyle, nthChild } from './helpers';
jest.dontMock('../src/MenuOption');
jest.dontMock('../src/helpers');
const { MenuOption } = require('../src/MenuOption');
const { createSpy, objectContaining } = jasmine;
describe('MenuOption', () => {
const makeMockContext = ({ optionsCustomStyles, onSelect, closeMenu } = {}) => ({
menuActions: {
_getOpenedMenu: () => ({
optionsCustomStyles: optionsCustomStyles || {},
instance: { props: { onSelect: onSelect } },
}),
closeMenu: closeMenu || createSpy(),
},
});
it('should render component', () => {
const { output } = render(
<MenuOption>
<Text>Option 1</Text>
</MenuOption>,
makeMockContext()
);
expect(output.type).toEqual(TouchableHighlight);
expect(nthChild(output, 1).type).toEqual(View);
expect(nthChild(output, 2)).toEqual(
<Text>Option 1</Text>
);
});
it('should be enabled by default', () => {
const { instance } = render(
<MenuOption />,
makeMockContext()
);
expect(instance.props.disabled).toBe(false);
});
it('should trigger on select event with value', () => {
const spy = createSpy();
const { renderer } = render(
<MenuOption onSelect={spy} value='hello' />,
makeMockContext()
);
const touchable = renderer.getRenderOutput();
touchable.props.onPress();
expect(spy).toHaveBeenCalledWith('hello');
expect(spy.calls.count()).toEqual(1);
});
it('should trigger onSelect event from Menu', () => {
const spy = createSpy();
const { renderer } = render(
<MenuOption value='hello' />,
makeMockContext({ onSelect: spy })
);
const touchable = renderer.getRenderOutput();
touchable.props.onPress();
expect(spy).toHaveBeenCalledWith('hello');
expect(spy.calls.count()).toEqual(1);
});
it('should close menu on select', () => {
const spy = createSpy();
const closeMenu = createSpy();
const { renderer } = render(
<MenuOption onSelect={spy} value='hello' />,
makeMockContext({ closeMenu })
);
const touchable = renderer.getRenderOutput();
touchable.props.onPress();
expect(spy).toHaveBeenCalled();
expect(closeMenu).toHaveBeenCalled();
});
it('should not close menu on select', () => {
const spy = createSpy().and.returnValue(false);
const closeMenu = createSpy()
const { renderer } = render(
<MenuOption onSelect={spy} value='hello' />,
makeMockContext({ closeMenu })
);
const touchable = renderer.getRenderOutput();
touchable.props.onPress();
expect(spy).toHaveBeenCalled();
expect(closeMenu).not.toHaveBeenCalled();
});
it('should not trigger event when disabled', () => {
const spy = createSpy();
const { output } = render(
<MenuOption onSelect={spy} disabled={true} />,
makeMockContext()
);
expect(output.type).toBe(View);
expect(output.props.onPress).toBeUndefined();
});
it('should render text passed in props', () => {
const { output } = render(
<MenuOption text='Hello world' />,
makeMockContext()
);
expect(output.type).toEqual(TouchableHighlight);
expect(output.props.children.type).toEqual(View);
const text = output.props.children.props.children;
expect(text).toEqual(
<Text>Hello world</Text>
);
});
it('should render component with custom styles', () => {
const customStyles = {
optionWrapper: { backgroundColor: 'red' },
optionText: { color: 'blue' },
optionTouchable: { underlayColor: 'green' },
};
const { output } = render(
<MenuOption text='some text' customStyles={customStyles} />,
makeMockContext()
);
const touchable = output;
const view = nthChild(output, 1);
const text = nthChild(output, 2);
expect(normalizeStyle(touchable.props))
.toEqual(objectContaining({ underlayColor: 'green' }));
expect(normalizeStyle(view.props.style))
.toEqual(objectContaining(customStyles.optionWrapper));
expect(normalizeStyle(text.props.style))
.toEqual(objectContaining(customStyles.optionText));
});
it('should render component with inherited custom styles', () => {
const optionsCustomStyles = {
optionWrapper: { backgroundColor: 'pink' },
optionText: { color: 'yellow' },
};
const customStyles = {
optionText: { color: 'blue' },
optionTouchable: { underlayColor: 'green' },
};
const { output } = render(
<MenuOption text='some text' customStyles={customStyles} />,
makeMockContext({ optionsCustomStyles })
);
const touchable = output;
const view = nthChild(output, 1);
const text = nthChild(output, 2);
expect(normalizeStyle(touchable.props))
.toEqual(objectContaining({ underlayColor: 'green' }));
expect(normalizeStyle(view.props.style))
.toEqual(objectContaining(optionsCustomStyles.optionWrapper));
expect(normalizeStyle(text.props.style))
.toEqual(objectContaining(customStyles.optionText));
})
});
|
build/libs/Adapter/src/lib/components/C3/ScatterPlot.js
|
as-me/dashboard
|
import React from 'react';
import C3ScatterPlot from './ScatterPlotUI';
import '../../session/ScatterPlot.js';
import 'weavecore';
//namesapce
if (typeof window === 'undefined') {
this.adapter = this.adapter || {};
} else {
window.adapter = window.adapter || {};
}
if (typeof window === 'undefined') {
this.adapter.libs = this.adapter.libs || {};
} else {
window.adapter.libs = window.adapter.libs || {};
}
if (typeof window === 'undefined') {
this.adapter.libs.c3 = this.adapter.libs.c3 || {};
} else {
window.adapter.libs.c3 = window.adapter.libs.c3 || {};
}
(function () {
Object.defineProperty(ScatterPlot, 'NS', {
value: 'adapter.libs.c3'
});
Object.defineProperty(ScatterPlot, 'CLASS_NAME', {
value: 'ScatterPlot'
});
function ScatterPlot() {
/**
* @public
* @property sessionable
* @readOnly
* @type Booloean
*/
Object.defineProperty(this, 'sessionable', {
value: true
});
/**
* @public
* @property ns
* @readOnly
* @type String
*/
Object.defineProperty(this, 'ns', {
value: 'adapter.libs.c3'
});
/**
* @public
* @property library
* @readOnly
* @type String
*/
Object.defineProperty(this, 'library', {
value: 'c3'
});
/**
* @public
* @property data
* @readOnly
* @type String
*/
Object.defineProperty(this, 'sessionData', {
value: WeaveAPI.SessionManager.registerLinkableChild(this, new adapter.session.ScatterPlot())
});
/**
* @public
* @property hook
* @readOnly
* @type d3Chart.Scatterplot
*/
Object.defineProperty(this, 'hook', {
value: new adapter.hook.C3Interface()
});
}
// Prototypes.
var p = ScatterPlot.prototype;
p.createUI = function (padding, size, interactions) {
/**
* @public
* @property ui
* @readOnly
* @type ReactElement
*/
if (!this.ui) {
Object.defineProperty(this, 'ui', {
value: React.createElement(C3ScatterPlot, {
sessionData: this.sessionData,
padding: {
top: padding.top,
bottom: padding.bottom,
left: padding.left,
right: padding.right
},
size: {
width: size.width,
height: size.height
},
height: size.height,
onProbe: interactions.onProbe,
onSelect: interactions.onSelect,
hook: this.hook
})
});
}
}
//TO-DO: Find a way for class part of Modules
// Need to save them global data in window object , as we need to create the object at runtime, we need namesapce
// where as in module provide by webpack we can't get the constructor name.
adapter.libs.c3.ScatterPlot = ScatterPlot;
}());
|
src/containers/utils/Root.prod.js
|
hannupekka/badgenator
|
// @flow
import React from 'react';
import { Provider } from 'react-redux';
import Routes from 'containers/utils/Routes';
const Root = ({ store, history }: { store: Object, history: Object }): ElementType => {
return (
<Provider store={store}>
<Routes history={history} />
</Provider>
);
};
module.exports = Root;
|
tests/layouts/MainScreenSpec.js
|
andela-iukwuoma/newsfeed
|
import React from 'react';
import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';
import { shallow } from 'enzyme';
import MainScreen from '../../src/app/components/layouts/MainScreen';
import Article from '../../src/app/components/Article';
import Sort from '../../src/app/components/Sort';
import * as data from '../testData';
chai.use(chaiEnzyme());
const expect = chai.expect;
describe('The MainScreen component', () => {
it('should be defined', () => {
expect(<MainScreen />).to.not.equal(undefined);
});
});
const wrapper = shallow(<MainScreen {...data}/>);
describe('After rendering, the mainscreen component', () => {
it('should have a div as the first child', () => {
expect(wrapper).to.have.tagName('div');
});
it('should have Article as its child component', () => {
expect(wrapper).to.have.descendants(Article);
});
it('should have an element with class name `main-headers`', () => {
expect(wrapper.find('.main-headers')).be.present();
});
it('should have a select tag with class name `styled-select`', () => {
expect(wrapper.find('select')).to.match('.styled-select');
});
it('should contain the text `News` in the h2 tag', () => {
expect(wrapper.find('h2')).to.contain.text('News');
});
it('should have the default value `sortby` for the select tag', () => {
expect(wrapper.find('select')).to.have.value('sortby');
});
it('should have option tags with attributes of `value`', () => {
expect(wrapper.find('option')).to.have.attr('value');
});
it('should have a state with key `defaultSort` and value `sortby`', () => {
expect(wrapper).to.have.state('defaultSort', 'sortby');
});
});
describe('The Article component, child of MainScreen,', () => {
it('should receives props named `article` from MainScreen', () => {
expect(wrapper.find(Article).first()).to.have.prop('article');
});
});
describe('The component', () => {
const children = wrapper.children();
it('should have two direct children of the top most div', () => {
expect(children).to.have.length(2);
});
it('should have a first child with an class of `main-headers`', () => {
expect(children.at(0)).to.have.className('main-headers');
});
it('should have a select tag with class of `styled-select`', () => {
expect(children.at(0).find('select')).to.have.className('styled-select');
});
it('should have a second child with an class name of `row`', () => {
expect(children.at(1)).to.have.className('row');
});
});
|
docs/src/sections/JumbotronSection.js
|
jesenko/react-bootstrap
|
import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function JumbotronSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="jumbotron">Jumbotron</Anchor> <small>Jumbotron</small>
</h2>
<p>A lightweight, flexible component that can optionally extend the entire viewport to showcase key content on your site.</p>
<ReactPlayground codeText={Samples.Jumbotron} />
<h3><Anchor id="jumbotron-props">Props</Anchor></h3>
<PropTable component="Jumbotron"/>
</div>
);
}
|
classic/src/scenes/wbui/SettingsListSection.js
|
wavebox/waveboxapp
|
import React from 'react'
import { List, Paper } from '@material-ui/core'
import shallowCompare from 'react-addons-shallow-compare'
import SettingsListContainer from './SettingsListContainer'
import SettingsListSectionTitle from './SettingsListSectionTitle'
class SettingsListSection extends React.Component {
/* **************************************************************************/
// Class
/* **************************************************************************/
static propTypes = {
...SettingsListSectionTitle.propTypes
}
/* **************************************************************************/
// Rendering
/* **************************************************************************/
shouldComponentUpdate (nextProps, nextState) {
return shallowCompare(this, nextProps, nextState)
}
render () {
const { classes, title, icon, subtitle, children, ...passProps } = this.props
return (
<SettingsListContainer {...passProps}>
<SettingsListSectionTitle title={title} subtitle={subtitle} icon={icon} />
<Paper>
<List dense>
{children}
</List>
</Paper>
</SettingsListContainer>
)
}
}
export default SettingsListSection
|
src/docs/ComponentPage.js
|
ThomasBem/ps-react-thomasbem
|
import React from 'react';
import PropTypes from 'prop-types';
import Example from './Example';
import Props from './Props';
const ComponentPage = ({component}) => {
const {name, description, props, examples} = component;
return (
<div className="componentpage">
<h2>{name}</h2>
<p>{description}</p>
<h3>Example{examples.length > 1 && "s"}</h3>
{
examples.length > 0 ?
examples.map( example => <Example key={example.code} example={example} componentName={name} /> ) :
"No examples exist."
}
<h3>Props</h3>
{
props ?
<Props props={props} /> :
"This component accepts no props."
}
</div>
)
};
ComponentPage.propTypes = {
component: PropTypes.object.isRequired
};
export default ComponentPage;
|
core/index.node.js
|
pawelgalazka/firestarter
|
import express from 'express'
import React from 'react'
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
import { match, RouterContext } from 'react-router'
import { Provider } from 'react-redux'
import routes from '../config/routes'
import { createStore } from '../config/store'
import webpackConfig from '../config/webpack/common'
import IndexPage from '../config/index.html'
import { prefetch } from './utils'
let bundleFileName = webpackConfig.output.filename
const styles = [`${webpackConfig.output.publicPath}bootstrap/css/bootstrap.min.css`]
if (process.env.NODE_ENV === 'production') {
const manifest = require('../build/manifest.json')
bundleFileName = manifest['main.js']
styles.push(`${webpackConfig.output.publicPath}${manifest['main.css']}`)
}
const scripts = [`${webpackConfig.output.publicPath}${bundleFileName}`]
function indexPageSanitizer (content) {
return `
<!DOCTYPE html>
${content}
`
}
function renderView (renderProps, req, res) {
const store = createStore()
prefetch(renderProps, store.dispatch)
.then(() => {
const contentHtml = renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
)
const indexPageHtml = renderToStaticMarkup(
<IndexPage initialState={store.getState()} styles={styles} scripts={scripts} innerHTML={contentHtml} />
)
res.status(200).send(indexPageSanitizer(indexPageHtml))
})
.catch((err) => {
console.error(err.stack)
})
}
function render (req, res, next) {
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
if (error) {
res.status(500).send(error.message)
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search)
} else if (renderProps) {
renderView(renderProps, req, res)
} else {
res.status(404).send('Not found')
}
})
}
const app = express()
app.use(render)
app.listen(7000, () => {
console.log('Application is served at http://localhost:7000')
})
|
js/src/dapps/dappreg/ModalUpdate/modalUpdate.js
|
jesuscript/parity
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import React, { Component } from 'react';
import { observer } from 'mobx-react';
import DappsStore from '../dappsStore';
import ModalStore from '../modalStore';
import Button from '../Button';
import Modal from '../Modal';
import styles from '../Modal/modal.css';
const HEADERS = [
'Error During Update',
'Confirm Application Update',
'Waiting for Signer Confirmation',
'Waiting for Transaction Receipt',
'Update Completed'
];
const STEP_ERROR = 0;
const STEP_CONFIRM = 1;
const STEP_SIGNER = 2;
const STEP_TXRECEIPT = 3;
const STEP_DONE = 4;
@observer
export default class ModalUpdate extends Component {
dappsStore = DappsStore.instance();
modalStore = ModalStore.instance();
render () {
if (!this.modalStore.showingUpdate) {
return null;
}
return (
<Modal
buttons={ this.renderButtons() }
error={ this.modalStore.errorUpdate }
header={ HEADERS[this.modalStore.stepUpdate] }
>
{ this.renderStep() }
</Modal>
);
}
renderButtons () {
switch (this.modalStore.stepUpdate) {
case STEP_ERROR:
case STEP_DONE:
return [
<Button
key='close'
label='Close'
onClick={ this.onClickClose }
/>
];
case STEP_CONFIRM:
return [
<Button
key='cancel'
label='No, Cancel'
onClick={ this.onClickClose }
/>,
<Button
key='delete'
label='Yes, Update'
warning
onClick={ this.onClickYes }
/>
];
default:
return null;
}
}
renderStep () {
switch (this.modalStore.stepUpdate) {
case STEP_CONFIRM:
return this.renderStepConfirm();
case STEP_SIGNER:
return this.renderStepWait('Waiting for transaction confirmation in the Parity secure signer');
case STEP_TXRECEIPT:
return this.renderStepWait('Waiting for the transaction receipt from the network');
case STEP_DONE:
return this.renderStepCompleted();
default:
return null;
}
}
renderStepCompleted () {
return (
<div>
<div className={ styles.section }>
Your application metadata has been updated in the registry.
</div>
</div>
);
}
renderStepConfirm () {
return (
<div>
<div className={ styles.section }>
You are about to update the application details in the registry, the details of these updates are given below. Please note that each update will generate a seperate transaction.
</div>
<div className={ styles.section }>
<div className={ styles.heading }>
Application identifier
</div>
<div>
{ this.dappsStore.wipApp.id }
</div>
</div>
{ this.renderChanges() }
</div>
);
}
renderChanges () {
return ['content', 'image', 'manifest']
.filter((type) => this.dappsStore.wipApp[`${type}Changed`])
.map((type) => {
return (
<div className={ styles.section } key={ `${type}Update` }>
<div className={ styles.heading }>
Updates to { type } hash
</div>
<div>
<div>{ this.dappsStore.wipApp[`${type}Hash`] || '(removed)' }</div>
<div className={ styles.hint }>
{ this.dappsStore.wipApp[`${type}Url`] || 'current url to be removed from registry' }
</div>
</div>
</div>
);
});
}
renderStepWait (waitingFor) {
return (
<div>
<div className={ styles.section }>
{ waitingFor }
</div>
</div>
);
}
onClickClose = () => {
this.modalStore.hideUpdate();
}
onClickYes = () => {
this.modalStore.doUpdate();
}
}
|
src/scenes/dashboard/groupprofile/index.js
|
PowerlineApp/powerline-rn
|
//This is the Group Profile Screen. Accessible by viewing tapping any group avatar or title anywhere it appears in the app, including My Groups, Standard Item Container, and Group Search
//GH 46
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Actions } from 'react-native-router-flux';
import {
Content,
Container,
Item,
Input,
Title,
Button,
Header,
Body,
Left,
Right,
Label,
Icon,
List,
ListItem,
Thumbnail,
Text
} from 'native-base';
import {
View,
RefreshControl,
Alert
} from 'react-native';
import styles from './styles';
const PLColors = require('PLColors');
import { getGroupDetails, inviteAllFollowers, getFollowers, unJoinGroup, getGroupPermissions } from 'PLActions';
class GroupProfile extends Component{
static propTypes = {
token: React.PropTypes.string
};
// The user will be asked to share the information with group owner upon joining the group
//GH59
permissionsLabels = {
"permissions_name":"Name",
"permissions_address":"Street Address",
"permissions_city":"City",
"permissions_state":"State",
"permissions_country":"Country",
"permissions_zip_code":"Zip Code",
"permissions_email":"Email",
"permissions_phone":"Phone Number",
"permissions_responses":"Responses"
};
constructor(props){
super(props);
this.state = {
permissions: [],
data: null,
refreshing: false,
refresh: false
};
this.unjoin = this.unjoin.bind(this);
this.join = this.join.bind(this);
}
componentWillMount(){
this._onRefresh();
}
loadGroup(){
if(this.props.required_permissions){
this.props.required_permissions.map((value, index) => {
this.state.permissions.push(this.permissionsLabels[value]);
});
}else{
this.state.permissions = [];
}
var { token, id } = this.props;
console.log('ioddd', id);
getGroupDetails(token, id).then(data => {
this.setState({
data: data,
refreshing: false
})
})
.catch(err => {
});
//GH59
getGroupPermissions(token, id).then(data => {
if(data.required_permissions){
data.required_permissions.map((value, index) => {
this.state.permissions.push(this.permissionsLabels[value]);
});
this.setState({
refresh: true
});
}
}).catch(err => {
});
}
_onRefresh(){
this.setState({
refreshing: true
});
this.loadGroup();
}
goToGroupMembers(){
Actions.groupmembers(this.state.data);
}
//This provides a user to invite all of their followers to a particular group.
//This will eventually be changed to allow a user to choose 1 or more users to invite to a group instead of all
invite(){
Alert.alert(
'Confirm',
'Are you sure you want to invite all of your followers to join this group?',
[
{
text: 'Cancel',
onPress: () => {
}
},
{
text: 'OK',
onPress: () => {
var { token } = this.props;
getFollowers(token, 1, 10).then(data => {
var users = [];
for (var i = 0; i < data.payload.length; i++){
users.push(data.payload[i].username);
}
inviteAllFollowers(token, this.state.data.id, users).then(data => {
alert("Invites sent!");
})
.catch(err => {
alert("Cannot send invites at this time. Try again later.");
});
})
.catch(err => {
});
}
}
],
{cancelable: false}
);
}
unjoin(){
Alert.alert(
'Are you Sure',
'',
[
{
text: 'Cancel',
onPress: () => {
}
},
{
text: 'OK',
onPress: () => {
var { token, id } = this.props;
unJoinGroup(token, id).then(data => {
this.state.data.joined = false;
this.state.data.total_member = this.state.data.total_member - 1;
this.setState({
refreshing: false
});
})
.catch(err => {
});
}
}
],
{cancelable: false}
);
}
join(){
var { id } = this.props;
}
render(){
return (
<Container style={styles.container}>
<Header style={styles.header}>
<Left>
<Button transparent onPress={() => Actions.pop()} style={{width: 50, height: 50 }} >
<Icon active name="arrow-back" style={{color: 'white'}}/>
</Button>
</Left>
<Body>
<Title>Group Profile</Title>
</Body>
<Right>
<Button transparent onPress={() => this.invite()}>
<Label style={{color: 'white'}}>Invite</Label>
</Button>
</Right>
</Header>
<Content
padder
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this._onRefresh.bind(this)}
/>
}
>
{this.state.data?
<List style={{marginLeft: 17, marginTop: 17}}>
<ListItem style={{backgroundColor: 'white', marginLeft: 0, paddingLeft: 17}}>
{this.state.data.avatar_file_path?
<Thumbnail style={styles.avatar} square source={{uri: this.state.data.avatar_file_path+'&w=50&h=50&auto=compress,format,q=95'}}/>:
<View style={styles.avatar}/>
}
<Body>
<Text style={{color: PLColors.main}}>{this.state.data.official_name}</Text>
{this.state.data.joined?
<Button block style={styles.unjoinBtn} onPress={() => this.unjoin()}>
<Label style={{color: 'white'}}>Unjoin</Label>
</Button>:
<Button block style={styles.joinBtn} onPress={() => this.join()}>
<Label style={{color: 'white'}}>Join</Label>
</Button>
}
</Body>
</ListItem>
{this.state.data.official_description?
<ListItem style={styles.listItem}>
<Text style={styles.groupDescription}>{this.state.data.official_description}</Text>
</ListItem>:null}
{this.state.data.joined?
<ListItem style={{borderBottomWidth: 0}}>
<Body>
<Button block style={{backgroundColor: PLColors.main}}>
<Label style={{color: 'white'}}>Manage</Label>
</Button>
</Body>
</ListItem>:
<ListItem style={{borderBottomWidth: 0, height: 40}}>
<Text> </Text>
</ListItem>}
{this.state.data.acronym?
<ListItem style={styles.listItem}>
<Body>
<Text style={styles.listItemTextField}>Acronym</Text>
<Text style={styles.listItemValueField}>{this.state.data.acronym}</Text>
</Body>
</ListItem>: null}
{this.state.data.membership_control?
<ListItem style={styles.listItem}>
<Body>
<Text style={styles.listItemTextField}>Membership</Text>
<Text style={styles.listItemValueField}>{this.state.data.membership_control}</Text>
</Body>
</ListItem>:null}
{this.state.data.manager_phone?
<ListItem style={styles.listItem}>
<Body>
<Text style={styles.listItemTextField}>Phone Number</Text>
<Text style={styles.listItemValueField}>{this.state.data.manager_phone}</Text>
</Body>
</ListItem>: null}
{this.state.data.official_state || this.state.data.official_city || this.state.data.official_address?
<ListItem style={styles.listItem}>
<Body>
<Text style={styles.listItemTextField}>Location</Text>
<Text style={styles.listItemValueField}>{this.state.data.official_address} {this.state.data.official_city},{this.state.data.official_state}</Text>
</Body>
</ListItem>: null}
{this.state.data.total_members?
<ListItem style={styles.listItem} onPress={() => this.goToGroupMembers()}>
<Body>
<Text style={styles.listItemTextField}>Total Members</Text>
<Text style={styles.listItemValueField}>{this.state.data.total_members}</Text>
</Body>
</ListItem>: null}
{this.state.permissions.length > 0?
<ListItem style={styles.listItem}>
<Body>
<Text style={styles.listItemTextField}>Permissions</Text>
<Text style={styles.listItemValueField}>
{
this.state.permissions.join(',')
}
</Text>
</Body>
</ListItem>: null}
</List> : null}
</Content>
</Container>
)
}
}
const mapStateToProps = state => ({
token: state.user.token
});
const mapDispatchToProps = dispatch => ({
openDrawer: () => dispatch(openDrawer())
});
export default connect(mapStateToProps, mapDispatchToProps)(GroupProfile);
|
src/font-icon.js
|
joxoo/react-material
|
import React from 'react';
import PropTypes from 'prop-types';
import { getClassesStatic } from './addons/get-classes';
const FontIcon = (props) => (
<i className={ getClassesStatic('font-icon', props) }>
{ props.icon.startsWith('0x') ? String.fromCharCode(props.icon) : props.icon }
</i>
);
FontIcon.propTypes = {
background: PropTypes.string,
color: PropTypes.string,
icon: PropTypes.string
};
export default FontIcon;
|
app/components/Work/WorkSection/index.js
|
yasserhennawi/yasserhennawi
|
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'utils/styled-components';
const Wrapper = styled.div`
display: flex;
flex-direction: column;
`;
const Title = styled.h4`
font-weight: normal;
margin-bottom: 5px;
`;
const WorkSection = ({ title, children, ...props }) => (
<Wrapper {...props}>
<Title>{title}</Title>
{children}
</Wrapper>
);
WorkSection.propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node,
]),
title: PropTypes.string,
};
export default WorkSection;
|
lavalab/html/node_modules/react-bootstrap/es/Row.js
|
LavaLabUSC/usclavalab.org
|
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 elementType from 'prop-types-extra/lib/elementType';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
componentClass: elementType
};
var defaultProps = {
componentClass: 'div'
};
var Row = function (_React$Component) {
_inherits(Row, _React$Component);
function Row() {
_classCallCheck(this, Row);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Row.prototype.render = function render() {
var _props = this.props,
Component = _props.componentClass,
className = _props.className,
props = _objectWithoutProperties(_props, ['componentClass', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement(Component, _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return Row;
}(React.Component);
Row.propTypes = propTypes;
Row.defaultProps = defaultProps;
export default bsClass('row', Row);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.