path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
client/app/components/Settings.Vendors.js
|
jfanderson/KIM
|
import React from 'react';
import h from '../helpers.js';
import v from '../services/vendorService.js';
import sign from '../services/sign.js';
import AddVendorForm from './Form.AddVendor.js';
import Cell from './Cell.js';
import Column from './Column.js';
import Table from './Table.js';
class VendorSettings extends React.Component {
constructor() {
super();
this.state = {
vendors: [],
removeMode: false,
isAddVendorFormOpen: false
};
}
componentDidMount() {
this._updateVendors();
}
//-----------------------------------
// RENDERING
//-----------------------------------
render() {
return (
<div>
<h2 className="with-button" ref={h2 => { this._vendorTitle = h2; }}>Vendors</h2>
<button className="add-button inner" onClick={this._handleAddClick.bind(this)}>+</button>
<button className="remove-button inner" onClick={this._handleRemoveModeClick.bind(this)}>--</button>
<Table classes="inner" data={this.state.vendors} uniqueId="company">
<Column header="Company" cell={vendor => (
<Cell modifyField={this._modifyVendor.bind(this, vendor.id, 'company')}>{vendor.company}</Cell>
)}
/>
<Column header="Address" cell={vendor => (
<Cell modifyField={this._modifyVendor.bind(this, vendor.id, 'address')}>{vendor.address}</Cell>
)}
/>
<Column header="Phone" cell={vendor => (
<Cell modifyField={this._modifyVendor.bind(this, vendor.id, 'phone')}>{vendor.phone}</Cell>
)}
/>
<Column header="Email" cell={vendor => (
<Cell modifyField={this._modifyVendor.bind(this, vendor.id, 'email')}>{vendor.email}</Cell>
)}
/>
{this._renderVendorRemoveColumn()}
</Table>
{this._renderAddVendorForm()}
</div>
);
}
_renderAddVendorForm() {
if (this.state.isAddVendorFormOpen) {
return (
<AddVendorForm cancel={this._handleAddClick.bind(this)}
submit={this._handleVendorSubmit.bind(this)}
top={h.findPopupTopValue(this._vendorTitle)}
/>
);
}
}
_renderVendorRemoveColumn() {
if (this.state.removeMode) {
return (
<Column header="Remove" cell={vendor => (
<Cell className="remove"><div onClick={this._removeVendor.bind(this, vendor)}>X</div></Cell>
)}
/>
);
}
}
//-----------------------------------
// PRIVATE METHODS
//-----------------------------------
_handleAddClick(event) {
if (event) {
event.preventDefault();
}
this.setState({ isAddVendorFormOpen: !this.state.isAddVendorFormOpen });
}
_handleRemoveModeClick() {
this.setState({ removeMode: !this.state.removeMode });
}
_handleVendorSubmit(vendor) {
v.addVendor(vendor).then(() => {
this._updateVendors();
}).catch(() => {
sign.setError('Failed to add new vendor.');
});
}
_modifyVendor(vendorId, key, value) {
let vendors = this.state.vendors;
for (let i = 0; i < vendors.length; i++) {
if (vendors[i].id === vendorId) {
vendors[i][key] = value;
break;
}
}
this.setState({ vendors });
v.modifyVendor(vendorId, key, value)
.catch(() => {
sign.setError('Failed to modify vendor. Try refreshing.');
this.state.vendors = null;
});
}
_removeVendor(vendor) {
let confirmed = confirm(`Are you sure you want to remove ${vendor.company}?`);
if (confirmed) {
v.removeVendor(vendor.id).then(() => {
this._updateVendors();
}).catch(() => {
sign.setError('Failed to remove vendor.');
});
}
}
_updateVendors() {
v.getVendors().then(vendors => {
this.setState({ vendors });
}).catch(() => {
sign.setError('Failed to retrieve vendors. Try refreshing.');
});
}
}
export default VendorSettings;
|
src/app.js
|
gj262/my-react-redux-starter-kit
|
import 'babel-polyfill'
import React from 'react'
import ReactDOM from 'react-dom'
import routes from './routes'
import Root from './containers/Root'
import { browserHistory } from 'react-router'
import { syncHistory, routeReducer } from 'redux-simple-router'
import thunkMiddleware from 'redux-thunk'
import reducers from './reducers'
import { applyMiddleware, createStore, combineReducers } from 'redux'
const reducer = combineReducers(Object.assign({}, reducers, {
routing: routeReducer
}))
const reduxRouterMiddleware = syncHistory(browserHistory)
const createStoreWithMiddleware = applyMiddleware(reduxRouterMiddleware, thunkMiddleware)(createStore)
const store = createStoreWithMiddleware(reducer)
// Render the React application to the DOM
ReactDOM.render(
<Root history={browserHistory} routes={routes} store={store} />,
document.getElementById('root')
)
|
packages/mcs-lite-landing-web/src/containers/Section1/Chart.js
|
MCS-Lite/mcs-lite
|
import React from 'react';
import styled from 'styled-components';
import rafThrottle from 'raf-throttle';
import TweenOne from 'rc-tween-one';
import Heading from 'mcs-lite-ui/lib/Heading';
import last from 'ramda/src/last';
import DataPointAreaChart from 'mcs-lite-ui/lib/DataPointAreaChart';
import localTimeFormat from 'mcs-lite-ui/lib/utils/localTimeFormat';
import { IMAGE_WIDTH } from './styled-components';
const Wrapper = styled.div`
display: flex;
bottom: 0;
width: ${IMAGE_WIDTH}px;
padding-right: 55px;
box-sizing: border-box;
> * {
background: white;
}
`;
const ChartWrapper = styled.div`
width: 420px;
height: 120px;
transform: translateY(29px);
margin-left: 31px;
`;
const StyledHeading = styled(Heading)`
font-size: 18px;
text-align: center;
width: 68px;
margin-left: 94px;
margin-right: 20px;
margin-top: 62px;
margin-bottom: 25px;
`;
function getRandomValue(min = 20, max = 35, digits = 2) {
return Number((Math.random() * (max - min) + min).toFixed(digits));
}
class Chart extends React.PureComponent {
state = {
data: [
{ value: 21, updatedAt: '2017-01-13 00:00' },
{ value: 24, updatedAt: '2017-01-13 00:00' },
{ value: 21, updatedAt: '2017-01-13 00:00' },
{ value: 28, updatedAt: '2017-02-13 00:01' },
{ value: 25, updatedAt: '2017-02-13 00:01' },
{ value: 25.2, updatedAt: '2017-02-13 00:01' },
{ value: 28, updatedAt: '2017-03-13 00:02' },
{ value: 28.1, updatedAt: '2017-03-13 00:02' },
{ value: 21.3, updatedAt: '2017-03-13 00:02' },
{ value: 23, updatedAt: '2017-04-13 00:04' },
{ value: 24.3, updatedAt: '2017-04-13 00:04' },
{ value: 24, updatedAt: '2017-04-13 00:04' },
{ value: 20, updatedAt: '2017-05-13 00:05' },
{ value: 21.5, updatedAt: '2017-05-13 00:05' },
{ value: 24.5, updatedAt: '2017-06-13 00:06' },
],
};
componentDidMount() {
this.timeout = setTimeout(() => {
this.interval = setInterval(this.appendData, 1500);
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
clearTimeout(this.timeout);
this.appendData.cancel();
}
appendData = rafThrottle(() => {
this.setState({
data: [
...this.state.data.slice(1),
{
value: getRandomValue(),
updatedAt: localTimeFormat(new Date()),
},
],
});
});
render() {
const { data } = this.state;
return (
<TweenOne
animation={{
opacity: 1,
duration: 550,
}}
style={{
opacity: 0,
}}
component={Wrapper}
>
<StyledHeading color="primary">{last(data).value}</StyledHeading>
<ChartWrapper>
<DataPointAreaChart isAnimationActive data={data} />
</ChartWrapper>
</TweenOne>
);
}
}
export default Chart;
|
fields/types/azurefile/AzureFileColumn.js
|
dvdcastro/keystone
|
import React from 'react';
var AzureFileColumn = React.createClass({
renderValue () {
var value = this.props.data.fields[this.props.col.path];
if (!value) return;
return <a href={value.url} target="_blank">{value.url}</a>;
},
render () {
return (
<td className="ItemList__col">
<div className="ItemList__value ItemList__value--azure-file">{this.renderValue()}</div>
</td>
);
},
});
module.exports = AzureFileColumn;
|
src/router.js
|
DanielHabib/onboarding
|
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react';
import Router from 'react-routing/src/Router';
import http from './core/http';
import App from './components/App';
import ContentPage from './components/ContentPage';
import ContactPage from './components/ContactPage';
import LoginPage from './components/LoginPage';
import RegisterPage from './components/RegisterPage';
import NotFoundPage from './components/NotFoundPage';
import ErrorPage from './components/ErrorPage';
const router = new Router(on => {
on('*', async (state, next) => {
const component = await next();
return component && <App context={state.context}>{component}</App>;
});
on('/contact', async () => <ContactPage />);
on('/login', async () => <LoginPage />);
on('/register', async () => <RegisterPage />);
on('*', async (state) => {
const content = await http.get(`/api/content?path=${state.path}`);
return content && <ContentPage {...content} />;
});
on('error', (state, error) => state.statusCode === 404 ?
<App context={state.context} error={error}><NotFoundPage /></App> :
<App context={state.context} error={error}><ErrorPage /></App>);
});
export default router;
|
client/src/components/CoursesPage.js
|
yegor-sytnyk/contoso-express
|
import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as courseActions from '../actions/courseActions';
import {departmentSelectListItem} from '../formatters/entityFromatter';
import CoursesList from './courses/CoursesList';
import CourseSave from './courses/CourseSave';
import CourseDetails from './courses/CourseDetails';
import CourseDelete from './courses/CourseDelete';
import CoursesFilter from './courses/CoursesFilter';
class CoursesPage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
courses: props.courses,
selectedDepartmentId: '',
saveModalVisible: false,
detailsModalVisible: false,
confirmationVisible: false
};
this.changeDepartmentState = this.changeDepartmentState.bind(this);
this.showSaveModal = this.showSaveModal.bind(this);
this.closeSaveModal = this.closeSaveModal.bind(this);
this.filterCourses = this.filterCourses.bind(this);
this.showDetailsModal = this.showDetailsModal.bind(this);
this.closeDetailsModal = this.closeDetailsModal.bind(this);
this.showConfirmationModal = this.showConfirmationModal.bind(this);
this.closeConfirmationModal = this.closeConfirmationModal.bind(this);
}
componentWillMount() {
this.props.loadCourses();
}
changeDepartmentState(event) {
let departmentId = event.target.value;
return this.setState({selectedDepartmentId: departmentId});
}
filterCourses() {
this.props.actions.loadCourses(this.state.selectedDepartmentId);
}
showSaveModal(courseId) {
this.props.actions.loadCourse(courseId)
.then(() => {
this.setState({saveModalVisible: true});
});
}
closeSaveModal() {
this.setState({saveModalVisible: false});
}
showDetailsModal(courseId) {
this.props.actions.loadCourse(courseId)
.then(() => {
this.setState({detailsModalVisible: true});
});
}
closeDetailsModal() {
this.setState({detailsModalVisible: false});
}
showConfirmationModal(courseId) {
this.props.actions.loadCourse(courseId)
.then(() => {
this.setState({confirmationVisible: true});
});
}
closeConfirmationModal() {
this.setState({confirmationVisible: false});
}
render() {
return (
<div className="container">
<h2>Courses</h2>
<a href="#" onClick={this.showSaveModal}>Create New</a>
<CoursesFilter departmentId={this.state.selectedDepartmentId}
departments={this.props.departments}
onChange={this.changeDepartmentState}
onClick={this.filterCourses}
/>
<CoursesList courses={this.props.courses}
onSaveClick={this.showSaveModal}
onDetailsClick={this.showDetailsModal}
onDeleteClick={this.showConfirmationModal}
/>
<CourseSave visible={this.state.saveModalVisible}
close={this.closeSaveModal}
/>
<CourseDetails visible={this.state.detailsModalVisible}
close={this.closeDetailsModal}
/>
<CourseDelete visible={this.state.confirmationVisible}
close={this.closeConfirmationModal}
/>
</div >
);
}
}
CoursesPage.propTypes = {
courses: React.PropTypes.array.isRequired,
actions: React.PropTypes.object.isRequired
};
function mapStateToProps(state) {
return {
courses: state.course.list,
departments: departmentSelectListItem(state.department.list)
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(courseActions, dispatch),
loadCourses: () => courseActions.loadCourses(null)(dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage);
|
admin/client/App/screens/Item/components/FormHeading.js
|
snowkeeper/keystone
|
import React from 'react';
import evalDependsOn from '../../../../../../fields/utils/evalDependsOn';
module.exports = React.createClass({
displayName: 'FormHeading',
propTypes: {
options: React.PropTypes.object,
},
render () {
if (!evalDependsOn(this.props.options.dependsOn, this.props.options.values)) {
return null;
}
return <h3 className="form-heading">{this.props.content}</h3>;
},
});
|
src/components/Header/Header.js
|
FAN-CUK/official
|
import React from 'react';
import FontAwesome from 'react-fontawesome';
import classNames from 'classnames';
import { Link } from 'react-router';
import MenuItem from './MenuItem';
import css from './Header.css';
class Header extends React.Component {
render() {
const c = [
{ name : "김수연조", boardId : 1 },
{ name : "유용우조", boardId : 2 },
{ name : "김소연조", boardId : 300 },
{ name : "이소정조", boardId : 45}
];
const cplus = [
{ name : "김수연조", boardId : 1 },
{ name : "유용우조", boardId : 2 },
{ name : "김소연조", boardId : 300 }
];
const web = [
{ name : "김수연조", boardId : 1 },
{ name : "유용우조", boardId : 2 },
];
const java = [
{ name : "김수연조", boardId : 1 },
{ name : "유용우조", boardId : 2 },
{ name : "김소연조", boardId : 300 },
{ name : "이소정조", boardId : 45},
{ name : "이종원조", boardId : 20}
];
const datastructure = [
{ name : "김수연조", boardId : 1 }
];
const mapToComponents = items => {
return items.map((item, idx) => {
return (
<MenuItem name={item.name} idx={item.boardId} key={idx} />
);
}
);
}
return(
<header>
<div className="container-fluid" id="header">
{/* Navigation */}
<nav className={classNames(css.menu, "navbar", "navbar-fixed-top")} role="navigation">
<div className="container">
<div className={classNames("navbar-header", "page-scroll")}>
<button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<Link className={classNames(css.logo, "page-scroll")} to='/#page-top'>F.A.N</Link>
</div>
{/* Collect the nav links, forms, and other content for toggling */}
<div className={classNames("collapse", "navbar-collapse", "navbar-ex1-collapse")}>
<ul className={classNames("nav", "navbar-nav", css.menuitem)}>
<li><a href="#">Home</a></li>
<li className="dropdown">
<a className="dropdown-toggle" data-toggle="dropdown" href="#">Board<span className="caret"></span></a>
<ul className={classNames("dropdown-menu", css.mdd, css.boarddrop)}>
<li><a href="#">Notice</a></li>
<li><a href="#">Question</a></li>
<li>
<Link to='/board'>Free Board</Link>
</li>
<li><a href="#">Library</a></li>
</ul>
</li>
<li className="dropdown">
<a className="dropdown-toggle" data-toggle="dropdown" href="#">Study<span className="caret"></span></a>
<ul className={classNames("dropdown-menu", "multi-level", css.mdd, css.studydrop)}>
<li className={css.st}>
<p className="text-center">C</p>
<ul className={classNames("text-center", css.studydbdrop)}>
{ mapToComponents(c) }
</ul>
</li>
<li className={css.st}>
<p className="text-center">C++</p>
<ul className={classNames("text-center", css.studydbdrop)}>
{mapToComponents(cplus)}
</ul>
</li>
<li className={css.st}>
<p className="text-center">Web</p>
<ul className={classNames("text-center", css.studydbdrop)}>
{ mapToComponents(web) }
</ul>
</li>
<li className={css.st}>
<p className="text-center">Java</p>
<ul className={classNames("text-center", css.studydbdrop)}>
{ mapToComponents(java) }
</ul>
</li>
<li className={css.st}>
<p className="text-center">자료구조</p>
<ul className={classNames("text-center", css.studydbdrop)}>
{ mapToComponents(datastructure) }
</ul>
</li>
</ul>
</li>
<li><a href="#">Gallery</a></li>
</ul>
<ul className={classNames("nav", "navbar-nav", "navbar-right", css.loginInfo)}>
<li className="dropdown">
<a className="dropdown-toggle" data-toggle="dropdown" href="#"><FontAwesome name="sign-in"/>My Info</a>
<div id="info_viewer" className={classNames("panel", "panel-info", "dropdown-menu")}>
<div className="panel-heading">
<h3 className="panel-title"><span id = "v_title_kr">정보</span> <span id = "v_title_en">My Info</span></h3>
</div>
<div className="panel-body">
<div id = "user_level" className="alert alert-info" role="alert">회원등급</div>
<ul className="list-group">
<li className="list-group-item">이름 : ㅇㅁㅇ</li>
<li className="list-group-item">전공 : 컴공</li>
<li className="list-group-item">학번 : 123456789</li>
<li className="list-group-item">상태 : 휴학</li>
<li className="list-group-item"><a href="#"> 소속스터디 : C언어 </a></li>
</ul>
</div>
</div>
</li>
<li><a href="#">Logout</a></li>
</ul>
</div>
{/* /.navbar-collapse */}
</div>
{/* /.container */}
</nav>
</div>
</header>
);
}
}
export default Header;
|
src/base/ActionBar.js
|
WellerQu/rongcapital-ui
|
/* 一种另类的尝试 */
import React from 'react';
import clazz from 'classnames';
import PropTypes from 'prop-types';
import * as componentStyles from '../styles/base/actionBar.sass';
const ActionBar = ({ children }) =>
<ul className={ componentStyles['action-bar'] }>{ children }</ul>;
ActionBar.Item = ({ children, right }) =>
<li className={ clazz({
[componentStyles.right]: right
}) }>{ children }</li>;
ActionBar.propTypes = {
children: PropTypes.oneOfType([ PropTypes.element, PropTypes.arrayOf(PropTypes.element) ])
};
ActionBar.Item.displayName = 'ActionBarItem';
ActionBar.Item.propTypes = {
right: PropTypes.bool,
children: PropTypes.any
};
ActionBar.Item.defaultProps = {
right: false
};
export default ActionBar;
|
examples/dynamic-segments/app.js
|
brownbathrobe/react-router
|
import React from 'react';
import { Router, Route, Link, Redirect } from 'react-router';
var App = React.createClass({
render() {
return (
<div>
<ul>
<li><Link to="/user/123">Bob</Link></li>
<li><Link to="/user/abc">Sally</Link></li>
</ul>
{this.props.children}
</div>
);
}
});
var User = React.createClass({
render() {
var { userID } = this.props.params;
return (
<div className="User">
<h1>User id: {userID}</h1>
<ul>
<li><Link to={`/user/${userID}/tasks/foo`}>foo task</Link></li>
<li><Link to={`/user/${userID}/tasks/bar`}>bar task</Link></li>
</ul>
{this.props.children}
</div>
);
}
});
var Task = React.createClass({
render() {
var { userID, taskID } = this.props.params;
return (
<div className="Task">
<h2>User ID: {userID}</h2>
<h3>Task ID: {taskID}</h3>
</div>
);
}
});
React.render((
<Router>
<Route path="/" component={App}>
<Route path="user/:userID" component={User}>
<Route path="tasks/:taskID" component={Task} />
<Redirect from="todos/:taskID" to="/user/:userID/tasks/:taskID" />
</Route>
</Route>
</Router>
), document.getElementById('example'));
|
node_modules/babel-plugin-react-transform/test/fixtures/code-ignore/expected.js
|
odapplications/WebView-with-Lower-Tab-Menu
|
import React from 'react';
const First = React.createNotClass({
displayName: 'First'
});
class Second extends React.NotComponent {}
|
src/svg-icons/editor/border-color.js
|
w01fgang/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorBorderColor = (props) => (
<SvgIcon {...props}>
<path d="M17.75 7L14 3.25l-10 10V17h3.75l10-10zm2.96-2.96c.39-.39.39-1.02 0-1.41L18.37.29c-.39-.39-1.02-.39-1.41 0L15 2.25 18.75 6l1.96-1.96z"/><path fillOpacity=".36" d="M0 20h24v4H0z"/>
</SvgIcon>
);
EditorBorderColor = pure(EditorBorderColor);
EditorBorderColor.displayName = 'EditorBorderColor';
EditorBorderColor.muiName = 'SvgIcon';
export default EditorBorderColor;
|
src/parser/shared/modules/features/Checklist/PreparationRule.js
|
anom0ly/WoWAnalyzer
|
import { Trans } from '@lingui/macro';
import PropTypes from 'prop-types';
import React from 'react';
import Requirement from './Requirement';
import Rule from './Rule';
class PreparationRule extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
thresholds: PropTypes.object.isRequired,
};
renderPotionRequirements() {
const { thresholds } = this.props;
return (
<>
<Requirement
name={
<Trans id="shared.modules.features.checklist.combatPotionsUsed">
Combat potions used
</Trans>
}
thresholds={thresholds.potionsUsed}
/>
<Requirement
name={
<Trans id="shared.modules.features.checklist.highQualityCombatPotionsUsed">
High quality combat potions used
</Trans>
}
thresholds={thresholds.bestPotionUsed}
/>
</>
);
}
renderEnchantRequirements() {
const { thresholds } = this.props;
return (
<>
<Requirement
name={<Trans id="shared.modules.features.checklist.enchanted">All items enchanted</Trans>}
thresholds={thresholds.itemsEnchanted}
/>
<Requirement
name={
<Trans id="shared.modules.features.checklist.enchantedHigh">
Using high quality enchants
</Trans>
}
thresholds={thresholds.itemsBestEnchanted}
/>
</>
);
}
renderWeaponEnhancementRequirements() {
const { thresholds } = this.props;
return (
<>
<Requirement
name={<Trans>All weapons enhanced (oils/stones)</Trans>}
thresholds={thresholds.weaponsEnhanced}
/>
<Requirement
name={<Trans>Using high quality weapon enhancements</Trans>}
thresholds={thresholds.bestWeaponEnhancements}
/>
</>
);
}
renderFlaskRequirements() {
const { thresholds } = this.props;
return (
<>
<Requirement
name={
<Trans id="shared.modules.features.checklist.flaskHigh">High quality flask used</Trans>
}
thresholds={thresholds.higherFlaskPresent}
/>
<Requirement
name={<Trans id="shared.modules.features.checklist.flask">Flask used</Trans>}
thresholds={thresholds.flaskPresent}
/>
</>
);
}
renderFoodRequirements() {
const { thresholds } = this.props;
return (
<>
<Requirement
name={
<Trans id="shared.modules.features.checklist.foodHigh">High quality food used</Trans>
}
thresholds={thresholds.higherFoodPresent}
/>
<Requirement
name={<Trans id="shared.modules.features.checklist.food">Food used</Trans>}
thresholds={thresholds.foodPresent}
/>
</>
);
}
renderAugmentRuneRequirements() {
const { thresholds } = this.props;
return (
<>
<Requirement
name={<Trans id="shared.modules.features.checklist.augmentRune">Augment rune used</Trans>}
thresholds={thresholds.augmentRunePresent}
/>
</>
);
}
render() {
const { children } = this.props;
return (
<Rule
name={<Trans id="shared.modules.features.checklist.wellPrepared">Be well prepared</Trans>}
description={
<Trans id="shared.modules.features.checklist.wellPreparedDetails">
Being well prepared with food, flasks, potions and enchants is an easy way to improve
your performance.
</Trans>
}
>
{this.renderEnchantRequirements()}
{this.renderWeaponEnhancementRequirements()}
{this.renderPotionRequirements()}
{this.renderFlaskRequirements()}
{this.renderFoodRequirements()}
{this.renderAugmentRuneRequirements()}
{children}
</Rule>
);
}
}
export default PreparationRule;
|
src/components/general/Error.js
|
OlivierVillequey/hackathon
|
/**
* Error Screen
*
<Error text={'Server is down'} />
*
* React Native Starter App
* https://github.com/mcnamee/react-native-starter-app
*/
import React from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
// Consts and Libs
import { AppStyles } from '@theme/';
// Components
import { Spacer, Text, Button } from '@ui/';
/* Component ==================================================================== */
const Error = ({ text, tryAgain }) => (
<View style={[AppStyles.container, AppStyles.containerCentered]}>
<Icon name={'ios-alert-outline'} size={50} color={'#CCC'} />
<Spacer size={10} />
<Text style={AppStyles.textCenterAligned}>{text}</Text>
<Spacer size={20} />
{!!tryAgain &&
<Button
small
outlined
title={'Try again'}
onPress={tryAgain}
/>
}
</View>
);
Error.propTypes = { text: PropTypes.string, tryAgain: PropTypes.func };
Error.defaultProps = { text: 'Woops, Something went wrong.', tryAgain: null };
Error.componentName = 'Error';
/* Export Component ==================================================================== */
export default Error;
|
src/svg-icons/action/watch-later.js
|
lawrence-yu/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionWatchLater = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm4.2 14.2L11 13V7h1.5v5.2l4.5 2.7-.8 1.3z"/>
</SvgIcon>
);
ActionWatchLater = pure(ActionWatchLater);
ActionWatchLater.displayName = 'ActionWatchLater';
ActionWatchLater.muiName = 'SvgIcon';
export default ActionWatchLater;
|
app/javascript/mastodon/components/missing_indicator.js
|
PlantsNetwork/mastodon
|
import React from 'react';
import { FormattedMessage } from 'react-intl';
const MissingIndicator = () => (
<div className='regeneration-indicator missing-indicator'>
<div>
<div className='regeneration-indicator__figure' />
<div className='regeneration-indicator__label'>
<FormattedMessage id='missing_indicator.label' tagName='strong' defaultMessage='Not found' />
<FormattedMessage id='missing_indicator.sublabel' defaultMessage='This resource could not be found' />
</div>
</div>
</div>
);
export default MissingIndicator;
|
src/components/editor/TuningButton.js
|
calesce/tab-editor
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { head, last } from 'lodash';
import Popover from 'react-popover';
import { StyleSheet, css } from 'aphrodite';
import { tuningSelector } from '../../util/selectors';
import HoverableText from './HoverableText';
import { changeTuning } from '../../actions/track';
import {
nextNote,
previousNote,
previousOctave,
nextOctave
} from '../../util/midiNotes';
const styles = StyleSheet.create({
hover: {
':hover': {
MozUserSelect: 'none',
WebkitUserSelect: 'none',
msUserSelect: 'none',
cursor: 'pointer',
fill: '#b3caf5'
},
fill: 'black'
},
popover: { zIndex: 5, fill: '#FEFBF7', marginLeft: -20 },
popoverContainer: {
display: 'flex',
flexDirection: 'row',
background: '#FEFBF7'
},
arrowButtons: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
marginLeft: 5
},
stringsColumn: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
alignItems: 'center',
marginRight: 5
},
stringRow: {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
},
textInput: {
fontFamily: 'Optima, Segoe, Segoe UI, Candara, Calibri, Arial, sans-serif',
margin: 5,
width: 25,
':focus': { outline: 'none' }
}
});
const TuningIcon = ({ onClick }) => (
<svg onClick={onClick} width={60} height={50} className={css(styles.hover)}>
<path d="M4.416 21.77c-1.058 0-1.916.858-1.916 1.916v3.704c0 1.058.858 1.917 1.916 1.917 1.058 0 1.916-.858 1.916-1.917v-.468h2.652v1.906c0 .575.367 1.328.82 1.683l5.355 4.185v7.07h9.42v-7.16l5.347-4.102c.457-.35.827-1.1.827-1.675v-1.906h2.65v.468c0 1.058.86 1.917 1.918 1.917 1.058 0 1.916-.858 1.916-1.917v-3.704c0-1.058-.858-1.916-1.916-1.916-1.058 0-1.917.858-1.917 1.916v.57h-2.65v-8.52h2.65v.568c0 1.058.86 1.917 1.917 1.917 1.058 0 1.916-.857 1.916-1.916V12.6c0-1.058-.858-1.916-1.916-1.916-1.058 0-1.917.858-1.917 1.916v.47h-2.65V8.678c0-.575-.43-.855-.955-.624l-9.01 3.945c-.528.23-1.383.23-1.91-.002l-8.943-3.94c-.527-.233-.953.046-.953.62v4.395H6.332v-.47c0-1.058-.858-1.916-1.916-1.916-1.058 0-1.916.858-1.916 1.916v3.705c0 1.058.858 1.916 1.916 1.916 1.058 0 1.916-.857 1.916-1.915v-.57h2.652v8.523H6.332v-.572c0-1.058-.858-1.916-1.916-1.916z" />
</svg>
);
class TuningStringInput extends Component {
componentDidMount() {
if (this.props.index === 0) {
this.input.select();
}
}
removeString = () => {
this.props.removeString(this.props.index);
};
midiStringFromKeyCode(string, keyCode, shiftKey) {
switch (keyCode) {
case 37:
return previousNote(string);
case 38:
return nextOctave(string);
case 39:
return nextNote(string);
case 40:
return previousOctave(string);
default: {
if (keyCode === 51 && shiftKey) {
if (string[0] !== 'e' && string[0] !== 'b' && string.length === 2) {
return string[0] + '#' + string[1];
}
} else if (keyCode >= 48 && keyCode <= 57) {
return string[0] + (keyCode - 48);
} else if (keyCode >= 65 && keyCode <= 71) {
return (
String.fromCharCode(keyCode).toLowerCase() + last(string.split(''))
);
}
return string;
}
}
}
onTextChanged = e => {
const newString = this.midiStringFromKeyCode(
this.props.string,
e.keyCode,
e.shiftKey
);
if (newString !== this.props.string) {
this.props.onChange(newString, this.props.index);
}
};
noop() {
/* this exists to make React happy */
}
setRef = el => {
this.input = el;
};
render() {
return (
<span className={css(styles.stringRow)}>
<input
className={css(styles.textInput)}
type="text"
size={2}
value={this.props.string}
onChange={this.noop}
onKeyDown={this.onTextChanged}
ref={this.setRef}
/>
<HoverableText onClick={this.removeString} text="x" weight="normal" />
</span>
);
}
}
class TuningPopover extends Component {
constructor(props) {
super(props);
this.state = { tuning: [].concat(props.tuning) };
}
componentWillUnmount() {
this.props.changeTuning(this.state.tuning);
}
removeString = index => {
this.setState({
tuning: this.state.tuning.filter(
(_, i) => i !== this.state.tuning.length - 1 - index
)
});
};
incrementAllStrings = () => {
this.setState({ tuning: this.state.tuning.map(nextNote) });
};
decrementAllStrings = () => {
this.setState({ tuning: this.state.tuning.map(previousNote) });
};
addTopString = () => {
this.setState({
tuning: this.state.tuning.concat(last(this.state.tuning))
});
};
addBottomString = () => {
this.setState({
tuning: [head(this.state.tuning)].concat(this.state.tuning)
});
};
onChange = (newString, i) => {
const { tuning } = this.state;
const { length } = tuning;
const newTuning = tuning
.slice(0, length - 1 - i)
.concat(newString)
.concat(tuning.slice(length - i, length));
this.setState({ tuning: newTuning });
};
render() {
const { tuning } = this.state;
const tuningInputs = tuning
.slice(0)
.reverse()
.map((string, i) => (
<TuningStringInput
string={string}
index={i}
key={i}
onChange={this.onChange}
removeString={this.removeString}
/>
));
return (
<div className={css(styles.popoverContainer)}>
<span className={css(styles.arrowButtons)}>
<HoverableText onClick={this.incrementAllStrings} text="▲" />
<HoverableText onClick={this.decrementAllStrings} text="▼" />
</span>
<div className={css(styles.stringsColumn)}>
<HoverableText onClick={this.addTopString} text="+" weight="heavy" />
{tuningInputs}
<HoverableText
onClick={this.addBottomString}
text="+"
weight="heavy"
/>
</div>
</div>
);
}
}
const ConnectedPopover = connect(null, { changeTuning })(TuningPopover);
class TuningButton extends Component {
constructor() {
super();
if (typeof window !== 'undefined') {
window.addEventListener('keydown', this.handleKeyPress);
}
this.state = { popoverOpen: false };
}
componentWillUnmount() {
window.removeEventListener('keywdown', this.handleKeyPress);
}
handleKeyPress = e => {
if (this.state.popoverOpen) {
if (e.keyCode === 13) {
// enter
this.onPopoverClose();
} else if (e.keyCode === 27) {
// escape
// TODO make this cancel the tuning change instead of updating it
this.onPopoverClose();
} else if (e.keyCode === 37 || e.keyCode === 39) {
// left/right arrow
e.preventDefault();
}
}
};
onClick = () => {
if (this.state.popoverOpen) {
this.onPopoverClose();
} else {
this.props.onClick();
this.setState({ popoverOpen: true });
}
};
onPopoverClose = () => {
this.setState({ popoverOpen: false });
this.props.onClose();
};
render() {
const { tuning } = this.props;
const body = <ConnectedPopover tuning={tuning} />;
return (
<div>
<Popover
preferPlace="right"
className={css(styles.popover)}
isOpen={this.state.popoverOpen}
onOuterAction={this.onPopoverClose}
body={body}
>
<TuningIcon onClick={this.onClick} />
</Popover>
</div>
);
}
}
export default connect(state => ({ tuning: tuningSelector(state) }))(
TuningButton
);
|
app/javascript/components/borrow_booking_calendar/BorrowBookingCalendar.js
|
leihs/leihs_legacy
|
import React from 'react'
import createReactClass from 'create-react-class'
import CalendarControls from './CalendarControls'
import CalendarContent from './CalendarContent'
import DateInput from './DateInput'
const inspect = window.Tools.inspect
const BorrowBookingCalendar = createReactClass({
displayName: 'BorrowBookingCalendar',
propTypes: {},
getInitialState() {
const todayDate = moment()
const firstDateOfCurrentMonth = moment([todayDate.year(), todayDate.month(), 1])
return {
todayDate: todayDate,
firstDateOfCurrentMonth: firstDateOfCurrentMonth,
startDate: this.props.initialStartDate,
endDate: this.props.initialEndDate,
selectedDate: null,
quantity: (this.props.initialQuantity || 1),
isLoading: true,
calendarData: [],
poolContext: this.props.inventoryPools[0]
}
},
componentDidMount() {
this._fetchAndUpdateCalendarData(this._getLastDateInCalendarView(this.state.endDate))
},
_f: 'YYYY-MM-DD',
_fetchAndUpdateCalendarData(toDate = null) {
let fromDate
if (_.isEmpty(this.state.calendarData)) {
fromDate = this._getFirstDateInCalendarView(this.state.todayDate)
} else {
fromDate = _.last(this.state.calendarData)
.date.clone()
.add(1, 'day')
}
if (this.state.isLoading) {
this._fetchAvailabilities(
fromDate.format(this._f),
toDate ? toDate.format(this._f) : this._getLastDateInCalendarView().format(this._f)
).done(data => {
const newDates = _.map(data.list, avalObject => {
return {
date: moment(avalObject.d),
availableQuantity: avalObject.quantity,
visitsCount: avalObject.visits_count
}
})
this.setState(prevState => {
return {
isLoading: false,
calendarData: prevState.calendarData.concat(newDates)
}
})
})
}
},
_getFirstDateInCalendarView(date = null) {
const firstDateOfMonth = date
? moment([date.year(), date.month()])
: this.state.firstDateOfCurrentMonth
let daysShift = firstDateOfMonth.day() - 1
// in the default moment locale week starts on Sunday (index 0)
if (daysShift == -1) {
daysShift = 6
}
return firstDateOfMonth.clone().subtract(daysShift, 'day')
},
_getLastDateInCalendarView(date = null) {
return this._getFirstDateInCalendarView(date)
.clone()
.add(41, 'day')
},
_dropUntil(arr, func) {
if (_.isEmpty(arr) || func(_.head(arr))) {
return arr
} else {
return this._dropUntil(_.rest(arr), func)
}
},
_getDatesForCurrentMonthView() {
const firstDate = this._getFirstDateInCalendarView()
const arr1 = this._dropUntil(this.state.calendarData, el => {
return el.date.isSame(firstDate)
})
return _.take(arr1, 42)
},
existingReservations() {
// component used for editing existing reservations
return (this.props.reservations.length != 0)
},
// TODO: a single callback should be given to this component.
// right now the component is used in different contextes, where
// different callback chains apply:
// 1. CREATE NEW RESERVATIONS (from models index; involves ajax post)
// 1.1 `createReservations` -> `finishCallback`
// 2. UPDATE EXISTING RESERVATIONS (from customer order; involves ajax post)
// 2.1 `createReservations` -> `finishCallback`
// 2.2 `deleteReservations` -> `finishCallback`
// 2.3 `changeTimeRange` -> `finishCallback`
// 2.3 `changeTimeRange` -> `createReservations` -> `finishCallback`
// 2.3 `changeTimeRange` -> `deleteReservations` -> `finishCallback`
// 3. PREPARE RESERVATIONS FOR CUSTOMER ORDER (from template wizard; does not involve ajax post)
// 3.3 `exclusiveCallback`
getOnClickCallback() {
if (this.props.exclusiveCallback) {
return () => {
this.props.exclusiveCallback({
start_date: this.state.startDate.format(this._f),
end_date: this.state.endDate.format(this._f),
quantity: Number(this.state.quantity),
inventory_pool_id: this.state.poolContext.inventory_pool.id
})
}
} else {
let callback
if (this.hasQuantityIncreased()) {
callback = this.createReservations
} else if (this.hasQuantityDecreased()) {
callback = this.deleteReservations
} else {
callback = this.props.finishCallback
}
if (this.existingReservations() && this.hasTimeRangeChanged()) {
return () => this.changeTimeRange(callback)
} else {
return callback
}
}
},
changeTimeRange(successCallback) {
$.ajax({
url: '/borrow/reservations/change_time_range',
method: 'POST',
dataType: 'json',
data: {
line_ids: _.map(this.props.reservations, (r) => r.id),
start_date: this.state.startDate.format(this._f),
end_date: this.state.endDate.format(this._f),
inventory_pool_id: this.state.poolContext.inventory_pool.id
},
success: successCallback,
error: (xhr) => this.setState({serverError: xhr.responseText})
})
},
deleteReservations() {
const reservation_ids = _.map(this.props.reservations, (r) => r.id)
$.ajax({
url: '/borrow/reservations',
method: 'DELETE',
dataType: 'json',
data: {
line_ids: _.take(reservation_ids, (this.props.initialQuantity - this.state.quantity))
},
success: (data) => this.props.finishCallback(data),
error: (xhr) => this.setState({serverError: xhr.responseText})
})
},
createReservations() {
$.ajax({
url: '/borrow/reservations',
method: 'POST',
dataType: 'json',
data: {
start_date: this.state.startDate.format(this._f),
end_date: this.state.endDate.format(this._f),
model_id: this.props.model.id,
inventory_pool_id: this.state.poolContext.inventory_pool.id,
quantity: (this.state.quantity - this.props.initialQuantity)
},
success: (data) => this.props.finishCallback(data),
error: (xhr) => {
this.setState({serverError: xhr.responseText})
}
})
},
_fetchAvailabilities(startDate, endDate) {
return $.ajax({
url: '/borrow/booking_calendar_availability',
method: 'GET',
dataType: 'json',
data: {
start_date: startDate,
end_date: endDate,
model_id: this.props.model.id,
inventory_pool_id: this.state.poolContext.inventory_pool.id,
reservation_ids: _.map(this.props.reservations, (r) => r.id)
}
})
},
_switchMonth(direction) {
this.setState(
prevState => {
let firstDateOfMonth
switch (direction) {
case 'forward':
firstDateOfMonth = prevState.firstDateOfCurrentMonth.add(1, 'month')
break
case 'backward':
firstDateOfMonth = prevState.firstDateOfCurrentMonth.subtract(1, 'month')
break
default:
throw new Error('invalid switch month direction')
}
const isLoading = !this._isLoadedUptoDate(this._getLastDateInCalendarView())
return {
firstDateOfCurrentMonth: firstDateOfMonth,
isLoading: isLoading
}
},
this._fetchAndUpdateCalendarData // second callback argument to setState
)
},
_isLoadedUptoDate(date) {
return _.any(_.map(this.state.calendarData, el => el.date), d => d.isSame(date))
},
_changeStartDate(sd) {
const ed = sd.isAfter(this.state.endDate) ? sd : this.state.endDate
this.setState({ startDate: sd, endDate: ed })
},
changeSelectedDate(date) {
this.setState({ selectedDate: date })
},
jumpToStartDate() {
const firstDateOfJumpMonth = moment([
this.state.startDate.year(),
this.state.startDate.month(),
1
])
this.setState({ firstDateOfCurrentMonth: firstDateOfJumpMonth })
},
jumpToEndDate() {
const firstDateOfJumpMonth = moment([this.state.endDate.year(), this.state.endDate.month(), 1])
this.setState({ firstDateOfCurrentMonth: firstDateOfJumpMonth })
},
onClickPopoverStartDateCallback(sd) {
const ed = this.state.endDate.isBefore(sd) ? sd : this.state.endDate
this.setState({ startDate: sd, endDate: ed, selectedDate: null })
},
onClickPopoverEndDateCallback(ed) {
const sd = this.state.startDate.isAfter(ed) ? ed : this.state.startDate
this.setState({ endDate: ed, startDate: sd, selectedDate: null })
},
_changeEndDate(ed) {
const sd = this.state.startDate.isAfter(ed) ? ed : this.state.startDate
if (sd.isValid()) {
const loadDate = this._getLastDateInCalendarView(ed)
this.setState(
{
startDate: sd,
endDate: ed,
isLoading: !this._isLoadedUptoDate(loadDate)
},
() => this._fetchAndUpdateCalendarData(loadDate)
)
}
},
_changeQuantity(event) {
this.setState({ quantity: event.target.value })
},
_changeInventoryPool(event) {
let toDate
if (this.state.endDate.month() > this.state.firstDateOfCurrentMonth.month()) {
toDate = this._getLastDateInCalendarView(this.state.endDate)
} else {
toDate = this._getLastDateInCalendarView(this.state.firstDateOfCurrentMonth)
}
this.setState(
{
calendarData: [],
isLoading: true,
poolContext: _.find(
this.props.inventoryPools,
ip => ip.inventory_pool.id == event.target.value
)
},
() => this._fetchAndUpdateCalendarData(toDate)
)
},
_goToNextMonth() {
this._switchMonth('forward')
},
_goToPreviousMonth() {
this._switchMonth('backward')
},
_isAvailableForDateRange() {
const range = _.select(
this.state.calendarData,
el =>
el.date.isSameOrAfter(this.state.startDate) && el.date.isSameOrBefore(this.state.endDate)
)
const maxAval = _.min(_.map(range, el => el.availableQuantity))
return this.state.quantity <= maxAval
},
_isPoolOpenOn(date, workday = this.state.poolContext.workday) {
const daysOfWeek = [
'sunday',
'monday',
'tuesday',
'wednesday',
'thursday',
'friday',
'saturday'
]
return workday[daysOfWeek[date.day()]]
},
_isWithinAdvanceDaysPeriod(date, workday = this.state.poolContext.workday) {
return date.isBefore(
this.state.todayDate.clone().add(workday.reservation_advance_days || 0, 'day'),
'day'
)
},
_poolHasStillCapacityFor(date) {
const dateContext = _.find(this.state.calendarData, el => el.date.isSame(date, 'day'))
return (
dateContext &&
(
this.state.poolContext.workday.max_visits[dateContext.date.day()] == null ||
dateContext.visitsCount < this.state.poolContext.workday.max_visits[dateContext.date.day()]
)
)
},
getHoliday(date) {
return _.find(this.state.poolContext.holidays, holiday => {
return (
date.isSameOrAfter(moment(holiday.start_date), 'day') &&
date.isSameOrBefore(moment(holiday.end_date), 'day')
)
})
},
getErrors() {
let errors = []
if (this.state.serverError) {
errors.push(this.state.serverError)
} else if (!this.state.startDate.isValid() || !this.state.endDate.isValid()) {
errors.push('Invalid date')
} else if (
this.state.startDate.isBefore(this.state.todayDate, 'day') ||
this.state.endDate.isBefore(this.state.todayDate, 'day')
) {
errors.push('Start and end date cannot be in the past')
} else if (this.state.startDate.isAfter(this.state.endDate, 'day')) {
errors.push('Start date must be before end date')
} else {
if (!this._isAvailableForDateRange()) {
errors.push('Item is not available in that time range')
}
if (!this._isPoolOpenOn(this.state.startDate) || this.getHoliday(this.state.startDate)) {
errors.push('Inventory pool is closed on start date')
}
if (!this._isPoolOpenOn(this.state.endDate) || this.getHoliday(this.state.endDate)) {
errors.push('Inventory pool is closed on end date')
}
if (this._isWithinAdvanceDaysPeriod(this.state.startDate)) {
errors.push('No orders are possible on this start date')
}
if (!this._poolHasStillCapacityFor(this.state.startDate)) {
errors.push('Booking is no longer possible on this start date')
}
if (!this._poolHasStillCapacityFor(this.state.endDate)) {
errors.push('Booking is no longer possible on this end date')
}
}
return errors
},
reloadCalendarContent() {
this.setState(
{
serverError: null,
isLoading: true,
calendarData: []
},
this._fetchAndUpdateCalendarData
)
},
_renderErrors(errors) {
if (errors.length) {
return (
<div id="booking-calendar-errors">
<div className="padding-horizontal-m padding-bottom-m">
<div className="row emboss red text-align-center font-size-m padding-inset-s">
<strong>{errors.push('') && errors.map(el => _jed(el)).join('. ')}</strong>
</div>
</div>
</div>
)
} else {
return null
}
},
hasTimeRangeChanged() {
return !(
this.state.startDate.format(this._f) == this.props.initialStartDate.format(this._f) &&
this.state.endDate.format(this._f) == this.props.initialEndDate.format(this._f)
)
},
hasQuantityDecreased() {
return this.state.quantity < this.props.initialQuantity
},
hasQuantityIncreased() {
return this.state.quantity > this.props.initialQuantity
},
hasQuantityChanged() {
return (this.hasQuantityDecreased() || this.hasQuantityIncreased())
},
renderAddButton(errors) {
const isEnabled = (errors.length == 0 && this.state.quantity > 0)
return (
<button
className="button green"
id="submit-booking-calendar"
onClick={this.getOnClickCallback()}
disabled={!isEnabled}>
{_jed('Add')}
</button>
)
},
renderContent() {
let content
if (this.state.isLoading) {
content = (
<div>
<div className="height-s" />
<div className="loading-bg" />
<div className="height-s" />
</div>
)
} else if (this.state.serverError) {
content = (
<div>
<div className="height-s" />
<div style={{ textAlign: 'center' }}>
<button
className="button white large"
onClick={this.reloadCalendarContent}>
{_jed('click here to reload')}
</button>
</div>
<div className="height-s" />
</div>
)
} else {
content = (
<CalendarContent
startDate={this.state.startDate}
endDate={this.state.endDate}
quantity={this.state.quantity}
dates={this._getDatesForCurrentMonthView()}
currentMonth={this.state.firstDateOfCurrentMonth.month()}
todayDate={this.state.todayDate}
poolContext={this.state.poolContext}
isPoolOpenOn={this._isPoolOpenOn}
onClickPopoverStartDateCallback={this.onClickPopoverStartDateCallback}
onClickPopoverEndDateCallback={this.onClickPopoverEndDateCallback}
changeSelectedDate={this.changeSelectedDate}
selectedDate={this.state.selectedDate}
isWithinAdvanceDaysPeriod={this._isWithinAdvanceDaysPeriod}
getHoliday={this.getHoliday}
/>
)
}
return content
},
render() {
const errors = this.getErrors()
return (
<div>
<div className="modal-header row">
<div className="col3of5">
<h2 className="headline-l">{_jed('Add to order')}</h2>
<h3 className="headline-m light">
{this.props.model.product} {this.props.model.version}
</h3>
</div>
<div className="col2of5 text-align-right">
<div className="modal-close">{_jed('Cancel')}</div>
{this.renderAddButton(errors)}
</div>
</div>
{!this.state.isLoading && this._renderErrors(errors)}
<div className="modal-body" style={{ maxHeight: '895.4px' }}>
<form className="padding-inset-m">
<div className="" id="booking-calendar-controls">
<div className="col5of8 float-right">
<div className="row grey padding-bottom-xxs">
<div className="col1of2">
<div className="col1of2 padding-right-xs text-align-left">
<div className="row">
<span>{_jed('Start date')}</span>
<a
className="grey fa fa-eye position-absolute-right padding-right-xxs"
id="jump-to-start-date"
onClick={this.jumpToStartDate}
/>
</div>
</div>
<div className="col1of2 padding-right-xs text-align-left">
<div className="row">
<span>{_jed('End date')}</span>
<a
className="grey fa fa-eye position-absolute-right padding-right-xxs"
id="jump-to-end-date"
onClick={this.jumpToEndDate}
/>
</div>
</div>
</div>
<div className="col1of2">
<div className="col2of8 text-align-left">{_jed('Quantity')}</div>
<div className="col6of8 padding-left-xs text-align-left">
{_jed('Inventory pool')}
</div>
</div>
</div>
<div className="row">
<div className="col1of2">
<div className="col1of2 padding-right-xs">
<DateInput
id="booking-calendar-start-date"
dateString={this.state.startDate.format(i18n.date.L)}
onChangeCallback={this._changeStartDate}
/>
</div>
<div className="col1of2 padding-right-xs">
<DateInput
id="booking-calendar-end-date"
dateString={this.state.endDate.format(i18n.date.L)}
onChangeCallback={this._changeEndDate}
/>
</div>
</div>
<div className="col1of2">
<div className="col2of8">
<input
autoComplete="off"
className="text-align-center"
id="booking-calendar-quantity"
type="number"
max={this.state.poolContext.total_borrowable}
defaultValue={this.state.quantity}
onChange={this._changeQuantity}
/>
</div>
<div className="col6of8 padding-left-xs">
<select
autoComplete="off"
className="min-width-full text-ellipsis"
id="booking-calendar-inventory-pool"
value={this.state.poolContext.inventory_pool.id}
onChange={this._changeInventoryPool}>
{_.map(this.props.inventoryPools, (ipContext, key) => {
return (
<option
key={key}
data-id={ipContext.inventory_pool.id}
value={ipContext.inventory_pool.id}>
{ipContext.inventory_pool.name} (max. {ipContext.total_borrowable})
</option>
)
})}
</select>
</div>
</div>
</div>
</div>
</div>
<div className="booking-calendar padding-top-xs fc fc-ltr" id="booking-calendar">
<CalendarControls
startDate={this.state.startDate}
endDate={this.state.endDate}
firstDateOfCurrentMonth={this.state.firstDateOfCurrentMonth}
nextMonthCallback={this._goToNextMonth}
previousMonthCallback={this._goToPreviousMonth}
previousMonthExists={
(this.state.firstDateOfCurrentMonth.year() > this.state.todayDate.year()) ||
(this.state.firstDateOfCurrentMonth.month() != this.state.todayDate.month())
}
/>
{this.renderContent()}
</div>
</form>
</div>
<div className="modal-footer" />
</div>
)
}
})
export default BorrowBookingCalendar
|
src/App.js
|
sadist007/aladon
|
import React, { Component } from 'react';
import './App.scss';
class App extends Component {
constructor (props) {
super(props);
this.state = this.getInitialState();
}
getInitialState () {
return {}
}
render () {
return (
<div className="container-fluid">
<h4 data-selenium-id="wpng-header-prefix">6-2</h4>
<h2 data-selenium-id="wpng-header-title">Apply Inventory Cost Flow Methods and Discuss Their Financial Effects</h2>
</div>
);
}
}
export default App;
|
src/js/wpecp-bind-editors.js
|
kfwebdev/wp-editor-comments-plus
|
'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
var $ = jQuery;
function bindCancelClick(editor, settings) {
editor.windowManager.windows[0].on('click', function(event){
const clickText = $(event.target).text().toLowerCase();
if (clickText === 'cancel') {
$.ajax({
url: wpecp.globals.ajaxUrl,
type: 'post',
data: $.param({
action: wpecp.globals.imageUploadCancelAction,
attachmentId: settings.attachmentId,
postId: settings.postId,
security: settings.security
})
});
}
});
}
var wpecpBindEditors = function() {
// include edit component
wpecp.Edit = require( '../components/edit/edit' );
// include delete component
wpecp.Delete = require( '../components/delete/delete' );
// include editor component
wpecp.Editor = require( '../components/editor/editor' );
wpecp.bindCancelClick = bindCancelClick;
// bind button components
$( wpecp.globals.wpecp_id_comment_reply ).each(function(){
const $editButton = $(this).siblings('.wpecp-edit'),
$deleteButton = $(this).siblings('.wpecp-delete');
$(this).addClass(`${wpecp.globals.wpecp_css_button} ${wpecp.globals.wpecp_css_reply_button}`);
if ($editButton.length) {
const commentId = $editButton.data( wpecp.globals.wpecp_css_comment_id ),
editId = wpecp.globals.wpecp_css_edit + commentId,
editorId = wpecp.globals.wpecp_css_editor + commentId;
ReactDOM.render(
<wpecp.Edit
wpecpGlobals={ wpecp.globals }
commentId={ commentId }
editId={ editId }
editorId={ editorId }
/>,
$editButton[0]
);
}
if ($deleteButton.length) {
const commentId = $deleteButton.data( wpecp.globals.wpecp_css_comment_id ),
deleteId = wpecp.globals.wpecp_css_delete + commentId,
deleteNonce = $deleteButton.data( wpecp.globals.wpecp_css_nonce );
ReactDOM.render(
<wpecp.Delete
wpecpGlobals={ wpecp.globals }
commentId={ commentId }
deleteId={ deleteId }
deleteNonce={ deleteNonce }
/>,
$deleteButton[0]
);
}
});
// bind editor components
$( '.' + wpecp.globals.wpecp_css_editor ).each(function(){
let commentId = $( this ).data( wpecp.globals.wpecp_css_comment_id ),
contentId = wpecp.globals.wpecp_css_comment_content + commentId,
editId = wpecp.globals.wpecp_css_edit + commentId,
editorId = wpecp.globals.wpecp_css_editor + commentId,
imageUploadNonce = $( this ).data( wpecp.globals.wpecp_image_upload_nonce ),
postId = $( this ).data( wpecp.globals.wpecp_css_post_id ),
updateNonce = $( this ).data( wpecp.globals.wpecp_css_nonce );
ReactDOM.render(
<wpecp.Editor
commentId={ commentId }
contentId={ contentId }
editId={ editId }
editorId={ editorId }
imageUploadNonce={ imageUploadNonce }
postId={ postId }
updateNonce={ updateNonce }
wpecpGlobals={ wpecp.globals }
/>,
this
);
});
};
export default wpecpBindEditors;
|
src/List/ListItemIcon.spec.js
|
dsslimshaddy/material-ui
|
// @flow
import React from 'react';
import { assert } from 'chai';
import { createShallow, getClasses } from '../test-utils';
import ListItemIcon from './ListItemIcon';
describe('<ListItemIcon />', () => {
let shallow;
let classes;
before(() => {
shallow = createShallow();
classes = getClasses(
<ListItemIcon>
<span />
</ListItemIcon>,
);
});
it('should render a span', () => {
const wrapper = shallow(
<ListItemIcon>
<span />
</ListItemIcon>,
);
assert.strictEqual(wrapper.name(), 'span');
});
it('should render with the user and root classes', () => {
const wrapper = shallow(
<ListItemIcon className="foo">
<span className="bar" />
</ListItemIcon>,
);
assert.strictEqual(wrapper.hasClass('foo'), true, 'should have the "foo" class');
assert.strictEqual(wrapper.hasClass('bar'), true, 'should have the "bar" class');
assert.strictEqual(wrapper.hasClass(classes.root), true);
});
});
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/Generators.js
|
amido/create-react-app
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function* load(limit) {
let i = 1;
while (i <= limit) {
yield { id: i, name: i };
i++;
}
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
componentDidMount() {
const users = [];
for (let user of load(4)) {
users.push(user);
}
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-generators">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
server/sonar-web/src/main/js/apps/settings/licenses/__tests__/LicensesList-test.js
|
lbndev/sonarqube
|
/*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
import { shallow, mount } from 'enzyme';
import LicensesList from '../LicensesList';
import LicenseRowContainer from '../LicenseRowContainer';
it('should render', () => {
const list = shallow(<LicensesList licenses={[]} fetchLicenses={jest.fn()} />);
expect(list.is('table')).toBe(true);
});
it('should fetch licenses', () => {
const fetchLicenses = jest.fn(() => Promise.resolve());
mount(<LicensesList licenses={[]} fetchLicenses={fetchLicenses} />);
expect(fetchLicenses).toBeCalled();
});
it('should render rows', () => {
const list = shallow(<LicensesList licenses={['foo', 'bar']} fetchLicenses={jest.fn()} />);
expect(list.find(LicenseRowContainer).length).toBe(2);
expect(list.find(LicenseRowContainer).at(0).prop('licenseKey')).toBe('foo');
expect(list.find(LicenseRowContainer).at(1).prop('licenseKey')).toBe('bar');
});
|
new-lamassu-admin/src/pages/UserManagement/modals/FIDOModal.js
|
naconner/lamassu-server
|
import { makeStyles } from '@material-ui/core/styles'
import React from 'react'
import Modal from 'src/components/Modal'
import { Button } from 'src/components/buttons'
import { Info2, P } from 'src/components/typography'
import styles from '../UserManagement.styles'
const useStyles = makeStyles(styles)
const ChangeRoleModal = ({ state, dispatch }) => {
const classes = useStyles()
const handleClose = () => {
dispatch({
type: 'close',
payload: 'showFIDOModal'
})
}
return (
<Modal
closeOnBackdropClick={true}
width={450}
height={275}
handleClose={handleClose}
open={state.showFIDOModal}>
<Info2 className={classes.modalTitle}>About FIDO authentication</Info2>
<P className={classes.info}>
This feature is only available for websites with configured domains, and
we detected that a domain is not configured at the moment.
</P>
<P>
Make sure that a domain is configured for this website and try again
later.
</P>
<div className={classes.footer}>
<Button className={classes.submit} onClick={() => handleClose()}>
Confirm
</Button>
</div>
</Modal>
)
}
export default ChangeRoleModal
|
node_modules/react-native-svg/elements/Path.js
|
MisterZhouZhou/ReactNativeLearing
|
import React from 'react';
import PropTypes from 'prop-types';
import createReactNativeComponentClass from 'react-native/Libraries/Renderer/shims/createReactNativeComponentClass.js';
import {PathAttributes} from '../lib/attributes';
import Shape from './Shape';
import {pathProps} from '../lib/props';
import extractProps from '../lib/extract/extractProps';
export default class extends Shape {
static displayName = 'Path';
static propTypes = {
...pathProps,
d: PropTypes.string.isRequired
};
setNativeProps = (...args) => {
this.root.setNativeProps(...args);
};
render() {
let props = this.props;
return (
<RNSVGPath
ref={ele => {this.root = ele;}}
{...extractProps(props, this)}
d={props.d}
/>
);
}
}
const RNSVGPath = createReactNativeComponentClass({
validAttributes: PathAttributes,
uiViewClassName: 'RNSVGPath'
});
|
src/components/common/svg-icons/notification/airline-seat-legroom-extra.js
|
abzfarah/Pearson.NAPLAN.GnomeH
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationAirlineSeatLegroomExtra = (props) => (
<SvgIcon {...props}>
<path d="M4 12V3H2v9c0 2.76 2.24 5 5 5h6v-2H7c-1.66 0-3-1.34-3-3zm18.83 5.24c-.38-.72-1.29-.97-2.03-.63l-1.09.5-3.41-6.98c-.34-.68-1.03-1.12-1.79-1.12L11 9V3H5v8c0 1.66 1.34 3 3 3h7l3.41 7 3.72-1.7c.77-.36 1.1-1.3.7-2.06z"/>
</SvgIcon>
);
NotificationAirlineSeatLegroomExtra = pure(NotificationAirlineSeatLegroomExtra);
NotificationAirlineSeatLegroomExtra.displayName = 'NotificationAirlineSeatLegroomExtra';
NotificationAirlineSeatLegroomExtra.muiName = 'SvgIcon';
export default NotificationAirlineSeatLegroomExtra;
|
test/BackgroundImage.spec.js
|
itsolutions-dev/react-styled-ui
|
import React from 'react';
import ReactTestRenderer from 'react-test-renderer';
import 'styled-components-test-utils/lib/jest';
import theme from '../src/theme';
import BackgroundImage from '../src/BackgroundImage';
describe('BackgroundImage', () => {
test('should render a BackgroundImage', () => {
const component = ReactTestRenderer.create(<BackgroundImage theme={theme} />);
expect(component).toBeDefined();
expect(component.toJSON()).toMatchSnapshot();
});
test('should have a div tag', () => {
const component = ReactTestRenderer.create(<BackgroundImage theme={theme} />).toJSON();
expect(component.type).toEqual('div');
});
test('should handle a src prop', () => {
const component = ReactTestRenderer.create(
<BackgroundImage
theme={theme}
src="http://localhost:8080/image.png"
/>,
);
expect(component).toHaveStyleRule('background-image', 'url(http://localhost:8080/image.png)');
});
test('should have a default ratio', () => {
const component = ReactTestRenderer.create(
<BackgroundImage
theme={theme}
/>,
);
expect(component).toHaveStyleRule('padding-bottom', '100%');
});
test('should handle a ratio prop', () => {
const component = ReactTestRenderer.create(
<BackgroundImage
theme={theme}
ratio={1 / 2}
/>,
);
expect(component).toHaveStyleRule('padding-bottom', '50%');
});
});
|
versions/v1/components/Debugger/Inspector/JSONInput/index.js
|
cerebral/cerebral-debugger-prototype
|
import React from 'react';
import styles from './styles.css';
import {connect} from 'cerebral-view-react';
import {
isObject,
isArray
} from 'common/utils';
@connect()
class JSONInput extends React.Component {
constructor(props) {
super(props);
this.state = {
isValid: true,
value: this.props.value,
initialValue: this.props.value
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
componentDidMount(prevProps, prevState) {
this.refs.input.select();
}
onChange(event) {
let value = event.target.value;
let isValid = true;
let parsedValue = value;
try {
parsedValue = JSON.parse(value);
} catch (e) {
isValid = value.length ? true : false;
}
if (isObject(parsedValue) || isArray(parsedValue)) {
return;
} else {
value = parsedValue;
}
this.setState({
value,
isValid
});
}
onBlur() {
this.setState({
value: this.state.initialValue
});
this.props.onBlur();
}
onSubmit(event) {
event.preventDefault();
this.props.onSubmit(this.state.value);
}
render() {
return (
<form style={{display: 'inline'}} onSubmit={this.onSubmit}>
<input
ref="input"
type="Text"
autoFocus
onKeyDown={(event) => {event.keyCode === 27 && this.onBlur()}}
className={this.state.isValid ? styles.input : styles.invalidInput}
value={String(this.state.value)}
onChange={this.onChange}
onBlur={() => this.onBlur()}
/>
</form>
);
}
}
export default JSONInput;
|
React Native/Demos/nearby/Nearby/views/toilet.js
|
AngryLi/ResourceSummary
|
/**
* Created by Liyazhou on 16/9/6.
*/
import React from 'react';
import {
View,
StyleSheet,
} from 'react-native';
export default class Toilet extends React.Component {
render() {
return (
<View></View>
)
}
}
const styles= StyleSheet.create({
})
|
app/components/HorizonalBarChart/Bar.js
|
thuy616/react-d3-charts
|
import React from 'react';
import PropTypes from 'prop-types';
type Props = {
data: PropTypes.object.isRequired,
xScale: PropTypes.func.isRequired,
yScale: PropTypes.func.isRequired,
colorScale: PropTypes.func.isRequired
}
export default ({
data,
xScale,
yScale,
colorScale
}: Props) => {
return (
<g className="horizontal-bar">>
<rect y={yScale(data.name)} height={yScale.rangeBand()} x={0} width={xScale(data.value)} style={{ fill: `${colorScale(data.name)}`}} />
<text className="horizontal-bar-text" y={yScale(data.name) + yScale.rangeBand() / 2 + 4} x={xScale(data.value) + 25} textAnchor="end">{data.value}</text>
</g>
);
};
|
src/Input.js
|
cat-react/form
|
import React from 'react';
import PropTypes from 'prop-types';
import autoBind from 'react-autobind';
import Form from './Form';
export default function (WrappedComponent) {
class Input extends React.Component {
constructor(props, context) {
super(props, context);
this.changeValueTimer = null;
this.dependencies = [];
for (let dependency of props.dependencies) {
this.addDependency(dependency);
}
this.state = {
value: props.value,
pristine: true,
valid: false,
messages: []
};
autoBind(this);
for (let validation in props.validations) {
const validationRule = Form.validationRules[validation];
if (validationRule && validationRule.createsDependencies) {
if (!Array.isArray(props.validations[validation])) {
this.addDependency(props.validations[validation]);
} else {
for (let dependency of props.validations[validation]) {
this.addDependency(dependency);
}
}
}
}
}
componentWillMount() {
this.context._reactForm.attach(this);
}
componentWillUnmount() {
this.context._reactForm.detach(this);
}
addDependency(dependency) {
if (dependency === this.getName()) {
throw new Error('An input cannot have itself as an dependency. Check your validation rules.')
}
if (this.dependencies.indexOf(dependency) < 0) {
this.dependencies.push(dependency);
}
}
getName() {
return this.props.name;
}
hasName(name) {
return this.props.name === name;
}
isRequired() {
return !!(this.props.validations && this.props.validations.isRequired);
}
isPristine() {
return this.state.pristine;
}
isValid() {
return this.state.valid;
}
getValue() {
return this.state.value;
}
setValue(value, suppressTouch) {
clearTimeout(this.changeValueTimer);
this.context._reactForm.addToValidationQueue(this);
this.setState({
value: value
}, () => {
const startValidation = () => {
if (!suppressTouch) {
this.touch();
}
this.context._reactForm.startValidation();
};
let timeout = this.props.changeValueTimeout;
if (timeout !== 0 && !timeout) {
timeout = this.context._reactForm.changeValueTimeout;
}
if (timeout > 0) {
this.changeValueTimer = setTimeout(startValidation, timeout);
} else {
startValidation();
}
});
}
getMessages() {
return this.state.messages;
}
touch() {
if (this.isPristine()) {
this.setState({
pristine: false
});
}
}
async validate() {
return new Promise((resolve) => {
this.runValidationRules(resolve);
});
}
async runValidationRules(resolve) {
let messages = [];
let allValid = true;
if (this.isRequired() || this.getValue()) {
for (let ruleName in this.props.validations) {
const ruleConditions = this.props.validations[ruleName];
if (ruleConditions) { // only execute validations if the ruleConditions are valid
const valid = await this.runValidationRule(ruleName);
if (!valid) {
const isWarning = this.props.warnings.indexOf(ruleName) > -1;
if (!isWarning) {
allValid = false;
}
if (this.props.messages && this.props.messages[ruleName]) {
// TODO: add support for arguments, maybe even different errormessages per validator?
messages.push(this.props.messages[ruleName]);
}
}
}
}
}
this.setState({
valid: allValid,
messages: messages
}, () => {
resolve(allValid);
});
}
async runValidationRule(ruleName) {
const ruleConditions = this.props.validations[ruleName];
let valid = true;
if (Form.validationRules[ruleName]) {
valid = await Form.validationRules[ruleName](this.context._reactForm.getValues(), this.getValue(), ruleConditions);
} else if (typeof ruleConditions === 'function') {
valid = await ruleConditions(this.context._reactForm.getValues(), this.getValue());
} else if (ruleConditions instanceof Array) {
valid = await ruleConditions[0](this.context._reactForm.getValues(), this.getValue(), ruleConditions[1]);
}
return valid;
}
reset(value) {
if (value || value === '' || value === null) {
this.setValue(value, true);
} else {
this.setValue(this.props.value, true);
}
this.setState({
pristine: true
});
}
render() {
const props = {
...this.props,
isRequired: this.isRequired,
isPristine: this.isPristine,
isValid: this.isValid,
getValue: this.getValue,
setValue: this.setValue,
getMessages: this.getMessages,
touch: this.touch
};
return (
<WrappedComponent {...props}/>
);
}
}
Input.propTypes = {
value: PropTypes.any,
name: PropTypes.string.isRequired,
validations: PropTypes.object,
warnings: PropTypes.arrayOf(PropTypes.string),
messages: PropTypes.object,
dependencies: PropTypes.arrayOf(PropTypes.string),
changeValueTimeout: PropTypes.number
};
Input.defaultProps = {
warnings: [],
dependencies: []
};
Input.contextTypes = {
_reactForm: PropTypes.object
};
return Input;
}
|
react/features/settings/components/web/audio/AudioSettingsPopup.js
|
gpolitis/jitsi-meet
|
// @flow
import InlineDialog from '@atlaskit/inline-dialog';
import React from 'react';
import { areAudioLevelsEnabled } from '../../../../base/config/functions';
import {
getAudioInputDeviceData,
getAudioOutputDeviceData,
setAudioInputDeviceAndUpdateSettings,
setAudioOutputDevice as setAudioOutputDeviceAction
} from '../../../../base/devices';
import { connect } from '../../../../base/redux';
import { SMALL_MOBILE_WIDTH } from '../../../../base/responsive-ui/constants';
import {
getCurrentMicDeviceId,
getCurrentOutputDeviceId
} from '../../../../base/settings';
import { toggleAudioSettings } from '../../../actions';
import { getAudioSettingsVisibility } from '../../../functions';
import AudioSettingsContent, { type Props as AudioSettingsContentProps } from './AudioSettingsContent';
type Props = AudioSettingsContentProps & {
/**
* Component's children (the audio button).
*/
children: React$Node,
/**
* Flag controlling the visibility of the popup.
*/
isOpen: boolean,
/**
* Callback executed when the popup closes.
*/
onClose: Function,
/**
* The popup placement enum value.
*/
popupPlacement: string
}
/**
* Popup with audio settings.
*
* @returns {ReactElement}
*/
function AudioSettingsPopup({
children,
currentMicDeviceId,
currentOutputDeviceId,
isOpen,
microphoneDevices,
setAudioInputDevice,
setAudioOutputDevice,
onClose,
outputDevices,
popupPlacement,
measureAudioLevels
}: Props) {
return (
<div className = 'audio-preview'>
<InlineDialog
content = { <AudioSettingsContent
currentMicDeviceId = { currentMicDeviceId }
currentOutputDeviceId = { currentOutputDeviceId }
measureAudioLevels = { measureAudioLevels }
microphoneDevices = { microphoneDevices }
outputDevices = { outputDevices }
setAudioInputDevice = { setAudioInputDevice }
setAudioOutputDevice = { setAudioOutputDevice } /> }
isOpen = { isOpen }
onClose = { onClose }
placement = { popupPlacement }>
{children}
</InlineDialog>
</div>
);
}
/**
* Function that maps parts of Redux state tree into component props.
*
* @param {Object} state - Redux state.
* @returns {Object}
*/
function mapStateToProps(state) {
const { clientWidth } = state['features/base/responsive-ui'];
return {
popupPlacement: clientWidth <= SMALL_MOBILE_WIDTH ? 'auto' : 'top-start',
currentMicDeviceId: getCurrentMicDeviceId(state),
currentOutputDeviceId: getCurrentOutputDeviceId(state),
isOpen: getAudioSettingsVisibility(state),
microphoneDevices: getAudioInputDeviceData(state),
outputDevices: getAudioOutputDeviceData(state),
measureAudioLevels: areAudioLevelsEnabled(state)
};
}
const mapDispatchToProps = {
onClose: toggleAudioSettings,
setAudioInputDevice: setAudioInputDeviceAndUpdateSettings,
setAudioOutputDevice: setAudioOutputDeviceAction
};
export default connect(mapStateToProps, mapDispatchToProps)(AudioSettingsPopup);
|
src/svg-icons/device/signal-wifi-3-bar-lock.js
|
skarnecki/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalWifi3BarLock = (props) => (
<SvgIcon {...props}>
<path opacity=".3" d="M12 3C5.3 3 .8 6.7.4 7l3.2 3.9L12 21.5l3.5-4.3v-2.6c0-2.2 1.4-4 3.3-4.7.3-.1.5-.2.8-.2.3-.1.6-.1.9-.1.4 0 .7 0 1 .1L23.6 7c-.4-.3-4.9-4-11.6-4z"/><path d="M23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16zm-10 5.5l3.5-4.3v-2.6c0-2.2 1.4-4 3.3-4.7C17.3 9 14.9 8 12 8c-4.8 0-8 2.6-8.5 2.9"/>
</SvgIcon>
);
DeviceSignalWifi3BarLock = pure(DeviceSignalWifi3BarLock);
DeviceSignalWifi3BarLock.displayName = 'DeviceSignalWifi3BarLock';
export default DeviceSignalWifi3BarLock;
|
__tests__/index.android.js
|
david1820/react-native-boilerplate
|
/* eslint-disable */
import 'react-native';
import React from 'react';
import Index from '../index.android.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
app/components/ImageComponent.js
|
fakob/electron-test-v003
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
// import mpLogo from './../img/MoviePrint_Logo_v002_128.jpg';
// import base64ArrayBuffer from './../utils/base64ArrayBuffer'
let temp = [];
class ImageComponent extends Component {
componentDidMount() {
const { store } = this.context;
this.unsubscribe = store.subscribe(() => this.forceUpdate());
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
const { store } = this.context;
const state = store.getState();
return (
<div>
<img src={temp} alt="mpLogo" width="300px" height="300px" />
</div>
);
}
}
ImageComponent.contextTypes = {
store: PropTypes.object
};
export default ImageComponent;
|
example_app/src/components/withViewport.js
|
blueberryapps/radium-bootstrap-grid
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React, { Component } from 'react'; // eslint-disable-line no-unused-vars
import EventEmitter from 'eventemitter3';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
let EE;
let viewport = { width: 1366, height: 768 }; // Default size for server-side rendering
const RESIZE_EVENT = 'resize';
function handleWindowResize() {
if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) {
viewport = { width: window.innerWidth, height: window.innerHeight };
EE.emit(RESIZE_EVENT, viewport);
}
}
function withViewport(ComposedComponent) {
return class WithViewport extends Component {
constructor() {
super();
this.state = {
viewport: canUseDOM ? { width: window.innerWidth, height: window.innerHeight } : viewport,
};
}
componentDidMount() {
if (!EE) {
EE = new EventEmitter();
window.addEventListener('resize', handleWindowResize);
window.addEventListener('orientationchange', handleWindowResize);
}
EE.on(RESIZE_EVENT, this.handleResize, this);
}
componentWillUnmount() {
EE.removeListener(RESIZE_EVENT, this.handleResize, this);
if (!EE.listeners(RESIZE_EVENT, true)) {
window.removeEventListener('resize', handleWindowResize);
window.removeEventListener('orientationchange', handleWindowResize);
EE = null;
}
}
render() {
return <ComposedComponent {...this.props} viewport={this.state.viewport} />;
}
handleResize(value) {
this.setState({ viewport: value }); // eslint-disable-line react/no-set-state
}
};
}
export default withViewport;
|
src/index.js
|
irla/react-cv
|
//import 'bootstrap/scss/bootstrap.scss'
//import 'font-awesome/scss/font-awesome.scss'
import 'bootstrap/dist/css/bootstrap.css'
import 'font-awesome/css/font-awesome.css'
import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import Application from './containers/Application'
const render = Component => {
ReactDOM.render(
<AppContainer>
<Component />
</AppContainer>,
document.getElementById('root')
)
}
render(Application)
if (module.hot) {
module.hot.accept('./containers/Application', () => { render(Application) })
}
|
view/dva/src/routes/HomePage.js
|
xuzhenyang/ZeroCola
|
import React from 'react';
import { connect } from 'dva';
import MyLayout from '../components/MyLayout';
function HomePage({ children }) {
return (
<div>
<MyLayout>
{children}
</MyLayout>
</div>
);
}
function mapStateToProps() {
return {};
}
export default connect(mapStateToProps)(HomePage);
|
src/renderer/components/MapFilter/ObservationDialog/DateTimeField.js
|
digidem/ecuador-map-editor
|
// @flow
import React from 'react'
import { DateTimePicker } from '@material-ui/pickers'
type Props = {
value: Date | void,
onChange: (string | void) => any
}
const DateTimeField = ({ value, onChange, ...otherProps }: Props) => {
return (
<DateTimePicker
fullWidth
variant='inline'
inputVariant='outlined'
margin='normal'
value={
// DateTimePicker shows the current date if value is undefined. To show
// it as empty, value needs to be null
value === undefined ? null : value
}
onChange={date =>
date === undefined ? onChange() : onChange(date.toISOString())
}
{...otherProps}
/>
)
}
export default DateTimeField
|
src/svg-icons/communication/chat-bubble-outline.js
|
verdan/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationChatBubbleOutline = (props) => (
<SvgIcon {...props}>
<path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>
</SvgIcon>
);
CommunicationChatBubbleOutline = pure(CommunicationChatBubbleOutline);
CommunicationChatBubbleOutline.displayName = 'CommunicationChatBubbleOutline';
CommunicationChatBubbleOutline.muiName = 'SvgIcon';
export default CommunicationChatBubbleOutline;
|
src/app/App.js
|
crisu83/timebox
|
import React from 'react';
import store from './store';
import AppConstants from './constants';
import TimerConstants from '../timer/constants';
import Header from '../header/Header';
import Picker from '../picker/Picker';
import Timer from '../timer/Timer';
import Footer from '../footer/Footer';
class App extends React.Component {
componentDidMount() {
this.unsubscribe = store.subscribe(() => {
this.forceUpdate();
});
}
componentWillUnmount() {
this.unsubscribe();
}
getClassNames() {
const state = store.getState();
let classNames = ['timebox'];
switch (state.name) {
case AppConstants.STATE_RUNNING:
classNames.push('state-running');
break;
case AppConstants.STATE_DONE:
classNames.push('state-done');
break;
case AppConstants.STATE_DEFAULT:
default:
classNames.push('state-default');
break;
}
return classNames.join(' ');
}
render() {
return (
<div className={this.getClassNames()}>
<Header />
<div className="centered">
<Picker buttons={this.props.buttons} />
<Timer />
</div>
<Footer />
</div>
);
}
}
export default App;
|
src/parser/warlock/affliction/modules/talents/Haunt.js
|
ronaldpereira/WoWAnalyzer
|
import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import Enemies from 'parser/shared/modules/Enemies';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import { formatPercentage, formatThousands, formatNumber } from 'common/format';
import Statistic from 'interface/statistics/Statistic';
import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER';
import { UNSTABLE_AFFLICTION_DEBUFFS } from '../../constants';
const HAUNT_DAMAGE_BONUS = 0.1;
class Haunt extends Analyzer {
static dependencies = {
enemies: Enemies,
};
bonusDmg = 0;
totalTicks = 0;
buffedTicks = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.HAUNT_TALENT.id);
this.addEventListener(Events.damage.by(SELECTED_PLAYER), this.onDamage);
}
onDamage(event) {
const target = this.enemies.getEntity(event);
if (!target) {
return;
}
const hasHaunt = target.hasBuff(SPELLS.HAUNT_TALENT.id, event.timestamp);
if (UNSTABLE_AFFLICTION_DEBUFFS.some(spell => spell.id === event.ability.guid)) {
this.totalTicks += 1;
if (hasHaunt) {
this.buffedTicks += 1;
}
}
if (hasHaunt) {
this.bonusDmg += calculateEffectiveDamage(event, HAUNT_DAMAGE_BONUS);
}
}
get uptime() {
return this.enemies.getBuffUptime(SPELLS.HAUNT_TALENT.id) / this.owner.fightDuration;
}
get dps() {
return this.bonusDmg / this.owner.fightDuration * 1000;
}
get suggestionThresholds() {
return {
actual: this.uptime,
isLessThan: {
minor: 0.9,
average: 0.85,
major: 0.75,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.suggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest(
<>
Your <SpellLink id={SPELLS.HAUNT_TALENT.id} /> debuff uptime is too low. While it's usually not possible to get 100% uptime due to travel and cast time, you should aim for as much uptime on the debuff as possible.
</>,
)
.icon(SPELLS.HAUNT_TALENT.icon)
.actual(`${formatPercentage(actual)}% Haunt uptime.`)
.recommended(`> ${formatPercentage(recommended)}% is recommended`);
});
}
statistic() {
const buffedTicksPercentage = (this.buffedTicks / this.totalTicks) || 1;
return (
<Statistic
position={STATISTIC_ORDER.OPTIONAL(4)}
size="flexible"
tooltip={(
<>
{formatThousands(this.bonusDmg)} bonus damage<br />
You buffed {formatPercentage(buffedTicksPercentage)} % of your Unstable Affliction ticks with Haunt.
</>
)}
>
<div className="pad">
<label><SpellLink id={SPELLS.HAUNT_TALENT.id} /></label>
<div className="flex">
<div className="flex-main value">
{formatPercentage(this.uptime)} % <small>uptime</small>
</div>
</div>
<div className="flex">
<div className="flex-main value">
{formatNumber(this.dps)} DPS <small>{formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.bonusDmg))} % of total</small>
</div>
</div>
</div>
</Statistic>
);
}
}
export default Haunt;
|
packages/node_modules/@webex/react-component-button/src/index.js
|
ciscospark/react-ciscospark
|
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Icon from '@webex/react-component-icon';
import styles from './styles.css';
const propTypes = {
accessibilityLabel: PropTypes.string,
buttonClassName: PropTypes.string,
children: PropTypes.node,
iconColor: PropTypes.string,
iconType: PropTypes.string,
label: PropTypes.string,
labelPosition: PropTypes.string,
onClick: PropTypes.func.isRequired,
title: PropTypes.string
};
const defaultProps = {
accessibilityLabel: '',
buttonClassName: '',
children: undefined,
iconColor: 'white-100',
iconType: '',
label: '',
labelPosition: '',
title: ''
};
function Button(props) {
const {
accessibilityLabel,
buttonClassName,
children,
iconColor,
iconType,
label,
labelPosition,
onClick,
title
} = props;
const ariaLabel = accessibilityLabel || label || title;
function handleKeyPress(e) {
if (e.key === 'Enter' || e.key === ' ') {
onClick();
}
}
return (
<div className={classNames('webex-button-container', styles.buttonContainer)}>
<button
aria-label={ariaLabel}
className={classNames('webex-button', styles.button, buttonClassName)}
onClick={onClick}
onKeyPress={handleKeyPress}
>
{
iconType &&
<div className={classNames('webex-button-icon', styles.buttonIcon)} >
<Icon color={iconColor} title={title} type={iconType} />
</div>
}
{
labelPosition !== 'bottom' &&
label
}
{children}
</button>
{
label && labelPosition === 'bottom' &&
<div className={classNames('webex-label', styles.label, styles.labelBottom)}>{label}</div>
}
</div>
);
}
Button.propTypes = propTypes;
Button.defaultProps = defaultProps;
export default Button;
|
src/components/RadioList.js
|
angeloocana/angeloocana
|
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import Radio from './Radio';
import { FormattedMessage } from 'react-intl';
import { contains } from 'ramda';
import { InvisibleSpan } from './Invisible';
const Ul = styled.ul`
display: flex;
flex-flow: row wrap;
justify-content: start;
margin: 0 0 1rem 0;
padding: 0;
`;
export const getCbListFromArray = (items, checkedItems) => {
return items.map(i => ({
label: i,
value: i,
checked: contains(i, checkedItems)
}));
};
const RadioList = (props) => {
return (
<fieldset>
<legend>
<FormattedMessage id={props.i18n.title}>
{(txt) => (
<InvisibleSpan>
{txt}
</InvisibleSpan>
)}
</FormattedMessage>
</legend>
<Ul>
{props.items.map(item => (
<li>
<Radio
value={item.value}
label={item.label}
check={props.check}
checked={item.checked}
/>
</li>
))}
</Ul>
</fieldset>
);
};
export const i18nPropTypes = PropTypes.shape({
title: PropTypes.string.isRequired
});
RadioList.propTypes = {
items: PropTypes.arrayOf(PropTypes.shape({
value: PropTypes.any.isRequired,
label: PropTypes.string.isRequired,
checked: PropTypes.bool.isRequired
})).isRequired,
check: PropTypes.func.isRequired,
i18n: i18nPropTypes
};
export default RadioList;
|
src/pages/404.js
|
angeloocana/tic-tac-toe-ai
|
import React from 'react';
class FourOFour extends React.PureComponent {
render() {
return (
<div>
<h1>Page not found</h1>
</div>
);
}
}
export default FourOFour;
|
node_modules/react-native/local-cli/templates/HelloWorld/index.android.js
|
RahulDesai92/PHR
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class HelloWorld extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
|
packages/icons/src/md/av/CallToAction.js
|
suitejs/suitejs
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdCallToAction(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M42 6c2.2 0 4 1.8 4 4v28c0 2.2-1.8 4-4 4H6c-2.2 0-4-1.8-4-4V10c0-2.2 1.8-4 4-4h36zm0 32v-6H6v6h36z" />
</IconBase>
);
}
export default MdCallToAction;
|
public/src/components/Layout/Layout.react.js
|
hugonasciutti/Challenge
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { FlatButton } from 'material-ui';
import AppBar from 'material-ui/AppBar';
import styles from './Layout.scss';
import Icon from '../../../icons/icons';
class _Layout extends React.Component {
render() {
return (
<div className={styles.LayoutRoot}>
<div className={styles.LayoutHeader}>
<AppBar
title="Hugo Nasciutti App"
iconElementRight={<FlatButton label="About" href="http://localhost:3000/about" />}
/>
</div>
<div className={styles.LayoutContent}>
{this.props.children}
</div>
<div className={styles.LayoutFooter}>
<div className={styles.footer1}>
<a href="https://dribbble.com/">
<Icon className={styles.dribbbleLogo} glyph={Icon.GLYPHS.dribbbleLogo} />
</a>
</div>
<div className={styles.footer2}>
Hugo Nasciutti © 2017
</div>
</div>
</div>
);
}
}
_Layout.propTypes = {
children: PropTypes.element.isRequired,
};
const mapStateToProps = () => ({
});
const mapActionsToProps = {
};
const Layout = connect(mapStateToProps, mapActionsToProps)(_Layout);
export default Layout;
|
src/components/course/ManageCoursePage.spec.js
|
santiaro90/pluralsight-react-redux
|
import React from 'react';
import expect from 'expect';
import { mount, shallow } from 'enzyme';
import { ManageCoursePage } from './ManageCoursePage';
describe('ManageCoursePage Component', () => {
it('sets error message when trying to save empty title', () => {
const props = {
actions: {
saveCourse() {
return Promise.resolve();
}
},
authors: [],
course: { id: '', watchHref: '', title: '', authorId: '', length: '', category: '' }
};
const wrapper = mount(<ManageCoursePage {...props} />);
const saveButton = wrapper.find('input').last();
expect(saveButton.prop('type')).toBe('submit');
saveButton.simulate('click');
expect(wrapper.state().errors.title).toBe('Title must be at least 5 characters.');
});
});
|
src/svg-icons/places/casino.js
|
manchesergit/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesCasino = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM7.5 18c-.83 0-1.5-.67-1.5-1.5S6.67 15 7.5 15s1.5.67 1.5 1.5S8.33 18 7.5 18zm0-9C6.67 9 6 8.33 6 7.5S6.67 6 7.5 6 9 6.67 9 7.5 8.33 9 7.5 9zm4.5 4.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4.5 4.5c-.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.5zm0-9c-.83 0-1.5-.67-1.5-1.5S15.67 6 16.5 6s1.5.67 1.5 1.5S17.33 9 16.5 9z"/>
</SvgIcon>
);
PlacesCasino = pure(PlacesCasino);
PlacesCasino.displayName = 'PlacesCasino';
PlacesCasino.muiName = 'SvgIcon';
export default PlacesCasino;
|
src/app/page/order_detail.js
|
borgnix/solid-winner
|
/**
* Created by luoop on 16-7-14.
*/
import React from 'react'
import {Component} from 'react'
import call from '../api'
import update from 'immutability-helper';
import {Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table';
class OrderDetail extends Component {
constructor(props) {
super(props)
this.state = {
hasData: false
}
}
getData() {
call('OrderDetailInfo',
{orderID: "123"},
(data ,err) => {
if(data !== null){
//console.log("data: ", data)
this.orderInfo = data;
this.setState(update(this.state, {hasData: {$set: true}}));
}
}
)
}
componentWillMount() {
this.getData();
}
render() {
//console.log("this.orderInfo: ", this.orderInfo);
if(this.state.hasData) {
//console.log("this.orderInfo: ", this.orderInfo.details);
return<div>
<Table>
<TableHeader
adjustForCheckbox={false}
displaySelectAll={false}>
<TableRow>
<TableRowColumn>订单号</TableRowColumn>
<TableRowColumn>{this.orderInfo.id}</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>金额</TableRowColumn>
<TableRowColumn>{this.orderInfo.sum}</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>时间</TableRowColumn>
<TableRowColumn>{this.orderInfo.time}</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>用户</TableRowColumn>
<TableRowColumn>{this.orderInfo.custName}</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>收货地址</TableRowColumn>
<TableRowColumn>{this.orderInfo.custAddr}</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>电话</TableRowColumn>
<TableRowColumn>{this.orderInfo.custPhone}</TableRowColumn>
</TableRow>
</TableHeader>
</Table>
<Table>
<TableHeader
adjustForCheckbox={false}
displaySelectAll={false}>
<TableRow>
<TableRowColumn>商品名</TableRowColumn>
<TableRowColumn>单价</TableRowColumn>
<TableRowColumn>数量</TableRowColumn>
</TableRow>
</TableHeader>
<TableBody>
{this.orderInfo.details.map((item) => {
return
<TableRow>
<TableRowColumn>{item.name}</TableRowColumn>
<TableRowColumn>{item.unitPrice}</TableRowColumn>
<TableRowColumn>{item.amount}</TableRowColumn>
</TableRow>
})})
</TableBody>
</Table>
</div>;
}
else {
return <p> wait for me </p>;
}
}
}
export default OrderDetail;
|
pages/less.js
|
rorz/a27-site
|
import React from 'react'
import './example.less'
import Helmet from 'react-helmet'
import { config } from 'config'
export default class Less extends React.Component {
render () {
return (
<div>
<Helmet
title={`${config.siteTitle} | Hi lessy friends`}
/>
<h1
className="the-less-class"
>
Hi lessy friends
</h1>
<div className="less-nav-example">
<h2>Nav example</h2>
<ul>
<li>
<a href="#">Store</a>
</li>
<li>
<a href="#">Help</a>
</li>
<li>
<a href="#">Logout</a>
</li>
</ul>
</div>
</div>
)
}
}
|
actor-apps/app-web/src/app/components/modals/Contacts.react.js
|
luoxiaoshenghustedu/actor-platform
|
//
// Deprecated
//
import _ from 'lodash';
import React from 'react';
import { PureRenderMixin } from 'react/addons';
import ContactActionCreators from 'actions/ContactActionCreators';
import DialogActionCreators from 'actions/DialogActionCreators';
import ContactStore from 'stores/ContactStore';
import Modal from 'react-modal';
import AvatarItem from 'components/common/AvatarItem.react';
let appElement = document.getElementById('actor-web-app');
Modal.setAppElement(appElement);
let getStateFromStores = () => {
return {
contacts: ContactStore.getContacts(),
isShown: ContactStore.isContactsOpen()
};
};
class Contacts extends React.Component {
componentWillMount() {
ContactStore.addChangeListener(this._onChange);
}
componentWillUnmount() {
ContactStore.removeChangeListener(this._onChange);
}
constructor() {
super();
this._onClose = this._onClose.bind(this);
this._onChange = this._onChange.bind(this);
this.state = getStateFromStores();
}
_onChange() {
this.setState(getStateFromStores());
}
_onClose() {
ContactActionCreators.hideContactList();
}
render() {
let contacts = this.state.contacts;
let isShown = this.state.isShown;
let contactList = _.map(contacts, (contact, i) => {
return (
<Contacts.ContactItem contact={contact} key={i}/>
);
});
if (contacts !== null) {
return (
<Modal className="modal contacts"
closeTimeoutMS={150}
isOpen={isShown}>
<header className="modal__header">
<a className="modal__header__close material-icons" onClick={this._onClose}>clear</a>
<h3>Contact list</h3>
</header>
<div className="modal__body">
<ul className="contacts__list">
{contactList}
</ul>
</div>
</Modal>
);
} else {
return (null);
}
}
}
Contacts.ContactItem = React.createClass({
propTypes: {
contact: React.PropTypes.object
},
mixins: [PureRenderMixin],
_openNewPrivateCoversation() {
DialogActionCreators.selectDialogPeerUser(this.props.contact.uid);
ContactActionCreators.hideContactList();
},
render() {
let contact = this.props.contact;
return (
<li className="contacts__list__item row">
<AvatarItem image={contact.avatar}
placeholder={contact.placeholder}
size="small"
title={contact.name}/>
<div className="col-xs">
<span className="title">
{contact.name}
</span>
</div>
<div className="controls">
<a className="material-icons" onClick={this._openNewPrivateCoversation}>message</a>
</div>
</li>
);
}
});
export default Contacts;
|
examples/counter/containers/Root.js
|
phated/redux
|
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import CounterApp from './CounterApp';
import configureStore from '../store/configureStore';
const store = configureStore();
export default class Root extends Component {
render() {
return (
<Provider store={store}>
{() => <CounterApp />}
</Provider>
);
}
}
|
src/pages/about.js
|
stolinski/st2017
|
import React from 'react';
import Link from 'gatsby-link';
import Layout from '../components/Layout';
import { Title, MainWrapper } from '../components/Headings';
import { Resume, FakeButtons } from '../components/AboutStyles';
export default class About extends React.Component {
render() {
return (
<Layout {...this.props}>
<MainWrapper color="#16a085">
<Title>About</Title>
<div>
<p>Hi, I'm Scott Tolinski.</p>
<p>
I'm a Senior Web Developer for Team Detroit and formerly a web applications developer for The University
of Michigan and the Senior Developer at{' '}
<a target="_blank" href="http://qltd.com">
Q LTD
</a>
in Ann Arbor, MI. I also do freelance web design and development for projects that I find
interesting, challenging or exciting, and give private training or consulting in various web topics.
In 2012, I created{' '}
<a target="_blank" href="http://www.youtube.com/user/LevelUpTuts/featured">
Level Up Tuts
</a>
with web developer{' '}
<a target="_blank" href="http://benschaaf.com/">
Ben Schaaf
</a>
. With Level Up Tutorials I have taken our knowledge of web technologies to YouTube to provide free
training to developers looking to learn something new. I've also created premium tutorial packages for{' '}
<a target="_blank" href="https://www.packtpub.com/getting-started-with-magento/video">
Packt Publishing
</a>
.
</p>
<p>
I also enjoy{' '}
<a target="_blank" href="http://youtu.be/Zcoj4Zfj6_k?t=1m34s">
bboying
</a>{' '}
also known as breakdancing, and have been dancing for over 8 years doing shows for professional NFL and
NBA teams. I'm inspired by a hot cup of green tea, excellent music, and Shaw Bros. kung fu movies.
</p>
<p>
Please <Link to="/contact">contact me</Link> if you would like to work on a project together, or just want
to chat.
</p>
</div>
<Resume>
<FakeButtons />
<div className="resume-inside">
<h3>/* --Resume-- */</h3>
<h4>/* SUMMARY OF QUALIFICATIONS */</h4>
<ul>
<li>
Received a Bachelors degree in the Fine Arts at the University of Michigan’s Media Arts program.
</li>
<li>Excellent organization, self-motivation, and problem-solving skills.</li>
<li>
Created and runs a popular Youtube coding education channel with over 700 videos, 8.5million views
& 85k subscribers.
</li>
<li>Creative, strong communication skills and consistently meets deadlines.</li>
<li>Passionate about web development and new technologies.</li>
</ul>
<h4>/* Experience */</h4>
<h5>// SENIOR FRONT-END DEVELOPER, Team Detroit - DEARBORN, MI</h5>
<span className="time">// MAY 2014 - PRESENT</span>
<ul>
<li>Rapidly prototyped designs for the design process and user testing.</li>
<li>Utilized AngularJS to build a component library for Ford.com Global Redesign.</li>
<li>Met with Ford executives to display functionality of design experiments.</li>
<li>Worked on a team of developers to coordinate and develop compoent library.</li>
<li>Built resposive web applications to display potential design and interaction experiences.</li>
</ul>
<h5>// OWNER, Level Up Tuts - ANN ARBOR, MI</h5>
<span className="time">// MARCH 2012 - PRESENT</span>
<ul>
<li>
Wrote, produced and recorded over 1000 popular tutorial videos on various topics for Level Up Tuts
(www.youtube.com/user/LevelUpTuts) with over 8,550,000 views.
</li>
<li>
Designed websites, interfaces, and layouts to fit clients’ desires including developing responsive
layouts to enhance the experience on mobile devices.
</li>
<li>Consulted on large scale development projects.</li>
<li>Provided dedicated training on coding practices and content management systems.</li>
<li>Wrote, produced and recorded commercial video tutorial series for Envato and Packt Publishing.</li>
</ul>
<h5>// WEB APPLICATIONS DEVELOPER, UM Creative - ANN ARBOR, MI</h5>
<span className="time">// OCT 2013 - MAY 2014</span>
<ul>
<li>Developed single page applications using Angular.js or Backbone.js.</li>
<li>Maintained and built websites for secure University servers.</li>
<li>Took initiative on internal projects to advance direction of department.</li>
<li>
Tested and troubleshot slow application speeds as well as slow front end load times on existing
websites.
</li>
<li>Built responsive, CMS based websites with rapid turnaround.</li>
</ul>
<h5>// SENIOR DEVELOPER, Q LTD - ANN ARBOR, MI</h5>
<span className="time">// MARCH 2011 - OCT 2013</span>
<ul>
<li>
Built large, medium, and small scale websites from the ground up using appropriate content management
systems (Drupal, Wordpress, Expression Engine, Magento).
</li>
<li>
Utilized latest HTML5 and CSS3 technologies to build semantically correct and visually interesting
responsive designs.
</li>
<li>Created interactive elements with custom JavaScript and Jquery.</li>
<li>Worked frequently with clients to train, assist, and troubleshoot their websites.</li>
<li>
Used Sass, Compass, and Coffee Script to more effectively write clean, fast, and easy to read code.
</li>
</ul>
<h4>/* EDUCATION */</h4>
<ul>
<li>University of Michigan - Media Arts Bachelors of the Arts Spring 2008</li>
</ul>
</div>
</Resume>
</MainWrapper>
</Layout>
);
}
}
|
app/components/common/nominationItem/index.js
|
liujia14/mayi
|
/*
name: listItem
desc: 提名团队列表组件
author: 俞雅菲
version:v1.0
*/
import React from 'react';
import ReactDOM from 'react-dom';
import './../commonCss/index.less';
import ajax from './../ajax/ajax.js';
import './index.less';
import { message,Modal } from 'antd';
import QueueAnim from 'rc-queue-anim'; //淡入淡出动画
const confirm = Modal.confirm;
export default class Items extends React.Component {
constructor(props) {
super(props);
this.state = {
visible:false,
nomineeCode:undefined
};
this.doAgree = this.doAgree.bind(this);
this.notAgree = this.notAgree.bind(this);
this.recall = this.recall.bind(this);
this.handleCancel = this.handleCancel.bind(this);
this.handleOk = this.handleOk.bind(this);
}
doAgree(code,e){ //点赞
let t = $(e.target);
if(t.hasClass("icon-dianzan")){
ajax({ //点赞接口 参数 nomineeCode type->YES 是点赞 NO 是取消赞
url:'/platform/nominate/LikeOperate.json',
type:"POST",
data:{
'nomineeCode':code,
'type':'YES'
},
success:(data)=>{
if(data.success){
t.removeClass("icon-dianzan")
.addClass("icon-dianzan-copy")
.siblings(".agreeNum").text( parseInt(t.siblings(".agreeNum").text())+1 );
}else{
message.error(data.errors);
}
},
error : (data) => {}
});
}else{
ajax({ //点赞接口 参数 nomineeCode type->YES 是点赞 NO 是取消赞
url:'/platform/nominate/LikeOperate.json',
type:"POST",
data:{
'nomineeCode':code,
'type':'NO'
},
success:(data)=>{
if(data.success){
t.removeClass("icon-dianzan-copy")
.addClass("icon-dianzan")
.siblings(".agreeNum").text( parseInt(t.siblings(".agreeNum").text())-1 );
}else{
message.error(data.errors);
}
},
error : (data) => {}
});
}
}
notAgree(code,e){ //取消点赞
let t = $(e.target);
if(t.hasClass("icon-dianzan-copy")){
ajax({ //点赞接口 参数 nomineeCode type->YES 是点赞 NO 是取消赞
url:'/platform/nominate/LikeOperate.json',
type:"POST",
data:{
'nomineeCode':code,
'type':'NO'
},
success:(data)=>{
if(data.success){
t.removeClass("icon-dianzan-copy")
.addClass("icon-dianzan")
.siblings(".agreeNum").text( parseInt(t.siblings(".agreeNum").text())-1 );
}else{
message.error(data.errors);
}
},
error : (data) => {}
});
}else{
ajax({ //点赞接口 参数 nomineeCode type->YES 是点赞 NO 是取消赞
url:'/platform/nominate/LikeOperate.json',
type:"POST",
data:{
'nomineeCode':code,
'type':'YES'
},
success:(data)=>{
if(data.success){
t.removeClass("icon-dianzan")
.addClass("icon-dianzan-copy")
.siblings(".agreeNum").text( parseInt(t.siblings(".agreeNum").text())+1 );
}else{
message.error(data.errors);
}
},
error : (data) => {}
});
}
}
recall(ev,code){ //删除事件
let self = this;
this.setState({
visible:true,
nomineeCode:code
});
confirm({ //确认
title: '你确定要删除吗',
onOk() {
self.handleOk();
},
onCancel() {
self.handleCancel();
}
});
}
handleOk(){
let self = this;
let codes = self.state.nomineeCode;
ajax({
url:'/platform/nominate/RemoveNominate.json',
type:"POST",
data:{
'nomineeCode': codes
},
success:(data) => {
if(data.success){
message.success("删除成功!3秒后刷新页面");
self.setState({
visible:false
});
setTimeout(function(){window.location.reload();},2000);
}else{
message.error(data.errors)
}
},
error : (data) => {}
});
}
handleCancel(){
this.setState({
visible:false
});
}
render() {
let self = this;
let datas = this.props.listData;
let nomineeType = this.props.nomineeType;
let strTip;
if(nomineeType == "nomination"){
strTip = "";
}else{
strTip = "被";
}
return (
<div className="clearFix">
<QueueAnim>
{
datas.length > 0 ?
datas.map((item,index)=>{
if(item.nomineeType == 1){ //个人
return(
<div className="nominationBox" key={index}>
<div className="nomi-caption">{strTip}提名信息</div>
<div className="item-leftimg">
<a href={"/platform/pageconfig/messageBoard.htm?nomineeCode="+item.nomineeCode}><img src={item.url} alt=""/></a>
</div>
<div className="item-component">
<div className="item-title"><a href={"/platform/pageconfig/messageBoard.htm?nomineeCode="+item.nomineeCode}>个人姓名:{item.nomineeName}</a></div>
<div className="item-department-b"><span>所属部门:</span><div className="item-inlb">{item.departmentName}</div></div>
<div className="item-type"><span>奖项类型:</span>{item.prizeType == 1 ? <div className="item-inlb">公司</div> : <div className="item-inlb">部门</div>}</div>
<div className="item-prize"><span>{strTip}提名奖项:</span><a className="aColor item-inlb" href={"/platform/pageconfig/awardsDetail.htm?prizeCode=" + item.prizeCode}>{item.prizeName}</a></div>
<div className="item-reason"><span>{strTip}提名理由:</span><div className="item-inlb">{item.nominatedReason}</div></div>
<div className="item-agree" >
<i className="iconfont icon-dianzan" ></i> <span className="agreeNum">{ item.likeSum }</span>
</div>
<div className="item-comment"><i className="iconfont icon-pinglun"></i> {item.messageSum}</div>
{
item.winStatus == 1 ? <div className="itemAwards"><i className="iconfont icon-huangguan"></i> 获奖</div> : null
}
{
item.type == '0' & (item.prizeStatus == 'normal') ? <div className="item-btngroup"><a className="ant-btn ant-btn-primary" href={"/platform/pageconfig/frontNominationEdit.htm?nomineeCode="+item.nomineeCode}>修改</a><a className="ant-btn ant-btn-primary" onClick={ (ev)=>self.recall(ev,item.nomineeCode) }>删除</a></div> : null
}
</div>
{
item.prizeStatus == 'normal' ? <div className="limite-state ongoing">进行中</div> :
item.prizeStatus == 'end' ? <div className="limite-state">已结束</div> :
item.prizeStatus == 'delete' ? <div className="limite-state">已删除</div> :
item.prizeStatus == 'before' ? <div className="limite-state">未开始</div> : null
}
</div>
)
}
else if(item.nomineeType == 2){
return(
<div className="nominationBox" key={index}>
<div className="nomi-caption">{strTip}提名信息</div>
<div className="item-leftimg">
<a href={"/platform/pageconfig/messageBoard.htm?nomineeCode="+item.nomineeCode}><img src={item.url} alt=""/></a>
</div>
<div className="item-component">
<div className="item-title"><a href={"/platform/pageconfig/messageBoard.htm?nomineeCode="+item.nomineeCode}>团队名称:{item.nomineeName}</a></div>
<div className="item-department-b"><span>所属部门:</span><div className="item-inlb">{item.departmentName}</div></div>
<div className="item-type"><span>奖项类型:</span>{item.prizeType == 1 ? <div className="item-inlb">公司</div> : <div className="item-inlb">部门</div>}</div>
<div className="item-prize"><span>{strTip}提名奖项:</span><a className="aColor item-inlb" href={"/platform/pageconfig/awardsDetail.htm?prizeCode="+item.prizeCode}>{item.prizeName}</a></div>
<div className="item-reason"><span>{strTip}提名理由:</span><div className="item-inlb">{item.nominatedReason}</div></div>
<div className="item-member"><span>团队名单:</span><div className="item-inlb">{ item.apTeamMembersNameList ? item.apTeamMembersNameList : <span>无</span> }</div>
</div>
<div className="item-agree" >
<i className="iconfont icon-dianzan" ></i> <span className="agreeNum">{ item.likeSum }</span>
</div>
<div className="item-comment"><i className="iconfont icon-pinglun"></i> {item.messageSum}</div>
{
item.winStatus == 1 ? <div className="itemAwards"><i className="iconfont icon-huangguan"></i> 获奖</div> : null
}
{
item.type == '0' & (item.prizeStatus == 'normal') ? <div className="item-btngroup"><a className="ant-btn ant-btn-primary" href={"/platform/pageconfig/frontNominationEdit.htm?nomineeCode="+item.nomineeCode}>修改</a><a className="ant-btn ant-btn-primary" onClick={ (ev)=>self.recall(ev,item.nomineeCode) }>删除</a></div> : null
}
</div>
{
item.prizeStatus == 'normal' ? <div className="limite-state ongoing">进行中</div> :
item.prizeStatus == 'end' ? <div className="limite-state">已结束</div> :
item.prizeStatus == 'delete' ? <div className="limite-state">已删除</div> :
item.prizeStatus == 'before' ? <div className="limite-state">未开始</div> : null
}
</div>
)
}
})
: nomineeType == "nomination" ? <div className="empty"><img src="../../../../static/images/noData.png" alt="无数据"/> <div>你还没有参与提名,赶快行动,表达你的支持!</div></div>
: <div className="empty"><img src="../../../../static/images/noData.png" alt="无数据"/> <div>小伙伴们的提名还在路上,先自荐一个?</div></div>
}
</QueueAnim>
</div>
)
}
}
|
docs/app/Examples/modules/Dropdown/Types/DropdownExampleMultipleSearchSelectionTwo.js
|
Rohanhacker/Semantic-UI-React
|
import React from 'react'
import { Dropdown } from 'semantic-ui-react'
import { countryOptions } from '../common'
// countryOptions = [ { value: 'af', flag: 'af', text: 'Afghanistan' }, ... ]
const DropdownExampleMultipleSearchSelectionTwo = () => (
<Dropdown placeholder='Select Country' fluid multiple search selection options={countryOptions} />
)
export default DropdownExampleMultipleSearchSelectionTwo
|
test/files/filelist.component.js
|
NebulousLabs/Sia-UI
|
import React from 'react'
import { shallow, mount } from 'enzyme'
import { List, OrderedSet } from 'immutable'
import { expect } from 'chai'
import { spy } from 'sinon'
import FileList from '../../plugins/Files/js/components/filelist.js'
const testFiles = List([
{size: '1337mb', available: true, redundancy: 1.0, uploadprogress: 100, name: 'hackers.mkv', siapath: 'movies/hackers.mkv', type: 'file'},
{size: '', available: true, redundancy: 1.0, uploadprogress: 100, name: 'movies', type: 'directory'},
{size: '137mb', available: true, redundancy: 1.5, uploadprogress: 100, name: 'test.jpg', siapath: 'test.jpg', type: 'file'},
{size: '137mb', available: true, redundancy: 2.0, uploadprogress: 100, name: 'meme.avi', siapath: 'meme.avi', type: 'file'},
{size: '137mb', available: true, redundancy: -1, uploadprogress: 100, name: 'test-0bytes', siapath: 'test-0bytes', type: 'file'},
{size: '', available: true, redundancy: 1.0, uploadprogress: 100, name: 'dankpepes', type: 'directory'},
])
const testActions = {
setPath: spy(),
selectFile: spy(),
deselectFile: spy(),
deselectAll: spy(),
selectUpTo: spy(),
setDragUploadEnabled: spy(),
}
describe('file list', () => {
beforeEach(() => {
for (const action in testActions) {
testActions[action].reset()
}
})
it('renders a ul with the correct number of file and directory children', () => {
const filelist = shallow(<FileList actions={testActions} files={testFiles} selected={OrderedSet()} showSearchField={false} path="" dragFileOrigin={{}} />)
expect(filelist.find('File')).to.have.length(testFiles.size)
})
it('renders a back button when path is set', () => {
expect(shallow(<FileList actions={testActions} files={testFiles} showSearchField={false} selected={OrderedSet()} path="movies/" dragFileOrigin={{}} />).find('ul').children()).to.have.length(testFiles.size + 1)
})
describe('file selection', () => {
it('selects files', () => {
const filelist = shallow(<FileList files={testFiles} showSearchField={false} selected={OrderedSet()} path="" actions={testActions} dragFileOrigin={{}} />)
const filenodes = filelist.find('File')
for (let nodeindex = 0; nodeindex < filenodes.length; nodeindex++) {
filenodes.at(nodeindex).simulate('click', { ctrlKey: false })
expect(testActions.deselectAll.called).to.equal(true)
expect(testActions.selectFile.calledWith(testFiles.get(nodeindex))).to.equal(true)
}
})
it('selects multiple files with ctrl key', () => {
const filelist = shallow(<FileList files={testFiles} showSearchField={false} selected={OrderedSet()} path="" actions={testActions} dragFileOrigin={{}} />)
const filenodes = filelist.find('File')
for (let nodeindex = 0; nodeindex < filenodes.length; nodeindex++) {
filenodes.at(nodeindex).simulate('click', { ctrlKey: true })
expect(testActions.deselectAll.called).to.equal(false)
testActions.deselectAll.reset()
expect(testActions.selectFile.calledWith(testFiles.get(nodeindex))).to.equal(true)
}
})
it('deselects a file when selected and ctrl-clicked', () => {
const filelist = shallow(<FileList files={testFiles} showSearchField={false} selected={OrderedSet([testFiles.get(0), testFiles.get(1)])} path="" actions={testActions} dragFileOrigin={{}} />)
const filenodes = filelist.find('File')
filenodes.at(0).simulate('click', { ctrlKey: true })
expect(testActions.deselectFile.calledWith(testFiles.get(0))).to.equal(true)
})
it('exclusively selects a file with multiple selected and no ctrl click', () => {
const filelist = shallow(<FileList files={testFiles} showSearchField={false} selected={OrderedSet([testFiles.get(0), testFiles.get(1)])} path="" actions={testActions} dragFileOrigin={{}} />)
const filenodes = filelist.find('File')
filenodes.at(1).simulate('click', { ctrlKey: false})
expect(testActions.deselectAll.called).to.equal(true)
expect(testActions.selectFile.calledWith(testFiles.get(1))).to.equal(true)
})
it('selects ranges with the shift key', () => {
const filelist = shallow(<FileList files={testFiles} showSearchField={false} selected={OrderedSet()} path="" actions={testActions} dragFileOrigin={{}} />)
const filenodes = filelist.find('File')
filenodes.first().simulate('click', { ctrlKey: false, shiftKey: false })
filenodes.last().simulate('click', { ctrlKey: false, shiftKey: true })
expect(testActions.selectUpTo.calledWith(testFiles.last())).to.equal(true)
})
})
it('navigates directories', () => {
let filelist = mount(<FileList files={testFiles} selected={OrderedSet()} showSearchField={false} path="test1/test2/" actions={testActions} dragFileOrigin={{}} />)
filelist.find('.back-button').first().simulate('click')
expect(testActions.setPath.calledWith('test1')).to.equal(true)
filelist = mount(<FileList files={testFiles} showSearchField={false} selected={OrderedSet()} path="test1/" actions={testActions} dragFileOrigin={{}} />)
filelist.find('.back-button').first().simulate('click')
expect(testActions.setPath.calledWith('')).to.equal(true)
filelist = mount(<FileList files={testFiles} showSearchField={false} selected={OrderedSet()} path="test1/test2/test3/" actions={testActions} dragFileOrigin={{}} />)
filelist.find('.back-button').first().simulate('click')
expect(testActions.setPath.calledWith('test1/test2')).to.equal(true)
const renderedDirectories = filelist.find('File [type="directory"]')
renderedDirectories.forEach((directory) => {
directory.find('i').first().simulate('click')
expect(testActions.setPath.calledWith('test1/' + directory.prop('name'))).to.equal(true)
})
})
})
|
client/src/js/components/Home.js
|
KevinBacas/TP2-Web-Semantique
|
import React from 'react';
import RequestList from './RequestList';
import DocumentActions from '../actions/DocumentActions';
import DocumentStore from '../stores/DocumentStore';
export default class Home extends React.Component {
constructor() {
super();
this.state = {
documents: false
}
}
handleSubmit(e) {
e.preventDefault();
let request = document.getElementById('request').value;
DocumentActions.fetchDocuments(request);
}
onChange() {
let doc= DocumentStore.getDocuments();
if(doc === []) {
doc = false;
}
this.setState({
documents: doc
});
}
conponentWillUnmount() {
this.setState({});
}
componentDidMount() {
DocumentStore.onChange = this.onChange.bind(this);
}
render() {
return (
<div className="container" >
<form
className="homePage"
onSubmit={this.handleSubmit}
action="return false;">
<input
type="text"
className="form-control"
id="request"
placeholder="your request" />
<input
className="btn btn-default"
type="submit"
value="search" />
</form>
<RequestList list={this.state.documents} />
</div>
);
}
};
|
src/svg-icons/device/usb.js
|
ArcanisCz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceUsb = (props) => (
<SvgIcon {...props}>
<path d="M15 7v4h1v2h-3V5h2l-3-4-3 4h2v8H8v-2.07c.7-.37 1.2-1.08 1.2-1.93 0-1.21-.99-2.2-2.2-2.2-1.21 0-2.2.99-2.2 2.2 0 .85.5 1.56 1.2 1.93V13c0 1.11.89 2 2 2h3v3.05c-.71.37-1.2 1.1-1.2 1.95 0 1.22.99 2.2 2.2 2.2 1.21 0 2.2-.98 2.2-2.2 0-.85-.49-1.58-1.2-1.95V15h3c1.11 0 2-.89 2-2v-2h1V7h-4z"/>
</SvgIcon>
);
DeviceUsb = pure(DeviceUsb);
DeviceUsb.displayName = 'DeviceUsb';
DeviceUsb.muiName = 'SvgIcon';
export default DeviceUsb;
|
frontend/components/home_show/home_show_container.js
|
qydchen/SafeHavn
|
import React from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import HomeShow from './home_show';
import { fetchHome } from '../../actions/home_actions';
import { openModal } from '../../actions/modal_actions';
import { clearErrors } from '../../actions/session_actions'
const mapStateToProps = ({ homes, session }, { match }) => {
const homeid = match.params.homeid;
const listing = homes[homeid];
return {
homeid,
listing,
currentUser: session.currentUser,
reviews: listing ? listing.reviews : [],
}
}
const mapDispatchToProps = (dispatch) => {
return {
fetchHome: id => dispatch(fetchHome(id)),
openModal: (component) => dispatch(openModal(component)),
clearErrors: () => dispatch(clearErrors()),
}
}
export default withRouter(connect(
mapStateToProps,
mapDispatchToProps
)(HomeShow));
|
frontend/node_modules/recharts/demo/component/Sector.js
|
justdotJS/rowboat
|
import React, { Component } from 'react';
import { Surface, Sector } from 'recharts';
export default class Demo extends Component {
static displayName = 'SectorDemo';
render () {
return (
<Surface width={500} height={1000}>
<Sector fill="#ff7902" cx={200} cy={200} innerRadius={150} outerRadius={200} endAngle={90} />
<Sector
fill="#287902"
cx={200}
cy={400}
innerRadius={180}
outerRadius={200}
startAngle={45}
endAngle={135}
cornerRadius={10}
/>
</Surface>
);
}
}
|
webapp-src/src/Modal/Message.js
|
babelouest/glewlwyd
|
import React, { Component } from 'react';
import i18next from 'i18next';
class Message extends Component {
constructor(props) {
super(props);
this.state = {
title: props.title,
label: props.label,
message: props.message
}
this.closeModal = this.closeModal.bind(this);
}
componentWillReceiveProps(nextProps) {
this.setState({
title: nextProps.title,
label: nextProps.label,
message: nextProps.message
});
}
closeModal(e, result) {
$("#messageModal").modal("hide");
}
render() {
var messageJsx = [], labelJsx;
if (this.state.label) {
labelJsx = <h5>{this.state.label}</h5>;
}
if (this.state.message) {
this.state.message.forEach((message, index) => {
messageJsx.push(<li key={index}>{message}</li>);
});
}
return (
<div className="modal fade on-top" id="messageModal" tabIndex="-1" role="dialog" aria-labelledby="messageModalLabel" aria-hidden="true">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="messageModalLabel">{this.state.title}</h5>
<button type="button" className="close" aria-label={i18next.t("modal.close")} onClick={(e) => this.closeModal(e, false)}>
<span aria-hidden="true">×</span>
</button>
</div>
<div className="modal-body">
{labelJsx}
<ul>
{messageJsx}
</ul>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" onClick={(e) => this.closeModal(e, false)}>{i18next.t("modal.close")}</button>
</div>
</div>
</div>
</div>
);
}
}
export default Message;
|
01-basic-example/components/Home.js
|
nodeyu/jason-react-router-demos-v4
|
import React from 'react';
class Home extends React.Component {
render() {
return (
<div>
<h2>Home</h2>
<p>Welcome To React Full Stack</p>
</div>
);
}
}
export default Home;
|
example/src/screens/types/tabs/TabTwo.js
|
junedomingo/react-native-navigation
|
import React from 'react';
import {View, Text} from 'react-native';
class TabOne extends React.Component {
render() {
return (
<View>
<Text>Tab Two</Text>
</View>
);
}
}
export default TabOne;
|
src/svg-icons/action/today.js
|
andrejunges/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionToday = (props) => (
<SvgIcon {...props}>
<path d="M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11zM7 10h5v5H7z"/>
</SvgIcon>
);
ActionToday = pure(ActionToday);
ActionToday.displayName = 'ActionToday';
ActionToday.muiName = 'SvgIcon';
export default ActionToday;
|
fields/types/cloudinaryimage/CloudinaryImageField.js
|
Pylipala/keystone
|
import _ from 'underscore';
import $ from 'jquery';
import React from 'react';
import Field from '../Field';
import Select from 'react-select';
import { Button, FormField, FormInput, FormNote } from 'elemental';
/**
* TODO:
* - Remove dependency on jQuery
* - Remove dependency on underscore
*/
const SUPPORTED_TYPES = ['image/gif', 'image/png', 'image/jpeg', 'image/bmp', 'image/x-icon', 'application/pdf', 'image/x-tiff', 'image/x-tiff', 'application/postscript', 'image/vnd.adobe.photoshop', 'image/svg+xml'];
module.exports = Field.create({
displayName: 'CloudinaryImageField',
fileFieldNode () {
return this.refs.fileField.getDOMNode();
},
changeImage () {
this.refs.fileField.getDOMNode().click();
},
getImageSource () {
if (this.hasLocal()) {
return this.state.localSource;
} else if (this.hasExisting()) {
return this.props.value.url;
} else {
return null;
}
},
getImageURL () {
if (!this.hasLocal() && this.hasExisting()) {
return this.props.value.url;
}
},
/**
* Reset origin and removal.
*/
undoRemove () {
this.fileFieldNode().value = '';
this.setState({
removeExisting: false,
localSource: null,
origin: false,
action: null
});
},
/**
* Check support for input files on input change.
*/
fileChanged (event) {
var self = this;
if (window.FileReader) {
var files = event.target.files;
_.each(files, function (f) {
if (!_.contains(SUPPORTED_TYPES, f.type)) {
self.removeImage();
alert('Unsupported file type. Supported formats are: GIF, PNG, JPG, BMP, ICO, PDF, TIFF, EPS, PSD, SVG');
return false;
}
var fileReader = new FileReader();
fileReader.onload = function (e) {
if (!self.isMounted()) return;
self.setState({
localSource: e.target.result,
origin: 'local'
});
};
fileReader.readAsDataURL(f);
});
} else {
this.setState({
origin: 'local'
});
}
},
/**
* If we have a local file added then remove it and reset the file field.
*/
removeImage (e) {
var state = {
localSource: null,
origin: false
};
if (this.hasLocal()) {
this.fileFieldNode().value = '';
} else if (this.hasExisting()) {
state.removeExisting = true;
if (this.props.autoCleanup) {
if (e.altKey) {
state.action = 'reset';
} else {
state.action = 'delete';
}
} else {
if (e.altKey) {
state.action = 'delete';
} else {
state.action = 'reset';
}
}
}
this.setState(state);
},
/**
* Is the currently active image uploaded in this session?
*/
hasLocal () {
return this.state.origin === 'local';
},
/**
* Do we have an image preview to display?
*/
hasImage () {
return this.hasExisting() || this.hasLocal();
},
/**
* Do we have an existing file?
*/
hasExisting () {
return !!this.props.value.url;
},
/**
* Render an image preview
*/
renderImagePreview () {
var iconClassName;
var className = 'image-preview';
if (this.hasLocal()) {
className += ' upload-pending';
iconClassName = 'upload-pending mega-octicon octicon-cloud-upload';
} else if (this.state.removeExisting) {
className += ' removed';
iconClassName = 'delete-pending mega-octicon octicon-x';
}
var body = [this.renderImagePreviewThumbnail()];
if (iconClassName) body.push(<div key={this.props.path + '_preview_icon'} className={iconClassName} />);
var url = this.getImageURL();
if (url) {
body = <a className="img-thumbnail" href={this.getImageURL()} target="__blank">{body}</a>;
} else {
body = <div className="img-thumbnail">{body}</div>;
}
return <div key={this.props.path + '_preview'} className={className}>{body}</div>;
},
renderImagePreviewThumbnail () {
return <img key={this.props.path + '_preview_thumbnail'} className="img-load" style={ { height: '90' } } src={this.getImageSource()} />;
},
/**
* Render image details - leave these out if we're uploading a local file or
* the existing file is to be removed.
*/
renderImageDetails (add) {
var values = null;
if (!this.hasLocal() && !this.state.removeExisting) {
values = (
<div className="image-values">
<FormInput noedit>{this.props.value.url}</FormInput>
{/*
TODO: move this somewhere better when appropriate
this.renderImageDimensions()
*/}
</div>
);
}
return (
<div key={this.props.path + '_details'} className="image-details">
{values}
{add}
</div>
);
},
renderImageDimensions () {
return <FormInput noedit>{this.props.value.width} x {this.props.value.height}</FormInput>;
},
/**
* Render an alert.
*
* - On a local file, output a "to be uploaded" message.
* - On a cloudinary file, output a "from cloudinary" message.
* - On removal of existing file, output a "save to remove" message.
*/
renderAlert () {
if (this.hasLocal()) {
return (
<FormInput noedit>Image selected - save to upload</FormInput>
);
} else if (this.state.origin === 'cloudinary') {
return (
<FormInput noedit>Image selected from Cloudinary</FormInput>
);
} else if (this.state.removeExisting) {
return (
<FormInput noedit>Image {this.props.autoCleanup ? 'deleted' : 'removed'} - save to confirm</FormInput>
);
} else {
return null;
}
},
/**
* Output clear/delete/remove button.
*
* - On removal of existing image, output "undo remove" button.
* - Otherwise output Cancel/Delete image button.
*/
renderClearButton () {
if (this.state.removeExisting) {
return (
<Button type="link" onClick={this.undoRemove}>
Undo Remove
</Button>
);
} else {
var clearText;
if (this.hasLocal()) {
clearText = 'Cancel';
} else {
clearText = (this.props.autoCleanup ? 'Delete Image' : 'Remove Image');
}
return (
<Button type="link-cancel" onClick={this.removeImage}>
{clearText}
</Button>
);
}
},
renderFileField () {
return <input ref="fileField" type="file" name={this.props.paths.upload} className="field-upload" onChange={this.fileChanged} tabIndex="-1" />;
},
renderFileAction () {
return <input type="hidden" name={this.props.paths.action} className="field-action" value={this.state.action} />;
},
renderImageToolbar () {
return (
<div key={this.props.path + '_toolbar'} className="image-toolbar">
<div className='u-float-left'>
<Button onClick={this.changeImage}>
{this.hasImage() ? 'Change' : 'Upload'} Image
</Button>
{this.hasImage() && this.renderClearButton()}
</div>
{this.props.select && this.renderImageSelect()}
</div>
);
},
renderImageSelect () {
var selectPrefix = this.props.selectPrefix;
var getOptions = function(input, callback) {
$.get('/keystone/api/cloudinary/autocomplete', {
dataType: 'json',
data: {
q: input
},
prefix: selectPrefix
}, function (data) {
var options = [];
_.each(data.items, function (item) {
options.push({
value: item.public_id,
label: item.public_id
});
});
callback(null, {
options: options,
complete: true
});
});
};
return (
<div className="image-select">
<Select
placeholder="Search for an image from Cloudinary ..."
className="ui-select2-cloudinary"
name={this.props.paths.select}
id={'field_' + this.props.paths.select}
asyncOptions={getOptions}
/>
</div>
);
},
renderUI () {
var container = [];
var body = [];
var hasImage = this.hasImage();
if (this.shouldRenderField()) {
if (hasImage) {
container.push(this.renderImagePreview());
container.push(this.renderImageDetails(this.renderAlert()));
}
body.push(this.renderImageToolbar());
} else {
if (hasImage) {
container.push(this.renderImagePreview());
container.push(this.renderImageDetails());
} else {
container.push(<div className="help-block">no image</div>);
}
}
return (
<FormField label={this.props.label} className="field-type-cloudinaryimage">
{this.renderFileField()}
{this.renderFileAction()}
<div className="image-container">{container}</div>
{body}
<FormNote note={this.props.note} />
</FormField>
);
}
});
|
docs/app/Examples/collections/Message/Types/MessageExampleList.js
|
aabustamante/Semantic-UI-React
|
import React from 'react'
import { Message } from 'semantic-ui-react'
const MessageExampleList = () => (
<Message>
<Message.Header>New Site Features</Message.Header>
<Message.List>
<Message.Item>You can now have cover images on blog pages</Message.Item>
<Message.Item>Drafts will now auto-save while writing</Message.Item>
</Message.List>
</Message>
)
export default MessageExampleList
|
components/Forecast.js
|
s1hit/react-onsenui-redux-weather-edited
|
import React from 'react';
import WeatherIcon from '../components/WeatherIcon';
import {weatherCodeToColor} from '../util';
const WEEKDAYS = {
0: 'SUN',
1: 'MON',
2: 'TUE',
3: 'WED',
4: 'THU',
5: 'FRI',
6: 'SAT'
};
const styles = {
forecast: {
margin: '0 25px',
display: 'flex'
},
weekday: {
flexGrow: 1,
display: 'flex',
flexDirection: 'column'
},
weekdayName: {
fontSize: '16px',
margin: '0 0 6px 0',
fontWeight: 200
},
weekdayIcon: {
fontSize: '24px'
},
weekdayMaxTemp: {
margin: '6px 0 0 0',
fontSize: '12px'
},
weekdayMinTemp: {
opacity: 0.6,
margin: '2px 0 0 0',
fontWeight: 200,
fontSize: '12px'
}
};
const Forecast = ({days}) => (
<div style={styles.forecast}>
{days.map(({weekday, icon, maxTemp, minTemp}) => {
const weatherColor = weatherCodeToColor(icon);
return (
<div key={weekday} style={styles.weekday}>
<div style={styles.weekdayName}>
{WEEKDAYS[weekday]}
</div>
<div style={styles.weekdayIcon}>
<WeatherIcon style={{color: weatherColor}} icon={icon} />
</div>
<div style={styles.weekdayMaxTemp}>
{maxTemp}°C
</div>
<div style={styles.weekdayMinTemp}>
{minTemp}°C
</div>
</div>
);
})}
</div>
);
export default Forecast;
|
Paths/React/05.Building Scalable React Apps/8-react-boilerplate-building-scalable-apps-m8-exercise-files/Before/app/components/Login/index.js
|
phiratio/Pluralsight-materials
|
/**
*
* Login
*
*/
import React from 'react';
import styles from './styles.css';
import validator from 'email-validator';
import classNames from 'classnames';
class Login extends React.Component { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
login: React.PropTypes.func.isRequired,
cancelLogin: React.PropTypes.func.isRequired,
};
state = {};
login = () => {
const email = this.emailField.value;
if (!validator.validate(email)) {
this.setState({
errorText: 'Please provide a valid email',
});
return;
}
this.setState({
errorText: null,
});
this.props.login(email);
}
render() {
const fieldError = this.state.errorText ? (
<div
className={styles.errorMessage}
>
{this.state.errorText}
</div>
) : null;
return (
<div className={styles.login}>
<div
className={styles.heading}
>
Login with your email
</div>
<input
className={classNames(styles.input, { [styles.inputError]: this.state.errorText })}
placeholder="Your email"
ref={(f) => { this.emailField = f; }}
type="text"
/>
{fieldError}
<div
className={styles.actionContainer}
>
<div
className={styles.button}
onClick={this.props.cancelLogin}
>
cancel
</div>
<div
className={styles.button}
onClick={this.login}
>
log in
</div>
</div>
</div>
);
}
}
export default Login;
|
admin/client/components/FooterBar.js
|
andreufirefly/keystone
|
import React from 'react';
import blacklist from 'blacklist';
var FooterBar = React.createClass({
propTypes: {
style: React.PropTypes.object,
},
getDefaultProps () {
return {
style: {},
};
},
getInitialState () {
return {
position: 'relative',
width: 'auto',
height: 'auto',
top: 0,
};
},
componentDidMount () {
// Bail in IE8 because React doesn't support the onScroll event in that browser
// Conveniently (!) IE8 doesn't have window.getComputedStyle which we also use here
if (!window.getComputedStyle) return;
var footer = this.refs.footer;
this.windowSize = this.getWindowSize();
var footerStyle = window.getComputedStyle(footer);
this.footerSize = {
x: footer.offsetWidth,
y: footer.offsetHeight + parseInt(footerStyle.marginTop || '0'),
};
window.addEventListener('scroll', this.recalcPosition, false);
window.addEventListener('resize', this.recalcPosition, false);
this.recalcPosition();
},
getWindowSize () {
return {
x: window.innerWidth,
y: window.innerHeight,
};
},
recalcPosition () {
var wrapper = this.refs.wrapper;
this.footerSize.x = wrapper.offsetWidth;
var offsetTop = 0;
var offsetEl = wrapper;
while (offsetEl) {
offsetTop += offsetEl.offsetTop;
offsetEl = offsetEl.offsetParent;
}
var maxY = offsetTop + this.footerSize.y;
var viewY = window.scrollY + window.innerHeight;
var newSize = this.getWindowSize();
var sizeChanged = (newSize.x !== this.windowSize.x || newSize.y !== this.windowSize.y);
this.windowSize = newSize;
var newState = {
width: this.footerSize.x,
height: this.footerSize.y,
};
if (viewY > maxY && (sizeChanged || this.mode !== 'inline')) {
this.mode = 'inline';
newState.top = 0;
newState.position = 'absolute';
this.setState(newState);
} else if (viewY <= maxY && (sizeChanged || this.mode !== 'fixed')) {
this.mode = 'fixed';
newState.top = window.innerHeight - this.footerSize.y;
newState.position = 'fixed';
this.setState(newState);
}
},
render () {
var wrapperStyle = {
height: this.state.height,
marginTop: 60,
position: 'relative',
};
var footerProps = blacklist(this.props, 'children', 'style');
var footerStyle = Object.assign({}, this.props.style, {
position: this.state.position,
top: this.state.top,
width: this.state.width,
height: this.state.height,
});
return (
<div ref="wrapper" style={wrapperStyle}>
<div ref="footer" style={footerStyle} {...footerProps}>{this.props.children}</div>
</div>
);
},
});
module.exports = FooterBar;
|
packages/@vega/tracks-tool/src/components/TracksArticlesTable.js
|
VegaPublish/vega-studio
|
/* eslint-disable react/jsx-no-bind, complexity */
import React from 'react'
import PropTypes from 'prop-types'
import styles from './styles/TracksArticlesTable.css'
import Menu from 'part:@lyra/components/menus/default'
import ArrowDropDown from 'part:@lyra/base/arrow-drop-down'
import {filterArticles, stagesSuperset} from '../utils'
import TrackStageTableCell from './TrackStageTableCell'
import {Portal} from 'part:@lyra/components/utilities/portal'
import {Manager, Popper, Target} from 'react-popper'
function issueTitle(issue) {
return [issue.year, issue.title].filter(Boolean).join(' - ')
}
class TracksArticlesTable extends React.Component {
static propTypes = {
onUpdateSelection: PropTypes.func.isRequired,
currentTrackName: PropTypes.string,
currentIssueId: PropTypes.string,
currentStageName: PropTypes.string,
articles: PropTypes.arrayOf(
PropTypes.shape({
_id: PropTypes.string.isRequired,
title: PropTypes.string
})
),
issues: PropTypes.arrayOf(
PropTypes.shape({
_id: PropTypes.string.isRequired,
volume: PropTypes.string,
number: PropTypes.number,
year: PropTypes.number
})
),
tracks: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string,
title: PropTypes.string,
trackStages: PropTypes.arrayOf(
PropTypes.shape({
stage: PropTypes.object
})
)
})
)
}
state = {
rootMenuOpen: false
}
static defaultProps = {
articles: [],
issues: [],
tracks: [],
currentTrackName: null,
currentIssueId: null,
currentStageName: null
}
rootMenuItems() {
const {issues} = this.props
return [{title: 'All', key: 'all'}].concat(
issues.map(issue => {
return {
title: issueTitle(issue),
key: issue._id
}
})
)
}
handleRootMenuAction = rootMenuItem => {
const {onUpdateSelection} = this.props
if (rootMenuItem.key === 'all') {
onUpdateSelection({track: null, stage: null, issue: null})
} else {
onUpdateSelection({issue: rootMenuItem.key})
}
this.handleRootMenuClose()
}
handleRootMenuClose = () => {
this.setState({rootMenuOpen: false})
}
handleRootMenuOpen = () => {
this.setState({rootMenuOpen: true})
}
render() {
const {
issues,
tracks,
currentTrackName,
currentIssueId,
currentStageName,
onUpdateSelection,
articles
} = this.props
const stages = stagesSuperset(tracks)
const selectedIssue = issues.find(issue => issue._id === currentIssueId)
const rootMenuTitle = selectedIssue ? issueTitle(selectedIssue) : 'All'
if (issues.length < 1 || tracks.length < 1) {
return <div>No issues or tracks</div>
}
return (
<table className={styles.root}>
<thead className={styles.tableHead}>
<tr>
<th className={styles.rootCell}>
<Manager>
<Target>
<div onClick={this.handleRootMenuOpen}>
<span>{rootMenuTitle}</span>
<span className={styles.arrowDropDown}>
<ArrowDropDown />
</span>
</div>
</Target>
{this.state.rootMenuOpen && (
<Portal>
<Popper>
<Menu
items={this.rootMenuItems()}
onAction={this.handleRootMenuAction}
onClose={this.handleRootMenuClose}
onClickOutside={this.handleRootMenuClose}
isOpen
/>
</Popper>
</Portal>
)}
</Manager>
</th>
{stages.map(stage => {
const stageColumnKey = stage.name
const handleColumnClick = () => {
const selectStage =
currentStageName !== stage.name ||
(currentStageName && currentTrackName)
return onUpdateSelection({
stage: selectStage ? stage.name : null,
track: null
})
}
const colorStyle = {color: `${stage.displayColor}`}
return (
<th
onClick={handleColumnClick}
key={stageColumnKey}
style={colorStyle}
className={`
${styles.stageHeader}
${styles[`stage__${stage.name}`]}
${
currentStageName == stage.name && !currentTrackName
? styles.active
: styles.inActive
}
`}
>
<div className={styles.stageTitle}>{stage.title}</div>
</th>
)
})}
</tr>
</thead>
<tbody className={styles.tableBody}>
{tracks.map(track => {
const trackRowKey = track.name
const handleRowClick = () => {
const selectTrack =
currentTrackName !== track.name ||
(currentTrackName && currentStageName)
return onUpdateSelection({
track: selectTrack ? track.name : null,
stage: null
})
}
return (
<tr key={trackRowKey} className={styles.trackRow}>
<th
onClick={handleRowClick}
className={`
${styles.trackHeader}
${
currentTrackName == track.name && !currentStageName
? styles.active
: styles.inActive
}
`}
>
{track.title}
</th>
{stages.map(stage => {
const stageCellKey = `${track.name}_${stage.name}`
const isActive =
(currentStageName == stage.name &&
currentTrackName == track.name) ||
(currentStageName == stage.name && !currentTrackName) ||
(currentTrackName == track.name && !currentStageName)
const filterOptions = {
track: track.name,
stage: stage.name,
issue: currentIssueId
}
const filteredArticles = filterArticles(
articles,
filterOptions
)
return (
<TrackStageTableCell
onUpdateSelection={this.props.onUpdateSelection}
key={stageCellKey}
track={track}
stage={stage}
articles={filteredArticles}
isActive={isActive}
/>
)
})}
</tr>
)
})}
</tbody>
</table>
)
}
}
export default TracksArticlesTable
/* eslint-enable react/jsx-no-bind, complexity */
|
src/ProjectBoard.js
|
mikadamsterdam/react_for_project
|
import React from 'react';
import jQuery from 'jquery';
import Project from './Project';
import AddProject from './AddProject';
class ProjectBoard extends React.Component {
constructor(){
super();
this.state = {
projects: [
]
};
}
reloadProjectBoard(){
let component = this;
jQuery.getJSON("https://taskpool.herokuapp.com/projects/", function(data){
component.setState({
projects: data.projects
})
});
}
componentDidMount() {
this.reloadProjectBoard();
}
renderProject(project){
return <Project
id={project.id}
name={project.name}
goal={project.goal}
/>;
}
onAddProject(newName, newGoal){
var currentProjects = this.state.projects;
var newProjects = currentProjects.concat(newName, newGoal);
this.setState({
projects: newProjects
});
}
render() {
return (
<div>
<AddProject onSubmit={this.onAddProject.bind(this)} />
<hr />
<table>
<tbody>
{this.state.projects.map(this.renderProject.bind(this))}
</tbody>
</table>
</div>
);
}
}
export default ProjectBoard;
|
components/slider/Slider.js
|
rubenmoya/react-toolbox
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import classnames from 'classnames';
import styleShape from 'react-style-proptype';
import { themr } from 'react-css-themr';
import { round, range } from '../utils/utils';
import { SLIDER } from '../identifiers';
import events from '../utils/events';
import InjectProgressBar from '../progress_bar/ProgressBar';
import InjectInput from '../input/Input';
const factory = (ProgressBar, Input) => {
class Slider extends Component {
static propTypes = {
buffer: PropTypes.number,
className: PropTypes.string,
disabled: PropTypes.bool,
editable: PropTypes.bool,
max: PropTypes.number,
min: PropTypes.number,
onChange: PropTypes.func,
onDragStart: PropTypes.func,
onDragStop: PropTypes.func,
pinned: PropTypes.bool,
snaps: PropTypes.bool,
step: PropTypes.number,
style: styleShape,
theme: PropTypes.shape({
container: PropTypes.string,
editable: PropTypes.string,
innerknob: PropTypes.string,
innerprogress: PropTypes.string,
input: PropTypes.string,
knob: PropTypes.string,
pinned: PropTypes.string,
pressed: PropTypes.string,
progress: PropTypes.string,
ring: PropTypes.string,
slider: PropTypes.string,
snap: PropTypes.string,
snaps: PropTypes.string,
}),
value: PropTypes.number,
};
static defaultProps = {
buffer: 0,
className: '',
editable: false,
max: 100,
min: 0,
onDragStart: () => {},
onDragStop: () => {},
pinned: false,
snaps: false,
step: 0.01,
value: 0,
};
state = {
inputFocused: false,
inputValue: null,
sliderLength: 0,
sliderStart: 0,
};
componentDidMount() {
window.addEventListener('resize', this.handleResize);
this.handleResize();
}
componentWillReceiveProps(nextProps) {
if (this.state.inputFocused && this.props.value !== nextProps.value) {
this.setState({ inputValue: this.valueForInput(nextProps.value) });
}
}
shouldComponentUpdate(nextProps, nextState) {
return this.state.inputFocused || !nextState.inputFocused;
}
componentWillUpdate(nextProps, nextState) {
if (nextState.pressed !== this.state.pressed) {
if (nextState.pressed) {
this.props.onDragStart();
} else {
this.props.onDragStop();
}
}
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
events.removeEventsFromDocument(this.getMouseEventMap());
events.removeEventsFromDocument(this.getTouchEventMap());
events.removeEventsFromDocument(this.getKeyboardEvents());
}
getInput() {
return this.inputNode && this.inputNode.getWrappedInstance
? this.inputNode.getWrappedInstance()
: this.inputNode;
}
getKeyboardEvents() {
return {
keydown: this.handleKeyDown,
};
}
getMouseEventMap() {
return {
mousemove: this.handleMouseMove,
mouseup: this.handleMouseUp,
};
}
getTouchEventMap() {
return {
touchmove: this.handleTouchMove,
touchend: this.handleTouchEnd,
};
}
addToValue(increment) {
let value = this.state.inputFocused ? parseFloat(this.state.inputValue) : this.props.value;
value = this.trimValue(value + increment);
if (value !== this.props.value) this.props.onChange(value);
}
handleInputFocus = () => {
this.setState({
inputFocused: true,
inputValue: this.valueForInput(this.props.value),
});
};
handleInputChange = (value) => {
this.setState({ inputValue: value });
};
handleInputBlur = (event) => {
const value = this.state.inputValue || 0;
this.setState({ inputFocused: false, inputValue: null }, () => {
this.props.onChange(this.trimValue(value), event);
});
};
handleKeyDown = (event) => {
if ([13, 27].indexOf(event.keyCode) !== -1) this.getInput().blur();
if (event.keyCode === 38) this.addToValue(this.props.step);
if (event.keyCode === 40) this.addToValue(-this.props.step);
};
handleMouseDown = (event) => {
if (this.state.inputFocused) this.getInput().blur();
events.addEventsToDocument(this.getMouseEventMap());
this.start(events.getMousePosition(event));
events.pauseEvent(event);
};
handleMouseMove = (event) => {
events.pauseEvent(event);
this.move(events.getMousePosition(event));
};
handleMouseUp = () => {
this.end(this.getMouseEventMap());
};
handleResize = (event, callback) => {
const { left, right } = ReactDOM.findDOMNode(this.progressbarNode).getBoundingClientRect();
const cb = (callback) || (() => {});
this.setState({ sliderStart: left, sliderLength: right - left }, cb);
};
handleSliderBlur = () => {
events.removeEventsFromDocument(this.getKeyboardEvents());
};
handleSliderFocus = () => {
events.addEventsToDocument(this.getKeyboardEvents());
};
handleTouchEnd = () => {
this.end(this.getTouchEventMap());
};
handleTouchMove = (event) => {
this.move(events.getTouchPosition(event));
};
handleTouchStart = (event) => {
if (this.state.inputFocused) this.getInput().blur();
this.start(events.getTouchPosition(event));
events.addEventsToDocument(this.getTouchEventMap());
events.pauseEvent(event);
};
end(revents) {
events.removeEventsFromDocument(revents);
this.setState({ pressed: false });
}
knobOffset() {
const { max, min, value } = this.props;
return 100 * ((value - min) / (max - min));
}
move(position) {
const newValue = this.positionToValue(position);
if (newValue !== this.props.value) this.props.onChange(newValue);
}
positionToValue(position) {
const { sliderStart: start, sliderLength: length } = this.state;
const { max, min, step } = this.props;
const pos = ((position.x - start) / length) * (max - min);
return this.trimValue((Math.round(pos / step) * step) + min);
}
start(position) {
this.handleResize(null, () => {
this.setState({ pressed: true });
this.props.onChange(this.positionToValue(position));
});
}
stepDecimals() {
return (this.props.step.toString().split('.')[1] || []).length;
}
trimValue(value) {
if (value < this.props.min) return this.props.min;
if (value > this.props.max) return this.props.max;
return round(value, this.stepDecimals());
}
valueForInput(value) {
const decimals = this.stepDecimals();
return decimals > 0 ? value.toFixed(decimals) : value.toString();
}
renderSnaps() {
if (!this.props.snaps) return undefined;
return (
<div className={this.props.theme.snaps}>
{range(0, (this.props.max - this.props.min) / this.props.step).map(i =>
<div key={`span-${i}`} className={this.props.theme.snap} />,
)}
</div>
);
}
renderInput() {
if (!this.props.editable) return undefined;
return (
<Input
ref={(node) => { this.inputNode = node; }}
className={this.props.theme.input}
disabled={this.props.disabled}
onFocus={this.handleInputFocus}
onChange={this.handleInputChange}
onBlur={this.handleInputBlur}
value={this.state.inputFocused
? this.state.inputValue
: this.valueForInput(this.props.value)}
/>
);
}
render() {
const { theme } = this.props;
const knobStyles = { left: `${this.knobOffset()}%` };
const className = classnames(theme.slider, {
[theme.editable]: this.props.editable,
[theme.disabled]: this.props.disabled,
[theme.pinned]: this.props.pinned,
[theme.pressed]: this.state.pressed,
[theme.ring]: this.props.value === this.props.min,
}, this.props.className);
return (
<div
className={className}
disabled={this.props.disabled}
data-react-toolbox="slider"
onBlur={this.handleSliderBlur}
onFocus={this.handleSliderFocus}
style={this.props.style}
tabIndex="0"
>
<div
ref={(node) => { this.sliderNode = node; }}
className={theme.container}
onMouseDown={this.handleMouseDown}
onTouchStart={this.handleTouchStart}
>
<div
ref={(node) => { this.knobNode = node; }}
className={theme.knob}
onMouseDown={this.handleMouseDown}
onTouchStart={this.handleTouchStart}
style={knobStyles}
>
<div className={theme.innerknob} data-value={parseInt(this.props.value, 10)} />
</div>
<div className={theme.progress}>
<ProgressBar
disabled={this.props.disabled}
ref={(node) => { this.progressbarNode = node; }}
className={theme.innerprogress}
max={this.props.max}
min={this.props.min}
mode="determinate"
value={this.props.value}
buffer={this.props.buffer}
/>
{this.renderSnaps()}
</div>
</div>
{this.renderInput()}
</div>
);
}
}
return Slider;
};
const Slider = factory(InjectProgressBar, InjectInput);
export default themr(SLIDER)(Slider);
export { factory as sliderFactory };
export { Slider };
|
test/specs/collections/Table/TableFooter-test.js
|
Semantic-Org/Semantic-UI-React
|
import React from 'react'
import * as common from 'test/specs/commonTests'
import TableFooter from 'src/collections/Table/TableFooter'
describe('TableFooter', () => {
common.isConformant(TableFooter)
it('renders as a tfoot by default', () => {
shallow(<TableFooter />).should.have.tagName('tfoot')
})
})
|
packages/wix-style-react/src/FunnelChart/test/FunnelChart.spec.js
|
wix/wix-style-react
|
import React from 'react';
import { createRendererWithUniDriver, cleanup } from '../../../test/utils/unit';
import FunnelChart from '../FunnelChart';
import { funnelChartPrivateDriverFactory } from './FunnelChart.private.uni.driver';
describe(FunnelChart.displayName, () => {
const render = createRendererWithUniDriver(funnelChartPrivateDriverFactory);
const dataExample = [
{ value: 1000, label: 'visits' },
{ value: 800, label: 'views' },
{ value: 400, label: 'cart' },
];
afterEach(() => {
cleanup();
});
it('should render', async () => {
const data = [
{ value: 1000, label: 'visits' },
{ value: 800, label: 'views' },
];
const { driver } = render(<FunnelChart data={data} />);
expect(await driver.exists()).toBe(true);
});
describe('multiple items', () => {
it('data should contains atleast 2 items', async () => {
const data = [{ value: 1000, label: 'visits' }];
const driver = render(<FunnelChart data={data} />).driver;
expect(await driver.exists()).toBe(false);
});
it('should render 3 items with correct values & labels', async () => {
const driver = render(<FunnelChart data={dataExample} />).driver;
expect(await driver.exists()).toBe(true);
expect(await driver.getItemsCount()).toBe(3);
expect(await driver.getValueAt(0)).toBe('1000');
expect(await driver.getLabelAt(0)).toBe('visits');
expect(await driver.getValueAt(1)).toBe('800');
expect(await driver.getLabelAt(1)).toBe('views');
expect(await driver.getValueAt(2)).toBe('400');
expect(await driver.getLabelAt(2)).toBe('cart');
});
it('should render 3 items with display values and values', async () => {
const dataValues = [
{ value: 2000, label: 'visits', displayValue: '2K' },
{ value: 300000, label: 'views', displayValue: '300K' },
{ value: 150, label: 'cart' },
];
const driver = render(<FunnelChart data={dataValues} />).driver;
expect(await driver.exists()).toBe(true);
expect(await driver.getItemsCount()).toBe(3);
expect(await driver.getValueAt(0)).toBe('2K');
expect(await driver.getLabelAt(0)).toBe('visits');
expect(await driver.getValueAt(1)).toBe('300K');
expect(await driver.getLabelAt(1)).toBe('views');
expect(await driver.getValueAt(2)).toBe('150');
expect(await driver.getLabelAt(2)).toBe('cart');
});
it('should not render badges', async () => {
const driver = render(
<FunnelChart data={dataExample} hideDifferenceBadge />,
).driver;
expect(await driver.exists()).toBe(true);
expect(await driver.getDifferenceFromDataAt(0)).toBe(null);
});
it('should calculate percentage badge', async () => {
const driver = render(<FunnelChart data={dataExample} />).driver;
expect(await driver.exists()).toBe(true);
expect(await driver.getDifferenceFromDataAt(0)).toBe('80%');
expect(await driver.getDifferenceFromDataAt(1)).toBe('50%');
});
it('should not render badge after the last item', async () => {
const driver = render(<FunnelChart data={dataExample} />).driver;
expect(await driver.exists()).toBe(true);
expect(await driver.getDifferenceFromDataAt(2)).toBe(null);
});
it('should render badges tooltips', async () => {
const driver = render(
<FunnelChart
data={dataExample}
differenceBadgeTooltipContent={({ currentIndex, difference }) =>
`${difference} from ${dataExample[currentIndex].label} moved to ${
dataExample[currentIndex + 1].label
}`
}
/>,
).driver;
expect(await driver.exists()).toBe(true);
expect(await driver.getDifferenceTooltipFromDataAt(0)).toBe(
'80% from visits moved to views',
);
});
});
});
|
pewview/index.js
|
matthewcodes/PewView
|
window.$ = window.jQuery = require("jquery");
window.Tether = require('tether');
require('bootstrap');
require('./scss/index.scss');
import React from 'react';
import ReactDOM from 'react-dom';
import PewView from './components/PewView.jsx';
ReactDOM.render(<PewView />, document.getElementById('root'));
|
src/components/calendar/PersonalInfoSection.js
|
ChrisWhiten/react-rink
|
import React from 'react';
import {
HelpBlock,
FormGroup,
FormControl,
Col,
} from 'react-bootstrap';
import MaskedInput from 'react-text-mask';
import './styles/PersonalInfoSection.css';
function FieldGroup({ id, label, help, validationState, ...props }) {
return (
<FormGroup controlId={id} validationState={validationState}>
<FormControl {...props} />
{help && <HelpBlock>{help}</HelpBlock>}
</FormGroup>
);
}
class PersonalInfoSection extends React.Component {
constructor() {
super();
this.state = {
selectedBooking: null,
firstName: '',
};
// this.notEmpty = this._notEmpty.bind(this);
this.handleFirstNameChange = this.handleFirstNameChange.bind(this);
this.handleLastNameChange = this.handleLastNameChange.bind(this);
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handlePhoneNumberChange = this.handlePhoneNumberChange.bind(this);
}
// _notEmpty() {
// if (this.state.firstName === null) {
// return null;
// }
// return this.state.firstName.length > 0 ? 'success' : 'error';
// }
handleFirstNameChange(e) {
this.setState({
firstName: e.target.value,
});
}
handleLastNameChange(e) {
this.setState({
lastName: e.target.value,
});
}
handleEmailChange(e) {
this.setState({
email: e.target.value,
});
}
handlePhoneNumberChange(e) {
this.setState({
phoneNumber: e.target.value,
});
}
clear() {
this.setState({
phoneNumber: '',
email: '',
lastName: '',
firstName: '',
});
}
render() {
return (
<div>
<Col md={6} lg={6} sm={6} xs={12}>
<FieldGroup
id='first-name-id'
type='text'
placeholder='First name'
// validationState={this.notEmpty()}
onChange={this.handleFirstNameChange}
value={this.state.firstName}
/>
</Col>
<Col md={6} lg={6} sm={6} xs={12}>
<FieldGroup
id='last-name-id'
type='text'
onChange={this.handleLastNameChange}
placeholder='Last name'
/>
</Col>
<Col md={6} lg={6} sm={6} xs={12}>
<FieldGroup
id='email-id'
type='email'
placeholder='Email'
onChange={this.handleEmailChange}
/>
</Col>
<Col md={6} lg={6} sm={6} xs={12}>
<MaskedInput
className='form-control'
mask={['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]}
placeholder='(613) 555-5555'
name='phone-number'
id='phone-number-id'
type='tel'
onChange={this.handlePhoneNumberChange}
/>
{/* <FieldGroup
id='phone-number-id'
type='text'
placeholder='Phone number'
onChange={this.handlePhoneNumberChange}
/> */}
</Col>
</div>
);
}
}
PersonalInfoSection.propTypes = {
};
export default PersonalInfoSection;
|
app/app.js
|
prajapati-parth/glitchy
|
import React from 'react'
import ReactDOM from 'react-dom'
//import application main component
import AppComponent from '../app/components/app_component'
class App extends React.Component {
render() {
return (
<AppComponent />
)
}
}
//render back to mark-up file
ReactDOM.render(
<App />,
document.getElementById('content')
)
|
client/src/app/routes.js
|
jhuntoo/starhackit
|
import React from 'react';
import {Route, IndexRoute} from 'react-router';
import Login from 'views/login';
import Signup from 'views/signup';
import Forgot from 'views/forgot';
import Application from 'views/application';
import Logout from 'views/logout';
import MainLanding from 'views/mainLanding';
import RegistrationComplete from 'views/registrationComplete';
import ResetPassword from 'views/resetPassword';
import MyProfile from 'views/myProfile';
import Authenticated from 'components/authenticatedComponent';
import UsersView from 'parts/admin/usersView';
let routes = (
<Route component={Application} name="home" path="/">
<IndexRoute component={MainLanding}/>
<Route component={Login} path="login"/>
<Route component={Signup} path="signup"/>
<Route component={Logout} path="logout"/>
<Route component={Forgot} path="forgot"/>
<Route component={RegistrationComplete} name="verifyEmail" path="verifyEmail/:code"/>
<Route component={ResetPassword} name="ResetPasswordToken" path="resetPassword/:token"/>
<Route path="/admin" component={Authenticated}>
<IndexRoute component={UsersView}/>
<Route component={UsersView} path="users"/>
</Route>
<Route path="/app" component={Authenticated}>
<IndexRoute component={MyProfile}/>
<Route name="account" path="my">
<Route component={MyProfile} path="profile"/>
</Route>
</Route>
</Route>
);
export default routes;
|
examples/ModalWithBottomSheet.js
|
chris-gooley/react-materialize
|
import React from 'react';
import Modal from '../src/Modal';
import Button from '../src/Button';
export default
<Modal
header='Modal Header'
bottomSheet
trigger={<Button>MODAL BUTTOM SHEET STYLE</Button>}>
Lorem ipsum dolor sit amet, consectetur adipiscing 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
</Modal>;
|
app/javascript/mastodon/features/compose/components/poll_form.js
|
salvadorpla/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import IconButton from 'mastodon/components/icon_button';
import Icon from 'mastodon/components/icon';
import AutosuggestInput from 'mastodon/components/autosuggest_input';
import classNames from 'classnames';
const messages = defineMessages({
option_placeholder: { id: 'compose_form.poll.option_placeholder', defaultMessage: 'Choice {number}' },
add_option: { id: 'compose_form.poll.add_option', defaultMessage: 'Add a choice' },
remove_option: { id: 'compose_form.poll.remove_option', defaultMessage: 'Remove this choice' },
poll_duration: { id: 'compose_form.poll.duration', defaultMessage: 'Poll duration' },
minutes: { id: 'intervals.full.minutes', defaultMessage: '{number, plural, one {# minute} other {# minutes}}' },
hours: { id: 'intervals.full.hours', defaultMessage: '{number, plural, one {# hour} other {# hours}}' },
days: { id: 'intervals.full.days', defaultMessage: '{number, plural, one {# day} other {# days}}' },
});
@injectIntl
class Option extends React.PureComponent {
static propTypes = {
title: PropTypes.string.isRequired,
index: PropTypes.number.isRequired,
isPollMultiple: PropTypes.bool,
onChange: PropTypes.func.isRequired,
onRemove: PropTypes.func.isRequired,
onToggleMultiple: PropTypes.func.isRequired,
suggestions: ImmutablePropTypes.list,
onClearSuggestions: PropTypes.func.isRequired,
onFetchSuggestions: PropTypes.func.isRequired,
onSuggestionSelected: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleOptionTitleChange = e => {
this.props.onChange(this.props.index, e.target.value);
};
handleOptionRemove = () => {
this.props.onRemove(this.props.index);
};
handleToggleMultiple = e => {
this.props.onToggleMultiple();
e.preventDefault();
e.stopPropagation();
};
onSuggestionsClearRequested = () => {
this.props.onClearSuggestions();
}
onSuggestionsFetchRequested = (token) => {
this.props.onFetchSuggestions(token);
}
onSuggestionSelected = (tokenStart, token, value) => {
this.props.onSuggestionSelected(tokenStart, token, value, ['poll', 'options', this.props.index]);
}
render () {
const { isPollMultiple, title, index, intl } = this.props;
return (
<li>
<label className='poll__text editable'>
<span
className={classNames('poll__input', { checkbox: isPollMultiple })}
onClick={this.handleToggleMultiple}
role='button'
tabIndex='0'
/>
<AutosuggestInput
placeholder={intl.formatMessage(messages.option_placeholder, { number: index + 1 })}
maxLength={25}
value={title}
onChange={this.handleOptionTitleChange}
suggestions={this.props.suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
onSuggestionSelected={this.onSuggestionSelected}
searchTokens={[':']}
/>
</label>
<div className='poll__cancel'>
<IconButton disabled={index <= 1} title={intl.formatMessage(messages.remove_option)} icon='times' onClick={this.handleOptionRemove} />
</div>
</li>
);
}
}
export default
@injectIntl
class PollForm extends ImmutablePureComponent {
static propTypes = {
options: ImmutablePropTypes.list,
expiresIn: PropTypes.number,
isMultiple: PropTypes.bool,
onChangeOption: PropTypes.func.isRequired,
onAddOption: PropTypes.func.isRequired,
onRemoveOption: PropTypes.func.isRequired,
onChangeSettings: PropTypes.func.isRequired,
suggestions: ImmutablePropTypes.list,
onClearSuggestions: PropTypes.func.isRequired,
onFetchSuggestions: PropTypes.func.isRequired,
onSuggestionSelected: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleAddOption = () => {
this.props.onAddOption('');
};
handleSelectDuration = e => {
this.props.onChangeSettings(e.target.value, this.props.isMultiple);
};
handleToggleMultiple = () => {
this.props.onChangeSettings(this.props.expiresIn, !this.props.isMultiple);
};
render () {
const { options, expiresIn, isMultiple, onChangeOption, onRemoveOption, intl, ...other } = this.props;
if (!options) {
return null;
}
return (
<div className='compose-form__poll-wrapper'>
<ul>
{options.map((title, i) => <Option title={title} key={i} index={i} onChange={onChangeOption} onRemove={onRemoveOption} isPollMultiple={isMultiple} onToggleMultiple={this.handleToggleMultiple} {...other} />)}
</ul>
<div className='poll__footer'>
{options.size < 4 && (
<button className='button button-secondary' onClick={this.handleAddOption}><Icon id='plus' /> <FormattedMessage {...messages.add_option} /></button>
)}
<select value={expiresIn} onChange={this.handleSelectDuration}>
<option value={300}>{intl.formatMessage(messages.minutes, { number: 5 })}</option>
<option value={1800}>{intl.formatMessage(messages.minutes, { number: 30 })}</option>
<option value={3600}>{intl.formatMessage(messages.hours, { number: 1 })}</option>
<option value={21600}>{intl.formatMessage(messages.hours, { number: 6 })}</option>
<option value={86400}>{intl.formatMessage(messages.days, { number: 1 })}</option>
<option value={259200}>{intl.formatMessage(messages.days, { number: 3 })}</option>
<option value={604800}>{intl.formatMessage(messages.days, { number: 7 })}</option>
</select>
</div>
</div>
);
}
}
|
docs/src/components/nav.js
|
optimizely/nuclear-js
|
import React from 'react'
import { BASE_URL } from '../globals'
function urlize(uri) {
return BASE_URL + uri
}
export default React.createClass({
render() {
const logo = this.props.includeLogo
? <a href={BASE_URL} className="brand-logo">NuclearJS</a>
: null
const homeLink = this.props.includeLogo
? <li className="hide-on-large-only"><a href={urlize("")}>Home</a></li>
: null
return <div className="navbar-fixed">
<nav className="nav">
<div className="hide-on-large-only">
<ul className="right">
{homeLink}
<li><a href={urlize("docs/01-getting-started.html")}>Docs</a></li>
<li><a href={urlize("docs/07-api.html")}>API</a></li>
<li><a href="https://github.com/optimizely/nuclear-js">Github</a></li>
</ul>
</div>
<div className="nav-wrapper hide-on-med-and-down">
{logo}
<ul className="right">
<li><a href={urlize("docs/01-getting-started.html")}>Docs</a></li>
<li><a href={urlize("docs/07-api.html")}>API</a></li>
<li><a href="https://github.com/optimizely/nuclear-js">Github</a></li>
</ul>
</div>
</nav>
</div>
}
})
|
src/routes/About/components/Resume.js
|
mjchamoures/personalPortfolio
|
import React from 'react';
import { Panel } from 'react-bootstrap';
import ResumeImg from '../assets/Michael_Chamoures_Resume.png';
import ResumeImg2 from '../assets/Michael_Chamoures_Resume_2.png';
import './About.scss';
export const Resume = (props) => (
<Panel header="Resume">
<img
alt=''
className='resumeImg'
src={ResumeImg}
/>
<img
alt=''
className='resumeImg'
src={ResumeImg2}
/>
</Panel>
);
export default Resume;
|
frontend/test/app/containers/ExperimentPage-test.js
|
6a68/testpilot
|
import React from 'react';
import { expect } from 'chai';
import sinon from 'sinon';
import { shallow, mount } from 'enzyme';
import moment from 'moment';
import ExperimentPage, { ExperimentDetail } from '../../../src/app/containers/ExperimentPage';
import { initialState as newsletterState } from '../../../src/app/reducers/newsletter-form';
const CHANGE_HEADER_ON = 105;
describe('app/containers/ExperimentPage', () => {
const mockExperiment = {
slug: 'testing',
foo: 'bar'
};
const mockExperiments = [ mockExperiment ];
const mockParams = { slug: mockExperiment.slug };
const mockProps = {
getCookie: sinon.spy(),
removeCookie: sinon.spy(),
experiments: [ mockExperiment ],
getExperimentBySlug: slug => {
return slug === mockExperiment.slug ? mockExperiment : null;
},
params: { slug: mockExperiment.slug }
};
it('should pass the correct experiment to children', () => {
const wrapper = shallow(<ExperimentPage {...mockProps} />);
const child = wrapper.find(ExperimentDetail);
expect(child.props().experiment).to.equal(mockExperiment);
});
});
describe('app/containers/ExperimentPage:ExperimentDetail', () => {
let mockExperiment, mockClickEvent, props, subject;
beforeEach(() => {
mockExperiment = {
slug: 'testing',
title: 'Testing',
subtitle: 'Testing',
subtitle_l10nsuffix: 'foo',
thumbnail: '/thumbnail.png',
introduction: '<p class="test-introduction">Introduction!</p>',
measurements: [
'Measurement 0'
],
graduation_report: '<p class="test-graduation">Off to college!</p>',
description: 'Description',
pre_feedback_copy: null,
contribute_url: 'https://example.com/contribute',
bug_report_url: 'https://example.com/bugs',
discourse_url: 'https://example.com/discourse',
privacy_notice_url: 'https://example.com/privacy',
changelog_url: 'https://example.com/changelog',
survey_url: 'https://example.com/survey',
contributors: [
{
display_name: 'Jorge Soler',
title: 'Right Fielder',
avatar: '/soler.jpg'
}
],
details: [
{
headline: ' ',
image: '/img.jpg',
copy: 'Testing'
}
],
min_release: 48.0,
error: false
};
mockClickEvent = {
preventDefault: sinon.spy(),
stopPropagation: sinon.spy(),
target: {
offsetWidth: 100
}
};
props = {
isDev: false,
hasAddon: false,
experiments: [],
installed: {},
installedAddons: [],
params: {},
uninstallAddon: sinon.spy(),
navigateTo: sinon.spy(),
isAfterCompletedDate: sinon.stub().returns(false),
isExperimentEnabled: sinon.spy(),
requireRestart: sinon.spy(),
sendToGA: sinon.spy(),
openWindow: sinon.spy(),
enableExperiment: sinon.spy(),
disableExperiment: sinon.spy(),
getExperimentBySlug: sinon.spy(),
addScrollListener: sinon.spy(),
removeScrollListener: sinon.spy(),
getScrollY: sinon.spy(),
setScrollY: sinon.spy(),
getElementY: sinon.spy(),
getElementOffsetHeight: sinon.spy(),
setExperimentLastSeen: sinon.spy(),
getCookie: sinon.spy(),
removeCookie: sinon.spy(),
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:51.0) Gecko/20100101 Firefox/51.0',
newsletterForm: newsletterState,
setPageTitleL10N: sinon.spy()
};
subject = shallow(<ExperimentDetail {...props} />);
});
const findByL10nID = id => subject.findWhere(el => id === el.props()['data-l10n-id']);
const setExperiment = experiment => {
subject.setProps({
experiment,
experiments: [ experiment ]
});
return experiment;
};
it('should have the correct l10n IDs', () => {
setExperiment(mockExperiment);
// Title field not localized; see #1732.
expect(findByL10nID('testingTitle')).to.have.property('length', 0);
expect(findByL10nID('testingSubtitleFoo')).to.have.property('length', 1);
expect(findByL10nID('testingIntroduction')).to.have.property('length', 1);
expect(findByL10nID('testingContributors0Title')).to.have.property('length', 1);
expect(findByL10nID('testingDetails0Headline')).to.have.property('length', 1);
expect(findByL10nID('testingDetails0Copy')).to.have.property('length', 1);
// Fields only available when the add-on is installed.
subject.setProps({ hasAddon: true });
// The measurements section is rendered twice, for responsiveness reasons.
expect(findByL10nID('testingMeasurements0')).to.have.property('length', 2);
expect(findByL10nID('testingDescription')).to.have.property('length', 1);
});
it('should omit l10n IDs for dev-only content', () => {
setExperiment({ dev: true, ...mockExperiment });
expect(findByL10nID('testingSubtitleFoo')).to.have.property('length', 0);
expect(findByL10nID('testingIntroduction')).to.have.property('length', 0);
expect(findByL10nID('testingContributors0Title')).to.have.property('length', 0);
expect(findByL10nID('testingDetails0Headline')).to.have.property('length', 0);
expect(findByL10nID('testingDetails0Copy')).to.have.property('length', 0);
});
it('should render a loading page if no experiments are available', () => {
expect(subject.find('LoadingPage')).to.have.property('length', 1);
});
it('should render a 404 page if experiment is undefined', () => {
props = { ...props,
experiment: undefined,
experiments: [ { ...mockExperiment, slug: 'notit' } ]
};
subject.setProps(props);
expect(subject.find('NotFoundPage'))
.to.have.property('length', 1);
});
describe('with a valid experiment slug', () => {
beforeEach(() => {
setExperiment(mockExperiment);
subject.setProps({
isExperimentEnabled: experiment => false
});
});
it('should localize the page title', () => {
expect(props.setPageTitleL10N.called).to.be.true;
expect(props.setPageTitleL10N.lastCall.args).to.deep.equal([
'pageTitleExperiment', mockExperiment
]);
});
it('should render a 404 page if not on dev and launch date has not yet passed', () => {
setExperiment({ ...mockExperiment, launch_date: moment().add(1, 'days').utc() });
subject.setProps({ isDev: false });
expect(subject.find('NotFoundPage')).to.have.property('length', 1);
});
it('should not render a 404 page if launch date has passed', () => {
setExperiment({ ...mockExperiment, launch_date: moment().subtract(1, 'days').utc() });
subject.setProps({ isDev: false });
expect(subject.find('NotFoundPage')).to.have.property('length', 0);
});
it('should not render a 404 page if isDev, regardless of launch date', () => {
setExperiment({ ...mockExperiment, launch_date: moment().add(1, 'days').utc() });
subject.setProps({ isDev: true });
expect(subject.find('NotFoundPage')).to.have.property('length', 0);
});
it('should set last seen timestamp for experiment when rendered', () => {
expect(props.setExperimentLastSeen.called).to.be.true;
});
it('should clear both enabling & disabling state if experiment.inProgress changes', () => {
const prevExperiment = { ...mockExperiment, inProgress: true };
const nextExperiment = { ...mockExperiment, inProgress: false };
subject.setProps({ experiment: prevExperiment });
subject.setState({ isEnabling: true, isDisabling: true });
subject.setProps({ experiment: nextExperiment });
expect(subject.state('isEnabling')).to.be.false;
expect(subject.state('isDisabling')).to.be.false;
});
it('should show the tour dialog if shouldShowTourDialog is true and experiment then becomes enabled', () => {
// Flag the tour dialog to be shown, but experiment isn't enabled yet.
subject.setState({ shouldShowTourDialog: true });
// Tour dialog isn't shown yet...
expect(subject.state('shouldShowTourDialog')).to.be.true;
expect(subject.state('showTourDialog')).to.be.false;
expect(subject.find('ExperimentTourDialog')).to.have.property('length', 0);
// Enable the experiment...
subject.setProps({ isExperimentEnabled: experiment => true });
// Now show the tour dialog...
expect(subject.state('shouldShowTourDialog')).to.be.false;
expect(subject.state('showTourDialog')).to.be.true;
expect(subject.find('ExperimentTourDialog')).to.have.property('length', 1);
});
it('should render a warning only if incompatible add-ons are installed', () => {
expect(subject.find('.incompatible-addons')).to.have.property('length', 0);
const experiment = { ...mockExperiment, incompatible: { foo: 1, bar: 2 } };
subject.setProps({ experiment });
subject.setProps({ installedAddons: [ 'baz' ] });
expect(subject.find('.incompatible-addons')).to.have.property('length', 0);
subject.setProps({ installedAddons: [ 'baz', 'bar' ] });
expect(subject.find('.incompatible-addons')).to.have.property('length', 1);
});
it('should display installation count if over 100', () => {
const experiment = setExperiment({ ...mockExperiment, installation_count: '101' });
const el = findByL10nID('userCountContainer');
expect(el).has.property('length', 1);
expect(JSON.parse(el.prop('data-l10n-args')))
.to.have.property('installation_count', experiment.installation_count);
});
it('should display alternative message if installation count <= 100', () => {
setExperiment({ ...mockExperiment, installation_count: '99' });
const el = findByL10nID('userCountContainerAlt');
expect(el).has.property('length', 1);
});
it('should display a call-to-action to install Test Pilot', () => {
expect(subject.find('.experiment-promo')).to.have.property('length', 1);
expect(subject.find('MainInstallButton')).to.have.property('length', 1);
});
it('should display a call-to-action to try other experiments', () => {
const experiment = setExperiment(mockExperiment);
expect(subject.find('.card-list-header')).to.have.property('length', 1);
const cardList = subject.find('ExperimentCardList');
expect(cardList).to.have.property('length', 1);
expect(cardList.prop('except')).to.equal(experiment.slug);
});
describe('with hasAddon=true', () => {
beforeEach(() => {
subject.setProps({ hasAddon: true });
});
it('should not display a call-to-action to install Test Pilot', () => {
expect(subject.find('.experiment-promo')).to.have.property('length', 0);
expect(subject.find('MainInstallButton')).to.have.property('length', 0);
});
it('should show an email dialog if the first-run cookie is set', () => {
const getCookie = sinon.spy(name => 1);
const removeCookie = sinon.spy();
props = { ...props, hasAddon: true, getCookie, removeCookie }
subject = shallow(<ExperimentDetail {...props} />);
setExperiment(mockExperiment);
expect(subject.find('EmailDialog')).to.have.property('length', 1);
expect(removeCookie.called).to.be.true;
subject.setState({ showEmailDialog: false });
expect(subject.find('EmailDialog')).to.have.property('length', 0);
});
it('should not show a "Disable" button', () =>
expect(subject.find('#uninstall-button')).to.have.property('length', 0));
it('should not show a "Give Feedback" button', () =>
expect(subject.find('#feedback-button')).to.have.property('length', 0));
it('should show an "Enable" button', () =>
expect(subject.find('#install-button')).to.have.property('length', 1));
it('should show an "Your privacy" button', () =>
expect(subject.find('.highlight-privacy')).to.have.property('length', 1));
it('should enable experiment and schedule tour when "Enable" clicked', () => {
const experiment = setExperiment(mockExperiment);
subject.find('#install-button').simulate('click', mockClickEvent);
expect(props.enableExperiment.lastCall.args)
.to.deep.equal([experiment]);
expect(subject.state('isEnabling')).to.be.true;
expect(subject.state('isDisabling')).to.be.false;
expect(subject.state('shouldShowTourDialog')).to.be.true;
expect(subject.state('progressButtonWidth'))
.to.equal(mockClickEvent.target.offsetWidth);
expect(props.sendToGA.lastCall.args).to.deep.equal(['event', {
eventCategory: 'ExperimentDetailsPage Interactions',
eventAction: 'Enable Experiment',
eventLabel: experiment.title
}]);
});
it('should show the tour dialog when the "tour" link is clicked', () => {
subject.setState({ showTourDialog: false });
subject.find('a.showTour').simulate('click', mockClickEvent);
expect(subject.state('showTourDialog')).to.be.true;
expect(subject.find('ExperimentTourDialog')).to.have.property('length', 1);
});
it('should display a warning only if userAgent does not meet minimum version', () => {
const experiment = setExperiment({ ...mockExperiment, min_release: 50 });
const userAgentPre = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:51.0) Gecko/20100101 Firefox/';
subject.setProps({ userAgent: `${userAgentPre}23.0` });
expect(subject.find('.upgrade-notice')).to.have.property('length', 1);
expect(subject.find('.experiment-controls')).to.have.property('length', 0);
findByL10nID('upgradeNoticeLink').simulate('click', mockClickEvent);
expect(props.sendToGA.lastCall.args).to.deep.equal(['event', {
eventCategory: 'ExperimentDetailsPage Interactions',
eventAction: 'Upgrade Notice',
eventLabel: experiment.title
}]);
subject.setProps({ userAgent: `${userAgentPre}50.0` });
expect(subject.find('.upgrade-notice')).to.have.property('length', 0);
expect(subject.find('.experiment-controls')).to.have.property('length', 1);
subject.setProps({ userAgent: `${userAgentPre}51.0` });
expect(subject.find('.upgrade-notice')).to.have.property('length', 0);
expect(subject.find('.experiment-controls')).to.have.property('length', 1);
});
it('should display a banner if the experiment has an error status', () => {
setExperiment({ ...mockExperiment, error: true });
expect(subject.find('.details-header-wrapper').hasClass('has-status')).to.be.true;
expect(subject.find('.status-bar').hasClass('error')).to.be.true;
expect(findByL10nID('installErrorMessage')).to.have.property('length', 1);
});
it('should make the page header sticky on page scrolling', (done) => {
// Switch to mounted component to exercise componentDidMount
let scrollY = 0;
const genericElementHeight = 125;
const mountedProps = { ...props,
hasAddon: true,
getScrollY: () => scrollY,
getElementOffsetHeight: () => genericElementHeight,
experiments: [ mockExperiment ],
experiment: mockExperiment
};
const mountedSubject = mount(<ExperimentDetail {...mountedProps} />);
expect(props.addScrollListener.called).to.be.true;
expect(mountedSubject.state('useStickyHeader')).to.be.false;
expect(mountedSubject.find('.details-header-wrapper').hasClass('stick')).to.be.false;
const scrollListener = props.addScrollListener.lastCall.args[0];
scrollY = 300; // see CHANGE_HEADER_ON in the component
scrollListener();
// HACK: scrollListner() has a setTimeout(..., 1) so let's wait longer.
setTimeout(() => {
expect(mountedSubject.state('useStickyHeader')).to.be.true;
expect(mountedSubject.find('.details-header-wrapper').hasClass('stick')).to.be.true;
// Now, scroll back.
scrollY = 10;
scrollListener();
setTimeout(() => {
expect(mountedSubject.state('useStickyHeader')).to.be.false;
expect(mountedSubject.find('.details-header-wrapper').hasClass('stick')).to.be.false;
expect(mountedSubject.find('.details-header-wrapper.stick'))
.to.have.property('length', 0);
mountedSubject.unmount();
expect(props.removeScrollListener.called).to.be.true;
done();
}, 5);
}, 5);
});
it('should scroll down to measurements block when "Your privacy" clicked', (done) => {
const elementY = 400;
const genericElementHeight = 125;
subject.setProps({
getElementY: sel => elementY,
getElementOffsetHeight: () => genericElementHeight
});
subject.find('.highlight-privacy').simulate('click', mockClickEvent);
expect(props.setScrollY.lastCall.args[0]).to.equal(
elementY + (genericElementHeight - subject.state('privacyScrollOffset')));
expect(subject.state('useStickyHeader')).to.be.true;
expect(subject.state('highlightMeasurementPanel')).to.be.true;
// TODO: 5 second delay is too much. Skip until/unless we mock setTimeout.
done();
/*
setTimeout(() => {
expect(subject.state('highlightMeasurementPanel')).to.be.false;
done();
}, 5010);
*/
});
describe('with experiment enabled', () => {
beforeEach(() => {
subject.setProps({ isExperimentEnabled: experiment => true });
});
it('should show a "Disable" button', () =>
expect(subject.find('#uninstall-button')).to.have.property('length', 1));
it('should show a "Give Feedback" button', () =>
expect(subject.find('#feedback-button')).to.have.property('length', 1));
it('should not show an "Enable" button', () =>
expect(subject.find('#install-button')).to.have.property('length', 0));
it('should not show an "Your privacy" button', () =>
expect(subject.find('.highlight-privacy')).to.have.property('length', 0));
it('should disable experiment and show a dialog when "Disable" clicked', () => {
const experiment = setExperiment(mockExperiment);
subject.find('#uninstall-button').simulate('click', mockClickEvent);
expect(props.disableExperiment.lastCall.args)
.to.deep.equal([experiment]);
expect(subject.state('showDisableDialog')).to.be.true;
expect(subject.find('ExperimentDisableDialog')).to.have.property('length', 1);
expect(subject.state('isEnabling')).to.be.false;
expect(subject.state('isDisabling')).to.be.true;
expect(subject.state('progressButtonWidth'))
.to.equal(mockClickEvent.target.offsetWidth);
expect(props.sendToGA.lastCall.args).to.deep.equal(['event', {
eventCategory: 'ExperimentDetailsPage Interactions',
eventAction: 'Disable Experiment',
eventLabel: experiment.title
}]);
});
it('should have the expected survey URL on the "Give Feedback" button', () => {
subject.setProps({ installed: { foo: true, bar: true }, clientUUID: '38c51b84-9586-499f-ac52-94626e2b29cf' });
const button = subject.find('#feedback-button');
const expectedHref = 'https://example.com/survey?ref=givefeedback&experiment=Testing&cid=38c51b84-9586-499f-ac52-94626e2b29cf&installed=foo&installed=bar';
expect(button.prop('href')).to.equal(expectedHref);
});
it('should navigate to survey URL when "Give Feedback" clicked', () => {
const experiment = setExperiment(mockExperiment);
const button = subject.find('#feedback-button');
const expectedHref = button.prop('href');
mockClickEvent.target.getAttribute = name => expectedHref;
button.simulate('click', mockClickEvent);
expect(props.sendToGA.lastCall.args).to.deep.equal(['event', {
eventCategory: 'ExperimentDetailsPage Interactions',
eventAction: 'Give Feedback',
eventLabel: experiment.title,
outboundURL: expectedHref
}]);
});
it('should show a pre-feedback dialog when message available & "Give Feedback" clicked', () => {
setExperiment({ ...mockExperiment,
pre_feedback_copy: '<p class="preFeedback">Hello</p>' });
const button = subject.find('#feedback-button');
const expectedHref = button.prop('href');
mockClickEvent.target.getAttribute = name => expectedHref;
button.simulate('click', mockClickEvent);
expect(subject.state('showPreFeedbackDialog')).to.be.true;
const dialog = subject.find('ExperimentPreFeedbackDialog');
expect(dialog).to.have.property('length', 1);
expect(dialog.prop('surveyURL')).to.equal(expectedHref);
});
it('should display a banner when the experiment is enabled', () => {
expect(subject.find('.details-header-wrapper').hasClass('has-status')).to.be.true;
expect(subject.find('.status-bar').hasClass('enabled')).to.be.true;
expect(findByL10nID('isEnabledStatusMessage')).to.have.property('length', 1);
});
});
describe('with a completed experiment', () => {
beforeEach(() => {
subject.setProps({
experiment: Object.assign({}, mockExperiment, { completed: '2016-10-01' }),
isAfterCompletedDate: sinon.stub().returns(true)
});
});
it('does not render controls', () => {
expect(subject.find('.experiment-controls').length).to.equal(0);
});
it('displays the end date instead of install count', () => {
expect(findByL10nID('completedDateLabel').length).to.equal(1);
expect(findByL10nID('userCountContainer').length).to.equal(0);
expect(findByL10nID('userCountContainerAlt').length).to.equal(0);
});
it('displays the graduation report', () => {
expect(subject.find('.graduation-report').length).to.equal(1);
});
describe('with experiment enabled', () => {
beforeEach(() => {
subject.setProps({ isExperimentEnabled: experiment => true });
});
it('only renders the disable button control', () => {
expect(findByL10nID('giveFeedback').length).to.equal(0);
expect(findByL10nID('disableExperiment').length).to.equal(1);
expect(subject.find('#uninstall-button').hasClass('warning')).to.equal(true);
});
it('shows a modal dialog when the disable button is clicked', () => {
expect(subject.state('showEolDialog')).to.equal(false);
subject.find('#uninstall-button').simulate('click', mockClickEvent);
expect(subject.state('showEolDialog')).to.equal(true);
});
});
});
});
});
});
|
node_modules/react-router/es6/Link.js
|
FrancoCotter/ReactWeatherApp
|
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
import React from 'react';
import warning from './routerWarning';
var _React$PropTypes = React.PropTypes;
var bool = _React$PropTypes.bool;
var object = _React$PropTypes.object;
var string = _React$PropTypes.string;
var func = _React$PropTypes.func;
var oneOfType = _React$PropTypes.oneOfType;
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
function isEmptyObject(object) {
for (var p in object) {
if (object.hasOwnProperty(p)) return false;
}return true;
}
function createLocationDescriptor(to, _ref) {
var query = _ref.query;
var hash = _ref.hash;
var state = _ref.state;
if (query || hash || state) {
return { pathname: to, query: query, hash: hash, state: state };
}
return to;
}
/**
* A <Link> is used to create an <a> element that links to a route.
* When that route is active, the link gets the value of its
* activeClassName prop.
*
* For example, assuming you have the following route:
*
* <Route path="/posts/:postID" component={Post} />
*
* You could use the following component to link to that route:
*
* <Link to={`/posts/${post.id}`} />
*
* Links may pass along location state and/or query string parameters
* in the state/query props, respectively.
*
* <Link ... query={{ show: true }} state={{ the: 'state' }} />
*/
var Link = React.createClass({
displayName: 'Link',
contextTypes: {
router: object
},
propTypes: {
to: oneOfType([string, object]).isRequired,
query: object,
hash: string,
state: object,
activeStyle: object,
activeClassName: string,
onlyActiveOnIndex: bool.isRequired,
onClick: func
},
getDefaultProps: function getDefaultProps() {
return {
onlyActiveOnIndex: false,
className: '',
style: {}
};
},
handleClick: function handleClick(event) {
var allowTransition = true;
if (this.props.onClick) this.props.onClick(event);
if (isModifiedEvent(event) || !isLeftClickEvent(event)) return;
if (event.defaultPrevented === true) allowTransition = false;
// If target prop is set (e.g. to "_blank") let browser handle link.
/* istanbul ignore if: untestable with Karma */
if (this.props.target) {
if (!allowTransition) event.preventDefault();
return;
}
event.preventDefault();
if (allowTransition) {
var _props = this.props;
var to = _props.to;
var query = _props.query;
var hash = _props.hash;
var state = _props.state;
var _location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
this.context.router.push(_location);
}
},
render: function render() {
var _props2 = this.props;
var to = _props2.to;
var query = _props2.query;
var hash = _props2.hash;
var state = _props2.state;
var activeClassName = _props2.activeClassName;
var activeStyle = _props2.activeStyle;
var onlyActiveOnIndex = _props2.onlyActiveOnIndex;
var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']);
process.env.NODE_ENV !== 'production' ? warning(!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : undefined;
// Ignore if rendered outside the context of router, simplifies unit testing.
var router = this.context.router;
if (router) {
var _location2 = createLocationDescriptor(to, { query: query, hash: hash, state: state });
props.href = router.createHref(_location2);
if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) {
if (router.isActive(_location2, onlyActiveOnIndex)) {
if (activeClassName) props.className += props.className === '' ? activeClassName : ' ' + activeClassName;
if (activeStyle) props.style = _extends({}, props.style, activeStyle);
}
}
}
return React.createElement('a', _extends({}, props, { onClick: this.handleClick }));
}
});
export default Link;
|
Console/app/node_modules/rc-trigger/es/index.js
|
RisenEsports/RisenEsports.github.io
|
import _extends from 'babel-runtime/helpers/extends';
import React from 'react';
import PropTypes from 'prop-types';
import { findDOMNode } from 'react-dom';
import createReactClass from 'create-react-class';
import contains from 'rc-util/es/Dom/contains';
import addEventListener from 'rc-util/lib/Dom/addEventListener';
import Popup from './Popup';
import { getAlignFromPlacement, getPopupClassNameFromAlign as _getPopupClassNameFromAlign } from './utils';
import getContainerRenderMixin from 'rc-util/lib/getContainerRenderMixin';
function noop() {}
function returnEmptyString() {
return '';
}
function returnDocument() {
return window.document;
}
var ALL_HANDLERS = ['onClick', 'onMouseDown', 'onTouchStart', 'onMouseEnter', 'onMouseLeave', 'onFocus', 'onBlur'];
var Trigger = createReactClass({
displayName: 'Trigger',
propTypes: {
children: PropTypes.any,
action: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
showAction: PropTypes.any,
hideAction: PropTypes.any,
getPopupClassNameFromAlign: PropTypes.any,
onPopupVisibleChange: PropTypes.func,
afterPopupVisibleChange: PropTypes.func,
popup: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired,
popupStyle: PropTypes.object,
prefixCls: PropTypes.string,
popupClassName: PropTypes.string,
popupPlacement: PropTypes.string,
builtinPlacements: PropTypes.object,
popupTransitionName: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
popupAnimation: PropTypes.any,
mouseEnterDelay: PropTypes.number,
mouseLeaveDelay: PropTypes.number,
zIndex: PropTypes.number,
focusDelay: PropTypes.number,
blurDelay: PropTypes.number,
getPopupContainer: PropTypes.func,
getDocument: PropTypes.func,
destroyPopupOnHide: PropTypes.bool,
mask: PropTypes.bool,
maskClosable: PropTypes.bool,
onPopupAlign: PropTypes.func,
popupAlign: PropTypes.object,
popupVisible: PropTypes.bool,
maskTransitionName: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
maskAnimation: PropTypes.string
},
mixins: [getContainerRenderMixin({
autoMount: false,
isVisible: function isVisible(instance) {
return instance.state.popupVisible;
},
getContainer: function getContainer(instance) {
var props = instance.props;
var popupContainer = document.createElement('div');
popupContainer.style.position = 'absolute';
popupContainer.style.top = '0';
popupContainer.style.left = '0';
popupContainer.style.width = '100%';
var mountNode = props.getPopupContainer ? props.getPopupContainer(findDOMNode(instance)) : props.getDocument().body;
mountNode.appendChild(popupContainer);
return popupContainer;
}
})],
getDefaultProps: function getDefaultProps() {
return {
prefixCls: 'rc-trigger-popup',
getPopupClassNameFromAlign: returnEmptyString,
getDocument: returnDocument,
onPopupVisibleChange: noop,
afterPopupVisibleChange: noop,
onPopupAlign: noop,
popupClassName: '',
mouseEnterDelay: 0,
mouseLeaveDelay: 0.1,
focusDelay: 0,
blurDelay: 0.15,
popupStyle: {},
destroyPopupOnHide: false,
popupAlign: {},
defaultPopupVisible: false,
mask: false,
maskClosable: true,
action: [],
showAction: [],
hideAction: []
};
},
getInitialState: function getInitialState() {
var props = this.props;
var popupVisible = void 0;
if ('popupVisible' in props) {
popupVisible = !!props.popupVisible;
} else {
popupVisible = !!props.defaultPopupVisible;
}
return {
popupVisible: popupVisible
};
},
componentWillMount: function componentWillMount() {
var _this = this;
ALL_HANDLERS.forEach(function (h) {
_this['fire' + h] = function (e) {
_this.fireEvents(h, e);
};
});
},
componentDidMount: function componentDidMount() {
this.componentDidUpdate({}, {
popupVisible: this.state.popupVisible
});
},
componentWillReceiveProps: function componentWillReceiveProps(_ref) {
var popupVisible = _ref.popupVisible;
if (popupVisible !== undefined) {
this.setState({
popupVisible: popupVisible
});
}
},
componentDidUpdate: function componentDidUpdate(_, prevState) {
var props = this.props;
var state = this.state;
this.renderComponent(null, function () {
if (prevState.popupVisible !== state.popupVisible) {
props.afterPopupVisibleChange(state.popupVisible);
}
});
if (state.popupVisible) {
var currentDocument = void 0;
if (!this.clickOutsideHandler && this.isClickToHide()) {
currentDocument = props.getDocument();
this.clickOutsideHandler = addEventListener(currentDocument, 'mousedown', this.onDocumentClick);
}
if (!this.touchOutsideHandler) {
currentDocument = currentDocument || props.getDocument();
this.touchOutsideHandler = addEventListener(currentDocument, 'touchstart', this.onDocumentClick);
}
return;
}
this.clearOutsideHandler();
},
componentWillUnmount: function componentWillUnmount() {
this.clearDelayTimer();
this.clearOutsideHandler();
},
onMouseEnter: function onMouseEnter(e) {
this.fireEvents('onMouseEnter', e);
this.delaySetPopupVisible(true, this.props.mouseEnterDelay);
},
onMouseLeave: function onMouseLeave(e) {
this.fireEvents('onMouseLeave', e);
this.delaySetPopupVisible(false, this.props.mouseLeaveDelay);
},
onPopupMouseEnter: function onPopupMouseEnter() {
this.clearDelayTimer();
},
onPopupMouseLeave: function onPopupMouseLeave(e) {
if (e.relatedTarget && !e.relatedTarget.setTimeout && this._component && contains(this._component.getPopupDomNode(), e.relatedTarget)) {
return;
}
this.delaySetPopupVisible(false, this.props.mouseLeaveDelay);
},
onFocus: function onFocus(e) {
this.fireEvents('onFocus', e);
this.clearDelayTimer();
if (this.isFocusToShow()) {
this.focusTime = Date.now();
this.delaySetPopupVisible(true, this.props.focusDelay);
}
},
onMouseDown: function onMouseDown(e) {
this.fireEvents('onMouseDown', e);
this.preClickTime = Date.now();
},
onTouchStart: function onTouchStart(e) {
this.fireEvents('onTouchStart', e);
this.preTouchTime = Date.now();
},
onBlur: function onBlur(e) {
this.fireEvents('onBlur', e);
this.clearDelayTimer();
if (this.isBlurToHide()) {
this.delaySetPopupVisible(false, this.props.blurDelay);
}
},
onClick: function onClick(event) {
this.fireEvents('onClick', event);
if (this.focusTime) {
var preTime = void 0;
if (this.preClickTime && this.preTouchTime) {
preTime = Math.min(this.preClickTime, this.preTouchTime);
} else if (this.preClickTime) {
preTime = this.preClickTime;
} else if (this.preTouchTime) {
preTime = this.preTouchTime;
}
if (Math.abs(preTime - this.focusTime) < 20) {
return;
}
this.focusTime = 0;
}
this.preClickTime = 0;
this.preTouchTime = 0;
event.preventDefault();
var nextVisible = !this.state.popupVisible;
if (this.isClickToHide() && !nextVisible || nextVisible && this.isClickToShow()) {
this.setPopupVisible(!this.state.popupVisible);
}
},
onDocumentClick: function onDocumentClick(event) {
if (this.props.mask && !this.props.maskClosable) {
return;
}
var target = event.target;
var root = findDOMNode(this);
var popupNode = this.getPopupDomNode();
if (!contains(root, target) && !contains(popupNode, target)) {
this.close();
}
},
getPopupDomNode: function getPopupDomNode() {
if (this._component && this._component.getPopupDomNode) {
return this._component.getPopupDomNode();
}
return null;
},
getRootDomNode: function getRootDomNode() {
return findDOMNode(this);
},
getPopupClassNameFromAlign: function getPopupClassNameFromAlign(align) {
var className = [];
var props = this.props;
var popupPlacement = props.popupPlacement,
builtinPlacements = props.builtinPlacements,
prefixCls = props.prefixCls;
if (popupPlacement && builtinPlacements) {
className.push(_getPopupClassNameFromAlign(builtinPlacements, prefixCls, align));
}
if (props.getPopupClassNameFromAlign) {
className.push(props.getPopupClassNameFromAlign(align));
}
return className.join(' ');
},
getPopupAlign: function getPopupAlign() {
var props = this.props;
var popupPlacement = props.popupPlacement,
popupAlign = props.popupAlign,
builtinPlacements = props.builtinPlacements;
if (popupPlacement && builtinPlacements) {
return getAlignFromPlacement(builtinPlacements, popupPlacement, popupAlign);
}
return popupAlign;
},
getComponent: function getComponent() {
var props = this.props,
state = this.state;
var mouseProps = {};
if (this.isMouseEnterToShow()) {
mouseProps.onMouseEnter = this.onPopupMouseEnter;
}
if (this.isMouseLeaveToHide()) {
mouseProps.onMouseLeave = this.onPopupMouseLeave;
}
return React.createElement(
Popup,
_extends({
prefixCls: props.prefixCls,
destroyPopupOnHide: props.destroyPopupOnHide,
visible: state.popupVisible,
className: props.popupClassName,
action: props.action,
align: this.getPopupAlign(),
onAlign: props.onPopupAlign,
animation: props.popupAnimation,
getClassNameFromAlign: this.getPopupClassNameFromAlign
}, mouseProps, {
getRootDomNode: this.getRootDomNode,
style: props.popupStyle,
mask: props.mask,
zIndex: props.zIndex,
transitionName: props.popupTransitionName,
maskAnimation: props.maskAnimation,
maskTransitionName: props.maskTransitionName
}),
typeof props.popup === 'function' ? props.popup() : props.popup
);
},
setPopupVisible: function setPopupVisible(popupVisible) {
this.clearDelayTimer();
if (this.state.popupVisible !== popupVisible) {
if (!('popupVisible' in this.props)) {
this.setState({
popupVisible: popupVisible
});
}
this.props.onPopupVisibleChange(popupVisible);
}
},
delaySetPopupVisible: function delaySetPopupVisible(visible, delayS) {
var _this2 = this;
var delay = delayS * 1000;
this.clearDelayTimer();
if (delay) {
this.delayTimer = setTimeout(function () {
_this2.setPopupVisible(visible);
_this2.clearDelayTimer();
}, delay);
} else {
this.setPopupVisible(visible);
}
},
clearDelayTimer: function clearDelayTimer() {
if (this.delayTimer) {
clearTimeout(this.delayTimer);
this.delayTimer = null;
}
},
clearOutsideHandler: function clearOutsideHandler() {
if (this.clickOutsideHandler) {
this.clickOutsideHandler.remove();
this.clickOutsideHandler = null;
}
if (this.touchOutsideHandler) {
this.touchOutsideHandler.remove();
this.touchOutsideHandler = null;
}
},
createTwoChains: function createTwoChains(event) {
var childPros = this.props.children.props;
var props = this.props;
if (childPros[event] && props[event]) {
return this['fire' + event];
}
return childPros[event] || props[event];
},
isClickToShow: function isClickToShow() {
var _props = this.props,
action = _props.action,
showAction = _props.showAction;
return action.indexOf('click') !== -1 || showAction.indexOf('click') !== -1;
},
isClickToHide: function isClickToHide() {
var _props2 = this.props,
action = _props2.action,
hideAction = _props2.hideAction;
return action.indexOf('click') !== -1 || hideAction.indexOf('click') !== -1;
},
isMouseEnterToShow: function isMouseEnterToShow() {
var _props3 = this.props,
action = _props3.action,
showAction = _props3.showAction;
return action.indexOf('hover') !== -1 || showAction.indexOf('mouseEnter') !== -1;
},
isMouseLeaveToHide: function isMouseLeaveToHide() {
var _props4 = this.props,
action = _props4.action,
hideAction = _props4.hideAction;
return action.indexOf('hover') !== -1 || hideAction.indexOf('mouseLeave') !== -1;
},
isFocusToShow: function isFocusToShow() {
var _props5 = this.props,
action = _props5.action,
showAction = _props5.showAction;
return action.indexOf('focus') !== -1 || showAction.indexOf('focus') !== -1;
},
isBlurToHide: function isBlurToHide() {
var _props6 = this.props,
action = _props6.action,
hideAction = _props6.hideAction;
return action.indexOf('focus') !== -1 || hideAction.indexOf('blur') !== -1;
},
forcePopupAlign: function forcePopupAlign() {
if (this.state.popupVisible && this._component && this._component.alignInstance) {
this._component.alignInstance.forceAlign();
}
},
fireEvents: function fireEvents(type, e) {
var childCallback = this.props.children.props[type];
if (childCallback) {
childCallback(e);
}
var callback = this.props[type];
if (callback) {
callback(e);
}
},
close: function close() {
this.setPopupVisible(false);
},
render: function render() {
var props = this.props;
var children = props.children;
var child = React.Children.only(children);
var newChildProps = {};
if (this.isClickToHide() || this.isClickToShow()) {
newChildProps.onClick = this.onClick;
newChildProps.onMouseDown = this.onMouseDown;
newChildProps.onTouchStart = this.onTouchStart;
} else {
newChildProps.onClick = this.createTwoChains('onClick');
newChildProps.onMouseDown = this.createTwoChains('onMouseDown');
newChildProps.onTouchStart = this.createTwoChains('onTouchStart');
}
if (this.isMouseEnterToShow()) {
newChildProps.onMouseEnter = this.onMouseEnter;
} else {
newChildProps.onMouseEnter = this.createTwoChains('onMouseEnter');
}
if (this.isMouseLeaveToHide()) {
newChildProps.onMouseLeave = this.onMouseLeave;
} else {
newChildProps.onMouseLeave = this.createTwoChains('onMouseLeave');
}
if (this.isFocusToShow() || this.isBlurToHide()) {
newChildProps.onFocus = this.onFocus;
newChildProps.onBlur = this.onBlur;
} else {
newChildProps.onFocus = this.createTwoChains('onFocus');
newChildProps.onBlur = this.createTwoChains('onBlur');
}
return React.cloneElement(child, newChildProps);
}
});
export default Trigger;
|
client/src/components/FormWiget/KeywordSelect.js
|
Nonsoft/crdweb
|
import React from 'react';
import PropTypes from 'prop-types';
import { Form, Select} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const KeywordSelect = (props) => (
<FormItem label="关键字">
{props.getFieldDecorator('keyword')(
<Select style={{width: '100%'}} size="default" allowClear showSearch optionFilterProp="children" filterOption>
<Option value="-1">缺省</Option>
<Option value="0">全部</Option>
{props.keywordSelect.map(data => (
<Option key={data.id} value={data.id.toString()}>{data.keyword}</Option>
))}
</Select>
)}
</FormItem>
)
KeywordSelect.propTypes = {
keywordSelect: PropTypes.array,
getFieldDecorator: PropTypes.func.isRequired,
}
export default KeywordSelect;
|
internals/templates/containers/NotFoundPage/index.js
|
projectcashmere/web-server
|
/**
* NotFoundPage
*
* This is the page we show when the user visits a url that doesn't have a route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<h1>
<FormattedMessage {...messages.header} />
</h1>
);
}
}
|
lib/shared/components/link/index.js
|
relax/relax
|
import Component from 'components/component';
import React from 'react';
import PropTypes from 'prop-types';
import {dataConnect} from 'relate-js';
import Link from './link';
@dataConnect(
(state) => ({
editing: state.pageBuilder && state.pageBuilder.editing
}),
(props) => {
const {link} = props;
let result = {};
if (link && link.options && link.type === 'internal') {
const options = link.options;
if (options.page) {
result = {
fragments: {
page: {
_id: 1,
slug: 1
}
},
variablesTypes: {
page: {
_id: 'ID!'
}
},
initialVariables: {
page: {
_id: options.page
}
}
};
}
}
return result;
}
)
export default class LinkContainer extends Component {
static propTypes = {
link: PropTypes.object,
page: PropTypes.object,
editing: PropTypes.bool,
relate: PropTypes.object.isRequired
};
componentWillReceiveProps (nextProps) {
if (this.props.link !== nextProps.link && nextProps.link) {
this.props.relate.refresh(nextProps);
}
}
render () {
const {link, page, editing, ...props} = this.props;
return (
<Link
link={link}
item={page}
editing={editing}
{...props}
/>
);
}
}
|
test/client-tests/components/NavBar.js
|
RedCometLabs/hapi-react-couch
|
import React from 'react';
import { mount, describeWithDOM } from 'enzyme';
import NavBar from '../../../client/components/NavigationBar';
import {expect} from 'chai';
describeWithDOM('NavBar', () => {
it('renders the Navbar component correctly when the user is authenticated', () => {
const wrapper = mount(
<NavBar authenticated={true} />
);
const links = wrapper.find('li');
expect(links.length).to.equal(3);
const leftLinks = wrapper.instance().getLeftHeaderLinks();
const rightLinks = wrapper.instance().getRightHeaderLinks();
expect(leftLinks[0].key).to.equal('Dashboard');
expect(rightLinks[0].key).to.equal('Account');
expect(rightLinks[1].key).to.equal('Logout');
});
it('renders the Navbar component correctly when the user is NOT authenticated', () => {
const wrapper = mount(
<NavBar authenticated={false} />
);
const links = wrapper.find('li');
expect(links.length).to.equal(2);
const leftLinks = wrapper.instance().getLeftHeaderLinks();
const rightLinks = wrapper.instance().getRightHeaderLinks();
expect(rightLinks[0].key).to.equal('Login');
expect(rightLinks[1].key).to.equal('SignUp');
});
});
|
app/routes/index.js
|
rclai/redux-blog-example
|
import React from 'react';
import { Route } from 'react-router';
import App from './App';
import SignupRoute from './SignupRoute';
import LoginRoute from './LoginRoute';
import ProfileRoute from './ProfileRoute';
import NotFound from '../components/NotFound';
import redirectBackAfter from '../utils/redirectBackAfter';
import fillStore from '../utils/fillStore';
import DashboardRoute from './DashboardRoute';
import * as Posts from './Posts';
const routes = (
<Route component={App}>
<Route path="/signup" component={SignupRoute} />
<Route path="/login" component={LoginRoute} />
<Route path="/" component={Posts.List} />
<Route path="/posts/:id" component={Posts.View} />
<Route requireAuth>
<Route path="/profile" component={ProfileRoute} />
<Route path="/dashboard" component={DashboardRoute} />
<Route path="/dashboard/add" component={Posts.Edit} />
<Route path="/dashboard/edit/:id" component={Posts.Edit} />
</Route>
<Route path="*" component={NotFound} />
</Route>
);
function walk(routes, cb) {
cb(routes);
if (routes.childRoutes) {
routes.childRoutes.forEach(route => walk(route, cb));
}
return routes;
}
export default (store, client) => {
return walk(Route.createRouteFromReactElement(routes), route => {
route.onEnter = (nextState, transition) => {
const loggedIn = !!store.getState().auth.token;
if (route.requireAuth && !loggedIn) {
transition.to(...redirectBackAfter('/login', nextState));
} else if (client) {
fillStore(store, nextState, [route.component]);
}
};
});
};
|
projects/twitch-ui/src/components/GridCell.js
|
unindented/twitch-x
|
import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import ImageWithPlaceholder from './ImageWithPlaceholder'
import {truncate} from '../utils/css'
const GridCellRoot = styled.a`
display: block;
overflow: hidden;
flex: 1;
padding: ${props => props.theme.layout.gaps.medium};
color: inherit;
text-decoration: none;
&:hover {
color: ${props => props.theme.colors.highlight};
}
`
const GridCellFrame = styled.div`
padding: ${props => props.theme.layout.borders.small};
/* stylelint-disable-next-line */
${GridCellRoot}:hover & {
border: ${props => props.theme.layout.borders.medium} solid;
margin: -${props => props.theme.layout.borders.medium};
}
`
const GridCellName = styled.h3`
margin: ${props => props.theme.layout.gaps.small} 0 0;
font-size: ${props => props.theme.font.sizes.secondary};
font-weight: normal;
${truncate}
`
const GridCellInfo = styled.p`
margin: 0;
font-size: ${props => props.theme.font.sizes.tertiary};
${truncate}
`
export default function GridCell (props) {
const {href, image, name, viewers, channels, width, height, focused} = props
return (
<GridCellRoot
href={href}
>
<GridCellFrame
focused={focused}
>
<ImageWithPlaceholder
src={image}
width={width}
height={height}
/>
</GridCellFrame>
<GridCellName>
{name}
</GridCellName>
{viewers && (
<GridCellInfo>
{viewers} viewers
</GridCellInfo>
)}
{channels && (
<GridCellInfo>
{channels} channels
</GridCellInfo>
)}
</GridCellRoot>
)
}
GridCell.propTypes = {
href: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
viewers: PropTypes.number,
channels: PropTypes.number,
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
focused: PropTypes.bool
}
GridCell.defaultProps = {
focused: false
}
|
src/icons/AndroidPeople.js
|
fbfeix/react-icons
|
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class AndroidPeople extends React.Component {
render() {
if(this.props.bare) {
return <g>
<path d="M337.454,232c33.599,0,61.092-27.002,61.092-60c0-32.997-27.493-60-61.092-60s-61.09,27.003-61.09,60
C276.364,204.998,303.855,232,337.454,232z M174.546,232c33.599,0,61.09-27.002,61.09-60c0-32.997-27.491-60-61.09-60
s-61.092,27.003-61.092,60C113.454,204.998,140.947,232,174.546,232z M174.546,276C126.688,276,32,298.998,32,346v54h288v-54
C320,298.998,222.401,276,174.546,276z M337.454,287.003c-6.105,0-10.325,0-17.454,0.997c23.426,17.002,32,28,32,58v54h128v-54
C480,298.998,385.312,287.003,337.454,287.003z"></path>
</g>;
} return <IconBase>
<path d="M337.454,232c33.599,0,61.092-27.002,61.092-60c0-32.997-27.493-60-61.092-60s-61.09,27.003-61.09,60
C276.364,204.998,303.855,232,337.454,232z M174.546,232c33.599,0,61.09-27.002,61.09-60c0-32.997-27.491-60-61.09-60
s-61.092,27.003-61.092,60C113.454,204.998,140.947,232,174.546,232z M174.546,276C126.688,276,32,298.998,32,346v54h288v-54
C320,298.998,222.401,276,174.546,276z M337.454,287.003c-6.105,0-10.325,0-17.454,0.997c23.426,17.002,32,28,32,58v54h128v-54
C480,298.998,385.312,287.003,337.454,287.003z"></path>
</IconBase>;
}
};AndroidPeople.defaultProps = {bare: false}
|
src/components/login.js
|
lizarraldeignacio/personal-website
|
import React, { Component } from 'react';
import { reduxForm } from 'redux-form';
import { compose } from 'redux';
import { connect } from 'react-redux';
import FieldGroup from './fieldgroup';
import Recaptcha from 'react-recaptcha';
import { verifyReCaptcha } from '../actions/index';
import _ from 'lodash';
import {
firebaseConnect,
pathToJS
} from 'react-redux-firebase';
/**
Login component
--TODO: Refactoring
**/
/**
Form Fields
**/
const FIELDS = {
email: {
type: 'email',
label: 'Email address',
name: "email",
placeholder: 'Enter email',
inputIconClass: 'glyphicon glyphicon-user'
},
password: {
type: 'password',
label: 'Password',
name: "password",
placeholder: '',
inputIconClass: 'glyphicon glyphicon-lock'
}
}
class Login extends Component {
constructor(props) {
super(props);
this.state = {error : null};
}
renderField(fieldConfig) {
return (
<FieldGroup
type={fieldConfig.type}
key={fieldConfig.name}
name={fieldConfig.name}
label={fieldConfig.label}
placeholder={fieldConfig.placeholder}
inputIconClass={fieldConfig.inputIconClass}
inputClass={"input-field col s4 offset-s4"}
/>
);
}
handleFormSubmit(values) {
if (!this.props.login.recaptcha) {
this.setState({ error: "Invalid captcha." });
return;
}
this.props.firebase.login({ email: values.email, password: values.password })
.then((authData) => {
this.props.history.push('/');
}).catch((error) => {
const searchPattern = new RegExp('^' + 'auth/', 'i');
if (searchPattern.test(error.code)) {
this.setState({ error: "User or password is invalid." });
}
else {
this.setState({ error: "Try again later." });
}
});
}
renderAlert() {
console.log("Devuelvo mensaje");
}
render() {
return (
<div className="materialize-iso">
<div className="valign-wrapper">
<div className="container">
<form onSubmit={this.props.handleSubmit(this.handleFormSubmit.bind(this))}>
{_.map(FIELDS, (this.renderField.bind(this)))}
<div className="row">
<div className="col s4 offset-s4">
{this.state.error &&
<div className="red-text">
<strong>Oops!</strong> { this.state.error }
</div>
}
<Recaptcha
render="explicit"
onloadCallback={() => {}}
sitekey="6LeffSMUAAAAAFxpA7nvHyhRMrr3iKvBoAyolC7u"
verifyCallback={recaptchaCallback.bind(this)}
/>
<br/>
</div>
</div>
<div className="row">
<div className="center-btn">
{!this.props.auth &&
<button
className="waves-effect waves-light btn blue darken-1"
type="submit"
name="action"
disabled={!this.props.login.recaptcha}>
Login
</button>}
</div>
</div>
</form>
</div>
</div>
</div>
);
}
}
function recaptchaCallback(response) {
this.props.verifyReCaptcha(response);
}
function mapStateToProps(state) {
return {
login: state.login,
auth: pathToJS(state.firebase, 'auth')
};
}
/**
Validiation function, it validates each field on the form
**/
function validate(values) {
const errors = {};
_.each(FIELDS, (type, field) => {
if (!values[field]) {
errors[field] = `Please Enter a ${type['label']}`;
}
});
return errors;
}
/**
Redux form decorator
params:
form: The name of the form
fields: The fields of the form
validate: the validation function
**/
export default compose(
connect(mapStateToProps, { verifyReCaptcha }), firebaseConnect(), reduxForm({
validate,
form: 'LoginForm'
}))(Login);
|
src/plugins/position/components/SpacerRow.js
|
GriddleGriddle/Griddle
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from '../../../utils/griddleConnect';
import compose from 'recompose/compose';
import mapProps from 'recompose/mapProps';
import getContext from 'recompose/getContext';
import withHandlers from 'recompose/withHandlers';
const spacerRow = compose(
getContext({
selectors: PropTypes.object,
}),
connect((state, props) => {
const { topSpacerSelector, bottomSpacerSelector } = props.selectors;
const { placement } = props;
return {
spacerHeight: placement === 'top' ? topSpacerSelector(state, props) : bottomSpacerSelector(state, props),
};
}),
mapProps(props => ({
placement: props.placement,
spacerHeight: props.spacerHeight,
}))
)(class extends Component {
static propTypes = {
placement: PropTypes.string,
spacerHeight: PropTypes.number,
}
static defaultProps = {
placement: 'top'
}
// shouldComponentUpdate(nextProps) {
// const { currentPosition: oldPosition, placement: oldPlacement } = this.props;
// const { currentPosition, placement } = nextProps;
//
// return oldPosition !== currentPosition || oldPlacement !== placement;
// }
render() {
const { placement, spacerHeight } = this.props;
let spacerRowStyle = {
height: `${spacerHeight}px`,
};
return (
<tr key={placement + '-' + spacerHeight} style={spacerRowStyle}></tr>
);
}
});
export default spacerRow;
|
app/javascript/mastodon/features/account_gallery/index.js
|
dunn/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { fetchAccount } from 'mastodon/actions/accounts';
import { expandAccountMediaTimeline } from '../../actions/timelines';
import LoadingIndicator from 'mastodon/components/loading_indicator';
import Column from '../ui/components/column';
import ColumnBackButton from 'mastodon/components/column_back_button';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { getAccountGallery } from 'mastodon/selectors';
import MediaItem from './components/media_item';
import HeaderContainer from '../account_timeline/containers/header_container';
import { ScrollContainer } from 'react-router-scroll-4';
import LoadMore from 'mastodon/components/load_more';
import MissingIndicator from 'mastodon/components/missing_indicator';
import { openModal } from 'mastodon/actions/modal';
const mapStateToProps = (state, props) => ({
isAccount: !!state.getIn(['accounts', props.params.accountId]),
attachments: getAccountGallery(state, props.params.accountId),
isLoading: state.getIn(['timelines', `account:${props.params.accountId}:media`, 'isLoading']),
hasMore: state.getIn(['timelines', `account:${props.params.accountId}:media`, 'hasMore']),
});
class LoadMoreMedia extends ImmutablePureComponent {
static propTypes = {
shouldUpdateScroll: PropTypes.func,
maxId: PropTypes.string,
onLoadMore: PropTypes.func.isRequired,
};
handleLoadMore = () => {
this.props.onLoadMore(this.props.maxId);
}
render () {
return (
<LoadMore
disabled={this.props.disabled}
onClick={this.handleLoadMore}
/>
);
}
}
export default @connect(mapStateToProps)
class AccountGallery extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
attachments: ImmutablePropTypes.list.isRequired,
isLoading: PropTypes.bool,
hasMore: PropTypes.bool,
isAccount: PropTypes.bool,
multiColumn: PropTypes.bool,
};
state = {
width: 323,
};
componentDidMount () {
this.props.dispatch(fetchAccount(this.props.params.accountId));
this.props.dispatch(expandAccountMediaTimeline(this.props.params.accountId));
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) {
this.props.dispatch(fetchAccount(nextProps.params.accountId));
this.props.dispatch(expandAccountMediaTimeline(this.props.params.accountId));
}
}
handleScrollToBottom = () => {
if (this.props.hasMore) {
this.handleLoadMore(this.props.attachments.size > 0 ? this.props.attachments.last().getIn(['status', 'id']) : undefined);
}
}
handleScroll = e => {
const { scrollTop, scrollHeight, clientHeight } = e.target;
const offset = scrollHeight - scrollTop - clientHeight;
if (150 > offset && !this.props.isLoading) {
this.handleScrollToBottom();
}
}
handleLoadMore = maxId => {
this.props.dispatch(expandAccountMediaTimeline(this.props.params.accountId, { maxId }));
};
handleLoadOlder = e => {
e.preventDefault();
this.handleScrollToBottom();
}
handleOpenMedia = attachment => {
if (attachment.get('type') === 'video') {
this.props.dispatch(openModal('VIDEO', { media: attachment, status: attachment.get('status') }));
} else if (attachment.get('type') === 'audio') {
this.props.dispatch(openModal('AUDIO', { media: attachment, status: attachment.get('status') }));
} else {
const media = attachment.getIn(['status', 'media_attachments']);
const index = media.findIndex(x => x.get('id') === attachment.get('id'));
this.props.dispatch(openModal('MEDIA', { media, index, status: attachment.get('status') }));
}
}
handleRef = c => {
if (c) {
this.setState({ width: c.offsetWidth });
}
}
render () {
const { attachments, shouldUpdateScroll, isLoading, hasMore, isAccount, multiColumn } = this.props;
const { width } = this.state;
if (!isAccount) {
return (
<Column>
<MissingIndicator />
</Column>
);
}
if (!attachments && isLoading) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
let loadOlder = null;
if (hasMore && !(isLoading && attachments.size === 0)) {
loadOlder = <LoadMore visible={!isLoading} onClick={this.handleLoadOlder} />;
}
return (
<Column>
<ColumnBackButton multiColumn={multiColumn} />
<ScrollContainer scrollKey='account_gallery' shouldUpdateScroll={shouldUpdateScroll}>
<div className='scrollable scrollable--flex' onScroll={this.handleScroll}>
<HeaderContainer accountId={this.props.params.accountId} />
<div role='feed' className='account-gallery__container' ref={this.handleRef}>
{attachments.map((attachment, index) => attachment === null ? (
<LoadMoreMedia key={'more:' + attachments.getIn(index + 1, 'id')} maxId={index > 0 ? attachments.getIn(index - 1, 'id') : null} onLoadMore={this.handleLoadMore} />
) : (
<MediaItem key={attachment.get('id')} attachment={attachment} displayWidth={width} onOpenMedia={this.handleOpenMedia} />
))}
{loadOlder}
</div>
{isLoading && attachments.size === 0 && (
<div className='scrollable__append'>
<LoadingIndicator />
</div>
)}
</div>
</ScrollContainer>
</Column>
);
}
}
|
src/components/PlayerControls.js
|
jeremyfry/init-tracker
|
import React from 'react';
import PropTypes from 'prop-types';
const setColor = (color, led) => () => fetch(`/led/${led}/${color}`);
const PlayerControls = (props) =>{
return (
<div className="player-card__controls">
<button onClick={setColor('255/0/0', props.player.ledPosition)} className="player-card__red"></button>
<button onClick={setColor('0/0/255', props.player.ledPosition)} className="player-card__blue"></button>
<button onClick={setColor('0/255/0', props.player.ledPosition)} className="player-card__green"></button>
</div>
);
};
PlayerControls.propTypes = {
player: PropTypes.object.isRequired
};
export default PlayerControls;
|
src/index.js
|
zacfukuda/universal-app-react-router
|
import React from 'react'
import { render } from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import App from './App'
import './index.css'
render((
<BrowserRouter>
<App />
</BrowserRouter>
), document.getElementById('root'))
|
codes/chapter05/react-router-v4/basic/demo04/app/components/About.js
|
atlantis1024/react-step-by-step
|
import React from 'react';
class About extends React.PureComponent {
render() {
return <h2>关于</h2>
}
}
export default About;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.