path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
stories/CardContent.stories.js
|
nekuno/client
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { linkTo } from '@storybook/addon-links'
import CardContent from '../src/js/components/ui/CardContent/CardContent.js';
storiesOf('CardContent', module)
.add('with text', () => (
<CardContent onClickHandler={action('clicked')}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam et elit ante.
</CardContent>
))
.add('with HTML', () => (
<CardContent onClickHandler={action('clicked')}>
<div>Lorem ipsum</div>
<br/>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam et elit ante.</div>
</CardContent>
));
|
examples/passing-props-to-children/app.js
|
batmanimal/react-router
|
import React from 'react';
import { Router, Route, Link, History } from 'react-router';
var App = React.createClass({
mixins: [ History ],
getInitialState() {
return {
tacos: [
{ name: 'duck confit' },
{ name: 'carne asada' },
{ name: 'shrimp' }
]
};
},
addTaco() {
var name = prompt('taco name?');
this.setState({
tacos: this.state.tacos.concat({name: name})
});
},
handleRemoveTaco(removedTaco) {
var tacos = this.state.tacos.filter(function (taco) {
return taco.name != removedTaco;
});
this.setState({tacos: tacos});
this.history.pushState(null, '/');
},
render() {
var links = this.state.tacos.map(function (taco, i) {
return (
<li key={i}>
<Link to={`/taco/${taco.name}`}>{taco.name}</Link>
</li>
);
});
return (
<div className="App">
<button onClick={this.addTaco}>Add Taco</button>
<ul className="Master">
{links}
</ul>
<div className="Detail">
{this.props.children && React.cloneElement(this.props.children, {
onRemoveTaco: this.handleRemoveTaco
})}
</div>
</div>
);
}
});
var Taco = React.createClass({
remove() {
this.props.onRemoveTaco(this.props.params.name);
},
render() {
return (
<div className="Taco">
<h1>{this.props.params.name}</h1>
<button onClick={this.remove}>remove</button>
</div>
);
}
});
React.render((
<Router>
<Route path="/" component={App}>
<Route path="taco/:name" component={Taco} />
</Route>
</Router>
), document.getElementById('example'));
|
webpack/containers/Application/index.js
|
Katello/katello
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BrowserRouter as Router } from 'react-router-dom';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { orgId } from '../../services/api';
import * as actions from '../../scenes/Organizations/OrganizationActions';
import reducer from '../../scenes/Organizations/OrganizationReducer';
import Routes from './Routes';
import './overrides.scss';
const mapStateToProps = state => ({ organization: state.organization });
const mapDispatchToProps = dispatch => bindActionCreators(actions, dispatch);
export const organization = reducer;
class Application extends Component {
componentDidMount() {
this.loadData();
}
loadData() {
if (orgId()) {
this.props.loadOrganization();
}
}
render() {
return (
<Router>
<Routes />
</Router>
);
}
}
Application.propTypes = {
loadOrganization: PropTypes.func.isRequired,
};
export default connect(mapStateToProps, mapDispatchToProps)(Application);
|
src/esm/components/graphics/icons/lock-icon/index.js
|
KissKissBankBank/kitten
|
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["color", "title", "width", "height"];
import React from 'react';
import PropTypes from 'prop-types';
import COLORS from '../../../../constants/colors-config';
import { computeFromRatio } from '../../../../helpers/utils/ratio';
var DEFAULT_WIDTH = 14;
var DEFAULT_HEIGHT = 18;
export var LockIcon = function LockIcon(_ref) {
var color = _ref.color,
title = _ref.title,
width = _ref.width,
height = _ref.height,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
var computed = computeFromRatio({
defaultWidth: DEFAULT_WIDTH,
defaultHeight: DEFAULT_HEIGHT,
width: width,
height: height
});
return /*#__PURE__*/React.createElement("svg", _extends({
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 14 18",
width: computed.width,
height: computed.height,
fill: color
}, props), title && /*#__PURE__*/React.createElement("title", null, title), /*#__PURE__*/React.createElement("path", {
d: "M5,6 L9,6 L9,4 C9,2.8954305 8.1045695,2 7,2 C5.8954305,2 5,2.8954305 5,4 L5,6 Z M11,6 L14,6 L14,18 L0,18 L0,6 L3,6 L3,4 C3,1.790861 4.790861,0 7,0 C9.209139,0 11,1.790861 11,4 L11,6 Z M6.5,11.9146471 L6.5,14.5 C6.5,14.7761424 6.72385763,15 7,15 C7.27614237,15 7.5,14.7761424 7.5,14.5 L7.5,11.9146471 C8.08259619,11.7087289 8.5,11.1531094 8.5,10.5 C8.5,9.67157288 7.82842712,9 7,9 C6.17157288,9 5.5,9.67157288 5.5,10.5 C5.5,11.1531094 5.91740381,11.7087289 6.5,11.9146471 Z"
}));
};
LockIcon.propTypes = {
color: PropTypes.string,
title: PropTypes.string,
width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
};
LockIcon.defaultProps = {
color: COLORS.background1
};
|
source/common/components/HomePage/HomePage.js
|
shery15/react
|
import React from 'react';
import { Link } from 'react-router';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
const HomePage = ({
userId,
onSubmitUserId,
onChangeUserId
}) => {
return (
<div>
<TextField
hintText="Please Key in your Github User Id."
onChange={onChangeUserId}
/>
<RaisedButton label="Submit" onClick={onSubmitUserId(userId)} primary />
<Link
to={{
pathname: '/result',
query: { userId }
}}
/>
</div>
);
// return (
// <div>
// </div>
// );
};
export default HomePage;
|
stories/Popover.js
|
propertybase/react-lds
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { boolean, text, select } from '@storybook/addon-knobs';
import { Popover, MediaObject, Icon } from '../src';
import { getThemesWithoutTexture } from './utils/helpers';
const stories = storiesOf('Popover', module);
const icon = <Icon sprite="standard" size="small" icon="account" />;
const sampleHeader = (<p className="slds-text-heading--medium slds-hyphenate"><a href="#anchor">Sample Account</a></p>);
const sampleText = (
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugiat minus molestias
reprehenderit consequuntur sapiente. Modi veritatis totam accusantium numquam assumenda.</p>
);
const header = (
<div>
<MediaObject figureLeft={icon} className="slds-m-bottom--small">{sampleHeader}</MediaObject>
{sampleText}
</div>
);
const icon2 = <Icon sprite="standard" size="small" icon="opportunity" />;
const sampleHeader2 = (<p className="slds-text-heading--small slds-hyphenate">Sample Opportunity</p>);
const sampleText2 = (<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugiat minus molestias
reprehenderit consequuntur sapiente. Modi veritatis totam accusantium numquam assumenda.</p>);
const body = (
<div>
<div className="slds-popover__body-list">
<MediaObject figureLeft={icon2} className="slds-m-bottom--small">{sampleHeader2}</MediaObject>
{sampleText2}
</div>
<div className="slds-popover__body-list">
<MediaObject figureLeft={icon2} className="slds-m-bottom--small">{sampleHeader2}</MediaObject>
{sampleText2}
</div>
</div>
);
stories
.add('Default', () => (
<Popover
open={boolean('Open', true)}
closeable={boolean('Closeable', true)}
onClose={action('Clicked close!')}
header={text('Header', 'Header can be element or string')}
body={text('Body', 'Body can be element or string')}
footer={text('Footer', '')}
nubbin={select('Nubbin', [
'',
'left',
'left-top',
'left-bottom',
'top-left',
'top-right',
'right-top',
'right-bottom',
'bottom-left',
'bottom-right',
], '') || undefined}
customHeaderTheme={select('CustomHeaderTheme', [
'',
'warning',
'error',
'success',
'info'
], '') || undefined}
theme={getThemesWithoutTexture()}
/>
))
.add('Panels', () => (
<Popover
open
closeable
onClose={action('Clicked close!')}
header={header}
body={body}
nubbin={select('Nubbin', [
'',
'left',
'left-top',
'left-bottom',
'top-left',
'top-right',
'right-top',
'right-bottom',
'bottom-left',
'bottom-right',
], '') || undefined}
panels
/>
));
|
src/components/article/HeaderOne.js
|
garfieldduck/twreporter-react
|
'use strict'
import commonStyles from './Common.scss'
import styles from './HeaderOne.scss'
import classNames from 'classnames'
import React from 'react' // eslint-disable-next-line
// lodash
import get from 'lodash/get'
export const HeaderOne = ({ content }) => {
return <h1 className={classNames(commonStyles['inner-block'],
styles['title'], 'text-justify')} dangerouslySetInnerHTML={{ __html: get(content, [ 0 ], '') }}></h1>
}
|
src/component/component.js
|
APSL/redux-i18n
|
/*
* Project: redux-i18n
* File: component/component.js
*/
import React from 'react'
import {PropTypes} from 'prop-types'
import {setForceRefresh, setLanguage} from '../actions'
import getTranslateFunction from '../getTranslateFunction';
class I18n extends React.Component {
getChildContext() {
const {lang, fallbackLang, useReducer, translations_reducer, translations, newFallbackLang} = this.props;
return {
t: getTranslateFunction(
useReducer ? translations_reducer : translations,
lang,
newFallbackLang ? newFallbackLang : fallbackLang
)
};
}
shouldComponentUpdate(nextProps, nextState) {
if (this.props.forceRefresh && !nextProps.forceRefresh) {
return false
}
return true
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.lang !== this.props.lang || (!prevProps.forceRefresh && this.props.forceRefresh)) {
this.forceUpdate();
if (this.props.forceRefresh) {
this.props.dispatch(setForceRefresh(false))
}
}
}
UNSAFE_componentWillMount() {
if (!this.props.initialized) {
this.props.dispatch(setLanguage(this.props.initialLang))
}
}
render() {
return this.props.children
}
}
I18n.childContextTypes = {
t: PropTypes.func.isRequired
}
I18n.propTypes = {
translations: PropTypes.object.isRequired,
useReducer: PropTypes.bool,
initialLang: PropTypes.string,
fallbackLang: PropTypes.string,
initialized: PropTypes.bool
}
I18n.defaultProps = {
useReducer: false,
initialLang: 'en',
fallbackLang: null
}
export default I18n
|
docs/src/pages/component-demos/progress/LinearQuery.js
|
dsslimshaddy/material-ui
|
// @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import { LinearProgress } from 'material-ui/Progress';
const styles = theme => ({
root: {
width: '100%',
marginTop: theme.spacing.unit * 3,
},
});
function LinearQuery(props) {
const classes = props.classes;
return (
<div className={classes.root}>
<LinearProgress mode="query" />
<br />
<LinearProgress color="accent" mode="query" />
</div>
);
}
LinearQuery.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(LinearQuery);
|
src/components/home/HomeView.js
|
ahonn/v2exRN
|
import React, { Component } from 'react';
import {
Text,
View,
ToolbarAndroid,
DrawerLayoutAndroid,
StyleSheet
} from 'react-native';
import { connect } from 'react-redux';
import SplashScreen from 'react-native-splash-screen';
import Icon from 'react-native-vector-icons/Ionicons';
import ScrollableTabView from 'react-native-scrollable-tab-view';
import defaultTabs from '../../constants/Tabs';
import TopicList from '../topicList/TopicList';
import SimpleTabBar from './SimpleTabBar';
const toolBarConfig = {
title: '浏览'
};
class HomeView extends Component {
componentDidMount() {
SplashScreen.hide();
}
_renderTopicList() {
return defaultTabs.map(item => {
return (
<TopicList
key={item.tab}
tab={item.tab}
tabLabel={item.name}
navigator={this.props.navigator}
/>
);
});
}
render() {
return (
<View style={styles.container}>
<Icon.ToolbarAndroid
title={toolBarConfig.title}
titleColor="#fff"
style={styles.toolbar}
navIconName="md-menu"
onIconClicked={() => this.props.openDrawer()} />
<ScrollableTabView
renderTabBar={() => <SimpleTabBar />}
tabBarBackgroundColor="#334"
tabBarActiveTextColor="#FFF"
tabBarInactiveTextColor="#EEE"
tabBarUnderlineStyle={styles.tabbar}
>
{ this._renderTopicList() }
</ScrollableTabView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'column',
},
toolbar: {
height: 56,
backgroundColor: '#334',
},
tabbar: {
backgroundColor: '#FFF',
}
});
const mapStateToProps = (state) => {
return {
topic: state.topic,
};
};
export default connect(mapStateToProps)(HomeView);
|
webapp/app/components/Users/Table/index.js
|
EIP-SAM/SAM-Solution-Server
|
//
// Table page save
//
import React from 'react';
import { Table } from 'react-bootstrap';
import ButtonPopover from 'components/ButtonPopover';
import UserDeletionModal from 'containers/Users/Table/ModalDeletionUser';
import Tr from 'components/Tr';
import Th from 'components/Th';
import Td from 'components/Td';
import styles from './styles.css';
/* eslint-disable react/prefer-stateless-function */
export default class UserTable extends React.Component {
handleDeleteClick(user) {
this.props.showInstantDeleteModal();
this.props.userToDelete(user.id);
this.props.getUsername(user.name);
}
render() {
const names = ['#', 'Name', 'Email', 'Group(s)', 'Actions'];
return (
<div>
<Table responsive hover striped>
<thead>
<Tr items={names} component={Th} />
</thead>
<tbody>
{this.props.users.map((user, index) => {
const action = [];
let groupName = '';
user.groups.map((group, index2) => {
if (index2 > 0) {
groupName += ', ';
}
groupName += group.name;
return true;
});
action.push(<ButtonPopover key={`action-${0}`} id="edit_user" trigger={['focus', 'hover']} placement="bottom" popoverContent="Edit User" buttonType="link" icon="pencil" link={`/edit-user/${user.id}`} />);
action.push(<ButtonPopover key={`action-${1}`} id="delete_user" trigger={['focus', 'hover']} placement="bottom" popoverContent="Delete User" buttonType="link" icon="trash" onClick={() => this.handleDeleteClick(user)} buttonStyle={styles.trash} />);
return (
<Tr
key={`row-${index}`} items={[
{ isLink: false, value: user.id },
{ isLink: true, link: `/dashboard/${user.name}/${user.id}`, value: user.name },
{ isLink: false, value: user.email },
{ isLink: false, value: groupName },
{ isLink: false, value: action }]} component={Td}
/>
);
})}
</tbody>
</Table>
<UserDeletionModal />
</div>
);
}
}
UserTable.propTypes = {
users: React.PropTypes.arrayOf(React.PropTypes.object),
showInstantDeleteModal: React.PropTypes.func,
userToDelete: React.PropTypes.func,
getUsername: React.PropTypes.func,
};
UserTable.defaultProps = {
users: [],
};
|
springboot/GReact/src/main/resources/static/app/routes/graphs/containers/EasyPieCharts.js
|
ezsimple/java
|
import React from 'react'
import {Stats, BigBreadcrumbs, WidgetGrid, JarvisWidget} from '../../../components'
import EasyPieChartContainer from '../../../components/graphs/inline/EasyPieChartContainer'
export default () => (
<div id="content">
<div className="row">
<BigBreadcrumbs items={["Easy Pie Charts"]} icon="fa fa-fw fa-bar-chart-o" className="col-xs-12 col-sm-7 col-md-7 col-lg-4"/>
<Stats />
</div>
<div className="row">
<EasyPieChartContainer className="col-sm-12">
<div className="well">
<h1>Easy <span className="semi-bold">Pie Charts</span>
<small>Simplified for faster production</small>
</h1>
<p>Easy Pie Charts gives you a nice animation twist to your pie charts - they are also dynamic,
which will make it a really nice ajax based live charts for your project</p>
<p className="note"><div class="easy-pie-chart txt-color-blue easyPieChart"
data-percent="36" data-size="180"> data-pie-size="50">
<span class="percent percent-sign txt-color-blue font-xl semi-bold">36<
/span>
</div></p>
<ul className="list-inline">
<li>
<div className="easy-pie-chart txt-color-red easyPieChart" data-percent="50" data-size="180"
data-pie-size="50">
<span className="percent percent-sign txt-color-red font-xl semi-bold">49</span>
</div>
</li>
<li>
<div className="easy-pie-chart txt-color-blue easyPieChart" data-percent="36"
data-pie-size="180">
<span className="percent percent-sign txt-color-blue font-xl semi-bold">36</span>
</div>
</li>
<li>
<div className="easy-pie-chart txt-color-pinkDark easyPieChart" data-percent="46"
data-pie-size="160">
<span className="percent percent-sign txt-color-pinkDark font-lg semi-bold">46</span>
</div>
</li>
<li>
<div className="easy-pie-chart txt-color-greenLight easyPieChart" data-percent="56"
data-pie-size="110">
<span className="percent percent-sign txt-color-greenLight font-md">56</span>
</div>
</li>
<li>
<div className="easy-pie-chart txt-color-orange easyPieChart" data-percent="66"
data-pie-size="60">
<span className="percent percent-sign txt-color-orange">66</span>
</div>
</li>
<li>
<div className="easy-pie-chart txt-color-darken easyPieChart" data-percent="76"
data-pie-size="45">
<span className="percent percent-sign font-sm">76</span>
</div>
</li>
<li>
<div className="easy-pie-chart txt-color-blue easyPieChart" data-percent="86"
data-pie-size="35">
<span className="percent percent-sign font-xs">86</span>
</div>
</li>
</ul>
</div>
</EasyPieChartContainer>
</div>
</div>
)
|
app/js/containers/CircleContainer.js
|
sgt39007/waji_redux
|
import React from 'react';
import {
Container,
List,
Group,
View,
} from 'amazeui-touch';
import {
Link,
} from 'react-router';
import { connect } from 'react-redux';
import * as AppActions from '../redux/actions/AppActions';
import { Login } from '../components';
class CircleContainer extends React.Component {
componentWillMount() {
const { dispatch } = this.props;
dispatch(AppActions.hideTabbar(false));
dispatch(AppActions.hideNavLeft(true));
dispatch(AppActions.setNavTitle('世界圈'));
}
renderItems() {
const { login, dispatch } = this.props;
if (login.loadState.success) {
// 如果登录 -> Circle -> CircleDetail
return (
<Group noPadded>
<List>
<List.Item
linkComponent={Link}
linkProps={{to: {pathname: '/circle/world'}}}
title="世界圈"
key="sj"
/>
<List.Item
linkComponent={Link}
linkProps={{to: {pathname: '/circle/friend'}}}
title="朋友圈"
key="py"
/>
</List>
</Group>
);
} else {
// 没登录-> login的内容
return (
<Login dispatch={dispatch}/>
);
}
}
render() {
return (
<View>
<Container scrollable>
{this.renderItems()}
</Container>
</View>
);
}
}
function mapStateToProps(state) {
return {
login: state.login
}
}
export default connect(mapStateToProps)(CircleContainer)
|
web/src/server/components/charts/time-vs-commits-chart.js
|
opendaylight/spectrometer
|
/**
# @License EPL-1.0 <http://spdx.org/licenses/EPL-1.0>
##############################################################################
# Copyright (c) 2016 The Linux Foundation and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
##############################################################################
*/
/**
* React component to display Timeline of Commits chart
* Used in TimelineCard
* Uses ChartLayout
*
* @author: Vasu Srinivasan
* @since: 0.0.1
*/
import React, { Component } from 'react';
import ReactHighcharts from 'react-highcharts'
import * as DataReducers from '../../api/data-reducers'
import ChartLayout from '../chart-layout'
const buttonActions = [
{type: 'chartType', option: 'line', icon: 'multiline_chart', tooltip: 'Area chart'}
]
const lineChart = (dataSeries) => {
const config = {
chart: { type: 'line' },
title: { text: '' },
xAxis: [{ title: { text: 'Time' }, categories: _.map(dataSeries, "name") }],
yAxis: [{ title: { text: 'Commits' }}, { title: { text: 'LoC Modified' }, opposite: true}],
series: [
{ name: 'Commits', type: 'area', data: _.map(dataSeries, "commitCount") },
{ name: 'LoC Modified', type: 'spline', yAxis: 1, data: _.map(dataSeries, "loc") }
],
tooltip: {
pointFormat: '{series.name}: {point.y}'
},
plotOptions: {
line: {
allowPointSelect: true, cursor: 'pointer',
dataLabels: { enabled: true },
enableMouseTracking: false
}
}
}
return (<ReactHighcharts config={config} />)
}
export default class TimeVsCommitsChart extends Component {
constructor(props) {
super(props)
this.state = {
view: _.assign({}, DEFAULT_VIEW, props.view)
}
this.handleButtonActions = this.handleButtonActions.bind(this)
}
handleButtonActions = (type, value) => {
const newView = _.merge(this.state.view, {[type]: value})
this.setState({ view: newView })
}
render() {
if (_.isEmpty(this.props.projects)) return null;
logger.info("time-vs-commits-chart:render", this.state.view)
const { name, ref1, ref2, author } = this.state.view
const dataSeries = DataReducers.timeVsCommitCount(this.props.projects, {name, ref1, ref2, author, sortBy: 'x'})
return (
<ChartLayout id="time-vs-loc-chart" title="Commits by Timeline"
buttonActions={buttonActions} currentView={this.state.view}
handleButtonActions={this.handleButtonActions}>
{lineChart(dataSeries)}
</ChartLayout>
)
}
}
const DEFAULT_VIEW = {
chartType: 'line',
sortBy: 'x'
}
TimeVsCommitsChart.propTypes = {
projects: React.PropTypes.array,
view: React.PropTypes.object
}
|
src/js/view/DrawerLists.js
|
yoichiro/chromeos-filesystem-sftp
|
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import classNames from 'classnames';
import Drawer from '@material-ui/core/Drawer';
import IconButton from '@material-ui/core/IconButton'
import List from '@material-ui/core/List';
import ListSubheader from '@material-ui/core/ListSubheader';
import FavoritesItem from './FavoritesItem';
import ChevronLeftIcon from '@material-ui/icons/ChevronRight';
import Divider from '@material-ui/core/Divider';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import Switch from '@material-ui/core/Switch';
const drawerWidth = 240;
const styles = theme => ({
drawerPaper: {
position: 'relative',
height: '100%',
width: drawerWidth,
},
drawerHeader: {
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
padding: '0 8px',
...theme.mixins.toolbar,
},
list: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
nested: {
paddingLeft: theme.spacing.unit * 4,
},
hide: {
visibility: 'hidden',
}
});
class FavoritesList extends React.Component {
render() {
const { classes, favorites, open, selectedFavorite='', keepCredentials=false,
onToggleDrawer, onShowFavorite, onRemoveFavorite, onToggleKeepCredentials } = this.props;
// Generate list items, based on the items within
// the favorites array in the state of the main app
const items = favorites.map((favorite) =>
<FavoritesItem
key={favorite.key}
favorite={favorite}
selected={selectedFavorite===favorite.key}
onShowFavorite={onShowFavorite}
onRemoveFavorite={onRemoveFavorite}
/>
);
const noItems = (
<ListItem dense disabled>
<ListItemText primary={chrome.i18n.getMessage("noFavorites")} />
</ListItem>
);
return (
<Drawer
variant="persistent"
anchor="right"
className={classNames(!open && classes.hide)}
classes={{
paper: classes.drawerPaper,
}}
open={open}>
<div className={classes.drawerInner}>
<div className={classes.drawerHeader}>
<IconButton onClick={onToggleDrawer}>
<ChevronLeftIcon />
</IconButton>
</div>
<Divider />
<div className={classes.list}>
<List
component="nav"
subheader={<ListSubheader component="div">{chrome.i18n.getMessage("favorites")}</ListSubheader>}>
{items.length > 0 ? items : noItems}
</List>
<List
component="nav"
subheader={<ListSubheader component="div">{chrome.i18n.getMessage("settings")}</ListSubheader>}>
<ListItem dense>
<ListItemText primary={chrome.i18n.getMessage("storeCredentials")} />
<ListItemSecondaryAction>
<Switch
onClick={onToggleKeepCredentials}
checked={keepCredentials}
/>
</ListItemSecondaryAction>
</ListItem>
</List>
</div>
</div>
</Drawer>
);
}
}
FavoritesList.propTypes = {
classes: PropTypes.object.isRequired,
favorites: PropTypes.array.isRequired,
open: PropTypes.bool.isRequired,
selectedFavorite: PropTypes.string,
keepCredentials: PropTypes.bool,
onToggleDrawer: PropTypes.func.isRequired,
onShowFavorite: PropTypes.func.isRequired,
onRemoveFavorite: PropTypes.func.isRequired,
onToggleKeepCredentials: PropTypes.func.isRequired
};
export default withStyles(styles)(FavoritesList);
|
admin/client/components/Toolbar.js
|
codevlabs/keystone
|
import React from 'react';
import { Container } from 'elemental';
module.exports = React.createClass({
displayName: 'Toolbar',
render () {
return (
<div {...this.props} className="Toolbar">
<Container clearfix >
{this.props.children}
</Container>
</div>
);
}
});
// expose the children to the top level export
module.exports.Section = require('./ToolbarSection');
|
webpack/components/surveys/SurveyEdit.js
|
CDCgov/SDP-Vocabulary-Service
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router';
import { Row, Col, Button } from 'react-bootstrap';
import TagsInput from 'react-tagsinput';
import { surveyProps } from '../../prop-types/survey_props';
import { sectionsProps } from '../../prop-types/section_props';
import { surveillanceSystemsProps } from '../../prop-types/surveillance_system_props';
import { surveillanceProgramsProps } from '../../prop-types/surveillance_program_props';
import { questionsProps } from "../../prop-types/question_props";
import currentUserProps from "../../prop-types/current_user_props";
import SurveySectionList from './SurveySectionList';
import CodedSetTableEditContainer from '../../containers/CodedSetTableEditContainer';
import Errors from '../Errors';
import ModalDialog from '../ModalDialog';
import InfoModal from '../InfoModal';
import ProgSysEditModal from './ProgSysEditModal';
class SurveyEdit extends Component {
stateForNew(currentUser) {
return {
id: null,
comment: '',
name: '',
version: 1,
conceptsAttributes: [],
tagList: [],
description: '',
surveySections: [],
controlNumber: null,
ombApprovalDate : '',
versionIndependentId: null,
showModal: false,
showInfo: false,
showInfoOMBApproval: false,
showInfoTags: false,
showInfoProgram: false,
showInfoSystem: false,
showInfoSelectedSections: false,
showInfoSearchandSelectSections: false,
progSysModalOpen: false,
surveillanceProgramId: currentUser.lastProgramId || null,
surveillanceSystemId: currentUser.lastSystemId || null
};
}
stateForExtend(survey, currentUser) {
var state = this.stateForEdit(survey, currentUser);
state.id = null;
state.versionIndependentId = null;
state.version = 1;
state.parentId = survey.id;
state.controlNumber = '';
state.ombApprovalDate = '';
state.groups = [];
return state;
}
stateForEdit(survey, currentUser) {
var newState = this.stateForNew(currentUser);
newState.id = survey.id;
newState.name = survey.name || '';
newState.version = survey.version;
newState.description = survey.description || '';
newState.surveySections = survey.surveySections || [];
newState.controlNumber = survey.controlNumber;
newState.ombApprovalDate = survey.ombApprovalDate;
newState.parentId = survey.parent ? survey.parent.id : '';
newState.surveillanceProgramId = survey.surveillanceProgramId || newState.surveillanceProgramId;
newState.surveillanceSystemId = survey.surveillanceSystemId || newState.surveillanceSystemId;
newState.versionIndependentId = survey.versionIndependentId;
newState.conceptsAttributes = filterConcepts(survey.concepts);
newState.tagList = survey.tagList || [];
newState.groups = survey.groups || [];
return newState;
}
stateForRevise(survey, currentUser) {
var newState = this.stateForEdit(survey, currentUser);
newState.version += 1;
return newState;
}
constructor(props) {
super(props);
switch (this.props.action) {
case 'revise':
this.state = this.stateForRevise(props.survey, props.currentUser);
break;
case 'extend':
this.state = this.stateForExtend(props.survey, props.currentUser);
break;
case 'edit':
this.state = this.stateForEdit(props.survey, props.currentUser);
break;
default:
this.state = this.stateForNew(props.currentUser);
}
this.unsavedState = false;
this.associationChanges = {};
this.lastSectionCount = this.state.surveySections.length;
this.handleTagChange = this.handleTagChange.bind(this);
}
componentDidMount() {
this.unbindHook = this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave.bind(this));
window.onbeforeunload = this.windowWillUnload.bind(this);
if(this.props.sections && !this.associationChanges['sections']) {
this.associationChanges['sections'] = {original: this.state.surveySections.map((ss) => {
let ssName = this.props.sections[ss.sectionId].name || '';
return {id: ss.id, name: ssName};
}), updated: this.state.surveySections.map((ss) => {
let ssName = this.props.sections[ss.sectionId].name || '';
return {id: ss.sectionId, name: ssName};
})};
}
}
componentDidUpdate(prevProps, prevState) {
if(this.lastSectionCount !== prevState.surveySections.length) {
this.unsavedState = true;
if (this.associationChanges['sections']) {
this.associationChanges['sections']['updated'] = this.state.surveySections.map((ss) => {
let ssName = this.props.sections[ss.sectionId].name || '';
return {id: ss.sectionId, name: ssName};
});
} else {
this.associationChanges['sections'] = {original: prevState.surveySections.map((ss) => {
let ssName = prevProps.sections[ss.sectionId].name || '';
return {id: ss.id, name: ssName};
}), updated: this.state.surveySections.map((ss) => {
let ssName = this.props.sections[ss.sectionId].name || '';
return {id: ss.sectionId, name: ssName};
})};
}
this.lastSectionCount = prevState.surveySections.length;
}
}
componentWillUnmount() {
this.unsavedState = false;
this.associationChanges = {};
this.unbindHook();
}
routerWillLeave(nextLocation) {
this.setState({ showModal: this.unsavedState });
this.nextLocation = nextLocation;
return !this.unsavedState;
}
handleConceptsChange(newConcepts) {
if (this.associationChanges['mappings']) {
this.associationChanges['mappings']['updated'] = newConcepts;
} else {
this.associationChanges['mappings'] = {original: this.state.conceptsAttributes, updated: newConcepts};
}
this.setState({conceptsAttributes: filterConcepts(newConcepts)});
this.unsavedState = true;
}
handleTagChange(tagList) {
this.setState({tagList});
this.unsavedState = true;
}
handleModalResponse(leavePage){
this.setState({ showModal: false });
if(leavePage){
this.unsavedState = false;
this.associationChanges = {};
this.props.router.push(this.nextLocation.pathname);
}else{
let survey = Object.assign({}, this.state);
// Because we were saving SurveySections with null positions for a while, we need to explicitly set position here to avoid sending a null position back to the server
// At some point, we can remove this code
survey.linkedSections = this.state.surveySections.map((sect, i) => ({id: sect.id, surveyId: sect.surveyId, sectionId: sect.sectionId, position: i}));
this.props.surveySubmitter(survey, this.state.comment, this.unsavedState, this.associationChanges, (response) => {
// TODO: Handle when the saving survey fails.
this.unsavedState = false;
this.associationChanges = {};
if (response.status === 201) {
this.props.router.push(this.nextLocation.pathname);
}
});
}
}
windowWillUnload() {
return (this.unsavedState || null);
}
handleChange(field) {
return (event) => {
let newState = {};
newState[field] = event.target.value;
this.setState(newState);
this.unsavedState = true;
};
}
handleSubmit(event) {
event.preventDefault();
// Because of the way we have to pass the current sections in we have to manually sync props and state for submit
let survey = Object.assign({}, this.state);
survey.linkedSections = this.state.surveySections;
this.props.surveySubmitter(survey, this.state.comment, this.unsavedState, this.associationChanges, (response) => {
this.unsavedState = false;
this.associationChanges = {};
if (this.props.action === 'new') {
let stats = Object.assign({}, this.props.stats);
stats.surveyCount = this.props.stats.surveyCount + 1;
stats.mySurveyCount = this.props.stats.mySurveyCount + 1;
this.props.setStats(stats);
}
this.props.router.push(`/surveys/${response.data.id}`);
}, (failureResponse) => {
this.setState({errors: failureResponse.response.data});
});
}
cancelButton() {
if(this.props.survey && this.props.survey.id) {
return(<Link tabIndex="3" className="btn btn-default pull-right" to={`/surveys/${this.props.survey.id}`}>Cancel</Link>);
}
return(<Link tabIndex="3" className="btn btn-default pull-right" to='/'>Cancel</Link>);
}
render() {
if(!this.props.sections){
return ('Loading');
}
return (
<Col md={7} className="survey-edit-details">
<div id='survey-div'>
<ModalDialog show ={this.state.showModal}
title="Warning"
subTitle="Unsaved Changes"
warning ={true}
message ="You are about to leave a page with unsaved changes. How would you like to proceed?"
secondaryButtonMessage="Continue Without Saving"
primaryButtonMessage="Save & Leave"
cancelButtonMessage="Cancel"
primaryButtonAction={() => this.handleModalResponse(false)}
cancelButtonAction ={() => {
this.props.router.push(this.props.route.path);
this.setState({ showModal: false });
}}
secondaryButtonAction={() => this.handleModalResponse(true)} />
<form onSubmit={(e) => this.handleSubmit(e)}>
<Errors errors={this.state.errors} />
<div className="survey-inline">
<input tabIndex="3" className='btn btn-default pull-right' name="Save Survey" type="submit" value={`Save`}/>
{this.cancelButton()}
</div>
<br/>
<hr />
<div className="survey-group">
<label htmlFor="survey-name">Survey Name</label>
<input tabIndex="3" className="input-format" placeholder="Survey Name" type="text" value={this.state.name} name="survey-name" id="survey-name" onChange={this.handleChange('name')}/>
</div>
<Row>
<Col md={8} className="survey-group">
<label htmlFor="survey-description">Description</label>
<input tabIndex="3" className="input-format" placeholder="Enter a description here..." type="text" value={this.state.description || ''} name="survey-description" id="survey-description" onChange={this.handleChange('description')}/>
</Col>
<Col md={4} className="survey-group">
<InfoModal show={this.state.showInfoOMBApproval} header="OMB Approval" body={<p>Provide the OMB Control Number associated with this data collection instrument (if applicable). <br/><br/>This attribute is optional but completion allows other users to find vocabulary that has been used on an OMB-approved data collection instrument. Reuse of vocabulary that has been part of one or more OMB approved Paperwork Reduction Act (PRA) packages in the past can help expedite the review process. There is an advanced search filter that is based off of this attribute.
</p>} hideInfo={()=>this.setState({showInfoOMBApproval: false})} />
<label htmlFor="controlNumber">OMB Approval<Button bsStyle='link' style={{ padding: 3 }} onClick={() => this.setState({showInfoOMBApproval: true})}><i className="fa fa-info-circle" aria-hidden="true"></i><text className="sr-only">Click for info about this item</text></Button></label>
<input tabIndex="3" className="input-format" placeholder="XXXX-XXXX" type="text" value={this.state.controlNumber || ''} name="controlNumber" id="controlNumber" onChange={this.handleChange('controlNumber')}/>
{ this.state.controlNumber !== '' && this.state.controlNumber !== null &&
<div>
<br/>
<label htmlFor="ombApprovalDate">OMB Approval Date</label>
<input tabIndex="3" className="input-format" type="date" placeholder="mm/dd/yyyy" value={this.state.ombApprovalDate || ''} name ="ombApprovalDate" id="ombApprovalDate" onChange={this.handleChange('ombApprovalDate')}/>
</div>
}
</Col>
</Row>
<Row>
<Col md={12} className="survey-group">
<InfoModal show={this.state.showInfoTags} header="Tags" body={<p>Tags are text strings that are either keywords or short phrases created by users to facilitate content discovery, organization, and reuse. Tags are weighted in the dashboard search result algorithm so users are presented with search results that have been tagged with the same keyword(s) entered in the dashboard search bar. <br/><br/>Keyword tags can be changed (added or deleted) at any time by the author(s) to meet user needs and to optimize search results. The history of tags is not saved on the change history tab; tags are not versioned.</p>} hideInfo={()=>this.setState({showInfoTags: false})} />
<label className="input-label" htmlFor="survey-tags">Tags<Button bsStyle='link' style={{ padding: 3 }} onClick={() => this.setState({showInfoTags: true})}><i className="fa fa-info-circle" aria-hidden="true"></i><text className="sr-only">Click for info about this item</text></Button></label>
<p>Press 'Tab' or 'Enter' after typing a tag to add it to the list. Press 'Backspace' or click the 'x' icon to remove a tag.</p>
<TagsInput value={this.state.tagList} onChange={this.handleTagChange} inputProps={{tabIndex: '3', id: 'survey-tags'}} />
</Col>
</Row>
<Row>
<ProgSysEditModal closer={() => this.setState({progSysModalOpen: false})}
show={this.state.progSysModalOpen}
update={(sid, pid) => this.setState({surveillanceSystemId: sid, surveillanceProgramId: pid, progSysModalOpen: false})}
programId={this.state.surveillanceProgramId}
systemId={this.state.surveillanceSystemId}
currentUser={this.props.currentUser}
surveillanceSystems={this.props.surveillanceSystems}
surveillancePrograms={this.props.surveillancePrograms} />
<Col md={6} className="survey-group">
<InfoModal show={this.state.showInfoProgram} header="Program" body={<p>Identify the program that will maintain and use this vocabulary to support public health activities.<br/><br/>The default value is populated from the author’s profile. The value can be changed by selecting the pencil icon.</p>} hideInfo={()=>this.setState({showInfoProgram: false})} />
<label htmlFor="program"><strong>Program</strong><Button bsStyle='link' style={{ padding: 3 }} onClick={() => this.setState({showInfoProgram: true})}><i className="fa fa-info-circle" aria-hidden="true"></i><text className="sr-only">Click for info about this item</text></Button>:</label>
<a className="tag-modal-link" href="#" onClick={(e) => {
e.preventDefault();
this.setState({ progSysModalOpen: true });
}}> {this.props.surveillancePrograms && this.props.surveillancePrograms[this.state.surveillanceProgramId] && this.props.surveillancePrograms[this.state.surveillanceProgramId].name} <i className="fa fa-pencil-square-o" aria-hidden="true"><text className='sr-only'>Click to edit program</text></i></a>
</Col>
<Col md={6} className="survey-group">
<InfoModal show={this.state.showInfoSystem} header="System" body={<p>Identify the surveillance system that will use this vocabulary to support public health activities.<br/><br/>The default value is populated from the author’s profile. The value can be changed by selecting the pencil icon.</p>} hideInfo={()=>this.setState({showInfoSystem: false})} />
<label htmlFor="system"><strong>System</strong><Button bsStyle='link' style={{ padding: 3 }} onClick={() => this.setState({showInfoSystem: true})}><i className="fa fa-info-circle" aria-hidden="true"></i><text className="sr-only">Click for info about this item</text></Button>: </label>
<a className="tag-modal-link" href="#" onClick={(e) => {
e.preventDefault();
this.setState({ progSysModalOpen: true });
}}> {this.props.surveillanceSystems && this.props.surveillanceSystems[this.state.surveillanceSystemId] && this.props.surveillanceSystems[this.state.surveillanceSystemId].name} <i className="fa fa-pencil-square-o" aria-hidden="true"><text className='sr-only'>Click to edit system</text></i></a>
</Col>
</Row>
<h2 className="code-system-mappings-table-header"><strong>Code System Mappings</strong></h2>
<CodedSetTableEditContainer itemWatcher={(r) => this.handleConceptsChange(r)}
initialItems={this.state.conceptsAttributes}
parentName={'survey'}
childName={'Code System Mapping'} />
{this.props.action === 'edit' && <div className="survey-group">
<label htmlFor="save-with-comment">Notes / Comments About Changes Made (Optional)</label>
<textarea className="input-format" tabIndex="3" placeholder="Add notes about the changes here..." type="text" value={this.state.comment || ''} name="save-with-comment" id="save-with-comment" onChange={this.handleChange('comment')}/>
</div>}
<br/>
<InfoModal show={this.state.showInfoSelectedSections} header="Selected Sections" body={<p>The “Selected Sections” panel displays the selected Sections for this Survey.</p>} hideInfo={()=>this.setState({showInfoSelectedSections: false})} />
<label className="pull-left">Selected Sections<Button bsStyle='link' style={{ padding: 3 }} onClick={() => this.setState({showInfoSelectedSections: true})}><i className="fa fa-info-circle" aria-hidden="true"></i><text className="sr-only">Click for info about this item</text></Button></label>
<InfoModal show={this.state.showInfo} header="Position" body="This column displays the order of the sections. To change position, enter the desired position and hit the 'Enter' key on your keyboard." hideInfo={()=>this.setState({showInfo: false})} />
<label className="pull-right">Position<Button bsStyle='link' style={{ padding: 3 }} onClick={() => this.setState({showInfo: true})}><i className="fa fa-info-circle" aria-hidden="true"></i><text className="sr-only">Click for info about this item</text></Button></label>
<br/>
<SurveySectionList survey={this.state}
sections ={this.props.sections}
questions ={this.props.questions}
reorderSection={this.props.reorderSection}
removeSection ={this.props.removeSection} />
</form>
</div>
</Col>
);
}
}
function filterConcepts(concepts) {
if(!concepts){
return [];
}
return concepts.filter((nc) => {
return (nc.value !=='' || nc.codeSystem !== '' || nc.displayName !=='');
}).map((nc) => {
return {value: nc.value, codeSystem: nc.codeSystem, displayName: nc.displayName};
});
}
SurveyEdit.propTypes = {
survey: surveyProps,
currentUser: currentUserProps,
surveillanceSystems: surveillanceSystemsProps,
surveillancePrograms: surveillanceProgramsProps,
sections: sectionsProps.isRequired,
questions: questionsProps.isRequired,
action: PropTypes.string.isRequired,
setStats: PropTypes.func,
stats: PropTypes.object,
surveySubmitter: PropTypes.func.isRequired,
removeSection: PropTypes.func.isRequired,
reorderSection: PropTypes.func.isRequired,
route: PropTypes.object.isRequired,
router: PropTypes.object.isRequired
};
export default SurveyEdit;
|
wrappers/md.js
|
adjohnson916/site-gatsby
|
import React from 'react'
import 'css/markdown-styles.css'
module.exports = React.createClass({
propTypes () {
return {
router: React.PropTypes.object,
}
},
render () {
const post = this.props.route.page.data
return (
<div className="markdown">
<h1>{post.title}</h1>
<div dangerouslySetInnerHTML={{ __html: post.body }} />
</div>
)
},
})
|
src/modules/CardsGrid.js
|
maizy/kanbanrum-cards
|
/**
* Copyright (c) Nikita Kovaliov, maizy.ru, 2017
* See LICENSE.txt for details.
*/
import React from 'react';
import SmallCard from './SmallCard';
function CardsGrid(props) {
const cards = props.cards.map(card => <SmallCard card={card} key={card.get('id')} />);
return (
<div>
<h1>Kanbanrum™ Cards</h1>
<div className="cards-grid">
{cards}
</div>
</div>
);
}
CardsGrid.propTypes = {
// FIXME: immutable list
cards: React.PropTypes.object,
};
export default CardsGrid;
|
src/svg-icons/communication/voicemail.js
|
rhaedes/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationVoicemail = (props) => (
<SvgIcon {...props}>
<path d="M18.5 6C15.46 6 13 8.46 13 11.5c0 1.33.47 2.55 1.26 3.5H9.74c.79-.95 1.26-2.17 1.26-3.5C11 8.46 8.54 6 5.5 6S0 8.46 0 11.5 2.46 17 5.5 17h13c3.04 0 5.5-2.46 5.5-5.5S21.54 6 18.5 6zm-13 9C3.57 15 2 13.43 2 11.5S3.57 8 5.5 8 9 9.57 9 11.5 7.43 15 5.5 15zm13 0c-1.93 0-3.5-1.57-3.5-3.5S16.57 8 18.5 8 22 9.57 22 11.5 20.43 15 18.5 15z"/>
</SvgIcon>
);
CommunicationVoicemail = pure(CommunicationVoicemail);
CommunicationVoicemail.displayName = 'CommunicationVoicemail';
export default CommunicationVoicemail;
|
packages/material-ui-icons/src/Landscape.js
|
cherniavskii/material-ui
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M14 6l-3.75 5 2.85 3.8-1.6 1.2C9.81 13.75 7 10 7 10l-6 8h22L14 6z" /></g>
, 'Landscape');
|
project/react-redux/src/pages/index/index.js
|
FFF-team/generator-earth
|
// //import base&&tools
import 'whatwg-fetch'
import 'scss_mixin/reset.scss' //reset 样式
import 'tools/polyfill'
import React from 'react'
import ReactDOM from 'react-dom'
import store from './store/index'
import {Provider} from 'react-redux'
import {
HashRouter as Router,
} from 'react-router-dom'
// import containers
import App from './containers/App'
import MainRouter from './containers/MainRouter'
const rootElement = document.getElementById('root');
ReactDOM.render(
<Provider store={store}>
<Router>
<div>
<App/>
<MainRouter/>
</div>
</Router>
</Provider>,
rootElement
)
|
src/Parser/Rogue/Common/Resources/EnergyDetails.js
|
hasseboulen/WoWAnalyzer
|
import React from 'react';
import Analyzer from 'Parser/Core/Analyzer';
import Tab from 'Main/Tab';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import Icon from 'common/Icon';
import ResourceBreakdown from 'Parser/Core/Modules/ResourceTracker/ResourceBreakdown';
import EnergyTracker from './EnergyTracker';
class EnergyDetails extends Analyzer {
static dependencies = {
energyTracker: EnergyTracker,
};
statistic() {
const energyWasted = this.energyTracker.wasted;
const pointsWastedPerMinute = (energyWasted / this.owner.fightDuration) * 1000 * 60;
return (
<StatisticBox
icon={<Icon icon="ability_warrior_decisivestrike" alt="Waisted Energy" />}
value={`${pointsWastedPerMinute.toFixed(2)}`}
label="Wasted Energy per minute"
tooltip={`You wasted a total of ${energyWasted} energy. Some waste is expected due to the random nature of some generation abilities.`}
/>
);
}
tab() {
return {
title: 'Energy usage',
url: 'energy-usage',
render: () => (
<Tab title="Energy usage breakdown">
<ResourceBreakdown
tracker={this.energyTracker}
/>
</Tab>
),
};
}
statisticOrder = STATISTIC_ORDER.CORE(5);
}
export default EnergyDetails;
|
blueocean-material-icons/src/js/components/svg-icons/maps/directions-transit.js
|
jenkinsci/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const MapsDirectionsTransit = (props) => (
<SvgIcon {...props}>
<path d="M12 2c-4.42 0-8 .5-8 4v9.5C4 17.43 5.57 19 7.5 19L6 20.5v.5h12v-.5L16.5 19c1.93 0 3.5-1.57 3.5-3.5V6c0-3.5-3.58-4-8-4zM7.5 17c-.83 0-1.5-.67-1.5-1.5S6.67 14 7.5 14s1.5.67 1.5 1.5S8.33 17 7.5 17zm3.5-6H6V6h5v5zm5.5 6c-.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.5zm1.5-6h-5V6h5v5z"/>
</SvgIcon>
);
MapsDirectionsTransit.displayName = 'MapsDirectionsTransit';
MapsDirectionsTransit.muiName = 'SvgIcon';
export default MapsDirectionsTransit;
|
app/components/team/Show.js
|
buildkite/frontend
|
import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import DocumentTitle from 'react-document-title';
import PageHeader from 'app/components/shared/PageHeader';
import Emojify from 'app/components/shared/Emojify';
import permissions from 'app/lib/permissions';
import TabControl from 'app/components/shared/TabControl';
import TeamLabels from './Labels';
import Pipelines from './Pipelines';
import Members from './Members';
class TeamShow extends React.Component {
static propTypes = {
team: PropTypes.shape({
name: PropTypes.string.isRequired,
description: PropTypes.string,
slug: PropTypes.string.isRequired,
members: PropTypes.shape({
count: PropTypes.number
}).isRequired,
pipelines: PropTypes.shape({
count: PropTypes.number
}).isRequired,
organization: PropTypes.shape({
name: PropTypes.string.isRequired,
slug: PropTypes.string.isRequired
}).isRequired,
permissions: PropTypes.shape({
teamUpdate: PropTypes.object.isRequired
}).isRequired
}),
children: PropTypes.node.isRequired
};
static contextTypes = {
router: PropTypes.object.isRequired
};
state = {
removing: false,
selectedTab: 0
};
render() {
// If the team doesn't exist, that means that it's just been deleted. And
// since we require all the team to render this component, we'll just
// short-circut the re-render when it's gone. This isn't great, maybe
// there's a beter way?
if (!this.props.team) {
return null;
}
return (
<DocumentTitle title={`${this.props.team.name} · ${this.props.team.organization.name} Team`}>
<div>
<PageHeader followedByTabs={true}>
<div className="flex items-center">
<h1 className="h1 m0 p0 block"><Emojify text={this.props.team.name} /></h1>
<TeamLabels team={this.props.team} />
</div>
<PageHeader.Description><Emojify text={this.props.team.description || "No description"} /></PageHeader.Description>
</PageHeader>
{this.renderTabs()}
{this.props.children}
</div>
</DocumentTitle>
);
}
renderTabs() {
const tabContent = permissions(this.props.team.permissions).collect(
{
always: true,
render: (idx) => (
<TabControl.Tab
key={idx}
to={`/organizations/${this.props.team.organization.slug}/teams/${this.props.team.slug}/members`}
badge={this.props.team.members.count}
>
Members
</TabControl.Tab>
)
},
{
always: true,
render: (idx) => (
<TabControl.Tab
key={idx}
to={`/organizations/${this.props.team.organization.slug}/teams/${this.props.team.slug}/pipelines`}
badge={this.props.team.pipelines.count}
>
Pipelines
</TabControl.Tab>
)
},
{
allowed: "teamUpdate",
render: (idx) => (
<TabControl.Tab
key={idx}
to={`/organizations/${this.props.team.organization.slug}/teams/${this.props.team.slug}/settings`}
>
Settings
</TabControl.Tab>
)
}
);
return (
<TabControl>
{tabContent}
</TabControl>
);
}
}
export default Relay.createContainer(TeamShow, {
fragments: {
team: () => Relay.QL`
fragment on Team {
${Pipelines.getFragment('team')}
${Members.getFragment('team')}
members {
count
}
pipelines {
count
}
name
description
slug
${TeamLabels.getFragment('team')}
organization {
name
slug
}
permissions {
teamUpdate {
allowed
}
}
}
`
}
});
|
test/PositionSpec.js
|
zerkms/react-bootstrap
|
import pick from 'lodash/object/pick';
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Position from '../src/Position';
import overlayPositionUtils from '../src/utils/overlayPositionUtils';
import {render} from './helpers';
describe('Position', function () {
it('Should output a child', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Position>
<span>Text</span>
</Position>
);
assert.equal(React.findDOMNode(instance).nodeName, 'SPAN');
});
it('Should warn about several children', function () {
expect(() => {
ReactTestUtils.renderIntoDocument(
<Position>
<span>Text</span>
<span>Another Text</span>
</Position>
);
}).to.throw(Error, /onlyChild must be passed a children with exactly one child/);
});
describe('position recalculation', function () {
beforeEach(function () {
sinon.spy(overlayPositionUtils, 'calcOverlayPosition');
sinon.spy(Position.prototype, 'componentWillReceiveProps');
});
afterEach(function () {
overlayPositionUtils.calcOverlayPosition.restore();
Position.prototype.componentWillReceiveProps.restore();
});
it('Should only recalculate when target changes', function () {
class TargetChanger extends React.Component {
constructor(props) {
super(props);
this.state = {
target: 'foo',
fakeProp: 0
};
}
render() {
return (
<div>
<div ref="foo" />
<div ref="bar" />
<Position
target={() => this.refs[this.state.target]}
fakeProp={this.state.fakeProp}
>
<div />
</Position>
</div>
);
}
}
const instance = ReactTestUtils.renderIntoDocument(<TargetChanger />);
// Position calculates initial position.
expect(Position.prototype.componentWillReceiveProps)
.to.have.not.been.called;
expect(overlayPositionUtils.calcOverlayPosition)
.to.have.been.calledOnce;
instance.setState({target: 'bar'});
// Position receives new props and recalculates position.
expect(Position.prototype.componentWillReceiveProps)
.to.have.been.calledOnce;
expect(overlayPositionUtils.calcOverlayPosition)
.to.have.been.calledTwice;
instance.setState({fakeProp: 1});
// Position receives new props but should not recalculate position.
expect(Position.prototype.componentWillReceiveProps)
.to.have.been.calledTwice;
expect(overlayPositionUtils.calcOverlayPosition)
.to.have.been.calledTwice;
});
});
describe('position calculation', function () {
let mountPoint;
beforeEach(function () {
mountPoint = document.createElement('div');
document.body.appendChild(mountPoint);
});
afterEach(function () {
React.unmountComponentAtNode(mountPoint);
document.body.removeChild(mountPoint);
});
function checkPosition(placement, targetPosition, expected) {
class FakeOverlay extends React.Component {
render() {
return (
<div style={{
position: 'absolute',
width: 200,
height: 200
}} />
);
}
}
class FakeContainer extends React.Component {
render() {
return (
<div style={{
position: 'relative',
width: 600,
height: 600
}}>
<div ref="target" style={{
position: 'absolute',
width: 100,
height: 100,
...targetPosition
}}/>
<Position
target={() => React.findDOMNode(this.refs.target)}
container={this}
containerPadding={50}
placement={placement}
>
<FakeOverlay ref="overlay" />
</Position>
</div>
);
}
}
const expectedPosition = {
positionLeft: expected[0],
positionTop: expected[1],
arrowOffsetLeft: expected[2],
arrowOffsetTop: expected[3]
};
it('Should calculate the correct position', function() {
const instance = render(<FakeContainer />, mountPoint);
const calculatedPosition = pick(
instance.refs.overlay.props, Object.keys(expectedPosition)
);
expect(calculatedPosition).to.eql(expectedPosition);
});
}
[
{
placement: 'left',
noOffset: [50, 200, null, '50%'],
offsetBefore: [-200, 50, null, '0%'],
offsetAfter: [300, 350, null, '100%']
},
{
placement: 'top',
noOffset: [200, 50, '50%', null],
offsetBefore: [50, -200, '0%', null],
offsetAfter: [350, 300, '100%', null]
},
{
placement: 'bottom',
noOffset: [200, 350, '50%', null],
offsetBefore: [50, 100, '0%', null],
offsetAfter: [350, 600, '100%', null]
},
{
placement: 'right',
noOffset: [350, 200, null, '50%'],
offsetBefore: [100, 50, null, '0%'],
offsetAfter: [600, 350, null, '100%']
}
].forEach(function(testCase) {
const placement = testCase.placement;
describe(`placement = ${placement}`, function() {
describe('no viewport offset', function() {
checkPosition(
placement, {left: 250, top: 250}, testCase.noOffset
);
});
describe('viewport offset before', function() {
checkPosition(
placement, {left: 0, top: 0}, testCase.offsetBefore
);
});
describe('viewport offset after', function() {
checkPosition(
placement, {left: 500, top: 500}, testCase.offsetAfter
);
});
});
});
});
// ToDo: add remaining tests
});
|
curator-web/src/js/components/frame/header.js
|
rajeshnaroth/curator
|
import React from 'react'
import { Link } from 'react-router'
const Header = () => (
<nav className="navbar navbar-default navbar-fixed-top">
<section className="userMenu">
<li><Link to='/curate'><span>Curate</span></Link></li>
</section>
<Link to='/'><h1>Tube2Flix</h1></Link>
</nav>
)
export default Header
|
components/GameGrid.js
|
turntwogg/esports-aggregator
|
import React from 'react';
import Link from 'next/link';
import LazyLoad from 'react-lazyload';
import idx from 'idx';
import { useTheme } from '@turntwo/react-ui';
import Heading from './Heading';
import CornerBox from './CornerBox';
import api from '../utils/api';
const GameCard = ({ game }) => {
const image = idx(game, _ => _.fieldGameTeaserImage.attributes.url);
return (
<div className="game-card">
<Link
href={`/game?slug=${game.attributes.field_game_slug}`}
as={`/games/${game.attributes.field_game_slug}`}
>
<a className="game-card__main-link">
<LazyLoad height={233} offset={100}>
<img alt={game.attributes.name} src={`${api.formatImg(image)}`} />
</LazyLoad>
<Heading element="h4" className="game-card__title" center>
{game.attributes.name}
</Heading>
</a>
</Link>
<style jsx>{`
.game-card {
max-width: 100%;
}
.game-card__main-link {
position: relative;
display: flex;
flex: 1 1 auto;
flex-flow: column nowrap;
background-color: rgba(0, 0, 0, 0.7);
}
:global(.game-card__title) {
position: absolute;
bottom: 24px;
left: 0;
width: 100%;
margin-bottom: 0;
color: #fff;
font-size: 16px;
font-weight: 700;
line-height: 1.2;
text-align: center;
text-transform: uppercase;
}
`}</style>
</div>
);
};
const GameGrid = ({ games }) => {
const theme = useTheme();
const homeGames = games.data.filter(
game => game.attributes.field_game_home_grid,
);
return (
<div className="game-grid">
{homeGames.map(game => (
<div className="game-grid__item" key={game.id}>
<GameCard game={game} />
</div>
))}
<div className="game-grid__item">
<CornerBox>
<Link href="/games">
<a>See all games</a>
</Link>
</CornerBox>
</div>
<style jsx>{`
.game-grid {
display: grid;
grid-template-columns: 1fr 1fr;
max-width: 750px;
margin: auto;
}
.game-grid__item:last-child {
display: flex;
flex-flow: column;
padding: 16px;
background: linear-gradient(
45deg,
rgba(4, 19, 59, 1) 0%,
rgba(113, 2, 68, 1) 100%
);
}
.game-grid__item:last-child > :global(div) {
display: flex;
flex: 1 auto;
}
.game-grid__item:last-child a {
margin: auto;
color: #fff;
font-size: 16px;
font-weight: 700;
text-transform: uppercase;
}
@media (max-width: ${theme.breakpoints.m + 1}px) {
.game-grid__item:last-child {
grid-column: 1 / span 2;
}
}
@media (min-width: ${theme.breakpoints.m}px) {
.game-grid {
grid-template-columns: 1fr 1fr 1fr;
}
}
`}</style>
</div>
);
};
export default GameGrid;
|
app/javascript/mastodon/features/status/index.js
|
anon5r/mastonon
|
import Immutable from 'immutable';
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { fetchStatus } from '../../actions/statuses';
import MissingIndicator from '../../components/missing_indicator';
import DetailedStatus from './components/detailed_status';
import ActionBar from './components/action_bar';
import Column from '../ui/components/column';
import {
favourite,
unfavourite,
reblog,
unreblog,
pin,
unpin,
} from '../../actions/interactions';
import {
replyCompose,
mentionCompose,
directCompose,
} from '../../actions/compose';
import { blockAccount } from '../../actions/accounts';
import {
muteStatus,
unmuteStatus,
deleteStatus,
hideStatus,
revealStatus,
} from '../../actions/statuses';
import { initMuteModal } from '../../actions/mutes';
import { initReport } from '../../actions/reports';
import { makeGetStatus } from '../../selectors';
import { ScrollContainer } from 'react-router-scroll-4';
import ColumnBackButton from '../../components/column_back_button';
import ColumnHeader from '../../components/column_header';
import StatusContainer from '../../containers/status_container';
import { openModal } from '../../actions/modal';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { HotKeys } from 'react-hotkeys';
import { boostModal, deleteModal } from '../../initial_state';
import { attachFullscreenListener, detachFullscreenListener, isFullscreen } from '../../features/ui/util/fullscreen';
const messages = defineMessages({
deleteConfirm: { id: 'confirmations.delete.confirm', defaultMessage: 'Delete' },
deleteMessage: { id: 'confirmations.delete.message', defaultMessage: 'Are you sure you want to delete this status?' },
blockConfirm: { id: 'confirmations.block.confirm', defaultMessage: 'Block' },
revealAll: { id: 'status.show_more_all', defaultMessage: 'Show more for all' },
hideAll: { id: 'status.show_less_all', defaultMessage: 'Show less for all' },
});
const makeMapStateToProps = () => {
const getStatus = makeGetStatus();
const mapStateToProps = (state, props) => {
const status = getStatus(state, props.params.statusId);
let ancestorsIds = Immutable.List();
let descendantsIds = Immutable.List();
if (status) {
ancestorsIds = ancestorsIds.withMutations(mutable => {
let id = status.get('in_reply_to_id');
while (id) {
mutable.unshift(id);
id = state.getIn(['contexts', 'inReplyTos', id]);
}
});
descendantsIds = descendantsIds.withMutations(mutable => {
const ids = [status.get('id')];
while (ids.length > 0) {
let id = ids.shift();
const replies = state.getIn(['contexts', 'replies', id]);
if (replies) {
replies.forEach(reply => {
mutable.push(reply);
ids.unshift(reply);
});
}
}
});
}
return {
status,
ancestorsIds,
descendantsIds,
};
};
return mapStateToProps;
};
@injectIntl
@connect(makeMapStateToProps)
export default class Status extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
status: ImmutablePropTypes.map,
ancestorsIds: ImmutablePropTypes.list,
descendantsIds: ImmutablePropTypes.list,
intl: PropTypes.object.isRequired,
};
state = {
fullscreen: false,
};
componentWillMount () {
this.props.dispatch(fetchStatus(this.props.params.statusId));
}
componentDidMount () {
attachFullscreenListener(this.onFullScreenChange);
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) {
this._scrolledIntoView = false;
this.props.dispatch(fetchStatus(nextProps.params.statusId));
}
}
handleFavouriteClick = (status) => {
if (status.get('favourited')) {
this.props.dispatch(unfavourite(status));
} else {
this.props.dispatch(favourite(status));
}
}
handlePin = (status) => {
if (status.get('pinned')) {
this.props.dispatch(unpin(status));
} else {
this.props.dispatch(pin(status));
}
}
handleReplyClick = (status) => {
this.props.dispatch(replyCompose(status, this.context.router.history));
}
handleModalReblog = (status) => {
this.props.dispatch(reblog(status));
}
handleReblogClick = (status, e) => {
if (status.get('reblogged')) {
this.props.dispatch(unreblog(status));
} else {
if (e.shiftKey || !boostModal) {
this.handleModalReblog(status);
} else {
this.props.dispatch(openModal('BOOST', { status, onReblog: this.handleModalReblog }));
}
}
}
handleDeleteClick = (status) => {
const { dispatch, intl } = this.props;
if (!deleteModal) {
dispatch(deleteStatus(status.get('id')));
} else {
dispatch(openModal('CONFIRM', {
message: intl.formatMessage(messages.deleteMessage),
confirm: intl.formatMessage(messages.deleteConfirm),
onConfirm: () => dispatch(deleteStatus(status.get('id'))),
}));
}
}
handleDirectClick = (account, router) => {
this.props.dispatch(directCompose(account, router));
}
handleMentionClick = (account, router) => {
this.props.dispatch(mentionCompose(account, router));
}
handleOpenMedia = (media, index) => {
this.props.dispatch(openModal('MEDIA', { media, index }));
}
handleOpenVideo = (media, time) => {
this.props.dispatch(openModal('VIDEO', { media, time }));
}
handleMuteClick = (account) => {
this.props.dispatch(initMuteModal(account));
}
handleConversationMuteClick = (status) => {
if (status.get('muted')) {
this.props.dispatch(unmuteStatus(status.get('id')));
} else {
this.props.dispatch(muteStatus(status.get('id')));
}
}
handleToggleHidden = (status) => {
if (status.get('hidden')) {
this.props.dispatch(revealStatus(status.get('id')));
} else {
this.props.dispatch(hideStatus(status.get('id')));
}
}
handleToggleAll = () => {
const { status, ancestorsIds, descendantsIds } = this.props;
const statusIds = [status.get('id')].concat(ancestorsIds.toJS(), descendantsIds.toJS());
if (status.get('hidden')) {
this.props.dispatch(revealStatus(statusIds));
} else {
this.props.dispatch(hideStatus(statusIds));
}
}
handleBlockClick = (account) => {
const { dispatch, intl } = this.props;
dispatch(openModal('CONFIRM', {
message: <FormattedMessage id='confirmations.block.message' defaultMessage='Are you sure you want to block {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />,
confirm: intl.formatMessage(messages.blockConfirm),
onConfirm: () => dispatch(blockAccount(account.get('id'))),
}));
}
handleReport = (status) => {
this.props.dispatch(initReport(status.get('account'), status));
}
handleEmbed = (status) => {
this.props.dispatch(openModal('EMBED', { url: status.get('url') }));
}
handleHotkeyMoveUp = () => {
this.handleMoveUp(this.props.status.get('id'));
}
handleHotkeyMoveDown = () => {
this.handleMoveDown(this.props.status.get('id'));
}
handleHotkeyReply = e => {
e.preventDefault();
this.handleReplyClick(this.props.status);
}
handleHotkeyFavourite = () => {
this.handleFavouriteClick(this.props.status);
}
handleHotkeyBoost = () => {
this.handleReblogClick(this.props.status);
}
handleHotkeyMention = e => {
e.preventDefault();
this.handleMentionClick(this.props.status);
}
handleHotkeyOpenProfile = () => {
this.context.router.history.push(`/accounts/${this.props.status.getIn(['account', 'id'])}`);
}
handleHotkeyToggleHidden = () => {
this.handleToggleHidden(this.props.status);
}
handleMoveUp = id => {
const { status, ancestorsIds, descendantsIds } = this.props;
if (id === status.get('id')) {
this._selectChild(ancestorsIds.size - 1);
} else {
let index = ancestorsIds.indexOf(id);
if (index === -1) {
index = descendantsIds.indexOf(id);
this._selectChild(ancestorsIds.size + index);
} else {
this._selectChild(index - 1);
}
}
}
handleMoveDown = id => {
const { status, ancestorsIds, descendantsIds } = this.props;
if (id === status.get('id')) {
this._selectChild(ancestorsIds.size + 1);
} else {
let index = ancestorsIds.indexOf(id);
if (index === -1) {
index = descendantsIds.indexOf(id);
this._selectChild(ancestorsIds.size + index + 2);
} else {
this._selectChild(index + 1);
}
}
}
_selectChild (index) {
const element = this.node.querySelectorAll('.focusable')[index];
if (element) {
element.focus();
}
}
renderChildren (list) {
return list.map(id => (
<StatusContainer
key={id}
id={id}
onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown}
/>
));
}
setRef = c => {
this.node = c;
}
componentDidUpdate () {
if (this._scrolledIntoView) {
return;
}
const { status, ancestorsIds } = this.props;
if (status && ancestorsIds && ancestorsIds.size > 0) {
const element = this.node.querySelectorAll('.focusable')[ancestorsIds.size - 1];
element.scrollIntoView(true);
this._scrolledIntoView = true;
}
}
componentWillUnmount () {
detachFullscreenListener(this.onFullScreenChange);
}
onFullScreenChange = () => {
this.setState({ fullscreen: isFullscreen() });
}
render () {
let ancestors, descendants;
const { status, ancestorsIds, descendantsIds, intl } = this.props;
const { fullscreen } = this.state;
if (status === null) {
return (
<Column>
<ColumnBackButton />
<MissingIndicator />
</Column>
);
}
if (ancestorsIds && ancestorsIds.size > 0) {
ancestors = <div>{this.renderChildren(ancestorsIds)}</div>;
}
if (descendantsIds && descendantsIds.size > 0) {
descendants = <div>{this.renderChildren(descendantsIds)}</div>;
}
const handlers = {
moveUp: this.handleHotkeyMoveUp,
moveDown: this.handleHotkeyMoveDown,
reply: this.handleHotkeyReply,
favourite: this.handleHotkeyFavourite,
boost: this.handleHotkeyBoost,
mention: this.handleHotkeyMention,
openProfile: this.handleHotkeyOpenProfile,
toggleHidden: this.handleHotkeyToggleHidden,
};
return (
<Column>
<ColumnHeader
showBackButton
extraButton={(
<button className='column-header__button' title={intl.formatMessage(status.get('hidden') ? messages.revealAll : messages.hideAll)} aria-label={intl.formatMessage(status.get('hidden') ? messages.revealAll : messages.hideAll)} onClick={this.handleToggleAll} aria-pressed={status.get('hidden') ? 'false' : 'true'}><i className={`fa fa-${status.get('hidden') ? 'eye-slash' : 'eye'}`} /></button>
)}
/>
<ScrollContainer scrollKey='thread'>
<div className={classNames('scrollable', 'detailed-status__wrapper', { fullscreen })} ref={this.setRef}>
{ancestors}
<HotKeys handlers={handlers}>
<div className='focusable' tabIndex='0'>
<DetailedStatus
status={status}
onOpenVideo={this.handleOpenVideo}
onOpenMedia={this.handleOpenMedia}
onToggleHidden={this.handleToggleHidden}
/>
<ActionBar
status={status}
onReply={this.handleReplyClick}
onFavourite={this.handleFavouriteClick}
onReblog={this.handleReblogClick}
onDelete={this.handleDeleteClick}
onDirect={this.handleDirectClick}
onMention={this.handleMentionClick}
onMute={this.handleMuteClick}
onMuteConversation={this.handleConversationMuteClick}
onBlock={this.handleBlockClick}
onReport={this.handleReport}
onPin={this.handlePin}
onEmbed={this.handleEmbed}
/>
</div>
</HotKeys>
{descendants}
</div>
</ScrollContainer>
</Column>
);
}
}
|
app/containers/CatKitDemo/SimpleAdsorbateInput.js
|
mhoffman/CatAppBrowser
|
import React from 'react';
import PropTypes, { instanceOf } from 'prop-types';
import { withCookies, Cookies } from 'react-cookie';
import { Link } from 'react-router';
import { compose } from 'recompose';
import _ from 'lodash';
import Grid from 'material-ui/Grid';
import Paper from 'material-ui/Paper';
import Button from 'material-ui/Button';
import { withStyles } from 'material-ui/styles';
import Switch from 'material-ui/Switch';
import { MenuItem } from 'material-ui/Menu';
import Select from 'material-ui/Select';
import { LinearProgress } from 'material-ui/Progress';
import { FormGroup, FormControl, FormControlLabel } from 'material-ui/Form';
import { InputLabel } from 'material-ui/Input';
import { MdLoop, MdChevronLeft, MdChevronRight, MdCheckCircle } from 'react-icons/lib/md';
import {
IoCube,
} from 'react-icons/lib/io';
import { FaList } from 'react-icons/lib/fa';
import Tooltip from 'material-ui/Tooltip';
import GeometryCanvasWithOptions from 'components/GeometryCanvasWithOptions';
import axios from 'axios';
import { apiRoot } from 'utils/constants';
import { styles } from './styles';
const backendRoot = `${apiRoot}/apps/catKitDemo`;
const siteUrl = `${backendRoot}/get_adsorption_sites`;
const defaultOccupation = 'empty';
const initialState = {
siteOccupation: {},
adsorptionSitesLoading: true,
loading: false,
siteType: 'all',
placeHolder: 'empty',
adsorbate: 'O',
activeImage: 0,
siteNames: [],
siteTypes: [],
checkedCatLearn: false,
};
const siteNames = [
'gas',
'top',
'bridge',
'hollow',
'4fold',
];
class AdsorbateInput extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
this.state = initialState;
this.updateAdsorptionSites = this.updateAdsorptionSites.bind(this);
this.handleChange = this.handleChange.bind(this);
this.saveCalculation = this.saveCalculation.bind(this);
}
componentDidMount() {
this.updateAdsorptionSites();
}
handlePageFlip(delta) {
const n = this.props.images.length;
this.setState({
activeImage: (((this.state.activeImage + delta) % n) + n) % n,
// javascript version of modulo that works for positive and negative
// input.
});
}
handleSwitch(name) {
return (event, checked) => {
this.setState({ [name]: checked });
this.updateAdsorptionSites({ callCatLearn: event.target.value });
};
}
resetPageFlip() {
this.setState({
activeImage: 0,
});
}
updateAdsorptionSites(options = {}) {
this.setState({
loading: true,
});
const adsorbateParams = {
siteType: options.siteType || this.state.siteType,
placeHolder: options.placeHolder || this.state.placeHolder,
adsorbate: options.adsorbate || this.state.adsorbate,
format: this.props.cookies.get('preferredFormat'),
callCatLearn: this.state.checkedCatLearn,
};
const params = { params: {
bulk_cif: this.props.bulkCif,
bulkParams: _.omit(this.props.bulkParams, ['cif', 'input', 'wyckoff.cif']),
slabParams: _.omit(this.props.slabParams, ['cif', 'input']),
adsorbateParams,
} };
axios.get(siteUrl, params).then((response) => {
if (response.data.error) {
this.props.openSnackbar(response.data.error);
}
const siteOccupation = [];
this.props.saveAdsorbateParams({
...adsorbateParams,
cifs: response.data.cifImages,
equations: response.data.equations,
molecules: response.data.molecules,
inputs: response.data.inputImages,
mean: response.data.mean,
uncertainty: response.data.uncertainty,
references: response.data.references,
});
this.props.saveAdsorptionSites(response.data.data);
this.setState({
siteNames: response.data.site_names,
siteTypes: response.data.site_types,
});
response.data.data.map((imageSites, i) => {
siteOccupation[i] = {};
return Object.keys(imageSites).map((siteName) => {
siteOccupation[i][siteName] = [];
return imageSites[siteName][0].map(() => siteOccupation[i][siteName].push(defaultOccupation));
});
});
this.props.receiveSlabCifs(response.data.cifImages);
this.props.saveAltLabels(response.data.altLabels);
this.setState({
siteOccupation,
adsorptionSitesLoading: false,
});
this.props.saveSiteOccupations(siteOccupation);
this.setState({
loading: false,
});
});
}
handleChange(name) {
return (event) => {
this.setState({
[name]: event.target.value,
});
if (name === 'placeHolder') {
this.updateAdsorptionSites({ placeHolder: event.target.value });
} else if (name === 'siteType') {
this.updateAdsorptionSites({ siteType: event.target.value });
} else if (name === 'adsorbate') {
this.updateAdsorptionSites({ adsorbate: event.target.value });
}
};
}
saveCalculation() {
this.props.saveCalculation({
bulkParams: this.props.bulkParams,
slabParams: this.props.slabParams,
siteOccupations: this.props.siteOccupations,
adsorbateParams: this.props.adsorbateParams,
dftParams: {
calculator: this.state.calculator,
functional: this.state.functional,
},
});
this.props.clearBulkParams();
this.props.clearBulkCif();
this.props.clearSlabParams();
this.props.clearSlabCifs();
}
render() {
return (
<div>
{ this.props.bulkCif === '' ? null :
<div>
{(typeof this.props.adsorptionSites === 'undefined' ||
!_.isFunction(this.props.adsorptionSites.map)) ?
null
:
<div>
<Paper className={this.props.classes.paper}>
<Grid container direction="row" justify="space-between">
<Grid item>
<h2>Configure Adsorbates</h2>
</Grid>
<Grid item>
<Grid container direction="row" justify="space-between">
<Grid item>
<FormGroup row className={this.props.classes.formGroup} >
<FormControl >
<InputLabel>Adsorbate</InputLabel>
<Select
className={this.props.classes.select}
value={this.state.adsorbate}
onChange={this.handleChange('adsorbate')}
>
<MenuItem value="C">C</MenuItem>
<MenuItem value="CH">CH</MenuItem>
<MenuItem value="CHH">CHH</MenuItem>
<MenuItem value="CHHH">CHHH</MenuItem>
<MenuItem value="CO">CO</MenuItem>
<MenuItem value="COH">COH</MenuItem>
<MenuItem value="COO">COO</MenuItem>
<MenuItem value="H">H</MenuItem>
<MenuItem value="N">N</MenuItem>
<MenuItem value="NH">NH</MenuItem>
<MenuItem value="NHH">NHH</MenuItem>
<MenuItem value="NO">NO</MenuItem>
<MenuItem value="O">O</MenuItem>
<MenuItem value="OCHO">OCHO</MenuItem>
<MenuItem value="OH">OH</MenuItem>
<MenuItem value="OOH">OOH</MenuItem>
<MenuItem value="S">S</MenuItem>
<MenuItem value="SH">SH</MenuItem>
</Select>
</FormControl>
</FormGroup>
</Grid>
<Grid item>
<FormGroup row className={this.props.classes.formGroup} >
<FormControl >
<InputLabel>Site Type</InputLabel>
<Select
className={this.props.classes.select}
value={this.state.siteType}
onChange={this.handleChange('siteType')}
>
<MenuItem value="all">all</MenuItem>
{this.state.siteTypes.map((siteType) => (
<MenuItem key={`siteType_${siteType}`} value={siteType}>{`${siteType} (${_.get(siteNames, siteType, 'all')})`}</MenuItem>
)
)}
</Select>
</FormControl>
</FormGroup>
</Grid>
<Grid item>
<FormGroup row className={this.props.classes.formGroup} >
<FormControl >
<InputLabel>Placeholder</InputLabel>
<Select
className={this.props.classes.select}
value={this.state.placeHolder}
onChange={this.handleChange('placeHolder')}
>
<MenuItem value="empty">empty</MenuItem>
<MenuItem value="Cl">Cl</MenuItem>
<MenuItem value="F">F</MenuItem>
<MenuItem value="B">B</MenuItem>
<MenuItem value="H">H</MenuItem>
<MenuItem value="Ne">Ne</MenuItem>
<MenuItem value="Br">Br</MenuItem>
</Select>
</FormControl>
</FormGroup>
</Grid>
<Grid item>
<Tooltip title="Powered by CatLearn">
<FormControlLabel
control={
<Switch
checked={this.state.checkedCatLearn}
onChange={this.handleSwitch('checkedCatLearn')}
/>
}
label="Estimate energies"
/>
</Tooltip>
</Grid>
</Grid>
</Grid>
</Grid>
</Paper>
{this.state.loading ? <LinearProgress /> : null }
</div>
}
{ _.isEmpty(this.props.adsorbateParams) || _.isEmpty(this.props.adsorbateParams.mean) ? null :
<Paper className={this.props.classes.paper}>
<Grid item>
<Grid container direction="row" justify="space-between">
<Grid item>
<h4> Estimated adsorbate energy </h4>
<div>
{Number((this.props.adsorbateParams.mean[this.state.activeImage]).toFixed(2))}{' eV \xb1 '}{Number((this.props.adsorbateParams.uncertainty[this.state.activeImage]).toFixed(2))}{' eV'}
</div>
</Grid>
<Grid item>
<h4>versus</h4>
<div>{this.props.adsorbateParams.references[this.state.activeImage]}</div>
</Grid>
</Grid>
</Grid>
</Paper>
}
<Paper className={this.props.classes.paper}>
<Grid container justify="center" direction="row">
<Grid item >
<Grid container direction="column" justify="space-around" className={this.props.classes.flipButton}>
<Grid item >
<Button
fab
mini
onClick={() => this.handlePageFlip(-1)}
>
<MdChevronLeft size={30} />
</Button>
</Grid>
</Grid>
</Grid>
<Grid item key={`item_${this.state.activeImage}`}>
<h4>{this.state.siteType !== 'all' ?
`Site "${this.state.siteType} (${siteNames[this.state.siteType]})"`
: `Site "${this.state.siteNames[this.state.activeImage]} (${_.get(siteNames, this.state.siteNames[this.state.activeImage], '')})"`}{` \u2014 (${this.state.activeImage + 1}/${this.props.images.length}).`}</h4>
<GeometryCanvasWithOptions
cifdata={this.props.images[this.state.activeImage]}
uniqueId={`slab_preview_${this.state.activeImage}`}
key={`slab_preview_${this.state.activeImage}`}
id={`slab_preview_${this.state.activeImage}`}
x={1} y={1} z={1}
altLabels={this.props.altLabels[0]}
/>
</Grid>
<Grid item >
<Grid container direction="column" justify="center" className={this.props.classes.flipButton}>
<Grid item>
<Button
fab
mini
onClick={() => this.handlePageFlip(+1)}
>
<MdChevronRight size={30} />
</Button>
</Grid>
</Grid>
</Grid>
</Grid>
</Paper>
</div>
}
{!_.isEmpty(this.props.slabParams) ? null :
<Grid container justify="center" direction="row">
<Grid item>
<Grid container direction="column" justify="space-between">
<Grid item className={this.props.classes.finish}>
{'And that\'s a wrap.\u00A0\u00A0\u00A0'} <MdCheckCircle size={92} color="green" />
</Grid>
<Grid item>
<div>Start new structure from scratch:
<Button
onClick={this.props.stepperHandleReset}
raised
className={this.props.classes.button}
><MdLoop />{'\u00A0'} Start Over </Button> </div>
</Grid>
<Grid item>
Find and start from an existing structure
<Link to="/prototypeSearch" className={this.props.classes.buttonLink}>
<Button raised onClick={this.props.stepperHandleReset} className={this.props.classes.button}><IoCube /> {'\u00A0'} Prototype Search </Button>
</Link>
</Grid>
</Grid>
</Grid>
</Grid>
}
<Grid container justify="flex-end" direction="row">
<Grid item>
<Button
raised
disabled={_.isEmpty(this.props.slabParams)}
onClick={this.saveCalculation}
color="primary"
><FaList /> {'\u00A0\u00A0'}Store Calculation</Button>
</Grid>
</Grid>
</div>
);
}
}
AdsorbateInput.defaultProps = {
altLabels: [],
};
AdsorbateInput.propTypes = {
adsorbateParams: PropTypes.object,
adsorptionSites: PropTypes.array,
altLabels: PropTypes.array,
bulkCif: PropTypes.string,
bulkParams: PropTypes.object,
classes: PropTypes.object,
clearBulkCif: PropTypes.func,
clearBulkParams: PropTypes.func,
clearSlabCifs: PropTypes.func,
clearSlabParams: PropTypes.func,
cookies: instanceOf(Cookies),
images: PropTypes.array,
openSnackbar: PropTypes.func,
receiveSlabCifs: PropTypes.func,
saveAdsorbateParams: PropTypes.func.isRequired,
saveAdsorptionSites: PropTypes.func,
saveAltLabels: PropTypes.func,
saveCalculation: PropTypes.func,
saveSiteOccupations: PropTypes.func,
siteOccupations: PropTypes.object,
slabParams: PropTypes.object,
stepperHandleReset: PropTypes.func,
};
export default compose(
withStyles(styles, { withTheme: true }),
withCookies,
)((AdsorbateInput));
|
packages/react-scripts/fixtures/kitchensink/src/features/webpack/SassModulesInclusion.js
|
ConnectedHomes/create-react-web-app
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import styles from './assets/sass-styles.module.sass';
import indexStyles from './assets/index.module.sass';
export default () => (
<div>
<p className={styles.sassModulesInclusion}>SASS Modules are working!</p>
<p className={indexStyles.sassModulesIndexInclusion}>
SASS Modules with index are working!
</p>
</div>
);
|
Docker/KlusterKiteMonitoring/klusterkite-web/src/components/Form/Modal.js
|
KlusterKite/KlusterKite
|
import React from 'react';
import { Modal, Button } from 'react-bootstrap';
import './styles.css';
export default class ModalBlock extends React.Component {
static propTypes = {
title: React.PropTypes.string.isRequired,
cancelText: React.PropTypes.string,
confirmText: React.PropTypes.string,
confirmClass: React.PropTypes.string,
onCancel: React.PropTypes.func.isRequired,
onConfirm: React.PropTypes.func.isRequired
};
render() {
return (
<div>
<div className="static-modal static-modal-center">
<Modal.Dialog>
<Modal.Header>
<Modal.Title>{this.props.title}</Modal.Title>
</Modal.Header>
<Modal.Body>
{this.props.children}
</Modal.Body>
<Modal.Footer>
<Button onClick={this.props.onCancel}>{this.props.cancelText || "Cancel"}</Button>
<Button onClick={this.props.onConfirm} bsStyle={this.props.confirmClass || "danger"}>{this.props.confirmText || "Confirm"}</Button>
</Modal.Footer>
</Modal.Dialog>
</div>
</div>
);
}
}
|
docs/app/Examples/modules/Dimmer/States/DimmerExampleActive.js
|
ben174/Semantic-UI-React
|
import React from 'react'
import { Dimmer, Segment } from 'semantic-ui-react'
const DimmerExampleActive = () => (
<Segment>
<Dimmer active />
<p>
<img src='http://semantic-ui.com/images/wireframe/short-paragraph.png' />
</p>
<p>
<img src='http://semantic-ui.com/images/wireframe/short-paragraph.png' />
</p>
</Segment>
)
export default DimmerExampleActive
|
src/dumb/editor/NotificationMap.js
|
jeckhummer/wf-constructor
|
import React from 'react';
import {Table, Checkbox} from "semantic-ui-react";
export const NotificationMap = ({map, teams, statuses, onChange}) => {
return (
<Table definition>
<Table.Header>
<Table.Row textAlign='center'>
<Table.HeaderCell />
{
statuses.map((status, i) => (
<Table.HeaderCell key={i} content={status}/>
))
}
</Table.Row>
</Table.Header>
<Table.Body>
{
teams.map((team, teamIndex) => (
<Table.Row textAlign='center' key={teamIndex}>
<Table.Cell content={team}/>
{
map[teamIndex].map((checked, statusIndex) => (
<Table.Cell key={statusIndex}>
<Checkbox
checked={checked}
onChange={(_, {checked}) => onChange(teamIndex, statusIndex, checked)}
/>
</Table.Cell>
))
}
</Table.Row>
))
}
</Table.Body>
</Table>
);
};
|
src/svg-icons/editor/drag-handle.js
|
mmrtnz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorDragHandle = (props) => (
<SvgIcon {...props}>
<path d="M20 9H4v2h16V9zM4 15h16v-2H4v2z"/>
</SvgIcon>
);
EditorDragHandle = pure(EditorDragHandle);
EditorDragHandle.displayName = 'EditorDragHandle';
EditorDragHandle.muiName = 'SvgIcon';
export default EditorDragHandle;
|
docs/app/Examples/elements/List/Variations/ListExampleDivided.js
|
aabustamante/Semantic-UI-React
|
import React from 'react'
import { Image, List } from 'semantic-ui-react'
const ListExampleDivided = () => (
<List divided verticalAlign='middle'>
<List.Item>
<Image avatar src='/assets/images/avatar/small/daniel.jpg' />
<List.Content>
<List.Header as='a'>Daniel Louise</List.Header>
</List.Content>
</List.Item>
<List.Item>
<Image avatar src='/assets/images/avatar/small/stevie.jpg' />
<List.Content>
<List.Header as='a'>Stevie Feliciano</List.Header>
</List.Content>
</List.Item>
<List.Item>
<Image avatar src='/assets/images/avatar/small/elliot.jpg' />
<List.Content>
<List.Header as='a'>Elliot Fu</List.Header>
</List.Content>
</List.Item>
</List>
)
export default ListExampleDivided
|
src/index.js
|
hlgbls/ReduxSimpleStarter
|
import _ from 'lodash';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail'
const API_KEY = 'AIzaSyDU2RsXS53i3yrCheiuqu2LVQxHVCmWCIE';
class App extends Component {
constructor(props) {
super(props);
this.state = {
videos: [],
selectedVideo: null
};
this.videoSearch('');
}
videoSearch(term) {
YTSearch({ key: API_KEY, term: term }, (videos) => {
this.setState({
videos: videos,
selectedVideo: videos[0]
});
});
}
render() {
const videoSearch = _.debounce((term) => { this.videoSearch(term)}, 500 );
return (
<div>
<SearchBar onSearchTermChange={videoSearch} />
<VideoDetail video={this.state.selectedVideo} />
<VideoList
onVideoSelect={selectedVideo => this.setState({ selectedVideo })}
videos={this.state.videos} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container'))
|
node_modules/react-router/es/Route.js
|
Rabbit884/reactapp
|
import React from 'react';
import invariant from 'invariant';
import { createRouteFromReactElement } from './RouteUtils';
import { component, components } from './InternalPropTypes';
var _React$PropTypes = React.PropTypes,
string = _React$PropTypes.string,
func = _React$PropTypes.func;
/**
* A <Route> is used to declare which components are rendered to the
* page when the URL matches a given pattern.
*
* Routes are arranged in a nested tree structure. When a new URL is
* requested, the tree is searched depth-first to find a route whose
* path matches the URL. When one is found, all routes in the tree
* that lead to it are considered "active" and their components are
* rendered into the DOM, nested in the same order as in the tree.
*/
/* eslint-disable react/require-render-return */
var Route = React.createClass({
displayName: 'Route',
statics: {
createRouteFromReactElement: createRouteFromReactElement
},
propTypes: {
path: string,
component: component,
components: components,
getComponent: func,
getComponents: func
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Route> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default Route;
|
src/svg-icons/action/polymer.js
|
nathanmarks/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPolymer = (props) => (
<SvgIcon {...props}>
<path d="M19 4h-4L7.11 16.63 4.5 12 9 4H5L.5 12 5 20h4l7.89-12.63L19.5 12 15 20h4l4.5-8z"/>
</SvgIcon>
);
ActionPolymer = pure(ActionPolymer);
ActionPolymer.displayName = 'ActionPolymer';
ActionPolymer.muiName = 'SvgIcon';
export default ActionPolymer;
|
app/private/indexerApp/imports/ui/pages/Ingest.js
|
ericvrp/GameCollie
|
import React from 'react';
import { Link } from 'react-router';
import { Row, Col, FormGroup, ControlLabel, FormControl, Button } from 'react-bootstrap';
export default class Ingest extends React.Component {
componentDidMount() {
}
ingestFiles(event) {
event.preventDefault();
const itemHashes = [
{"path":"./gba/0001 - F-Zero for GameBoy Advance (J)(Mr. Lee)/0001 - F-Zero for GameBoy Advance (J)(Mr. Lee).gba", "sha256":"0x86C5E12E6C9C946A2E3FDA7BDDAC25455C2CF0C6E78D4AF9108714A5BBADEE4E", "md5":"0x0915AC62D58A160028EB47141657013F", "crc32":"0x25E3FC9A"},
{"path":"./n64/Banjo-Tooie (U) [!].v64", "sha256":"0x9EC37FBA6890362EBA86FB855697A9CFF1519275531B172083A1A6A045483583", "md5":"0x40E98FAA24AC3EBE1D25CB5E5DDF49E4", "crc32":"0xBAB803EF"},
{"path":"./n64/Banjo-Tooie (U) [!].z64", "sha256":"0x9EC37FBA6890362EBA86FB855697A9CFF1519275531B172083A1A6A045483583", "md5":"0x40E98FAA24AC3EBE1D25CB5E5DDF49E4", "crc32":"0xBAB803EF"},
{"path":"./n64/Donkey Kong 64 (U) [!].v64", "sha256":"0x5778C9EF72EF269CDCC52333710A79961A343B1F01D12189D1DBE94DF3CBABED", "md5":"0xB71A88BA73E141FA2D355A6A72F46F6C", "crc32":"0x96972D67"},
{"path":"./n64/Donkey Kong 64 (U) [!].z64", "sha256":"0xB6347D9F1F75D38A88D829B4F80B1ACF0D93344170A5FBE9546C484DAE416CE3", "md5":"0x9EC41ABF2519FC386CADD0731F6E868C", "crc32":"0xD44B4FC6"},
{"path":"./n64/Dr. Mario 64 (U) [!].v64", "sha256":"0x613778B244784492A881C0D72D6017F82C39026706A406BD7EF95C6F33E53B89", "md5":"0x30EC4F3E1C435ED8B1D1FD3788B6A407", "crc32":"0xF7C44B5B"},
{"path":"./psx/Crash Bandicoot 2/Crash 2.bin", "sha256":"0xA2E2AB37CD6E0D5180876BF7786AC699B3B691208EFE8DE66AFE7779BF4D1605", "md5":"0x3C31B5E038F025098A2FDFA70C8213F2", "crc32":"0x395C0916"},
{"path":"./psx/Crash Bandicoot 2/Crash 2.cue", "sha256":"0xBE5587C93CB4180FE6156DCB931EFC81F2DBBFE491018E5E8F7C9F81DC15A93B", "md5":"0xCAFB479A95A1F2880C1C61B4796A665C", "crc32":"0xA0BE515F"},
];
for(i=0;i<itemHashes.length;i++) {
var item = itemHashes[i];
var data = {
path:item.path,
hash_sha256:item.sha256,
hash_md5:item.md5,
hash_crc32:item.crc32
};
Meteor.call('files.upsert', data);
}
}
render() {
return (
<div className="IngestFiles">
<Row>
<Col xs={ 12 } sm={ 6 } md={ 4 }>
<h4 className="page-header">Import File</h4>
<Button type="submit" bsStyle="success" onClick={this.ingestFiles}>Ingest</Button>
</Col>
</Row>
</div>
);
}
}
|
docs/src/app/components/pages/components/List/ExampleSettings.js
|
w01fgang/material-ui
|
import React from 'react';
import MobileTearSheet from '../../../MobileTearSheet';
import {List, ListItem} from 'material-ui/List';
import Subheader from 'material-ui/Subheader';
import Divider from 'material-ui/Divider';
import Checkbox from 'material-ui/Checkbox';
import Toggle from 'material-ui/Toggle';
const styles = {
root: {
display: 'flex',
flexWrap: 'wrap',
},
};
const ListExampleSettings = () => (
<div style={styles.root}>
<MobileTearSheet>
<List>
<Subheader>General</Subheader>
<ListItem
primaryText="Profile photo"
secondaryText="Change your Google+ profile photo"
/>
<ListItem
primaryText="Show your status"
secondaryText="Your status is visible to everyone you use with"
/>
</List>
<Divider />
<List>
<Subheader>Hangout Notifications</Subheader>
<ListItem
leftCheckbox={<Checkbox />}
primaryText="Notifications"
secondaryText="Allow notifications"
/>
<ListItem
leftCheckbox={<Checkbox />}
primaryText="Sounds"
secondaryText="Hangouts message"
/>
<ListItem
leftCheckbox={<Checkbox />}
primaryText="Video sounds"
secondaryText="Hangouts video call"
/>
</List>
</MobileTearSheet>
<MobileTearSheet>
<List>
<ListItem
primaryText="When calls and notifications arrive"
secondaryText="Always interrupt"
/>
</List>
<Divider />
<List>
<Subheader>Priority Interruptions</Subheader>
<ListItem primaryText="Events and reminders" rightToggle={<Toggle />} />
<ListItem primaryText="Calls" rightToggle={<Toggle />} />
<ListItem primaryText="Messages" rightToggle={<Toggle />} />
</List>
<Divider />
<List>
<Subheader>Hangout Notifications</Subheader>
<ListItem primaryText="Notifications" leftCheckbox={<Checkbox />} />
<ListItem primaryText="Sounds" leftCheckbox={<Checkbox />} />
<ListItem primaryText="Video sounds" leftCheckbox={<Checkbox />} />
</List>
</MobileTearSheet>
</div>
);
export default ListExampleSettings;
|
src/components/topic/snapshots/foci/builder/FocusForm2ConfigureContainer.js
|
mitmedialab/MediaCloud-Web-Tools
|
import PropTypes from 'prop-types';
import React from 'react';
import { formValueSelector } from 'redux-form';
import { FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import EditSearchContainer from './search/EditSearchContainer';
import EditRetweetPartisanshipContainer from './retweetPartisanship/EditRetweetPartisanshipContainer';
import EditTopCountriesContainer from './topCountries/EditTopCountriesContainer';
import EditNytThemeContainer from './nyttheme/EditNytThemeContainer';
import EditMediaTypeContainer from './mediaType/EditMediaTypeContainer';
import { goToCreateFocusStep } from '../../../../../actions/topicActions';
import { FOCAL_TECHNIQUE_BOOLEAN_QUERY, FOCAL_TECHNIQUE_RETWEET_PARTISANSHIP, FOCAL_TECHNIQUE_TOP_COUNTRIES, FOCAL_TECHNIQUE_NYT_THEME, FOCAL_TECHNIQUE_MEDIA_TYPE } from '../../../../../lib/focalTechniques';
import messages from '../../../../../resources/messages';
const formSelector = formValueSelector('snapshotFocus');
const FocusForm2ConfigureContainer = (props) => {
const { topicId, initialValues, handleNextStep, currentFocalTechnique, handlePreviousStep, location } = props;
let content = null;
switch (currentFocalTechnique) {
case FOCAL_TECHNIQUE_BOOLEAN_QUERY:
content = (
<EditSearchContainer
topicId={topicId}
initialValues={initialValues}
onPreviousStep={handlePreviousStep}
onNextStep={handleNextStep}
location={location}
/>
);
break;
case FOCAL_TECHNIQUE_RETWEET_PARTISANSHIP:
content = (
<EditRetweetPartisanshipContainer
topicId={topicId}
initialValues={initialValues}
onPreviousStep={handlePreviousStep}
onNextStep={handleNextStep}
location={location}
/>
);
break;
case FOCAL_TECHNIQUE_TOP_COUNTRIES:
content = (
<EditTopCountriesContainer
topicId={topicId}
initialValues={initialValues}
onPreviousStep={handlePreviousStep}
onNextStep={handleNextStep}
location={location}
/>
);
break;
case FOCAL_TECHNIQUE_NYT_THEME:
content = (
<EditNytThemeContainer
topicId={topicId}
initialValues={initialValues}
onPreviousStep={handlePreviousStep}
onNextStep={handleNextStep}
location={location}
/>
);
break;
case FOCAL_TECHNIQUE_MEDIA_TYPE:
content = (
<EditMediaTypeContainer
topicId={topicId}
initialValues={initialValues}
onPreviousStep={handlePreviousStep}
onNextStep={handleNextStep}
location={location}
/>
);
break;
default:
content = <FormattedMessage {...messages.unimplemented} />;
}
return (
<div>
{ content }
</div>
);
};
FocusForm2ConfigureContainer.propTypes = {
// from parent
topicId: PropTypes.number.isRequired,
initialValues: PropTypes.object,
// form context
intl: PropTypes.object.isRequired,
// from dipatch
handlePreviousStep: PropTypes.func.isRequired,
handleNextStep: PropTypes.func.isRequired,
// from state:
currentFocalTechnique: PropTypes.string.isRequired,
location: PropTypes.object,
};
const mapStateToProps = (state, ownProps) => ({
currentFocalTechnique: formSelector(state, 'focalTechnique'),
params: ownProps.params,
});
const mapDispatchToProps = dispatch => ({
handlePreviousStep: () => {
dispatch(goToCreateFocusStep(0));
},
handleNextStep: () => {
dispatch(goToCreateFocusStep(2));
},
});
export default
connect(mapStateToProps, mapDispatchToProps)(
injectIntl(
FocusForm2ConfigureContainer
)
);
|
src/client/assets/javascripts/app/routes.js
|
nicksp/redux-webpack-es6-boilerplate
|
import React from 'react';
import { Route, IndexRoute, Redirect } from 'react-router';
import App from './App';
import FriendsView from 'features/friends/components/FriendsView';
import NotFoundView from 'components/NotFound';
export default (
<Route path="/" component={App}>
<IndexRoute component={FriendsView} />
<Route path="404" component={NotFoundView} />
<Redirect from="*" to="404" />
</Route>
);
|
src/components/const/addedVideoUser.js
|
motion123/mbookmakerUI
|
/**
* Created by tomino on 17/03/14.
*/
import React from 'react';
import {List,ListItem} from 'material-ui/List';
import InfiniteScroll from 'react-infinite-scroller';
import CircularProgress from 'material-ui/CircularProgress';
import style from './boardList.css';
import {grey500, darkBlack, lightBlack} from 'material-ui/styles/colors';
export default class AddVideoUser extends React.Component {
render() {
const {
boardInfo,
loadMore,
hasMore,
} = this.props;
const loader = <div className={style.loader}>
<CircularProgress
size={20}
/>
</div>;
let item = [];
boardInfo.map((info) =>
item.push(
<ListItem
key={info._id}
primaryText={info._user.name}
secondaryText={
<p>
<span style={{color: darkBlack}}>{info.board_title}</span>
へ追加しました。
</p>
}
/>
)
);
return (
<InfiniteScroll
loadMore={loadMore}
loader={loader}
hasMore={hasMore}
useWindow={false}
>
<List>
{item}
</List>
</InfiniteScroll>
);
}
}
|
Realization/frontend/czechidm-acc/src/content/provisioning/ProvisioningOperationTable.js
|
bcvsolutions/CzechIdMng
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import _ from 'lodash';
import { Link } from 'react-router-dom';
//
import { Basic, Advanced, Enums, Utils, Managers } from 'czechidm-core';
import SystemEntityTypeEnum from '../../domain/SystemEntityTypeEnum';
import ProvisioningOperationTypeEnum from '../../domain/ProvisioningOperationTypeEnum';
import EmptyProvisioningTypeEnum from '../../domain/EmptyProvisioningTypeEnum';
import { SystemManager } from '../../redux';
const systemManager = new SystemManager();
/**
* Provisioning operation and archive table.
*
* @author Radk Tomiška
*/
export class ProvisioningOperationTable extends Advanced.AbstractTableContent {
constructor(props, context) {
super(props, context);
this.state = {
filterOpened: this.props.filterOpened,
operationState: this._getOperationState(props._searchParameters)
};
}
UNSAFE_componentWillReceiveProps(nextProps) {
// filters from redux
if (nextProps._searchParameters) {
const newOperationState = this._getOperationState(nextProps._searchParameters);
if (newOperationState && this.state.operationState !== newOperationState) {
this.setState({
operationState: newOperationState
}, () => {
//
const filterData = {};
nextProps._searchParameters.getFilters().forEach((v, k) => {
filterData[k] = v;
});
this.refs.filterForm.setData(filterData);
this.refs.table.useFilterData(filterData);
});
}
}
}
_getOperationState(searchParameters) {
if (!searchParameters || !searchParameters.getFilters().has('resultState')) {
return null;
}
return searchParameters.getFilters().get('resultState');
}
getContentKey() {
return 'acc:content.provisioningOperations';
}
getManager() {
return this.props.manager;
}
clearSelectedRows() {
this.refs.table.clearSelectedRows();
}
reload() {
this.refs.table.reload();
}
useFilter(event) {
if (event) {
event.preventDefault();
}
this.refs.table.useFilterForm(this.refs.filterForm);
}
cancelFilter(event) {
if (event) {
event.preventDefault();
}
this.setState({
operationState: null
}, () => {
if (this.refs.emptyProvisioning) {
this.refs.emptyProvisioning.setValue(null);
}
this.refs.table.cancelFilter(this.refs.filterForm);
});
}
getDefaultSearchParameters() {
let searchParameters = this.getManager().getDefaultSearchParameters();
//
if (this.props.isArchive) {
searchParameters = searchParameters.setFilter('emptyProvisioning',
Utils.Config.getConfig('provisioning-archive.table.filter.emptyProvisioning', null));
}
//
return searchParameters;
}
_deleteAll() {
const { uiKey, manager, isArchive } = this.props;
if (isArchive) {
// not supported for archive
return;
}
//
this.refs['confirm-deleteAll'].show(
this.i18n(`action.deleteAll.message`),
this.i18n(`action.deleteAll.header`),
(result) => {
if (result === 'reject') {
return true;
}
if (result === 'confirm' && this.refs['delete-form'].isFormValid()) {
return true;
}
return false;
}
).then(() => {
const systemField = this.refs['delete-system'];
if (systemField.isValid()) {
//
this.context.store.dispatch(manager.deleteAll(systemField.getValue(), uiKey, (entity, error) => {
if (!error) {
this.addMessage({ level: 'success', message: this.i18n('action.deleteAll.success')});
} else {
this.addError(error);
}
this.reload();
}));
}
}, () => {
// nothing
});
}
render() {
const {
uiKey,
manager,
showRowSelection,
showDetail,
forceSearchParameters,
columns,
isArchive,
showDeleteAllButton,
showTransactionId
} = this.props;
const { filterOpened } = this.state;
let systemId = null;
if (forceSearchParameters && forceSearchParameters.getFilters().has('systemId')) {
systemId = forceSearchParameters.getFilters().get('systemId');
}
//
return (
<Basic.Div>
<Basic.Confirm ref="confirm-deleteAll" level="danger">
<Basic.Div style={{ marginTop: 20 }}>
<Basic.AbstractForm ref="delete-form" uiKey="confirm-deleteAll" >
<Basic.SelectBox
ref="delete-system"
label={ this.i18n('action.deleteAll.system.label') }
placeholder={ this.i18n('action.deleteAll.system.placeholder') }
manager={ systemManager }
value={ systemId }
readOnly={ systemId !== null }/>
</Basic.AbstractForm>
</Basic.Div>
</Basic.Confirm>
<Advanced.Table
ref="table"
uiKey={ uiKey }
manager={ manager }
showRowSelection={ showRowSelection }
forceSearchParameters={ forceSearchParameters }
filterOpened={ filterOpened }
filter={
<Advanced.Filter onSubmit={ this.useFilter.bind(this) }>
<Basic.AbstractForm ref="filterForm">
<Basic.Row>
<Basic.Col lg={ 8 }>
<Advanced.Filter.FilterDate ref="fromTill" placeholder="TODO"/>
</Basic.Col>
<Basic.Col lg={ 4 } className="text-right">
<Advanced.Filter.FilterButtons cancelFilter={ this.cancelFilter.bind(this) }/>
</Basic.Col>
</Basic.Row>
<Basic.Row>
<Basic.Col lg={ 4 }>
<Advanced.Filter.EnumSelectBox
ref="resultState"
placeholder={ this.i18n('acc:entity.ProvisioningOperation.resultState') }
enum={ Enums.OperationStateEnum }/>
</Basic.Col>
<Basic.Col lg={ 4 }>
<Advanced.Filter.EnumSelectBox
ref="operationType"
placeholder={ this.i18n('acc:entity.ProvisioningOperation.operationType') }
enum={ ProvisioningOperationTypeEnum }/>
</Basic.Col>
<Basic.Col lg={ 4 }>
{
!_.includes(columns, 'system')
||
<Advanced.Filter.SelectBox
ref="systemId"
placeholder={ this.i18n('acc:entity.System._type') }
multiSelect={ false }
manager={ systemManager }/>
}
</Basic.Col>
</Basic.Row>
<Basic.Row rendered={ _.includes(columns, 'entityIdentifier') }>
<Basic.Col lg={ 4 }>
<Advanced.Filter.EnumSelectBox
ref="entityType"
placeholder={ this.i18n('acc:entity.SystemEntity.entityType') }
enum={ SystemEntityTypeEnum }/>
</Basic.Col>
<Basic.Col lg={ 8 }>
<Basic.Row>
<Basic.Col lg={ showTransactionId ? 4 : 6 }>
<Advanced.Filter.TextField
ref="entityIdentifier"
placeholder={ this.i18n('acc:entity.ProvisioningOperation.entityIdentifier') }/>
</Basic.Col>
<Basic.Col lg={ showTransactionId ? 4 : 6 }>
<Advanced.Filter.TextField
ref="systemEntityUid"
placeholder={ this.i18n('acc:entity.SystemEntity.uid') }/>
</Basic.Col>
<Basic.Col lg={ 4 } rendered={ showTransactionId }>
<Advanced.Filter.TextField
ref="transactionId"
placeholder={ this.i18n('filter.transactionId.placeholder') }/>
</Basic.Col>
</Basic.Row>
</Basic.Col>
</Basic.Row>
<Basic.Row className="last">
<Basic.Col lg={ 4 }>
<Advanced.Filter.CreatableSelectBox
ref="attributeUpdated"
placeholder={ this.i18n('filter.attributeUpdated.placeholder') }/>
</Basic.Col>
<Basic.Col lg={ 4 }>
<Advanced.Filter.CreatableSelectBox
ref="attributeRemoved"
placeholder={ this.i18n('filter.attributeRemoved.placeholder') }/>
</Basic.Col>
<Basic.Col lg={ 4 }>
<Advanced.Filter.EnumSelectBox
ref="emptyProvisioningType"
placeholder={ this.i18n('filter.emptyProvisioning.placeholder') }
enum={ EmptyProvisioningTypeEnum }
rendered={ !isArchive }/>
<Advanced.Filter.BooleanSelectBox
ref="emptyProvisioning"
placeholder={ this.i18n('filter.emptyProvisioning.placeholder') }
options={ [
{ value: 'true', niceLabel: this.i18n('filter.emptyProvisioning.yes') },
{ value: 'false', niceLabel: this.i18n('filter.emptyProvisioning.no') }
]}
rendered={ isArchive }/>
</Basic.Col>
</Basic.Row>
</Basic.AbstractForm>
</Advanced.Filter>
}
buttons={
[
<Basic.Button
level="danger"
key="delete-all-button"
className="btn-xs"
onClick={ this._deleteAll.bind(this) }
rendered={ showDeleteAllButton && Managers.SecurityManager.hasAnyAuthority(['PROVISIONINGOPERATION_DELETE']) && !isArchive }
title={ this.i18n('action.deleteAll.button.title') }
titlePlacement="bottom"
icon="fa:trash">
{ this.i18n('action.deleteAll.button.label') }
</Basic.Button>
]
}
_searchParameters={ this.getSearchParameters() }>
{
!showDetail
||
<Advanced.Column
property=""
header=""
className="detail-button"
cell={
({ rowIndex, data }) => (
<Advanced.DetailButton
title={this.i18n('button.detail')}
onClick={() => showDetail(data[rowIndex], isArchive)}/>
)
}/>
}
<Advanced.Column
property="resultState"
width={75}
header={this.i18n('acc:entity.ProvisioningOperation.resultState')}
face="text"
cell={
({ rowIndex, data }) => {
const entity = data[rowIndex];
return (
<Advanced.OperationResult value={ entity.result } detailLink={ !showDetail ? null : () => showDetail(data[rowIndex], isArchive) }/>
);
}
}
rendered={_.includes(columns, 'resultState')}/>
<Advanced.Column
property="created"
width={ 100 }
header={ this.i18n('acc:entity.ProvisioningOperation.created.short') }
title={ this.i18n('acc:entity.ProvisioningOperation.created.title') }
sort
face="datetime"
rendered={ _.includes(columns, 'created') }/>
<Advanced.Column
property="modified"
width={ 100 }
header={ isArchive ? this.i18n('acc:entity.ProvisioningArchive.modified.short') : this.i18n('entity.modified.short') }
title={
isArchive
?
this.i18n('acc:entity.ProvisioningArchive.modified.title')
:
this.i18n('acc:entity.ProvisioningOperation.modified.label')
}
sort
face="datetime"
rendered={ _.includes(columns, 'modified') }/>
<Advanced.Column
property="operationType"
width={ 75 }
header={ this.i18n('acc:entity.ProvisioningOperation.operationType') }
sort
face="enum"
enumClass={ ProvisioningOperationTypeEnum }
rendered={ _.includes(columns, 'operationType') }/>
<Advanced.Column
property="entityType"
width={ 75 }
header={ this.i18n('acc:entity.SystemEntity.entityType') }
sort
face="enum"
enumClass={ SystemEntityTypeEnum }
rendered={ _.includes(columns, 'entityType') } />
<Advanced.Column
property="entityIdentifier"
header={ this.i18n('acc:entity.ProvisioningOperation.entity') }
face="text"
cell={
/* eslint-disable react/no-multi-comp */
({ rowIndex, data }) => {
const entity = data[rowIndex];
//
if (!data[rowIndex]._embedded || !data[rowIndex]._embedded.entity) {
return (
<Advanced.UuidInfo value={ entity.entityIdentifier } />
);
}
//
return (
<Advanced.EntityInfo
entityType={ entity.entityType }
entityIdentifier={ entity.entityIdentifier }
entity={ entity._embedded.entity }
face="popover"
showIcon/>
);
}
}
rendered={ _.includes(columns, 'entityIdentifier') }/>
<Advanced.Column
property="system.name"
header={ this.i18n('acc:entity.System.name') }
sort
cell={
({ rowIndex, data }) => {
const entity = data[rowIndex];
return (
<Advanced.EntityInfo
entityType="system"
entityIdentifier={ entity.system }
entity={ entity._embedded.system }
face="popover"
showIcon/>
);
}
}
rendered={ _.includes(columns, 'system') } />
<Advanced.Column
property="systemEntityUid"
header={ this.i18n('acc:entity.SystemEntity.uid') }
sort
sortProperty="systemEntityUid"
face="text"
rendered={ isArchive && _.includes(columns, 'systemEntityUid') }/>
<Advanced.Column
property="_embedded.systemEntity.uid"
header={ this.i18n('acc:entity.SystemEntity.uid') }
sort
sortProperty="systemEntity"
face="text"
rendered={ !isArchive && _.includes(columns, 'systemEntityUid') }/>
<Advanced.Column
property="roleRequestId"
header={ this.i18n('acc:entity.ProvisioningOperation.roleRequestId.label') }
sort
cell={
({ rowIndex, data }) => {
const entity = data[rowIndex];
if (!entity || !entity.roleRequestId) {
return null;
}
return (
<Link
to={ `/role-requests/${ encodeURIComponent(entity.roleRequestId) }/detail` }
title={ this.i18n('acc:entity.ProvisioningOperation.roleRequestId.help') }>
<Basic.Icon value="fa:key" style={{ marginLeft: 25 }}/>
</Link>
);
}
}
rendered={ _.includes(columns, 'roleRequestId') } />
</Advanced.Table>
</Basic.Div>
);
}
}
ProvisioningOperationTable.propTypes = {
uiKey: PropTypes.string.isRequired,
manager: PropTypes.object.isRequired,
/**
* Enable row selection - checkbox in first cell
*/
showRowSelection: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
/**
* Bulk actions e.g. { value: 'activate', niceLabel: this.i18n('content.identities.action.activate.action'), action: this.onActivate.bind(this) }
*/
actions: PropTypes.arrayOf(PropTypes.object),
/**
* Detail callback
*/
showDetail: PropTypes.func,
/**
* "Hard filters"
*/
forceSearchParameters: PropTypes.object,
/**
* Rendered columns
*/
columns: PropTypes.arrayOf(PropTypes.string),
/**
* Show delete all button
*/
showDeleteAllButton: PropTypes.bool
};
ProvisioningOperationTable.defaultProps = {
showRowSelection: false,
forceSearchParameters: null,
columns: ['resultState', 'created', 'modified', 'operationType', 'entityType', 'entityIdentifier', 'system', 'systemEntityUid', 'roleRequestId'],
showDeleteAllButton: true
};
function select(state, component) {
return {
showTransactionId: Managers.ConfigurationManager.showTransactionId(state),
_searchParameters: Utils.Ui.getSearchParameters(state, component.uiKey)
};
}
export default connect(select, null, null, { forwardRef: true })(ProvisioningOperationTable);
|
src/components/app.js
|
RaulEscobarRivas/React-Redux-High-Order-Components
|
import React, { Component } from 'react';
import Header from './header';
import Content from './content';
export default class App extends Component {
render() {
return (
<div>
<Header />
<Content />
</div>
);
}
}
|
src/containers/auth/AuthenticateView.js
|
OlivierVillequey/hackathon
|
/**
* Authenticate Screen
* - Entry screen for all authentication
* - User can tap to login, forget password, signup...
*
* React Native Starter App
* https://github.com/mcnamee/react-native-starter-app
*/
import React, { Component } from 'react';
import {
View,
Image,
StyleSheet,
} from 'react-native';
import { Actions } from 'react-native-router-flux';
// Consts and Libs
import { AppStyles, AppSizes, AppColors } from '@theme/';
// Components
import { Spacer, Text, Button } from '@ui/';
/* state ===================================================================== */
const state = {
user: {
firstName: '',
lastName: '',
email: '',
nickname: '',
id: '',
}
};
/* Styles ==================================================================== */
const styles = StyleSheet.create({
background: {
backgroundColor: AppColors.brand.secondary,
height: AppSizes.screen.height,
width: AppSizes.screen.width,
},
logo: {
width: AppSizes.screen.width * 0.85,
resizeMode: 'contain',
},
whiteText: {
color: '#FFF',
},
});
/* Component ==================================================================== */
class Authenticate extends Component {
static componentName = 'Authenticate';
render = () => (
<View style={[AppStyles.containerCentered, AppStyles.container, styles.background]}>
<Image
source={require('../../images/logo.png')}
style={[styles.logo]}
/>
<View style={[AppStyles.row, AppStyles.paddingHorizontal]}>
<View style={[AppStyles.flex1]}>
<Button
title={'Login'}
icon={{ name: 'lock' }}
onPress={Actions.login}
backgroundColor={'#000000'}
/>
</View>
</View>
<Spacer size={10} />
<View style={[AppStyles.row, AppStyles.paddingHorizontal]}>
<View style={[AppStyles.flex1]}>
<Button
title={'Sign up'}
icon={{ name: 'face' }}
onPress={Actions.signUp}
backgroundColor={'#000000'}
/>
</View>
</View>
<Spacer size={15} />
<Text p style={[AppStyles.textCenterAligned, styles.blackText]}>
- or -
</Text>
<Spacer size={10} />
<View style={[AppStyles.row, AppStyles.paddingHorizontal]}>
<View style={[AppStyles.flex1]} />
<View style={[AppStyles.flex2]}>
<Button
small
title={'Skip'}
onPress={Actions.app}
raised={false}
backgroundColor={'#5a5a5a'}
/>
</View>
<View style={[AppStyles.flex1]} />
</View>
<Spacer size={40} />
</View>
)
}
/* Export Component ==================================================================== */
export default Authenticate;
|
src/svg-icons/device/signal-cellular-connected-no-internet-0-bar.js
|
pancho111203/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalCellularConnectedNoInternet0Bar = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M20 22h2v-2h-2v2zm0-12v8h2v-8h-2z"/>
</SvgIcon>
);
DeviceSignalCellularConnectedNoInternet0Bar = pure(DeviceSignalCellularConnectedNoInternet0Bar);
DeviceSignalCellularConnectedNoInternet0Bar.displayName = 'DeviceSignalCellularConnectedNoInternet0Bar';
DeviceSignalCellularConnectedNoInternet0Bar.muiName = 'SvgIcon';
export default DeviceSignalCellularConnectedNoInternet0Bar;
|
test/InputSpec.js
|
lo1tuma/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Input from '../src/Input';
import Button from '../src/Button';
import DropdownButton from '../src/DropdownButton';
import MenuItem from '../src/MenuItem';
import {shouldWarn} from './helpers';
describe('Input', function () {
it('renders children when type is not set', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input>
<span />
</Input>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'span'));
assert.throw(instance.getValue);
});
it('renders a select element when type=select', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="select" defaultValue="v">
<option value="v" />
<option value="w" />
</Input>
);
let select = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'select');
assert.ok(select);
assert.equal(React.findDOMNode(select).children.length, 2);
assert.equal(instance.getValue(), 'v');
});
it('renders a textarea element when type=textarea', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="textarea" defaultValue="v" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'textarea'));
assert.equal(instance.getValue(), 'v');
});
it('throws a deprecation warning on type=button', function () {
ReactTestUtils.renderIntoDocument(
<Input type="button" />
);
shouldWarn('deprecated');
});
it('throws a deprecation warning on type=reset', function () {
ReactTestUtils.renderIntoDocument(
<Input type="reset" />
);
shouldWarn('deprecated');
});
it('throws a deprecation warning on type=submit', function () {
ReactTestUtils.renderIntoDocument(
<Input type="submit" />
);
shouldWarn('deprecated');
});
it('throws a warning when type=static', function () {
ReactTestUtils.renderIntoDocument(
<Input type="static" value="v" />
);
shouldWarn('deprecated');
});
it('renders an input element of given type when type is anything else', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="text" defaultValue="v" />
);
let node = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'input'));
assert.equal(node.getAttribute('type'), 'text');
assert.equal(instance.getValue(), 'v');
});
it('renders form-group wrapper', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input groupClassName="group" bsStyle="error" />
);
let node = React.findDOMNode(instance);
assert.include(node.className, 'form-group');
assert.include(node.className, 'group');
assert.include(node.className, 'has-error');
});
it('renders label', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input label="Label" labelClassName="label" id="input" />
);
let node = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'label'));
assert.ok(node);
assert.include(node.className, 'label');
assert.equal(node.textContent, 'Label');
assert.equal(node.getAttribute('for'), 'input');
});
it('renders wrapper', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input wrapperClassName="wrapper" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'wrapper'));
});
it('renders input-group', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input addonBefore="$" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group-addon'));
});
it('renders form-group with sm or lg class when bsSize is small or large', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input bsSize="small" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group-sm'));
instance = ReactTestUtils.renderIntoDocument(
<Input bsSize="large" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group-lg'));
});
it('renders input-group with sm or lg class name when bsSize is small or large', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input addonBefore="$" bsSize="small" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group-sm'));
instance = ReactTestUtils.renderIntoDocument(
<Input addonBefore="$" bsSize="large" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group-lg'));
});
it('renders btn-group', function() {
let instance = ReactTestUtils.renderIntoDocument(
<Input buttonAfter={<Button>!</Button>} />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group-btn'));
});
it('renders btn-group with dropdown', function() {
let instance = ReactTestUtils.renderIntoDocument(
<Input buttonAfter={<DropdownButton title="dropdown">
<MenuItem key="1">One</MenuItem>
</DropdownButton>} />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group-btn'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'btn'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'dropdown-menu'));
});
it('renders help', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input help="Help" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'help-block'));
});
it('renders form-group class', function() {
let instance = ReactTestUtils.renderIntoDocument(
<Input />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group'));
});
it('renders no form-group class', function() {
let instance = ReactTestUtils.renderIntoDocument(
<Input standalone />
);
assert.equal(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'form-group').length, 0);
});
it('renders custom-form-group class', function() {
let instance = ReactTestUtils.renderIntoDocument(
<Input groupClassName='custom-form-class' />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'custom-form-class'));
});
it('renders feedback icon', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input hasFeedback={true} bsStyle="error" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-control-feedback'));
});
it('renders file correctly', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="file" wrapperClassName="wrapper" label="Label" help="h" />
);
let node = React.findDOMNode(instance);
assert.include(node.className, 'form-group');
assert.equal(node.children[0].tagName.toLowerCase(), 'label');
assert.include(node.children[1].className, 'wrapper');
assert.equal(node.children[1].children[0].tagName.toLowerCase(), 'input');
assert.equal(node.children[1].children[0].className, '');
assert.equal(node.children[1].children[0].type, 'file');
assert.equal(node.children[1].children[1].className, 'help-block');
});
it('renders checkbox/radio correctly', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="checkbox" wrapperClassName="wrapper" label="Label" help="h" />
);
let node = React.findDOMNode(instance);
assert.include(node.className, 'form-group');
assert.include(node.children[0].className, 'wrapper');
assert.include(node.children[0].children[0].className, 'checkbox');
assert.equal(node.children[0].children[0].children[0].tagName.toLowerCase(), 'label');
assert.equal(node.children[0].children[0].children[0].children[0].tagName.toLowerCase(), 'input');
assert.include(node.children[0].children[1].className, 'help-block');
});
it('renders non-checkbox/radio correctly', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="text" label="l" wrapperClassName="wrapper" addonAfter="a" hasFeedback={true} help="h"/>
);
let node = React.findDOMNode(instance);
assert.include(node.className, 'form-group');
assert.equal(node.children[0].tagName.toLowerCase(), 'label');
assert.include(node.children[1].className, 'wrapper');
assert.include(node.children[1].children[0].className, 'input-group');
assert.equal(node.children[1].children[0].children[0].tagName.toLowerCase(), 'input');
assert.equal(node.children[1].children[0].children[1].tagName.toLowerCase(), 'span');
assert.include(node.children[1].children[1].className, 'form-control-feedback');
assert.include(node.children[1].children[2].className, 'help-block');
});
it('returns checked value for checkbox/radio', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="checkbox" checked readOnly />
);
assert.equal(instance.getChecked(), true);
});
it('returns the only selected option for select', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="select" value={'one'}>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</Input>
);
assert.equal(instance.getValue(), 'one');
});
it('returns all selected options for multiple select', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="select" multiple value={['one', 'two']}>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</Input>
);
assert.deepEqual(instance.getValue(), ['one', 'two']);
});
it('renders a disabled input correctly', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="text" disabled={true} />
);
let node = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'input'));
assert.isNotNull(node.getAttribute('disabled'));
});
});
|
app/javascript/mastodon/containers/mastodon.js
|
salvadorpla/mastodon
|
import React from 'react';
import { Provider, connect } from 'react-redux';
import PropTypes from 'prop-types';
import configureStore from '../store/configureStore';
import { INTRODUCTION_VERSION } from '../actions/onboarding';
import { BrowserRouter, Route } from 'react-router-dom';
import { ScrollContext } from 'react-router-scroll-4';
import UI from '../features/ui';
import Introduction from '../features/introduction';
import { fetchCustomEmojis } from '../actions/custom_emojis';
import { hydrateStore } from '../actions/store';
import { connectUserStream } from '../actions/streaming';
import { IntlProvider, addLocaleData } from 'react-intl';
import { getLocale } from '../locales';
import initialState from '../initial_state';
import ErrorBoundary from '../components/error_boundary';
const { localeData, messages } = getLocale();
addLocaleData(localeData);
export const store = configureStore();
const hydrateAction = hydrateStore(initialState);
store.dispatch(hydrateAction);
store.dispatch(fetchCustomEmojis());
const mapStateToProps = state => ({
showIntroduction: state.getIn(['settings', 'introductionVersion'], 0) < INTRODUCTION_VERSION,
});
@connect(mapStateToProps)
class MastodonMount extends React.PureComponent {
static propTypes = {
showIntroduction: PropTypes.bool,
};
render () {
const { showIntroduction } = this.props;
if (showIntroduction) {
return <Introduction />;
}
return (
<BrowserRouter basename='/web'>
<ScrollContext>
<Route path='/' component={UI} />
</ScrollContext>
</BrowserRouter>
);
}
}
export default class Mastodon extends React.PureComponent {
static propTypes = {
locale: PropTypes.string.isRequired,
};
componentDidMount() {
this.disconnect = store.dispatch(connectUserStream());
}
componentWillUnmount () {
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
render () {
const { locale } = this.props;
return (
<IntlProvider locale={locale} messages={messages}>
<Provider store={store}>
<ErrorBoundary>
<MastodonMount />
</ErrorBoundary>
</Provider>
</IntlProvider>
);
}
}
|
modules/Redirect.js
|
chrisirhc/react-router
|
import React from 'react'
import invariant from 'invariant'
import { createRouteFromReactElement } from './RouteUtils'
import { formatPattern } from './PatternUtils'
import { falsy } from './PropTypes'
const { string, object } = React.PropTypes
/**
* 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.
*/
const Redirect = React.createClass({
statics: {
createRouteFromReactElement(element) {
const route = createRouteFromReactElement(element)
if (route.from)
route.path = route.from
// TODO: Handle relative pathnames, see #1658
invariant(
route.to.charAt(0) === '/',
'<Redirect to> must be an absolute path. This should be fixed in the future'
)
route.onEnter = function (nextState, replaceState) {
const { location, params } = nextState
const pathname = route.to ? formatPattern(route.to, params) : location.pathname
replaceState(
route.state || location.state,
pathname,
route.query || location.query
)
}
return route
}
},
propTypes: {
path: string,
from: string, // Alias for path
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
render() {
invariant(
false,
'<Redirect> elements are for router configuration only and should not be rendered'
)
}
})
export default Redirect
|
actor-apps/app-web/src/app/components/common/Text.react.js
|
stonegithubs/actor-platform
|
import _ from 'lodash';
import React from 'react';
import memoize from 'memoizee';
import emojify from 'emojify.js';
import hljs from 'highlight.js';
import marked from 'marked';
import emojiCharacters from 'emoji-named-characters';
emojify.setConfig({
mode: 'img',
img_dir: 'assets/img/emoji' // eslint-disable-line
});
const mdRenderer = new marked.Renderer();
// target _blank for links
mdRenderer.link = function(href, title, text) {
let external, newWindow, out;
external = /^https?:\/\/.+$/.test(href);
newWindow = external || title === 'newWindow';
out = '<a href=\"' + href + '\"';
if (newWindow) {
out += ' target="_blank"';
}
if (title && title !== 'newWindow') {
out += ' title=\"' + title + '\"';
}
return (out + '>' + text + '</a>');
};
const markedOptions = {
sanitize: true,
breaks: true,
highlight: function (code) {
return hljs.highlightAuto(code).value;
},
renderer: mdRenderer
};
const inversedEmojiCharacters = _.invert(_.mapValues(emojiCharacters, (e) => e.character));
const emojiVariants = _.map(Object.keys(inversedEmojiCharacters), function(name) {
return name.replace(/\+/g, '\\+');
});
const emojiRegexp = new RegExp('(' + emojiVariants.join('|') + ')', 'gi');
const processText = function(text) {
let markedText = marked(text, markedOptions);
// need hack with replace because of https://github.com/Ranks/emojify.js/issues/127
const noPTag = markedText.replace(/<p>/g, '<p> ');
let emojifiedText = emojify
.replace(noPTag.replace(emojiRegexp, (match) => ':' + inversedEmojiCharacters[match] + ':'));
return emojifiedText;
};
const memoizedProcessText = memoize(processText, {
length: 1000,
maxAge: 60 * 60 * 1000,
max: 10000
});
class Text extends React.Component {
static propTypes = {
content: React.PropTypes.object.isRequired,
className: React.PropTypes.string
};
constructor(props) {
super(props);
}
render() {
const { content, className } = this.props;
return (
<div className={className}
dangerouslySetInnerHTML={{__html: memoizedProcessText(content.text)}}>
</div>
);
}
}
export default Text;
|
week3/react/counter-app/src/App.js
|
jfhinchcliffe/Coderfactory_Term3_Notes
|
//import React, { Component } from 'react';
// import logo from './logo.svg';
import React from 'react';
import './App.css';
import 'whatwg-fetch'; // Polyfills window.fetch
import Counter from './components/Counter';
import fetchAPI from './api/fetchAPI';
import replaceItemWithID from './utils/replaceItemWithId';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
counters: [],
};
fetchAPI('/counters')
.then(counters => {
console.log('counters', counters);
this.setState({
counters: counters
})
})
.catch(error => {
console.error('Error loading counter API', error.message)
})
}
onChangeCount(id, change) {
fetchAPI(`/counters/${ id }`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
change: change,
})
})
.then(newCounter => {
this.setState(({ counters }) => ({
counters: replaceItemWithID(counters, id, newCounter)
}))
})
}
render() {
const {counters} = this.state;
return (
<main className="app">
{
counters.map((counter, index) => {
return (
<Counter
key={ index }
count={ counter.count }
onIncrement={ this.onChangeCount.bind(this, counter._id, 1 )}
onDecrement={ this.onChangeCount.bind(this, counter._id, -1 )}
/>
)
})
}
</main>
);
}
}
export default App;
|
app/containers/WorkSpace/index.js
|
Zurico/t7
|
/*
* WorkSpacePage
*
* This is the first thing users see of our App, at the '/' route
*/
import React from 'react';
import Helmet from 'react-helmet';
import styles from './styles.css';
import { selectWorkSpace } from './selectors';
import { connect } from 'react-redux';
import { mouseTrap } from 'react-mousetrap';
import { createStructuredSelector } from 'reselect';
import { splitPane } from './actions';
// https://github.com/primer/octicons/tree/v2.1.2
import Octicon from 'react-octicon';
import HotKeys from 'utils/hotkeys';
import WorkSpacePane from 'containers/WorkSpacePane';
class WorkSpace extends React.Component {
constructor(props, context){
super(props, context);
}
componentWillMount() {
// Subscribe to hotkeys
this.props.bindShortcut(HotKeys.SPLIT_WORKSPACE_VERTICALLY.keys, this.splitWorkSpaceVerticallyShortcut.bind(this));
}
splitWorkSpaceVerticallyShortcut(){
this.splitWorkSpaceVertically();
return HotKeys.ADD_NOTEBOOK.default;
}
splitWorkSpaceVertically(){
this.props.splitPane();
}
render(){
return (
<article className={styles.container}>
<Helmet
title="Workspace Page"
meta={[
{ name: 'description', content: 'Talo Workspace' },
]}
/>
{
this.props.workspace.panes.map((pane, num) => <WorkSpacePane key={num} id={num} pane={pane} />)
}
</article>
);
}
}
WorkSpace.propTypes = {
workspace: React.PropTypes.object
};
const mapStateToProps = createStructuredSelector({
workspace: selectWorkSpace()
});
const mapDispatchToProps = dispatch => ({
splitPane: () => dispatch(splitPane())
});
// Wrap the component to inject dispatch and state into it
export default connect(mapStateToProps, mapDispatchToProps)(mouseTrap(WorkSpace));
|
sources/views/app/index.spec.js
|
gigacool/resume-maker
|
import React from 'react';
import { shallow } from 'enzyme';
import { App } from './index';
describe('views', () => {
describe('App', () => {
beforeEach(() => {
});
function getWrapper() {
return shallow(
<App />
);
}
it('should have a `h1` component', () => {
const wrapper = getWrapper();
const appHeader = wrapper.find('h1');
expect(appHeader.length).toBe(1);
});
});
});
|
components/image/index.js
|
voylinux/voylinux.com-frontend
|
import React from 'react';
class Image extends React.Component {
render() {
return (
<img src={this.props.src} className={this.props.class} alt={this.props.alt} />
)
}
}
export default Image;
|
components/dash-core-components/src/components/LogoutButton.react.js
|
plotly/dash
|
import React from 'react';
import PropTypes from 'prop-types';
import './css/logout.css';
/**
* Logout button to submit a form post request to the `logout_url` prop.
* Usage is intended for dash-deployment-server authentication.
*
* DDS usage:
*
* `dcc.LogoutButton(logout_url=os.getenv('DASH_LOGOUT_URL'))`
*
* Custom usage:
*
* - Implement a login mechanism.
* - Create a flask route with a post method handler.
* `@app.server.route('/logout', methods=['POST'])`
* - The logout route should perform what's necessary for the user to logout.
* - If you store the session in a cookie, clear the cookie:
* `rep = flask.Response(); rep.set_cookie('session', '', expires=0)`
*
* - Create a logout button component and assign it the logout_url
* `dcc.LogoutButton(logout_url='/logout')`
*
* See https://dash.plotly.com/dash-core-components/logout_button
* for more documentation and examples.
*/
export default class LogoutButton extends React.Component {
render() {
const {id, logout_url, label, className, style, method, loading_state} =
this.props;
let url, submitMethod;
if (!logout_url) {
url =
logout_url ||
'https://dash.plotly.com/dash-core-components/logout_button';
submitMethod = 'get';
} else {
url = logout_url;
submitMethod = method;
}
return (
<form
data-dash-is-loading={
(loading_state && loading_state.is_loading) || undefined
}
action={url}
method={submitMethod}
className="dash-logout-frame"
>
<button
className={`dash-logout-btn ${className || ''}`}
style={style}
id={id}
type="submit"
>
{label}
</button>
</form>
);
}
}
LogoutButton.defaultProps = {
label: 'Logout',
method: 'post',
};
LogoutButton.propTypes = {
/**
* Id of the button.
*/
id: PropTypes.string,
/**
* Text of the button
*/
label: PropTypes.string,
/**
* Url to submit a post logout request.
*/
logout_url: PropTypes.string,
/**
* Style of the button
*/
style: PropTypes.object,
/**
* Http method to submit the logout form.
*/
method: PropTypes.string,
/**
* CSS class for the button.
*/
className: PropTypes.string,
/**
* Dash-assigned callback that gets fired when the value changes.
*/
setProps: PropTypes.func,
/**
* Object that holds the loading state object coming from dash-renderer
*/
loading_state: PropTypes.shape({
/**
* Determines if the component is loading or not
*/
is_loading: PropTypes.bool,
/**
* Holds which property is loading
*/
prop_name: PropTypes.string,
/**
* Holds the name of the component that is loading
*/
component_name: PropTypes.string,
}),
};
|
app/javascript/mastodon/features/hashtag_timeline/index.js
|
cobodo/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import ColumnSettingsContainer from './containers/column_settings_container';
import { expandHashtagTimeline, clearTimeline } from '../../actions/timelines';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import { FormattedMessage } from 'react-intl';
import { connectHashtagStream } from '../../actions/streaming';
import { isEqual } from 'lodash';
const mapStateToProps = (state, props) => ({
hasUnread: state.getIn(['timelines', `hashtag:${props.params.id}${props.params.local ? ':local' : ''}`, 'unread']) > 0,
});
export default @connect(mapStateToProps)
class HashtagTimeline extends React.PureComponent {
disconnects = [];
static propTypes = {
params: PropTypes.object.isRequired,
columnId: PropTypes.string,
dispatch: PropTypes.func.isRequired,
hasUnread: PropTypes.bool,
multiColumn: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('HASHTAG', { id: this.props.params.id }));
}
}
title = () => {
let title = [this.props.params.id];
if (this.additionalFor('any')) {
title.push(' ', <FormattedMessage key='any' id='hashtag.column_header.tag_mode.any' values={{ additional: this.additionalFor('any') }} defaultMessage='or {additional}' />);
}
if (this.additionalFor('all')) {
title.push(' ', <FormattedMessage key='all' id='hashtag.column_header.tag_mode.all' values={{ additional: this.additionalFor('all') }} defaultMessage='and {additional}' />);
}
if (this.additionalFor('none')) {
title.push(' ', <FormattedMessage key='none' id='hashtag.column_header.tag_mode.none' values={{ additional: this.additionalFor('none') }} defaultMessage='without {additional}' />);
}
return title;
}
additionalFor = (mode) => {
const { tags } = this.props.params;
if (tags && (tags[mode] || []).length > 0) {
return tags[mode].map(tag => tag.value).join('/');
} else {
return '';
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
_subscribe (dispatch, id, tags = {}, local) {
let any = (tags.any || []).map(tag => tag.value);
let all = (tags.all || []).map(tag => tag.value);
let none = (tags.none || []).map(tag => tag.value);
[id, ...any].map(tag => {
this.disconnects.push(dispatch(connectHashtagStream(id, tag, local, status => {
let tags = status.tags.map(tag => tag.name);
return all.filter(tag => tags.includes(tag)).length === all.length &&
none.filter(tag => tags.includes(tag)).length === 0;
})));
});
}
_unsubscribe () {
this.disconnects.map(disconnect => disconnect());
this.disconnects = [];
}
componentDidMount () {
const { dispatch } = this.props;
const { id, tags, local } = this.props.params;
this._subscribe(dispatch, id, tags, local);
dispatch(expandHashtagTimeline(id, { tags, local }));
}
componentWillReceiveProps (nextProps) {
const { dispatch, params } = this.props;
const { id, tags, local } = nextProps.params;
if (id !== params.id || !isEqual(tags, params.tags) || !isEqual(local, params.local)) {
this._unsubscribe();
this._subscribe(dispatch, id, tags, local);
dispatch(clearTimeline(`hashtag:${id}${local ? ':local' : ''}`));
dispatch(expandHashtagTimeline(id, { tags, local }));
}
}
componentWillUnmount () {
this._unsubscribe();
}
setRef = c => {
this.column = c;
}
handleLoadMore = maxId => {
const { id, tags, local } = this.props.params;
this.props.dispatch(expandHashtagTimeline(id, { maxId, tags, local }));
}
render () {
const { hasUnread, columnId, multiColumn } = this.props;
const { id, local } = this.props.params;
const pinned = !!columnId;
return (
<Column bindToDocument={!multiColumn} ref={this.setRef} label={`#${id}`}>
<ColumnHeader
icon='hashtag'
active={hasUnread}
title={this.title()}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
showBackButton
>
{columnId && <ColumnSettingsContainer columnId={columnId} />}
</ColumnHeader>
<StatusListContainer
trackScroll={!pinned}
scrollKey={`hashtag_timeline-${columnId}`}
timelineId={`hashtag:${id}${local ? ':local' : ''}`}
onLoadMore={this.handleLoadMore}
emptyMessage={<FormattedMessage id='empty_column.hashtag' defaultMessage='There is nothing in this hashtag yet.' />}
bindToDocument={!multiColumn}
/>
</Column>
);
}
}
|
imports/components/TabNav.js
|
tampham47/nau-jukebox
|
/* © 2017
* @author Tu Nguyen
*/
/* eslint-disable react/no-array-index-key */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Container } from 'flux/utils';
import { withTracker } from 'meteor/react-meteor-data';
import ReactGA from 'react-ga';
import AppStore from '../events/AppStore';
import UserStore from '../events/UserStore';
import AccountsUIWrapper from './AccountUIWrapper';
import { changeTab, toggleSearch } from '../events/AppActions';
class TabNav extends Component {
static propTypes = {
isSignedIn: PropTypes.bool,
};
static defaultProps = {
isSignedIn: false,
};
static getStores() {
return [AppStore, UserStore];
}
static calculateState(/*prevState*/) {
return {
errorSignIn: UserStore.getState()['errorSignIn'],
toggleBtnNav: AppStore.getState()['toggleBtnNav'],
tabIndex: AppStore.getState()['tabIndex'],
};
}
state = {
navbarIsShown: false,
};
componentDidUpdate(prevProps, prevState) {
if (prevState.tabIndex !== this.state.tabIndex) {
ReactGA.event({
category: 'Navigation',
action: 'Switched tab',
label: this.tabList[this.state.tabIndex],
});
}
}
onTabClick = e => {
const index = parseInt(e.currentTarget.dataset.index, 10);
changeTab(index);
if (this.state.navbarIsShown) {
this.toggleNavbar();
}
};
tabList = ['Play List', 'Yesterday', 'Last 7 day', 'Top Lists', 'Users', 'My Bookings'];
_renderTabNav = () => {
const lst = this.tabList.map((item, index) => {
const listItem = (
<li
key={index}
data-index={index}
className={`tab__nav__list-item ${this.state.tabIndex === index ? 'tab__nav__list-item--active' : ''}`}
onClick={this.onTabClick}
>
<a href="#">{item}</a>
</li>
);
if (index !== 5) {
return listItem;
} else if (this.props.isSignedIn) {
return listItem;
}
return '';
});
return lst;
};
toggleNavbar = () => {
this.setState({
navbarIsShown: !this.state.navbarIsShown,
});
};
render() {
return (
<nav className="tab__nav noselect">
<div className="container tab__nav__container tab__nav--mobile-no-pd">
<ul className={`tab__nav__playlist ${this.state.navbarIsShown ? 'tab__nav__playlist--active' : ''}`}>
{this._renderTabNav()}
</ul>
<div className="tab__nav__login-outter login-block">
<AccountsUIWrapper />
<div className="tab__nav__buttons-wrapper">
<i
className="fa fa-search tab__nav__search nau--hidden-md nau--hidden-lg"
aria-hidden="true"
onClick={toggleSearch}
/>
<button
className={`tab__nav__button tab__collapse nau--hidden-md nau--hidden-lg`}
onClick={this.toggleNavbar}
>
<i className="fa fa-bars tab__nav__icon" aria-hidden="true" />
</button>
</div>
{this.state.errorSignIn && !this.props.isSignedIn ? (
<div className="login-block__error">
<p>Please login first!</p>
</div>
) : null}
</div>
</div>
</nav>
);
}
}
export default withTracker(() => ({
isSignedIn: !!Meteor.userId(),
}))(Container.create(TabNav));
|
src/client/now/components/phone-number-input.js
|
michigan-com/nova
|
'use strict';
import React from 'react';
import { findDOMNode } from 'react-dom';
import xr from 'xr';
import Store from '../store';
import { showInput, dismissInput, hideInputForever, expandInput } from '../actions/phone-number';
import { getTopArticleStyle } from './top-article';
export default class PhoneNumberInput extends React.Component {
constructor(props) {
super(props);
this.state = {
error: '',
sendingMessage: false,
messageSent: false,
phoneNumber: ''
}
}
componentDidMount() {
if (this.shouldShowInput) {
//setTimeout(() => { Store.dispatch(showInput()); }, 2500);
Store.dispatch(showInput());
}
}
componentDidUpdate(lastProps, lastState) {
if (this.props.expandInput && !lastProps.expandInput) {
findDOMNode(this.refs['phone-number']).focus();
}
}
submitNumber(e) {
e.preventDefault();
e.stopPropagation();
if (!this.props.expandInput) {
return Store.dispatch(expandInput());
}
let _csrf = document.getElementById('_csrf').value;
let phoneNumber = this.state.phoneNumber;
if (phoneNumber.length != 10) {
return this.setState({ error: 'Please include area code and phone number (10 numbers total)' })
} else if (isNaN(phoneNumber)) {
return this.setState({ error: 'Only numbers, please' });
}
this.setState({
error: '',
sendingMessage: true
});
xr.post('/text-mobile-link/', { phoneNumber, _csrf }).then(
(resp) => {
this.setState({
error: '',
sendingMessage: false,
messageSent: true,
});
setTimeout(() => { Store.dispatch(hideInputForever()); }, 2000);
},
(err) => {
let resp = JSON.parse(err.response);
this.setState({
error: resp.error
});
}
)
}
checkKeyValue(e) {
let keyCode = e.which || e.keyCode;
if (keyCode === 13) return;
e.stopPropagation();
e.preventDefault();
if ((keyCode > 57 || keyCode < 48) && keyCode !== 8) {
this.setState(this.state);
return;
}
let newState = { ...this.state }
let newVal = String.fromCharCode(keyCode);
let oldNumber = this.state.phoneNumber
if (keyCode == 8) {
newState.phoneNumber = oldNumber.slice(0, oldNumber.length - 1)
} else if (oldNumber.length < 10) {
newState.phoneNumber += newVal;
}
this.setState(newState);
}
dismissInput() {
Store.dispatch(dismissInput());
}
hideForever(e) {
e.preventDefault();
e.stopPropagation();
Store.dispatch(hideInputForever());
}
renderContent() {
let content = null;
let submitClass = 'submit';
let submitValue = 'Text Me';
if (!this.props.expandInput) submitValue = 'Sure!';
if (this.state.sendingMessage) {
submitClass += ' disabled';
submitValue = 'Texting...'
} else if (this.state.messageSent) {
submitClass += ' disabled';
submitValue = 'Sent!';
}
if (this.props.expandInput) {
let phoneNumberInputClass = 'phone-number-input';
if (this.state.error) phoneNumberInputClass += ' error';
content = (
<input type='text'
ref='phone-number'
className={ phoneNumberInputClass }
placeholder='3135550123'
value={ this.state.phoneNumber }
onKeyDown={ this.checkKeyValue.bind(this) }/>
);
} else {
content = (
<p className='blurb'>We tailored this experience for mobile phones. Can we text you a link?</p>
);
}
let formContentClass = 'form-content';
if (this.props.expandInput) formContentClass += ' expand';
let style = {};
style.animationDelay = `${this.props.rank * 50}ms`;
return (
<div className='phone-number-input-content' style={ style }>
<form onSubmit={ this.submitNumber.bind(this) }>
<div className={ formContentClass }>
<div className='errors'>{ this.state.error || ' '}</div>
{ content }
<p className='blurb'>We will never spam or share your number.</p>
</div>
<div className='form-submit'>
<input type='submit' className={ submitClass } value={ submitValue } onClick={ this.submitNumber.bind(this) }/>
</div>
</form>
</div>
)
}
render() {
let className = 'phone-number-input-container';
let style = getTopArticleStyle(this.props.rank);
if (this.props.expandInput) style.height *= 2;
return (
<div className={ className } style={ style }>
{ this.renderContent() }
</div>
)
}
}
|
src/views/ChannelForm/index.js
|
chad-ding/koala
|
/**
*@Author: chad.ding
*@Copyright: 2017-2018 DMF
*@Date: 2017-05-18 16:22:05
*/
import React, { Component } from 'react';
import { Form, Input, Switch, Button, Checkbox, Select, Radio, Slider, InputNumber, Breadcrumb, Icon } from 'antd';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import SelectInput from '../../components/SelectInput';
import RangeInput from '../../components/RangeInput';
import './style.less';
@connect(state => ({
...state.ChannelFormReducer
}))
@Form.create()
export default class ChannelForm extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.checkFlow = this.checkFlow.bind(this);
}
handleSubmit = async(e) => {
e.preventDefault();
let invalid = false;
await this.props.form.validateFields((err, values) => {
if (!err) {
invalid = true;
}
});
if (invalid) {
console.log('form is invalid');
return;
}
}
checkFlow(rule, value, callback) {
if (value.number > 0) {
callback();
return;
}
callback('总流量预估必须大于0!');
}
render() {
let FormItem = Form.Item;
let { getFieldDecorator } = this.props.form;
let { Option, OptGroup } = Select;
let RadioGroup = Radio.Group;
let formItemLayout = {
labelCol: {
xs: { span: 14 },
sm: { span: 6 }
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 }
}
};
let tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0
},
sm: {
span: 14,
offset: 6
}
}
};
let marks = {
1: {
style: {
color: '#f50'
},
label: <strong>1KB</strong>
},
900: {
style: {
color: '#f50'
},
label: <strong>900KB</strong>
}
};
let unitMap = [
{ value: '1', text: 'QPS(请求/秒)' },
{ value: '2', text: 'QPM(请求/分)' },
{ value: '3', text: 'QPH(请求/小时)' },
{ value: '4', text: 'QPD(请求/天)' }
];
return (
<div className="container">
<Breadcrumb>
<Breadcrumb.Item>
<Icon type="home" />
</Breadcrumb.Item>
<Breadcrumb.Item>
<span>
<Link to="/application/list">接入申请</Link>
</span>
</Breadcrumb.Item>
<Breadcrumb.Item>
申请频道
</Breadcrumb.Item>
</Breadcrumb>
<br/><br/>
<Form onSubmit={this.handleSubmit}>
<FormItem {...formItemLayout} label="频道名称" hasFeedback>
{getFieldDecorator('channelName', {
rules: [{
type: 'string', message: '输入不合法!',
pattern: /^channel.\w+/
}, {
required: true, message: '请输入频道名称!'
}]
})(
<Input placeholder="必须以channel开头,包含数字,字母,'_'和'.',如channel.cfg_2d" />
)}
</FormItem>
<FormItem {...formItemLayout} label="区间" hasFeedback>
{getFieldDecorator('range', {
rules: [{
required: true, message: '请输入区间范围!'
}, {
validator: function(rule, value, callback){
if (value.min <= value.max) {
callback();
return;
}
callback('请输入正确的数据范围');
}
}],
initialValue: {min: 5, max: 340}
})(
<RangeInput unit="msg/s"></RangeInput>
)}
</FormItem>
<FormItem {...formItemLayout} label="存储引擎" hasFeedback>
{getFieldDecorator('cluster', {
rules: [{
required: true, message: '请选择存储引擎!'
}],
initialValue: '消息堆积(Kafka)'
})(
<Select>
<Option value="消息堆积(Kafka)">消息堆积(Kafka)</Option>
<Option value="任务事件(RabbitMQ)">任务事件(RabbitMQ)</Option>
</Select>
)}
</FormItem>
<FormItem {...formItemLayout} label="路由策略" hasFeedback>
{getFieldDecorator('mode', {
rules: [{
type: 'string', message: '输入不合法!'
}, {
required: true, message: '请输入环境名称!'
}],
initialValue: 'direct'
})(
<RadioGroup>
<Radio value="direct">direct</Radio>
<Radio value="topic">topic</Radio>
</RadioGroup>
)}
</FormItem>
<FormItem {...formItemLayout} label="是否分片" hasFeedback>
{getFieldDecorator('sharding', {
rules: [{
required: true, message: '请选择是否分片!'
}],
valuePropName: 'checked',
initialValue: false
})(
<Switch checkedChildren={'是'} unCheckedChildren={'否'} />
)}
</FormItem>
<FormItem {...formItemLayout} label="项目名称" hasFeedback>
{getFieldDecorator('project', {
rules: [{
type: 'string', message: '输入不合法!'
}, {
required: true, message: '请输入项目名称名称!'
}]
})(
<Input />
)}
</FormItem>
<FormItem {...formItemLayout} label="App ID" hasFeedback>
{getFieldDecorator('appId', {
rules: [{
type: 'string', message: '输入不合法!'
}, {
required: true, message: '请输入App ID!'
}]
})(
<Input />
)}
</FormItem>
<FormItem {...formItemLayout} label="用途" hasFeedback>
{getFieldDecorator('purpose', {
rules: [{
required: true, message: '请选择用途!'
}],
initialValue: '1'
})(
<Select>
<OptGroup label="线上">
<Option value="1">数据统计</Option>
<Option value="2">数据同步</Option>
<Option value="3">任务处理</Option>
<Option value="4">事件广播</Option>
</OptGroup>
</Select>
)}
</FormItem>
<FormItem {...formItemLayout} label="存活时间" hasFeedback>
{getFieldDecorator('liveTime', {
rules: [{
required: true, message: '请选择存活时间!'
}],
initialValue: '1'
})(
<Select>
<Option value="1">1天</Option>
<Option value="2">5天</Option>
<Option value="3">1周</Option>
<Option value="4">2周</Option>
<Option value="5">1月</Option>
<Option value="6">半年</Option>
<Option value="7">1年</Option>
<Option value="8">永久</Option>
</Select>
)}
</FormItem>
<FormItem {...formItemLayout} label="开发语言" hasFeedback>
{getFieldDecorator('language', {
valuePropName: 'checked'
})(
<div>
<Checkbox>Java</Checkbox>
<Checkbox>PHP</Checkbox>
<Checkbox>C++</Checkbox>
</div>
)}
</FormItem>
<FormItem {...formItemLayout} label="消息体预估" hasFeedback>
{getFieldDecorator('message', {
initialValue: [1, 500]
})(
<Slider marks={marks} range min={1} max={900} />
)}
</FormItem>
<FormItem {...formItemLayout} label="应用规划数" hasFeedback>
{getFieldDecorator('program', {
rules: [{
type: 'number', message: '只能输入数字!'
},{
required: true, message: '请输入应用规划数!'
}],
initialValue: 30
})(
<InputNumber min={1} max={10} className="full-width" />
)}
</FormItem>
<FormItem {...formItemLayout} label="总流量预估" hasFeedback>
{getFieldDecorator('flow', {
rules: [{
required: true, message: '请输入总流量预估'
},{
validator: this.checkFlow
}],
initialValue: { number: 1, unit: '1' }
})(
<SelectInput unitMap={unitMap}></SelectInput>
)}
</FormItem>
<FormItem {...formItemLayout} label="用途说明" hasFeedback>
{getFieldDecorator('useage', {
rules: [{
required: true, message: '请输入用途说明'
}]
})(
<Input type="textarea" rows={10}></Input>
)}
</FormItem>
<FormItem {...tailFormItemLayout}>
<Link to="/application/list">
<Button type="default" htmlType="button" size="large">取消</Button>
</Link>
<Button type="primary" htmlType="submit" size="large">保存</Button>
</FormItem>
</Form>
</div>
);
}
};
|
sms_sponsorship/webapp/src/App.js
|
eicher31/compassion-modules
|
import React from 'react';
import TopAppBar from './components/TopAppBar';
import ChildCard from './components/ChildCard';
import { translate } from 'react-i18next';
import i18n from './i18n';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import CenteredLoading from './components/CenteredLoading';
import jsonRPC from './components/jsonRPC';
import getRequestId from './components/getRequestId';
import Message from './components/Message';
import SuccessMessage from './components/SuccessMessage';
import Button from "@material-ui/core/Button";
const theme = createMuiTheme({
palette: {
primary: {
main: '#0054A6'
},
},
overrides: {
// Name of the component ⚛️ / style sheet
MuiTypography: {
// Name of the rule
headline: {
color: '#555555'
},
title: {
color: '#555555'
}
},
MuiCardHeader: {
title: {
textAlign: 'center',
fontSize: '30px',
// textTransform: 'uppercase'
}
},
MuiSnackbarContent: {
root: {
backgroundColor: "darkred"
}
}
},
});
window.pageLoaded = false;
window.getChildTimeout = false;
class Main extends React.Component {
state = {
child: false,
partner: false,
success: false,
langDialog: false,
langChanged: false,
};
count_try = 0;
parseResult = (res) => {
let child;
try {
child = JSON.parse(res.responseText).result
}
catch(e) {
child = false;
}
return child;
};
getChild = (forceLang) => {
let data = {};
if (forceLang || this.state.langChanged) {
data.lang = i18n.language
}
let requestId = getRequestId();
if (!requestId) {
return;
}
let url = "/sms_sponsorship/step1/" + requestId + "/get_child_data";
jsonRPC(url, data, (res) => {
let child = this.parseResult(res);
let partner = (typeof(child.partner) === 'undefined') ? false:child.partner[0];
this.setState({
child: child,
partner: partner,
});
// Set the language as the request
i18n.changeLanguage(child.lang);
});
};
changeChild = () => {
let requestId = getRequestId();
let lang = i18n.language;
let url = "/sms_sponsorship/step1/" + requestId + "/change_child";
let form = document.forms.other_child_form;
let data = {
gender: form.gender.value,
age: form.age.value,
country: form.country.value,
lang: lang,
};
this.setState({
child: {
'has_a_child': true,
'loading_other_child': true
},
dialogOpen: false
});
jsonRPC(url, data, (res) => {
this.getChild();
});
};
changeLanguage = () => {
let form = document.forms.lang_form;
let lang = form.lang.value;
i18n.changeLanguage(lang);
this.setState({
langDialog: false,
langChanged: true,
});
this.getChild(lang);
};
componentDidMount() {
if (!window.pageLoaded) {
window.pageLoaded = true;
this.getChild();
}
}
reload() {
window.location.reload();
}
redirectToWebsite(url) {
window.location.href = url;
}
render() {
const { t } = this.props;
document.title = t("cardTitle");
let image_url = '';
let child = this.state.child;
if (child && child.image_url) {
image_url = child.image_url.replace('/w_150', '').replace('media.ci.org/', 'media.ci.org/g_face,c_thumb,w_150,h_150,r_max/');
}
let topAppBar = <TopAppBar title="Compassion" t={t} appContext={this}/>;
if (!getRequestId()) {
return (
<div>
{topAppBar}
<div>
<Message text={t("error_noRequestID")}/>
</div>
</div>
)
}
if (!child.has_a_child && !this.state.success && !child.sponsorship_confirmed && !child.invalid_sms_child_request) {
clearTimeout(window.getChildTimeout);
if(this.count_try > 40){
return (
<div>
{topAppBar}
<Message text={t("error_noService")} style={{marginBottom: '20px'}}/>
<div style={{textAlign: 'center', marginTop: '20px'}}>
<Button variant="contained"
onClick={this.reload}
color="primary"
size="medium"
>
{t("error_refresh")}
</Button>
<br/>
<br/>
<Button variant="outlined"
onClick={() => this.redirectToWebsite(t('error_websiteUrl'))}
color="primary"
size="medium"
>
{t("error_sponsorFromWebsite")}
</Button>
</div>
</div>
)
}else{
window.getChildTimeout = setTimeout(() => {
this.getChild();
}, 1000);
++this.count_try;
}
}
return (
<MuiThemeProvider theme={theme}>
<div>
{topAppBar}
{this.state.success ? (
<SuccessMessage preferred_name={this.state.success.preferred_name}
gender={this.state.success.gender}
image_url={this.state.success.image_url.replace('/w_150', '').replace('media.ci.org/', 'media.ci.org/g_face,c_thumb,w_150,h_150,r_max/')} t={t}
/>
):(
<div>
{child ? (
<div>
{child.sponsorship_confirmed ? (
<div>
<Message text={t('error_sponsorshipAlreadyMade')}/>
</div>
):(
<div>
{!child.invalid_sms_child_request ? (
<div>
{!child.loading_other_child ? (
<div>
{child.has_a_child ? (
<ChildCard centered
name={child.name}
preferredName={child.preferred_name}
country={child.country}
age={child.age + ' ' + t('ageYears')}
gender={child.gender === 'M' ? 'Male':'Female'}
image_url={image_url}
appContext={this}
t={t}
/>
):(
<CenteredLoading text={t("waitingForChild")}/>
)}
</div>
):(
<div>
<CenteredLoading text={t("waitingForOtherChild")}/>
</div>
)}
</div>
):(
<div>
<Message text={t("error_noRequestID")}/>
</div>
)}
</div>
)}
</div>
):(
<div>
<CenteredLoading text={t("waitingForChild")}/>
</div>
)}
</div>
)}
</div>
</MuiThemeProvider>
)
}
}
// extended main view with translate hoc
export default translate('translations')(Main);
|
client/src/components/CountryDetails.js
|
mandrive/CountriesApp
|
import React from 'react';
import cssmodules from 'react-css-modules';
import styles from './styles/countrydetails.cssmodule.scss';
@cssmodules(styles)
class CountryDetails extends React.Component {
render() {
var countryDetails = this.props.selectedCountry && this.props.selectedCountry.Id
? (<div className="card">
<div className="card-block">
<h2>Country name: {this.props.selectedCountry.Name}</h2>
<h4>Capital name: {this.props.selectedCountry.Capital.Name}</h4>
</div>
</div>)
: (<h3>Select a country from list on the left</h3>)
return (
<div className="countrydetails-component">
{countryDetails}
</div>
);
}
}
export default CountryDetails;
|
dynamic/react/api-models/index.js
|
balasuar/developer-dot
|
import 'babel-polyfill';
import Model from './model';
import React from 'react';
import {render} from 'react-dom';
const model = window.PAGE_MODEL;
const name = window.MODEL_NAME;
render(<Model m={model} name={name} />, document.getElementById('react-root'));
|
front/src/components/App.js
|
litleleprikon/ds_chat
|
import React from 'react';
import Header from './header/Header';
import Body from './body/Body';
const App = () => (
<div className="App">
<Header/>
<Body/>
</div>
);
export default App;
|
app/javascript/mastodon/containers/status_container.js
|
summoners-riftodon/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import Status from '../components/status';
import { makeGetStatus } from '../selectors';
import {
replyCompose,
mentionCompose,
directCompose,
} from '../actions/compose';
import {
reblog,
favourite,
unreblog,
unfavourite,
pin,
unpin,
} from '../actions/interactions';
import { blockAccount } from '../actions/accounts';
import {
muteStatus,
unmuteStatus,
deleteStatus,
hideStatus,
revealStatus,
} from '../actions/statuses';
import { initMuteModal } from '../actions/mutes';
import { initReport } from '../actions/reports';
import { openModal } from '../actions/modal';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { boostModal, deleteModal } from '../initial_state';
import { showAlertForError } from '../actions/alerts';
const messages = defineMessages({
deleteConfirm: { id: 'confirmations.delete.confirm', defaultMessage: 'Delete' },
deleteMessage: { id: 'confirmations.delete.message', defaultMessage: 'Are you sure you want to delete this status?' },
redraftConfirm: { id: 'confirmations.redraft.confirm', defaultMessage: 'Delete & redraft' },
redraftMessage: { id: 'confirmations.redraft.message', defaultMessage: 'Are you sure you want to delete this status and re-draft it? Favourites and boosts will be lost, and replies to the original post will be orphaned.' },
blockConfirm: { id: 'confirmations.block.confirm', defaultMessage: 'Block' },
});
const makeMapStateToProps = () => {
const getStatus = makeGetStatus();
const mapStateToProps = (state, props) => ({
status: getStatus(state, props),
});
return mapStateToProps;
};
const mapDispatchToProps = (dispatch, { intl }) => ({
onReply (status, router) {
dispatch(replyCompose(status, router));
},
onModalReblog (status) {
dispatch(reblog(status));
},
onReblog (status, e) {
if (status.get('reblogged')) {
dispatch(unreblog(status));
} else {
if (e.shiftKey || !boostModal) {
this.onModalReblog(status);
} else {
dispatch(openModal('BOOST', { status, onReblog: this.onModalReblog }));
}
}
},
onFavourite (status) {
if (status.get('favourited')) {
dispatch(unfavourite(status));
} else {
dispatch(favourite(status));
}
},
onPin (status) {
if (status.get('pinned')) {
dispatch(unpin(status));
} else {
dispatch(pin(status));
}
},
onEmbed (status) {
dispatch(openModal('EMBED', {
url: status.get('url'),
onError: error => dispatch(showAlertForError(error)),
}));
},
onDelete (status, history, withRedraft = false) {
if (!deleteModal) {
dispatch(deleteStatus(status.get('id'), history, withRedraft));
} else {
dispatch(openModal('CONFIRM', {
message: intl.formatMessage(withRedraft ? messages.redraftMessage : messages.deleteMessage),
confirm: intl.formatMessage(withRedraft ? messages.redraftConfirm : messages.deleteConfirm),
onConfirm: () => dispatch(deleteStatus(status.get('id'), history, withRedraft)),
}));
}
},
onDirect (account, router) {
dispatch(directCompose(account, router));
},
onMention (account, router) {
dispatch(mentionCompose(account, router));
},
onOpenMedia (media, index) {
dispatch(openModal('MEDIA', { media, index }));
},
onOpenVideo (media, time) {
dispatch(openModal('VIDEO', { media, time }));
},
onBlock (account) {
dispatch(openModal('CONFIRM', {
message: <FormattedMessage id='confirmations.block.message' defaultMessage='Are you sure you want to block {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />,
confirm: intl.formatMessage(messages.blockConfirm),
onConfirm: () => dispatch(blockAccount(account.get('id'))),
}));
},
onReport (status) {
dispatch(initReport(status.get('account'), status));
},
onMute (account) {
dispatch(initMuteModal(account));
},
onMuteConversation (status) {
if (status.get('muted')) {
dispatch(unmuteStatus(status.get('id')));
} else {
dispatch(muteStatus(status.get('id')));
}
},
onToggleHidden (status) {
if (status.get('hidden')) {
dispatch(revealStatus(status.get('id')));
} else {
dispatch(hideStatus(status.get('id')));
}
},
});
export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Status));
|
src/js/pages/ProfessionalProfileIndustryPage.js
|
nekuno/client
|
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import connectToStores from '../utils/connectToStores';
import translate from '../i18n/Translate';
import LoginActionCreators from '../actions/LoginActionCreators';
import LocaleStore from '../stores/LocaleStore';
import ProfileStore from '../stores/ProfileStore';
import RegisterStore from '../stores/RegisterStore';
import InputSelectText from '../components/RegisterFields/InputSelectText/InputSelectText.js';
import StepsBar from '../components/ui/StepsBar/StepsBar.js';
import TopNavBar from '../components/TopNavBar/TopNavBar.js';
import * as UserActionCreators from '../actions/UserActionCreators';
import '../../scss/pages/professional-profile-industry.scss';
function requestData(props) {
if (!props.metadata) {
UserActionCreators.requestMetadata();
}
}
function getState() {
const interfaceLanguage = LocaleStore.locale;
const metadata = ProfileStore.getMetadata();
const choices = metadata && metadata.industry ? metadata.industry.choices : [];
const user = RegisterStore.user;
const username = user && user.username ? user.username : null;
const profile = RegisterStore.profile;
return {
interfaceLanguage,
choices,
profile,
username
};
}
@translate('ProfessionalProfileIndustryPage')
@connectToStores([LocaleStore, ProfileStore, RegisterStore], getState)
export default class ProfessionalProfileIndustryPage extends Component {
static propTypes = {
// Injected by @translate:
strings : PropTypes.object,
// Injected by @connectToStores:
choices : PropTypes.array,
profile : PropTypes.object,
username : PropTypes.string,
interfaceLanguage: PropTypes.string
};
static contextTypes = {
router: PropTypes.object.isRequired
};
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.goToProfessionalProfileSkillsPage = this.goToProfessionalProfileSkillsPage.bind(this);
}
componentDidMount() {
if (!this.props.username) {
this.context.router.push('/answer-username');
}
requestData(this.props);
}
goToProfessionalProfileSkillsPage() {
this.context.router.push('/professional-profile-skills');
}
onChange(choices) {
const {profile} = this.props;
LoginActionCreators.preRegisterProfile({...profile, ...{industry: choices}});
}
render() {
const {choices, profile, strings} = this.props;
const canContinue = profile && profile.industry && profile.industry.length > 0;
return (
<div className="views">
<div className="view view-main professional-profile-industry-view">
<TopNavBar iconLeft={'arrow-left'} textCenter={strings.workAndIdeas} textSize={'small'}/>
<div className="professional-profile-industry-wrapper">
<h2>{strings.title}</h2>
<InputSelectText options={choices}
placeholder={strings.searchIndustry}
searchIcon={true}
size={'small'}
chipsColor={'blue'}
onClickHandler={this.onChange}
selectedLabel={strings.selected}/>
</div>
</div>
<StepsBar color={'blue'} canContinue={canContinue} cantContinueText={strings.addIndustry} continueText={strings.continue} currentStep={0} totalSteps={2} onClickHandler={this.goToProfessionalProfileSkillsPage}/>
</div>
);
}
}
ProfessionalProfileIndustryPage.defaultProps = {
strings: {
workAndIdeas : 'Work, Ideas & Projects',
title : 'What are your professional industry?',
selected : 'Your professional industries',
searchIndustry: 'Search industry (e.g. Internet)',
addIndustry : 'Add an industry to continue',
continue : 'Continue'
}
};
|
app/main.js
|
laynemcnish/walksafely-react
|
import 'babel/register';
import React from 'react';
import Root from './containers';
import $ from 'jquery';
if(__DEV__) {
const devAjaxDebug = require('./util/dev_ajax_debug');
devAjaxDebug.initializeAjaxDebuggingUtils();
}
function renderReactApp () {
const mountPoint = document.getElementById('root');
React.render(<Root />, mountPoint);
}
$(document).ready(renderReactApp);
|
Paths/React/05.Building Scalable React Apps/8-react-boilerplate-building-scalable-apps-m8-exercise-files/Before/app/containers/LoginContainer/index.js
|
phiratio/Pluralsight-materials
|
/*
*
* LoginContainer
*
*/
import React from 'react';
import { connect } from 'react-redux';
import selectLoginContainer from './selectors';
import Login from '../../components/Login';
import { login, cancelLogin } from './actions';
export class LoginContainer extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<div>
<Login {...this.props} />
</div>
);
}
}
const mapStateToProps = selectLoginContainer();
function mapDispatchToProps(dispatch) {
return {
login: (email) => dispatch(login(email)),
cancelLogin: () => dispatch(cancelLogin()),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(LoginContainer);
|
examples/DemoRotation.js
|
MrCheater/text-resize-and-word-wrap-provider
|
import React from 'react';
import { Text, textResizeAndWordWrap } from '../src';
import { randomContent } from './randomContent';
import Slider from 'rc-slider';
import 'rc-slider/assets/index.css';
@textResizeAndWordWrap
export class DemoRotation extends React.Component {
state = {
rotation : 0,
rotationCenterX : 0.5,
rotationCenterY : 0.5
};
updateRotation = (rotation) => this.setState({
rotation
});
updateRotationCenterX = (rotationCenterX) => this.setState({
rotationCenterX
});
updateRotationCenterY = (rotationCenterY) => this.setState({
rotationCenterY
});
render() {
const size = Math.min(this.props.width, this.props.height) / 3;
return (
<div>
<svg
width = {`${this.props.width}px`}
height = {`${this.props.height}px`}
>
<rect
width = {`${this.props.width}px`}
height = {`${this.props.height}px`}
fill = {this.props.backgroundColor}
/>
<circle
fill = 'red'
r = '5px'
cx = {size + size * this.state.rotationCenterX}
cy = {size + size * this.state.rotationCenterY}
/>
<Text
x = {size}
y = {size}
width = {size}
height = {size}
rotation = {this.state.rotation}
rotationCenterX = {this.state.rotationCenterX}
rotationCenterY = {this.state.rotationCenterY}
debugMode
>
{randomContent.longText}
</Text>
</svg>
<div>
<div>
Rotation
<Slider
min = {0}
max = {360}
step = {1}
value = {this.state.rotation}
onChange = {this.updateRotation}
/>
</div>
<div>
Rotation Center X
<Slider
min = {0}
max = {1}
step = {0.05}
value = {this.state.rotationCenterX}
onChange = {this.updateRotationCenterX}
/>
</div>
<div>
Rotation Center Y
<Slider
min = {0}
max = {1}
step = {0.05}
value = {this.state.rotationCenterY}
onChange = {this.updateRotationCenterY}
/>
</div>
</div>
</div>
);
}
}
DemoRotation.defaultProps = {
width: 480,
height: 480,
backgroundColor: '#DDDDDD',
};
|
EEG101/src/components/WhiteButton.js
|
tmcneely/eeg-101
|
// WhiteButton.js
// A duplicate Button component for the early connector slides that is white instead of blue
import React, { Component } from 'react';
import {
Text,
View,
TouchableOpacity,
StyleSheet,
} from 'react-native';
import * as colors from "../styles/colors";
export default class WhiteButton extends Component{
constructor(props){
super(props);
}
render() {
const dynamicStyle = (this.props.disabled) ? styles.disabled: styles.active;
return(
<TouchableOpacity onPress={this.props.onPress} disabled={this.props.disabled}>
<View style={dynamicStyle}>
<Text style={{color: colors.skyBlue, fontFamily: 'Roboto-Bold', fontSize: 15}}>{this.props.children}</Text>
</View>
</TouchableOpacity>
)
}
};
const styles = StyleSheet.create({
active: {
justifyContent: 'center',
backgroundColor: colors.white,
height: 50,
margin: 5,
padding: 5,
alignItems: 'center',
elevation: 2,
borderRadius: 4,
},
disabled: {
justifyContent: 'center',
backgroundColor: colors.faintBlue,
height: 50,
margin: 5,
padding: 5,
alignItems: 'center',
borderRadius: 4,
}
});
|
client/channel/components/NotificationStatus.js
|
Sing-Li/Rocket.Chat
|
import React from 'react';
import { Box } from '@rocket.chat/fuselage';
export function NotificationStatus({ t = (e) => e, label, ...props }) {
return <Box width='x8' aria-label={t(label)} borderRadius='full' height='x8' {...props} />;
}
export function All(props) {
return <NotificationStatus label='mention-all' bg='#F38C39' {...props} />;
}
export function Me(props) {
return <NotificationStatus label='Me' bg='danger-500' {...props} />;
}
export function Unread(props) {
return <NotificationStatus label='Unread' bg='primary-500' {...props} />;
}
|
src/components/views/allot-user-list-view.js
|
HuangXingBin/goldenEast
|
import React from 'react';
import { Table, Button, Popconfirm } from 'antd';
import weiGuDong from '../../appConstants/assets/images/微股东.png';
import normalCard from '../../appConstants/assets/images/普卡.png';
import silverCard from '../../appConstants/assets/images/银卡.png';
import goldenCard from '../../appConstants/assets/images/金卡.png';
import superGoldenCard from '../../appConstants/assets/images/白金卡.png';
import { Link } from 'react-router';
// In the fifth row, other columns are merged into first column
// by setting it's colSpan to be 0
const UserListTable = React.createClass({
jinLevels() {
return ['注册用户(0%)', weiGuDong, normalCard, silverCard, goldenCard, superGoldenCard];
},
getColumns(){
const jinLevels = this.jinLevels();
const columns = [{
title: '姓名',
dataIndex: 'user_name',
key : 'user_name',
render(text, row, index) {
var firstName = !row.wechat_avatar ? text.slice(0,1) : '';
return (
<div className="user-avatar-bar">
<span className="user-avatar" style={{backgroundImage:'url('+ row.wechat_avatar +')'}}>
{firstName}
</span>
<div className="user-avatar-bar-text">
<p className="name">{text}</p>
{/*<span>微信昵称</span>*/}
</div>
</div>
);
},
}, {
title: '级别',
dataIndex: 'level',
key : 'level',
render(text) {
// console.log(text);
if(text == '0'){
return <span>{jinLevels[text]}</span>
} else {
return <img src={jinLevels[text]}/>
}
}
}, {
title: '手机号',
dataIndex: 'cellphone',
key : 'cellphone'
}, {
title: '邀请人',
render: function(text, record, index){
const inv_user_name = record.inviting.user_name;
return (
<div>
{inv_user_name}
</div>
)
},
key:'inviting_people',
}, {
title: '邀请人手机',
render: function(text, record, index){
const inv_cellphone = record.inviting.cellphone;
return (
<div>
{inv_cellphone}
</div>
)
},
ket:'user_id',
}, {
title: '注册时间',
dataIndex: 'register_date',
key : 'register_date'
}, {
title: '操作',
render : function(text, record, index) {
return (
<div>
<Link style={{color : 'white'}} to={`/author_user_list/set_authorization/${record.user_sn}`}>
<Button type="primary" size="small" icon="setting">分配权限</Button>
</Link>
</div>
)
}.bind(this),
}];
return columns;
},
onChange(page){
this.props.onPageChange(page)
},
render(){
const columns = this.getColumns();
const data = this.props.data;
console.log('data8', data)
const pagination = {
defaultPageSize : 12,
onChange : this.onChange,
total : this.props.total,
current : parseInt(this.props.currentPage)
};
return(
<Table pagination={pagination} size="middle" columns={columns} dataSource={this.props.data} bordered />
)
}
});
export default UserListTable;
|
src/app.js
|
AnastasiaJS/myTask-demo
|
/**
* Created by SWSD on 2016-12-26.
*/
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import configureStore from './redux/configureStore';
// 引入Ant-Design样式 & Animate.CSS样式
import 'antd/dist/antd.min.css'
import App from './containers/App'
const store = configureStore();
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
src/svg-icons/hardware/cast-connected.js
|
tan-jerene/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareCastConnected = (props) => (
<SvgIcon {...props}>
<path d="M1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm18-7H5v1.63c3.96 1.28 7.09 4.41 8.37 8.37H19V7zM1 10v2c4.97 0 9 4.03 9 9h2c0-6.08-4.93-11-11-11zm20-7H3c-1.1 0-2 .9-2 2v3h2V5h18v14h-7v2h7c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/>
</SvgIcon>
);
HardwareCastConnected = pure(HardwareCastConnected);
HardwareCastConnected.displayName = 'HardwareCastConnected';
HardwareCastConnected.muiName = 'SvgIcon';
export default HardwareCastConnected;
|
src/client/scripts/client.js
|
uttrasey/wt-namegame
|
import React from 'react';
import ReactDOM from 'react-dom';
import config from '../../../config/app';
import Game from '../../game';
var gameNode = document.getElementById('game');
ReactDOM.render(<Game url={config.apiUrl} roundCount={config.roundCount} />, gameNode);
|
docs/src/pages/demos/chips/ChipsArray.js
|
cherniavskii/material-ui
|
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Avatar from 'material-ui/Avatar';
import Chip from 'material-ui/Chip';
import Paper from 'material-ui/Paper';
import TagFacesIcon from '@material-ui/icons/TagFaces';
const styles = theme => ({
root: {
display: 'flex',
justifyContent: 'center',
flexWrap: 'wrap',
padding: theme.spacing.unit / 2,
},
chip: {
margin: theme.spacing.unit / 2,
},
});
class ChipsArray extends React.Component {
state = {
chipData: [
{ key: 0, label: 'Angular' },
{ key: 1, label: 'jQuery' },
{ key: 2, label: 'Polymer' },
{ key: 3, label: 'React' },
{ key: 4, label: 'Vue.js' },
],
};
handleDelete = data => () => {
if (data.label === 'React') {
alert('Why would you want to delete React?! :)'); // eslint-disable-line no-alert
return;
}
const chipData = [...this.state.chipData];
const chipToDelete = chipData.indexOf(data);
chipData.splice(chipToDelete, 1);
this.setState({ chipData });
};
render() {
const { classes } = this.props;
return (
<Paper className={classes.root}>
{this.state.chipData.map(data => {
let avatar = null;
if (data.label === 'React') {
avatar = (
<Avatar>
<TagFacesIcon className={classes.svgIcon} />
</Avatar>
);
}
return (
<Chip
key={data.key}
avatar={avatar}
label={data.label}
onDelete={this.handleDelete(data)}
className={classes.chip}
/>
);
})}
</Paper>
);
}
}
ChipsArray.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(ChipsArray);
|
node_modules/enzyme/src/version.js
|
jotamaggi/react-calendar-app
|
import React from 'react';
export const VERSION = React.version;
const [major, minor] = VERSION.split('.');
export const REACT013 = VERSION.slice(0, 4) === '0.13';
export const REACT014 = VERSION.slice(0, 4) === '0.14';
export const REACT15 = major === '15';
export const REACT155 = REACT15 && minor >= 5;
|
src/common/components/repository-row/dropdowns/edit-config-dropdown.js
|
canonical-websites/build.snapcraft.io
|
import PropTypes from 'prop-types';
import React from 'react';
import { Row, Data, Dropdown } from '../../vanilla/table-interactive';
import getTemplateUrl from './template-url.js';
const EditConfigDropdown = ({ snap }) => {
const templateUrl = getTemplateUrl(snap);
return (
<Dropdown>
<Row>
<Data col="100">
<p>
This repo has a snapcraft.yaml file.{' '}
<a href={ templateUrl } target="_blank" rel="noreferrer noopener">
You can edit the file on GitHub.
</a>
</p>
</Data>
</Row>
</Dropdown>
);
};
EditConfigDropdown.propTypes = {
snap: PropTypes.shape({
gitRepoUrl: PropTypes.string,
gitBranch: PropTypes.string,
snapcraftData: PropTypes.shape({
path: PropTypes.string
})
})
};
export default EditConfigDropdown;
|
inlineStyles/src/components/Example/Example.js
|
3mundi/React-Bible
|
import React from 'react';
import styles from './styles';
class Example extends React.Component {
render() {
return (
<p style={styles.announcement}>{this.props.content}</p>
);
}
}
Example.propTypes = {
content: React.PropTypes.string.isRequired
};
export default Example;
|
js/src/views/Signer/signer.js
|
immartian/musicoin
|
// 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 { Actionbar } from '~/ui';
import RequestsPage from './containers/RequestsPage';
export default class Signer extends Component {
render () {
return (
<div>
<Actionbar title='Trusted Signer' />
<RequestsPage />
</div>
);
}
}
|
__sites_/src/index.js
|
Vanthink-UED/react-core-image-upload
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app';
require('./less/vtui.less');
ReactDOM.render(<App />, document.getElementById('app'));
|
Jest/Enzyme/public/components/About/__tests__/About.spec.js
|
hugonasciutti/Exercises
|
import React from 'react';
import { shallow, mount } from 'enzyme';
import toJson from 'enzyme-to-json';
import About from '../index';
describe('<About />', () => {
it('should render <About /> component', () => {
const component = shallow(<About />);
const tree = toJson(component);
expect(tree).toMatchSnapshot();
});
it('should delete item from array', () => {
const component = mount(<About />);
let tree = toJson(component);
const items = component.find('.item');
expect(tree).toMatchSnapshot();
items.at(2).simulate('click');
tree = toJson(component);
expect(tree).toMatchSnapshot();
});
});
|
lib/components/modification/__tests__/list.js
|
conveyal/scenario-editor
|
// @flow
import renderer from 'react-test-renderer'
import React from 'react'
import {Provider} from 'react-redux'
import ModificationsList from '../list'
import {
makeMockStore,
mockProject,
mockStores
} from '../../../utils/mock-data.js'
const mockStore = makeMockStore(mockStores.init)
describe('Component > Modification > ModificationsList', () => {
it('renders correctly', () => {
const props = {
modifications: [],
project: mockProject,
projectId: mockProject._id,
regionId: mockProject.regionId,
createModification: jest.fn(),
push: jest.fn(),
updateModification: jest.fn()
}
const tree = renderer
.create(
<Provider store={mockStore}>
<ModificationsList {...props} />
</Provider>
)
.toJSON()
expect(tree).toMatchSnapshot()
const noCalls = ['createModification', 'updateModification']
noCalls.forEach(fn => {
expect(props[fn]).not.toBeCalled()
})
})
})
|
src-rx/src/components/JsonConfigComponent/ConfigImageUpload.js
|
ioBroker/ioBroker.admin
|
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import InputLabel from '@material-ui/core/InputLabel';
import FormHelperText from '@material-ui/core/FormHelperText';
import FormControl from '@material-ui/core/FormControl';
import ConfigGeneric from './ConfigGeneric';
import UploadImage from '../UploadImage';
const styles = theme => ({
fullWidth: {
width: '100%'
},
image: {
width: 100
}
});
class ConfigCertificateSelect extends ConfigGeneric {
constructor(props) {
super(props);
this.imageRef = React.createRef();
this.index = Date.now();
}
async componentDidMount() {
super.componentDidMount();
if (this.props.schema.base64) {
const value = ConfigGeneric.getValue(this.props.data, this.props.attr);
this.setState({ value });
} else {
this.props.socket.fileExists(this.props.adapterName + '.' + this.props.instance, this.props.attr)
.then(exist => {
if (exist && this.imageRef.current) {
this.imageRef.current.src = this._getUrl();
this.imageRef.current.style.display = 'block';
}
});
}
}
_getUrl(update) {
if (update) {
this.index = Date.now();
}
let url = `files/${this.props.adapterName}.${this.props.instance}/${this.props.attr}?t=${this.index}`;
if (window.location.port === '3000') {
url = window.location.protocol + '//' + window.location.hostname + ':8081/' + url;
}
return url;
}
renderItem(error, disabled, defaultValue) {
// eslint-disable-next-line
return <FormControl className={this.props.classes.fullWidth}>
<InputLabel shrink>{this.getText(this.props.schema.label)}</InputLabel>
<UploadImage
error={!!error}
disabled={disabled}
accept={this.props.schema.accept}
crop={this.props.schema.crop}
maxSize={this.props.schema.maxSize || 256 * 1024}
icon={this.state.value || undefined}
removeIconFunc={() => {
if (this.props.schema.base64) {
this.setState({ value: null }, () =>
this.onChange(this.props.attr, this.state.value));
} else {
// delete file to /instance/attr
this.props.socket.deleteFile(this.props.adapterName + '.' + this.props.instance, this.props.attr);
// update image
if (this.imageRef.current) {
this.imageRef.current.style.display = 'none';
this.imageRef.current.src = '';
}
}
}}
onChange={base64 => {
if (this.props.schema.base64) {
this.setState({ value: base64 }, () =>
this.onChange(this.props.attr, this.state.value));
} else {
if (base64.startsWith('data')) {
base64 = base64.split(',')[1];
}
// upload file to /instance/attr
this.props.socket.writeFile64(this.props.adapterName + '.' + this.props.instance, this.props.attr, base64)
.then(() => {
if (this.imageRef.current) {
this.imageRef.current.style.display = 'block';
this.imageRef.current.src = this._getUrl(true);
}
});
}
}}
t={this.props.t}
/>
{this.props.schema.help ? <FormHelperText>{this.renderHelp(this.props.schema.help, this.props.schema.helpLink, this.props.schema.noTranslation)}</FormHelperText> : null}
{this.props.schema.base64 ? null : <img
src={this._getUrl()}
ref={this.imageRef}
className={this.props.classes.image}
style={{display: 'none'}}
alt="Background"
/>}
</FormControl>;
}
}
ConfigCertificateSelect.propTypes = {
socket: PropTypes.object.isRequired,
themeType: PropTypes.string,
themeName: PropTypes.string,
style: PropTypes.object,
className: PropTypes.string,
data: PropTypes.object.isRequired,
schema: PropTypes.object,
onError: PropTypes.func,
onChange: PropTypes.func,
};
export default withStyles(styles)(ConfigCertificateSelect);
|
src/views/ContractBusiness/Guarantee/ExamineGuarantee.js
|
bruceli1986/contract-react
|
import React from 'react'
import PageHeader from 'components/PageHeader'
import GuaranteeBasicInfo from 'components/GuaranteeBasicInfo'
import FileListTable from 'components/FileListTable'
import TaskHandleForm from 'components/TaskHandleForm'
import TaskHistory from 'components/TaskHistory'
import formatter from 'utils/formatter.js'
class ExamGuarantee extends React.Component {
constructor (props, context) {
super(props, context)
this.state = {
guaranteeInfo: null,
validStatus: false,
associateFile: [],
loadAssociateFile: false,
history: [],
loadHistory: false,
examining: false,
outGoing: []
}
}
componentDidMount () {
this.fetchGuaranteeInfo()
this.fetchAssociateFile()
this.fetchOutGoing()
this.fetchTaskHistory()
}
vaildateForm () {
this.setState({validStatus: true})
return true
}
// 提交质保金申请
submitForm () {
if (this.vaildateForm()) {
$.ajax({
cache: true,
type: this.refs.form.method,
url: this.refs.form.action,
data: $(this.refs.form).serialize(),
async: true,
success: function (data) {
if (data === true) {
swal({
title: '质保金申请成功!',
text: '点击回到合同列表!',
type: 'success',
showCancelButton: false,
confirmButtonColor: '#428bca',
confirmButtonText: '确认',
closeOnConfirm: true},
function (isConfirm) {
if (isConfirm) {
location.href = '/contract/view'
}
})
} else {
swal({
title: '质保金申请失败!',
text: '点击回到待办事项!',
type: 'error',
showCancelButton: false,
confirmButtonColor: '#428bca',
confirmButtonText: '确认',
closeOnConfirm: true},
function (isConfirm) {
if (isConfirm) {
location.href = '/contract/view'
}
})
}
}
})
}
}
examineGuarantee = (user, comment) => {
var title = user.userName ? formatter.formatString('确定交给{0}处理?', user.userName) : '确定处理质保金?'
var component = this
swal({
title: title,
text: formatter.formatString('处理意见:{0}', comment),
type: 'warning',
showCancelButton: true,
confirmButtonText: '确认',
cancelButtonText: '取消'
}, function () {
component.setState({
examining: true
})
component.refs.taskHandleForm.submitForm()
})
}
redirect = (result) => {
this.setState({
examining: false
})
if (result === true) {
swal({
title: '审批成功!',
text: '点击回到待办事项!',
type: 'success',
showCancelButton: false,
confirmButtonColor: '#428bca',
confirmButtonText: '确认',
closeOnConfirm: true},
function (isConfirm) {
if (isConfirm) {
location.href = '/taskManage/todoTask'
}
})
} else {
swal({
title: '审批失败!',
text: '点击回到待办事项!',
type: 'error',
showCancelButton: false,
confirmButtonColor: '#428bca',
confirmButtonText: '确认',
closeOnConfirm: true},
function (isConfirm) {
if (isConfirm) {
location.href = '/taskManage/todoTask'
}
})
}
}
fetchGuaranteeInfo () {
var businessId = this.props.location.query.businessId
var param = businessId.split('||')
var systemCode = param[0]
var poNo = param[1]
this.serverRequest = $.get('/qdp/payment/guarantee/info', {systemCode: systemCode, poNo: poNo}, function (result) {
this.setState({
guaranteeInfo: result
})
}.bind(this))
}
fetchAssociateFile () {
this.setState({
loadAssociateFile: false
})
this.serverRequest = $.get('/qdp/payment/file/associate', this.props.location.query, function (result) {
this.setState({
associateFile: result,
loadAssociateFile: true
})
}.bind(this))
}
fetchOutGoing () {
this.serverRequest = $.get('/qdp/payment/bpm/task/outUsers', this.props.location.query, function (result) {
this.setState({
outGoing: result
})
}.bind(this))
}
fetchTaskHistory () {
this.setState({
loadHistory: false
})
this.serverRequest = $.get('/qdp/payment/bpm/task/history', this.props.location.query, function (result) {
this.setState({
history: result,
loadHistory: true
})
}.bind(this))
}
render () {
return (
<div className='container'>
<div className='row'>
<div className='col-md-12'>
<PageHeader title='质保金审签流程' subTitle='审批质保金' />
</div>
</div>
<div className='row'>
<div className='col-md-12'>
<h3 className='form-section-header'>1.质保金详细信息</h3>
<GuaranteeBasicInfo guarantee={this.state.guaranteeInfo} />
</div>
</div>
<div className='row'>
<div className='col-md-12'>
<h3 className='form-section-header'>2.上传附件</h3>
<FileListTable files={this.state.associateFile} loaded={this.state.loadAssociateFile} deletable={false} />
</div>
</div>
<div className='row'>
<div className='col-md-12'>
<h3 className='form-section-header'>3.流转历史</h3>
<TaskHistory history={this.state.history} loaded={this.state.loadHistory} />
</div>
</div>
<div className='row'>
<div className='col-md-12'>
<TaskHandleForm ref='taskHandleForm' {... this.props.location.query} showOutGoing
outGoing={this.state.outGoing} onSubmit={this.examineGuarantee}
AfterSubmit={this.redirect} />
</div>
</div>
</div>
)
}
}
export default ExamGuarantee
|
webui/pages/help.js
|
stiftungswo/izivi_relaunch
|
import React from 'react';
import { Container } from 'semantic-ui-react';
import App from '../components/AppContainer';
export default ({ ...rest }) => (
<App {...rest}>
<Container>
<h1>1. Titel</h1>
<h2>1.1 Subtitel</h2>
<p>
Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa
qui officia deserunt mollit anim id est laborum.
</p>
<h2>1.2 Subtitel</h2>
<p>
Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa
qui officia deserunt mollit anim id est laborum.
</p>
<h1>2. Titel</h1>
<h2>2.1 Subtitel</h2>
<p>
Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa
qui officia deserunt mollit anim id est laborum.
</p>
<h2>2.2 Subtitel</h2>
<p>
Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa
qui officia deserunt mollit anim id est laborum.
</p>
</Container>
</App>
);
|
src/svg-icons/notification/live-tv.js
|
barakmitz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationLiveTv = (props) => (
<SvgIcon {...props}>
<path d="M21 6h-7.59l3.29-3.29L16 2l-4 4-4-4-.71.71L10.59 6H3c-1.1 0-2 .89-2 2v12c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.11-.9-2-2-2zm0 14H3V8h18v12zM9 10v8l7-4z"/>
</SvgIcon>
);
NotificationLiveTv = pure(NotificationLiveTv);
NotificationLiveTv.displayName = 'NotificationLiveTv';
NotificationLiveTv.muiName = 'SvgIcon';
export default NotificationLiveTv;
|
src/components/async-img.js
|
jjmulenex/sdk
|
import React from 'react';
import PropTypes from 'prop-types';
import fetch from 'isomorphic-fetch';
/**
* WARNING! This class uses a "mounted" member of state
* which react recommends against. Changing that would make the
* code a lot messier and this solution is otherwise a clean way
* to get protected images.
*/
export default class AsyncImage extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
mounted: false,
};
}
updateData() {
if (this.props.async) {
fetch(this.props.src, this.props.fetchOptions)
.then(r => r.blob())
.then((imgData) => {
if (this.state.mounted) {
this.setState({data: URL.createObjectURL(imgData)});
}
})
.catch((error) => {
console.error('Error fetchimg image at:', this.props.src);
this.props.onError(error);
});
}
}
componentDidMount() {
this.setState({mounted: true});
this.updateData();
}
componentWillUnmount() {
this.setState({mounted: false});
}
componentDidUpdate(prevProps) {
if (this.props.async && this.props.src !== prevProps.src) {
this.updateData();
}
}
render() {
const props = {};
const copy_props = ['height', 'width', 'src', 'onClick', 'alt', 'className'];
for (let prop of copy_props) {
if (this.props[prop]) {
props[prop] = this.props[prop];
}
}
if (this.props.async) {
props.src = this.state.data;
}
// it is necessary to ensure an alt tag for a11y,
// and the prop version needs to be deleted to ensure no
// duplicate props for the img tag.
const alt = this.props.alt ? this.props.alt : '';
return (
<img alt={alt} {...props} />
);
}
}
AsyncImage.propTypes = {
/** Do we need to fetch the image asynchronous? */
async: PropTypes.bool,
/** Options to use for fetch calls */
fetchOptions: PropTypes.object,
/** onError callback */
onError: PropTypes.func,
/** onCLick callback */
onClick: PropTypes.func,
/** Width in pixels */
width: PropTypes.number,
/** Height in pixels */
height: PropTypes.number,
/** Source attribute */
src: PropTypes.string,
/** Alt text */
alt: PropTypes.string,
/** CSS class name */
className: PropTypes.string,
};
|
Docker/KlusterKiteMonitoring/klusterkite-web/src/components/NodesList/NodesList.js
|
KlusterKite/KlusterKite
|
import React from 'react';
import Relay from 'react-relay'
import delay from 'lodash/delay'
import { Popover, OverlayTrigger, Button } from 'react-bootstrap';
import Icon from 'react-fa';
import UpgradeNodeMutation from './mutations/UpgradeNodeMutation';
import './styles.css';
export class NodesList extends React.Component {
constructor(props) {
super(props);
this.nodePopover = this.nodePopover.bind(this);
this.state = {
upgradingNodes: []
};
}
static propTypes = {
nodeDescriptions: React.PropTypes.object,
hasError: React.PropTypes.bool.isRequired,
upgradeNodePrivilege: React.PropTypes.bool.isRequired,
testMode: React.PropTypes.bool,
hideDetails: React.PropTypes.bool,
};
drawRole(node, role) {
const isLeader = node.leaderInRoles.indexOf(role) >= 0;
return (<span key={`${node.NodeId}/${role}`}>
{isLeader && <span className="label label-info" title={`${role} leader`}>{role}</span>}
{!isLeader && <span className="label label-default">{role}</span>}
{' '}
</span>);
}
nodePopover(node) {
return (
<Popover title={`${node.nodeTemplate}`} id={`${node.nodeId}`}>
{node.modules.edges.map((subModuleEdge) => {
const subModuleNode = subModuleEdge.node;
return (
<span key={`${subModuleNode.id}`}>
<span className="label label-default">{subModuleNode.__id} {subModuleNode.version}</span>{' '}
</span>
);
})
}
</Popover>
);
}
onManualUpgrade(nodeAddress, nodeId) {
if (this.props.testMode) {
this.showUpgrading(nodeId);
this.hideUpgradingAfterDelay(nodeId);
} else {
Relay.Store.commitUpdate(
new UpgradeNodeMutation({address: nodeAddress}),
{
onSuccess: (response) => {
const result = response.klusterKiteNodeApi_klusterKiteNodesApi_upgradeNode.result && response.klusterKiteNodeApi_klusterKiteNodesApi_upgradeNode.result.result;
if (result) {
this.showUpgrading(nodeId);
this.hideUpgradingAfterDelay(nodeId);
} else {
this.showErrorMessage();
this.hideErrorMessageAfterDelay();
}
},
onFailure: (transaction) => console.log(transaction),
},
)
}
}
showUpgrading(nodeId) {
this.setState((prevState, props) => ({
upgradingNodes: [...prevState.upgradingNodes, nodeId]
}));
}
hideUpgrading(nodeId) {
this.setState(function(prevState, props) {
const index = prevState.upgradingNodes.indexOf(nodeId);
return {
upgradingNodes: [
...prevState.upgradingNodes.slice(0, index),
...prevState.upgradingNodes.slice(index + 1)
]
};
});
}
hideUpgradingAfterDelay(nodeId) {
delay(() => this.hideUpgrading(nodeId), 20000);
}
/**
* Shows reloading packages message
*/
showErrorMessage = () => {
this.setState({
isError: true
});
};
/**
* Hides reloading packages message after delay
*/
hideErrorMessageAfterDelay = () => {
delay(() => this.hideErrorMessage(), 5000);
};
/**
* Hides reloading packages message
*/
hideErrorMessage = () => {
this.setState({
isError: false
});
};
render() {
if (!this.props.nodeDescriptions.getActiveNodeDescriptions){
return (<div></div>);
}
let { hasError } = this.props;
if (this.state.isError) {
hasError = true;
}
const edges = this.props.nodeDescriptions.getActiveNodeDescriptions.edges;
return (
<div>
<h3>Nodes list</h3>
{hasError &&
<div className="alert alert-danger" role="alert">
<span className="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span> Could not connect to the server</span>
</div>
}
<table className="table table-hover">
<thead>
<tr>
<th>Leader</th>
<th>Address</th>
<th>Template</th>
<th>Container</th>
{!this.props.hideDetails &&
<th>Modules</th>
}
{!this.props.hideDetails &&
<th>Roles</th>
}
<th>Status</th>
</tr>
</thead>
<tbody>
{edges && edges.map((edge) => {
const node = edge.node;
const isUpdating = this.state.upgradingNodes.indexOf(node.nodeId) !== -1;
const reloadClassName = isUpdating ? 'fa fa-refresh fa-spin' : 'fa fa-refresh';
return (
<tr key={`${node.nodeId}`}>
<td>{node.isClusterLeader ? <i className="fa fa-check-circle" aria-hidden="true"></i> : ''}</td>
<td>{node.nodeAddress.host}:{node.nodeAddress.port}</td>
<td>
{node.nodeTemplate}
</td>
<td>
{node.containerType}
</td>
{!this.props.hideDetails &&
<td>
{node.isInitialized &&
<OverlayTrigger trigger="click" rootClose placement="bottom" overlay={this.nodePopover(node)}>
<Button className="btn-info btn-xs">
<Icon name="search"/>
</Button>
</OverlayTrigger>
}
</td>
}
{!this.props.hideDetails &&
<td>
{node.roles.map((role) => this.drawRole(node, role))}
</td>
}
{node.isInitialized &&
<td>
<span className="label">{node.isInitialized}</span>
{this.props.upgradeNodePrivilege &&
<span>
{!node.isObsolete &&
<button
disabled={isUpdating}
type="button" className="upgrade btn btn-xs btn-success"
title="Upgrade Node"
onClick={() => this.onManualUpgrade(node.nodeAddress.asString, node.nodeId)}>
<i className={reloadClassName} /> Actual
</button>
}
{node.isObsolete &&
<button
disabled={isUpdating}
type="button" className="upgrade btn btn-xs btn-warning"
title="Upgrade Node"
onClick={() => this.onManualUpgrade(node.nodeAddress.asString, node.nodeId)}>
<i className={reloadClassName} /> Obsolete
</button>
}
</span>
}
{!this.props.upgradeNodePrivilege &&
<span>
{!node.isObsolete &&
<span className="label label-success">Actual</span>
}
{node.isObsolete &&
<span className="label label-warning">Obsolete</span>
}
</span>
}
</td>
}
{!node.isInitialized &&
<td>
<span className="label label-info">Uncontrolled</span>
</td>
}
</tr>
)
})
}
</tbody>
</table>
</div>
);
}
}
export default Relay.createContainer(
NodesList,
{
fragments: {
nodeDescriptions: () => Relay.QL`fragment on IKlusterKiteNodeApi_Root {
getActiveNodeDescriptions
{
edges {
node {
containerType,
isClusterLeader,
isObsolete,
isInitialized,
leaderInRoles,
nodeId,
nodeTemplate,
roles,
startTimeStamp,
nodeAddress {
host,
port,
asString,
},
modules {
edges {
node {
id,
__id,
version,
}
}
},
}
}
}
}
`,
},
},
)
|
app/javascript/mastodon/features/compose/components/navigation_bar.js
|
danhunsaker/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ActionBar from './action_bar';
import Avatar from '../../../components/avatar';
import Permalink from '../../../components/permalink';
import IconButton from '../../../components/icon_button';
import { FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
export default class NavigationBar extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
onLogout: PropTypes.func.isRequired,
onClose: PropTypes.func,
};
render () {
return (
<div className='navigation-bar'>
<Permalink href={this.props.account.get('url')} to={`/accounts/${this.props.account.get('id')}`}>
<span style={{ display: 'none' }}>{this.props.account.get('acct')}</span>
<Avatar account={this.props.account} size={48} />
</Permalink>
<div className='navigation-bar__profile'>
<Permalink href={this.props.account.get('url')} to={`/accounts/${this.props.account.get('id')}`}>
<strong className='navigation-bar__profile-account'>@{this.props.account.get('acct')}</strong>
</Permalink>
<a href='/settings/profile' className='navigation-bar__profile-edit'><FormattedMessage id='navigation_bar.edit_profile' defaultMessage='Edit profile' /></a>
</div>
<div className='navigation-bar__actions'>
<IconButton className='close' title='' icon='close' onClick={this.props.onClose} />
<ActionBar account={this.props.account} onLogout={this.props.onLogout} />
</div>
</div>
);
}
}
|
test/MediaRightSpec.js
|
mmarcant/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import ReactDOM from 'react-dom';
import Media from '../src/Media';
describe('Media.Right', () => {
it('uses "div"', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Media.Right />
);
assert.equal(ReactDOM.findDOMNode(instance).nodeName, 'DIV');
});
it('has "media-right" class', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Media.Right />
);
assert.ok(ReactDOM.findDOMNode(instance).className.match(/\bmedia-right\b/));
});
it('should be able to change alignment to middle', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Media.Right align="middle" />
);
assert.ok(ReactDOM.findDOMNode(instance).className.match(/\bmedia-middle\b/));
});
it('should be able to change alignment to bottom', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Media.Right align="bottom" />
);
assert.ok(ReactDOM.findDOMNode(instance).className.match(/\bmedia-bottom\b/));
});
it('should merge additional classes passed in', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Media.Right className="custom-class" />
);
assert.include(ReactDOM.findDOMNode(instance).className, 'media-right');
assert.include(ReactDOM.findDOMNode(instance).className, 'custom-class');
});
it('should render children', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Media.Right>
<img />
</Media.Right>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'img'));
});
});
|
admin/src/containers/views/tests/pageedit.spec.js
|
mparlak/mparlak.github.io
|
import React from 'react';
import { Link } from 'react-router';
import { shallow } from 'enzyme';
import expect from 'expect';
import { PageEdit } from '../PageEdit';
import Errors from '../../../components/Errors';
import Button from '../../../components/Button';
import { page } from './fixtures';
const defaultProps = {
page: page,
errors: [],
fieldChanged: false,
updated: false,
isFetching: false,
router: {},
route: {},
params: { splat: [null, "page", "md"] }
};
const setup = (props = defaultProps) => {
const actions = {
fetchPage: expect.createSpy(),
putPage: expect.createSpy(),
deletePage: expect.createSpy(),
updateTitle: expect.createSpy(),
updateBody: expect.createSpy(),
updatePath: expect.createSpy(),
updateDraft: expect.createSpy(),
clearErrors: expect.createSpy()
};
const component = shallow(<PageEdit {...actions} {...props} />);
return {
component,
actions,
saveButton: component.find(Button).first(),
deleteButton: component.find(Button).last(),
errors: component.find(Errors),
props
};
};
describe('Containers::PageEdit', () => {
it('should render correctly', () => {
let { component } = setup(Object.assign(
{}, defaultProps, { isFetching: true }
));
component = setup(Object.assign(
{}, defaultProps, { page: {} }
)).component;
expect(component.find('h1').node).toExist();
});
it('should not render error messages initially', () => {
const { errors } = setup();
expect(errors.node).toNotExist();
});
it('should render error messages', () => {
const { errors } = setup(Object.assign({}, defaultProps, {
errors: ['The title field is required!']
}));
expect(errors.node).toExist();
});
it('should not call putPage if a field is not changed.', () => {
const { saveButton, actions } = setup();
saveButton.simulate('click');
expect(actions.putPage).toNotHaveBeenCalled();
});
it('should call putPage if a field is changed.', () => {
const { saveButton, actions } = setup(Object.assign({}, defaultProps, {
fieldChanged: true
}));
saveButton.simulate('click');
expect(actions.putPage).toHaveBeenCalled();
});
it('should call deletePage', () => {
const { deleteButton, actions } = setup();
deleteButton.simulate('click');
expect(actions.deletePage).toNotHaveBeenCalled(); // TODO pass prompt
});
});
|
src/components/Loader/Loader.js
|
tyleriguchi/photoshop-battles
|
import React from 'react'
import classes from './Loader.scss'
export const Loader = (props) => {
return (
<div className={classes['loading-div']}>
<i className='fa fa-refresh fa-spin fa-4x'></i>
</div>
)
}
export default Loader
|
docs/src/app/components/pages/components/SelectField/ExampleSimple.js
|
skarnecki/material-ui
|
import React from 'react';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
const styles = {
customWidth: {
width: 150,
},
};
export default class SelectFieldExampleSimple extends React.Component {
constructor(props) {
super(props);
this.state = {value: 1};
}
handleChange = (event, index, value) => this.setState({value});
render() {
return (
<div>
<SelectField value={this.state.value} onChange={this.handleChange}>
<MenuItem value={1} primaryText="Never" />
<MenuItem value={2} primaryText="Every Night" />
<MenuItem value={3} primaryText="Weeknights" />
<MenuItem value={4} primaryText="Weekends" />
<MenuItem value={5} primaryText="Weekly" />
</SelectField>
<br />
<SelectField value={1} disabled={true}>
<MenuItem value={1} primaryText="Disabled" />
<MenuItem value={2} primaryText="Every Night" />
</SelectField>
<br />
<SelectField
value={this.state.value}
onChange={this.handleChange}
style={styles.customWidth}
>
<MenuItem value={1} primaryText="Custom width" />
<MenuItem value={2} primaryText="Every Night" />
<MenuItem value={3} primaryText="Weeknights" />
<MenuItem value={4} primaryText="Weekends" />
<MenuItem value={5} primaryText="Weekly" />
</SelectField>
<br />
<SelectField
value={this.state.value}
onChange={this.handleChange}
autoWidth={true}
>
<MenuItem value={1} primaryText="Auto width" />
<MenuItem value={2} primaryText="Every Night" />
<MenuItem value={3} primaryText="Weeknights" />
<MenuItem value={4} primaryText="Weekends" />
<MenuItem value={5} primaryText="Weekly" />
</SelectField>
</div>
);
}
}
|
app/utils/markdown.js
|
rapicastillo/beautifulrising-client
|
import React from 'react';
import { Link } from 'react-router';
export function RouterLink(props) {
return (
props.href.match(/^(https?:)?\/\//)
? <a href={props.href} target={'_blank'}>{props.children}</a>
: <Link to={props.href}>{props.children}</Link>
);
}
|
modern_react_with_redux/test/test_helper.js
|
Mad-Labs/open-lab
|
import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
test/specs/elements/Rail/Rail-test.js
|
ben174/Semantic-UI-React
|
import React from 'react'
import * as common from 'test/specs/commonTests'
import Rail from 'src/elements/Rail/Rail'
const requiredProps = { position: 'left' }
describe('Rail', () => {
common.isConformant(Rail, { requiredProps })
common.hasUIClassName(Rail, { requiredProps })
common.rendersChildren(Rail, { requiredProps })
common.propKeyOnlyToClassName(Rail, 'attached', { requiredProps })
common.propKeyOnlyToClassName(Rail, 'dividing', { requiredProps })
common.propKeyOnlyToClassName(Rail, 'internal', { requiredProps })
common.propKeyOrValueAndKeyToClassName(Rail, 'close', { requiredProps })
common.propValueOnlyToClassName(Rail, 'position', { requiredProps })
common.propValueOnlyToClassName(Rail, 'size', { requiredProps })
it('renders an div element', () => {
shallow(<Rail position='left' />)
.should.have.tagName('div')
})
})
|
app/components/Operation/index.js
|
Princess310/antd-demo
|
/*
* Overwrite the component from antd Modal.operation
*
*/
/* tslint:disable:no-unused-variable */
import React from 'react';
/* tslint:enable:no-unused-variable */
import ReactDOM from 'react-dom';
import { Modal } from 'antd-mobile';
export default function a(...args) {
const actions = args[0] || [{ text: '确定' }];
const resProps = args[1];
const prefixCls = 'am-modal';
let div = document.createElement('div');
document.body.appendChild(div);
function close() {
ReactDOM.unmountComponentAtNode(div);
if (div && div.parentNode) {
div.parentNode.removeChild(div);
}
}
const footer = actions.map((button) => {
const orginPress = button.onPress || function() {};
button.onPress = () => {
const res = orginPress();
if (res && res.then) {
res.then(() => {
close();
});
} else {
close();
}
};
return button;
});
ReactDOM.render(
<Modal
visible
operation
transparent
prefixCls={prefixCls}
transitionName="am-zoom"
closable={false}
maskClosable
onClose={close}
footer={footer}
{...resProps}
maskTransitionName="am-fade"
className="am-modal-operation"
/> , div,
);
return {
close,
};
}
|
08-create-a-sidebar/components/Home/index.js
|
nodeyu/jason-react-router-demos-v4
|
import React from 'react';
class Home extends React.Component {
render() {
return (
<div>
<h1>Home</h1>
<p>This is home page.</p>
</div>
);
}
}
export default Home;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.