path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
app/containers/Chat/message-box.js | VonIobro/ab-web | import React from 'react';
import PropTypes from 'prop-types';
class MessageBox extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
this.handleSend = this.handleSend.bind(this);
}
handleSend(event) {
if (event.which === 13) {
const text = this.input.value.trim();
event.preventDefault();
if (text.length > 0) {
this.props.onAddMessage(text);
this.input.value = '';
}
}
}
render() {
return (
<div>
<input
placeholder="enter message..."
onKeyDown={this.handleSend}
ref={(input) => { this.input = input; }}
style={{
width: '100%',
background: 'whitesmoke',
boxShadow: 'inset black 0 0 3px 0px',
padding: '10px',
fontSize: 'large',
}}
/>
</div>
);
}
}
MessageBox.propTypes = {
onAddMessage: PropTypes.func,
};
export default MessageBox;
|
app/containers/NotFoundPage/index.js | nathanhood/mmdb | import React from 'react';
import Helmet from 'react-helmet';
export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<div>
<Helmet>
<title>Page Not Found | MMDb</title>
</Helmet>
<h1>Not found</h1>
</div>
);
}
}
|
src/containers/challenges/Browse/BrowseView.js | OlivierVillequey/hackathon | /**
* Challenge Tabs Screen
* - Shows tabs, which contain challenge listings
*
* React Native Starter App
* https://github.com/mcnamee/react-native-starter-app
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
View,
StyleSheet,
InteractionManager,
} from 'react-native';
import { TabViewAnimated, TabBar } from 'react-native-tab-view';
// Consts and Libs
import { AppColors } from '@theme/';
// Containers
import ChallengeListing from '@containers/challenges/Listing/ListingContainer';
// Components
import { Text } from '@ui/';
import Loading from '@components/general/Loading';
/* Styles ==================================================================== */
const styles = StyleSheet.create({
// Tab Styles
tabContainer: {
flex: 1,
},
tabbar: {
backgroundColor: AppColors.brand.primary,
},
tabbarIndicator: {
backgroundColor: '#FFF',
},
tabbarText: {
color: '#FFF',
},
});
/* Component ==================================================================== */
let loadingTimeout;
class ChallengeTabs extends Component {
static componentName = 'CHallengeTabs';
static propTypes = {
challengeTypes: PropTypes.arrayOf(PropTypes.object).isRequired,
}
static defaultProps = {
challengeTypes: [],
}
constructor(props) {
super(props);
this.state = {
loading: true,
visitedRoutes: [],
};
}
/**
* Wait until any interactions are finished, before setting up tabs
*/
componentDidMount = () => {
InteractionManager.runAfterInteractions(() => {
this.setTabs();
});
}
componentWillUnmount = () => clearTimeout(loadingTimeout);
/**
* When challengeTypes are ready, populate tabs
*/
setTabs = () => {
const routes = [];
let idx = 0;
this.props.challengeTypes.forEach((challengeType) => {
routes.push({
key: idx.toString(),
id: challengeType.id.toString(),
title: challengeType.title,
});
idx += 1;
});
this.setState({
navigation: {
index: 0,
routes,
},
}, () => {
// Hack to prevent error showing
loadingTimeout = setTimeout(() => {
this.setState({ loading: false });
}, 100);
});
}
/**
* On Change Tab
*/
handleChangeTab = (index) => {
this.setState({
navigation: { ...this.state.navigation, index },
});
}
/**
* Header Component
*/
renderHeader = props => (
<TabBar
{...props}
style={styles.tabbar}
indicatorStyle={styles.tabbarIndicator}
renderLabel={scene => (
<Text style={[styles.tabbarText]}>{scene.route.title}</Text>
)}
/>
)
/**
* Which component to show
*/
renderScene = ({ route }) => {
// For performance, only render if it's this route, or I've visited before
if (
parseInt(route.key, 0) !== parseInt(this.state.navigation.index, 0) &&
this.state.visitedRoutes.indexOf(route.key) < 0
) {
return null;
}
// And Add this index to visited routes
if (this.state.visitedRoutes.indexOf(this.state.navigation.index) < 0) {
this.state.visitedRoutes.push(route.key);
}
// Which component should be loaded?
return (
<View style={styles.tabContainer}>
<ChallengeListing
challengeType={route.id}
/>
</View>
);
}
render = () => {
if (this.state.loading || !this.state.navigation) return <Loading />;
return (
<TabViewAnimated
style={[styles.tabContainer]}
renderScene={this.renderScene}
renderHeader={this.renderHeader}
navigationState={this.state.navigation}
onRequestChangeTab={this.handleChangeTab}
/>
);
}
}
/* Export Component ==================================================================== */
export default ChallengeTabs;
|
src/js/pages/App.js | ilken/LinkinParkRadio | import React from 'react';
import Radio from '../components/Radio';
export default class App extends React.Component {
render () {
return (<Radio/>);
}
}
|
src/common/components/vanilla-modules/breadcrumbs/index.js | canonical-websites/build.snapcraft.io | import PropTypes from 'prop-types';
import React from 'react';
import { Link } from 'react-router';
import style from '../../../style/vanilla/css/breadcrumbs.css';
const breadcrumbsStyle = (element = '', modifier = '') => {
element = element ? '__' + element : '';
modifier = modifier ? '--' + modifier : '';
const className = `p-breadcrumbs${element}${modifier}`;
return style[className];
};
export default function Breadcrumbs({ children }) {
return (
<ul className={ breadcrumbsStyle() }>
{ children }
</ul>
);
}
Breadcrumbs.propTypes = {
children: PropTypes.node
};
export function BreadcrumbsLink({ to, children }) {
return (
<li className={ breadcrumbsStyle('item') }>
{ to
? <Link className={ breadcrumbsStyle('link') } to={to}>{ children }</Link>
: children
}
</li>
);
}
BreadcrumbsLink.propTypes = {
to: PropTypes.string,
children: PropTypes.node
};
|
src/components/NotFound.js | bjacobel/rak | import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { notFound } from '../stylesheets/notFound.css';
import { link } from '../stylesheets/link.css';
export default class NotFound extends Component {
render() {
return (
<div>
<h1 className={notFound}>404: page not found</h1>
<Link className={link} to="/">
Home
</Link>
</div>
);
}
}
|
node_modules/react-select/src/utils/defaultArrowRenderer.js | darklilium/Factigis_2 | import React from 'react';
export default function arrowRenderer ({ onMouseDown }) {
return (
<span
className="Select-arrow"
onMouseDown={onMouseDown}
/>
);
};
|
node_modules/react-router/es6/RouterContext.js | silky098/Youtube-React-Search | var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
import invariant from 'invariant';
import React from 'react';
import deprecateObjectProperties from './deprecateObjectProperties';
import getRouteParams from './getRouteParams';
import { isReactChildren } from './RouteUtils';
import warning from './routerWarning';
var _React$PropTypes = React.PropTypes;
var array = _React$PropTypes.array;
var func = _React$PropTypes.func;
var object = _React$PropTypes.object;
/**
* A <RouterContext> renders the component tree for a given router state
* and sets the history object and the current location in context.
*/
var RouterContext = React.createClass({
displayName: 'RouterContext',
propTypes: {
history: object,
router: object.isRequired,
location: object.isRequired,
routes: array.isRequired,
params: object.isRequired,
components: array.isRequired,
createElement: func.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
createElement: React.createElement
};
},
childContextTypes: {
history: object,
location: object.isRequired,
router: object.isRequired
},
getChildContext: function getChildContext() {
var _props = this.props;
var router = _props.router;
var history = _props.history;
var location = _props.location;
if (!router) {
process.env.NODE_ENV !== 'production' ? warning(false, '`<RouterContext>` expects a `router` rather than a `history`') : void 0;
router = _extends({}, history, {
setRouteLeaveHook: history.listenBeforeLeavingRoute
});
delete router.listenBeforeLeavingRoute;
}
if (process.env.NODE_ENV !== 'production') {
location = deprecateObjectProperties(location, '`context.location` is deprecated, please use a route component\'s `props.location` instead. http://tiny.cc/router-accessinglocation');
}
return { history: history, location: location, router: router };
},
createElement: function createElement(component, props) {
return component == null ? null : this.props.createElement(component, props);
},
render: function render() {
var _this = this;
var _props2 = this.props;
var history = _props2.history;
var location = _props2.location;
var routes = _props2.routes;
var params = _props2.params;
var components = _props2.components;
var element = null;
if (components) {
element = components.reduceRight(function (element, components, index) {
if (components == null) return element; // Don't create new children; use the grandchildren.
var route = routes[index];
var routeParams = getRouteParams(route, params);
var props = {
history: history,
location: location,
params: params,
route: route,
routeParams: routeParams,
routes: routes
};
if (isReactChildren(element)) {
props.children = element;
} else if (element) {
for (var prop in element) {
if (Object.prototype.hasOwnProperty.call(element, prop)) props[prop] = element[prop];
}
}
if ((typeof components === 'undefined' ? 'undefined' : _typeof(components)) === 'object') {
var elements = {};
for (var key in components) {
if (Object.prototype.hasOwnProperty.call(components, key)) {
// Pass through the key as a prop to createElement to allow
// custom createElement functions to know which named component
// they're rendering, for e.g. matching up to fetched data.
elements[key] = _this.createElement(components[key], _extends({
key: key }, props));
}
}
return elements;
}
return _this.createElement(components, props);
}, element);
}
!(element === null || element === false || React.isValidElement(element)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The root route must render a single element') : invariant(false) : void 0;
return element;
}
});
export default RouterContext; |
docs/src/app/components/pages/components/Dialog/ExampleAlert.js | tan-jerene/material-ui | import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
/**
* Alerts are urgent interruptions, requiring acknowledgement, that inform the user about a situation.
*/
export default class DialogExampleAlert extends React.Component {
state = {
open: false,
};
handleOpen = () => {
this.setState({open: true});
};
handleClose = () => {
this.setState({open: false});
};
render() {
const actions = [
<FlatButton
label="Cancel"
primary={true}
onTouchTap={this.handleClose}
/>,
<FlatButton
label="Discard"
primary={true}
onTouchTap={this.handleClose}
/>,
];
return (
<div>
<RaisedButton label="Alert" onTouchTap={this.handleOpen} />
<Dialog
actions={actions}
modal={false}
open={this.state.open}
onRequestClose={this.handleClose}
>
Discard draft?
</Dialog>
</div>
);
}
}
|
src/screens/main/SearchModal/SearchHeader/SearchHeader.js | Barylskyigb/simple-debts-react-native | import React from 'react';
import { View } from 'react-native';
import { MKTextField } from 'react-native-material-kit';
import PropTypes from 'prop-types';
import Icon from 'react-native-vector-icons/Ionicons';
import TouchableArea from '../../../../components/TouchableArea/TouchableArea';
import styles from './SearchHeader.styles';
import * as colors from '../../../../utils/colors';
const RegHeader = ({ onBackPress, onTextChange }) => (
<View style={styles.header}>
<View style={styles.buttonWrapper}>
<TouchableArea onPress={onBackPress} borderless style={styles.backButton}>
<Icon name="ios-arrow-back" color={colors.black} size={30} />
</TouchableArea>
</View>
<Icon
name="ios-search"
size={20}
color={colors.gray}
style={styles.searchIcon}
/>
<MKTextField
placeholder="Email or username"
underlineEnabled={false}
tintColor="transparent"
onTextChange={onTextChange}
style={styles.container}
textInputStyle={styles.searchInput}
autoCapitalize="none"
autoCorrect={false}
/>
</View>
);
RegHeader.propTypes = {
onBackPress: PropTypes.func.isRequired,
onTextChange: PropTypes.func.isRequired
};
export default RegHeader;
|
client/modules/App/components/Header/Header.js | tranphong001/BIGVN | import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Navbar, Nav, NavItem, MenuItem, Glyphicon, Image, Form, FormGroup, InputGroup, FormControl, Button, NavDropdown, DropdownButton } from 'react-bootstrap';
import styles from './Header.css';
import grid from '../../../../grid.css';
import MenuItem2 from 'material-ui/MenuItem';
import { logout, setSearchString, setSearchCategory, setSearchCategoryName, setPageHeader, setExpanded, setIsTyping } from '../../AppActions';
import { getSearchCity, getUserName, getId, getFullName, getCategories, getBlogger, getNewser, getSearchCategory, getSearchString, getSearchCategoryName, getExpanded } from '../../AppReducer';
import FlatButton from 'material-ui/FlatButton';
import FontIcon from 'material-ui/FontIcon';
import Divider from 'material-ui/Divider';
import Drawer from 'material-ui/Drawer';
class Header extends Component {
constructor(props) {
super(props);
this.state = {
value: 'en',
open: false,
openUserMenu: false,
dataSource: [],
oldSearchCategory: '',
oldSearchCity: '',
oldSearchString: '--',
selected1: true,
selected2: false,
openForm: false,
};
this.loaded = false;
this.typing = false;
}
componentDidMount() {
this.loaded = true;
}
componentWillReceiveProps(nextProps) {
if (
(
nextProps.searchString !== this.state.oldSearchString ||
nextProps.searchCity !== this.state.oldSearchCity ||
nextProps.searchCategory !== this.state.searchCategory
) &&
nextProps.params &&
// this.typing &&
this.loaded
) {
// this.setState({ oldSearchString: nextProps.searchString, searchCategory: nextProps.searchCategory });
// let str = '/?';
// if (nextProps.searchCategory !== '') str += `searchCategory=${nextProps.searchCategory}`;
// if (str.length > 2) str += '&';
// if (nextProps.searchString !== '') str += `searchString=${nextProps.searchString}`;
// if (str.indexOf('searchString') > -1) str += '&';
// if (nextProps.searchCity !== '') str += `searchCity=${nextProps.searchCity}`;
// if (str.length === 2) str = '';
// this.context.router.push(str);
// this.props.dispatch(searchNews(str));
}
}
onClick = () => {
this.context.router.push('/');
this.props.dispatch(setSearchString(''));
};
onCreateNews = () => {
this.context.router.push('/news');
};
onCreateBlog = () => {
this.context.router.push('/blog');
};
handleUser = (selectedKey) => {
switch (selectedKey) {
case 'logOut': {
this.context.router.push('/');
this.props.dispatch(logout());
break;
}
default: break;
}
};
onFree = () => {
if (this.props.id !== '') {
this.context.router.push('/news');
} else {
this.context.router.push('/signin');
}
};
onLogOut = () => {
this.context.router.push('/');
this.props.dispatch(logout());
};
onSignIn = () => {
this.context.router.push('/signin');
};
onSignUp = () => {
this.context.router.push('/signup');
};
onManageNews = () => {
this.context.router.push('/managenews');
};
onManageBlog = () => {
this.context.router.push('/manageblogs');
};
onToggle = (expanded) => {
this.props.dispatch(setExpanded(expanded));
};
onSelected1 = () => {
this.setState({ selected1: true, selected2: false });
};
onSelected2 = () => {
this.setState({ selected1: false, selected2: true });
};
openForm = () => {
this.setState({ openForm: !this.state.openForm });
};
render() {
return (
<Navbar
className={`${grid.customNavbar} ${(this.state.openForm) ? (grid.customNavbarMoved) : ''}`}
collapseOnSelect
inverse
onToggle={this.onToggle}
expanded={false}
>
<Navbar.Header className={`${grid.customHeader}`}>
<div className={`${grid.logoAndToggle}`}>
<Navbar.Toggle className={grid.headerForm} style={{ marginRight: '0' }}/>
<div
onClick={this.onClick}
style={{
backgroundImage: 'url(/images/nextLogo.png)',
backgroundRepeat: 'no-repeat',
backgroundSize: '100%',
height: '35px',
width: '100px',
display: 'table-cell',
marginTop: '8px',
marginLeft: 'auto',
}}
/>
<Form className={`${grid.headerForm} ${(this.state.openForm) ? (styles.formWidthWhenOpen) : ''}`} style={{ marginLeft: 'auto' }}>
<FormGroup>
<InputGroup style={{ paddingTop: '3px' }}>
<DropdownButton
className={(this.state.openForm) ? (styles.openForm) : (styles.closeForm)}
componentClass={InputGroup.Button}
id="categoryDropDown"
title={this.props.searchCategoryName}
value={this.props.searchCategory}
style={{fontSize: '11pt', height: '32px', paddingTop: '6px', backgroundColor: 'white', backgroundImage: 'none' }}
>
<MenuItem
style={{ color: 'red' }}
onClick={() => {
this.props.dispatch(setSearchCategory(''));
this.props.dispatch(setSearchCategoryName('Tất cả danh mục'));
this.props.dispatch(setPageHeader('TIN TỨC MỚI NHẤT'));
}
}
>
Tất cả danh mục
</MenuItem>
{
this.props.categories.map((cate, index) => (
<MenuItem
key={index}
value={cate.alias}
onClick={() => {
this.props.dispatch(setSearchCategory(cate.alias));
this.props.dispatch(setSearchCategoryName(cate.title));
this.props.dispatch(setPageHeader(cate.title.toUpperCase()));
}
}
style={{fontSize: '11pt'}}
>
{cate.title}
</MenuItem>
))
}
</DropdownButton>
<FormControl
type="text"
style={{
borderLeft: 'none',
borderRight: 'none',
borderTop: '1px solid #ccc',
borderBottom: '1px solid #ccc',
fontSize: '11pt',
height: '32px',
display: (this.state.openForm) ? 'block' : 'none'
}}
value={this.props.searchString}
onBlur={() => {
this.setState({typing: false});
this.props.dispatch(setIsTyping(false));
}}
onFocus={() => {
this.props.dispatch(setIsTyping(true));
}}
onChange={(event) => {
this.props.dispatch(setSearchString(event.target.value));
this.typing = true;
}}
/>
<InputGroup.Button style={{ height: '32px' }}>
<Button
onClick={this.openForm}
style={{
borderLeft: 'none',
paddingTop: '7px',
paddingBottom: '3px',
paddingRight: '12px',
float: 'right',
backgroundColor: 'white',
backgroundImage: 'none',
}}
>
<Glyphicon glyph="glyphicon glyphicon-search" style={{fontSize: '16px'}}/>
</Button>
</InputGroup.Button>
</InputGroup>
</FormGroup>
</Form>
</div>
</Navbar.Header>
<Navbar.Collapse >
<Nav className={`${grid.centerizeNav} ${grid.customCollapse}`} style={{ paddingTop: '9px' }}>
<div className={styles.customForm}>
<Form>
<FormGroup>
<InputGroup style={{ paddingTop: '3px' }}>
<DropdownButton
componentClass={InputGroup.Button}
id="categoryDropDown"
title={this.props.searchCategoryName}
value={this.props.searchCategory}
style={{fontSize: '11pt', height: '32px', paddingTop: '6px', backgroundColor: 'white', backgroundImage: 'none'}}
>
<MenuItem
style={{ color: 'red' }}
onClick={() => {
this.props.dispatch(setSearchCategory(''));
this.props.dispatch(setSearchCategoryName('Tất cả danh mục'));
this.props.dispatch(setPageHeader('TIN TỨC MỚI NHẤT'));
}
}
>
Tất cả danh mục
</MenuItem>
{
this.props.categories.map((cate, index) => (
<MenuItem
key={index}
value={cate.alias}
onClick={() => {
this.props.dispatch(setSearchCategory(cate.alias));
this.props.dispatch(setSearchCategoryName(cate.title));
this.props.dispatch(setPageHeader(cate.title.toUpperCase()));
}
}
style={{fontSize: '11pt'}}
>
{cate.title}
</MenuItem>
))
}
</DropdownButton>
<FormControl
type="text"
style={{
borderLeft: 'none',
borderRight: 'none',
borderTop: '1px solid #ccc',
borderBottom: '1px solid #ccc',
fontSize: '11pt',
height: '32px'
}}
value={this.props.searchString}
onBlur={() => {
this.setState({typing: false});
this.props.dispatch(setIsTyping(false));
}}
onFocus={() => {
this.props.dispatch(setIsTyping(true));
}}
onChange={(event) => {
this.props.dispatch(setSearchString(event.target.value));
this.typing = true;
}}
/>
<InputGroup.Button style={{ height: '32px' }}>
<Button
style={{
borderLeft: 'none',
paddingTop: '7px',
paddingBottom: '3px',
paddingRight: '12px',
backgroundColor: 'white',
backgroundImage: 'none'
}}
>
<Glyphicon glyph="glyphicon glyphicon-search" style={{fontSize: '16px'}}/>
</Button>
</InputGroup.Button>
</InputGroup>
</FormGroup>
</Form>
</div>
</Nav>
{
(this.props.userName === '') ? (
<Nav className={`${grid.centerizeNav} ${grid.customCollapse}`} style={{ float: 'right', marginTop: '10px' }}>
<NavItem onSelect={this.onSignIn} className={styles.headerLogInButton}>
Đăng nhập
</NavItem>
<NavItem className={styles.verticalSpliter}>
</NavItem>
<NavItem onSelect={this.onSignUp} className={styles.headerLogOutButton}>
Đăng ký
</NavItem>
<NavItem className={styles.headerFreeButton}>
<FlatButton
icon={<FontIcon className="fa fa-pencil-square-o fa-5" style={{ fontSize: '16px' }}/>}
onClick={this.onFree}
label="ĐĂNG TIN MIỄN PHÍ"
labelStyle={{
fontSize: '13px'
}}
style={{
float: 'right',
font: '13px Arial, Arial',
textAlign: 'center',
backgroundColor: '#FF6600',
border: 0,
color: '#FFF',
padding: '0',
position: 'relative',
height: '30px',
width: '180px',
paddingRight: '0'
}}
/>
</NavItem>
</Nav>
) : (
<Nav className={`${styles.headerAfterLogIn} ${grid.customCollapse} ${grid.centerizeNav}`} onSelect={this.handleUser} style={{ float: 'right' }}>
<NavDropdown
pullRight
componentClass={InputGroup.Button}
id="newsDropDown"
title={this.props.userName}
>
{
(this.props.newser) ? (
<MenuItem onClick={this.onCreateNews}>
<Glyphicon glyph="glyphicon glyphicon-file" />
<span>Đăng tin rao vặt</span>
</MenuItem>
) : ''
}
{
(this.props.newser) ? (
<MenuItem onClick={this.onManageNews}>
<Glyphicon glyph="glyphicon glyphicon-duplicate" />
<span>Quản lý tin</span>
</MenuItem>
) : ''
}
{
(this.props.newser && this.props.blogger) ? (
<Divider />
) : ''
}
{
(this.props.blogger) ? (
<MenuItem onClick={this.onCreateBlog}>
<Glyphicon glyph="glyphicon glyphicon-inbox" />
<span>Đăng blog mới</span>
</MenuItem>
) : ''
}
{
(this.props.blogger) ? (
<MenuItem onClick={this.onManageBlog}>
<Glyphicon glyph="glyphicon glyphicon-list"/>
<span>Quản lý blog</span>
</MenuItem>
) : ''
}
<Divider />
<MenuItem onClick={this.onLogOut}>
<Glyphicon glyph="glyphicon glyphicon-log-out"/>
<span>Đăng xuất</span>
</MenuItem>
</NavDropdown>
<NavItem className={styles.headerFree2Button}>
<FlatButton
icon={<FontIcon className="fa fa-pencil-square-o fa-5" style={{ fontSize: '16px' }}/>}
onClick={this.onFree}
label="ĐĂNG TIN MIỄN PHÍ"
labelStyle={{
fontSize: '13px'
}}
style={{
float: 'right',
font: '13px Arial, Arial',
textAlign: 'center',
backgroundColor: '#FF6600',
border: 0,
color: '#FFF',
padding: '0',
position: 'relative',
height: '30px',
width: '180px',
paddingRight: '0'
}}
/>
</NavItem>
</Nav>
)
}
</Navbar.Collapse>
</Navbar>
);
}
}
function mapStateToProps(state) {
return {
userName: getUserName(state),
blogger: getBlogger(state),
newser: getNewser(state),
fullName: getFullName(state),
categories: getCategories(state),
id: getId(state),
searchCategory: getSearchCategory(state),
searchCategoryName: getSearchCategoryName(state),
searchString: getSearchString(state),
searchCity: getSearchCity(state),
expanded: getExpanded(state),
};
}
Header.propTypes = {
dispatch: PropTypes.func,
blogger: PropTypes.bool.isRequired,
newser: PropTypes.bool.isRequired,
userName: PropTypes.string.isRequired,
fullName: PropTypes.string.isRequired,
categories: PropTypes.array.isRequired,
id: PropTypes.string.isRequired,
searchCategory: PropTypes.string.isRequired,
searchCategoryName: PropTypes.string.isRequired,
searchString: PropTypes.string.isRequired,
expanded: PropTypes.bool.isRequired,
};
Header.contextTypes = {
router: PropTypes.object,
};
export default connect(mapStateToProps)(Header);
|
web/src/index.js | cardigann/cardigann | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootswatch/flatly/bootstrap.min.css';
import 'react-select/dist/react-select.min.css';
ReactDOM.render(<App />, document.getElementById('root')); |
src/svg-icons/places/free-breakfast.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesFreeBreakfast = (props) => (
<SvgIcon {...props}>
<path d="M20 3H4v10c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.11 0 2-.9 2-2V5c0-1.11-.89-2-2-2zm0 5h-2V5h2v3zM4 19h16v2H4z"/>
</SvgIcon>
);
PlacesFreeBreakfast = pure(PlacesFreeBreakfast);
PlacesFreeBreakfast.displayName = 'PlacesFreeBreakfast';
PlacesFreeBreakfast.muiName = 'SvgIcon';
export default PlacesFreeBreakfast;
|
client/src/header/LogoutButton.js | ziel5122/autograde | import React from 'react';
import { connect } from 'react-redux';
const style = {
fontSize: '16px',
lineHeight: '16px',
padding: '12px',
};
const LogoutButton = ({ logout }) => (
<div
className="logout"
onClick={logout}
role="button"
style={style}
tabIndex={0}
>
logout
<style jsx>{`
.logout {
cursor: hand;
cursor: pointer;
}
.logout:hover {
background: rgba(106, 90, 205, .25);
}
`}</style>
</div>
);
const mapDispatchToProps = dispatch => ({
logout() {
dispatch({
admin: false,
type: 'SET_ADMIN',
});
dispatch({
loggedIn: false,
type: 'SET_LOGGED_IN',
});
sessionStorage.removeItem('jwt');
},
});
export default connect(null, mapDispatchToProps)(LogoutButton);
|
react_this/setup.js | devSC/react-native | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View
} from 'react-native';
//this 指向
//1.如果一个函数中有this,但是它没有以对象方法的形式调用,而是以函数名的形式执行,那么this指向的就是全局对象。
/*
test() {
console.log(this)
}
* */
//2.如果一个函数中有this,并且这个函数是以对象方法的形式调用,那么this指向的就是调用该方法的对象。
var obj = {
test() {
console.log(this)
}
}
obj.test() //obj
//3.如果一个函数中有this,并且包含该函数的对象也同时被另一个对象所包含,尽管这个函数是被最外层的对象所调用,this指向的也只是它上一级的对象。
var obj = {
test: {
fun() {
console.log(this)
}
}
}
obj.test.fun() //test
//4.如果一个构造函数或类方法中有this,那么它指向由该构造函数或类创建出来的实例对象。
class Test {
constructor() {
this.test = 'test'; //this = 类示例
//4.1 强制绑定为当前类
this.option = this.option.bind(this)
}
option() {
console.log(this) //this指向调用该函数的 类 的this
}
//剪头函数
arrowOption = () => {
console.log(this) //Test
}
}
export default class setup extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Bind this
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
|
frontend/src/components/dialog/org-delete-member-dialog.js | miurahr/seahub | import React from 'react';
import PropTypes from 'prop-types';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
import { gettext, orgID } from '../../utils/constants';
import { seafileAPI } from '../../utils/seafile-api';
import { Utils } from '../../utils/utils';
import toaster from '../toast';
const propTypes = {
member: PropTypes.object.isRequired,
groupID: PropTypes.string.isRequired,
toggle: PropTypes.func.isRequired,
onMemberChanged: PropTypes.func.isRequired
};
class DeleteMemberDialog extends React.Component {
constructor(props) {
super(props);
}
deleteMember = () => {
const userEmail = this.props.member.email;
seafileAPI.orgAdminDeleteGroupMember(orgID, this.props.groupID, userEmail).then((res) => {
if (res.data.success) {
this.props.onMemberChanged();
this.props.toggle();
}
}).catch(error => {
let errMessage = Utils.getErrorMsg(error);
toaster.danger(errMessage);
});
}
render() {
let subtitle = gettext('Are you sure you want to delete {placeholder} ?');
subtitle = subtitle.replace('{placeholder}', '<span class="op-target">' + Utils.HTMLescape(this.props.member.name) + '</span>');
return (
<Modal isOpen={true} toggle={this.props.toggle}>
<ModalHeader toggle={this.props.toggle}>{gettext('Delete Member')}</ModalHeader>
<ModalBody>
<div dangerouslySetInnerHTML={{__html: subtitle}}></div>
</ModalBody>
<ModalFooter>
<Button color="primary" onClick={this.deleteMember}>{gettext('Delete')}</Button>
<Button color="secondary" onClick={this.props.toggle}>{gettext('Cancel')}</Button>
</ModalFooter>
</Modal>
);
}
}
DeleteMemberDialog.propTypes = propTypes;
export default DeleteMemberDialog;
|
src/components/HomePage/HomePage.js | alexbonine/react-starter-kit | /*
* React.js Starter Kit
* Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
'use strict';
import React from 'react';
export default React.createClass({
propTypes: {
body: React.PropTypes.string.isRequired
},
render() {
return <div className="ContentPage"
dangerouslySetInnerHTML={{__html: this.props.body}} />;
}
});
|
src/parser/shared/modules/others/DistanceMoved.js | fyruna/WoWAnalyzer | import React from 'react';
import { XYPlot, AreaSeries } from 'react-vis';
import { AutoSizer } from 'react-virtualized';
import 'react-vis/dist/style.css';
import { formatPercentage, formatThousands } from 'common/format';
import groupDataForChart from 'common/groupDataForChart';
import Statistic from 'interface/statistics/Statistic';
import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
const debug = false;
class DistanceMoved extends Analyzer {
lastPosition = null;
lastPositionChange = null;
totalDistanceMoved = 0;
timeSpentMoving = 0;
bySecond = {};
constructor(options) {
super(options);
this.addEventListener(Events.cast.by(SELECTED_PLAYER), this.updatePlayerPosition);
// These coordinates are for the target, so they are only accurate when done TO player
this.addEventListener(Events.damage.to(SELECTED_PLAYER), this.updatePlayerPosition);
this.addEventListener(Events.energize.to(SELECTED_PLAYER), this.updatePlayerPosition);
this.addEventListener(Events.heal.to(SELECTED_PLAYER), this.updatePlayerPosition);
this.addEventListener(Events.absorbed.to(SELECTED_PLAYER), this.updatePlayerPosition);
}
timeSinceLastMovement() {
return this.owner.currentTimestamp - this.lastPositionChange.timestamp;
}
// Data parsing
calculateDistance(x1, y1, x2, y2) {
return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) / 100;
}
updateTotalDistance(event) {
if (!this.lastPosition) {
return;
}
const distanceMoved = this.calculateDistance(this.lastPosition.x, this.lastPosition.y, event.x, event.y);
if (distanceMoved !== 0) {
this.timeSpentMoving += event.timestamp - this.lastPosition.timestamp;
this.totalDistanceMoved += distanceMoved;
const secondsIntoFight = Math.floor((event.timestamp - this.owner.fight.start_time) / 1000);
this.bySecond[secondsIntoFight] = (this.bySecond[secondsIntoFight] || 0) + distanceMoved;
}
}
updatePlayerPosition(event) {
if (!event.x || !event.y) {
return;
}
this.updateTotalDistance(event);
if (!this.lastPositionChange || this.lastPositionChange.x !== event.x || this.lastPositionChange.y !== event.y) {
this.lastPositionChange = event;
}
this.lastPosition = event;
}
statistic() {
debug && console.log(`Time spent moving: ${this.timeSpentMoving / 1000}s, Total distance moved: ${this.totalDistanceMoved} yds`);
const groupedData = groupDataForChart(this.bySecond, this.owner.fightDuration);
return (
<Statistic
position={STATISTIC_ORDER.UNIMPORTANT()}
tooltip={(
<>
Consider this when analyzing the fight, as some fights require more movement than others. Unnecessary movement can result in a DPS/HPS loss.<br /><br />
In ≈{formatThousands(this.timeSpentMoving / 1000)} seconds of movement you moved ≈{formatThousands(this.totalDistanceMoved)} yards (≈{formatThousands(this.totalDistanceMoved / (this.owner.fightDuration / 1000) * 60)} yards per minute). This statistic may not be entirely accurate for fights with lots of problems.
</>
)}
>
<div className="pad">
<label>Distance moved</label>
<div className="value">
≈ {formatThousands(this.totalDistanceMoved)} yards
<small style={{ marginLeft: 15 }}>
≈ {formatPercentage(this.timeSpentMoving / (this.owner.fightDuration))}%
</small>
</div>
<div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, width: '100%', height: '45%' }}>
<AutoSizer>
{({ width, height }) => (
<XYPlot
margin={0}
width={width}
height={height}
>
<AreaSeries
data={Object.keys(groupedData).map(x => ({
x: x / width,
y: groupedData[x],
}))}
className="primary"
/>
</XYPlot>
)}
</AutoSizer>
</div>
</div>
</Statistic>
);
}
}
export default DistanceMoved;
|
src/containers/universe.js | anshudutta/React-Conway | import React, { Component } from 'react';
import { connect } from 'react-redux';
import Unit from '../components/unit'
import {Cell} from '../middleware/cell'
class Universe extends Component {
constructor(props){
super(props);
this.state = {};
}
renderUniverse(){
const numOfRows = this.props.population.rows;
const cells = this.props.population.cells;
var orderByRows = new Array();
for (var i = 0; i < numOfRows; i++) {
const items = cells.filter(function(c, index){
return c.position.row == i;
});
orderByRows.push(items);
}
return orderByRows.map(function(item, index) {
var rows = item.map(function(cell, i) {
var cName = cell.state == 1 ? "bg-success" : "bg-danger";
return(
<td
key={i}
className={cName}>
</td>
/*
<Unit
data=
{
{
cellState : cell.state,
key : `row ${cell.position.row}, col ${cell.position.col}`
}
}>
</Unit>
*/
);
});
return <tr key={index}>{rows}</tr>;
});
}
render(){
return(
<div>
<table className="table table-responsive table-condensed table-bordered">
<tbody>
{this.renderUniverse()}
</tbody>
</table>
</div>
);
}
}
function mapStateToProps(state){
return {
population: state.population
};
}
export default connect(mapStateToProps)(Universe);
|
blueocean-material-icons/src/js/components/svg-icons/action/pets.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionPets = (props) => (
<SvgIcon {...props}>
<circle cx="4.5" cy="9.5" r="2.5"/><circle cx="9" cy="5.5" r="2.5"/><circle cx="15" cy="5.5" r="2.5"/><circle cx="19.5" cy="9.5" r="2.5"/><path d="M17.34 14.86c-.87-1.02-1.6-1.89-2.48-2.91-.46-.54-1.05-1.08-1.75-1.32-.11-.04-.22-.07-.33-.09-.25-.04-.52-.04-.78-.04s-.53 0-.79.05c-.11.02-.22.05-.33.09-.7.24-1.28.78-1.75 1.32-.87 1.02-1.6 1.89-2.48 2.91-1.31 1.31-2.92 2.76-2.62 4.79.29 1.02 1.02 2.03 2.33 2.32.73.15 3.06-.44 5.54-.44h.18c2.48 0 4.81.58 5.54.44 1.31-.29 2.04-1.31 2.33-2.32.31-2.04-1.3-3.49-2.61-4.8z"/>
</SvgIcon>
);
ActionPets.displayName = 'ActionPets';
ActionPets.muiName = 'SvgIcon';
export default ActionPets;
|
src/components/icons/PlusIcon.js | austinknight/ui-components | import React from 'react';
const PlusIcon = props => (
<svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 100 100">
{props.title && <title>{props.title}</title>}
<polygon points="55 25 45 25 45 45 25 45 25 55 45 55 45 75 55 75 55 55 75 55 75 45 55 45 55 25" />
</svg>
);
export default PlusIcon;
|
packages/arwes/src/Button/Button.js | romelperez/ui | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import AnimationComponent from '../Animation';
import HighlightComponent from '../Highlight';
import FrameComponent from '../Frame';
export default class Button extends Component {
static propTypes = {
Animation: PropTypes.any.isRequired,
Highlight: PropTypes.any.isRequired,
Frame: PropTypes.any.isRequired,
theme: PropTypes.any.isRequired,
classes: PropTypes.any.isRequired,
animate: PropTypes.bool,
show: PropTypes.bool,
animation: PropTypes.object,
/**
* It uses the `click` player.
*/
sounds: PropTypes.object,
layer: PropTypes.oneOf([
'primary',
'secondary',
'header',
'control',
'success',
'alert',
'disabled'
]),
disabled: PropTypes.bool,
active: PropTypes.bool,
/**
* The inside `<Frame />` level.
*/
level: PropTypes.number,
/**
* Props to pass down to the `<button />` element.
*/
buttonProps: PropTypes.object,
/**
* If function, receives the animation status object.
*/
children: PropTypes.any
};
static defaultProps = {
Animation: AnimationComponent,
Highlight: HighlightComponent,
Frame: FrameComponent,
sounds: {},
show: true,
layer: 'control',
level: 2
};
render() {
const {
Animation,
Highlight,
Frame,
theme,
classes,
sounds,
animation,
animate,
show,
layer,
level,
disabled,
active,
className,
buttonProps,
children,
...etc
} = this.props;
const cls = cx(classes.root, className);
return (
<Animation
show={show}
animate={animate}
timeout={theme.animTime}
{...animation}
>
{anim => (
<div className={cls} {...etc} onClick={this.onClick}>
<Frame
hover
animate={animate}
show={show}
corners={1}
level={level}
layer={disabled ? 'disabled' : layer}
disabled={disabled}
active={active}
>
<Highlight animate={!disabled} layer={layer}>
<button
className={classes.button}
disabled={disabled}
{...buttonProps}
>
{typeof children === 'function' ? children(anim) : children}
</button>
</Highlight>
</Frame>
</div>
)}
</Animation>
);
}
/**
* Internal click event listener.
* @param {Event} ev
*/
onClick = ev => {
const { disabled, onClick, animate, sounds } = this.props;
if (!disabled) {
onClick && onClick(ev);
if (animate) {
sounds.click && sounds.click.play();
}
}
};
}
|
src/index.js | RobGThai/ReduxTutorial | import _ from 'lodash';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail';
import secret from './_secret.js';
const YOUTUBE_API_KEY = secret.API_KEY;
// This is a class of a component
// To create an instance of this class use <App />
class App extends Component {
constructor(props) {
super(props);
this.state = {
videos: [],
selectedVideo: null
};
this.videoSearch('surfboards')
}
videoSearch(term) {
YTSearch({key: YOUTUBE_API_KEY, term: term }, (videos) => {
this.setState({
videos: videos,
selectedVideo: videos[0]
})
})
}
render() {
const videoSearch = _.debounce((term) => { this.videoSearch(term) }, 300);
return (
<div>
<SearchBar onSearchTermChange={videoSearch} />
<VideoDetail video={this.state.selectedVideo} />
<VideoList
onVideoSelect={ selectedVideo => this.setState({selectedVideo}) }
videos={this.state.videos} />
</div>
);
}
}
// Render App inside an element with class name 'container'
ReactDOM.render(<App />, document.querySelector('.container'));
|
client/index.js | johngodley/search-regex | /* global document, SearchRegexi10n */
import 'wp-plugin-lib/polyfill';
/**
* External dependencies
*/
import React from 'react';
import ReactDOM from 'react-dom';
import i18n from 'i18n-calypso';
import { registerLocale, setDefaultLocale } from 'react-datepicker';
/**
* Internal dependencies
*/
import App from './app';
const show = ( dom ) => {
// sigh
document.querySelector( '.jquery-migrate-deprecation-notice' ) &&
document.querySelector( '.jquery-migrate-deprecation-notice' ).remove();
i18n.setLocale( { '': SearchRegexi10n.locale } );
i18n.addTranslations( SearchRegexi10n.locale.translations );
const dateLocale = SearchRegexi10n.locale.localeSlug.replace( '_', '' );
setDefaultLocale( dateLocale );
ReactDOM.render( <App />, document.getElementById( dom ) );
};
if ( document.querySelector( '#react-ui' ) ) {
show( 'react-ui' );
}
window.searchregex = SearchRegexi10n.version;
|
src/index.js | yeying0827/gallery-by-react | import 'core-js/fn/object/assign';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/Main';
// Render the main component into the dom
ReactDOM.render(<App />, document.getElementById('app'));
|
src/svg-icons/av/video-call.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvVideoCall = (props) => (
<SvgIcon {...props}>
<path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4zM14 13h-3v3H9v-3H6v-2h3V8h2v3h3v2z"/>
</SvgIcon>
);
AvVideoCall = pure(AvVideoCall);
AvVideoCall.displayName = 'AvVideoCall';
export default AvVideoCall;
|
lib/ui/src/components/notifications/item.stories.js | storybooks/react-storybook | import React from 'react';
import NotificationItem from './item';
export default {
component: NotificationItem,
title: 'UI/Notifications/Item',
decorators: [storyFn => <div style={{ width: '240px', margin: '1rem' }}>{storyFn()}</div>],
excludeStories: /.*Data$/,
};
export const simpleData = {
id: '1',
content: '🎉 Storybook is cool!',
};
export const longData = {
id: '2',
content: '🎉 This is a long message that extends over two lines!',
};
export const linkData = {
id: '3',
content: '🎉 Storybook X.X is available! Download now »',
link: '/some/path',
};
export const simple = () => <NotificationItem notification={simpleData} />;
export const longText = () => <NotificationItem notification={longData} />;
export const withLink = () => <NotificationItem notification={linkData} />;
|
packages/xo-web/src/common/link.js | vatesfr/xo-web | import Link from 'react-router/lib/Link'
import PropTypes from 'prop-types'
import React from 'react'
import { routerShape } from 'react-router/lib/PropTypes'
import Component from './base-component'
// ===================================================================
export { Link as default }
// -------------------------------------------------------------------
const _IGNORED_TAGNAMES = {
A: true,
BUTTON: true,
INPUT: true,
SELECT: true,
}
export class BlockLink extends Component {
static propTypes = {
className: PropTypes.string,
tagName: PropTypes.string,
}
static contextTypes = {
router: routerShape,
}
_style = { cursor: 'pointer' }
_onClickCapture = event => {
const { currentTarget } = event
let element = event.target
while (element !== currentTarget) {
if (_IGNORED_TAGNAMES[element.tagName]) {
return
}
element = element.parentNode
}
event.stopPropagation()
if (event.ctrlKey || event.button === 1) {
window.open(this.context.router.createHref(this.props.to))
} else {
this.context.router.push(this.props.to)
}
}
_addAuxClickListener = ref => {
// FIXME: when https://github.com/facebook/react/issues/8529 is fixed,
// remove and use onAuxClickCapture.
// In Chrome ^55, middle-clicking triggers auxclick event instead of click
// Other browsers may trigger both events.
if (!!window.chrome && ref !== null) {
ref.addEventListener('auxclick', this._onClickCapture)
}
}
render() {
const { children, tagName = 'div', className } = this.props
const Component = tagName
return (
<Component
className={className}
ref={this._addAuxClickListener}
style={this._style}
onClickCapture={this._onClickCapture}
>
{children}
</Component>
)
}
}
|
client/extensions/woocommerce/woocommerce-services/views/shipping-label/label-purchase-modal/packages-step/index.js | Automattic/woocommerce-connect-client | /** @format */
/**
* External dependencies
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { localize, numberFormat } from 'i18n-calypso';
import { find, isEmpty } from 'lodash';
/**
* Internal dependencies
*/
import PackageList from './list';
import PackageInfo from './package-info';
import MoveItemDialog from './move-item';
import AddItemDialog from './add-item';
import StepConfirmationButton from '../step-confirmation-button';
import { hasNonEmptyLeaves } from 'woocommerce/woocommerce-services/lib/utils/tree';
import StepContainer from '../step-container';
import {
getShippingLabel,
isLoaded,
getFormErrors,
} from 'woocommerce/woocommerce-services/state/shipping-label/selectors';
import {
toggleStep,
confirmPackages,
} from 'woocommerce/woocommerce-services/state/shipping-label/actions';
// Display precision for various unit settings.
const PRECISION = {
g: 0,
oz: 1,
lbs: 3,
kg: 3,
}
const PackagesStep = props => {
const { siteId, orderId, selected, weightUnit, errors, expanded, translate } = props;
const packageIds = Object.keys( selected );
const itemsCount = packageIds.reduce(
( result, pId ) => result + selected[ pId ].items.length,
0
);
const totalWeight = packageIds.reduce( ( result, pId ) => result + selected[ pId ].weight, 0 );
const isValidPackages = 0 < packageIds.length;
const getContainerState = () => {
if ( ! isValidPackages ) {
return {
isError: true,
summary: translate( 'No packages selected' ),
};
}
const errorPackage = find( errors, pckg => ! isEmpty( pckg ) );
if ( errorPackage ) {
return {
isError: true,
summary: errorPackage[ Object.keys( errorPackage )[ 0 ] ],
};
}
const weightString = numberFormat( totalWeight, { decimals: PRECISION[ weightUnit ] } );
let summary = '';
if ( 1 === packageIds.length && 1 === itemsCount ) {
summary = translate( '1 item in 1 package: %(weight)s %(unit)s total', {
args: {
weight: weightString,
unit: weightUnit,
},
} );
} else if ( 1 === packageIds.length ) {
summary = translate( '%(itemsCount)d items in 1 package: %(weight)s %(unit)s total', {
args: {
itemsCount,
weight: weightString,
unit: weightUnit,
},
} );
} else {
summary = translate(
'%(itemsCount)d items in %(packageCount)d packages: %(weight)s %(unit)s total',
{
args: {
itemsCount,
packageCount: packageIds.length,
weight: weightString,
unit: weightUnit,
},
}
);
}
return { isSuccess: true, summary };
};
const toggleStepHandler = () => props.toggleStep( orderId, siteId, 'packages' );
const confirmPackagesHandler = () => props.confirmPackages( orderId, siteId );
return (
<StepContainer
title={ translate( 'Packaging' ) }
{ ...getContainerState() }
expanded={ expanded }
toggleStep={ toggleStepHandler }
>
<div className="packages-step__contents">
<PackageList siteId={ props.siteId } orderId={ props.orderId } />
<PackageInfo siteId={ props.siteId } orderId={ props.orderId } />
</div>
<StepConfirmationButton
disabled={ hasNonEmptyLeaves( errors ) || ! packageIds.length }
onClick={ confirmPackagesHandler }
>
{ translate( 'Use these packages' ) }
</StepConfirmationButton>
<MoveItemDialog siteId={ props.siteId } orderId={ props.orderId } />
<AddItemDialog siteId={ props.siteId } orderId={ props.orderId } />
</StepContainer>
);
};
PackagesStep.propTypes = {
siteId: PropTypes.number.isRequired,
orderId: PropTypes.number.isRequired,
selected: PropTypes.object.isRequired,
weightUnit: PropTypes.string.isRequired,
errors: PropTypes.object.isRequired,
expanded: PropTypes.bool,
};
const mapStateToProps = ( state, { orderId, siteId } ) => {
const loaded = isLoaded( state, orderId, siteId );
const shippingLabel = getShippingLabel( state, orderId, siteId );
const storeOptions = loaded ? shippingLabel.storeOptions : {};
return {
errors: loaded && getFormErrors( state, orderId, siteId ).packages,
weightUnit: storeOptions.weight_unit,
expanded: shippingLabel.form.packages.expanded,
selected: shippingLabel.form.packages.selected,
};
};
const mapDispatchToProps = dispatch => {
return bindActionCreators( { toggleStep, confirmPackages }, dispatch );
};
export default connect(
mapStateToProps,
mapDispatchToProps
)( localize( PackagesStep ) );
|
src/decorators/withViewport.js | carlosCeron/react-starter-kit | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
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/client/main.js | AlesJiranek/este | import React from 'react';
import ReactDOM from 'react-dom';
import Router from 'react-router';
import configureStore from '../common/configureStore';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import createEngine from 'redux-storage/engines/localStorage';
import createRoutes from './createRoutes';
import {IntlProvider} from 'react-intl';
import {Provider} from 'react-redux';
// TODO: Add app storage example.
// import storage from 'redux-storage';
const app = document.getElementById('app');
const engine = createEngine('este-app');
const initialState = window.__INITIAL_STATE__;
const store = configureStore({engine, initialState});
const routes = createRoutes(store.getState);
ReactDOM.render(
<Provider store={store}>
<IntlProvider>
<Router history={createBrowserHistory()}>
{routes}
</Router>
</IntlProvider>
</Provider>,
app,
() => {
// This is where state from local storage should be retrieved.
// storage.createLoader(engine)(store);
}
);
|
frame-react/src/component/repos.js | shenqingling/myTemplates | import React, { Component } from 'react';
export default class Repos extends Component {
render() {
return <div>
ReposPage
</div>
}
} |
src/modules/ImagePreview/component.js | svmn/ace-fnd | 'use strict';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Paper from 'material-ui/Paper';
import RefreshIndicator from 'material-ui/RefreshIndicator';
import IconButton from 'material-ui/IconButton';
import { fullWhite, lightBlack } from 'material-ui/styles/colors';
export default class ImagePreview extends Component {
constructor(props) {
super(props);
this.state = {
image: null
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.file) {
const reader = new FileReader();
reader.readAsDataURL(nextProps.file);
reader.onload = (e) => {
this.setState({ image: e.target.result });
};
} else {
this.setState({ image: null });
}
}
render() {
if (!this.state.image) {
return null;
}
const spinner = (
<RefreshIndicator
top={26}
left={26}
size={48}
status='loading'
loadingColor={fullWhite}
style={{ backgroundColor: lightBlack }}
/>
);
const closeButton = (
<IconButton
style={{
backgroundColor: lightBlack,
borderRadius: '50%'
}}
iconStyle={{
color: fullWhite
}}
iconClassName='material-icons'
onTouchTap={this.props.unset}
>close</IconButton>
);
return (
<Paper
style={{
height: '100px',
width: '100px',
position: 'absolute',
top: '-108px',
right: '16px',
backgroundSize: 'cover',
backgroundImage: `url('${this.state.image}')`,
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
}}
>
{
this.props.processing
? spinner
: closeButton
}
</Paper>
);
}
}
ImagePreview.propTypes = {
file: PropTypes.object,
processing: PropTypes.bool,
unset: PropTypes.func.isRequired
};
|
src/client/routes.js | AlexanderKapelyukhovskiy/rcn.io | import React from 'react'
import { Route, IndexRoute, Redirect } from 'react-router'
import App from 'App'
import Home from 'Home'
import Dev from 'Dev'
import MtbCalendar from 'calendar/MtbCalendar'
import NcncaCalendar from 'calendar/NcncaCalendar'
import NcncaDraftCalendar from 'calendar/NcncaDraftCalendar'
import EventDetails from 'calendar/events/event-details/EventDetails.jsx'
import AdminIndex from 'admin/index'
import CreateEventId from 'admin/events/CreateEventId.jsx'
const routes = (
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="/dev" component={Dev} />
<Route path="/calendars/norcal-mtb" component={MtbCalendar} />
<Route path="/calendars/ncnca-2017-draft" component={NcncaDraftCalendar} />
<Route path="/calendars/:calendarId" component={NcncaCalendar} />
<Route path="/events/:eventId" component={EventDetails}/>
<Redirect from="/mtb" to="/calendars/norcal-mtb" />
<Route path="admin" component={AdminIndex}>
<Route path="events/create-id" component={CreateEventId} />
</Route>
<Route path="*" component={Home}/>
</Route>
)
export default routes
|
admin/src/components/PopoutListItem.js | woody0907/keystone | import blacklist from 'blacklist';
import classnames from 'classnames';
import React from 'react';
var PopoutListItem = React.createClass({
displayName: 'PopoutListItem',
propTypes: {
icon: React.PropTypes.string,
iconHover: React.PropTypes.string,
iconHoverAlt: React.PropTypes.string,
isSelected: React.PropTypes.bool,
label: React.PropTypes.string.isRequired,
onClick: React.PropTypes.func,
},
getInitialState () {
return {
currentIcon: this.props.icon
};
},
setToActive (e) {
this.setState({ currentIcon: e.altKey ? this.props.iconHoverAlt : this.props.iconHover });
},
setToInactive (e) {
this.setState({ currentIcon: this.props.icon });
},
renderIcon () {
if (!this.props.icon) return null;
let iconClassname = classnames('PopoutList__item__icon octicon', ('octicon-' + this.state.currentIcon));
return <span className={iconClassname} />;
},
render () {
let itemClassname = classnames('PopoutList__item', {
'is-selected': this.props.isSelected
});
let props = blacklist(this.props, 'className', 'icon', 'isSelected', 'label');
return (
<button
type="button"
title={this.props.label}
className={itemClassname}
onFocus={this.setToActive}
onBlur={this.setToInactive}
onMouseOver={this.setToActive}
onMouseOut={this.setToInactive}
{...props}
>
{this.renderIcon()}
<span className="PopoutList__item__label">{this.props.label}</span>
</button>
);
}
});
module.exports = PopoutListItem;
|
frontend/node_modules/react-scripts/template/src/index.js | andres81/auth-service | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
src/app/components/CardExampleWithAvatar.js | leoliew/react-webpack-example | /**
* Created by leoliew on 2016/11/28.
*/
import React from 'react';
import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import ShowCaseCard from './ShowCaseCard';
const styles = {
card: {
margin: '2%'
}
};
class FlatButtonExampleSimple extends React.Component {
render() {
var showCase =
<Card >
<CardHeader
title="URL Avatar"
subtitle="Subtitle"
avatar="images/jsa-128.jpg"
/>
<CardMedia
overlay={<CardTitle title="Overlay title" subtitle="Overlay subtitle" />}
>
<img src="images/nature-600-337.jpg"/>
</CardMedia>
<CardTitle title="Card title" subtitle="Card subtitle"/>
<CardText>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi.
Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque.
Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio.
</CardText>
<CardActions>
<FlatButton label="Action1"/>
<FlatButton label="Action2"/>
</CardActions>
</Card>
;
return (
<ShowCaseCard
title="Simple example"
subtitle="The input is used to create the dataSource, so the input always matches three entries."
text={showCase}
/>
)
}
}
export default FlatButtonExampleSimple;
|
actor-apps/app-web/src/app/components/common/Stateful.react.js | liruqi/actor-platform-v0.9 | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
import _ from 'lodash';
import React from 'react';
import { AsyncActionStates } from 'constants/ActorAppConstants';
export class Root extends React.Component {
static propTypes = {
className: React.PropTypes.string,
currentState: React.PropTypes.number.isRequired,
children: React.PropTypes.array
};
constructor(props) {
super(props);
}
render() {
const { currentState, className, children } = this.props;
const equalsState = (state, type) => {
return (state === AsyncActionStates.PENDING && type === Pending) ||
(state === AsyncActionStates.PROCESSING && type === Processing) ||
(state === AsyncActionStates.SUCCESS && type === Success) ||
(state === AsyncActionStates.FAILURE && type === Failure)
};
const currentStateChild = _.find(children, (child) => {
if (equalsState(currentState, child.type)) return child;
});
return (
<div className={className}>{currentStateChild}</div>
)
}
}
export class Pending extends React.Component {
static propTypes = {
children: React.PropTypes.node
};
render() {
return this.props.children;
}
}
export class Processing extends React.Component {
static propTypes = {
children: React.PropTypes.node
};
render() {
return this.props.children;
}
}
export class Success extends React.Component {
static propTypes = {
children: React.PropTypes.node
};
render() {
return this.props.children;
}
}
export class Failure extends React.Component {
static propTypes = {
children: React.PropTypes.node
};
render() {
return this.props.children;
}
}
|
frontend/src/components/siteComponents/NewCollection/index.js | webrecorder/webrecorder | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Toggle from 'react-toggle';
import { Alert, Button, Form } from 'react-bootstrap';
import { defaultCollectionTitle } from 'config';
import { collection } from 'helpers/userMessaging';
import { GlobeIcon } from 'components/icons';
import Modal from 'components/Modal';
class NewCollection extends Component {
static propTypes = {
close: PropTypes.func,
createCollection: PropTypes.func,
creatingCollection: PropTypes.bool,
error: PropTypes.string,
showModal: PropTypes.bool,
visible: PropTypes.bool
};
constructor(props) {
super(props);
this.state = {
collTitle: defaultCollectionTitle,
isPublic: false
};
}
submit = (evt) => {
evt.stopPropagation();
evt.preventDefault();
const { collTitle, isPublic } = this.state;
this.props.createCollection(collTitle, isPublic);
}
focusInput = (evt) => {
this.input.setSelectionRange(0, this.state.collTitle.length);
}
handleInput = (evt) => {
this.setState({ collTitle: evt.target.value });
}
togglePublic = (evt) => {
this.setState({ isPublic: !this.state.isPublic });
}
titleValidation = () => {
return this.props.error ? 'error' : null;
}
render() {
const { close, creatingCollection, error, visible } = this.props;
const { collTitle, isPublic } = this.state;
return (
<Modal
closeCb={close}
header="Create New Collection"
visible={visible}>
<form onSubmit={this.submit} id="create-coll" className="form-horizontal">
{
error &&
<Alert variant="danger">
{ collection[error] || 'Error encountered' }
</Alert>
}
<Form.Group bsPrefix="form-group col-xs-5" validationState={this.titleValidation()}>
<Form.Label htmlFor="collection">Collection Name:</Form.Label>
<Form.Control id="collection" type="text" ref={(obj) => { this.input = obj; }} name="title" onFocus={this.focusInput} onChange={this.handleInput} value={collTitle} />
</Form.Group>
{
!__DESKTOP__ &&
<Form.Group>
<Form.Label htmlFor="public-switch"><GlobeIcon /> Make public (visible to all)?</Form.Label>
<div>
<Toggle
id="public-switch"
defaultChecked={isPublic}
onChange={this.togglePublic} />
</div>
</Form.Group>
}
<Button variant="primary" block onClick={this.submit} disabled={creatingCollection && !error}>Create</Button>
</form>
</Modal>
);
}
}
export default NewCollection;
|
app/javascript/src/components/rtc.js | michelson/chaskiq | import React from 'react'
import Button from './Button'
import { connect } from 'react-redux'
import Peer from 'simple-peer'
import { createPortal } from 'react-dom'
import usePortal from './hooks/usePortal'
import styled from '@emotion/styled'
// Broadcast Types
const JOIN_ROOM = 'JOIN_ROOM'
//const EXCHANGE = 'EXCHANGE'
//const REMOVE_USER = 'REMOVE_USER'
const START_CALL = 'START_CALL'
//const END_CALL = 'END_CALL'
const SIGNAL = 'SIGNAL'
const INIT = 'INIT'
const READY = 'READY'
const CLOSE_SESSION = 'CLOSE_SESSION'
const REJECT_CALL = 'REJECT_CALL'
// Ice Credentials
function getDisplayStream () {
return navigator.mediaDevices.getDisplayMedia()
}
class VideoCall {
peer = null
init = (stream, initiator) => {
this.peer = new Peer({
initiator: initiator,
stream: stream,
trickle: false,
reconnectTimer: 1000,
iceTransportPolicy: 'relay',
config: {
iceServers: [
{ urls: ['stun:stun4.l.google.com:19302'] }
/* {
urls: process.env.REACT_APP_TURN_SERVERS.split(','),
username: process.env.REACT_APP_TURN_USERNAME,
credential: process.env.REACT_APP_TURN_CREDENCIAL
}, */
]
}
})
// console.log("inicializó peer", this.peer)
return this.peer
}
connect = (otherId) => {
// console.log("CONNECTING PEER", this.peer)
this.peer.signal(otherId)
}
}
let gstream = null
export function RtcView (props) {
const currentUser = props.current_user.email
const localVideo = React.useRef(null)
const remoteVideoContainer = React.useRef(null)
const documentObject = props.document || document
//const target = usePortal(props.buttonElement, documentObject)
const infoTarget = usePortal(props.infoElement, documentObject)
const localVideoTarget = usePortal(props.localVideoElement, documentObject)
const remoteVideoTarget = usePortal(props.remoteVideoElement, documentObject)
const callStatusTarget = usePortal(props.callStatusElement, documentObject)
const callInitiatorTarget = usePortal(props.callInitiatorElement, documentObject)
const callButtonsTarget = usePortal(props.callButtonsElement, documentObject)
const [localStream, setLocalStream] = React.useState({})
//const [remoteStreamUrl, setRemoteStreamUrl] = React.useState('')
const [_streamUrl, setStreamUrl] = React.useState('')
const [initiator, setInitiator] = React.useState(false)
const [peer, setPeer] = React.useState({})
//const [full, setFull] = React.useState(false)
const [connecting, setConnecting] = React.useState(false)
const [waiting, setWaiting] = React.useState(true)
const [callStarted, setCallStarted] = React.useState(false)
const videoCall = new VideoCall()
React.useEffect(() => {
// returned function will be called on component unmount
return () => {
// console.log("unmount!", localStream)
removePeers()
}
}, [])
React.useEffect(() => {
if (!props.video) return
startCall()
}, [props.video])
React.useEffect(() => {
// console.log("LOCAL STREAM CHANGED?", localStream )
gstream = localStream
}, [localStream.id])
React.useEffect(() => {
// console.log("RTC CHANGED!", props.rtc)
handleRtcData()
}, [props.rtc])
React.useEffect(() => {
setAudioLocal()
setVideoLocal()
}, [props.rtcVideo, props.rtcAudio])
function startCall () {
getUserMedia().then(() => {
broadcastJoinSession()
})
}
function broadcastData (data) {
const a = {
type: 'rtc_events',
app: props.appKey,
conversation_id: props.conversation.key
}
const params = Object.assign({}, data, a)
// console.log('BROADCAST', params)
props.events.perform('rtc_events', params)
}
function broadcastJoinSession () {
broadcastData({
event_type: JOIN_ROOM,
from: currentUser
})
}
function stopUserMedia () {
removePeers()
}
function getUserMedia (_cb) {
return new Promise((resolve, _reject) => {
/* const op = {
video: {
enabled: props.rtcVideo,
width: { min: 160, ideal: 640, max: 1280 },
height: { min: 120, ideal: 360, max: 720 }
},
audio: {
enabled: props.rtcAudio,
noiseSuppression: true,
echoCancellation: true,
autoGainControl: true,
sampleRate: 44000,
channelCount: {
ideal: 1
},
volume: 0.9
},
}; */
const op = {
audio: true,
video: true
}
navigator.mediaDevices.getUserMedia(op).then(gotMedia).catch((err) => {
console.log('error on RTC', err)
})
function gotMedia (stream) {
setLocalStream(stream)
setStreamUrl(stream)
localVideo.current.srcObject = stream
localVideo.current.muted = true
localVideo.current.setAttribute('muted', 'muted')
localVideo.current.volume = 0
resolve()
}
})
}
function setAudioLocal () {
if (localStream.getAudioTracks &&
localStream.getAudioTracks().length > 0) {
localStream.getAudioTracks().forEach(track => {
track.enabled = props.rtcAudio //! track.enabled;
})
}
}
function setVideoLocal () {
if (localStream.getVideoTracks &&
localStream.getVideoTracks().length > 0) {
localStream.getVideoTracks().forEach(track => {
track.enabled = props.rtcVideo
})
}
}
function getDisplay () {
getDisplayStream().then(stream => {
stream.oninactive = () => {
peer.removeStream(localStream)
getUserMedia().then(() => {
peer.addStream(localStream)
})
}
setStreamUrl(stream)
setLocalStream(stream)
localVideo.current.srcObject = stream
peer.addStream(stream)
})
}
function requestCall () {
broadcastData({
event_type: START_CALL,
from: currentUser
})
setWaiting(true)
setCallStarted(true)
}
function handleRtcData () {
/* socket.on('full', () => {
component.setState({ full: true });
}); */
const data = props.rtc
if (data.from === currentUser) return
if (data.event_type === START_CALL) setCallStarted(true)
if (!props.video) return
switch (data.event_type) {
case JOIN_ROOM:
// console.log('join room!', data)
return enter(data)
case SIGNAL:
const signal = data.signal
if (signal.type === 'offer' && initiator) return
if (signal.type === 'answer' && !initiator) return
return call(signal)
case INIT:
// console.log("INIT!!!!")
return setInitiator(true)
case READY:
// console.log("READY!!!")
return enter()
case START_CALL:
return setCallStarted(true)
case REJECT_CALL:
return setCallStarted(false)
case CLOSE_SESSION:
setCallStarted(false)
closePeers()
if (props.video) props.toggleVideoSession()
break
default: null // console.log('default receive DATA', data)
}
}
function call (data) {
peer && peer.signal && peer.signal(data.desc)
}
function enter (_params) {
setConnecting(true)
const peer = videoCall.init(
localStream,
initiator
)
setPeer(peer)
peer.on('signal', data => {
const signal = {
room: props.conversation.key,
desc: data
}
broadcastData({
event_type: 'SIGNAL',
from: currentUser,
signal: signal
})
})
peer.on('stream', stream => {
const id = 'remoteVideoContainer'
let element = documentObject.getElementById(id)
if (!element) {
element = documentObject.createElement('video')
element.id = id
remoteVideoContainer.current.appendChild(element)
}
element.autoplay = 'autoplay'
element.srcObject = stream
// element.muted = true
// element.setAttribute('muted', 'muted')
element.volume = 0.9
setConnecting(false)
setWaiting(false)
})
peer.on('error', function (err) {
console.log(err)
})
}
function removePeers () {
broadcastData({
event_type: CLOSE_SESSION,
from: currentUser
})
closePeers()
}
function closePeers () {
// if(props.video) props.toggleVideoSession()
peer && peer.destroy && peer.destroy() // && peer.removeAllListeners()
props.onCloseSession && props.onCloseSession()
gstream.id && gstream.getTracks().forEach(track => track.stop())
localStream.id && localStream.getTracks().forEach(track => track.stop())
}
function rejectCall () {
broadcastData({
event_type: REJECT_CALL,
from: currentUser
})
closePeers()
}
return <React.Fragment>
{
localVideoTarget && createPortal(
<div id="local-video-wrapper">
<video id="local-video"
muted="muted"
autoPlay
ref={ localVideo }>
</video>
{callStarted && <button
className='control-btn'
onClick={() => { getDisplay() }}
>
share screen
</button>}
</div>, localVideoTarget
)
}
{
remoteVideoTarget && createPortal(
<div id="remote-video-container"
ref={ remoteVideoContainer }>
</div>, remoteVideoTarget)
}
{
infoTarget && createPortal(
<React.Fragment>
{/* callStarted && 'call started' */}
{connecting && (
<div className="status inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium bg-green-100 text-green-800 border border-green-400">
<p>Establishing connection...</p>
</div>
)}
{waiting && callStarted && (
<div className="status inline-flex items-center px-3 py-0.5 rounded-full text-sm font-medium bg-green-100 text-green-800 border border-green-400">
<p>Waiting for someone...</p>
</div>
)}
</React.Fragment>, infoTarget)
}
{
initiator && !callStarted &&
callInitiatorTarget && createPortal(
<div id="call-initiator" className="flex flex-col justify-center items-center space-y-6">
<p className="inline-flex items-center px-2.5 py-0.5 rounded-full text-sm font-medium bg-pink-100 text-blue-800 border border-pink-900-">
Start a call
</p>
<div className="call-buttons">
<button
style={{ color: 'white', backgroundColor: 'green', border: 'none' }}
onClick={requestCall}>
<CallIcon style={{ height: '30px', width: '30px' }}/>
</button>
<button
onClick={() => {
props.toggleVideoSession()
closePeers()
} }
style={{ color: 'white', backgroundColor: 'red', border: 'none' }}>
<CallEndIcon style={{ height: '30px', width: '30px' }}/>
</button>
</div>
</div>
,
callInitiatorTarget)
}
{/* {
props.buttonElement && createPortal(
<Button
className={`btn btn-outline${props.video ? '-success active' : '-secondary'}`}
onClick={() => {
// if(props.video) localStream.stop()
props.toggleVideoSession()
}
}>
<i className="fa fa-video"></i>
</Button>
, target)
}
*/}
{/* check the event start call instead event_type */ }
{
props.callStatusElement && !props.video &&
!initiator && callStarted &&
createPortal(
<div id="call-status">
<p>Hey! an agent is calling you</p>
<div className="call-buttons">
<button
style={{ color: 'white', backgroundColor: 'green', border: 'none' }}
onClick={() => props.toggleVideoSession() } >
<CallIcon style={{ height: '30px', width: '30px' }}/>
</button>
<button
onClick={() => rejectCall() }
style={{ color: 'white', backgroundColor: 'red', border: 'none' }}>
<CallEndIcon style={{ height: '30px', width: '30px' }}/>
</button>
</div>
</div>
, callStatusTarget)
}
{
props.callButtonsElement &&
props.video &&
callStarted &&
createPortal(
<div className="call-buttons flex flex-col space-y-1">
<Button
variant="outlined"
className="rounded-full"
onClick={() => props.toggleVideo()}
style={{ color: `${props.rtcVideo ? 'green' : 'gray'}` }}>
<CameraIcon/>
</Button>
<Button
variant="outlined"
onClick={() => props.toggleAudio()}
style={{ color: `${props.rtcAudio ? 'green' : 'gray'}` }}>
<MicIcon/>
</Button>
<Button
variant="outlined"
onClick={() => {
stopUserMedia()
setCallStarted(false)
closePeers()
props.toggleVideoSession()
}
}
style={{
color: 'white',
background: 'red',
border: 0
}}>
{!props.video ? <CallIcon/> : <CallEndIcon/>}
</Button>
</div>
, callButtonsTarget)
}
</React.Fragment>
}
export function RtcWrapper (props) {
return props.current_user ? <RtcView {...props}/> : <p>k</p>
}
function mapStateToProps (state) {
const { app, conversation, current_user, rtc } = state
const appKey = app.key
return {
conversation,
current_user,
appKey,
rtc
}
}
const BaseIcon = styled.svg`
height: 30px;
width: 30px;
`
export function CloseIcon (props) {
return (
<BaseIcon {...props} fill="currentColor" viewBox="0 0 24 24">
<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z">
</path>
</BaseIcon>
)
}
export function MicIcon (props) {
return (
<BaseIcon {...props} fill="currentColor"
viewBox="0 0 24 24" aria-hidden="true"
tabindex="-1" title="Mic">
<path d="M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5.3-3c0 3-2.54 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c3.28-.48 6-3.3 6-6.72h-1.7z">
</path>
</BaseIcon>
)
}
export function MicOffIcon (props) {
return (
<BaseIcon {...props} fill="currentColor" viewBox="0 0 24 24"
aria-hidden="true" tabindex="-1" title="MicOff">
<path d="M19 11h-1.7c0 .74-.16 1.43-.43 2.05l1.23 1.23c.56-.98.9-2.09.9-3.28zm-4.02.17c0-.06.02-.11.02-.17V5c0-1.66-1.34-3-3-3S9 3.34 9 5v.18l5.98 5.99zM4.27 3L3 4.27l6.01 6.01V11c0 1.66 1.33 3 2.99 3 .22 0 .44-.03.65-.08l1.66 1.66c-.71.33-1.5.52-2.31.52-2.76 0-5.3-2.1-5.3-5.1H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c.91-.13 1.77-.45 2.54-.9L19.73 21 21 19.73 4.27 3z">
</path>
</BaseIcon>
)
}
export function CameraIcon (props) {
return (
<BaseIcon {...props} fill="currentColor" viewBox="0 0 24 24"
aria-hidden="true" tabindex="-1" title="Videocam">
<path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z">
</path>
</BaseIcon>
)
}
export function CameraOffIcon (props) {
return (
<BaseIcon {...props} fill="currentColor" viewBox="0 0 24 24"
aria-hidden="true" tabindex="-1" title="Videocam">
<path d="M21 6.5l-4 4V7c0-.55-.45-1-1-1H9.82L21 17.18V6.5zM3.27 2L2 3.27 4.73 6H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.21 0 .39-.08.54-.18L19.73 21 21 19.73 3.27 2z"></path>
</BaseIcon>
)
}
export function FullScreenIcon (props) {
return (
<BaseIcon {...props} fill="currentColor" viewBox="0 0 24 24"
aria-hidden="true" tabindex="-1" title="Fullscreen">
<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z">
</path>
</BaseIcon>
)
}
export function FullScreenExitIcon (props) {
return (
<BaseIcon {...props} fill="currentColor" viewBox="0 0 24 24"
aria-hidden="true" tabindex="-1" title="FullscreenExit">
<path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z">
</path>
</BaseIcon>
)
}
export function ScreenShareIcon (props) {
return (
<BaseIcon {...props} fill="currentColor" viewBox="0 0 24 24"
aria-hidden="true" tabindex="-1" title="ScreenShare">
<path d="M20 18c1.1 0 1.99-.9 1.99-2L22 6c0-1.11-.9-2-2-2H4c-1.11 0-2 .89-2 2v10c0 1.1.89 2 2 2H0v2h24v-2h-4zm-7-3.53v-2.19c-2.78 0-4.61.85-6 2.72.56-2.67 2.11-5.33 6-5.87V7l4 3.73-4 3.74z">
</path>
</BaseIcon>
)
}
export function ScreenShareExitIcon (props) {
return (
<BaseIcon {...props} fill="currentColor" viewBox="0 0 24 24"
aria-hidden="true" tabindex="-1" title="ScreenShare">
<path d="M21.22 18.02l2 2H24v-2h-2.78zm.77-2l.01-10c0-1.11-.9-2-2-2H7.22l5.23 5.23c.18-.04.36-.07.55-.1V7.02l4 3.73-1.58 1.47 5.54 5.54c.61-.33 1.03-.99 1.03-1.74zM2.39 1.73L1.11 3l1.54 1.54c-.4.36-.65.89-.65 1.48v10c0 1.1.89 2 2 2H0v2h18.13l2.71 2.71 1.27-1.27L2.39 1.73zM7 15.02c.31-1.48.92-2.95 2.07-4.06l1.59 1.59c-1.54.38-2.7 1.18-3.66 2.47z">
</path>
</BaseIcon>
)
}
export function CallIcon (props) {
return (
<BaseIcon {...props} fill="currentColor" viewBox="0 0 24 24"
aria-hidden="true" tabIndex="-1" title="Call">
<path d="M20.01 15.38c-1.23 0-2.42-.2-3.53-.56-.35-.12-.74-.03-1.01.24l-1.57 1.97c-2.83-1.35-5.48-3.9-6.89-6.83l1.95-1.66c.27-.28.35-.67.24-1.02-.37-1.11-.56-2.3-.56-3.53 0-.54-.45-.99-.99-.99H4.19C3.65 3 3 3.24 3 3.99 3 13.28 10.73 21 20.01 21c.71 0 .99-.63.99-1.18v-3.45c0-.54-.45-.99-.99-.99z"></path>
</BaseIcon>
)
}
export function CallEndIcon (props) {
return (
<BaseIcon {...props} fill="currentColor" viewBox="0 0 24 24"
aria-hidden="true" tabIndex="-1" title="CallEnd">
<path d="M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08c-.18-.17-.29-.42-.29-.7 0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28-.79-.74-1.69-1.36-2.67-1.85-.33-.16-.56-.5-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z">
</path>
</BaseIcon>
)
}
export default connect(mapStateToProps)(RtcWrapper)
|
src/DepartmentContainer.js | Andrew-He/moka | import React, { Component } from 'react';
import PositionListing from './PositionListing.js';
import CountBubble from './CountBubble.js';
import uuidV4 from 'uuid/v4';
class DepartmentContainer extends Component {
constructor(props){
super(props);
this.state = { checked: false };
this.handleCheck = () => {
this.setState({ checked: !this.state.checked});
};
}
render() {
const positions = this.props.positions.map((position) => {
return (<PositionListing key={uuidV4()} {...position} checked={this.state.checked}/>);
});
return (
<div className="DepartmentContainer">
<div className="DepartmentHeader">
<input
type="checkbox"
checked={this.props.checked ? this.props.checked : (this.state.checked)}
onClick={this.handleCheck}
onChange={()=>{}}
/>
<h2>{this.props.departmentNameInChinese} ⌄</h2>
<CountBubble> {this.props.departmentPostingCount} </CountBubble>
</div>
{positions}
</div>
);
}
}
DepartmentContainer.propTypes = {
departmentName: React.PropTypes.string.isRequired,
departmentNameInChinese: React.PropTypes.string.isRequired,
departmentPostingCount: React.PropTypes.number.isRequired,
positions: React.PropTypes.array.isRequired,
checked: React.PropTypes.bool.isRequired,
};
export default DepartmentContainer;
|
client/scripts/components/toggle-switch/index.js | kuali/research-coi | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import styles from './style';
import classNames from 'classnames';
import React from 'react';
export default class ToggleSwitch extends React.Component {
constructor(props) {
super();
this.state = {
on: props.defaultValue.toLowerCase() === 'on'
};
this.onClick = this.onClick.bind(this);
}
onClick() {
const newValue = !this.state.on;
this.setState({
on: newValue
});
if (this.props.onChange) {
this.props.onChange(newValue ? 'On' : 'Off');
}
}
render() {
const classes = classNames(
styles.container,
{[styles.on]: this.state.on},
this.props.className
);
return (
<span onClick={this.onClick} className={classes}>
<span style={{marginRight: 8}}>
<span className={styles.base}>
<span className={styles.label}>OFF</span>
<span className={styles.label}>ON</span>
<span className={styles.slider} />
</span>
</span>
<span style={{verticalAlign: 'middle'}}>{this.props.label}</span>
</span>
);
}
}
|
modules/TransitionHook.js | wmyers/react-router | import React from 'react';
import warning from 'warning';
var { object } = React.PropTypes;
var TransitionHook = {
contextTypes: {
router: object.isRequired
},
componentDidMount() {
warning(
typeof this.routerWillLeave === 'function',
'Components that mixin TransitionHook should have a routerWillLeave method, check %s',
this.constructor.displayName || this.constructor.name
);
if (this.routerWillLeave)
this.context.router.addTransitionHook(this.routerWillLeave);
},
componentWillUnmount() {
if (this.routerWillLeave)
this.context.router.removeTransitionHook(this.routerWillLeave);
}
};
export default TransitionHook;
|
actor-apps/app-web/src/app/components/dialog/messages/Document.react.js | yangchaogit/actor-platform | import React from 'react';
import classnames from 'classnames';
class Document extends React.Component {
static propTypes = {
content: React.PropTypes.object.isRequired,
className: React.PropTypes.string
};
constructor(props) {
super(props);
}
render() {
const { content, className } = this.props;
const documentClassName = classnames(className, 'row');
let availableActions;
if (content.isUploading === true) {
availableActions = <span>Loading...</span>;
} else {
availableActions = <a href={content.fileUrl}>Download</a>;
}
return (
<div className={documentClassName}>
<div className="document row">
<div className="document__icon">
<i className="material-icons">attach_file</i>
</div>
<div className="col-xs">
<span className="document__filename">{content.fileName}</span>
<div className="document__meta">
<span className="document__meta__size">{content.fileSize}</span>
<span className="document__meta__ext">{content.fileExtension}</span>
</div>
<div className="document__actions">
{availableActions}
</div>
</div>
</div>
<div className="col-xs"></div>
</div>
);
}
}
export default Document;
|
src/index.js | emilpalsson/react-metro | // REACT METRO - Nicolas Delfino
// www.github.com/nicolasdelfino
import React from 'react'
import MetroHoc from './MetroHoc'
import MetroAnimations from './MetroAnimations'
const defaultAnimation = {
animation: {
out: {
time: 0.4,
delay: 0
},
in: {
time: 0.4,
delay: 0
},
willEnter: {
from: { opacity: 0 },
to: { opacity: 1, ease: 'easeInOut' }
},
willLeave: {
from: {
opacity: 1
},
to: {
opacity: 0
}
}
}
}
// metroContainer
// single node enhancer
const metroContainer = (
component,
defaultAnimationOverride = null,
props = {}
) => {
const baseAnimation = defaultAnimationOverride || defaultAnimation
const animation = {
...baseAnimation
}
const containerData = {
...animation,
key: 0,
itemIndex: 0,
sequence: [{ ...animation }]
}
return (
<Metro.animation {...containerData} {...props}>
{component}
</Metro.animation>
)
}
const combineAnimations = (base, animation) => {
if (!animation) {
return base
}
return {
out: { ...base.out, ...animation.out },
in: { ...base.in, ...animation.in },
willEnter: {
from: {
...(base.willEnter && base.willEnter.from),
...(animation.willEnter && animation.willEnter.from)
},
to: {
...(base.willEnter && base.willEnter.to),
...(animation.willEnter && animation.willEnter.to)
}
},
willLeave: {
from: {
...(base.willLeave && base.willLeave.from),
...(animation.willLeave && animation.willLeave.from)
},
to: {
...(base.willLeave && base.willLeave.to),
...(animation.willLeave && animation.willLeave.to)
}
}
}
}
// metroSequence
// enhances an array of data to a Metro sequence with animation data
const metroSequence = (
dataArray,
animationMap = [],
defaultAnimationOverride = null
) => {
const baseAnimation = {
animation: defaultAnimationOverride
? combineAnimations(
defaultAnimation.animation,
defaultAnimationOverride.animation
)
: defaultAnimation.animation
}
const sequence = dataArray.map((data, i) => {
const combAnim = combineAnimations(baseAnimation.animation, animationMap[i])
const settings = {
...baseAnimation,
animation: combAnim
}
return {
...settings,
content: data
}
})
return sequence.map((data, index) => ({
key: index,
itemIndex: index,
...data,
sequence
}))
}
// metroAnimation
// HOC, uses greensock TweenMax for animation
/* eslint-disable */
const metroAnimation = MetroHoc(
class extends React.Component {
render() {
return (
<div
onClick={() => {
const animating = this.props.sequence.some(s => s.animating)
if (
this.props.onClick &&
(!animating || this.props.enableClickDuringAnimation)
) {
this.props.onClick(
this.props.content,
this.props.itemIndex,
animating
)
}
}}
>
{this.props.children}
</div>
)
}
}
)
// generateFocusAnimationMap
// focusIndex - array based (starts at 0)
// presets:
// -> domino: dominoForwards, dominoBackwards, dominoMulti
// -> delayedVertical
const generateFocusAnimationMap = (
focusIndex = null,
cols,
totalItems,
animationType = 'dominoForwards',
duration = 1
) => {
/* eslint-disable */
// columns / rows for more advanced types of presets
const rows = Math.ceil(totalItems / cols)
// default time and delay per item based on the total duration
const defaultItemTime = duration * 0.75 / totalItems
const delayTime = defaultItemTime + duration * 0.25 / totalItems
const presetSettings = [focusIndex, totalItems, defaultItemTime, delayTime]
// match animationType
if (animationType.includes('domino')) {
const type = animationType.split('domino')[1].toLowerCase()
return MetroAnimations.domino(type, ...presetSettings)
} else if (animationType.includes('delayed')) {
const type = animationType.split('delayed')[1].toLowerCase()
return MetroAnimations.delayedVertical(type, ...presetSettings)
} else {
// no map found
return []
}
/* eslint-enable */
}
const Metro = {
sequence: metroSequence,
animation: metroAnimation,
container: metroContainer,
generateFocusMap: generateFocusAnimationMap
}
export default Metro
|
assets/components/Calendar/GoogleCalendar.js | hemstreet/MagicMirror | import config from '../../../config/config'
import React from 'react';
var gcal = require('google-calendar');
export default React.createClass({
componentWillMount() {
this.google_calendar = new gcal.GoogleCalendar(config.calendar.google);
},
componentDidMount() {
window.setInterval(() => {
this.fetchCalendarEvents();
}, 1000 * 60 * 15);
},
fetchCalendarEvents() {
this.google_calendar.calendarList.list(function(err, calendarList) {
this.google_calendar.events.list(calendarId, function(err, calendarList) {
this.setState({
calendarList
});
});
});
},
render() {
return (
<div className="MirrorCalendarList">
{this.state.calendarList}
</div>
);
}
}); |
src/src/routes/Deals/routes/View/containers/DealContainer.js | alexberriman/local-deals | import React from 'react'
import { connect } from 'react-redux'
import Deal from '../components/Deal'
import { fetchDeal } from '../modules/actions'
import strings from './DealContainer.strings.js'
class DealContainer extends React.Component {
/**
* Fetches the user's profile.
*/
componentDidMount() {
const { fetchDeal, layout, params } = this.props
fetchDeal(params.id)
layout.setHeader({
displayMenuAsBackButton: true
})
}
/**
* Updates the document title when the deal has loaded.
*
* @param nextProps
*/
componentWillReceiveProps(nextProps) {
const { deal } = nextProps
if (this.props.deal.deal === null && deal.deal) {
this.props.layout
.setTitle(deal.deal.title)
.updateHeader({
title: deal.deal.title
})
}
}
/**
* Renders the Navigation Drawer.
*
* @returns {*}
*/
render() {
const { deal } = this.props
if (deal.loading || !deal.deal) {
return null
}
return (
<Deal
{...this.props}
deal={deal.deal}
/>
)
}
}
DealContainer.propTypes = {
deal: React.PropTypes.object.isRequired,
fetchDeal: React.PropTypes.func.isRequired,
layout: React.PropTypes.object.isRequired,
params: React.PropTypes.object.isRequired
}
const mapStateToProps = state => ({
deal: state.dealView
})
const mapDispatchToProps = {
fetchDeal
}
export default connect(mapStateToProps, mapDispatchToProps)(DealContainer)
|
src/GameCard.js | leemeli/game | import React from 'react';
import firebase from 'firebase';
String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
return this.toString();
}
return this.split(search).join(replace);
}
// Individual Card Component
export default class GameCard extends React.Component {
constructor(props) {
super(props);
this.state = {
games: [],
guessed: false,
correct: false
};
this.showAnswer = this.showAnswer.bind(this);
this.resetGuess = this.resetGuess.bind(this);
this.userGuess = this.userGuess.bind(this);
}
// Method to concat the background url
backgroundUrl(array, fn){
var result = [];
for (var i = 0; i < array.length; i ++){
var mapping = fn(array[i]);
result = result.concat(mapping);
}
return result;
}
showAnswer(){
this.setState({guessed: true});
}
resetGuess(curGame){
var prevGame = curGame;
var that = this;
// Make it check if the new data has loaded yet. If not, wait 100 milliseconds and try again
if (this.props.data["name"].replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/gi,"") == prevGame){
setTimeout(function(){
that.resetGuess(prevGame);
},10);
}
else {
this.setState({guessed: false, correct: false});
}
}
userGuess(guessName){
var correct = this.props.data["name"];
correct = correct.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/gi,"");
if (guessName == correct){ // user guessed correctly
this.setState({guessed: true, correct: true});
this.props.gainPoints();
}
else { // user guessed incorrectly
this.setState({guessed: true, yourGuess: guessName});
this.props.losePoints();
}
}
render() {
var that = this;
var coverId = "0";
if ("screenshots" in this.props.data){ // If it has a cover
coverId = this.props.data["screenshots"][0]["cloudinary_id"];
}
var currentBackgroundId = coverId;
if (currentBackgroundId != "0"){
var backgroundUrlParts = "url('https://images.igdb.com/igdb/image/upload/t_screenshot_huge/$.png') center center no-repeat #46B6AC"
var backResult = this.backgroundUrl(backgroundUrlParts.split('$'), function(part){
return [part, currentBackgroundId];
});
backResult.pop();
backResult = backResult.join("");
var cardStyle = {
background: backResult,
}
}
else {
var cardStyle = {
backgroundColor: "black", // If it doesn't have a cover, make it black
}
}
// Shorten and filter summary
var filteredSummary = "";
var defaultSummary = this.props.data["summary"];
var name = this.props.data["name"];
name = name.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/gi,"");
var wordToFilter = name.split(" ");
if (defaultSummary){
filteredSummary = defaultSummary.replace(name, "*****");
for (var i = 0; i < wordToFilter.length; i ++){
//if (wordToFilter[i].length > 3 || !isNaN(wordToFilter[i])){
filteredSummary = filteredSummary.replaceAll(wordToFilter[i], "*****");
//}
}
if (filteredSummary.length > 350){
filteredSummary = filteredSummary.substring(0, 350)+"...";
}
}
var guessChoicesArray = [name, this.props.game2["name"], this.props.game3["name"]];
var guessChoicesProcessedArray = guessChoicesArray.map(function(game){ // Go through every game in the array
return <p key={game}><a className="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect" onClick={function(){that.userGuess(game)}}>{game}</a></p>
});
return (
<div className="demo-card-wide mdl-card mdl-shadow--2dp">
<div className="mdl-card__title" style={cardStyle}>
</div>
<div className="mdl-card__supporting-text">
{filteredSummary}
</div>
<div className="mdl-card__actions mdl-card--border">
{!this.state.guessed &&
<div>
{this.props.userName !== '' &&
<p><strong>Can you guess the game? (+3 points)</strong></p>
}
{this.props.userName === '' &&
<p><strong>Can you guess the game?</strong></p>
}
{guessChoicesProcessedArray}
<p>
{this.props.userName !== '' &&
<button className="mdl-button mdl-js-button mdl-button--raised mdl-button--accent" onClick={(e) => {this.showAnswer(); this.props.losePoints()}}>
See Answer (-2 points)
</button>
}
{this.props.userName === '' &&
<button className="mdl-button mdl-js-button mdl-button--raised mdl-button--accent" onClick={this.showAnswer}>
See Answer
</button>
}
</p>
</div>
}
{this.state.guessed &&
<div>
<h4><strong>Answer:</strong> {name}</h4>
{this.state.correct &&
<div>
{this.props.userName !== '' &&
<p className="correct">Correct! You gained 3 points.</p>
}
{this.props.userName === '' &&
<p className="correct">Correct! Great job!</p>
}
</div>
}
{!this.state.correct &&
<div>
<p><strong>Your guess:</strong> {this.state.yourGuess}</p>
<div>
{this.props.userName !== '' &&
<p className="wrong">Incorrect. You lost 2 points.</p>
}
{this.props.userName === '' &&
<p className="wrong">Incorrect. Try again!</p>
}
</div>
</div>
}
<p>You can learn more about {name} <a href={this.props.data["url"]} target="_blank">here!</a></p>
<button className="mdl-button mdl-js-button mdl-button--raised mdl-button--accent" onClick={(e) => {this.resetGuess(name); this.props.newPrompt()}}>
Challenge me again!
</button>
</div>
}
</div>
</div>
);
}
} |
examples/src/app.js | naturalatlas/react-select | /* eslint react/prop-types: 0 */
import React from 'react';
import Select from 'react-select';
import CustomRenderField from './components/CustomRenderField';
import MultiSelectField from './components/MultiSelectField';
import RemoteSelectField from './components/RemoteSelectField';
import SelectedValuesField from './components/SelectedValuesField';
import StatesField from './components/StatesField';
import UsersField from './components/UsersField';
import ValuesAsNumbersField from './components/ValuesAsNumbersField';
import DisabledUpsellOptions from './components/DisabledUpsellOptions';
var FLAVOURS = [
{ label: 'Chocolate', value: 'chocolate' },
{ label: 'Vanilla', value: 'vanilla' },
{ label: 'Strawberry', value: 'strawberry' },
{ label: 'Cookies and Cream', value: 'cookiescream' },
{ label: 'Peppermint', value: 'peppermint' }
];
var FLAVOURS_WITH_DISABLED_OPTION = FLAVOURS.slice(0);
FLAVOURS_WITH_DISABLED_OPTION.unshift({ label: 'Caramel (You don\'t like it, apparently)', value: 'caramel', disabled: true });
function logChange() {
console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments)));
}
React.render(
<div>
<StatesField label="States" searchable />
<UsersField label="Users (custom options/value)" hint="This example uses Gravatar to render user's image besides the value and the options" />
<ValuesAsNumbersField label="Values as numbers" />
<MultiSelectField label="Multiselect"/>
<SelectedValuesField label="Clickable labels (labels as links)" options={FLAVOURS} hint="Open the console to see click behaviour (data/event)" />
<SelectedValuesField label="Disabled option" options={FLAVOURS_WITH_DISABLED_OPTION} hint="You savage! Caramel is the best..." />
<DisabledUpsellOptions label="Disable option with an upsell link"/>
<SelectedValuesField label="Option Creation (tags mode)" options={FLAVOURS} allowCreate hint="Enter a value that's not in the list, then hit enter" />
<CustomRenderField label="Custom render options/values" />
<CustomRenderField label="Custom render options/values (multi)" multi delimiter="," />
<RemoteSelectField label="Remote Options" hint='Type anything in the remote example to asynchronously load options. Valid alternative results are "A", "AA", and "AB"' />
</div>,
document.getElementById('example')
);
|
admin/client/components/PopoutListHeading.js | mikaoelitiana/keystone | import React from 'react';
import blacklist from 'blacklist';
import classnames from 'classnames';
var PopoutListHeading = React.createClass({
displayName: 'PopoutListHeading',
propTypes: {
children: React.PropTypes.node.isRequired,
className: React.PropTypes.string,
},
render () {
let className = classnames('PopoutList__heading', this.props.className);
let props = blacklist(this.props, 'className');
return <div className={className} {...props} />;
}
});
module.exports = PopoutListHeading;
|
src/pages/base/settings.js | voidxnull/libertysoil-site | /*
This file is a part of libertysoil.org website
Copyright (C) 2015 Loki Education (Social Enterprise)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react';
import { Link, IndexLink } from 'react-router';
import { getUrl, URL_NAMES } from '../../utils/urlGenerator';
import Header from '../../components/header';
import Footer from '../../components/footer';
import ProfileHeader from '../../components/profile';
import Sidebar from '../../components/sidebar';
import Messages from '../../components/messages';
export default class BaseSettingsPage extends React.Component {
static displayName = 'BaseSettingsPage';
render () {
const {
onSave,
children,
is_logged_in,
current_user,
following,
followers,
messages,
triggers
} = this.props;
return (
<div>
<Header is_logged_in={is_logged_in} current_user={current_user}/>
<div className="page__container">
<div className="page__body">
<Sidebar current_user={current_user} />
<div className="page__body_content">
<ProfileHeader
user={current_user}
current_user={current_user}
following={following}
followers={followers}
/>
<div className="page__content page__content-spacing">
<div className="layout__row layout-small">
<div className="layout__grid tabs">
<div className="layout__grid_item"><IndexLink to={getUrl(URL_NAMES.SETTINGS)} activeClassName="tabs__link-active" className="tabs__link">About</IndexLink></div>
<div className="layout__grid_item"><Link to={getUrl(URL_NAMES.CHANGE_PASSWORD)} activeClassName="tabs__link-active" className="tabs__link">Change password</Link></div>
</div>
</div>
<div className="paper layout">
<div className="layout__grid_item layout__grid_item-fill layout__grid_item-wide">
{children}
</div>
<div className="layout-normal layout__grid_item layout__grid_item-fill page__content_sidebar">
<div className="tabs tabs-vertical">
<IndexLink to={getUrl(URL_NAMES.SETTINGS)} activeClassName="tabs__link-active" className="tabs__link">Basic info</IndexLink>
<Link to={getUrl(URL_NAMES.MANAGE_FOLLOWERS)} activeClassName="tabs__link-active" className="tabs__link">Manage Followers</Link>
<Link to={getUrl(URL_NAMES.CHANGE_PASSWORD)} activeClassName="tabs__link-active" className="tabs__link">Change password</Link>
</div>
</div>
</div>
<div className="void">
<span className="button button-green action" onClick={onSave}>Save changes</span>
</div>
<Messages messages={messages} removeMessage={triggers.removeMessage}/>
</div>
</div>
</div>
</div>
<Footer/>
</div>
);
}
}
|
src/js/components/DataChart/stories/Axis.js | grommet/grommet | import React from 'react';
import { Box, DataChart } from 'grommet';
const data = [];
for (let i = 1; i <= 7; i += 1) {
const v = Math.sin(i / 2.0);
const digits = ((i % 12) + 1).toString().padStart(2, 0);
data.push({
// explore variations in date format by changing the xAxis key to
// the time period you are interested in
second: `2020-05-15T08:04:${digits}`,
minute: `2020-05-15T08:${digits}:00`,
hour: `2020-05-15T${digits}:00:00`,
day: `2020-05-${digits}`,
month: `2020-${digits}-15`,
year: `20${digits}-01-15`,
// explore variations in yAxis value handling by changing the chart key
// to one of these
percent: Math.abs(v * 100), // make yAxis suffix '%'
amount: i * 111111, // make yAxis prefix '$'
});
}
export const Axis = () => (
// Uncomment <Grommet> lines when using outside of storybook
// <Grommet theme={grommet}>
<Box align="center" justify="start" pad="large">
<DataChart
data={data}
series={['day', { property: 'percent', suffix: '%' }]}
chart="percent"
axis={{
x: { property: 'day', granularity: 'medium' },
y: { property: 'percent', granularity: 'medium' },
}}
/>
</Box>
// </Grommet>
);
export default {
title: 'Visualizations/DataChart/Axis',
};
|
docs/snippets/plugin-default-config.js | zapier/formatic | //CUT
import React from 'react';
import Formatic from 'formatic';
const fields = [];
//CUT
const config = Formatic.createConfig();
React.render(<Formatic config={config} fields={fields} />, document.body);
|
src/client/components/WidgetContainer/WidgetContainer.js | jaimerosales/visual-reports-bim360dc | import PropTypes from 'prop-types'
import ReactDOM from 'react-dom'
import './WidgetContainer.scss'
import React from 'react'
class WidgetContainer extends React.Component {
/////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////
static propTypes = {
className: PropTypes.string,
showTitle: PropTypes.bool
}
/////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////
static defaultProps = {
showTitle: true,
className: ''
}
/////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////
renderTitle () {
if (!this.props.showTitle) {
return <div/>
}
if (this.props.renderTitle) {
return this.props.renderTitle()
}
return (
<div className="title">
<label>
{ this.props.title }
</label>
</div>
)
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
renderChildren() {
if (this.props.dimensions) {
return React.Children.map(this.props.children, (child) => {
const newProps = Object.assign({},
child.props, {
dimensions: this.props.dimensions
})
return React.cloneElement(child, newProps)
})
}
return this.props.children
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
render() {
const classNames = [
'widget-container',
...this.props.className.split(' ')
]
const height = this.props.showTitle
? 'calc(100% - 40px)'
: '100%'
return (
<div className={classNames.join(' ')} style={this.props.style}>
{ this.renderTitle() }
<div className="content" style={{height}}>
{this.renderChildren()}
</div>
</div>
)
}
}
export default WidgetContainer
|
docs/app/Examples/elements/Reveal/Content/index.js | ben174/Semantic-UI-React | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const RevealContentExamples = () => (
<ExampleSection title='Content'>
<ComponentExample
title='Visible Content'
description='A reveal may contain content that is visible before interaction.'
examplePath='elements/Reveal/Content/RevealExampleVisible'
/>
<ComponentExample
title='Hidden Content'
description='A reveal may contain content that is hidden before user interaction.'
examplePath='elements/Reveal/Content/RevealExampleHidden'
/>
</ExampleSection>
)
export default RevealContentExamples
|
newclient/scripts/components/dynamic-icons/checkmark-icon/index.js | kuali/research-coi | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
/* eslint-disable max-len */
import React from 'react';
export default function CheckmarkIcon(props) {
return (
<svg className={props.className} version="1.1" data-icon="check" data-container-transform="translate(2 15)" viewBox="0 0 128 160" x="0px" y="0px">
<title id="title">Checkmark Icon</title>
<path fill={props.color} d="M112.156.188l-5.469 5.844-64.906 68.938-24.188-23.688-5.719-5.594-11.188 11.438 5.719 5.594 30 29.406 5.813 5.688 5.594-5.938 70.5-74.906 5.5-5.813-11.656-10.969z" transform="translate(2 15)" />
</svg>
);
}
CheckmarkIcon.defaultProps = {
color: 'white'
};
|
src/components/EventList/EventList.js | jhabdas/lumpenradio-com | import React from 'react';
import styles from './EventList.css';
import withStyles from '../../decorators/withStyles';
import Link from '../Link';
import EventItem from '../EventItem';
@withStyles(styles)
class EventList extends React.Component {
render() {
let eventItems = this.props.data.map((eventItems, i) => {
return (
<EventItem key={i} data={eventItems} />
)
});
return (
<div className="EventList">
<div className="EventList-container">
<div className="EventList-header">
<h1>Events</h1>
</div>
<div className="EventList-newsItems">
{eventItems}
</div>
<a className="EventList-moreLink" href="/events">More Events →</a>
</div>
</div>
);
}
}
export default EventList;
|
src/components/common/Pagination.js | kmcarter/karaoke-song-lister | import React from 'react';
import PropTypes from 'prop-types';
import Icon from './Icon';
import PerPageSelector from './PerPageSelector';
import PaginationLink from './PaginationLink';
const Pagination = props => {
const totalNumPages = Math.floor( props.count / props.perPage );
const onNextClick = e => {
e.preventDefault();
props.onClick(e, props.page + 1);
};
const onPreviousClick = e => {
e.preventDefault();
props.onClick(e, props.page - 1);
};
const onPageClick = e => {
props.onClick(e, parseInt(e.currentTarget.value));
};
const onPerPageChange = e => {
props.onPerPageChange(e, parseInt(e.currentTarget.value));
};
let rows = [];
for (let i = 0; i <= totalNumPages; i++) {
rows.push(<option key={i} value={i}>{i + 1}</option>);
}
return (
<form className="row" aria-label="Search results navigation">
<div className="col-4">
<PerPageSelector value={props.perPage} onChange={onPerPageChange}>
{[10, 100, 200, 500]}
</PerPageSelector>
</div>
<div className="col-4 pt-2 text-center">
Page {props.page + 1} of {totalNumPages + 1}
</div>
<div className="col-4">
<div className="input-group input-group-sm">
<span className="input-group-btn">
<PaginationLink onClick={onPreviousClick} disabled={props.page == 0}><Icon className="fa-arrow-left" /></PaginationLink>
</span>
<select className="form-control custom-select" value={props.page} onChange={onPageClick}>
{rows}
</select>
<span className="input-group-btn">
<PaginationLink onClick={onNextClick} disabled={props.page == totalNumPages}><Icon className="fa-arrow-right" /></PaginationLink>
</span>
</div>
</div>
</form>
);
};
Pagination.propTypes = {
count: PropTypes.number.isRequired,
onClick: PropTypes.func.isRequired,
page: PropTypes.number.isRequired,
perPage: PropTypes.number.isRequired,
onPerPageChange: PropTypes.func.isRequired
};
export default Pagination; |
frontend/app/components/Alphabet/AlphabetContainer.js | First-Peoples-Cultural-Council/fv-web-ui | import React from 'react'
import PropTypes from 'prop-types'
import AlphabetPresentation from 'components/Alphabet/AlphabetPresentation'
import AlphabetPrintPresentation from 'components/Alphabet/AlphabetPrintPresentation'
import AlphabetData from 'components/Alphabet/AlphabetData'
/**
* @summary AlphabetContainer
* @version 1.0.1
* @component
*
* @param {object} props
* @param {string} dialectName
* @param {boolean} isPrint
* @returns {node} jsx markup
*/
function AlphabetContainer({ dialectName, isPrint }) {
return (
<AlphabetData>
{({ characters, currentChar, intl, onCharacterClick, onCharacterLinkClick, properties }) => {
return isPrint ? (
<AlphabetPrintPresentation characters={characters} dialectName={dialectName} />
) : (
<AlphabetPresentation
characters={characters}
currentChar={currentChar}
dialectName={dialectName}
intl={intl}
onCharacterClick={onCharacterClick}
onCharacterLinkClick={onCharacterLinkClick}
properties={properties}
/>
)
}}
</AlphabetData>
)
}
// PROPTYPES
const { bool, string } = PropTypes
AlphabetContainer.propTypes = {
dialectName: string,
isPrint: bool,
}
export default AlphabetContainer
|
techCurriculum/ui/solutions/4.4/src/components/Message.js | AnxChow/EngineeringEssentials-group | /**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
import React from 'react';
function Message(props) {
return (
<div className='message-text'>
<p>{props.text}</p>
</div>
);
}
export default Message;
|
src/svg-icons/maps/terrain.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsTerrain = (props) => (
<SvgIcon {...props}>
<path d="M14 6l-3.75 5 2.85 3.8-1.6 1.2C9.81 13.75 7 10 7 10l-6 8h22L14 6z"/>
</SvgIcon>
);
MapsTerrain = pure(MapsTerrain);
MapsTerrain.displayName = 'MapsTerrain';
MapsTerrain.muiName = 'SvgIcon';
export default MapsTerrain;
|
src/components/Conversation.js | stefan-moraru/please | import React, { Component } from 'react';
import RenderWithTimeout from './RenderWithTimeout';
import request from 'superagent';
import _get from 'lodash.get';
import ReactTooltip from 'react-tooltip';
import ReactMarkdown from 'react-markdown';
import _ from '../services/_';
import { OptionButton, OptionIcon, OptionInput, OptionVideo } from './Option';
import superagentjsonp from 'superagent-jsonp';
export default class Conversation extends Component {
state = {
currentPlugin: null
};
startBestMatchingPlugin(input, settings) {
if (!input || !settings || (settings && !settings.plugins)) {
return;
}
this.setState({
currentPlugin: _.bestPluginMatch(settings, input),
settings: settings
});
}
componentWillReceiveProps(nextProps) {
const input = nextProps.input;
const settings = nextProps.settings;
if (this.props !== nextProps) {
this.startBestMatchingPlugin(input, settings);
}
}
changeStep(option) {
this.setState({
currentPlugin: _.pluginAtStep(this.state.currentPlugin, option)
});
}
renderConversationStepText(text, markdown = false, params) {
let content = null;
text = _.substituteParamsInString(params, text);
if (text && markdown) {
const ReactMarkdownProps = {
className: "markdown u-m-0",
containerTagName: "div",
source: text
};
content = <ReactMarkdown {...ReactMarkdownProps} />;
} else {
content = <h4 className="u-m-0">{text}</h4>;
}
return content;
}
renderConversationStepImage(image, params) {
let content = null;
if (image) {
content = <img src={image} />;
}
return content;
}
updateParamAndChangeStepFromInput(option, input) {
const plugin = _.pluginWithUpdatedParamAndStep(this.state.currentPlugin, option.step, option.input.param.replace(/[{}]/g, ''), input.text);
this.setState({
plugin: plugin
});
}
generateButton(option, params, stepKey) {
let onClick = () => {};
if (!option.button.maintainStep) {
onClick = this.changeStep.bind(this, option);
}
if (option.button.fill) {
onClick = this.updateParamFromQuery.bind(this, option.button.fill.replace(/[{}]/g, ''), option.button.text, this.state.currentPlugin, stepKey);
}
const props = {
text: _.substituteParamsInString(params, option.button.text),
href: _.substituteParamsInString(params, option.button.href),
image: option.button.image,
onClick: onClick,
params: params
};
let rendered = null;
if (option.button.displayOnly && !params[option.button.displayOnly.replace(/[{}]/g, '')]) {
rendered = null;
} else {
rendered = <OptionButton {...props} />;
}
return rendered;
}
generateVideo(option, params) {
const props = {
id: option.video.id,
path: option.video.path
};
return <OptionVideo {...props} />;
}
renderOption(params, option, stepKey) {
let renderedOption = null;
if (option.button) {
renderedOption = this.generateButton(option, params, stepKey);
} else if (option.icon) {
const props = {
icon: option.icon,
text: option.text,
onClick: this.changeStep.bind(this, option)
};
renderedOption = <OptionIcon {...props} />;
} else if (option.input) {
const props = {
label: option.input.label,
placeholder: option.input.placeholder,
onInputSubmit: this.updateParamAndChangeStepFromInput.bind(this, option)
};
renderedOption = <OptionInput {...props} />;
} else if (option.video) {
renderedOption = this.generateVideo(option, params);
}
if (option.generate) {
renderedOption = null;
const param = params[option.generate.replace(/[{}]/g, '')];
if (param && param.value && param.value.length > 0) {
let items = param.value;
if (option.generateReverse) {
items = items.reverse();
}
if (option.generateLimit) {
items = items.slice(0, option.generateLimit);
}
items = items
.map(val => {
if (option.button) {
const newOption = Object.assign({}, option);
newOption.button = Object.assign({}, option.button);
newOption.button.text = _get(val, option.button.text);
newOption.button.href = _get(val, option.button.href);
newOption.button.image = _get(val, option.button.image);
newOption.button.maintainStep = option.button.maintainStep;
newOption.button.displayOnly = option.button.displayOnly;
return this.generateButton(newOption, params, stepKey);
} else if (option.video) {
const newOption = Object.assign({}, option);
newOption.video = Object.assign({}, option.video);
newOption.video.id = _get(val, option.video.id);
newOption.video.path = _get(val, option.video.path);
return this.generateVideo(newOption, params);
}
return val;
});
renderedOption = (
<div>
{items}
</div>
);
} else {
const def = <h6>{option.generateDefault || 'No results'}</h6>;
renderedOption = (
<div>
{def}
</div>
);
}
}
const renderedOptionTitle = !option.title ? null : (
<h5 className="u-m-b-10 u-m-t-0">{option.title}</h5>
);
return (
<div className="component-Conversation__step__options__option">
{renderedOptionTitle}
{renderedOption}
</div>
);
}
renderConversationStepOptions(options, params, optionsTitle, stepKey) {
let rendered = null;
if (options) {
if (!options.cancel) {
options.cancel = {
icon: 'ion-close-circled',
text: 'Cancel',
step: 'cancel'
};
}
options = Object.keys(options).map(key => options[key]);
options = _.sortOptions(options);
rendered = options.map(option => {
return this.renderOption(params, option, stepKey);
});
}
const title = optionsTitle ? <h4 className="u-m-0 u-m-b-15">{_.substituteParamsInString(params, optionsTitle)}</h4> : null;
return (
<div className="component-Conversation__step__options">
{title}
{rendered}
</div>
);
}
updateParamFromQuery(paramName, value, plugin, stepKey) {
this.setState({
currentPlugin: _.pluginWithUpdatedParam(plugin, stepKey, paramName, value)
});
}
renderConversationStep(stepKey, step, params, plugin, settings, fromHistory = false) {
let contentText = <h4>Thank you for using Please!</h4>;
let contentImage = null;
let contentOptions = null;
if (step) {
contentText = step.text ? this.renderConversationStepText(step.text, step.markdown, params) : null;
contentImage = step.image ? this.renderConversationStepImage(step.image, params) : null;
contentOptions = step.options ? this.renderConversationStepOptions(step.options, params, step.optionsTitle, stepKey) : null;
if (step.query && !step.queryDone && !fromHistory) {
const query = step.query;
request[query.method.toLowerCase()](query.url)
.use(superagentjsonp({
timeout: 10000
}))
.query(_.substituteParamsInString(params, query.params))
.then((response) => {
const data = response.body;
console.log('got data from query', data);
return this.updateParamFromQuery(query.fill.replace(/[{}]/g, ''), _get(data, query.responsePath), this.state.currentPlugin, stepKey);
}, (error) => {
console.error(error);
})
}
}
if (step.jumpToStep && !fromHistory) {
setTimeout(() => {
this.changeStep({
step: step.jumpToStep
});
}, step.jumpToStepDelay || 1000);
}
const contentBot = (
<div className="component-Conversation__step__bot" data-tip={plugin.title}>
<img src={plugin.image} alt={plugin.title} />
</div>
);
const contentUser = (
<div className="component-Conversation__step__bot right" data-tip="You">
<img src={settings.user.profile.image} alt="User profile" />
</div>
);
const _contentTextClassname = "component-Conversation__step " + (contentImage ? "image" : "");
const _contentText = !(contentText || contentImage) ? null : (
<div className={_contentTextClassname}>
<div className="component-Conversation__step__content">
{contentBot}
<RenderWithTimeout timeout={500} loader={true} enabled={!fromHistory}>
<div>
{contentText}
{contentImage}
</div>
</RenderWithTimeout>
</div>
</div>
);
const _contentOptions = !contentOptions ? null : (
<RenderWithTimeout timeout={1500} enabled={!fromHistory}>
<div className="component-Conversation__step right">
<div className="component-Conversation__step__content">
{contentUser}
<RenderWithTimeout timeout={500} loader={true} enabled={!fromHistory}>
{contentOptions}
</RenderWithTimeout>
</div>
</div>
</RenderWithTimeout>
);
return (
<div>
{_contentOptions}
{_contentText}
</div>
);
}
renderConversation(plugin, settings) {
let content = null;
let history = null
if (plugin && plugin.conversation) {
if (plugin.history) {
history = plugin.history.map(snapshot => {
return this.renderConversationStep(snapshot.step, snapshot.plugin.conversation[snapshot.step], snapshot.params, snapshot.plugin, settings, true);
}).reverse();
}
content = this.renderConversationStep(plugin.step, plugin.conversation[plugin.step], plugin.params, plugin, settings);
}
return (
<div>
{content}
<div className="history">
{history}
</div>
</div>
);
}
render() {
const conversation = this.renderConversation(this.state.currentPlugin, this.state.settings);
return (
<div className="component-Conversation">
{conversation}
<ReactTooltip type="dark" effect="solid" />
</div>
);
}
}
|
src/svg-icons/device/signal-wifi-4-bar.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalWifi4Bar = (props) => (
<SvgIcon {...props}>
<path d="M12.01 21.49L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l11.63 14.49.01.01.01-.01z"/>
</SvgIcon>
);
DeviceSignalWifi4Bar = pure(DeviceSignalWifi4Bar);
DeviceSignalWifi4Bar.displayName = 'DeviceSignalWifi4Bar';
export default DeviceSignalWifi4Bar;
|
docs/src/components/Breakpoint.js | storybooks/react-storybook | import React from 'react';
import PropTypes from 'prop-types';
import './breakpoints.css';
const Breakpoint = ({ mobile, children }) => {
const className = mobile ? 'breakpoint-min-width-700' : 'breakpoint-max-width-700';
return <div className={className}>{children}</div>;
};
Breakpoint.propTypes = {
children: PropTypes.array, // eslint-disable-line
mobile: PropTypes.bool,
};
Breakpoint.defaultProps = {
mobile: false,
};
export { Breakpoint as default };
|
examples/group/App.js | sskyy/redux-task | 'use strict'
import React from 'react'
import {Message,Input, Indicator} from './components'
const App = React.createClass({
render(){
return <div>
<Input />
<Message />
<Indicator />
</div>
}
})
export default App
|
app/javascript/mastodon/features/favourited_statuses/index.js | koba-lab/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { fetchFavouritedStatuses, expandFavouritedStatuses } from '../../actions/favourites';
import Column from '../ui/components/column';
import ColumnHeader from '../../components/column_header';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import StatusList from '../../components/status_list';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { debounce } from 'lodash';
const messages = defineMessages({
heading: { id: 'column.favourites', defaultMessage: 'Favourites' },
});
const mapStateToProps = state => ({
statusIds: state.getIn(['status_lists', 'favourites', 'items']),
isLoading: state.getIn(['status_lists', 'favourites', 'isLoading'], true),
hasMore: !!state.getIn(['status_lists', 'favourites', 'next']),
});
export default @connect(mapStateToProps)
@injectIntl
class Favourites extends ImmutablePureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
statusIds: ImmutablePropTypes.list.isRequired,
intl: PropTypes.object.isRequired,
columnId: PropTypes.string,
multiColumn: PropTypes.bool,
hasMore: PropTypes.bool,
isLoading: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchFavouritedStatuses());
}
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('FAVOURITES', {}));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
setRef = c => {
this.column = c;
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandFavouritedStatuses());
}, 300, { leading: true })
render () {
const { intl, statusIds, columnId, multiColumn, hasMore, isLoading } = this.props;
const pinned = !!columnId;
const emptyMessage = <FormattedMessage id='empty_column.favourited_statuses' defaultMessage="You don't have any favourite toots yet. When you favourite one, it will show up here." />;
return (
<Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.heading)}>
<ColumnHeader
icon='star'
title={intl.formatMessage(messages.heading)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
showBackButton
/>
<StatusList
trackScroll={!pinned}
statusIds={statusIds}
scrollKey={`favourited_statuses-${columnId}`}
hasMore={hasMore}
isLoading={isLoading}
onLoadMore={this.handleLoadMore}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
/>
</Column>
);
}
}
|
docs/app/Examples/elements/Image/Variations/ImageExampleVerticallyAligned.js | aabustamante/Semantic-UI-React | import React from 'react'
import { Divider, Image } from 'semantic-ui-react'
const src = '/assets/images/wireframe/image.png'
const ImageExampleVerticallyAligned = () => (
<div>
<Image src={src} size='tiny' verticalAlign='top' /> <span>Top Aligned</span>
<Divider />
<Image src={src} size='tiny' verticalAlign='middle' /> <span>Middle Aligned</span>
<Divider />
<Image src={src} size='tiny' verticalAlign='bottom' /> <span>Bottom Aligned</span>
</div>
)
export default ImageExampleVerticallyAligned
|
src/components/common/Login.js | projecter-org/projecter | import React from 'react'
import FlatButton from 'material-ui/FlatButton'
class Login extends React.Component {
static muiName = 'FlatButton'
render () {
return (
<FlatButton {...this.props} label='Login' />
)
}
}
export default Login
|
app/blocks/header/index.js | lamo2k123/demo.bestplace.pro | // @flow
import React from 'react'
import { Link } from 'react-router-async'
import SignButton from 'block/sign/button'
import AuthProfile from 'block/auth/profile'
import style from './style'
const Header = () => (
<header className={style['header']}>
<Link to="/" className={style['header__logo']}>Best Place PRO</Link>
<SignButton />
<AuthProfile />
</header>
);
Header.displayName = '[block] header';
export { Header as default };
|
ui/src/main/js/components/Tabs.js | rdelval/aurora | import React from 'react';
import Icon from 'components/Icon';
import { addClass } from 'utils/Common';
// Wrapping tabs in his component helps simplify testing of Tabs with enzyme's shallow renderer.
export function Tab({ children, icon, id, name }) {
return <div>{children}</div>;
}
export default class Tabs extends React.Component {
constructor(props) {
super(props);
this.state = {
active: props.activeTab || React.Children.toArray(props.children)[0].props.id
};
}
select(tab) {
this.setState({active: tab.id});
if (this.props.onChange) {
this.props.onChange(tab);
}
}
componentWillReceiveProps(nextProps) {
// Because this component manages its own state, we need to listen to changes to the activeTab
// property - as the changes will not propagate without the component being remounted.
if (nextProps.activeTab !== this.props.activeTab &&
nextProps.activeTab !== this.state.activeTab) {
this.setState({active: nextProps.activeTab});
}
}
render() {
const that = this;
const isActive = (t) => t.id === that.state.active;
return (<div className={addClass('tabs', this.props.className)}>
<ul className='tab-navigation'>
{React.Children.map(this.props.children, (t) => (<li
className={isActive(t.props) ? 'active' : ''}
key={t.props.name}
onClick={(e) => this.select(t.props)}>
{t.props.icon ? <Icon name={t.props.icon} /> : ''}
{t.props.name}
</li>))}
</ul>
<div className='active-tab'>
{React.Children.toArray(this.props.children).find((t) => isActive(t.props))}
</div>
</div>);
}
}
|
docs/src/PageFooter.js | collinwu/react-bootstrap | import React from 'react';
import packageJSON from '../../package.json';
let version = packageJSON.version;
if (/docs/.test(version)) {
version = version.split('-')[0];
}
const PageHeader = React.createClass({
render() {
return (
<footer className='bs-docs-footer' role='contentinfo'>
<div className='container'>
<div className='bs-docs-social'>
<ul className='bs-docs-social-buttons'>
<li>
<iframe className='github-btn'
src='http://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=watch&count=true'
width={95}
height={20}
title='Star on GitHub' />
</li>
<li>
<iframe className='github-btn'
src='http://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=fork&count=true'
width={92}
height={20}
title='Fork on GitHub' />
</li>
<li>
<iframe
src="http://platform.twitter.com/widgets/follow_button.html?screen_name=react_bootstrap&show_screen_name=true"
width={230}
height={20}
allowTransparency="true"
frameBorder='0'
scrolling='no'>
</iframe>
</li>
</ul>
</div>
<p>Code licensed under <a href='https://github.com/react-bootstrap/react-bootstrap/blob/master/LICENSE' target='_blank'>MIT</a>.</p>
<ul className='bs-docs-footer-links muted'>
<li>Currently v{version}</li>
<li>·</li>
<li><a href='https://github.com/react-bootstrap/react-bootstrap/'>GitHub</a></li>
<li>·</li>
<li><a href='https://github.com/react-bootstrap/react-bootstrap/issues?state=open'>Issues</a></li>
<li>·</li>
<li><a href='https://github.com/react-bootstrap/react-bootstrap/releases'>Releases</a></li>
</ul>
</div>
</footer>
);
}
});
export default PageHeader;
|
assets/jqwidgets/demos/react/app/grid/groupingwithpager/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxGrid from '../../../jqwidgets-react/react_jqxgrid.js';
import JqxButton from '../../../jqwidgets-react/react_jqxbuttons.js';
import JqxInput from '../../../jqwidgets-react/react_jqxinput.js';
class App extends React.Component {
componentDidMount() {
this.refs.ExpandButton.on('click', () => {
let groupnum = this.refs.myInput.val();
if (!isNaN(groupnum)) {
this.refs.Grid.expandgroup(groupnum);
}
});
// collapse group.
this.refs.CollapseButton.on('click', () => {
let groupnum = this.refs.myInput.val();
if (!isNaN(groupnum)) {
this.refs.Grid.collapsegroup(groupnum);
}
});
// expand all groups.
this.refs.ExpandAllButton.on('click', () => {
this.refs.Grid.expandallgroups();
});
// collapse all groups.
this.refs.CollapseAllButton.on('click', () => {
this.refs.Grid.collapseallgroups();
});
// trigger expand and collapse events.
this.refs.Grid.on('groupexpand', (event) => {
let args = event.args;
document.getElementById('expandedgroup').innerHTML = 'Group: ' + args.group + ', Level: ' + args.level;
});
this.refs.Grid.on('groupcollapse', (event) => {
let args = event.args;
document.getElementById('collapsedgroup').innerHTML = 'Group: ' + args.group + ', Level: ' + args.level
});
}
render() {
let source =
{
datatype: 'xml',
datafields: [
{ name: 'CompanyName', map: 'm\\:properties>d\\:CompanyName', type: 'string' },
{ name: 'ContactName', map: 'm\\:properties>d\\:ContactName', type: 'string' },
{ name: 'ContactTitle', map: 'm\\:properties>d\\:ContactTitle', type: 'string' },
{ name: 'City', map: 'm\\:properties>d\\:City', type: 'string' },
{ name: 'PostalCode', map: 'm\\:properties>d\\:PostalCode', type: 'string' },
{ name: 'Country', map: 'm\\:properties>d\\:Country', type: 'string' }
],
root: 'entry',
record: 'content',
id: 'm\\:properties>d\\:CustomerID',
url: '../sampledata/customers.xml'
};
let dataAdapter = new $.jqx.dataAdapter(source);
let columns =
[
{ text: 'Company Name', datafield: 'CompanyName', width: 250 },
{ text: 'City', datafield: 'City', width: 120 },
{ text: 'Country', datafield: 'Country' }
];
return (
<div>
<JqxGrid ref='Grid'
width={850} height={280} source={dataAdapter} groupable={true}
pageable={true} columns={columns} groups={['City']}
/>
<div style={{ marginTop: 30 }}>
<div style={{ float: 'left', marginLeft: 20 }}>
<JqxButton ref='ExpandButton' width={125} height={25} value='Expand Group' />
<br />
<JqxButton ref='CollapseButton' width={125} height={25} style={{ marginTop: 10 }} value='Collapse Group' />
<br />
<span style={{ marginTop: 10 }}>Group:</span>
<JqxInput ref='myInput' style={{ marginLeft: 10, marginTop: 10 }} width={20} value={1} />
</div>
<div style={{ float: 'left', marginLeft: 20 }}>
<JqxButton ref='ExpandAllButton' width={125} height={25} value='Expand All' />
<br />
<JqxButton ref='CollapseAllButton' width={125} height={25} value='Collapse All' style={{ marginTop: 10, marginBottom: 10 }} />
<br />
</div>
<div style={{ float: 'left', marginLeft: 20 }}>
<div style={{ fontWeight: 'bold' }}>
<span>Event Log:</span>
</div>
<div style={{ marginTop: 10 }}>
<span>Expanded Group:</span>
<span id='expandedgroup'></span>
</div>
<div style={{ marginTop: 10 }}>
<span>Collapsed Group:</span>
<span id='collapsedgroup'></span>
</div>
</div>
</div>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/app/components/search/SearchResultsTable/CommentCountCell.js | meedan/check-web | import React from 'react';
import PropTypes from 'prop-types';
import NumberCell from './NumberCell';
export default function CommentCountCell({ projectMedia }) {
const commentCount = projectMedia.list_columns_values.comment_count;
return <NumberCell value={commentCount} />;
}
CommentCountCell.propTypes = {
projectMedia: PropTypes.shape({
list_columns_values: PropTypes.shape({
comment_count: PropTypes.number.isRequired,
}).isRequired,
}).isRequired,
};
|
src/index.js | YMFL/reactNews | import React from 'react';
import ReactDOM from 'react-dom';
import 'core-js/fn/object/assign';
import { Router,Route,hashHistory } from 'react-router';
import MediaQuery from 'react-responsive';
//pc
import PCIndex from './components/pc_index';
import PCNewsDetails from './components/pc_news_details';
import PCUserCenter from './components/pc_userCenter';
//mobile
import MobileIndex from './components/mobile_index';
import MobileNewsDetails from './components/mobile_news_details';
import MobileUserCenter from './components/mobile_userCenter';
//样式
import 'antd/dist/antd.css';
export default class Root extends React.Component{
render(){
return(
<div>
<MediaQuery query='(min-device-width:1224px)'>
<Router history={hashHistory}>
<Route path="/" component={PCIndex}></Route>
<Route path="/details/:uniquekey" component={PCNewsDetails}></Route>
<Route path="/usercenter" component={PCUserCenter}></Route>
</Router>
</MediaQuery>
<MediaQuery query='(max-device-width:1224px)'>
<Router history={hashHistory}>
<Route path="/" component={MobileIndex}></Route>
<Route path="/details/:uniquekey" component={MobileNewsDetails}></Route>
<Route path="/usercenter" component={MobileUserCenter}></Route>
</Router>
</MediaQuery>
</div>
)
}
}
ReactDOM.render(<Root />, document.getElementById('app'));
|
src/routes/chart/Container.js | ykx456654/hr_admin | import React from 'react'
import PropTypes from 'prop-types'
import styles from './Container.less'
import { ResponsiveContainer } from 'recharts'
const Container = ({ children, ratio = 5 / 2, minHeight = 250, maxHeight = 350 }) => <div className={styles.container} style={{ minHeight, maxHeight }}>
<div style={{ marginTop: `${100 / ratio}%` || '100%' }}></div>
<div className={styles.content} style={{ minHeight, maxHeight }}>
<ResponsiveContainer>
{children}
</ResponsiveContainer>
</div>
</div>
Container.propTypes = {
children: PropTypes.element.isRequired,
ratio: PropTypes.number,
minHeight: PropTypes.number,
maxHeight: PropTypes.number,
}
export default Container
|
src/components/App.js | budiantotan/book-store | import React from 'react';
import { Link } from 'react-router';
const App = (props) => {
return (
<div className="container">
<nav className="navbar navbar-default">
<div className="container-fluid">
<div className="navbar-header">
<a className="navbar-brand" href="#">Books</a>
</div>
<div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul className="nav navbar-nav">
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/books">Book</Link></li>
<li><Link to="/cart">Cart</Link></li>
</ul>
</div>
</div>
</nav>
{props.children}
</div>
);
};
export default App; |
vgdb-frontend/src/components/Title.js | mattruston/idb | import React, { Component } from 'react';
import './Title.css';
class Title extends Component {
render() {
return (
<div className="title">{ this.props.title }</div>
);
}
}
export default Title; |
src/components/loading-animation/LoadingAnimation.js | ipfs/webui | import React from 'react'
import { withTranslation } from 'react-i18next'
// Components
import GlyphDots from '../../icons/GlyphDots'
import Checkbox from '../../components/checkbox/Checkbox'
import FileIcon from '../../files/file-icon/FileIcon'
// Styles
import './LoadingAnimation.css'
const FakeHeader = ({ t }) => (
<header className='gray pv2 flex items-center flex-none'>
<div className='pa2 w2'><Checkbox disabled /></div>
<div className='ph2 f6 flex-auto'>{t('app:terms.name')}</div>
<div className='pl2 pr4 tr f6 flex-none dn db-l'>{t('app:terms.size')}</div>
<div className='pa2' style={{ width: '2.5rem' }} />
</header>
)
const FakeFile = ({ nameWidth }) => (
<div className='b--light-gray relative flex items-center bt' style={{ height: 55 }}>
<div className='pa2 w2'>
<Checkbox disabled />
</div>
<div className='relative pointer flex items-center flex-grow-1 ph2 pv1 w-40'>
<div className='dib flex-shrink-0 mr2'>
<FileIcon cls='fill-charcoal' />
</div>
<div className='w-100'>
<div className={`w-${nameWidth} br1 bg-charcoal-muted f7`}> </div>
<div className='w-80 br1 mt1 bg-gray f7 o-70'> </div>
</div>
</div>
<div className='size mr4 pl2 pr4 flex-none dn db-l br1 tr f7 bg-gray'> </div>
<div className='ph2' style={{ width: '2.5rem' }}>
<GlyphDots className='fill-gray-muted pointer' />
</div>
</div>
)
const LoadingAnimation = ({ t }) => (
<div className='LoadingAnimation'>
<div className='LoadingAnimationSwipe'>
<FakeHeader t={t} />
<FakeFile nameWidth={50} />
<FakeFile nameWidth={40} />
<FakeFile nameWidth={60} />
<FakeFile nameWidth={30} />
<FakeFile nameWidth={50} />
<FakeFile nameWidth={60} />
<FakeFile nameWidth={70} />
<FakeFile nameWidth={40} />
<FakeFile nameWidth={30} />
<FakeFile nameWidth={50} />
</div>
</div>
)
export default withTranslation('files')(LoadingAnimation)
|
src/data-store/index.js | ForbesLindesay/react-data-fetching-demo | import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app';
ReactDOM.render(
<App/>,
document.getElementById('container'),
);
|
src/svg-icons/image/exposure-plus-2.js | lawrence-yu/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageExposurePlus2 = (props) => (
<SvgIcon {...props}>
<path d="M16.05 16.29l2.86-3.07c.38-.39.72-.79 1.04-1.18.32-.39.59-.78.82-1.17.23-.39.41-.78.54-1.17.13-.39.19-.79.19-1.18 0-.53-.09-1.02-.27-1.46-.18-.44-.44-.81-.78-1.11-.34-.31-.77-.54-1.26-.71-.51-.16-1.08-.24-1.72-.24-.69 0-1.31.11-1.85.32-.54.21-1 .51-1.36.88-.37.37-.65.8-.84 1.3-.18.47-.27.97-.28 1.5h2.14c.01-.31.05-.6.13-.87.09-.29.23-.54.4-.75.18-.21.41-.37.68-.49.27-.12.6-.18.96-.18.31 0 .58.05.81.15.23.1.43.25.59.43.16.18.28.4.37.65.08.25.13.52.13.81 0 .22-.03.43-.08.65-.06.22-.15.45-.29.7-.14.25-.32.53-.56.83-.23.3-.52.65-.88 1.03l-4.17 4.55V18H22v-1.71h-5.95zM8 7H6v4H2v2h4v4h2v-4h4v-2H8V7z"/>
</SvgIcon>
);
ImageExposurePlus2 = pure(ImageExposurePlus2);
ImageExposurePlus2.displayName = 'ImageExposurePlus2';
ImageExposurePlus2.muiName = 'SvgIcon';
export default ImageExposurePlus2;
|
common/components/scrollable/VerticalScrollbar.js | ebertmi/webbox | /*The MIT License (MIT)
Copyright (c) 2016 Naufal Rabbani
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
import React from 'react';
class VerticalScrollbar extends React.Component {
constructor() {
super();
this.state = {
height: 0,
dragging: false,
start: 0
};
}
render() {
if (this.state.height < 100) {
return (
<div
className="react-scrollbar__scrollbar-vertical"
ref="container"
onClick={ this.jump.bind(this) }>
<div
className={ "scrollbar" + ( this.state.dragging || this.props.draggingFromParent ? '' : ' react-scrollbar-transition') }
ref="scrollbar"
onTouchStart={ this.startDrag.bind(this) }
onMouseDown={ this.startDrag.bind(this) }
style={{
height: this.state.height+'%',
top: this.props.scrolling + '%'
}} />
</div>
);
} else {
return null;
}
}
startDrag(e) {
e.preventDefault();
e.stopPropagation();
e = e.changedTouches ? e.changedTouches[0] : e;
// Prepare to drag
this.setState({
dragging: true,
start: e.clientY
});
}
onDrag(e) {
if (this.state.dragging) {
// Make The Parent being in the Dragging State
this.props.onDragging();
e.preventDefault();
e.stopPropagation();
e = e.changedTouches ? e.changedTouches[0] : e;
let yMovement = e.clientY - this.state.start;
let yMovementPercentage = yMovement / this.props.wrapper.height * 100;
// Update the last e.clientY
this.setState({ start: e.clientY }, () => {
// The next Vertical Value will be
let next = this.props.scrolling + yMovementPercentage;
// Tell the parent to change the position
this.props.onChangePosition(next, 'vertical');
});
}
}
stopDrag(e) {
if (this.state.dragging) {
// Parent Should Change the Dragging State
this.props.onStopDrag();
this.setState({ dragging: false });
}
}
jump(e) {
let isContainer = e.target === this.refs.container;
if (isContainer) {
// Get the Element Position
let position = this.refs.scrollbar.getBoundingClientRect();
// Calculate the vertical Movement
let yMovement = e.clientY - position.top;
let centerize = (this.state.height / 2);
let yMovementPercentage = yMovement / this.props.wrapper.height * 100 - centerize;
// Update the last e.clientY
this.setState({ start: e.clientY }, () => {
// The next Vertical Value will be
let next = this.props.scrolling + yMovementPercentage;
// Tell the parent to change the position
this.props.onChangePosition(next, 'vertical');
});
}
}
calculateSize(source) {
// Scrollbar Height
this.setState({ height: source.wrapper.height / source.area.height * 100 });
}
UNSAFE_componentWillReceiveProps(nextProps) {
if ( nextProps.wrapper.height !== this.props.wrapper.height ||
nextProps.area.height !== this.props.area.height ) {
this.calculateSize(nextProps);
}
}
componentDidMount() {
this.calculateSize(this.props);
// Put the Listener
document.addEventListener("mousemove", this.onDrag.bind(this));
document.addEventListener("touchmove", this.onDrag.bind(this));
document.addEventListener("mouseup", this.stopDrag.bind(this));
document.addEventListener("touchend", this.stopDrag.bind(this));
}
componentWillUnmount() {
// Remove the Listener
document.removeEventListener("mousemove", this.onDrag.bind(this));
document.removeEventListener("touchmove", this.onDrag.bind(this));
document.removeEventListener("mouseup", this.stopDrag.bind(this));
document.removeEventListener("touchend", this.stopDrag.bind(this));
}
}
export default VerticalScrollbar; |
client/my-sites/upgrades/domain-management/transfer/shared.js | allendav/wp-calypso | /**
* External dependencies
*/
import React from 'react';
/**
* Internal dependencies
*/
import notices from 'notices';
import { translate } from 'lib/mixins/i18n';
import support from 'lib/url/support';
export const displayResponseError = ( responseError ) => {
const errorMessages = {
unlock_domain_and_disable_private_reg_failed: translate(
'The domain could not be unlocked. ' +
'Additionally, Privacy Protection could not be disabled. ' +
'The transfer will most likely fail due to these errors.'
),
unlock_domain_failed: translate(
'The domain could not be unlocked. ' +
'The transfer will most likely fail due to this error.'
),
disable_private_reg_failed: translate(
'Privacy Protection could not be disabled. ' +
'The transfer will most likely fail due to this error.'
)
};
if ( responseError.error && Object.keys( errorMessages ).indexOf( responseError.error ) !== - 1 ) {
notices.error(
translate(
'An error occurred while trying to send the Domain Transfer code: {{strong}}%s{{/strong}} ' +
'Please {{a}}Contact Support{{/a}}.',
{
args: errorMessages[ responseError.error ],
components: {
strong: <strong />,
a: <a href={ support.CALYPSO_CONTACT } target="_blank"/>
}
}
)
);
} else {
notices.error(
translate(
'An error occurred while trying to send the Domain Transfer code. ' +
'Please try again or {{a}}Contact Support{{/a}} if you continue ' +
'to have trouble.',
{
components: {
a: <a href={ support.CALYPSO_CONTACT } target="_blank"/>
}
}
)
);
}
};
export const displayRequestTransferCodeResponseNotice = ( responseError, domainStatus ) => {
if ( responseError ) {
displayResponseError( responseError );
return;
}
if ( domainStatus.manualTransferRequired ) {
notices.success(
translate(
'The registry for your domain requires a special process for transfers. ' +
'Our Happiness Engineers have been notified about your transfer request and will be in touch ' +
'shortly to help you complete the process.'
)
);
} else {
notices.success(
translate(
'We have sent the transfer authorization code to the domain registrant\'s email address. ' +
'If you don\'t receive the email shortly, please check your spam folder.'
)
);
}
};
|
ui/js/pages/file/FilesSectionEdit.js | ericsoderberg/pbc-web |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import FormState from '../../utils/FormState';
import SectionMultiEdit from '../../components/SectionMultiEdit';
import FilesItemEdit from './FilesItemEdit';
export default class FilesSectionEdit extends Component {
constructor(props) {
super(props);
const { section, onChange } = props;
this.state = { formState: new FormState(section, onChange) };
}
componentWillReceiveProps(nextProps) {
const { section, onChange } = nextProps;
this.setState({ formState: new FormState(section, onChange) });
}
render() {
const { formState } = this.state;
return (
<SectionMultiEdit formState={formState}
property="files"
label="file"
ItemEdit={FilesItemEdit} />
);
}
}
FilesSectionEdit.propTypes = {
onChange: PropTypes.func.isRequired,
section: PropTypes.object.isRequired,
};
|
App/Services/ExamplesRegistry.js | tetriseffect/activate | import React from 'react'
import {Text, View} from 'react-native'
import R from 'ramda'
import { ApplicationStyles } from '../Themes'
import DebugSettings from '../Config/DebugSettings'
let globalExamplesRegistry = []
export const addExample = (title, usage) => { if (DebugSettings.includeExamples) globalExamplesRegistry.push({title, usage}) }
const renderExample = (example) => {
return (
<View key={example.title}>
<View style={ApplicationStyles.darkLabelContainer}>
<Text style={ApplicationStyles.darkLabel}>{example.title}</Text>
</View>
{example.usage.call()}
</View>
)
}
export const renderExamples = () => R.map(renderExample, globalExamplesRegistry)
// Default for readability
export default {
render: renderExamples,
add: addExample
}
|
private/Components/ViewFavorites.js | Bartoshko/occasion-jitsu | import React from 'react'
import {Link} from 'react-router-dom'
import {ToggleFavorite} from './Components.js'
// ViewFavorites component renders favorites stores
const SearchFavorites = props => (
<div>
<form className='row underline'>
<div className='row'>
<div className='four columns'>
<label>Sklepy Alfabetycznie</label>
<select
className='u-full-width'
id='alphabet'
autoFocus='none'
defaultValue='none'
onChange={props.handleAlphabetLetter}
>
<option value='all'>Nie wybrano</option>
<option value='A'>A</option>
<option value='B'>B</option>
<option value='C'>C</option>
<option value='D'>D</option>
<option value='E'>E</option>
<option value='F'>F</option>
<option value='G'>G</option>
<option value='H'>H</option>
<option value='I'>I</option>
<option value='J'>J</option>
<option value='K'>K</option>
<option value='L'>L</option>
<option value='M'>M</option>
<option value='N'>N</option>
<option value='O'>O</option>
<option value='P'>P</option>
<option value='R'>R</option>
<option value='S'>S</option>
<option value='T'>T</option>
<option value='U'>U</option>
<option value='W'>W</option>
<option value='X'>X</option>
<option value='Y'>Y</option>
<option value='Z'>Z</option>
</select>
</div>
</div>
</form>
</div>
)
const ViewFavorites = props => {
return(
<div>
<div>
<div className='row'>
<div className='columns center-text view-separator'>
<h5><b>Ulubione Sklepy</b></h5>
</div>
</div>
</div>
<SearchFavorites />
<div>
{props.stores.map(store =>
<div
key={store.id}
className='row view-separator'>
<div className='columns'>
<div className='row'>
<div className='four columns'>
<h2>{store.storeName}</h2>
</div>
<div className='four columns'>
<Link
className='button in-line'
to={{pathname: '/sklepulubiony', search: 'id='+store.id}}
>Przejdz do sklepu {store.storeName}</Link>
</div>
<div className='four columns'>
<ToggleFavorite
favToggle={store.favToggle}
toggleValue={store.id}
handleFavorite={props.handleToggleFavorite}
toggleFavTitle={store.toggleFavTitle}
/>
</div>
</div>
<div className='row'>
<div className='four columns'>
<img
className='image'
src={store.pictureUrl} />
<p>{store.type}</p>
<p><b>Liczba Promocji: {store.items.length}</b></p>
<p>{store.info}</p>
</div>
<div className='four columns'>
<h5>Lokalizacja:</h5>
<p><b>Kraj: </b>{store.localization.country}</p>
<p><b>Miejscowosc: </b>{store.localization.city}</p>
<p><b>Ulica: </b>{store.localization.street} {store.localization.houseNumber}</p>
<p><b>Kod pocztowy: </b>{store.localization.postCode}</p>
</div>
<div className='four columns'>
<ul>Godziny otwarcia</ul>
<li>Poniedzialek: {store.localization.openHours[0]}</li>
<li>Wtorek: {store.localization.openHours[1]}</li>
<li>Sroda: {store.localization.openHours[2]}</li>
<li>Czwartek: {store.localization.openHours[3]}</li>
<li>Piatek: {store.localization.openHours[4]}</li>
<li>Sobota: {store.localization.openHours[5]}</li>
<li>Niedziela: {store.localization.openHours[6]}</li>
</div>
</div>
</div>
</div>,
props)}
</div>
<div className='column'>
</div>
</div>
)}
ViewFavorites.propTypes = {
stores: React.PropTypes.array.isRequired,
handlePromoMount: React.PropTypes.func.isRequired,
handleToggleFavorite: React.PropTypes.func,
toggleValue: React.PropTypes.string,
favToggle: React.PropTypes.string,
toggleFavTitle: React.PropTypes.string
}
// --- --- --- --- --- ---
export {ViewFavorites}
|
client/components/FileUpload.js | phoenixmusical/membres | import React from 'react';
import s3upload from 'utils/s3upload';
import ProgressBar from './ProgressBar';
export default class FileUpload extends React.Component {
constructor (props) {
super(props);
this.state = {
status: 'init',
error: null,
progress: 0,
uploadRequest: null
};
this.handleUpload = this.handleUpload.bind(this);
this.handleProgress = this.handleProgress.bind(this);
this.handleError = this.handleError.bind(this);
this.handleUploadDone = this.handleUploadDone.bind(this);
}
handleProgress (progress) {
console.log('handleProgress', progress);
this.setState({progress});
}
handleError (error) {
console.log('handleError', error);
this.setState({
status: 'error',
error: error,
progress: 0,
uploadRequest: null
});
}
handleUploadDone (uploadRequest) {
console.log('handleUploadDone', uploadRequest.id);
this.setState({
status: 'init',
error: null,
progress: 0,
uploadRequest: null
});
const file = {
id: uploadRequest.id,
name: uploadRequest.file.name,
mime_type: uploadRequest.file.type
};
this.props.onUpload(file);
}
handleUpload (event) {
const file = event.target.files[0];
console.log('handleUpload', file);
this.setState({
status: 'uploading',
error: null,
progress: 0,
uploadRequest: null
});
s3upload(file).then(function (uploadRequest) {
console.log('uploading', uploadRequest);
this.setState({
uploadRequest: uploadRequest
});
uploadRequest.on('error', this.handleError);
uploadRequest.on('progress', this.handleProgress);
uploadRequest.on('done', this.handleUploadDone.bind(null, uploadRequest));
}.bind(this), this.handleError);
}
render () {
return (
<div>
<input type="file" onChange={this.handleUpload} />
<ProgressBar progress={this.state.progress} />
<div className="error">{this.state.error}</div>
</div>
);
}
}
|
react/BuildingIcon/BuildingIcon.sketch.js | seek-oss/seek-style-guide | import React from 'react';
import BuildingIcon from './BuildingIcon';
import generateSketchIconSizes from '../private/generateSketchIconSizes';
export const symbols = {
...generateSketchIconSizes('Building', <BuildingIcon />)
};
|
src/error/index.js | kyoyadmoon/fuzzy-hw1 | /**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import history from '../history';
import Link from '../../components/Link';
import s from './styles.css';
class ErrorPage extends React.Component {
static propTypes = {
error: React.PropTypes.object, // eslint-disable-line react/forbid-prop-types
};
componentDidMount() {
document.title = this.props.error && this.props.error.status === 404 ?
'Page Not Found' : 'Error';
}
goBack = (event) => {
event.preventDefault();
history.goBack();
};
render() {
if (this.props.error) console.error(this.props.error); // eslint-disable-line no-console
const [code, title] = this.props.error && this.props.error.status === 404 ?
['404', 'Page not found'] :
['Error', 'Oups, something went wrong'];
return (
<div className={s.container}>
<main className={s.content}>
<h1 className={s.code}>{code}</h1>
<p className={s.title}>{title}</p>
{code === '404' &&
<p className={s.text}>
The page you're looking for does not exist or an another error occurred.
</p>
}
<p className={s.text}>
<a href="/" onClick={this.goBack}>Go back</a>
, or head over to the
<Link to="/">home page</Link>
to choose a new direction.
</p>
</main>
</div>
);
}
}
export default ErrorPage;
|
examples/transitions/app.js | whouses/react-router | import React from 'react';
import { Router, Route, Link, History, Lifecycle } from 'react-router';
var App = React.createClass({
render() {
return (
<div>
<ul>
<li><Link to="/dashboard">Dashboard</Link></li>
<li><Link to="/form">Form</Link></li>
</ul>
{this.props.children}
</div>
);
}
});
var Home = React.createClass({
render() {
return <h1>Home</h1>;
}
});
var Dashboard = React.createClass({
render() {
return <h1>Dashboard</h1>;
}
});
var Form = React.createClass({
mixins: [ Lifecycle, History ],
getInitialState() {
return {
textValue: 'ohai'
};
},
routerWillLeave(nextLocation) {
if (this.state.textValue)
return 'You have unsaved information, are you sure you want to leave this page?';
},
handleChange(event) {
this.setState({
textValue: event.target.value
});
},
handleSubmit(event) {
event.preventDefault();
this.setState({
textValue: ''
}, () => {
this.history.pushState(null, '/');
});
},
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<p>Click the dashboard link with text in the input.</p>
<input type="text" ref="userInput" value={this.state.textValue} onChange={this.handleChange} />
<button type="submit">Go</button>
</form>
</div>
);
}
});
React.render((
<Router>
<Route path="/" component={App}>
<Route path="dashboard" component={Dashboard} />
<Route path="form" component={Form} />
</Route>
</Router>
), document.getElementById('example'));
|
app/javascript/mastodon/features/ui/components/column_subheading.js | yi0713/mastodon | import React from 'react';
import PropTypes from 'prop-types';
const ColumnSubheading = ({ text }) => {
return (
<div className='column-subheading'>
{text}
</div>
);
};
ColumnSubheading.propTypes = {
text: PropTypes.string.isRequired,
};
export default ColumnSubheading;
|
actor-apps/app-web/src/app/components/sidebar/ContactsSection.react.js | JeeLiu/actor-platform | import _ from 'lodash';
import React from 'react';
import { Styles, RaisedButton } from 'material-ui';
import ActorTheme from 'constants/ActorTheme';
import ContactStore from 'stores/ContactStore';
import ContactActionCreators from 'actions/ContactActionCreators';
import AddContactStore from 'stores/AddContactStore';
import AddContactActionCreators from 'actions/AddContactActionCreators';
import ContactsSectionItem from './ContactsSectionItem.react';
import AddContactModal from 'components/modals/AddContact.react.js';
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return {
isAddContactModalOpen: AddContactStore.isModalOpen(),
contacts: ContactStore.getContacts()
};
};
class ContactsSection extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
componentWillUnmount() {
ContactActionCreators.hideContactList();
ContactStore.removeChangeListener(this.onChange);
AddContactStore.removeChangeListener(this.onChange);
}
constructor(props) {
super(props);
this.state = getStateFromStores();
ContactActionCreators.showContactList();
ContactStore.addChangeListener(this.onChange);
AddContactStore.addChangeListener(this.onChange);
ThemeManager.setTheme(ActorTheme);
}
onChange = () => {
this.setState(getStateFromStores());
};
openAddContactModal = () => {
AddContactActionCreators.openModal();
};
render() {
let contacts = this.state.contacts;
let contactList = _.map(contacts, (contact, i) => {
return (
<ContactsSectionItem contact={contact} key={i}/>
);
});
let addContactModal;
if (this.state.isAddContactModalOpen) {
addContactModal = <AddContactModal/>;
}
return (
<section className="sidebar__contacts">
<ul className="sidebar__list sidebar__list--contacts">
{contactList}
</ul>
<footer>
<RaisedButton label="Add contact" onClick={this.openAddContactModal} style={{width: '100%'}}/>
{addContactModal}
</footer>
</section>
);
}
}
export default ContactsSection;
|
packages/ringcentral-widgets-docs/src/app/pages/Components/Panel/Demo.js | ringcentral/ringcentral-js-widget | import React from 'react';
// eslint-disable-next-line
import Panel from 'ringcentral-widgets/components/Panel';
const props = {};
/**
* A example of `Panel`
*/
const PanelDemo = () => <Panel {...props} />;
export default PanelDemo;
|
webpack/JobWizard/steps/AdvancedFields/Fields.js | theforeman/foreman_remote_execution | import React from 'react';
import PropTypes from 'prop-types';
import { FormGroup, TextInput, Radio } from '@patternfly/react-core';
import { translate as __ } from 'foremanReact/common/I18n';
import { helpLabel } from '../form/FormHelpers';
import { formatter } from '../form/Formatter';
import { NumberInput } from '../form/NumberInput';
export const EffectiveUserField = ({ value, setValue }) => (
<FormGroup
label={__('Effective user')}
labelIcon={helpLabel(
__(
'A user to be used for executing the script. If it differs from the SSH user, su or sudo is used to switch the accounts.'
),
'effective-user'
)}
fieldId="effective-user"
>
<TextInput
aria-label="effective user"
autoComplete="effective-user"
id="effective-user"
type="text"
value={value}
onChange={newValue => setValue(newValue)}
/>
</FormGroup>
);
export const TimeoutToKillField = ({ value, setValue }) => (
<NumberInput
formProps={{
label: __('Timeout to kill'),
labelIcon: helpLabel(
__(
'Time in seconds from the start on the remote host after which the job should be killed.'
),
'timeout-to-kill'
),
fieldId: 'timeout-to-kill',
}}
inputProps={{
value,
placeholder: __('For example: 1, 2, 3, 4, 5...'),
autoComplete: 'timeout-to-kill',
id: 'timeout-to-kill',
onChange: newValue => setValue(newValue),
}}
/>
);
export const PasswordField = ({ value, setValue }) => (
<FormGroup
label={__('Password')}
labelIcon={helpLabel(
__(
'Password is stored encrypted in DB until the job finishes. For future or recurring executions, it is removed after the last execution.'
),
'password'
)}
fieldId="job-password"
>
<TextInput
aria-label="job password"
autoComplete="new-password" // to prevent firefox from autofilling the user password
id="job-password"
type="password"
placeholder="*****"
value={value}
onChange={newValue => setValue(newValue)}
/>
</FormGroup>
);
export const KeyPassphraseField = ({ value, setValue }) => (
<FormGroup
label={__('Private key passphrase')}
labelIcon={helpLabel(
__(
'Key passphrase is only applicable for SSH provider. Other providers ignore this field. Passphrase is stored encrypted in DB until the job finishes. For future or recurring executions, it is removed after the last execution.'
),
'key-passphrase'
)}
fieldId="key-passphrase"
>
<TextInput
aria-label="key passphrase"
autoComplete="key-passphrase"
id="key-passphrase"
type="password"
placeholder="*****"
value={value}
onChange={newValue => setValue(newValue)}
/>
</FormGroup>
);
export const EffectiveUserPasswordField = ({ value, setValue }) => (
<FormGroup
label={__('Effective user password')}
labelIcon={helpLabel(
__(
'Effective user password is only applicable for SSH provider. Other providers ignore this field. Password is stored encrypted in DB until the job finishes. For future or recurring executions, it is removed after the last execution.'
),
'effective-user-password'
)}
fieldId="effective-user-password"
>
<TextInput
aria-label="effective userpassword"
autoComplete="effective-user-password"
id="effective-user-password"
type="password"
placeholder="*****"
value={value}
onChange={newValue => setValue(newValue)}
/>
</FormGroup>
);
export const ConcurrencyLevelField = ({ value, setValue }) => (
<NumberInput
formProps={{
label: __('Concurrency level'),
labelIcon: helpLabel(
__(
'Run at most N tasks at a time. If this is set and proxy batch triggering is enabled, then tasks are triggered on the smart proxy in batches of size 1.'
),
'concurrency-level'
),
fieldId: 'concurrency-level',
}}
inputProps={{
min: 1,
autoComplete: 'concurrency-level',
id: 'concurrency-level',
placeholder: __('For example: 1, 2, 3, 4, 5...'),
value,
onChange: newValue => setValue(newValue),
}}
/>
);
export const TimeSpanLevelField = ({ value, setValue }) => (
<NumberInput
formProps={{
label: __('Time span'),
labelIcon: helpLabel(
__(
'Distribute execution over N seconds. If this is set and proxy batch triggering is enabled, then tasks are triggered on the smart proxy in batches of size 1.'
),
'time-span'
),
fieldId: 'time-span',
}}
inputProps={{
min: 1,
autoComplete: 'time-span',
id: 'time-span',
placeholder: __('For example: 1, 2, 3, 4, 5...'),
value,
onChange: newValue => setValue(newValue),
}}
/>
);
export const ExecutionOrderingField = ({ isRandomizedOrdering, setValue }) => (
<FormGroup
label={__('Execution ordering')}
fieldId="schedule-type"
labelIcon={helpLabel(
<div
dangerouslySetInnerHTML={{
__html: __(
'Execution ordering determines whether the jobs should be executed on hosts in alphabetical order or in randomized order.<br><ul><li><b>Ordered</b> - executes the jobs on hosts in alphabetical order</li><li><b>Randomized</b> - randomizes the order in which jobs are executed on hosts</li></ul>'
),
}}
/>,
'effective-user-password'
)}
isInline
>
<Radio
aria-label="execution order alphabetical"
isChecked={!isRandomizedOrdering}
name="execution-order"
onChange={() => setValue(false)}
id="execution-order-alphabetical"
label={__('Alphabetical')}
/>
<Radio
aria-label="execution order randomized"
isChecked={isRandomizedOrdering}
name="execution-order"
onChange={() => setValue(true)}
id="execution-order-randomized"
label={__('Randomized')}
/>
</FormGroup>
);
export const TemplateInputsFields = ({ inputs, value, setValue }) => (
<>{inputs?.map(input => formatter(input, value, setValue))}</>
);
EffectiveUserField.propTypes = {
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
setValue: PropTypes.func.isRequired,
};
EffectiveUserField.defaultProps = {
value: '',
};
TimeoutToKillField.propTypes = EffectiveUserField.propTypes;
TimeoutToKillField.defaultProps = EffectiveUserField.defaultProps;
PasswordField.propTypes = EffectiveUserField.propTypes;
PasswordField.defaultProps = EffectiveUserField.defaultProps;
KeyPassphraseField.propTypes = EffectiveUserField.propTypes;
KeyPassphraseField.defaultProps = EffectiveUserField.defaultProps;
EffectiveUserPasswordField.propTypes = EffectiveUserField.propTypes;
EffectiveUserPasswordField.defaultProps = EffectiveUserField.defaultProps;
ConcurrencyLevelField.propTypes = EffectiveUserField.propTypes;
ConcurrencyLevelField.defaultProps = EffectiveUserField.defaultProps;
TimeSpanLevelField.propTypes = EffectiveUserField.propTypes;
TimeSpanLevelField.defaultProps = EffectiveUserField.defaultProps;
ExecutionOrderingField.propTypes = {
isRandomizedOrdering: PropTypes.bool,
setValue: PropTypes.func.isRequired,
};
ExecutionOrderingField.defaultProps = {
isRandomizedOrdering: false,
};
TemplateInputsFields.propTypes = {
inputs: PropTypes.array.isRequired,
value: PropTypes.object,
setValue: PropTypes.func.isRequired,
};
TemplateInputsFields.defaultProps = {
value: {},
};
|
node_modules/react-bootstrap/es/NavbarHeader.js | xuan6/admin_dashboard_local_dev | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import { prefix } from './utils/bootstrapUtils';
var contextTypes = {
$bs_navbar: PropTypes.shape({
bsClass: PropTypes.string
})
};
var NavbarHeader = function (_React$Component) {
_inherits(NavbarHeader, _React$Component);
function NavbarHeader() {
_classCallCheck(this, NavbarHeader);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
NavbarHeader.prototype.render = function render() {
var _props = this.props,
className = _props.className,
props = _objectWithoutProperties(_props, ['className']);
var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' };
var bsClassName = prefix(navbarProps, 'header');
return React.createElement('div', _extends({}, props, { className: classNames(className, bsClassName) }));
};
return NavbarHeader;
}(React.Component);
NavbarHeader.contextTypes = contextTypes;
export default NavbarHeader; |
src/svg-icons/action/query-builder.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionQueryBuilder = (props) => (
<SvgIcon {...props}>
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/>
</SvgIcon>
);
ActionQueryBuilder = pure(ActionQueryBuilder);
ActionQueryBuilder.displayName = 'ActionQueryBuilder';
ActionQueryBuilder.muiName = 'SvgIcon';
export default ActionQueryBuilder;
|
es/components/style/form-number-input.js | vovance/3d-demo | 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 FormTextInput from './form-text-input';
export default function FormNumberInput(_ref) {
var onChange = _ref.onChange,
rest = _objectWithoutProperties(_ref, ['onChange']);
var onChangeCustom = function onChangeCustom(event) {
var value = event.target.value;
rest.min = rest.min ? parseFloat(rest.min) : -Infinity;
rest.max = rest.max ? parseFloat(rest.max) : Infinity;
if (parseFloat(value) <= (parseFloat(rest.min) || -Infinity) || parseFloat(value) >= (parseFloat(rest.max) || Infinity)) {
event.target.value = rest.min;
onChange(event);
event.target.select();
} else {
if (!isNaN(parseFloat(value)) && isFinite(value)) {
onChange(event);
} else {
if (value === '-') {
if (rest.min == 0) {
event.target.value = '0';
event.target.select();
}
onChange(event);
} else if (value === '0' || value === '') {
event.target.value = rest.min > 0 ? rest.min : '0';
onChange(event);
event.target.select();
}
}
}
};
var textProps = _extends({}, rest);
delete textProps.state;
return React.createElement(FormTextInput, _extends({ onChange: onChangeCustom, autoComplete: 'off' }, textProps));
} |
examples/counter/index.js | mrblueblue/redux | import React from 'react';
import App from './containers/App';
React.render(
<App />,
document.getElementById('root')
);
|
src/client/components/Home/Landing/BannerHeader.js | kowhai-2016/flatme | import React from 'react'
const BannerHeader = () => {
return (
<div className='header'>
<div className='description1'>
<h1 id='mainTitle'>goFlat</h1>
<h3 id='subtitle'>resolves all your flatting issues</h3>
</div>
<br />
<br />
<div className='row description2'>
<div className='col-md-12'>
<h2>Make the Rules, Share the load, Live the dream!</h2>
<h3>Creates transparency, accountability and harmony between flatmates to maintain ideal living conditions</h3>
</div>
</div>
</div>
)
}
export default BannerHeader
|
src/fullConditional.js | clearbridgesoft/form-builder | import React from 'react';
import ObjectField from 'react-jsonschema-form/lib/components/fields/ObjectField';
import deepcopy from 'deepcopy';
function eval_fun(str_fun){
if(str_fun){
return new Function('args','return ('+str_fun+')(args);');
}
return function(a){return a;};
}
class FullControlConditional extends React.Component{
constructor(props){
super(props);
const condition_fun = eval_fun(
props.schema.conditionFun
);
let new_props=deepcopy({
schema:this.props.schema,
uiSchema:this.props.uiSchema,
});
if(this.props.formData){
new_props.formData = props.formData;
}
let {schema,uiSchema,formData} = condition_fun(new_props);
if (uiSchema.hasOwnProperty('ui:order')){
uiSchema = Object.assign({},uiSchema,{
'ui:order':props.uiSchema['ui:order'].filter(
(p)=>p in schema.properties
)});
}
this.state = {
schema,
uiSchema,
formData,
condition_fun,
needUpdate:false
};
}
componentWillReceiveProps(nextProps){
console.log(['nextprops',nextProps]);
let condition_fun = this.state.condition_fun;
if(nextProps.uiSchema != this.props.uiSchema){
condition_fun = eval_fun(
nextProps.schema.conditionFun
);
this.setState({condition_fun:condition_fun});
}
let new_props=deepcopy({
schema:nextProps.schema,
uiSchema:nextProps.uiSchema,
formData:nextProps.formData || this.state.formData
});
let {schema,uiSchema,formData} = condition_fun(new_props);
if (uiSchema.hasOwnProperty('ui:order')){
uiSchema = Object.assign({},uiSchema,{
'ui:order':nextProps.uiSchema['ui:order'].filter(
(p)=>p in schema.properties
)});
}
//this.state.needUpdate = true;
this.setState({schema,uiSchema,formData});
}
onChange(_formData, options){
console.log('change');
if(this.state.condition_fun){
let new_props=deepcopy({
schema:this.props.schema,
uiSchema:this.props.uiSchema,
formData:_formData
});
let {schema,uiSchema,formData} = this.state.condition_fun(new_props);
//let {schema,uiSchema,formData} = myCondition(kcuf);
if (uiSchema.hasOwnProperty('ui:order')){
uiSchema = Object.assign({},uiSchema,{
'ui:order':this.props.uiSchema['ui:order'].filter(
(p)=>p in schema.properties
)});
}
this.setState({
schema,
uiSchema,
formData:formData
});
this.state.needUpdate = true;
}
this.props.onChange(_formData);
}
componentDidUpdate(){
console.log(this.state.needUpdate);
if(this.state.needUpdate){
this.state.needUpdate = false;
this.props.onChange(this.state.formData);
}
}
render (){
const props = {
...this.props,
onChange:this.onChange.bind(this),
schema:this.state.schema,
uiSchema:this.state.uiSchema,
formData:this.state.formData
};
console.log('render');
return (<ObjectField {...props} />);
}
}
export default FullControlConditional;
|
packages/react-error-overlay/src/components/CloseButton.js | gutenye/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* @flow */
import React from 'react';
import { black } from '../styles';
const closeButtonStyle = {
color: black,
lineHeight: '1rem',
fontSize: '1.5rem',
padding: '1rem',
cursor: 'pointer',
position: 'absolute',
right: 0,
top: 0,
};
type CloseCallback = () => void;
function CloseButton({ close }: {| close: CloseCallback |}) {
return (
<span
title="Click or press Escape to dismiss."
onClick={close}
style={closeButtonStyle}
>
×
</span>
);
}
export default CloseButton;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.