path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
client/src/components/articles/ArticleCard.js | kevinladkins/newsfeed | import React from 'react'
import {Link} from 'react-router-dom'
const ArticleCard = ({channel, article, setArticleUrl}) => {
return (
<Link to={`/newsfeed/${channel.source_id}/${setArticleUrl(article.title)}`} className="article-link">
<div className="card">
<h3>{article.title}</h3>
<img src={article.urlToImage} className="image" alt=""/>
</div>
</Link>
)
}
export default ArticleCard
|
front_end/front_end_app/src/client/main.js | carlodicelico/horizon | import React from 'react';
import Router from 'react-router';
import routes from './routes';
const app = document.getElementById('app');
const initialState = window._initialState;
Router.run(routes, Router.HistoryLocation, (Handler) => {
React.render(<Handler initialState={initialState} />, app);
});
|
node_modules/babel-plugin-react-transform/test/fixtures/code-ignore/actual.js | Right-Men/Ironman | import React from 'react';
const First = React.createNotClass({
displayName: 'First'
});
class Second extends React.NotComponent {}
|
src/app-client.js | NoobJS-nwhax/nwhacks-2017 | 'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import AppRoutes from './components/AppRoutes';
window.onload = () => {
ReactDOM.render(<AppRoutes/>, document.getElementById('main'));
};
|
src/widgets/TimePicker.android.js | airloy/objective | /**
* Created by Layman(http://github.com/anysome) on 16/5/19.
*/
import React from 'react'
import {StyleSheet, View} from 'react-native'
import WheelView from 'react-native-wheel'
export default class TimePicker extends React.Component {
render() {
return (
<DateTimePicker
date={this.props.date}
mode="time"
minuteInterval={this.props.minuteInterval || 5}
onDateChange={this.props.onDateChange}
/>
)
}
}
function makeRange (min, max, step, twice) {
const range = [];
var entry = "";
min = min || 0;
max = max || 9999;
step = step || 1;
for(min; min <= max; min += step) {
entry = min + "";
if (twice) {
entry = entry.length === 1 ? "0" + entry : entry;
}
range.push(entry);
}
return range;
}
class DateTimePicker extends React.Component {
constructor(props) {
super(props);
const { minuteInterval, date } = props;
let dateIndices = this.getDateIndices(date);
this.minutes = makeRange(0, 59, minuteInterval, true);
this.hours = makeRange(1, 12);
this.ampm = ['AM', 'PM'];
this.state = dateIndices;
}
getDateIndices(date) {
const { minuteInterval } = this.props;
let hour = date.getHours();
let hourIndex = hour % 12;
const ampmIndex = hour > 11 ? 1 : 0;
hourIndex = hourIndex === 0 ? 11 : hourIndex - 1;
const minuteIndex = Math.floor(date.getMinutes() / minuteInterval);
return {
hourIndex,
minuteIndex,
ampmIndex
};
}
getNewDate(hourIndex, minuteIndex, ampmIndex) {
hourIndex = hourIndex + 1;
hourIndex = hourIndex === 12 ? 0 : hourIndex;
hourIndex = ampmIndex === 0 ? hourIndex : hourIndex + 12;
let minutes = minuteIndex * this.props.minuteInterval;
let newDate = new Date();
newDate.setHours(hourIndex, minutes, 0, 0);
return newDate;
}
onHourChange(index) {
this.setState({
hourIndex: index
});
let newDate = this.getNewDate(index, this.state.minuteIndex, this.state.ampmIndex);
this.props.onDateChange(newDate);
}
onMinuteChange(index) {
this.setState({
minuteIndex: index
});
let newDate = this.getNewDate(this.state.hourIndex, index, this.state.ampmIndex);
this.props.onDateChange(newDate);
}
onAmpmChange(index) {
this.setState({
ampmIndex: index
});
let newDate = this.getNewDate(this.state.hourIndex, this.state.minuteIndex, index);
this.props.onDateChange(newDate);
}
render() {
return (
<View style={style.container} >
<WheelView
style={style.wheel}
onItemChange={this.onHourChange.bind(this)}
values={this.hours}
isLoop={true}
selectedIndex={this.state.hourIndex}
textSize={this.props.textSize}
/>
<WheelView
style={style.wheel}
onItemChange={(index) => this.onMinuteChange(index)}
values={this.minutes}
isLoop={true}
selectedIndex={this.state.minuteIndex}
textSize={this.props.textSize}
/>
<WheelView
style={style.wheel}
onItemChange={(index) => this.onAmpmChange(index)}
values={this.ampm}
isLoop={false}
selectedIndex={this.state.ampmIndex}
textSize={this.props.textSize}
/>
</View>
);
}
}
DateTimePicker.defaultProps = {
date: new Date(),
minuteInterval: 1,
textSize: 20
};
DateTimePicker.propTypes = {
date: React.PropTypes.instanceOf(Date),
minuteInterval: React.PropTypes.oneOf([1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30]),
onDateChange: React.PropTypes.func.isRequired,
textSize: React.PropTypes.number,
};
const style = StyleSheet.create({
wheel: {
flex: 1,
height: 200
},
container: {
flex: 1,
paddingLeft: 50,
paddingRight: 50,
height: 200,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
}
});
|
app/utils/devtools.component.js | ellheat/devtalk-testing-exercise | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
module.exports = createDevTools(
<DockMonitor
toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-w"
defaultIsVisible={false}
>
<LogMonitor />
</DockMonitor>
);
|
examples/tree-view/index.js | naoishii/ohk2016C | import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import Node from './containers/Node'
import configureStore from './store/configureStore'
import generateTree from './generateTree'
const tree = generateTree()
const store = configureStore(tree)
render(
<Provider store={store}>
<Node id={0} />
</Provider>,
document.getElementById('root')
)
|
src/Container.js | cpojer/react-router-relay | import React from 'react';
import StaticContainer from 'react-static-container';
import getParamsForRoute from './getParamsForRoute';
import RootComponent from './RootComponent';
import RouteAggregator from './RouteAggregator';
export default class Container extends React.Component {
static displayName = 'ReactRouterRelay.Container';
static propTypes = {
Component: React.PropTypes.func.isRequired,
};
static contextTypes = {
routeAggregator: React.PropTypes.instanceOf(RouteAggregator),
};
render() {
const {routeAggregator} = this.context;
if (!routeAggregator) {
return <RootComponent {...this.props} />;
}
const {Component, ...routerProps} = this.props;
const {route} = routerProps;
// FIXME: Remove once fix for facebook/react#4218 is released.
const {children} = routerProps;
if (children) {
routerProps.children = React.cloneElement(children, {});
}
const {queries} = route;
if (!queries) {
return <Component {...routerProps} />;
}
const params = getParamsForRoute(routerProps);
const {fragmentPointers, failure} =
routeAggregator.getData(queries, params);
let shouldUpdate = true;
let element;
// This is largely copied from RelayRootContainer#render.
if (failure) {
const {renderFailure} = route;
if (renderFailure) {
const [error, retry] = failure;
element = renderFailure(error, retry);
} else {
element = null;
}
} else if (fragmentPointers) {
const data = {...routerProps, ...params, ...fragmentPointers};
const {renderFetched} = route;
if (renderFetched) {
element = renderFetched(data);
} else {
element = <Component {...data} />;
}
} else {
const {renderLoading} = route;
if (renderLoading) {
element = renderLoading();
} else {
element = undefined;
}
if (element === undefined) {
element = null;
shouldUpdate = false;
}
}
return (
<StaticContainer shouldUpdate={shouldUpdate}>
{element}
</StaticContainer>
);
}
}
|
node_modules/@exponent/ex-navigation/src/ExNavigationBadge.js | 15chrjef/mobileHackerNews | /**
* @flow
*/
import React from 'react';
import {
StyleSheet,
Text,
View,
} from 'react-native';
type Props = {
textStyle: Object,
onLayout: () => void,
};
type State = {
computedSize: ?{
width: number,
height: number,
},
};
export default class Badge extends React.Component {
static propTypes = Text.propTypes;
_handleLayout: (event: Object) => void;
constructor(props: Props, context: mixed) {
super(props, context);
this._handleLayout = this._handleLayout.bind(this);
}
state: State = {
computedSize: null,
};
render() {
let { computedSize } = this.state;
let style = {};
if (!computedSize) {
style.opacity = 0;
} else {
style.width = Math.max(computedSize.height, computedSize.width);
style.borderRadius = style.width / 2.0;
}
return (
<View
{...this.props}
onLayout={this._handleLayout}
style={[styles.container, this.props.style, style]}>
<Text
numberOfLines={1}
style={[styles.textStyle, this.props.textStyle]}>
{this.props.children}
</Text>
</View>
);
}
_handleLayout(event: Object) {
let { width, height } = event.nativeEvent.layout;
let { computedSize } = this.state;
if (computedSize && computedSize.height === height &&
computedSize.width === width) {
return;
}
this.setState({
computedSize: {
width, height,
},
});
if (this.props.onLayout) {
this.props.onLayout(event);
}
}
}
let styles = StyleSheet.create({
container: {
backgroundColor: 'rgb(0, 122, 255)',
borderWidth: 1 + StyleSheet.hairlineWidth,
borderColor: '#fefefe',
borderRadius: 17 / 2,
overflow: 'hidden',
alignItems: 'center',
justifyContent: 'center',
padding: 1,
},
textStyle: {
fontSize: 12,
color: '#fff',
textAlign: 'center',
lineHeight: 15,
marginBottom: 2,
},
});
|
src/components/svg/icon/Checkbox-Dash.js | ryanabragg/VanguardLARP | import React from 'react';
import PropTypes from 'prop-types';
const DashboxDash = (props) => {
const color = props.color == 'inherit' ? undefined : props.color;
const aria = props.title ? 'svg-dashbox-dash-title' : '' +
props.title && props.description ? ' ' : '' +
props.description ? 'svg-dashbox-dash-desc' : '';
return (
<svg width={props.width} height={props.height} viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg' role='img'
aria-labelledby={aria}
>
{!props.title ? null :
<title id='svg-dashbox-dash-title'>{props.title}</title>
}
{!props.description ? null :
<desc id='svg-dashbox-dash-desc'>{props.description}</desc>
}
<path fill={color} clip-path="url(#b)" d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-2 10H7v-2h10v2z" />
</svg>
);
};
DashboxDash.defaultProps = {
color: 'inherit',
width: undefined,
height: undefined,
title: '',
description: ''
};
DashboxDash.propTypes = {
color: PropTypes.string,
width: PropTypes.string,
height: PropTypes.string,
title: PropTypes.string,
description: PropTypes.string
};
export default DashboxDash;
|
src/components/Footer/Footer.js | HildoBijl/DondersHackathonTR | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Footer.css';
import Link from '../Link';
class Footer extends React.Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<span className={s.text}>© Team Random</span>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/">Home</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/admin">Admin</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/privacy">Privacy</Link>
</div>
</div>
);
}
}
export default withStyles(s)(Footer);
|
actor-apps/app-web/src/app/components/Login.react.js | KitoHo/actor-platform | import _ from 'lodash';
import React from 'react';
import classNames from 'classnames';
import { Styles, RaisedButton, TextField } from 'material-ui';
import { AuthSteps } from 'constants/ActorAppConstants';
import LoginActionCreators from 'actions/LoginActionCreators';
import LoginStore from 'stores/LoginStore';
import ActorTheme from 'constants/ActorTheme';
const ThemeManager = new Styles.ThemeManager();
let getStateFromStores = function () {
return ({
step: LoginStore.getStep(),
errors: LoginStore.getErrors(),
smsRequested: LoginStore.isSmsRequested(),
signupStarted: LoginStore.isSignupStarted(),
codeSent: false
});
};
class Login extends React.Component {
static contextTypes = {
router: React.PropTypes.func
};
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
componentWillUnmount() {
LoginStore.removeChangeListener(this.onChange);
}
componentDidMount() {
this.handleFocus();
}
componentDidUpdate() {
this.handleFocus();
}
constructor(props) {
super(props);
this.state = _.assign({
phone: '',
name: '',
code: ''
}, getStateFromStores());
ThemeManager.setTheme(ActorTheme);
if (LoginStore.isLoggedIn()) {
window.setTimeout(() => this.context.router.replaceWith('/'), 0);
} else {
LoginStore.addChangeListener(this.onChange);
}
}
onChange = () => {
this.setState(getStateFromStores());
}
onPhoneChange = event => {
this.setState({phone: event.target.value});
}
onCodeChange = event => {
this.setState({code: event.target.value});
}
onNameChange = event => {
this.setState({name: event.target.value});
}
onRequestSms = event => {
event.preventDefault();
LoginActionCreators.requestSms(this.state.phone);
}
onSendCode = event => {
event.preventDefault();
LoginActionCreators.sendCode(this.context.router, this.state.code);
}
onSignupRequested = event => {
event.preventDefault();
LoginActionCreators.sendSignup(this.context.router, this.state.name);
}
onWrongNumberClick = event => {
event.preventDefault();
LoginActionCreators.wrongNumberClick();
}
handleFocus = () => {
switch (this.state.step) {
case AuthSteps.PHONE_WAIT:
this.refs.phone.focus();
break;
case AuthSteps.CODE_WAIT:
this.refs.code.focus();
break;
case AuthSteps.SIGNUP_NAME_WAIT:
this.refs.name.focus();
break;
default:
return;
}
}
render() {
let requestFormClassName = classNames('login__form', 'login__form--request', {
'login__form--done': this.state.step > AuthSteps.PHONE_WAIT,
'login__form--active': this.state.step === AuthSteps.PHONE_WAIT
});
let checkFormClassName = classNames('login__form', 'login__form--check', {
'login__form--done': this.state.step > AuthSteps.CODE_WAIT,
'login__form--active': this.state.step === AuthSteps.CODE_WAIT
});
let signupFormClassName = classNames('login__form', 'login__form--signup', {
'login__form--active': this.state.step === AuthSteps.SIGNUP_NAME_WAIT
});
return (
<section className="login-new row center-xs middle-xs">
<div className="login-new__welcome col-xs row center-xs middle-xs">
<img alt="Actor messenger"
className="logo"
src="assets/img/logo.png"
srcSet="assets/img/[email protected] 2x"/>
<article>
<h1 className="login-new__heading">Welcome to <strong>Actor</strong></h1>
<p>
Actor Messenger brings all your business network connections into one place,
makes it easily accessible wherever you go.
</p>
<p>
Our aim is to make your work easier, reduce your email amount,
make the business world closer by reducing time to find right contacts.
</p>
</article>
<footer>
<div className="pull-left">
Actor Messenger © 2015
</div>
<div className="pull-right">
<a href="//actor.im/ios">iPhone</a>
<a href="//actor.im/android">Android</a>
</div>
</footer>
</div>
<div className="login-new__form col-xs-6 col-md-4 row center-xs middle-xs">
<div>
<h1 className="login-new__heading">Sign in</h1>
<form className={requestFormClassName} onSubmit={this.onRequestSms}>
<TextField className="login__form__input"
disabled={this.state.step > AuthSteps.PHONE_WAIT}
errorText={this.state.errors.phone}
floatingLabelText="Phone number"
onChange={this.onPhoneChange}
ref="phone"
type="tel"
value={this.state.phone}/>
<footer className="text-center">
<RaisedButton label="Request code" type="submit"/>
</footer>
</form>
<form className={checkFormClassName} onSubmit={this.onSendCode}>
<TextField className="login__form__input"
disabled={this.state.step > AuthSteps.CODE_WAIT}
errorText={this.state.errors.code}
floatingLabelText="Auth code"
onChange={this.onCodeChange}
ref="code"
type="text"
value={this.state.code}/>
<footer className="text-center">
<RaisedButton label="Check code" type="submit"/>
</footer>
</form>
<form className={signupFormClassName} onSubmit={this.onSignupRequested}>
<TextField className="login__form__input"
errorText={this.state.errors.signup}
floatingLabelText="Your name"
onChange={this.onNameChange}
ref="name"
type="text"
value={this.state.name}/>
<footer className="text-center">
<RaisedButton label="Sign up" type="submit"/>
</footer>
</form>
</div>
</div>
</section>
);
}
}
export default Login;
|
src/svg-icons/action/spellcheck.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSpellcheck = (props) => (
<SvgIcon {...props}>
<path d="M12.45 16h2.09L9.43 3H7.57L2.46 16h2.09l1.12-3h5.64l1.14 3zm-6.02-5L8.5 5.48 10.57 11H6.43zm15.16.59l-8.09 8.09L9.83 16l-1.41 1.41 5.09 5.09L23 13l-1.41-1.41z"/>
</SvgIcon>
);
ActionSpellcheck = pure(ActionSpellcheck);
ActionSpellcheck.displayName = 'ActionSpellcheck';
ActionSpellcheck.muiName = 'SvgIcon';
export default ActionSpellcheck;
|
client/app/containers/NotFoundPage/index.js | KamillaKhabibrakhmanova/postcardsforchange-api | /**
* NotFoundPage
*
* This is the page we show when the user visits a url that doesn't have a route
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import H1 from 'components/H1';
import messages from './messages';
export default function NotFound() {
return (
<article>
<H1>
<FormattedMessage {...messages.header} />
</H1>
</article>
);
}
|
src/components/tabCamera/PhotoDataInputForm.js | timLoewel/sites | /**
* Created by tim on 16/03/17.
*/
/**
* Created by tim on 13/03/17.
*/
import React from 'react';
import {connect} from 'react-redux';
import {ScrollView, TextInput, Text, View, KeyboardAvoidingView, Button} from 'react-native';
import I18n from '../../assets/translations';
import theme from '../../assets/themes/sites-theme';
import {setPhotoLocation, setPhotoDescription} from '../../model/ui/camera/cameraReducer';
class PhotoDataInputForm extends React.Component {
constructor(props) {
super(props);
this.state = {
focused : true,
}
}
_onFocus() {
this.setState({focused: true});
}
_onBlur() {
this.setState({focused: false});
}
render() {
const fontSize = this.state.focused ? theme.fontSizeSmall : theme.inputFontSize;
return (
<View style={{flex: 1, flexDirection: 'column', justifyContent: 'flex-start', alignItems: 'stretch',}}>
<View style={{flex: 1, flexDirection: 'column', justifyContent: 'flex-start', alignItems: 'flex-start'}}>
<Text style={{fontSize: theme.fontSizeBase, fontWeight: 'bold'}}>{I18n.t('camera.descriptionTitle')}</Text>
<View style={{flexDirection: 'row', justifyContent: 'flex-start'}}>
<TextInput
placeholderTextColor={theme.subtitleColor}
style={{flex: 1, fontSize: fontSize, backgroundColor: theme.inputBGColor, textAlign: 'left', textAlignVertical: 'top'}}
onChangeText={this.props.setPhotoDescription}
onBlur={this._onFocus.bind(this)}
onFocus={this._onBlur.bind(this)}
value={this.props.description}
placeholder={I18n.t('camera.thisIsAppendedToPhoto')}
multiline={true}
numberOfLines={5}
maxLength={280}
selectTextOnFocus={true}
underlineColorAndroid="transparent"
/>
</View>
</View>
</View>
);
}
}
const mapStateToProps = state => ({
// currentLocation: state.ui.geoLocationReducer.get('position'),
location: state.ui.cameraReducer.location,
description: state.ui.cameraReducer.description,
});
function bindAction(dispatch) {
return {
//newLocation: { formattedAddress, location: { latitude, longitude } }
setPhotoLocation: (newLocation) => dispatch(setPhotoLocation(newLocation)),
setPhotoDescription: (description) => dispatch(setPhotoDescription(description))
}
}
export default connect(mapStateToProps, bindAction)(PhotoDataInputForm);
|
src/svg-icons/hardware/mouse.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareMouse = (props) => (
<SvgIcon {...props}>
<path d="M13 1.07V9h7c0-4.08-3.05-7.44-7-7.93zM4 15c0 4.42 3.58 8 8 8s8-3.58 8-8v-4H4v4zm7-13.93C7.05 1.56 4 4.92 4 9h7V1.07z"/>
</SvgIcon>
);
HardwareMouse = pure(HardwareMouse);
HardwareMouse.displayName = 'HardwareMouse';
HardwareMouse.muiName = 'SvgIcon';
export default HardwareMouse;
|
src/components/common/svg-icons/action/view-quilt.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionViewQuilt = (props) => (
<SvgIcon {...props}>
<path d="M10 18h5v-6h-5v6zm-6 0h5V5H4v13zm12 0h5v-6h-5v6zM10 5v6h11V5H10z"/>
</SvgIcon>
);
ActionViewQuilt = pure(ActionViewQuilt);
ActionViewQuilt.displayName = 'ActionViewQuilt';
ActionViewQuilt.muiName = 'SvgIcon';
export default ActionViewQuilt;
|
src/widgets/StepperInputs/StepperInputWithLabel.js | sussol/mobile | /* eslint-disable react/forbid-prop-types */
import React from 'react';
import { Text, View } from 'react-native';
import propTypes from 'prop-types';
import { BaseStepperInput } from './BaseStepperInput';
import { DARKER_GREY, APP_FONT_FAMILY } from '../../globalStyles';
export const StepperInputWithLabel = ({
containerStyle,
textStyle,
label,
LeftButton,
RightButton,
TextInput,
...stepperProps
}) => (
<View style={containerStyle}>
<Text style={textStyle}>{label}</Text>
<BaseStepperInput
LeftButton={LeftButton}
RightButton={RightButton}
TextInput={TextInput}
{...stepperProps}
/>
</View>
);
StepperInputWithLabel.defaultProps = {
containerStyle: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-end',
},
textStyle: {
marginRight: 10,
fontSize: 12,
minWidth: 90,
textAlign: 'right',
fontFamily: APP_FONT_FAMILY,
color: DARKER_GREY,
},
label: '',
LeftButton: null,
RightButton: null,
};
StepperInputWithLabel.propTypes = {
containerStyle: propTypes.object,
textStyle: propTypes.object,
label: propTypes.string,
RightButton: propTypes.node,
LeftButton: propTypes.node,
TextInput: propTypes.node.isRequired,
};
|
src/views/icons/ExpandIcon.js | physiii/open-automation | import React from 'react';
import PropTypes from 'prop-types';
import IconBase from './IconBase.js';
import './ExpandIcon.css';
export class ExpandIcon extends React.Component {
constructor (props) {
super(props);
this.state = {isHovered: false};
this.handleMouseOver = this.handleMouseOver.bind(this);
this.handleMouseOut = this.handleMouseOut.bind(this);
}
handleMouseOver () {
this.setState({isHovered: true});
}
handleMouseOut () {
this.setState({isHovered: false});
}
render () {
const {isExpanded, ...iconBaseProps} = this.props;
return (
<IconBase
{...iconBaseProps}
viewBox="0 0 22 22"
onMouseOver={this.handleMouseOver}
onMouseOut={this.handleMouseOut}>
<g styleName={(this.state.isHovered ? 'isHovered' : '') + (isExpanded ? ' isExpanded' : '')} fillRule="evenodd">
<path styleName="topArrow" d="M10.2,10.2L16.5,4L12,4l0-2h7c0.5,0,1,0.5,1,1v7h-2V5.5l-6.2,6.2L10.2,10.2z" />
<path styleName="bottomArrow" d="M11.8,11.8L5.5,18l4.5,0l0,2H3c-0.5,0-1-0.5-1-1v-7h2v4.5l6.2-6.2L11.8,11.8z" />
</g>
</IconBase>
);
}
}
ExpandIcon.propTypes = {
isExpanded: PropTypes.bool
};
export default ExpandIcon;
|
src/components/dialog/Dialog.js | isogon/styled-mdl | import React from 'react'
import ReactModal from 'react-modal'
import { DialogStyle, fadeIn } from './Dialog.style'
const style = {
overlay: {
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(100, 100, 100, 0.3)',
zIndex: 999,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
animation: `${fadeIn} 0.3s cubic-bezier(0.4, 0, 0.2, 1) forwards`,
},
content: {
position: 'reltive',
top: 0,
left: 0,
right: 0,
bottom: 0,
height: 'auto',
width: 'auto',
background: 'transparent',
zIndex: 1000,
padding: 0,
margin: 0,
border: 0,
overflow: 'visible',
},
}
const DialogWrap = ({ className, children, ...props }) => (
<ReactModal style={style} {...props}>
<div className={className}>{children}</div>
</ReactModal>
)
const Dialog = DialogStyle.withComponent(DialogWrap)
Dialog.displayName = 'Dialog'
export default Dialog
|
mlflow/server/js/src/common/utils/Utils.js | mlflow/mlflow | import dateFormat from 'dateformat';
import React from 'react';
import notebookSvg from '../static/notebook.svg';
import revisionSvg from '../static/revision.svg';
import emptySvg from '../static/empty.svg';
import laptopSvg from '../static/laptop.svg';
import projectSvg from '../static/project.svg';
import jobSvg from '../static/job.svg';
import qs from 'qs';
import { MLFLOW_INTERNAL_PREFIX } from './TagUtils';
import { message } from 'antd';
import _ from 'lodash';
import { ErrorCodes, SupportPageUrl } from '../constants';
import { FormattedMessage } from 'react-intl';
import { ErrorWrapper } from './ErrorWrapper';
message.config({
maxCount: 1,
duration: 5,
});
class Utils {
/**
* Merge a runs parameters / metrics.
* @param runUuids - A list of Run UUIDs.
* @param keyValueList - A list of objects. One object for each run.
* @retuns A key to a map of (runUuid -> value)
*/
static mergeRuns(runUuids, keyValueList) {
const ret = {};
keyValueList.forEach((keyValueObj, i) => {
const curRunUuid = runUuids[i];
Object.keys(keyValueObj).forEach((key) => {
const cur = ret[key] || {};
ret[key] = {
...cur,
[curRunUuid]: keyValueObj[key],
};
});
});
return ret;
}
static runNameTag = 'mlflow.runName';
static sourceNameTag = 'mlflow.source.name';
static sourceTypeTag = 'mlflow.source.type';
static gitCommitTag = 'mlflow.source.git.commit';
static entryPointTag = 'mlflow.project.entryPoint';
static backendTag = 'mlflow.project.backend';
static userTag = 'mlflow.user';
static loggedModelsTag = 'mlflow.log-model.history';
static formatMetric(value) {
if (value === 0) {
return '0';
} else if (Math.abs(value) < 1e-3) {
return value.toExponential(3).toString();
} else if (Math.abs(value) < 10) {
return (Math.round(value * 1000) / 1000).toString();
} else if (Math.abs(value) < 100) {
return (Math.round(value * 100) / 100).toString();
} else {
return (Math.round(value * 10) / 10).toString();
}
}
/**
* Helper method for that returns a truncated version of the passed-in string (with trailing
* ellipsis) if the string is longer than maxLength. Otherwise, just returns the passed-in string.
*/
static truncateString(string, maxLength) {
if (string.length > maxLength) {
return string.slice(0, maxLength - 3) + '...';
}
return string;
}
/**
* We need to cast all of the timestamps back to numbers since keys of JS objects are auto casted
* to strings.
*
* @param metrics - List of { timestamp: "1", [run1.uuid]: 7, ... }
* @returns Same list but all of the timestamps casted to numbers.
*/
static convertTimestampToInt(metrics) {
return metrics.map((metric) => {
return {
...metric,
timestamp: Number.parseFloat(metric.timestamp),
};
});
}
/**
* Format timestamps from millisecond epoch time.
*/
static formatTimestamp(timestamp, format = 'yyyy-mm-dd HH:MM:ss') {
if (timestamp === undefined) {
return '(unknown)';
}
const d = new Date(0);
d.setUTCMilliseconds(timestamp);
return dateFormat(d, format);
}
static timeSinceStr(date, referenceDate = new Date()) {
const seconds = Math.max(0, Math.floor((referenceDate - date) / 1000));
let interval = Math.floor(seconds / 31536000);
if (interval >= 1) {
return (
<FormattedMessage
defaultMessage='{timeSince, plural, =1 {1 year} other {# years}} ago'
description='Text for time in years since given date for MLflow views'
values={{ timeSince: interval }}
/>
);
}
interval = Math.floor(seconds / 2592000);
if (interval >= 1) {
return (
<FormattedMessage
defaultMessage='{timeSince, plural, =1 {1 month} other {# months}} ago'
description='Text for time in months since given date for MLflow views'
values={{ timeSince: interval }}
/>
);
}
interval = Math.floor(seconds / 86400);
if (interval >= 1) {
return (
<FormattedMessage
defaultMessage='{timeSince, plural, =1 {1 day} other {# days}} ago'
description='Text for time in days since given date for MLflow views'
values={{ timeSince: interval }}
/>
);
}
interval = Math.floor(seconds / 3600);
if (interval >= 1) {
return (
<FormattedMessage
defaultMessage='{timeSince, plural, =1 {1 hour} other {# hours}} ago'
description='Text for time in hours since given date for MLflow views'
values={{ timeSince: interval }}
/>
);
}
interval = Math.floor(seconds / 60);
if (interval >= 1) {
return (
<FormattedMessage
defaultMessage='{timeSince, plural, =1 {1 minute} other {# minutes}} ago'
description='Text for time in minutes since given date for MLflow views'
values={{ timeSince: interval }}
/>
);
}
return (
<FormattedMessage
defaultMessage='{timeSince, plural, =1 {1 second} other {# seconds}} ago'
description='Text for time in seconds since given date for MLflow views'
values={{ timeSince: seconds }}
/>
);
}
/**
* Format a duration given in milliseconds.
*
* @param duration in milliseconds
*/
static formatDuration(duration) {
if (duration < 500) {
return duration + 'ms';
} else if (duration < 1000 * 60) {
return (duration / 1000).toFixed(1) + 's';
} else if (duration < 1000 * 60 * 60) {
return (duration / 1000 / 60).toFixed(1) + 'min';
} else if (duration < 1000 * 60 * 60 * 24) {
return (duration / 1000 / 60 / 60).toFixed(1) + 'h';
} else {
return (duration / 1000 / 60 / 60 / 24).toFixed(1) + 'd';
}
}
/**
* Get the duration of a run given start- and end time.
*
* @param startTime in milliseconds
* @param endTime in milliseconds
*/
static getDuration(startTime, endTime) {
return startTime && endTime ? this.formatDuration(endTime - startTime) : null;
}
static baseName(path) {
const pieces = path.split('/');
return pieces[pieces.length - 1];
}
static dropExtension(path) {
return path.replace(/(.*[^/])\.[^/.]+$/, '$1');
}
/**
* Normalizes a URI, removing redundant slashes and trailing slashes
* For example, normalize("foo://bar///baz/") === "foo://bar/baz"
*/
static normalize(uri) {
// Remove empty authority component (e.g., "foo:///" becomes "foo:/")
const withNormalizedAuthority = uri.replace(/[:]\/\/\/+/, ':/');
// Remove redundant slashes while ensuring that double slashes immediately following
// the scheme component are preserved
const withoutRedundantSlashes = withNormalizedAuthority.replace(/(^\/|[^:]\/)\/+/g, '$1');
const withoutTrailingSlash = withoutRedundantSlashes.replace(/\/$/, '');
return withoutTrailingSlash;
}
static getGitHubRegex() {
return /[@/]github.com[:/]([^/.]+)\/([^/#]+)#?(.*)/;
}
static getGitLabRegex() {
return /[@/]gitlab.com[:/]([^/.]+)\/([^/#]+)#?(.*)/;
}
static getBitbucketRegex() {
return /[@/]bitbucket.org[:/]([^/.]+)\/([^/#]+)#?(.*)/;
}
static getGitRepoUrl(sourceName) {
const gitHubMatch = sourceName.match(Utils.getGitHubRegex());
const gitLabMatch = sourceName.match(Utils.getGitLabRegex());
const bitbucketMatch = sourceName.match(Utils.getBitbucketRegex());
let url = null;
if (gitHubMatch || gitLabMatch) {
const baseUrl = gitHubMatch ? 'https://github.com/' : 'https://gitlab.com/';
const match = gitHubMatch || gitLabMatch;
url = baseUrl + match[1] + '/' + match[2].replace(/.git/, '');
if (match[3]) {
url = url + '/tree/master/' + match[3];
}
} else if (bitbucketMatch) {
const baseUrl = 'https://bitbucket.org/';
url = baseUrl + bitbucketMatch[1] + '/' + bitbucketMatch[2].replace(/.git/, '');
if (bitbucketMatch[3]) {
url = url + '/src/master/' + bitbucketMatch[3];
}
}
return url;
}
static getGitCommitUrl(sourceName, sourceVersion) {
const gitHubMatch = sourceName.match(Utils.getGitHubRegex());
const gitLabMatch = sourceName.match(Utils.getGitLabRegex());
const bitbucketMatch = sourceName.match(Utils.getBitbucketRegex());
let url = null;
if (gitHubMatch || gitLabMatch) {
const baseUrl = gitHubMatch ? 'https://github.com/' : 'https://gitlab.com/';
const match = gitHubMatch || gitLabMatch;
url =
baseUrl +
match[1] +
'/' +
match[2].replace(/.git/, '') +
'/tree/' +
sourceVersion +
'/' +
match[3];
} else if (bitbucketMatch) {
const baseUrl = 'https://bitbucket.org/';
url =
baseUrl +
bitbucketMatch[1] +
'/' +
bitbucketMatch[2].replace(/.git/, '') +
'/src/' +
sourceVersion +
'/' +
bitbucketMatch[3];
}
return url;
}
static getQueryParams = () => {
return window.location && window.location.search ? window.location.search : '';
};
/**
* Returns a copy of the provided URL with its query parameters set to `queryParams`.
* @param url URL string like "http://my-mlflow-server.com/#/experiments/9.
* @param queryParams Optional query parameter string like "?param=12345". Query params provided
* via this string will override existing query param values in `url`
*/
static setQueryParams(url, queryParams) {
const urlObj = new URL(url);
urlObj.search = queryParams || '';
return urlObj.toString();
}
/**
* Set query params and returns the updated query params.
* @returns {string} updated query params
*/
static addQueryParams(currentQueryParams, newQueryParams) {
if (!newQueryParams || Object.keys(newQueryParams).length === 0) {
return currentQueryParams;
}
const urlSearchParams = new URLSearchParams(currentQueryParams);
Object.entries(newQueryParams).forEach(
([key, value]) => !!key && !!value && urlSearchParams.set(key, value),
);
const queryParams = urlSearchParams.toString();
if (queryParams !== '' && !queryParams.includes('?')) {
return `?${queryParams}`;
}
return queryParams;
}
static getDefaultJobRunName(jobId, runId, workspaceId = null) {
if (!jobId) {
return '-';
}
let name = `job ${jobId}`;
if (runId) {
name = `run ${runId} of ` + name;
}
if (workspaceId) {
name = `workspace ${workspaceId}: ` + name;
}
return name;
}
static getDefaultNotebookRevisionName(notebookId, revisionId, workspaceId = null) {
if (!notebookId) {
return '-';
}
let name = `notebook ${notebookId}`;
if (revisionId) {
name = `revision ${revisionId} of ` + name;
}
if (workspaceId) {
name = `workspace ${workspaceId}: ` + name;
}
return name;
}
static getNotebookId(tags) {
const notebookIdTag = 'mlflow.databricks.notebookID';
return tags && tags[notebookIdTag] && tags[notebookIdTag].value;
}
static getClusterSpecJson(tags) {
const clusterSpecJsonTag = 'mlflow.databricks.cluster.info';
return tags && tags[clusterSpecJsonTag] && tags[clusterSpecJsonTag].value;
}
static getClusterLibrariesJson(tags) {
const clusterLibrariesJsonTag = 'mlflow.databricks.cluster.libraries';
return tags && tags[clusterLibrariesJsonTag] && tags[clusterLibrariesJsonTag].value;
}
static getClusterId(tags) {
const clusterIdTag = 'mlflow.databricks.cluster.id';
return tags && tags[clusterIdTag] && tags[clusterIdTag].value;
}
static getNotebookRevisionId(tags) {
const revisionIdTag = 'mlflow.databricks.notebookRevisionID';
return tags && tags[revisionIdTag] && tags[revisionIdTag].value;
}
/**
* Renders the source name and entry point into an HTML element. Used for display.
* @param tags Object containing tag key value pairs.
* @param queryParams Query params to add to certain source type links.
* @param runUuid ID of the MLflow run to add to certain source (revision) links.
*/
static renderSource(tags, queryParams, runUuid) {
const sourceName = Utils.getSourceName(tags);
const sourceType = Utils.getSourceType(tags);
let res = Utils.formatSource(tags);
if (sourceType === 'PROJECT') {
const url = Utils.getGitRepoUrl(sourceName);
if (url) {
res = (
<a target='_top' href={url}>
{res}
</a>
);
}
return res;
}
return res;
}
/**
* Renders the notebook source name and entry point into an HTML element. Used for display.
*/
static renderNotebookSource(
queryParams,
notebookId,
revisionId,
runUuid,
sourceName,
workspaceUrl = null,
nameOverride = null,
) {
// sourceName may not be present when rendering feature table notebook consumers from remote
// workspaces or when notebook fetcher failed to fetch the sourceName. Always provide a default
// notebook name in such case.
const baseName = sourceName
? Utils.baseName(sourceName)
: Utils.getDefaultNotebookRevisionName(notebookId, revisionId);
if (notebookId) {
let url = Utils.setQueryParams(workspaceUrl || window.location.origin, queryParams);
url += `#notebook/${notebookId}`;
if (revisionId) {
url += `/revision/${revisionId}`;
if (runUuid) {
url += `/mlflow/run/${runUuid}`;
}
}
return (
<a
title={sourceName || Utils.getDefaultNotebookRevisionName(notebookId, revisionId)}
href={url}
target='_top'
>
{nameOverride || baseName}
</a>
);
} else {
return nameOverride || baseName;
}
}
/**
* Renders the job source name and entry point into an HTML element. Used for display.
*/
static renderJobSource(
queryParams,
jobId,
jobRunId,
jobName,
workspaceUrl = null,
nameOverride = null,
) {
if (jobId) {
// jobName may not be present when rendering feature table job consumers from remote
// workspaces or when getJob API failed to fetch the jobName. Always provide a default
// job name in such case.
const reformatJobName = jobName || Utils.getDefaultJobRunName(jobId, jobRunId);
let url = Utils.setQueryParams(workspaceUrl || window.location.origin, queryParams);
url += `#job/${jobId}`;
if (jobRunId) {
url += `/run/${jobRunId}`;
}
return (
<a title={reformatJobName} href={url} target='_top'>
{nameOverride || reformatJobName}
</a>
);
} else {
return nameOverride || jobName;
}
}
/**
* Returns an svg with some styling applied.
*/
static renderSourceTypeIcon(tags) {
const imageStyle = {
height: '20px',
marginRight: '4px',
};
const sourceType = this.getSourceType(tags);
if (sourceType === 'NOTEBOOK') {
if (Utils.getNotebookRevisionId(tags)) {
return (
<img
alt='Notebook Revision Icon'
title='Notebook Revision'
style={imageStyle}
src={revisionSvg}
/>
);
} else {
return <img alt='Notebook Icon' title='Notebook' style={imageStyle} src={notebookSvg} />;
}
} else if (sourceType === 'LOCAL') {
return (
<img alt='Local Source Icon' title='Local Source' style={imageStyle} src={laptopSvg} />
);
} else if (sourceType === 'PROJECT') {
return <img alt='Project Icon' title='Project' style={imageStyle} src={projectSvg} />;
} else if (sourceType === 'JOB') {
return <img alt='Job Icon' title='Job' style={imageStyle} src={jobSvg} />;
}
return <img alt='No icon' style={imageStyle} src={emptySvg} />;
}
/**
* Renders the source name and entry point into a string. Used for sorting.
* @param run MlflowMessages.RunInfo
*/
static formatSource(tags) {
const sourceName = Utils.getSourceName(tags);
const sourceType = Utils.getSourceType(tags);
const entryPointName = Utils.getEntryPointName(tags);
if (sourceType === 'PROJECT') {
let res = Utils.dropExtension(Utils.baseName(sourceName));
if (entryPointName && entryPointName !== 'main') {
res += ':' + entryPointName;
}
return res;
} else if (sourceType === 'JOB') {
const jobIdTag = 'mlflow.databricks.jobID';
const jobRunIdTag = 'mlflow.databricks.jobRunID';
const jobId = tags && tags[jobIdTag] && tags[jobIdTag].value;
const jobRunId = tags && tags[jobRunIdTag] && tags[jobRunIdTag].value;
if (jobId && jobRunId) {
return Utils.getDefaultJobRunName(jobId, jobRunId);
}
return sourceName;
} else {
return Utils.baseName(sourceName);
}
}
/**
* Returns the absolute path to a notebook given a notebook id
* @param notebookId Notebook object id
* @returns
*/
static getNotebookLink(notebookId) {
return window.location.origin + '/#notebook/' + notebookId;
}
/**
* Renders the run name into a string.
* @param runTags Object of tag name to MlflowMessages.RunTag instance
*/
static getRunDisplayName(runTags, runUuid) {
return Utils.getRunName(runTags) || 'Run ' + runUuid;
}
static getRunName(runTags) {
const runNameTag = runTags[Utils.runNameTag];
if (runNameTag) {
return runNameTag.value;
}
return '';
}
static getSourceName(runTags) {
const sourceNameTag = runTags[Utils.sourceNameTag];
if (sourceNameTag) {
return sourceNameTag.value;
}
return '';
}
static getSourceType(runTags) {
const sourceTypeTag = runTags[Utils.sourceTypeTag];
if (sourceTypeTag) {
return sourceTypeTag.value;
}
return '';
}
static getSourceVersion(runTags) {
const gitCommitTag = runTags[Utils.gitCommitTag];
if (gitCommitTag) {
return gitCommitTag.value;
}
return '';
}
static getEntryPointName(runTags) {
const entryPointTag = runTags[Utils.entryPointTag];
if (entryPointTag) {
return entryPointTag.value;
}
return '';
}
static getBackend(runTags) {
const backendTag = runTags[Utils.backendTag];
if (backendTag) {
return backendTag.value;
}
return '';
}
// TODO(aaron) Remove runInfo when user_id deprecation is complete.
static getUser(runInfo, runTags) {
const userTag = runTags[Utils.userTag];
if (userTag) {
return userTag.value;
}
return runInfo.user_id;
}
static renderVersion(tags, shortVersion = true) {
const sourceVersion = Utils.getSourceVersion(tags);
const sourceName = Utils.getSourceName(tags);
const sourceType = Utils.getSourceType(tags);
return Utils.renderSourceVersion(sourceVersion, sourceName, sourceType, shortVersion);
}
static renderSourceVersion(sourceVersion, sourceName, sourceType, shortVersion = true) {
if (sourceVersion) {
const versionString = shortVersion ? sourceVersion.substring(0, 6) : sourceVersion;
if (sourceType === 'PROJECT') {
const url = Utils.getGitCommitUrl(sourceName, sourceVersion);
if (url) {
return (
<a href={url} target='_top'>
{versionString}
</a>
);
}
return versionString;
} else {
return versionString;
}
}
return null;
}
static pluralize(word, quantity) {
if (quantity > 1) {
return word + 's';
} else {
return word;
}
}
static getRequestWithId(requests, requestId) {
return requests.find((r) => r.id === requestId);
}
static getCurveKey(runId, metricName) {
return `${runId}-${metricName}`;
}
static getCurveInfoFromKey(curvePair) {
const splitPair = curvePair.split('-');
return { runId: splitPair[0], metricName: splitPair.slice(1, splitPair.length).join('-') };
}
/**
* Return metric plot state from the current URL
*
* The reverse transformation (from metric plot component state to URL) is exposed as a component
* method, as it only needs to be called within the MetricsPlotPanel component
*
* See documentation in Routes.getMetricPageRoute for descriptions of the individual fields
* within the returned state object.
*
* @param search - window.location.search component of the URL - in particular, the query string
* from the URL.
*/
static getMetricPlotStateFromUrl(search) {
const defaultState = {
selectedXAxis: 'relative',
selectedMetricKeys: [],
showPoint: false,
yAxisLogScale: false,
lineSmoothness: 1,
layout: {},
};
const params = qs.parse(search.slice(1, search.length));
if (!params) {
return defaultState;
}
const selectedXAxis = params['x_axis'] || 'relative';
const selectedMetricKeys =
JSON.parse(params['plot_metric_keys']) || defaultState.selectedMetricKeys;
const showPoint = params['show_point'] === 'true';
const yAxisLogScale = params['y_axis_scale'] === 'log';
const lineSmoothness = params['line_smoothness'] ? parseFloat(params['line_smoothness']) : 0;
const layout = params['plot_layout'] ? JSON.parse(params['plot_layout']) : { autosize: true };
// Default to displaying all runs, i.e. to deselectedCurves being empty
const deselectedCurves = params['deselected_curves']
? JSON.parse(params['deselected_curves'])
: [];
const lastLinearYAxisRange = params['last_linear_y_axis_range']
? JSON.parse(params['last_linear_y_axis_range'])
: [];
return {
selectedXAxis,
selectedMetricKeys,
showPoint,
yAxisLogScale,
lineSmoothness,
layout,
deselectedCurves,
lastLinearYAxisRange,
};
}
static getPlotLayoutFromUrl(search) {
const params = qs.parse(search);
const layout = params['plot_layout'];
return layout ? JSON.parse(layout) : {};
}
static getSearchParamsFromUrl(search) {
const params = qs.parse(search, { ignoreQueryPrefix: true });
const str = JSON.stringify(params, function replaceUndefinedAndBools(key, value) {
return value === undefined ? '' : value === 'true' ? true : value === 'false' ? false : value;
});
return params ? JSON.parse(str) : [];
}
static getSearchUrlFromState(state) {
const replaced = {};
for (const key in state) {
if (state[key] === undefined) {
replaced[key] = '';
} else {
replaced[key] = state[key];
}
}
return qs.stringify(replaced);
}
static compareByTimestamp(history1, history2) {
return history1.timestamp - history2.timestamp;
}
static compareByStepAndTimestamp(history1, history2) {
const stepResult = history1.step - history2.step;
return stepResult === 0 ? history1.timestamp - history2.timestamp : stepResult;
}
static getVisibleTagValues(tags) {
// Collate tag objects into list of [key, value] lists and filter MLflow-internal tags
return Object.values(tags)
.map((t) => [t.key || t.getKey(), t.value || t.getValue()])
.filter((t) => !t[0].startsWith(MLFLOW_INTERNAL_PREFIX));
}
static getVisibleTagKeyList(tagsList) {
return _.uniq(
_.flatMap(tagsList, (tags) => Utils.getVisibleTagValues(tags).map(([key]) => key)),
);
}
/**
* Concat array with arrayToConcat and group by specified key 'id'.
* if array==[{'theId': 123, 'a': 2}, {'theId': 456, 'b': 3}]
* and arrayToConcat==[{'theId': 123, 'c': 3}, {'theId': 456, 'd': 4}]
* then concatAndGroupArraysById(array, arrayToConcat, 'theId')
* == [{'theId': 123, 'a': 2, 'c': 3}, {'theId': 456, 'b': 3, 'd': 4}].
* From https://stackoverflow.com/a/38506572/13837474
*/
static concatAndGroupArraysById(array, arrayToConcat, id) {
return (
_(array)
.concat(arrayToConcat)
.groupBy(id)
// complication of _.merge necessary to avoid mutating arguments
.map(_.spread((obj, source) => _.merge({}, obj, source)))
.value()
);
}
/**
* Parses the mlflow.log-model.history tag and returns a list of logged models,
* with duplicates (as defined by two logged models with the same path) removed by
* keeping the logged model with the most recent creation date.
* Each logged model will be of the form:
* { artifactPath: string, flavors: string[], utcTimeCreated: number }
*/
static getLoggedModelsFromTags(tags) {
const modelsTag = tags[this.loggedModelsTag];
if (modelsTag) {
const models = JSON.parse(modelsTag.value);
if (models) {
// extract artifact path, flavors and creation time from tag.
// 'python_function' should be interpreted as pyfunc flavor
const filtered = models.map((model) => {
const removeFunc = Object.keys(_.omit(model.flavors, 'python_function'));
const flavors = removeFunc.length ? removeFunc : ['pyfunc'];
return {
artifactPath: model.artifact_path,
flavors: flavors,
utcTimeCreated: new Date(model.utc_time_created).getTime() / 1000,
};
});
// sort in descending order of creation time
const sorted = filtered.sort(
(a, b) => parseFloat(b.utcTimeCreated) - parseFloat(a.utcTimeCreated),
);
return _.uniqWith(sorted, (a, b) => a.artifactPath === b.artifactPath);
}
}
return [];
}
/**
* Returns a list of models formed by merging the given logged models and registered models.
* Sort such that models that are logged and registered come first, followed by
* only registered models, followed by only logged models. Ties broken in favor of newer creation
* time.
* @param loggedModels
* @param registeredModels Model versions by run uuid, from redux state.
*/
static mergeLoggedAndRegisteredModels(loggedModels, registeredModels) {
// use artifactPath for grouping while merging lists
const registeredModelsWithNormalizedPath = registeredModels.map((model) => {
return {
registeredModelName: model.name,
artifactPath: this.normalize(model.source).split('/artifacts/')[1],
registeredModelVersion: model.version,
registeredModelCreationTimestamp: model.creation_timestamp,
};
});
const loggedModelsWithNormalizedPath = loggedModels.map((model) => {
return { ...model, artifactPath: this.normalize(model.artifactPath) };
});
const models = this.concatAndGroupArraysById(
loggedModelsWithNormalizedPath,
registeredModelsWithNormalizedPath,
'artifactPath',
);
return models.sort((a, b) => {
if (a.registeredModelVersion && b.registeredModelVersion) {
if (a.flavors && !b.flavors) {
return -1;
} else if (!a.flavors && b.flavors) {
return 1;
} else {
return (
parseInt(b.registeredModelCreationTimestamp, 10) -
parseInt(a.registeredModelCreationTimestamp, 10)
);
}
} else if (a.registeredModelVersion && !b.registeredModelVersion) {
return -1;
} else if (!a.registeredModelVersion && b.registeredModelVersion) {
return 1;
}
return b.utcTimeCreated - a.utcTimeCreated;
});
}
static logErrorAndNotifyUser(e) {
console.error(e);
if (typeof e === 'string') {
message.error(e);
} else if (e instanceof ErrorWrapper) {
// not all error is wrapped by ErrorWrapper
message.error(e.renderHttpError());
}
}
static sortExperimentsById = (experiments) => {
return _.sortBy(experiments, [({ experiment_id }) => experiment_id]);
};
static getExperimentNameMap = (experiments) => {
// Input:
// [
// { experiment_id: 1, name: '/1/bar' },
// { experiment_id: 2, name: '/2/foo' },
// { experiment_id: 3, name: '/3/bar' },
// ]
//
// Output:
// {
// 1: {name: '/1/bar', basename: 'bar (1)'},
// 2: {name: '/2/foo', basename: 'foo'},
// 3: {name: '/3/bar', basename: 'bar (2)'},
// }
const experimentsByBasename = {};
experiments.forEach((experiment) => {
const { name } = experiment;
const basename = name.split('/').pop();
experimentsByBasename[basename] = [...(experimentsByBasename[basename] || []), experiment];
});
const idToNames = {};
Object.entries(experimentsByBasename).forEach(([basename, exps]) => {
const isUnique = exps.length === 1;
exps.forEach(({ experiment_id, name }, index) => {
idToNames[experiment_id] = {
name,
basename: isUnique ? basename : `${basename} (${index + 1})`,
};
});
});
return idToNames;
};
static isModelRegistryEnabled() {
return true;
}
static updatePageTitle(title) {
window.parent.postMessage(
{
// Please keep this type name in sync with PostMessage.js
type: 'UPDATE_TITLE',
title,
},
window.parent.location.origin,
);
}
/**
* Check if current browser tab is the visible tab.
* More info about document.visibilityState:
* https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState
* @returns {boolean}
*/
static isBrowserTabVisible() {
return document.visibilityState !== 'hidden';
}
static shouldRender404(requests, requestIdsToCheck) {
const requestsToCheck = requests.filter((request) => requestIdsToCheck.includes(request.id));
return requestsToCheck.some((request) => {
const { error } = request;
return error && error.getErrorCode() === ErrorCodes.RESOURCE_DOES_NOT_EXIST;
});
}
static compareExperiments(a, b) {
const aId = typeof a.getExperimentId === 'function' ? a.getExperimentId() : a.experiment_id;
const bId = typeof b.getExperimentId === 'function' ? b.getExperimentId() : b.experiment_id;
const aIntId = parseInt(aId, 10);
const bIntId = parseInt(bId, 10);
if (Number.isNaN(aIntId)) {
if (!Number.isNaN(bIntId)) {
// Int IDs before anything else
return 1;
}
} else if (Number.isNaN(bIntId)) {
// Int IDs before anything else
return -1;
} else {
return aIntId - bIntId;
}
return aId.localeCompare(bId);
}
static getSupportPageUrl = () => SupportPageUrl;
static getIframeCorrectedRoute(route) {
if (window.self !== window.top || window.isTestingIframe) {
// If running in an iframe, include the parent params and assume mlflow served at #
const parentHref = window.parent.location.href;
const parentHrefBeforeMlflowHash = parentHref.split('#')[0];
return `${parentHrefBeforeMlflowHash}#mlflow${route}`;
}
return `./#${route}`; // issue-2213 use relative path in case there is a url prefix
}
}
export default Utils;
|
src/Fade.js | HPate-Riptide/react-bootstrap | import classNames from 'classnames';
import React from 'react';
import Transition from 'react-overlays/lib/Transition';
const propTypes = {
/**
* Show the component; triggers the fade in or fade out animation
*/
in: React.PropTypes.bool,
/**
* Unmount the component (remove it from the DOM) when it is faded out
*/
unmountOnExit: React.PropTypes.bool,
/**
* Run the fade in animation when the component mounts, if it is initially
* shown
*/
transitionAppear: React.PropTypes.bool,
/**
* Duration of the fade animation in milliseconds, to ensure that finishing
* callbacks are fired even if the original browser transition end events are
* canceled
*/
timeout: React.PropTypes.number,
/**
* Callback fired before the component fades in
*/
onEnter: React.PropTypes.func,
/**
* Callback fired after the component starts to fade in
*/
onEntering: React.PropTypes.func,
/**
* Callback fired after the has component faded in
*/
onEntered: React.PropTypes.func,
/**
* Callback fired before the component fades out
*/
onExit: React.PropTypes.func,
/**
* Callback fired after the component starts to fade out
*/
onExiting: React.PropTypes.func,
/**
* Callback fired after the component has faded out
*/
onExited: React.PropTypes.func,
};
const defaultProps = {
in: false,
timeout: 300,
unmountOnExit: false,
transitionAppear: false,
};
class Fade extends React.Component {
render() {
return (
<Transition
{...this.props}
className={classNames(this.props.className, 'fade')}
enteredClassName="in"
enteringClassName="in"
/>
);
}
}
Fade.propTypes = propTypes;
Fade.defaultProps = defaultProps;
export default Fade;
|
app/components/myGrid.js | JustinBeckwith/trebuchet | import React from 'react';
import {Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table';
import MyGridRow from './myGridRow';
import * as AppEvents from './../machines/appEvents';
export default class MyGrid extends React.Component {
constructor(props) {
super(props);
this.state = {
apps: [],
selectedRows: [],
}
let manager = this.props.manager;
manager.getApps().then((apps) => {
this.setState({apps: apps});
});
// handle app remove events
manager.on(AppEvents.REMOVED, (app) => {
this.setState({
apps: manager.apps
});
});
// handle app add events
manager.on(AppEvents.APP_CREATED, (app) => {
this.setState({
apps: manager.apps
});
});
// handle app update events
manager.on(AppEvents.APP_UPDATED, (apps) => {
this.setState({
apps: apps,
});
});
/**
* Raise an event for the appBar when selection in the grid changes.
*/
this.onRowSelection = (selectedRows) => {
console.log(selectedRows);
let selectedApps = [];
if (selectedRows === "all") {
selectedApps = this.state.apps;
} else if (selectedRows === "none") {
selectedApps = [];
} else {
for (let idx in selectedRows) {
selectedApps.push(this.state.apps[idx]);
}
}
manager.selectionChanged(selectedApps);
}
// handle the click of the back button on the action bar
manager.on(AppEvents.EXIT_SELECTION, () => {
// There is a bug here. When selected is set to false, for some reason the grid
// isn't respecting this setting. For now, if the user uses 'select all', and then
// click 'back', deselect won't work.
// https://github.com/callemall/material-ui/issues/1897
this.setState({
selectedRows: [],
});
});
}
/**
* This is a terrible hack that prevents the row from being selected unless
* the user clicked on the checkbox column.
*/
onCellClick = (rowNumber, columnNumber, e) => {
if (columnNumber > 0) {
e.preventDefault();
e.stopPropagation();
setTimeout(this.props.manager.exitSelection, 2);
}
}
render() {
let listItems = this.state.apps.map((app) =>
<MyGridRow
app={app}
key={app.name}
manager={this.props.manager} />
);
let displayGrid = listItems.length > 0 ? '' : 'none';
let hideStyle = {
display: 'none',
}
let showStyle = {
display: '',
}
let displayEmpty = listItems.length > 0 ? hideStyle : showStyle;
return (
<div style={{flexGrow: 1, display: 'flex'}}>
<Table
multiSelectable={true}
style={{display: displayGrid}}
onCellClick={this.onCellClick}
onRowSelection={this.onRowSelection}>
<TableHeader>
<TableRow>
<TableHeaderColumn className="iconCol"></TableHeaderColumn>
<TableHeaderColumn className="medCol">Name</TableHeaderColumn>
<TableHeaderColumn className="smallCol">Port</TableHeaderColumn>
<TableHeaderColumn>Path</TableHeaderColumn>
<TableHeaderColumn className="iconCol"></TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody
showRowHover={true}
deselectOnClickaway={false}>
{listItems}
</TableBody>
</Table>
<div style={displayEmpty} className="dragBox">
<div style={{alignSelf: 'center', marginTop: '-100px'}}>
<img src="./images/svg/engine.svg" className="logo" />
Drag a folder into the app, or click the (+) to get started.
</div>
</div>
</div>
);
}
}
|
src/svg-icons/device/gps-off.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceGpsOff = (props) => (
<SvgIcon {...props}>
<path d="M20.94 11c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06c-1.13.12-2.19.46-3.16.97l1.5 1.5C10.16 5.19 11.06 5 12 5c3.87 0 7 3.13 7 7 0 .94-.19 1.84-.52 2.65l1.5 1.5c.5-.96.84-2.02.97-3.15H23v-2h-2.06zM3 4.27l2.04 2.04C3.97 7.62 3.25 9.23 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c1.77-.2 3.38-.91 4.69-1.98L19.73 21 21 19.73 4.27 3 3 4.27zm13.27 13.27C15.09 18.45 13.61 19 12 19c-3.87 0-7-3.13-7-7 0-1.61.55-3.09 1.46-4.27l9.81 9.81z"/>
</SvgIcon>
);
DeviceGpsOff = pure(DeviceGpsOff);
DeviceGpsOff.displayName = 'DeviceGpsOff';
export default DeviceGpsOff;
|
classic/src/scenes/mailboxes/src/Scenes/AppScene/Sidelist/SidelistMailboxes/SidelistItemMailbox/SidelistMultiService.js | wavebox/waveboxapp | import PropTypes from 'prop-types'
import React from 'react'
import { accountStore, accountActions } from 'stores/account'
import shallowCompare from 'react-addons-shallow-compare'
import SidelistMailboxContainer from './SidelistCommon/SidelistMailboxContainer'
import SidelistMailboxTooltip from './SidelistCommon/SidelistMailboxTooltip'
import SidelistServiceTooltip from './SidelistCommon/SidelistServiceTooltip'
import MailboxAndServiceContextMenu from 'Components/MailboxAndServiceContextMenu'
import ErrorBoundary from 'wbui/ErrorBoundary'
import ServiceTabs from 'Components/ServiceTabs'
import ACMailbox from 'shared/Models/ACAccounts/ACMailbox'
import Tappable from 'react-tappable/lib/Tappable'
import SidelistTLMailboxAvatar from './SidelistCommon/SidelistTLMailboxAvatar'
import SidelistTLServiceAvatar from './SidelistCommon/SidelistTLServiceAvatar'
class SidelistItemMultiService extends React.Component {
/* **************************************************************************/
// Class
/* **************************************************************************/
static propTypes = {
mailboxId: PropTypes.string.isRequired,
sidebarSize: PropTypes.string.isRequired,
sortableGetScrollContainer: PropTypes.func.isRequired
}
/* **************************************************************************/
// Component Lifecycle
/* **************************************************************************/
componentDidMount () {
accountStore.listen(this.accountChanged)
this.popoverCustomizeClearTO = null
}
componentWillUnmount () {
accountStore.unlisten(this.accountChanged)
clearTimeout(this.popoverCustomizeClearTO)
}
componentWillReceiveProps (nextProps) {
if (this.props.mailboxId !== nextProps.mailboxId) {
this.setState(this.generateAccountState(nextProps.mailboxId, accountStore.getState()))
}
}
/* **************************************************************************/
// Data lifecycle
/* **************************************************************************/
state = (() => {
return {
isHoveringGroup: false,
popover: false,
popoverAnchor: null,
popoverMailboxId: undefined,
popoverServiceId: undefined,
...this.generateAccountState(this.props.mailboxId, accountStore.getState())
}
})()
accountChanged = (accountState) => {
this.setState(this.generateAccountState(this.props.mailboxId, accountState))
}
/**
* @param mailboxId: the id of the mailbox
* @param accountState: the current account store state
* @return state for this object based on accounts
*/
generateAccountState (mailboxId, accountState) {
const mailbox = accountState.getMailbox(mailboxId)
if (mailbox) {
return {
hasMembers: true,
isMailboxActive: accountState.activeMailboxId() === mailboxId,
prioritizeFirstSidebarService: mailbox.sidebarFirstServicePriority !== ACMailbox.SIDEBAR_FIRST_SERVICE_PRIORITY.NORMAL,
sidebarServicesCount: mailbox.sidebarServices.length,
extraContextServiceId: mailbox.sidebarFirstServicePriority !== ACMailbox.SIDEBAR_FIRST_SERVICE_PRIORITY.NORMAL && mailbox.sidebarServices.length
? mailbox.sidebarServices[0]
: undefined,
renderAsServiceId: mailbox.sidebarFirstServicePriority === ACMailbox.SIDEBAR_FIRST_SERVICE_PRIORITY.PRIMARY && mailbox.sidebarServices.length
? mailbox.sidebarServices[0]
: undefined
}
} else {
return {
hasMembers: false
}
}
}
/* **************************************************************************/
// User Interaction
/* **************************************************************************/
/**
* Handles the item being clicked on
* @param evt: the event that fired
*/
handleClick = (evt) => {
const { mailboxId } = this.props
const { prioritizeFirstSidebarService, sidebarServicesCount } = this.state
if (evt.metaKey) {
window.location.hash = `/settings/accounts/${mailboxId}`
} else {
if (prioritizeFirstSidebarService && sidebarServicesCount) {
accountActions.changeActiveMailbox(mailboxId, true)
} else {
accountActions.changeActiveMailbox(mailboxId)
}
}
}
/**
* Handles the item being long clicked on
* @param evt: the event that fired
*/
handleLongClick = (evt) => {
accountActions.changeActiveMailbox(this.props.mailboxId, true)
}
/**
* Handles a service being clicked
* @param evt: the event that fired
* @param serviceId: the id of the service
*/
handleClickService = (evt, serviceId) => {
evt.preventDefault()
accountActions.changeActiveService(serviceId)
}
/**
* Opens the popover
* @param evt: the event that fired
*/
handleOpenMailboxPopover = (evt) => {
evt.preventDefault()
evt.stopPropagation()
clearTimeout(this.popoverCustomizeClearTO)
this.setState({
isHoveringGroup: false,
popover: true,
popoverMailboxId: this.props.mailboxId,
popoverServiceId: undefined,
popoverAnchor: evt.currentTarget
})
}
/**
* Opens the popover for a prioritized service
* @param evt: the event that fired
*/
handleOpenPrioritizedServicePopover = (evt) => {
this.handleOpenServicePopover(evt, this.state.extraContextServiceId)
}
/**
* Opens the popover for a service
* @param evt: the event that fired
* @param serviceId: the id of the service to open for
*/
handleOpenServicePopover = (evt, serviceId) => {
evt.preventDefault()
evt.stopPropagation()
clearTimeout(this.popoverCustomizeClearTO)
this.setState({
isHoveringGroup: false,
popover: true,
popoverMailboxId: this.props.mailboxId,
popoverServiceId: serviceId,
popoverAnchor: evt.currentTarget
})
}
handleClosePopover = () => {
clearTimeout(this.popoverCustomizeClearTO)
this.popoverCustomizeClearTO = setTimeout(() => {
this.setState({
popoverMailboxId: undefined,
popoverServiceId: undefined
})
}, 500)
this.setState({ popover: false })
}
/* **************************************************************************/
// Rendering
/* **************************************************************************/
shouldComponentUpdate (nextProps, nextState) {
return shallowCompare(this, nextProps, nextState)
}
render () {
const {
mailboxId,
sidebarSize,
sortableGetScrollContainer,
...passProps
} = this.props
const {
isHoveringGroup,
popover,
popoverAnchor,
popoverMailboxId,
popoverServiceId,
hasMembers,
renderAsServiceId,
extraContextServiceId,
isMailboxActive
} = this.state
if (!hasMembers) { return false }
const TooltipClass = extraContextServiceId
? SidelistServiceTooltip
: SidelistMailboxTooltip
const tooltipProps = extraContextServiceId
? { mailboxId: mailboxId, serviceId: extraContextServiceId }
: { mailboxId: mailboxId }
return (
<SidelistMailboxContainer
onMouseEnter={() => this.setState({ isHoveringGroup: true })}
onMouseLeave={() => this.setState({ isHoveringGroup: false })}
{...passProps}>
<TooltipClass {...tooltipProps}>
<Tappable
onClick={this.handleClick}
onPress={this.handleLongClick}
onContextMenu={(extraContextServiceId
? this.handleOpenPrioritizedServicePopover
: this.handleOpenMailboxPopover
)}>
{renderAsServiceId ? (
<SidelistTLServiceAvatar
mailboxId={mailboxId}
serviceId={renderAsServiceId}
sidebarSize={sidebarSize}
isTransientActive={isHoveringGroup}
forceIndicator={isMailboxActive} />
) : (
<SidelistTLMailboxAvatar
mailboxId={mailboxId}
sidebarSize={sidebarSize}
isTransientActive={isHoveringGroup}
forceIndicator={isMailboxActive} />
)}
</Tappable>
</TooltipClass>
<ServiceTabs
mailboxId={mailboxId}
uiLocation={ACMailbox.SERVICE_UI_LOCATIONS.SIDEBAR}
sidebarSize={sidebarSize}
onOpenService={this.handleClickService}
sortableGetScrollContainer={sortableGetScrollContainer}
onContextMenuService={this.handleOpenServicePopover} />
{popoverMailboxId || popoverServiceId ? (
<ErrorBoundary>
<MailboxAndServiceContextMenu
mailboxId={popoverMailboxId}
serviceId={popoverServiceId}
isOpen={popover}
anchor={popoverAnchor}
onRequestClose={this.handleClosePopover} />
</ErrorBoundary>
) : undefined}
</SidelistMailboxContainer>
)
}
}
export default SidelistItemMultiService
|
src/components/options/OptionsText2x.js | m0sk1t/react_email_editor | import React from 'react';
const OptionsText2x = ({ block, language, onPropChange }) => {
const fontSize = block.options.container.fontSize.match(/\d+/)?block.options.container.fontSize.match(/\d+/)[0]: '16';
return (
<div>
<div>
<label>{language["Custom style"]}: <input type="checkbox" checked={block.options.container.customStyle? 'checked': '' } onChange={(e) => onPropChange('customStyle', !block.options.container.customStyle, true)} /></label>
</div>
<hr />
<div>
<label>{language["Color"]}: <input type="color" value={block.options.container.color} onChange={(e) => onPropChange('color', e.target.value, true)} /></label>
</div>
<div>
<label>{language["Background"]}: <input type="color" value={block.options.container.backgroundColor} onChange={(e) => onPropChange('backgroundColor', e.target.value, true)} /></label>
</div>
<div>
<label>{language["Font size"]}: <input type="number" value={fontSize} onChange={(e) => onPropChange('fontSize', `${e.target.value}px`, true)} /></label>
</div>
<div>
<label>
{language["Font family"]}:
<select style={{width: '50%'}} onChange={(e) => onPropChange('fontFamily', e.target.value, true)}>
<option value="Georgia, serif">Georgia, serif</option>
<option value="Tahoma, Geneva, sans-serif">Tahoma, Geneva, sans-serif</option>
<option value="Verdana, Geneva, sans-serif">Verdana, Geneva, sans-serif</option>
<option value="Arial, Helvetica, sans-serif">Arial, Helvetica, sans-serif</option>
<option value="Impact, Charcoal, sans-serif">Impact, Charcoal, sans-serif</option>
<option value="'Times New Roman', Times, serif">"Times New Roman", Times, serif</option>
<option value="'Courier New', Courier, monospace">"Courier New", Courier, monospace</option>
<option value="'Arial Black', Gadget, sans-serif">"Arial Black", Gadget, sans-serif</option>
<option value="'Lucida Console', Monaco, monospace">"Lucida Console", Monaco, monospace</option>
<option value="'Comic Sans MS', cursive, sans-serif">"Comic Sans MS", cursive, sans-serif</option>
<option value="'Trebuchet MS', Helvetica, sans-serif">"Trebuchet MS", Helvetica, sans-serif</option>
<option value="'Lucida Sans Unicode', 'Lucida Grande', sans-serif">"Lucida Sans Unicode", "Lucida Grande", sans-serif</option>
<option value="'Palatino Linotype', 'Book Antiqua', Palatino, serif">"Palatino Linotype", "Book Antiqua", Palatino, serif</option>
</select>
</label>
</div>
<div>
<label>{language["Align"]} {language["Text"]} 1:
<input type="range" min="0" max="3" step="1" value={block.options.elements[0].textSize} onChange={(e) => {
switch (+e.target.value) {
case 0:
onPropChange('width', '50', false, 0);
onPropChange('width', '500', false, 1);
break;
case 1:
onPropChange('width', '100', false, 0);
onPropChange('width', '450', false, 1);
break;
case 2:
onPropChange('width', '200', false, 0);
onPropChange('width', '350', false, 1);
break;
case 3:
onPropChange('width', '275', false, 0);
onPropChange('width', '275', false, 1);
break;
default:
break;
}
onPropChange('textSize', e.target.value, false, 0);
}} />
</label>
</div>
</div>
);
};
export default OptionsText2x;
|
src/svg-icons/hardware/phonelink-off.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwarePhonelinkOff = (props) => (
<SvgIcon {...props}>
<path d="M22 6V4H6.82l2 2H22zM1.92 1.65L.65 2.92l1.82 1.82C2.18 5.08 2 5.52 2 6v11H0v3h17.73l2.35 2.35 1.27-1.27L3.89 3.62 1.92 1.65zM4 6.27L14.73 17H4V6.27zM23 8h-6c-.55 0-1 .45-1 1v4.18l2 2V10h4v7h-2.18l3 3H23c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1z"/>
</SvgIcon>
);
HardwarePhonelinkOff = pure(HardwarePhonelinkOff);
HardwarePhonelinkOff.displayName = 'HardwarePhonelinkOff';
HardwarePhonelinkOff.muiName = 'SvgIcon';
export default HardwarePhonelinkOff;
|
app/src/components/Artists.js | Rhadammanthis/BreadScraps | import React, { Component } from 'react';
import { ScrollView, Text, Button, Linking, TextInput, View } from 'react-native';
import { connect } from 'react-redux';
import { artistChanged, artistSelected, searchArtist } from '../actions';
import { Actions } from 'react-native-router-flux';
import { Card, CardSection, Input, Spinner } from './common';
import ArtistDetail from './ArtistDetail';
class Artists extends Component {
// state = { searchResults: null };
componentWillMount() {
}
onEmailChange(text) {
this.props.codeChanged(text);
}
onArtistNameChanged(text) {
this.props.artistChanged(text);
}
onArtistSelected(artist) {
this.props.artistSelected(artist)
}
onSearchPress() {
this.props.searchArtist(this.props.artistText)
}
onFinishedTyping() {
this.props.searchArtist(this.props.artistText)
}
renderArtists() {
if (this.props.searchResults !== null) {
return this.props.searchResults.artists.items.map(artist =>
<ArtistDetail key={artist.id} artist={artist} artistSelected={this.props.artistSelected}/>
);
}
}
renderSelectedArtists() {
if(this.props.artists.length > 0){
var selectedArtists = this.props.artists.map(artist => artist.name + ', ')
return(
<Text style={{ fontSize: 15, color: 'white', flex: 1 }}>
{selectedArtists}
</Text>
)
}
}
render() {
const { searchContainerStyle, inputStyle, artistsTextStyle } = styles;
console.log('Selected srtists', this.props.artists)
if(this.props.artists.length === 3)
Actions.songs();
return (
<View style={{
flexDirection: 'column',
justifyContent: 'center'
}}>
<View style={{ flexDirection: 'row' }}>
{this.renderSelectedArtists()}
<Text style={ artistsTextStyle }>
{this.props.artists.length}
</Text>
</View>
<View style={searchContainerStyle}>
<TextInput
style={inputStyle}
onChangeText={this.onArtistNameChanged.bind(this)}
value={this.props.artistText}
onSubmitEditing={this.onFinishedTyping.bind(this)}
/>
<View style={{ flex: 1, flexDirection: 'column', justifyContent: 'center' }}>
<Button
onPress={this.onSearchPress.bind(this)}
title="Search artist"
accessibilityLabel="See an informative alert"
color="#FF7F00"
style={{ height: 40, marginRight: 10 }}
/>
</View>
</View>
<ScrollView style={{ marginBottom: 50 }}>
{this.renderArtists()}
</ScrollView>
</View>
);
}
}
const styles = {
searchContainerStyle: {
flexDirection: 'row',
justifyContent: 'space-around',
marginRight: 10
},
inputStyle: {
height: 40,
flex: 1,
backgroundColor: 'white',
borderRadius: 10,
margin: 15
},
artistsTextStyle: {
color: 'white',
fontSize: 30
}
}
const mapStateToProps = ({ artist }) => {
const { artistText, artists, searchResults } = artist;
return {
artistText, artists, searchResults
};
};
export default connect(mapStateToProps, { artistChanged, artistSelected, searchArtist })(Artists); |
src/encoded/static/components/item-pages/components/HiGlass/HiGlassAjaxLoadContainer.js | 4dn-dcic/fourfront | 'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import _ from 'underscore';
import memoize from 'memoize-one';
import { console, object, ajax } from '@hms-dbmi-bgm/shared-portal-components/es/components/util';
import { HiGlassPlainContainer, HiGlassLoadingIndicator } from './HiGlassPlainContainer';
/**
* Accepts `higlassItem` (HiglassViewConfig Item JSON) as a prop and loads in the full
* representation from `higlassItem.@id` if `higlassItem.viewconfig` is not present before
* instantiating a HiGlassPlainContainer.
*/
export class HiGlassAjaxLoadContainer extends React.PureComponent {
static propTypes = {
'higlassItem': PropTypes.object,
'scale1dTopTrack': PropTypes.bool.isRequired,
'height': PropTypes.number
}
static defaultProps = {
'scale1dTopTrack': true
}
constructor(props){
super(props);
this.getFullHiglassItem = this.getFullHiglassItem.bind(this);
this.state = {
'loading': false,
'higlassItem' : (props.higlassItem && props.higlassItem.viewconfig) ? props.higlassItem : null
};
this.containerRef = React.createRef();
}
componentDidMount(){
if (!this.state.higlassItem) {
this.getFullHiglassItem();
}
}
componentDidUpdate(pastProps){
// After updating the component, load the new higlass component if it changed.
if (pastProps.higlassItem !== this.props.higlassItem){
if (this.props.higlassItem.viewconfig){
this.setState({ 'higlassItem' : this.props.higlassItem });
} else {
this.getFullHiglassItem();
}
}
}
/**
* Retrieve the HiGlass Component, if it exists.
*
* @returns {object} The result of getHiGlassComponent on the HiGlass container. Or null if it doesn't exist.
*/
getHiGlassComponent(){
return (this.containerRef && this.containerRef.current && this.containerRef.current.getHiGlassComponent()) || null;
}
/**
* Makes an AJAX call to get the Higlass viewconfig resource.
*/
getFullHiglassItem(){
var { higlassItem } = this.props;
// Use the @id to make an AJAX request to get the HiGlass Item.
this.setState({ 'loading': true }, ()=>{
// Use the @id to get the item, then remove the loading message
ajax.load(object.itemUtil.atId(higlassItem), (r)=>{
this.setState({ 'higlassItem' : r,'loading': false });
});
});
}
render(){
const { higlassItem, loading } = this.state;
let { height } = this.props;
//if height not defined by container then use instance defined value
if (!height && higlassItem && higlassItem.instance_height && higlassItem.instance_height > 0) {
height = higlassItem.instance_height;
}
// Use the height to make placeholder message when loading.
var placeholderStyle = { "height" : height || 600 };
if (placeholderStyle.height >= 140) {
placeholderStyle.paddingTop = (placeholderStyle.height / 2) - 40;
}
// If we're loading, show a loading screen
if (loading){
return <div className="text-center" style={placeholderStyle}><HiGlassLoadingIndicator title="Loading" /></div>;
}
// Raise an error if there is no viewconfig
if (!higlassItem || !higlassItem.viewconfig) {
return (
<div className="text-center" style={placeholderStyle}>
<HiGlassLoadingIndicator icon="exclamation-triangle" title="No HiGlass content found. Please go back or try again later." />
</div>
);
}
return <HiGlassPlainContainer {..._.omit(this.props, 'higlassItem', 'height')} viewConfig={higlassItem.viewconfig} ref={this.containerRef} height={height} />;
}
}
|
Js/Ui/Components/Filters/DateTime.js | Webiny/Webiny | import React from 'react';
import Webiny from 'webiny';
class DateTime extends Webiny.Ui.Component {
}
DateTime.defaultProps = {
format: null,
default: '-',
value: null,
renderer() {
try {
return <span>{Webiny.I18n.datetime(this.props.value, this.props.format)}</span>;
} catch (e) {
return this.props.default;
}
}
};
export default Webiny.createComponent(DateTime); |
pkg/interface/chat/src/js/components/lib/chat-input.js | jfranklin9000/urbit | import React, { Component } from 'react';
import _ from 'lodash';
import moment from 'moment';
import { UnControlled as CodeEditor } from 'react-codemirror2';
import CodeMirror from 'codemirror';
import 'codemirror/mode/markdown/markdown';
import 'codemirror/addon/display/placeholder';
import { Sigil } from '/components/lib/icons/sigil';
import { ShipSearch } from '/components/lib/ship-search';
import { S3Upload } from '/components/lib/s3-upload';
import { uxToHex } from '/lib/util';
const MARKDOWN_CONFIG = {
name: 'markdown',
tokenTypeOverrides: {
header: 'presentation',
quote: 'presentation',
list1: 'presentation',
list2: 'presentation',
list3: 'presentation',
hr: 'presentation',
image: 'presentation',
imageAltText: 'presentation',
imageMarker: 'presentation',
formatting: 'presentation',
linkInline: 'presentation',
linkEmail: 'presentation',
linkText: 'presentation',
linkHref: 'presentation'
}
};
export class ChatInput extends Component {
constructor(props) {
super(props);
this.state = {
message: '',
patpSearch: null
};
this.textareaRef = React.createRef();
this.messageSubmit = this.messageSubmit.bind(this);
this.messageChange = this.messageChange.bind(this);
this.patpAutocomplete = this.patpAutocomplete.bind(this);
this.completePatp = this.completePatp.bind(this);
this.clearSearch = this.clearSearch.bind(this);
this.toggleCode = this.toggleCode.bind(this);
this.editor = null;
// perf testing:
/* let closure = () => {
let x = 0;
for (var i = 0; i < 30; i++) {
x++;
props.api.chat.message(
props.station,
`~${window.ship}`,
Date.now(),
{
text: `${x}`
}
);
}
setTimeout(closure, 1000);
};
this.closure = closure.bind(this);*/
moment.updateLocale('en', {
relativeTime : {
past: function(input) {
return input === 'just now'
? input
: input + ' ago';
},
s : 'just now',
future: 'in %s',
ss : '%d sec',
m: 'a minute',
mm: '%d min',
h: 'an hr',
hh: '%d hrs',
d: 'a day',
dd: '%d days',
M: 'a month',
MM: '%d months',
y: 'a year',
yy: '%d years'
}
});
}
nextAutocompleteSuggestion(backward = false) {
const { patpSuggestions } = this.state;
let idx = patpSuggestions.findIndex(s => s === this.state.selectedSuggestion);
idx = backward ? idx - 1 : idx + 1;
idx = idx % patpSuggestions.length;
if(idx < 0) {
idx = patpSuggestions.length - 1;
}
this.setState({ selectedSuggestion: patpSuggestions[idx] });
}
patpAutocomplete(message) {
const match = /~([a-zA-Z\-]*)$/.exec(message);
if (!match ) {
this.setState({ patpSearch: null });
return;
}
this.setState({ patpSearch: match[1].toLowerCase() });
}
clearSearch() {
this.setState({
patpSearch: null
});
}
completePatp(suggestion) {
if(!this.editor) {
return;
}
const newMessage = this.editor.getValue().replace(
/[a-zA-Z\-]*$/,
suggestion
);
this.editor.setValue(newMessage);
const lastRow = this.editor.lastLine();
const lastCol = this.editor.getLineHandle(lastRow).text.length;
this.editor.setCursor(lastRow, lastCol);
this.setState({
patpSearch: null
});
}
messageChange(editor, data, value) {
const { patpSearch } = this.state;
if(patpSearch !== null) {
this.patpAutocomplete(value, false);
}
}
getLetterType(letter) {
if (letter.startsWith('/me ')) {
letter = letter.slice(4);
// remove insignificant leading whitespace.
// aces might be relevant to style.
while (letter[0] === '\n') {
letter = letter.slice(1);
}
return {
me: letter
};
} else if (this.isUrl(letter)) {
return {
url: letter
};
} else {
return {
text: letter
};
}
}
isUrl(string) {
try {
const websiteTest = new RegExp(String(/^((\w+:\/\/)[-a-zA-Z0-9:@;?&=\/%\+\.\*!'\(\),\$_\{\}\^~\[\]`#|]+)/.source)
);
return websiteTest.test(string);
} catch (e) {
return false;
}
}
messageSubmit() {
if(!this.editor) {
return;
}
const { props, state } = this;
const editorMessage = this.editor.getValue();
if (editorMessage === '') {
return;
}
props.onEnter();
if(state.code) {
props.api.chat.message(props.station, `~${window.ship}`, Date.now(), {
code: {
expression: editorMessage,
output: undefined
}
});
this.editor.setValue('');
return;
}
let message = [];
editorMessage.split(' ').map((each) => {
if (this.isUrl(each)) {
if (message.length > 0) {
message = message.join(' ');
message = this.getLetterType(message);
props.api.chat.message(
props.station,
`~${window.ship}`,
Date.now(),
message
);
message = [];
}
const URL = this.getLetterType(each);
props.api.chat.message(
props.station,
`~${window.ship}`,
Date.now(),
URL
);
} else {
return message.push(each);
}
});
if (message.length > 0) {
message = message.join(' ');
message = this.getLetterType(message);
props.api.chat.message(
props.station,
`~${window.ship}`,
Date.now(),
message
);
message = [];
}
// perf:
// setTimeout(this.closure, 2000);
this.editor.setValue('');
}
toggleCode() {
if(this.state.code) {
this.setState({ code: false });
this.editor.setOption('mode', MARKDOWN_CONFIG);
this.editor.setOption('placeholder', this.props.placeholder);
} else {
this.setState({ code: true });
this.editor.setOption('mode', null);
this.editor.setOption('placeholder', 'Code...');
}
const value = this.editor.getValue();
// Force redraw of placeholder
if(value.length === 0) {
this.editor.setValue(' ');
this.editor.setValue('');
}
}
uploadSuccess(url) {
const { props } = this;
props.api.chat.message(
props.station,
`~${window.ship}`,
Date.now(),
{ url }
);
}
uploadError(error) {
// no-op for now
}
render() {
const { props, state } = this;
const color = props.ownerContact
? uxToHex(props.ownerContact.color) : '000000';
const sigilClass = props.ownerContact
? '' : 'mix-blend-diff';
const img = (props.ownerContact && (props.ownerContact.avatar !== null))
? <img src={props.ownerContact.avatar} height={24} width={24} className="dib" />
: <Sigil
ship={window.ship}
size={24}
color={`#${color}`}
classes={sigilClass}
/>;
const candidates = _.chain(this.props.envelopes)
.defaultTo([])
.map('author')
.uniq()
.reverse()
.value();
const codeTheme = state.code ? ' code' : '';
const options = {
mode: MARKDOWN_CONFIG,
theme: 'tlon' + codeTheme,
lineNumbers: false,
lineWrapping: true,
scrollbarStyle: 'native',
cursorHeight: 0.85,
placeholder: state.code ? 'Code...' : props.placeholder,
extraKeys: {
Tab: cm =>
this.patpAutocomplete(cm.getValue(), true),
'Enter': () => {
this.messageSubmit();
if (this.state.code) {
this.toggleCode();
}
},
'Shift-3': cm =>
cm.getValue().length === 0
? this.toggleCode()
: CodeMirror.Pass
}
};
return (
<div className="pa3 cf flex black white-d bt b--gray4 b--gray1-d bg-white bg-gray0-d relative"
style={{ flexGrow: 1 }}
>
<ShipSearch
popover
onSelect={this.completePatp}
onClear={this.clearSearch}
contacts={props.contacts}
candidates={candidates}
searchTerm={this.state.patpSearch}
cm={this.editor}
/>
<div
className="fl"
style={{
marginTop: 6,
flexBasis: 24,
height: 24
}}
>
{img}
</div>
<div
className="fr h-100 flex bg-gray0-d lh-copy pl2 w-100 items-center"
style={{ flexGrow: 1, maxHeight: '224px', width: 'calc(100% - 72px)' }}
>
<CodeEditor
options={options}
editorDidMount={(editor) => {
this.editor = editor;
if (!/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(
navigator.userAgent
)) {
editor.focus();
}
}}
onChange={(e, d, v) => this.messageChange(e, d, v)}
/>
</div>
<div className="ml2 mr2"
style={{ height: '16px', width: '16px', flexBasis: 16, marginTop: 10 }}>
<S3Upload
configuration={props.s3.configuration}
credentials={props.s3.credentials}
uploadSuccess={this.uploadSuccess.bind(this)}
uploadError={this.uploadError.bind(this)}
/>
</div>
<div style={{ height: '16px', width: '16px', flexBasis: 16, marginTop: 10 }}>
<img
style={{ filter: state.code && 'invert(100%)', height: '100%', width: '100%' }}
onClick={this.toggleCode}
src="/~chat/img/CodeEval.png"
className="contrast-10-d bg-white bg-none-d ba b--gray1-d br1"
/>
</div>
</div>
);
}
}
|
packages/logos/src/redis.js | geek/joyent-portal | import React from 'react';
export default props => (
<svg
id="svg4300"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 42 42"
{...props}
>
<defs>
<style
dangerouslySetInnerHTML={{
__html:
'.cls-1,.cls-2{fill:#fff}.cls-1{opacity:.25;isolation:isolate}.cls-3{fill:#333}'
}}
/>
</defs>
<title>Artboard 1 copy 20</title>
<path
fill="#1B3240"
d="M37.57 23.65c-1.9-.7-11.8-4.6-13.7-5.3s-2.7-.7-4.9.1-12.8 4.9-14.6 5.7c-.9.4-1.4.7-1.4 1.1H3v3.6c0 .4.5.7 1.5 1.2 1.9.9 12.5 5.2 14.2 6s2.9.8 5-.3 12.1-5.2 14-6.2c1-.5 1.4-.9 1.4-1.3v-3.6c-.1-.4-.53-.65-1.53-1z"
/>
<path
className="cls-1"
d="M37.57 25.85c-1.9 1-11.9 5.1-14 6.2s-3.3 1.1-5 .3-12.3-5.1-14.2-6-1.9-1.5-.1-2.3 12.4-4.9 14.6-5.7 3-.8 4.9-.1 11.8 4.6 13.7 5.3 2 1.3.1 2.3z"
/>
<path
fill="#1B3240"
d="M37.57 17.75c-1.9-.7-11.8-4.6-13.7-5.3s-2.7-.7-4.9.1-12.8 4.9-14.6 5.7c-.9.4-1.4.7-1.4 1.1H3V23c0 .4.5.7 1.5 1.2 1.9.9 12.5 5.2 14.2 6s2.9.8 5-.3 12.1-5.2 14-6.2c1-.5 1.4-.9 1.4-1.3v-3.6c-.1-.35-.53-.75-1.53-1.05z"
/>
<path
className="cls-1"
d="M37.57 20c-1.9 1-11.9 5.1-14 6.2s-3.3 1.1-5 .3-12.3-5.1-14.2-6-1.9-1.5-.1-2.3 12.4-4.9 14.6-5.7 3-.8 4.9-.1 11.8 4.6 13.7 5.3 2 1.3.1 2.3z"
/>
<path
fill="#1B3240"
d="M37.57 11.55c-1.9-.7-11.8-4.6-13.7-5.3s-2.7-.7-4.9.1-12.8 4.9-14.6 5.7c-.9.4-1.4.7-1.4 1.1H3v3.6c0 .4.5.7 1.5 1.2 1.9.9 12.5 5.2 14.2 6s2.9.8 5-.3 12.1-5.2 14-6.2c1-.5 1.4-.9 1.4-1.3v-3.6c-.1-.3-.53-.7-1.53-1z"
/>
<path
className="cls-1"
d="M37.57 13.75c-1.9 1-11.9 5.1-14 6.2s-3.3 1.1-5 .3-12.3-5.1-14.2-6-1.9-1.5-.1-2.3 12.4-4.9 14.6-5.7 3-.8 4.9-.1 11.8 4.6 13.7 5.3 2 1.3.1 2.3z"
/>
<path
className="cls-2"
d="M25.77 10.25l-3.2.4-.7 1.6-1.1-1.8-3.6-.4 2.7-.9-.8-1.5 2.5 1 2.4-.8-.7 1.5 2.5.9zm-4.1 8.2l-5.8-2.4 8.4-1.3-2.6 3.7z"
/>
<ellipse className="cls-2" cx="13.67" cy="12.95" rx="4.5" ry="1.7" />
<path fill="#1B3240" d="M29.37 10.75l5 1.9-5 2v-3.9z" />
<path className="cls-3" d="M23.97 12.95l5.4-2.2v3.9l-.5.2-4.9-1.9z" />
</svg>
);
|
src/components/SignupPage/SignupForm.js | arimaulana/rest-api-frontend-in-react | import React, { Component } from 'react';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import PropTypes from 'prop-types';
// import { Link } from 'react-router-dom';
const styleForm = {
display: 'flex',
flexDirection: 'column',
alignItems: 'center'
};
class SignupForm extends Component {
constructor(props) {
super(props);
this.state = {
first_name: '',
last_name: '',
username: '',
email: '',
password: '',
con_pass: '',
errors: {},
isLoading: false
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
onSubmit(e) {
e.preventDefault();
this.setState({ errors: {}, isLoading: true });
this.props.userSignupRequest(this.state).then(
() => {
setTimeout(
this.props.addFlashMessage({
type: 'success',
text: 'You signed up successfully. Welcome!'
}),
2000
);
this.props.history.push('/');
},
err => this.setState({ errors: err.response.data, isLoading: false })
);
}
render() {
const { errors } = this.state;
return (
<form onSubmit={this.onSubmit}>
<div className="flex-item" style={styleForm}>
<h2>Sign Up</h2>
<TextField
name="first_name"
value={this.state.first_name}
onChange={this.onChange}
hintText="First Name"
errorText={errors.first_name}
floatingLabelText="First Name"
/>
<TextField
name="last_name"
value={this.state.last_name}
onChange={this.onChange}
hintText="Last Name"
errorText={errors.last_name}
floatingLabelText="Last Name"
/>
<TextField
name="username"
value={this.state.username}
onChange={this.onChange}
hintText="Username"
errorText={errors.username}
floatingLabelText="Username"
/>
<TextField
name="email"
value={this.state.email}
onChange={this.onChange}
hintText="Email"
errorText={errors.email}
floatingLabelText="Email"
type="email"
/>
<TextField
name="password"
value={this.state.password}
onChange={this.onChange}
hintText="Password"
errorText={errors.password}
floatingLabelText="Password"
type="password"
/>
<TextField
name="con_pass"
value={this.state.con_pass}
onChange={this.onChange}
hintText="Confirm Password"
errorText={errors.con_pass}
floatingLabelText="Confirm Password"
type="password"
/>
<br />
<RaisedButton
disabled={this.state.isLoading}
label="Sign Up"
type="sumbit"
primary
/>
</div>
</form>
);
}
}
SignupForm.propTypes = {
userSignupRequest: PropTypes.func.isRequired,
addFlashMessage: PropTypes.func.isRequired,
history: PropTypes.object.isRequired // eslint-disable-line react/forbid-prop-types
};
export default SignupForm;
|
src/components/LoginPlease.js | MouseZero/voting-app | import React from 'react';
import SmallerContainer from './SmallerContainer';
function LoginPlease(){
return(
<SmallerContainer>
<h1>Please Login</h1>
Please login to view this page.
</SmallerContainer>
);
}
export default LoginPlease;
|
source/components/Tab.js | TroyAlford/axis-wiki | import React from 'react'
import Icon from '@components/Icon'
import noop from '@utils/noop'
const Tab = ({ caption = '', children, icon = '', onClick = noop, onRemoveClick = noop, removable = false }) => (
<div className="tab" onClick={onClick}>
{icon && <Icon name={icon} />}
{caption && <div className="caption">{caption}</div>}
{removable && <Icon name="remove is-small" onClick={onRemoveClick} />}
{children}
</div>
)
Tab.displayName = 'Tab'
export default Tab
|
frontend/components/user/avatar.js | apostolidhs/wiregoose | import React from 'react';
import PropTypes from 'prop-types';
import FontAwesome from 'react-fontawesome';
import CSSModules from 'react-css-modules';
import classnames from 'classnames';
import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger';
import Tooltip from 'react-bootstrap/lib/Tooltip';
import tr from '../localization/localization.js';
import * as Events from '../events/events.js';
import * as Auth from '../authorization/auth.js';
import styles from './user.less';
@CSSModules(styles, {
allowMultiple: true,
})
class Avatar extends React.Component {
static propTypes = {
type: PropTypes.oneOf(['HEADER', 'HEADER_DROPDOWN', 'PROFILE']),
isUser: PropTypes.bool
}
static defaultProps = {
type: 'HEADER_DROPDOWN',
isUser: false
}
componentWillMount() {
this.updateAvatarClass();
}
updateAvatarClass() {
switch(this.props.type) {
case 'HEADER':
return this.setState({avatarClass: 'header'});
case 'HEADER_DROPDOWN':
return this.setState({avatarClass: 'header-dropdown'});
case 'PROFILE':
default:
this.setState({avatarClass: 'profile'});
}
}
isUserEmailVerified() {
return Auth.isAuthenticated() && Auth.isEmailValid();
}
renderAvatar(isEmailValid) {
const {avatarClass} = this.state;
const className = classnames(
'avatar',
`avatar-${avatarClass}`,
{'avatar-invalid': !isEmailValid}
);
return (
<FontAwesome
styleName={className}
name="user-circle"
/>
);
}
render() {
if (this.isUserEmailVerified()) {
return this.renderAvatar(true);
}
return (
<OverlayTrigger placement="bottom" overlay={
<Tooltip id="validate-user-account">{tr.validateUserAccount}</Tooltip>
}>
{this.renderAvatar(false)}
</OverlayTrigger>
);
}
}
export default Events.EventHOC(Avatar, ['credentials']);
|
src/components/editor/textEditor.js | eveafeline/D3-ID3-Naomi | import React, { Component } from 'react';
import { ipcRenderer } from 'electron';
const d3parser = require('../../d3-parser/d3parser');
const path = require('path');
const fs = require('fs');
var editor;
class TextEditor extends Component {
constructor(props) {
super();
this.state = {
url: path.resolve(__dirname, 'src/components/temp/temp.html'),
}
}
componentDidMount() {
let amdRequire = global.require('monaco-editor/min/vs/loader.js').require;
function uriFromPath(_path) {
let pathName = path.resolve(_path).replace(/\\/g, '/');
if (pathName.length > 0 && pathName.charAt(0) !== '/') {
pathName = '/' + pathName;
}
return encodeURI('file://' + pathName);
}
// uriFromPath needs to take in a path including the main folder
// __dirname doesn't reach ID3-React
amdRequire.config({
baseUrl: uriFromPath(path.resolve(__dirname, 'node_modules/monaco-editor/min/'))
});
// workaround monaco-css not understanding the environment
self.module = undefined;
// workaround monaco-typescript not understanding the environment
self.process.browser = true;
amdRequire(['vs/editor/editor.main'], () => {
editor = monaco.editor.create(document.getElementById('editor'), {
value: [
'//code here'
].join('\n'),
language: 'html',
theme: "vs-dark",
wrappingColumn: 0,
scrollBeyondLastLine: false,
wrappingIndent: "indent",
});
window.onresize = () => {
editor.layout();
}
let editorView = document.getElementById('editor-container');
let webview = document.getElementById('webview-container');
ipcRenderer.on('updateMain', (event, arg) => {
let newEditorString = fs.readFileSync(path.resolve(__dirname, 'src/components/temp/temp.html'), 'utf8');
//console.log(newEditorString);
editor.setValue(newEditorString);
document.querySelector('webview').reload();
let string = JSON.stringify(d3parser.parseD3(newEditorString), null, '\t');
fs.writeFileSync('./src/d3ParserObj.js', string);
ipcRenderer.send('updateAttr');
});
ipcRenderer.on('resize', (event, arg) => {
editorView.style.height = 'calc(50% - 4px)';
webview.style.height = 'calc(50% - 4px)';
});
ipcRenderer.on('openEditor', (event) => {
editorView.style.height = 'calc(100% - 8px)';
});
ipcRenderer.on('openWebView', (event) => {
webview.style.height = 'calc(100% - 8px)';
});
// import files into text-editor
let importBtn = document.getElementById('import-btn');
let fileUpLoadBtn = document.getElementById('upload-file');
fileUpLoadBtn.setAttribute("accept", ".html,.csv,.tsv,.js,.txt");
function openFile() {
fileUpLoadBtn.click();
}
// d3 parse on upload
fileUpLoadBtn.addEventListener('change', (event) => {
const file = event.target.files[0];
const reader = new FileReader();
var currPath = document.getElementById('currPath');
currPath.innerHTML = file.path;
console.log(file.path)
reader.onload = function (event) {
fs.writeFileSync(path.resolve(__dirname, 'src/components/temp/temp.html'), event.target.result);
let string = JSON.stringify(d3parser.parseD3(event.target.result), null, '\t');
fs.writeFileSync('./src/d3ParserObj.js', string);
editor.setValue(event.target.result);
document.querySelector('webview').reload();
ipcRenderer.send('fileUpload', event.target.result);
};
reader.readAsText(file);
})
importBtn.addEventListener('click', (event) => {
openFile();
});
// export to html
const exportBtn = document.getElementById('export-btn');
exportBtn.addEventListener("click", (e) => {
let d3string = fs.readFileSync('./src/d3ParserObj.js');
let htmlString = d3parser.reCode(JSON.parse(d3string));
const htmlFile = new Blob([htmlString], { type: 'text/html' });
exportBtn.href = URL.createObjectURL(htmlFile);
exportBtn.download = 'ID3_export.html';
});
// setInterval(function(){
// fs.writeFile(path.resolve(__dirname, 'src/components/temp/temp.html'), editor.getValue(), (err) => {
// if (err) throw err;
// // console.log('The file has been saved!');
// })
// }, 300);
//
// setInterval(function(){
// const webview = document.querySelector('webview');
// webview.reload();
// }, 300);
// document.getElementById("editor").onkeyup = () => {
// fs.writeFile(path.resolve(__dirname, 'src/components/temp/temp.html'), startHtml + editor.getValue() + endHtml, (err) => {
// // fs.writeFile(path.resolve(__dirname, 'src/components/temp/temp.html'), editor.getValue(), (err) => {
// if (err) throw err;
// console.log('The file has been saved!');
// })
// }
window.addEventListener('keypress', function (event) {
if (event.ctrlKey && event.which === 19) {
let editorValue = editor.getValue();
fs.writeFileSync(path.resolve(__dirname, 'src/components/temp/temp.html'), editorValue);
let string = JSON.stringify(d3parser.parseD3(editorValue), null, '\t');
fs.writeFileSync('./src/d3ParserObj.js', string);
document.querySelector('webview').reload();
ipcRenderer.send('updateAttr');
}
});
let scatterPlot_button = document.querySelector('#scatter-plot');
scatterPlot_button.addEventListener('click', function (e) {
console.log('---ok you are calling a second method on click')
var scatterPlot_code = fs.readFileSync(path.resolve(__dirname, 'src/templates/ScatterPlot.html'), 'utf8');
editor.setValue(scatterPlot_code);
fs.writeFile(path.resolve(__dirname, 'src/components/temp/temp.html'), editor.getValue(), (err) => {
if (err) throw err;
})
document.querySelector('webview').reload();
});
});
}
render() {
return (
<div className="pane">
<div id="webview-container" className="renderer-container">
<header className="toolbar toolbar-header renderer-header">
<span id="render-subheader">Renderer</span>
<button id="popRender" className="btn btn-default pop-window-btn pull-right">
<span className="icon icon-popup icon-text"></span>
</button>
</header>
<div className="webview-container">
<webview id="render-window" src={this.state.url}></webview>
</div>
</div>
<div id="editor-container" className="editor-container">
<header className="toolbar toolbar-header renderer-header">
<span id="render-subheader">Editor</span>
<button id="popEditor" className="btn btn-default pop-window-btn pull-right">
<span className="icon icon-popup icon-text"></span>
</button>
</header>
<div className="editor-subcontainer">
<div id="editor"></div>
</div>
</div>
</div>
);
}
}
export { TextEditor, editor }
|
src/decorators/withViewport.js | thisarala/eye-elephant | /*! 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/AdminRoutes.js | azureReact/AzureReact | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Redirect, Route, Switch } from 'react-router-dom';
import { connect } from 'react-redux';
import compose from 'recompose/compose';
import getContext from 'recompose/getContext';
import CrudRoute from './CrudRoute';
import NotFound from './mui/layout/NotFound';
import Restricted from './auth/Restricted';
import { AUTH_GET_PERMISSIONS } from './auth';
import { declareResources as declareResourcesAction } from './actions';
import getMissingAuthClientError from './util/getMissingAuthClientError';
export class AdminRoutes extends Component {
componentDidMount() {
this.initializeResources(this.props.children);
}
initializeResources(children) {
if (typeof children === 'function') {
if (!this.props.authClient) {
throw new Error(getMissingAuthClientError('Admin'));
}
this.props.authClient(AUTH_GET_PERMISSIONS).then(permissions => {
const resources = children(permissions)
.filter(node => node)
.map(node => node.props);
this.props.declareResources(resources);
});
} else {
const resources =
React.Children.map(children, ({ props }) => props) || [];
this.props.declareResources(resources);
}
}
render() {
const {
customRoutes,
resources = [],
dashboard,
catchAll,
} = this.props;
return (
<Switch>
{customRoutes &&
customRoutes.map((route, index) => (
<Route
key={index}
exact={route.props.exact}
path={route.props.path}
component={route.props.component}
render={route.props.render}
children={route.props.children} // eslint-disable-line react/no-children-prop
/>
))}
{resources.map(resource => (
<Route
path={`/${resource.name}`}
key={resource.name}
render={() => (
<CrudRoute
resource={resource.name}
list={resource.list}
create={resource.create}
edit={resource.edit}
show={resource.show}
remove={resource.remove}
options={resource.options}
/>
)}
/>
))}
{dashboard ? (
<Route
exact
path="/"
render={routeProps => (
<Restricted
authParams={{ route: 'dashboard' }}
{...routeProps}
>
{React.createElement(dashboard)}
</Restricted>
)}
/>
) : (
resources[0] && (
<Route
exact
path="/"
render={() => (
<Redirect to={`/${resources[0].name}`} />
)}
/>
)
)}
<Route component={catchAll || NotFound} />
</Switch>
);
}
}
const componentPropType = PropTypes.oneOfType([
PropTypes.func,
PropTypes.string,
]);
AdminRoutes.propTypes = {
authClient: PropTypes.func,
children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
catchAll: componentPropType,
customRoutes: PropTypes.array,
declareResources: PropTypes.func.isRequired,
resources: PropTypes.array,
dashboard: componentPropType,
};
const mapStateToProps = state => ({
resources: Object.keys(state.admin.resources).map(
key => state.admin.resources[key].props
),
});
export default compose(
getContext({
authClient: PropTypes.func,
}),
connect(mapStateToProps, {
declareResources: declareResourcesAction,
})
)(AdminRoutes);
|
es/components/viewer2d/group.js | cvdlab/react-planner | import React from 'react';
import PropTypes from 'prop-types';
import If from '../../utils/react-if';
import * as sharedStyles from '../../shared-style';
var cx = 0;
var cy = 0;
var radius = 5;
var STYLE_CIRCLE = {
fill: sharedStyles.MATERIAL_COLORS[500].orange,
stroke: sharedStyles.MATERIAL_COLORS[500].orange,
cursor: 'default'
};
export default function Group(_ref, _ref2) {
var layer = _ref.layer,
group = _ref.group,
scene = _ref.scene,
catalog = _ref.catalog;
var translator = _ref2.translator;
return React.createElement(
'g',
{
'data-element-root': true,
'data-prototype': group.prototype,
'data-id': group.id,
'data-selected': group.selected,
'data-layer': layer.id,
style: group.selected ? { cursor: 'move' } : {},
transform: 'translate(' + group.x + ',' + group.y + ') rotate(' + group.rotation + ')'
},
React.createElement(
If,
{ condition: group.selected },
React.createElement(
'g',
{
'data-element-root': true,
'data-prototype': group.prototype,
'data-id': group.id,
'data-selected': group.selected,
'data-layer': layer.id,
'data-part': 'rotation-anchor'
},
React.createElement(
'circle',
{ cx: cx, cy: cy, r: radius, style: STYLE_CIRCLE },
React.createElement(
'title',
null,
translator.t('Group\'s Barycenter')
)
)
)
)
);
}
Group.propTypes = {
group: PropTypes.object.isRequired,
layer: PropTypes.object.isRequired,
scene: PropTypes.object.isRequired,
catalog: PropTypes.object.isRequired
};
Group.contextTypes = {
translator: PropTypes.object.isRequired
}; |
src/components/icons/Link.js | typical000/paveldavydov | import React from 'react'
import PropTypes from 'prop-types'
import cn from 'classnames'
import Icon from './Icon'
const Link = ({className}) => (
<Icon>
{({classes}) => (
<svg
className={cn(classes.icon, className)}
viewBox="0 0 16 16"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"
fillRule="evenodd"
/>
</svg>
)}
</Icon>
)
Link.propTypes = {
className: PropTypes.string,
}
export default Link
|
src/javascript/components/Device/deviceDetailView.js | rahulharinkhede2013/xigro-dashboard | import React from 'react';
import classnames from 'classnames';
import GoogleMapDeviceDetailComponet from './../googleMap/deviceDetailsMap';
import index from '../../index.scss';
import { Button, IconButton } from 'att-iot-ui/lib/button';
import Icon from 'att-iot-ui/lib/icon';
let deviceData = {
name: "Denny's device",
serialNumber: '2546852315',
activeAlert: 'alerts',
activeProfile: 'My Profile',
assetGroupName: 'Asset Group 1',
actions: [],
location: { latitude: 33.00765, longitude: -96.75070 }
};
class DeviceDetailView extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className={classnames(index.mt5, index.mb5)}>
<h3>{deviceData.name}</h3>
<hr />
<div className={classnames(index.dFlex, index.p2, index.mr5)}>
<ul className={classnames(index.listUnstyled)}>
<li>Serial#:{deviceData.serialNumber}</li>
<li>Active alerts:{deviceData.activeAlert}</li>
<li>Active profile:{deviceData.activeProfile}</li>
<li>Asset group:{deviceData.assetGroupName}</li>
</ul>
</div>
<h4>Geofence</h4>
<IconButton primary key='gearL'><Icon name='gearL' /></IconButton>
<GoogleMapDeviceDetailComponet deviceData={deviceData} />
<h4>Device tresholds</h4>
<p>Device will send alerts when the tresholds critera is met.</p>
</div>
)
}
}
export default DeviceDetailView; |
src/routes/error/index.js | zhouchao0924/SLCOPY | import React from 'react'
import { Icon } from 'antd'
import styles from './index.less'
const Error = () => <div className="content-inner">
<div className={styles.error}>
<Icon type="frown-o" />
<h1>404 Not Found</h1>
</div>
</div>
export default Error
|
editor/components/FileLoader.js | VishalRohra/chroma-tone | // import classNames from 'classnames';
import React from 'react'
import PureComponent from 'react-pure-render/component';
import { Dialog, CircularProgress } from 'material-ui'
import Dropzone from 'react-dropzone'
import { hideFileLoader, loadFile } from '../actions'
import '../styles/FileLoader.less'
export default class FileLoader extends PureComponent {
componentWillReceiveProps(nextProps) {
if (this.props.open && !nextProps.open) {
this.dialog.dismiss();
}
if (!this.props.open && nextProps.open) {
this.dialog.show();
}
}
render() {
return (
<Dialog
ref={component => this.dialog = component}
title='Load From File'
openImmediately={this.props.open}
modal={true}
actions={[{ text: 'Cancel' }]}
onDismiss={() => this.props.dispatch(hideFileLoader())}
>
<Dropzone
className='file-loader-dropzone'
activeClassName='file-loader-dropzone active'
onDrop={file => this.props.dispatch(loadFile(file))}
multiple={false}
>
{
this.props.loadingFile ? [
<CircularProgress key={0} mode="indeterminate" />,
<p key={1}>Loading file</p>
] : [
<p key={2}>{'Drag and drop the file into this box'}</p>,
<p key={3}>Or click in this box to select the file</p>
].concat(this.props.error ? [
<p key={4}>Something wrong happened:</p>,
<p key={5}><i>{this.props.error}</i></p>
] : [])
}
</Dropzone>
</Dialog>
)
}
}
|
node_modules/re-base/examples/firebase/chatapp/src/components/Container.js | aggiedefenders/aggiedefenders.github.io | import React from 'react';
import Message from './Message.js';
import base from '../rebase';
class Container extends React.Component {
constructor(props) {
super(props);
this.state = {
messages: [],
show: null
};
}
componentWillMount() {
/*
* We bind the 'chats' firebase endopint to our 'messages' state.
* Anytime the firebase updates, it will call 'setState' on this component
* with the new state.
*
* Any time we call 'setState' on our 'messages' state, it will
* updated the Firebase '/chats' endpoint. Firebase will then emit the changes,
* which causes our local instance (and any other instances) to update
* state to reflect those changes.
*/
this.ref = base.syncState('chats', {
context: this,
state: 'messages',
asArray: true
});
}
componentWillUnmount() {
/*
* When the component unmounts, we remove the binding.
* Invoking syncState (or bindToState or listenTo)
* will return a reference to that listener (see line 30).
* You will use that ref to remove the binding here.
*/
base.removeBinding(this.ref);
}
_removeMessage(index, e) {
e.stopPropagation();
var arr = this.state.messages.concat([]);
arr.splice(index, 1);
/*
* Calling setState here will update the '/chats' ref on our Firebase.
* Notice that I'm also updating the 'show' state. Because there is no
* binding to our 'show' state, it will update the local 'show' state normally,
* without going to Firebase.
*/
this.setState({
messages: arr,
show: null
});
}
_toggleView(index) {
/*
* Because nothing is bound to our 'show' state, calling
* setState on 'show' here will do nothing with Firebase,
* but simply update our local state like normal.
*/
this.setState({
show: index
});
}
render() {
var messages = this.state.messages.map((item, index) => {
return (
<Message
thread={item}
show={this.state.show === index}
removeMessage={this._removeMessage.bind(this, index)}
handleClick={this._toggleView.bind(this, index)}
key={index}
/>
);
});
return (
<div className="col-md-12">
<div className="col-md-8">
<h1>{(this.state.messages.length || 0) + ' messages'}</h1>
<ul style={{ listStyle: 'none' }}>{messages}</ul>
</div>
</div>
);
}
}
export default Container;
|
app/components/formInputs/BasicInput.js | dawidgorczyca/Jeduthun-desktop | import React from 'react'
import classnames from 'classnames'
const BasicInputComponent = props => { return (
<div className={classnames('basic-input', props.wrapperClass)}>
{(props.label
? <label htmlFor={props.name}>{props.label}</label>
: ''
)}
{(props.type === 'text' &&
<input
name={props.name}
type={props.type}
value={props.value}
onChange={props.onChange}
/>
)}
{(props.type === 'select' &&
<select
name={props.name}
value={props.value}
onChange={props.onChange}
>
{
props.options.map(function(option, i) {
return (
<option
key={i}
value={option.value}
label={option.label}
>{option.label}</option>
)
})
}
</select>
)}
</div>
)}
BasicInputComponent.propTypes = {
label: React.PropTypes.string,
wrapperClass: React.PropTypes.string,
name: React.PropTypes.string.isRequired,
type: React.PropTypes.string.isRequired,
value: React.PropTypes.string.isRequired,
onChange: React.PropTypes.func.isRequired
}
export default BasicInputComponent |
src/templates/category-template.js | ivanminutillo/faircoopWebSite | import React from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
import Sidebar from '../components/Sidebar';
import CategoryTemplateDetails from '../components/CategoryTemplateDetails';
class CategoryTemplate extends React.Component {
render() {
const { title } = this.props.data.site.siteMetadata;
const { category } = this.props.pathContext;
return (
<div>
<Helmet title={`${category} - ${title}`} />
<Sidebar {...this.props} />
<CategoryTemplateDetails {...this.props} />
</div>
);
}
}
CategoryTemplate.propTypes = {
data: PropTypes.shape({
site: PropTypes.shape({
siteMetadata: PropTypes.shape({
title: PropTypes.string.isRequired
})
})
}),
pathContext: PropTypes.shape({
category: PropTypes.string.isRequired
})
};
export default CategoryTemplate;
export const pageQuery = graphql`
query CategoryPage($category: String) {
site {
siteMetadata {
title
subtitle
copyright
menu {
label
path
}
author {
name
email
telegram
twitter
github
}
}
}
allMarkdownRemark(
limit: 1000,
filter: { frontmatter: { category: { eq: $category }, layout: { eq: "post" }, draft: { ne: true } } },
sort: { order: DESC, fields: [frontmatter___date] }
){
edges {
node {
fields {
slug
categorySlug
}
frontmatter {
title
date
category
description
}
}
}
}
}
`;
|
src/templates/ruling_entity_promises.js | Betree/democracy-watcher | import React from 'react'
import groupBy from 'lodash.groupby'
import RulingEntityLayout from '../components/Layout/ruling_entity'
import PromisesCategoriesTabs from '../components/Promises/promises_categories_tabs'
import PromisesStatistics from '../components/Promises/promises_statistics'
export default class RulingEntityPromises extends React.PureComponent {
render() {
const {pageContext: {entity}} = this.props
const groupedPromises = groupBy(entity.promises, 'category')
return (
<RulingEntityLayout entity={entity}>
<PromisesCategoriesTabs
categories={Object.keys(groupedPromises)}
promises={groupedPromises}
/>
<PromisesStatistics
ruling_entity={entity}
promises={entity.promises}
/>
</RulingEntityLayout>
)
}
}
|
src/parser/rogue/assassination/modules/features/Checklist/Component.js | fyruna/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import Checklist from 'parser/shared/modules/features/Checklist';
import Rule from 'parser/shared/modules/features/Checklist/Rule';
import Requirement from 'parser/shared/modules/features/Checklist/Requirement';
import PreparationRule from 'parser/shared/modules/features/Checklist/PreparationRule';
import GenericCastEfficiencyRequirement from 'parser/shared/modules/features/Checklist/GenericCastEfficiencyRequirement';
class AssassinationRogueChecklist extends React.PureComponent {
static propTypes = {
castEfficiency: PropTypes.object.isRequired,
combatant: PropTypes.shape({
hasTalent: PropTypes.func.isRequired,
hasTrinket: PropTypes.func.isRequired,
}).isRequired,
thresholds: PropTypes.object.isRequired,
};
render() {
const { combatant, castEfficiency, thresholds } = this.props;
const AbilityRequirement = props => (
<GenericCastEfficiencyRequirement
castEfficiency={castEfficiency.getCastEfficiencyForSpellId(props.spell)}
{...props}
/>
);
return (
<Checklist>
<Rule
name="Maintain your DoTs on the boss"
description="DoTs are a big part of your damage. You should try to keep as high uptime on them as possible, but do not refresh them too early"
>
<Requirement
name={(
<>
<SpellLink id={SPELLS.GARROTE.id} /> uptime
</>
)}
thresholds={thresholds.garroteUptime}
/>
<Requirement
name={(
<>
<SpellLink id={SPELLS.RUPTURE.id} /> uptime
</>
)}
thresholds={thresholds.ruptureUptime}
/>
<Requirement
name={(
<>
<SpellLink id={SPELLS.GARROTE.id} /> effective refresh duration
</>
)}
thresholds={thresholds.garroteEfficiency}
/>
<Requirement
name={(
<>
<SpellLink id={SPELLS.RUPTURE.id} /> effective refresh duration
</>
)}
thresholds={thresholds.ruptureEfficiency}
/>
</Rule>
<Rule
name="Do not overcap your resources"
description="You should try to always avoid overcapping your Energy and Combo Points."
>
<Requirement name="Energy generator efficiency" thresholds={thresholds.energyEfficiency} />
<Requirement name="Combo Point efficiency" thresholds={thresholds.comboPointEfficiency} />
<Requirement name="Energy regeneration efficiency" thresholds={thresholds.energyCapEfficiency} />
{combatant.hasTalent(SPELLS.BLINDSIDE_TALENT.id) && (
<Requirement
name={(
<>
<SpellLink id={SPELLS.BLINDSIDE_TALENT.id} /> efficiency
</>
)}
thresholds={thresholds.blindsideEfficiency}
/>
)}
</Rule>
<Rule
name="Use your cooldowns"
description="Your cooldowns are a major contributor to your DPS, and should be used as frequently as possible throughout a fight. A cooldown should be held on to only if a priority DPS phase is coming soon. Holding cooldowns too long will hurt your DPS."
>
<AbilityRequirement spell={SPELLS.VENDETTA.id} />
{combatant.hasTalent(SPELLS.EXSANGUINATE_TALENT.id) && (
<AbilityRequirement spell={SPELLS.EXSANGUINATE_TALENT.id} />
)}
{combatant.hasTalent(SPELLS.TOXIC_BLADE_TALENT.id) && (
<AbilityRequirement spell={SPELLS.TOXIC_BLADE_TALENT.id} />
)}
{combatant.hasTalent(SPELLS.MARKED_FOR_DEATH_TALENT.id) && (
<AbilityRequirement spell={SPELLS.MARKED_FOR_DEATH_TALENT.id} />
)}
</Rule>
<Rule
name="Maximize Vanish usage"
description="Your level 30 talent turns Vanish into a powerful DPS cooldown, significantly buffing the next 1-3 casts. Making sure to cast the correct abilities during this short window is important to maximizing your DPS."
>
<AbilityRequirement spell={SPELLS.VANISH.id} />
{combatant.hasTalent(SPELLS.SUBTERFUGE_TALENT.id) && (
<Requirement
name={(
<>
<SpellLink id={SPELLS.SUBTERFUGE_BUFF.id} />s with atleast one <SpellLink id={SPELLS.GARROTE.id} /> cast
</>
)}
thresholds={thresholds.subterfugeEfficiency}
/>
)}
{combatant.hasTalent(SPELLS.MASTER_ASSASSIN_TALENT.id) && (
<Requirement
name={(
<>
Good casts during <SpellLink id={SPELLS.MASTER_ASSASSIN_TALENT.id} />
</>
)}
thresholds={thresholds.masterAssassinEfficiency}
/>
)}
{combatant.hasTalent(SPELLS.NIGHTSTALKER_TALENT.id) && (
<Requirement
name={(
<>
<SpellLink id={SPELLS.VANISH.id} />es spent on snapshotting <SpellLink id={SPELLS.RUPTURE.id} />
</>
)}
thresholds={thresholds.nightstalkerEfficiency}
/>
)}
{combatant.hasTalent(SPELLS.NIGHTSTALKER_TALENT.id) && (
<Requirement
name={(
<>
On pull opener spent on snapshotting <SpellLink id={SPELLS.RUPTURE.id} /> or <SpellLink id={SPELLS.GARROTE.id} />
</>
)}
thresholds={thresholds.nightstalkerOpenerEfficiency}
/>
)}
{(combatant.hasTalent(SPELLS.NIGHTSTALKER_TALENT.id)) && (
<Requirement
name={(
<>
Lost snapshotted <SpellLink id={SPELLS.RUPTURE.id} /> due to early refreshes
</>
)}
thresholds={thresholds.garroteSnapshotEfficiency}
/>
)}
{(combatant.hasTalent(SPELLS.SUBTERFUGE_TALENT.id) || combatant.hasTalent(SPELLS.NIGHTSTALKER_TALENT.id)) && (
<Requirement
name={(
<>
Lost snapshotted <SpellLink id={SPELLS.GARROTE.id} /> due to early refreshes
</>
)}
thresholds={thresholds.garroteSnapshotEfficiency}
/>
)}
</Rule>
<PreparationRule thresholds={thresholds} />
</Checklist>
);
}
}
export default AssassinationRogueChecklist;
|
modules/gui/src/widget/split/splitHandleCenter.js | openforis/sepal | import {SplitHandle} from './splitHandle'
import PropTypes from 'prop-types'
import React from 'react'
import _ from 'lodash'
import styles from './splitView.module.css'
export class SplitHandleCenter extends React.Component {
render() {
const {position, size, onDragging, onPosition} = this.props
return (
<SplitHandle
name='center'
classNames={this.getClassNames()}
position={position}
size={size}
onDragging={onDragging}
onPosition={onPosition}
/>
)
}
getClassNames() {
return [
styles.handle,
styles.center
]
}
}
SplitHandleCenter.propTypes = {
position: PropTypes.object.isRequired,
size: PropTypes.object.isRequired,
onDragging: PropTypes.func.isRequired,
onPosition: PropTypes.func.isRequired
}
|
blueocean-material-icons/src/js/components/svg-icons/action/done.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionDone = (props) => (
<SvgIcon {...props}>
<path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"/>
</SvgIcon>
);
ActionDone.displayName = 'ActionDone';
ActionDone.muiName = 'SvgIcon';
export default ActionDone;
|
src/interface/statistics/components/RadarChart/index.js | sMteX/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import { scaleLinear, scaleOrdinal } from 'd3-scale';
import { schemeCategory10 } from 'd3-scale-chromatic';
import { lineRadial, curveCardinalClosed, curveLinearClosed } from 'd3-shape';
import SvgWrappingText from './SvgWrappingText';
// This is heavily based on https://gist.github.com/nbremer/21746a9668ffdf6d8242#file-radarchart-js
// It was severely cleaned up, updated for the d3 version we use, and modified to behave as a component.
// The original code was licensed as "license: mit". These modifications (basically any code not straight from the original) is licensed under the regular license used in this project. If you need a MIT license you should use the code in the above link instead.
export function maxDataValue(data) {
return data.reduce((dataMax, series) => series.points.reduce((seriesMax, item) => (
Math.max(seriesMax, item.value)
), dataMax), 0);
}
class RadarChart extends React.Component {
static propTypes = {
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
margin: PropTypes.shape({
top: PropTypes.number,
right: PropTypes.number,
bottom: PropTypes.number,
left: PropTypes.number,
}),
levels: PropTypes.number,
maxValue: PropTypes.number,
labelFactor: PropTypes.number,
wrapWidth: PropTypes.number,
opacityArea: PropTypes.number,
dotRadius: PropTypes.number,
opacityCircles: PropTypes.number,
strokeWidth: PropTypes.number,
roundStrokes: PropTypes.bool,
color: PropTypes.object,
data: PropTypes.arrayOf(PropTypes.shape({
color: PropTypes.string,
points: PropTypes.arrayOf(PropTypes.shape({
axis: PropTypes.string.isRequired,
value: PropTypes.number.isRequired,
})).isRequired,
})).isRequired,
labelFormatter: PropTypes.array.isRequired,
};
static defaultProps = {
width: 500, //Width of the circle
height: 500, //Height of the circle
margin: { top: 40, right: 40, bottom: 40, left: 40 }, //The margins of the SVG
levels: 3, //How many levels or inner circles should there be drawn
maxValue: 0, //What is the value that the biggest circle will represent
labelFactor: 1.25, //How much farther than the radius of the outer circle should the labels be placed
labelMaxWidth: 60, //The number of pixels after which a label needs to be given a new line
opacityArea: 0.35, //The opacity of the area of the blob
dotRadius: 4, //The size of the colored circles of each blog
opacityCircles: 0.1, //The opacity of the circles of each blob
strokeWidth: 2, //The width of the stroke around each blob
roundStrokes: false, //If true the area and stroke will follow a round path (cardinal-closed)
color: scaleOrdinal(schemeCategory10), //Color function
};
render() {
const { data, width, height, margin, levels, opacityCircles, labelFactor, labelMaxWidth, roundStrokes, color, opacityArea, strokeWidth, dotRadius, labelFormatter, ...others } = this.props;
//If the supplied maxValue is smaller than the actual one, replace by the max in the data
const maxValue = Math.max(this.props.maxValue, maxDataValue(data));
//Names of each axis
const allAxis = data[0].points.map(i => i.axis);
//The number of different axes
const total = allAxis.length;
//Radius of the outermost circle
const radius = Math.min(width / 2, height / 2);
//The width in radians of each "slice"
const angleSlice = Math.PI * 2 / total;
//Scale for the radius
const rScale = scaleLinear()
.range([0, radius])
.domain([0, maxValue]);
//The radial line function
const radarLine = lineRadial()
.curve(curveLinearClosed)
.radius(d => rScale(d.value))
.angle((_, i) => i * angleSlice);
if (roundStrokes) {
radarLine.curve(curveCardinalClosed);
}
return (
<svg
width={width + margin.left + margin.right}
height={height + margin.top + margin.bottom}
className="radar"
style={{ overflow: 'visible' }}
{...others}
>
<g transform={`translate(${width / 2 + margin.left}, ${height / 2 + margin.top})`}>
<defs>
<filter id="glow">
<feGaussianBlur stdDeviation={2.5} result="coloredBlur" />
<feMerge>
<feMergeNode in="coloredBlur" />
<feMergeNode in="SourceGraphic" />
</feMerge>
</filter>
</defs>
<g className="axisWrapper">
{/* the background circles */}
{[...Array(3).keys()].reverse().map(level => (
<circle
className="gridCircle"
r={radius / levels * (level + 1)}
style={{
fill: '#CDCDCD',
stroke: '#CDCDCD',
strokeOpacity: 0.5,
fillOpacity: opacityCircles,
filter: 'url(#glow)',
}}
/>
))}
{/* the background circle labels */}
{/* don't merge with the above loop since we need text to overlap ALL circles */}
{[...Array(3).keys()].reverse().map(level => (
<text
className="axisLabel"
x={4}
y={-(level + 1) * radius / levels}
dy="0.4em"
style={{ fontSize: 10 }}
fill="rgba(200, 200, 200, 0.7)"
>
{labelFormatter(maxValue * (level + 1) / levels)}
</text>
))}
{/* Create the straight lines radiating outward from the center */}
{allAxis.map((label, i) => (
<g className="axis">
<line
className="line"
x1={0}
y1={0}
x2={rScale(maxValue * 1.1) * Math.cos(angleSlice * i - Math.PI / 2)}
y2={rScale(maxValue * 1.1) * Math.sin(angleSlice * i - Math.PI / 2)}
style={{
stroke: 'white',
strokeOpacity: 0.5,
strokeWidth: 2,
}}
/>
{/* the labels at the end of each axis */}
<SvgWrappingText
className="legend"
style={{ fontSize: 11 }}
textAnchor="middle"
dy="0.35em"
x={rScale(maxValue * labelFactor) * Math.cos(angleSlice * i - Math.PI / 2)}
y={rScale(maxValue * labelFactor) * Math.sin(angleSlice * i - Math.PI / 2)}
width={labelMaxWidth}
>
{label}
</SvgWrappingText>
</g>
))}
{/* Draw the radar chart blobs (value blobs) */}
{data.map((series, i) => (
<g className="radarWrapper">
{/* The backgrounds */}
<path
className="radarArea"
d={radarLine(series.points)}
style={{
fill: series.color || color(i),
fillOpacity: opacityArea,
}}
/>
{/* The outlines */}
<path
className="radarStroke"
d={radarLine(series.points)}
style={{
strokeWidth: strokeWidth,
stroke: series.color || color(i),
fill: 'none',
filter: 'url(#glow)',
}}
/>
{/* Circles on the axis to show exact cross over */}
{series.points.map((point, pointIndex) => (
<circle
className="radarCircle"
r={dotRadius}
cx={rScale(point.value) * Math.cos(angleSlice * pointIndex - Math.PI / 2)}
cy={rScale(point.value) * Math.sin(angleSlice * pointIndex - Math.PI / 2)}
style={{
fill: series.color || color(i),
fillOpacity: 0.8,
}}
/>
))}
</g>
))}
</g>
</g>
</svg>
);
}
}
export default RadarChart;
// TODO: Tooltips
// export default function RadarChart(id, data, options) {
// //Append the circles
// blobWrapper.selectAll('.radarCircle')
// .data(function (d, i) {
// return d;
// })
// .enter().append('circle')
// .attr('class', 'radarCircle')
// .attr('r', cfg.dotRadius)
// .attr('cx', function (d, i) {
// return rScale(d.value) * Math.cos(angleSlice * i - Math.PI / 2);
// })
// .attr('cy', function (d, i) {
// return rScale(d.value) * Math.sin(angleSlice * i - Math.PI / 2);
// })
// .style('fill', function (d, i, j) {
// return cfg.color(j);
// })
// .style('fill-opacity', 0.8);
//
// /////////////////////////////////////////////////////////
// //////// Append invisible circles for tooltip ///////////
// /////////////////////////////////////////////////////////
//
// //Wrapper for the invisible circles on top
// const blobCircleWrapper = g.selectAll('.radarCircleWrapper')
// .data(data)
// .enter().append('g')
// .attr('class', 'radarCircleWrapper');
//
// //Append a set of invisible circles on top for the mouseover pop-up
// blobCircleWrapper.selectAll('.radarInvisibleCircle')
// .data(d => d)
// .enter().append('circle')
// .attr('class', 'radarInvisibleCircle')
// .attr('r', cfg.dotRadius * 1.5)
// .attr('cx', (d, i) => rScale(d.value) * Math.cos(angleSlice * i - Math.PI / 2))
// .attr('cy', (d, i) => rScale(d.value) * Math.sin(angleSlice * i - Math.PI / 2))
// .style('fill', 'none')
// .style('pointer-events', 'all')
// .on('mouseover', function (d) {
// const newX = parseFloat(select(this).attr('cx')) - 10;
// const newY = parseFloat(select(this).attr('cy')) - 10;
//
// tooltip
// .attr('x', newX)
// .attr('y', newY)
// .text(Format(d.value))
// .transition().duration(200)
// .style('opacity', 1);
// })
// .on('mouseout', () => {
// tooltip.transition().duration(200)
// .style('opacity', 0);
// });
//
// //Set up the small tooltip for when you hover over a circle
// const tooltip = g.append('text')
// .attr('class', 'tooltip')
// .style('opacity', 0);
//
// }//RadarChart
|
src/media/js/addon/components/progressBar.js | mozilla/marketplace-submission | /*
ProgressBar, primarily for file uploads.
*/
import React from 'react';
function toFixedDown(number, digits) {
const re = new RegExp("(\\d+\\.\\d{" + digits + "})(\\d)");
const m = number.toString().match(re);
return m ? parseFloat(m[1]) : number.valueOf();
}
export default class ProgressBar extends React.Component {
static propTypes = {
loadedSize: React.PropTypes.number,
totalSize: React.PropTypes.number,
unit: React.PropTypes.string,
};
static defaultProps = {
loadedSize: 0,
totalSize: 100,
unit: '%',
};
render() {
const barFillStyle = {
width: `${this.props.loadedSize / this.props.totalSize * 100}%`
};
const loadedSize = toFixedDown(this.props.loadedSize, 2);
const totalSize = toFixedDown(this.props.totalSize, 2);
return (
<div className="progress-bar">
<div className="progress-bar-bar">
<div className="progress-bar-fill" style={barFillStyle}/>
</div>
<span className="progress-bar-text">
{loadedSize} {this.props.unit} / {totalSize} {this.props.unit}
</span>
</div>
);
}
}
|
node_modules/react-router/es/Redirect.js | SpatialMap/SpatialMapDev | import React from 'react';
import invariant from 'invariant';
import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils';
import { formatPattern } from './PatternUtils';
import { falsy } from './InternalPropTypes';
var _React$PropTypes = React.PropTypes,
string = _React$PropTypes.string,
object = _React$PropTypes.object;
/**
* A <Redirect> is used to declare another URL path a client should
* be sent to when they request a given URL.
*
* Redirects are placed alongside routes in the route configuration
* and are traversed in the same manner.
*/
/* eslint-disable react/require-render-return */
var Redirect = React.createClass({
displayName: 'Redirect',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element) {
var route = _createRouteFromReactElement(element);
if (route.from) route.path = route.from;
route.onEnter = function (nextState, replace) {
var location = nextState.location,
params = nextState.params;
var pathname = void 0;
if (route.to.charAt(0) === '/') {
pathname = formatPattern(route.to, params);
} else if (!route.to) {
pathname = location.pathname;
} else {
var routeIndex = nextState.routes.indexOf(route);
var parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1);
var pattern = parentPattern.replace(/\/*$/, '/') + route.to;
pathname = formatPattern(pattern, params);
}
replace({
pathname: pathname,
query: route.query || location.query,
state: route.state || location.state
});
};
return route;
},
getRoutePattern: function getRoutePattern(routes, routeIndex) {
var parentPattern = '';
for (var i = routeIndex; i >= 0; i--) {
var route = routes[i];
var pattern = route.path || '';
parentPattern = pattern.replace(/\/*$/, '/') + parentPattern;
if (pattern.indexOf('/') === 0) break;
}
return '/' + parentPattern;
}
},
propTypes: {
path: string,
from: string, // Alias for path
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Redirect> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default Redirect; |
src/components/app/Avatar.js | metasfresh/metasfresh-webui-frontend | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { getAvatar } from '../../api';
import defaultAvatar from '../../assets/images/default-avatar.png';
class Avatar extends Component {
constructor(props) {
super(props);
}
render() {
const { size, className, id, title } = this.props;
return (
<img
src={id ? getAvatar(id) : defaultAvatar}
title={title}
className={
'avatar img-fluid rounded-circle ' +
(size ? 'avatar-' + size + ' ' : '') +
(className ? className : '')
}
/>
);
}
}
Avatar.propTypes = {
size: PropTypes.string,
className: PropTypes.string,
id: PropTypes.string,
title: PropTypes.string,
};
export default Avatar;
|
app/src/js/components/notifs/notif_bubble.js | tahnik/devRantron | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { getNotifText } from '../../consts/utils';
class Notification extends Component {
shouldComponentUpdate(nextProps) {
const { notif } = this.props;
if (nextProps.unread === 0 && (notif.read === 1)) {
return false;
}
if (
notif.read === nextProps.notif.read
&& nextProps.unread !== 0
) {
return false;
}
return true;
}
open(id, commentID) {
this.props.open(id, commentID);
}
render() {
const { notif, user, unread } = this.props;
let icon;
let imageSource = 'res/images/invis.png';
if (user && user.avatar.i) {
imageSource = `https://avatars.devrant.io/${user.avatar.i}`;
}
const username = user ? user.name : 'Deleted user';
const avatarBack = user ? user.avatar.b : '#FFF';
const isCollab = notif.rt === 2;
const notifText = getNotifText(notif.type, username, isCollab);
switch (notif.type) {
case 'comment_mention':
icon = 'ion-chatbubble-working';
break;
case 'comment_content':
icon = 'ion-chatbubble-working';
break;
case 'comment_discuss':
icon = 'ion-chatbubbles';
break;
case 'comment_vote':
icon = 'ion-chatbubbles';
break;
default:
icon = 'ion-plus-round';
}
return (
<div
onClick={() => this.open(notif.rant_id, notif.comment_id)}
className="notif_bubble"
>
<div className={`notif_badge ${notif.read === 1 ? 'read' : ''}`}>
<img
alt=""
src={imageSource}
className="notif_image"
style={{ background: `#${avatarBack}` }}
/>
<i
className={`${icon} ${notif.read === 1 || unread === 0 ? 'read' : ''}`}
/>
</div>
<div className="notif_desc">
<p>{notifText}</p>
</div>
</div>
);
}
}
Notification.propTypes = {
notif: PropTypes.object.isRequired,
user: PropTypes.object,
open: PropTypes.func.isRequired,
unread: PropTypes.number.isRequired,
};
export default Notification;
|
components/LodingScreen.js | akashnautiyal013/ImpactRun01 |
'use strict';
import React, { Component } from 'react';
import{
StyleSheet,
View,
Image,
ScrollView,
Dimensions,
TouchableOpacity,
Text,
ActivityIndicatorIOS,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
var deviceWidth = Dimensions.get('window').width;
var deviceHeight = Dimensions.get('window').height;
class Loding extends Component {
constructor(props) {
super(props);
this.state = {
animating: true,
};
}
render() {
return (
<View style={styles.LodingWrap}>
<Image source={require('../images/backgroundLodingscreen.png')} style={styles.LodingBackgroundImg}>
<ActivityIndicatorIOS
style={{height: 80}}
size="large"
/>
</Image>
</View>
);
}
}
const styles = StyleSheet.create({
LodingWrap: {
flex:1,
justifyContent: 'center',
alignItems: 'center',
},
LodingBackgroundImg:{
flex:1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default Loding; |
frontend/src/Settings/CustomFormats/CustomFormats/CustomFormat.js | Radarr/Radarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Card from 'Components/Card';
import Label from 'Components/Label';
import IconButton from 'Components/Link/IconButton';
import ConfirmModal from 'Components/Modal/ConfirmModal';
import { icons, kinds } from 'Helpers/Props';
import translate from 'Utilities/String/translate';
import EditCustomFormatModalConnector from './EditCustomFormatModalConnector';
import ExportCustomFormatModal from './ExportCustomFormatModal';
import styles from './CustomFormat.css';
class CustomFormat extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this.state = {
isEditCustomFormatModalOpen: false,
isExportCustomFormatModalOpen: false,
isDeleteCustomFormatModalOpen: false
};
}
//
// Listeners
onEditCustomFormatPress = () => {
this.setState({ isEditCustomFormatModalOpen: true });
};
onEditCustomFormatModalClose = () => {
this.setState({ isEditCustomFormatModalOpen: false });
};
onExportCustomFormatPress = () => {
this.setState({ isExportCustomFormatModalOpen: true });
};
onExportCustomFormatModalClose = () => {
this.setState({ isExportCustomFormatModalOpen: false });
};
onDeleteCustomFormatPress = () => {
this.setState({
isEditCustomFormatModalOpen: false,
isDeleteCustomFormatModalOpen: true
});
};
onDeleteCustomFormatModalClose = () => {
this.setState({ isDeleteCustomFormatModalOpen: false });
};
onConfirmDeleteCustomFormat = () => {
this.props.onConfirmDeleteCustomFormat(this.props.id);
};
onCloneCustomFormatPress = () => {
const {
id,
onCloneCustomFormatPress
} = this.props;
onCloneCustomFormatPress(id);
};
//
// Render
render() {
const {
id,
name,
specifications,
isDeleting
} = this.props;
return (
<Card
className={styles.customFormat}
overlayContent={true}
onPress={this.onEditCustomFormatPress}
>
<div className={styles.nameContainer}>
<div className={styles.name}>
{name}
</div>
<div>
<IconButton
className={styles.cloneButton}
title={translate('CloneCustomFormat')}
name={icons.CLONE}
onPress={this.onCloneCustomFormatPress}
/>
<IconButton
className={styles.cloneButton}
title={translate('ExportCustomFormat')}
name={icons.EXPORT}
onPress={this.onExportCustomFormatPress}
/>
</div>
</div>
<div>
{
specifications.map((item, index) => {
if (!item) {
return null;
}
let kind = kinds.DEFAULT;
if (item.required) {
kind = kinds.SUCCESS;
}
if (item.negate) {
kind = kinds.DANGER;
}
return (
<Label
key={index}
kind={kind}
>
{item.name}
</Label>
);
})
}
</div>
<EditCustomFormatModalConnector
id={id}
isOpen={this.state.isEditCustomFormatModalOpen}
onModalClose={this.onEditCustomFormatModalClose}
onDeleteCustomFormatPress={this.onDeleteCustomFormatPress}
/>
<ExportCustomFormatModal
id={id}
isOpen={this.state.isExportCustomFormatModalOpen}
onModalClose={this.onExportCustomFormatModalClose}
/>
<ConfirmModal
isOpen={this.state.isDeleteCustomFormatModalOpen}
kind={kinds.DANGER}
title={translate('DeleteCustomFormat')}
message={
<div>
<div>
{translate('AreYouSureYouWantToDeleteFormat', [name])}
</div>
</div>
}
confirmLabel={translate('Delete')}
isSpinning={isDeleting}
onConfirm={this.onConfirmDeleteCustomFormat}
onCancel={this.onDeleteCustomFormatModalClose}
/>
</Card>
);
}
}
CustomFormat.propTypes = {
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
specifications: PropTypes.arrayOf(PropTypes.object).isRequired,
isDeleting: PropTypes.bool.isRequired,
onConfirmDeleteCustomFormat: PropTypes.func.isRequired,
onCloneCustomFormatPress: PropTypes.func.isRequired
};
export default CustomFormat;
|
livedoc-ui-webjar/src/App.js | joffrey-bion/livedoc | // @flow
import React from 'react';
import { connect } from 'react-redux';
import { Redirect, Route, Switch, withRouter } from 'react-router-dom';
import { Doc } from './components/doc/DocPresenter';
import { DocFetcher } from './components/fetcher/DocFetcher';
import { LoadingSpinner } from './components/shared/LoadingSpinner';
import { Header } from './components/header/Header';
import type { State } from './model/state';
import type { LoadingState } from './redux/loader';
import { getLoadingState } from './redux/loader';
import './icons'
export const APP_VERSION = process.env.REACT_APP_VERSION || '?:?:?';
export const APP_SPEC_VERSION = parseInt(process.env.REACT_APP_SPEC_VERSION, 10) || 0;
type AppProps = {
loadingState: LoadingState,
}
const AppPresenter = (props: AppProps) => (<div>
<Header/>
<AppContent {...props}/>
</div>);
const AppContent = ({loadingState}: AppProps) => {
if (loadingState === 'LOADING_NEW') {
return <LoadingSpinner/>;
}
return <Switch>
<Route path="/fetch" render={() => <DocFetcher/>}/>
{loadingState === 'IDLE_EMPTY' && <Redirect to="/fetch"/>}
<Route path="/" component={Doc}/>
</Switch>;
};
const mapStateToProps = (state: State): AppProps => ({
loadingState: getLoadingState(state),
});
const mapDispatchToProps = {};
export const App = withRouter(connect(mapStateToProps, mapDispatchToProps)(AppPresenter));
|
src/components/Project/Project.js | ortonomy/flingapp-frontend | import React, { Component } from 'react';
class Project extends Component {
render() {
return(
<div className="Project">
This is a project!
</div>
)
}
}
export default Project;
|
app/packages/client/src/components/tax/Tax.js | kslat3r/anpr-dashcam | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { ListGroup, ListGroupItem } from 'react-bootstrap';
import Loading from '../loading/Loading';
import './Tax.css';
class Tax extends Component {
static propTypes = {
details: PropTypes.object.isRequired,
}
shouldComponentUpdate(nextProps) {
if (this.props.details.incoming !== nextProps.details.incoming) {
return true;
}
if (this.props.details.item.numberPlate !== nextProps.details.item.numberPlate) {
return true;
}
return false;
}
render() {
let taxed;
let taxDue = 'UKNOWN';
if (this.props.details.item.dvlaDetails && this.props.details.item.dvlaDetails.taxed !== undefined) {
taxed = this.props.details.item.dvlaDetails.taxed;
taxDue = this.props.details.item.dvlaDetails.taxDue || 'UNKNOWN';
}
return (
<ListGroup className="tax">
<ListGroupItem header="Tax" className={[taxed === undefined ? '' : taxed ? 'valid' : 'invalid']}>
{this.props.details.incoming ? (
<Loading />
) : null}
{taxed === undefined ? 'UNKNOWN' : taxed ? `Due ${taxDue}` : 'Expired'}
</ListGroupItem>
</ListGroup>
)
}
}
export default Tax;
|
app/javascript/mastodon/features/standalone/compose/index.js | unarist/mastodon | import React from 'react';
import ComposeFormContainer from '../../compose/containers/compose_form_container';
import NotificationsContainer from '../../ui/containers/notifications_container';
import LoadingBarContainer from '../../ui/containers/loading_bar_container';
import ModalContainer from '../../ui/containers/modal_container';
export default class Compose extends React.PureComponent {
render () {
return (
<div>
<ComposeFormContainer />
<NotificationsContainer />
<ModalContainer />
<LoadingBarContainer className='loading-bar' />
</div>
);
}
}
|
node_modules/react-native/local-cli/templates/HelloNavigation/views/chat/ChatListScreen.js | solium/swift-react-native-hybrid | 'use strict';
import React, { Component } from 'react';
import {
ActivityIndicator,
Image,
ListView,
Platform,
StyleSheet,
View,
} from 'react-native';
import ListItem from '../../components/ListItem';
import Backend from '../../lib/Backend';
export default class ChatListScreen extends Component {
static navigationOptions = {
title: 'Chats',
header: {
visible: Platform.OS === 'ios',
},
tabBar: {
icon: ({ tintColor }) => (
<Image
// Using react-native-vector-icons works here too
source={require('./chat-icon.png')}
style={[styles.icon, {tintColor: tintColor}]}
/>
),
},
}
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
isLoading: true,
dataSource: ds,
};
}
async componentDidMount() {
const chatList = await Backend.fetchChatList();
this.setState((prevState) => ({
dataSource: prevState.dataSource.cloneWithRows(chatList),
isLoading: false,
}));
}
// Binding the function so it can be passed to ListView below
// and 'this' works properly inside renderRow
renderRow = (name) => {
return (
<ListItem
label={name}
onPress={() => {
// Start fetching in parallel with animating
this.props.navigation.navigate('Chat', {
name: name,
});
}}
/>
);
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.loadingScreen}>
<ActivityIndicator />
</View>
);
}
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
style={styles.listView}
/>
);
}
}
const styles = StyleSheet.create({
loadingScreen: {
backgroundColor: 'white',
paddingTop: 8,
flex: 1,
},
listView: {
backgroundColor: 'white',
},
icon: {
width: 30,
height: 26,
},
});
|
app/javascript/mastodon/features/ui/index.js | honpya/taketodon | import classNames from 'classnames';
import React from 'react';
import NotificationsContainer from './containers/notifications_container';
import PropTypes from 'prop-types';
import LoadingBarContainer from './containers/loading_bar_container';
import TabsBar from './components/tabs_bar';
import ModalContainer from './containers/modal_container';
import { connect } from 'react-redux';
import { Redirect, withRouter } from 'react-router-dom';
import { isMobile } from '../../is_mobile';
import { debounce } from 'lodash';
import { uploadCompose, resetCompose } from '../../actions/compose';
import { refreshHomeTimeline } from '../../actions/timelines';
import { refreshNotifications } from '../../actions/notifications';
import { clearHeight } from '../../actions/height_cache';
import { WrappedSwitch, WrappedRoute } from './util/react_router_helpers';
import UploadArea from './components/upload_area';
import ColumnsAreaContainer from './containers/columns_area_container';
import {
Compose,
Status,
GettingStarted,
KeyboardShortcuts,
PublicTimeline,
CommunityTimeline,
AccountTimeline,
AccountGallery,
HomeTimeline,
Followers,
Following,
Reblogs,
Favourites,
HashtagTimeline,
Notifications,
FollowRequests,
GenericNotFound,
FavouritedStatuses,
ListTimeline,
Blocks,
Mutes,
PinnedStatuses,
Lists,
} from './util/async-components';
import { HotKeys } from 'react-hotkeys';
import { me } from '../../initial_state';
import { defineMessages, injectIntl } from 'react-intl';
// Dummy import, to make sure that <Status /> ends up in the application bundle.
// Without this it ends up in ~8 very commonly used bundles.
import '../../components/status';
const messages = defineMessages({
beforeUnload: { id: 'ui.beforeunload', defaultMessage: 'Your draft will be lost if you leave Mastodon.' },
});
const mapStateToProps = state => ({
isComposing: state.getIn(['compose', 'is_composing']),
hasComposingText: state.getIn(['compose', 'text']) !== '',
dropdownMenuIsOpen: state.getIn(['dropdown_menu', 'openId']) !== null,
});
const keyMap = {
help: '?',
new: 'n',
search: 's',
forceNew: 'option+n',
focusColumn: ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
reply: 'r',
favourite: 'f',
boost: 'b',
mention: 'm',
open: ['enter', 'o'],
openProfile: 'p',
moveDown: ['down', 'j'],
moveUp: ['up', 'k'],
back: 'backspace',
goToHome: 'g h',
goToNotifications: 'g n',
goToLocal: 'g l',
goToFederated: 'g t',
goToStart: 'g s',
goToFavourites: 'g f',
goToPinned: 'g p',
goToProfile: 'g u',
goToBlocked: 'g b',
goToMuted: 'g m',
};
class SwitchingColumnsArea extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
location: PropTypes.object,
onLayoutChange: PropTypes.func.isRequired,
};
state = {
mobile: isMobile(window.innerWidth),
};
componentWillMount () {
window.addEventListener('resize', this.handleResize, { passive: true });
}
componentDidUpdate (prevProps) {
if (![this.props.location.pathname, '/'].includes(prevProps.location.pathname)) {
this.node.handleChildrenContentChange();
}
}
componentWillUnmount () {
window.removeEventListener('resize', this.handleResize);
}
handleResize = debounce(() => {
// The cached heights are no longer accurate, invalidate
this.props.onLayoutChange();
this.setState({ mobile: isMobile(window.innerWidth) });
}, 500, {
trailing: true,
});
setRef = c => {
this.node = c.getWrappedInstance().getWrappedInstance();
}
render () {
const { children } = this.props;
const { mobile } = this.state;
return (
<ColumnsAreaContainer ref={this.setRef} singleColumn={mobile}>
<WrappedSwitch>
<Redirect from='/' to='/getting-started' exact />
<WrappedRoute path='/getting-started' component={GettingStarted} content={children} />
<WrappedRoute path='/keyboard-shortcuts' component={KeyboardShortcuts} content={children} />
<WrappedRoute path='/timelines/home' component={HomeTimeline} content={children} />
<WrappedRoute path='/timelines/public' exact component={PublicTimeline} content={children} />
<WrappedRoute path='/timelines/public/local' component={CommunityTimeline} content={children} />
<WrappedRoute path='/timelines/tag/:id' component={HashtagTimeline} content={children} />
<WrappedRoute path='/timelines/list/:id' component={ListTimeline} content={children} />
<WrappedRoute path='/notifications' component={Notifications} content={children} />
<WrappedRoute path='/favourites' component={FavouritedStatuses} content={children} />
<WrappedRoute path='/pinned' component={PinnedStatuses} content={children} />
<WrappedRoute path='/statuses/new' component={Compose} content={children} />
<WrappedRoute path='/statuses/:statusId' exact component={Status} content={children} />
<WrappedRoute path='/statuses/:statusId/reblogs' component={Reblogs} content={children} />
<WrappedRoute path='/statuses/:statusId/favourites' component={Favourites} content={children} />
<WrappedRoute path='/accounts/:accountId' exact component={AccountTimeline} content={children} />
<WrappedRoute path='/accounts/:accountId/with_replies' component={AccountTimeline} content={children} componentParams={{ withReplies: true }} />
<WrappedRoute path='/accounts/:accountId/followers' component={Followers} content={children} />
<WrappedRoute path='/accounts/:accountId/following' component={Following} content={children} />
<WrappedRoute path='/accounts/:accountId/media' component={AccountGallery} content={children} />
<WrappedRoute path='/follow_requests' component={FollowRequests} content={children} />
<WrappedRoute path='/blocks' component={Blocks} content={children} />
<WrappedRoute path='/mutes' component={Mutes} content={children} />
<WrappedRoute path='/lists' component={Lists} content={children} />
<WrappedRoute component={GenericNotFound} content={children} />
</WrappedSwitch>
</ColumnsAreaContainer>
);
}
}
@connect(mapStateToProps)
@injectIntl
@withRouter
export default class UI extends React.PureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
dispatch: PropTypes.func.isRequired,
children: PropTypes.node,
isComposing: PropTypes.bool,
hasComposingText: PropTypes.bool,
location: PropTypes.object,
intl: PropTypes.object.isRequired,
dropdownMenuIsOpen: PropTypes.bool,
};
state = {
draggingOver: false,
};
handleBeforeUnload = (e) => {
const { intl, isComposing, hasComposingText } = this.props;
if (isComposing && hasComposingText) {
// Setting returnValue to any string causes confirmation dialog.
// Many browsers no longer display this text to users,
// but we set user-friendly message for other browsers, e.g. Edge.
e.returnValue = intl.formatMessage(messages.beforeUnload);
}
}
handleLayoutChange = () => {
// The cached heights are no longer accurate, invalidate
this.props.dispatch(clearHeight());
}
handleDragEnter = (e) => {
e.preventDefault();
if (!this.dragTargets) {
this.dragTargets = [];
}
if (this.dragTargets.indexOf(e.target) === -1) {
this.dragTargets.push(e.target);
}
if (e.dataTransfer && e.dataTransfer.types.includes('Files')) {
this.setState({ draggingOver: true });
}
}
handleDragOver = (e) => {
e.preventDefault();
e.stopPropagation();
try {
e.dataTransfer.dropEffect = 'copy';
} catch (err) {
}
return false;
}
handleDrop = (e) => {
e.preventDefault();
this.setState({ draggingOver: false });
if (e.dataTransfer && e.dataTransfer.files.length === 1) {
this.props.dispatch(uploadCompose(e.dataTransfer.files));
}
}
handleDragLeave = (e) => {
e.preventDefault();
e.stopPropagation();
this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el));
if (this.dragTargets.length > 0) {
return;
}
this.setState({ draggingOver: false });
}
closeUploadModal = () => {
this.setState({ draggingOver: false });
}
handleServiceWorkerPostMessage = ({ data }) => {
if (data.type === 'navigate') {
this.context.router.history.push(data.path);
} else {
console.warn('Unknown message type:', data.type);
}
}
componentWillMount () {
window.addEventListener('beforeunload', this.handleBeforeUnload, false);
document.addEventListener('dragenter', this.handleDragEnter, false);
document.addEventListener('dragover', this.handleDragOver, false);
document.addEventListener('drop', this.handleDrop, false);
document.addEventListener('dragleave', this.handleDragLeave, false);
document.addEventListener('dragend', this.handleDragEnd, false);
if ('serviceWorker' in navigator) {
navigator.serviceWorker.addEventListener('message', this.handleServiceWorkerPostMessage);
}
this.props.dispatch(refreshHomeTimeline());
this.props.dispatch(refreshNotifications());
}
componentDidMount () {
this.hotkeys.__mousetrap__.stopCallback = (e, element) => {
return ['TEXTAREA', 'SELECT', 'INPUT'].includes(element.tagName);
};
}
componentWillUnmount () {
window.removeEventListener('beforeunload', this.handleBeforeUnload);
document.removeEventListener('dragenter', this.handleDragEnter);
document.removeEventListener('dragover', this.handleDragOver);
document.removeEventListener('drop', this.handleDrop);
document.removeEventListener('dragleave', this.handleDragLeave);
document.removeEventListener('dragend', this.handleDragEnd);
}
setRef = c => {
this.node = c;
}
handleHotkeyNew = e => {
e.preventDefault();
const element = this.node.querySelector('.compose-form__autosuggest-wrapper textarea');
if (element) {
element.focus();
}
}
handleHotkeySearch = e => {
e.preventDefault();
const element = this.node.querySelector('.search__input');
if (element) {
element.focus();
}
}
handleHotkeyForceNew = e => {
this.handleHotkeyNew(e);
this.props.dispatch(resetCompose());
}
handleHotkeyFocusColumn = e => {
const index = (e.key * 1) + 1; // First child is drawer, skip that
const column = this.node.querySelector(`.column:nth-child(${index})`);
if (column) {
const status = column.querySelector('.focusable');
if (status) {
status.focus();
}
}
}
handleHotkeyBack = () => {
if (window.history && window.history.length === 1) {
this.context.router.history.push('/');
} else {
this.context.router.history.goBack();
}
}
setHotkeysRef = c => {
this.hotkeys = c;
}
handleHotkeyToggleHelp = () => {
if (this.props.location.pathname === '/keyboard-shortcuts') {
this.context.router.history.goBack();
} else {
this.context.router.history.push('/keyboard-shortcuts');
}
}
handleHotkeyGoToHome = () => {
this.context.router.history.push('/timelines/home');
}
handleHotkeyGoToNotifications = () => {
this.context.router.history.push('/notifications');
}
handleHotkeyGoToLocal = () => {
this.context.router.history.push('/timelines/public/local');
}
handleHotkeyGoToFederated = () => {
this.context.router.history.push('/timelines/public');
}
handleHotkeyGoToStart = () => {
this.context.router.history.push('/getting-started');
}
handleHotkeyGoToFavourites = () => {
this.context.router.history.push('/favourites');
}
handleHotkeyGoToPinned = () => {
this.context.router.history.push('/pinned');
}
handleHotkeyGoToProfile = () => {
this.context.router.history.push(`/accounts/${me}`);
}
handleHotkeyGoToBlocked = () => {
this.context.router.history.push('/blocks');
}
handleHotkeyGoToMuted = () => {
this.context.router.history.push('/mutes');
}
render () {
const { draggingOver } = this.state;
const { children, isComposing, location, dropdownMenuIsOpen } = this.props;
const handlers = {
help: this.handleHotkeyToggleHelp,
new: this.handleHotkeyNew,
search: this.handleHotkeySearch,
forceNew: this.handleHotkeyForceNew,
focusColumn: this.handleHotkeyFocusColumn,
back: this.handleHotkeyBack,
goToHome: this.handleHotkeyGoToHome,
goToNotifications: this.handleHotkeyGoToNotifications,
goToLocal: this.handleHotkeyGoToLocal,
goToFederated: this.handleHotkeyGoToFederated,
goToStart: this.handleHotkeyGoToStart,
goToFavourites: this.handleHotkeyGoToFavourites,
goToPinned: this.handleHotkeyGoToPinned,
goToProfile: this.handleHotkeyGoToProfile,
goToBlocked: this.handleHotkeyGoToBlocked,
goToMuted: this.handleHotkeyGoToMuted,
};
return (
<HotKeys keyMap={keyMap} handlers={handlers} ref={this.setHotkeysRef}>
<div className={classNames('ui', { 'is-composing': isComposing })} ref={this.setRef} style={{ pointerEvents: dropdownMenuIsOpen ? 'none' : null }}>
<TabsBar />
<SwitchingColumnsArea location={location} onLayoutChange={this.handleLayoutChange}>
{children}
</SwitchingColumnsArea>
<NotificationsContainer />
<LoadingBarContainer className='loading-bar' />
<ModalContainer />
<UploadArea active={draggingOver} onClose={this.closeUploadModal} />
</div>
</HotKeys>
);
}
}
|
src/components/options/RangeStackOption.js | rokka-io/rokka-dashboard | import React from 'react'
import PropTypes from 'prop-types'
import FormGroup from '../forms/FormGroup'
import InputRange from '../forms/InputRange'
const RangeStackOption = ({ label, name, value, definitions, required, onChange, error }) => {
// default value may be null
if (value === null || value === undefined) {
value = ''
}
const step = definitions.type === 'number' ? 0.1 : 1
return (
<FormGroup label={label} error={error} required={required}>
<InputRange
onChange={onChange}
defaultValue={definitions.default}
min={definitions.minimum}
max={definitions.maximum}
step={step}
name={name}
value={value}
/>
</FormGroup>
)
}
RangeStackOption.propTypes = {
label: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
definitions: PropTypes.object.isRequired,
required: PropTypes.bool,
value: PropTypes.number,
onChange: PropTypes.func,
error: PropTypes.string
}
export default RangeStackOption
|
app/scripts/MoveableTrack.js | hms-dbmi/4DN_matrix-viewer | import PropTypes from 'prop-types';
import React from 'react';
import DraggableDiv from './DraggableDiv';
import TrackArea from './TrackArea';
// See commented out block in "render()".
//
// const checkMousePosVsEl = (x, y, el) => {
// const bBox = el.getBoundingClientRect();
// return isWithin(
// x, y, bBox.left, bBox.left + bBox.width, bBox.top, bBox.top + bBox.height
// );
// };
class MoveableTrack extends TrackArea {
constructor(props) {
super(props);
this.moveable = true;
}
render() {
return (
<div
ref={(r) => {
this.el = r;
}}
className={this.props.className}
onMouseEnter={this.handleMouseEnter.bind(this)}
onMouseLeave={
(/* e */) => {
// This let to https://github.com/higlass/higlass/issues/263
// Therefore I disabled it.
// if (checkMousePosVsEl(
// e.nativeEvent.clientX, e.nativeEvent.clientY, this.el
// )) {
// return;
// }
this.handleMouseLeave();
}
}
style={{
height: this.props.height,
width: this.props.width,
}}
>
<DraggableDiv
key={this.props.uid}
height={this.props.height}
resizeHandles={
this.props.editable ? this.props.resizeHandles : new Set()
}
sizeChanged={(stuff) =>
this.props.handleResizeTrack(
this.props.uid,
stuff.width,
stuff.height,
)
}
style={{ background: 'transparent' }}
uid={this.props.uid}
width={this.props.width}
/>
{this.props.editable &&
this.getControls(
this.state.controlsVisible || this.props.item.configMenuVisible,
)}
</div>
);
}
}
MoveableTrack.propTypes = {
className: PropTypes.string,
uid: PropTypes.string,
item: PropTypes.object,
height: PropTypes.number,
width: PropTypes.number,
};
export default MoveableTrack;
|
node_modules/babel-plugin-react-transform/test/fixtures/code-class-extends-component-with-render-method/expected.js | TrungSpy/React-Native-SampleProject | import _transformLib from 'transform-lib';
const _components = {
Foo: {
displayName: 'Foo'
}
};
const _transformLib2 = _transformLib({
filename: '%FIXTURE_PATH%',
components: _components,
locals: [],
imports: []
});
function _wrapComponent(id) {
return function (Component) {
return _transformLib2(Component, id);
};
}
import React, { Component } from 'react';
const Foo = _wrapComponent('Foo')(class Foo extends Component {
render() {}
});
|
client/page/options/options-form/url-options.js | johngodley/redirection | /**
* External dependencies
*/
import React from 'react';
import { translate as __ } from 'i18n-calypso';
/**
* Internal dependencies
*/
import { TableRow } from 'component/form-table';
import { Select } from 'wp-plugin-components';
import UrlMonitoring from './url-monitor';
export const queryMatch = () => [
{ value: 'exact', label: __( 'Exact match in any order' ) },
{ value: 'ignore', label: __( 'Ignore all query parameters' ) },
{ value: 'pass', label: __( 'Ignore and pass all query parameters' ) },
];
const expireTimes = () => [
{ value: -1, label: __( 'Never cache' ) },
{ value: 1, label: __( 'An hour' ) },
{ value: 24, label: __( 'A day' ) },
{ value: 24 * 7, label: __( 'A week' ) },
{ value: 0, label: __( 'Forever' ) },
];
function UrlOptions( props ) {
const { settings, onChange, getLink, groups, postTypes } = props;
const { flag_case, flag_trailing, flag_query, auto_target, redirect_cache, cache_key } = settings;
return (
<>
<tr className="redirect-option__row">
<td colSpan={ 2 }>
<h2 className="title">{ __( 'URL' ) }</h2>
</td>
</tr>
<UrlMonitoring
settings={ settings }
onChange={ onChange }
groups={ groups }
getLink={ getLink }
postTypes={ postTypes }
/>
<TableRow title={ __( 'Default URL settings' ) + ':' } url={ getLink( 'options', 'urlsettings' ) }>
<p>{ __( 'Applies to all redirections unless you configure them otherwise.' ) }</p>
<label>
<p>
<input type="checkbox" name="flag_case" onChange={ onChange } checked={ flag_case } />
{ __(
'Case insensitive matches (i.e. {{code}}/Exciting-Post{{/code}} will match {{code}}/exciting-post{{/code}})',
{
components: {
code: <code />,
},
}
) }
</p>
</label>
<label>
<p>
<input
type="checkbox"
name="flag_trailing"
onChange={ onChange }
checked={ flag_trailing }
/>
{ __(
'Ignore trailing slashes (i.e. {{code}}/exciting-post/{{/code}} will match {{code}}/exciting-post{{/code}})',
{
components: {
code: <code />,
},
}
) }
</p>
</label>
</TableRow>
<TableRow title={ __( 'Default query matching' ) + ':' } url={ getLink( 'options', 'querysettings' ) }>
<p>{ __( 'Applies to all redirections unless you configure them otherwise.' ) }</p>
<p>
<Select items={ queryMatch() } name="flag_query" value={ flag_query } onChange={ onChange } />
</p>
<ul>
<li>
{ __(
'Exact - matches the query parameters exactly defined in your source, in any order'
) }
</li>
<li>{ __( 'Ignore - as exact, but ignores any query parameters not in your source' ) }</li>
<li>{ __( 'Pass - as ignore, but also copies the query parameters to the target' ) }</li>
</ul>
</TableRow>
<TableRow title={ __( 'Auto-generate URL' ) + ':' } url={ getLink( 'options', 'autogenerate' ) }>
<input
className="regular-text"
type="text"
value={ auto_target }
name="auto_target"
onChange={ onChange }
/>
<br />
<span className="sub">
{ __(
'Used to auto-generate a URL if no URL is given. Use the special tags {{code}}$dec${{/code}} or {{code}}$hex${{/code}} to insert a unique ID instead',
{
components: {
code: <code />,
},
}
) }
</span>
</TableRow>
<TableRow title={ __( 'HTTP Cache Header' ) } url={ getLink( 'options', 'cache' ) }>
<Select
items={ expireTimes() }
name="redirect_cache"
value={ parseInt( redirect_cache, 10 ) }
onChange={ onChange }
/>{' '}
<span className="sub">
{ __( 'How long to cache redirected 301 URLs (via "Expires" HTTP header)' ) }
</span>
</TableRow>
<TableRow title={ __( 'Redirect Caching' ) } url={ getLink( 'options', 'cache' ) }>
<label>
<input type="checkbox" name="cache_key" onChange={ onChange } checked={ cache_key !== 0 && cache_key !== false } />
<span className="sub">
{ __(
'(beta) Enable caching of redirects via WordPress object cache. Can improve performance. Requires an object cache.'
) }
</span>
</label>
</TableRow>
</>
);
}
export default UrlOptions;
|
src/js/components/ui/ButtonFloating.js | nekuno/client | import PropTypes from 'prop-types';
import React, { Component } from 'react';
export default class ButtonFloating extends Component {
static propTypes = {
onClickHandler: PropTypes.func.isRequired,
icon : PropTypes.string.isRequired
};
handleClick() {
this.props.onClickHandler();
}
render() {
const {icon} = this.props;
return (
<div className="button button-floating" onClick={this.handleClick.bind(this)}>
<span className={'icon icon-' + icon}></span>
</div>
);
}
} |
app/javascript/controllers/graphiql_controller.js | psu-stewardship/scholarsphere | import { Controller } from 'stimulus'
import React from 'react'
import ReactDOM from 'react-dom'
import GraphiQL from 'graphiql'
export default class extends Controller {
connect () {
const graphQLFetcher = (graphQLParams) => {
return fetch(this.data.get('endpoint'), {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(graphQLParams)
}).then(response => response.json())
}
ReactDOM.render(
React.createElement(GraphiQL, { fetcher: graphQLFetcher }),
this.element
)
}
}
|
src/components/Account/CirculationHistory/CircHistorySidebar/index.js | ndlib/usurper | import React from 'react'
import PropTypes from 'prop-types'
import PageLink from 'components/Contentful/PageLink'
import Config from 'shared/Configuration'
import styles from './style.module.css'
const CircHistorySidebar = (props) => {
const calloutLink = {
fields: {
title: 'Report a Problem',
url: `${Config.serviceNowBaseURL}&lib_list_problem=lib_list_general`,
},
}
if (!props.optedIn) {
return null
}
return (
<aside className={'col-md-4 col-sm-5 col-xs-12 right ' + styles.checkoutHistorySidebar}>
<button className={'button callout ' + styles.optOutBtn} onClick={props.onClickOptOut}>
Opt-Out and Delete History
</button>
<PageLink className='button callout' cfPage={calloutLink} />
<h3 id='note'>NOTE:</h3>
<ul>
<li>Items may take up to 24 hours to display or update.</li>
<li>You cannot delete items in your history until 31 days after they are returned.</li>
<li>ILL records cannot be deleted.</li>
<li>Deleted items are lost permanently and cannot be restored.</li>
</ul>
</aside>
)
}
CircHistorySidebar.propTypes = {
optedIn: PropTypes.bool,
onClickOptOut: PropTypes.func.isRequired,
}
export default CircHistorySidebar
|
docs/app/Examples/collections/Table/Types/TableExampleStructured.js | koenvg/Semantic-UI-React | import React from 'react'
import { Icon, Table } from 'semantic-ui-react'
const TableExampleStructured = () => {
return (
<Table celled structured>
<Table.Header>
<Table.Row>
<Table.HeaderCell rowSpan='2'>Name</Table.HeaderCell>
<Table.HeaderCell rowSpan='2'>Type</Table.HeaderCell>
<Table.HeaderCell rowSpan='2'>Files</Table.HeaderCell>
<Table.HeaderCell colSpan='3'>Languages</Table.HeaderCell>
</Table.Row>
<Table.Row>
<Table.HeaderCell>Ruby</Table.HeaderCell>
<Table.HeaderCell>JavaScript</Table.HeaderCell>
<Table.HeaderCell>Python</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>Alpha Team</Table.Cell>
<Table.Cell>Project 1</Table.Cell>
<Table.Cell textAlign='right'>2</Table.Cell>
<Table.Cell textAlign='center'>
<Icon color='green' name='checkmark' size='large' />
</Table.Cell>
<Table.Cell />
<Table.Cell />
</Table.Row>
<Table.Row>
<Table.Cell rowSpan='3'>Beta Team</Table.Cell>
<Table.Cell>Project 1</Table.Cell>
<Table.Cell textAlign='right'>52</Table.Cell>
<Table.Cell textAlign='center'>
<Icon color='green' name='checkmark' size='large' />
</Table.Cell>
<Table.Cell />
<Table.Cell />
</Table.Row>
<Table.Row>
<Table.Cell>Project 2</Table.Cell>
<Table.Cell textAlign='right'>12</Table.Cell>
<Table.Cell />
<Table.Cell textAlign='center'>
<Icon color='green' name='checkmark' size='large' />
</Table.Cell>
<Table.Cell />
</Table.Row>
<Table.Row>
<Table.Cell>Project 3</Table.Cell>
<Table.Cell textAlign='right'>21</Table.Cell>
<Table.Cell textAlign='center'>
<Icon color='green' name='checkmark' size='large' />
</Table.Cell>
<Table.Cell />
<Table.Cell />
</Table.Row>
</Table.Body>
</Table>
)
}
export default TableExampleStructured
|
pages/discover-more/roadmap.js | AndriusBil/material-ui | // @flow
import React from 'react';
import withRoot from 'docs/src/modules/components/withRoot';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import markdown from '../../ROADMAP.md';
function Page() {
return <MarkdownDocs markdown={markdown} sourceLocation="/ROADMAP.md" />;
}
export default withRoot(Page);
|
src/Toolbar/macOs/Nav/index.js | gabrielbull/react-desktop | import React, { Component } from 'react';
import { Style } from 'radium';
import Dimension, { dimensionPropTypes } from '../../../style/dimension';
import WindowFocus from '../../../windowFocus';
const styles = {
nav: {
display: 'flex',
alignItems: 'center'
}
};
@Dimension({ height: '54px' })
@WindowFocus()
class Nav extends Component {
static propTypes = {
...dimensionPropTypes
};
render() {
const { children, style, isWindowFocused, ...props } = this.props;
let componentStyle = { ...styles.nav };
let fillOpacity = '.8';
if (!isWindowFocused) {
componentStyle.opacity = '.5';
fillOpacity = '.3';
}
return (
<div style={{ ...componentStyle, ...style }} {...props}>
<Style
scopeSelector="._reactDesktop-Toolbar-Nav-Item-SVG"
rules={{
'a svg *': {
fill: '#363336',
fillOpacity
},
'a:active svg *': {
fill: '#1e1c1e',
fillOpacity: '.9'
}
}}
/>
<Style
scopeSelector="._reactDesktop-Toolbar-Nav-Item-SVG._selected"
rules={{
'a svg *': {
fill: '#007bfa',
fillOpacity: '1'
},
'a:active svg *': {
fill: '#003dd6',
fillOpacity: '1'
}
}}
/>
{children}
</div>
);
}
}
export default Nav;
|
packages/mineral-ui-icons/src/IconFilter3.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconFilter3(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M21 1H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zM3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm14 8v-1.5c0-.83-.67-1.5-1.5-1.5.83 0 1.5-.67 1.5-1.5V7a2 2 0 0 0-2-2h-4v2h4v2h-2v2h2v2h-4v2h4a2 2 0 0 0 2-2z"/>
</g>
</Icon>
);
}
IconFilter3.displayName = 'IconFilter3';
IconFilter3.category = 'image';
|
examples/universal/server/server.js | bnwan/redux | /* eslint-disable no-console, no-use-before-define */
import path from 'path';
import Express from 'express';
import qs from 'qs';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackConfig from '../webpack.config';
import React from 'react';
import { Provider } from 'react-redux';
import configureStore from '../common/store/configureStore';
import App from '../common/containers/App';
import { fetchCounter } from '../common/api/counter';
const app = new Express();
const port = 3000;
// Use this middleware to set up hot module reloading via webpack.
const compiler = webpack(webpackConfig);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
// This is fired every time the server side receives a request
app.use(handleRender);
function handleRender(req, res) {
// Query our mock API asynchronously
fetchCounter(apiResult => {
// Read the counter from the request, if provided
const params = qs.parse(req.query);
const counter = parseInt(params.counter, 10) || apiResult || 0;
// Compile an initial state
const initialState = { counter };
// Create a new Redux store instance
const store = configureStore(initialState);
// Render the component to a string
const html = React.renderToString(
<Provider store={store}>
{ () => <App/> }
</Provider>);
// Grab the initial state from our Redux store
const finalState = store.getState();
// Send the rendered page back to the client
res.send(renderFullPage(html, finalState));
});
}
function renderFullPage(html, initialState) {
return `
<!doctype html>
<html>
<head>
<title>Redux Universal Example</title>
</head>
<body>
<div id="app">${html}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
</script>
<script src="/static/bundle.js"></script>
</body>
</html>
`;
}
app.listen(port, (error) => {
if (error) {
console.error(error);
} else {
console.info(`==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`);
}
});
|
js/jqwidgets/demos/react/app/navigationbar/defaultfunctionality/app.js | luissancheza/sice | import React from 'react';
import ReactDOM from 'react-dom';
import JqxNavigationBar from '../../../jqwidgets-react/react_jqxnavigationbar.js';
class App extends React.Component {
render () {
let innerHtml =
'<div>' +
'Early History of the Internet</div>' +
'</div>' +
'<div>' +
'<ul>' +
'<li>1961 First packet-switching papers</li>' +
'<li>1966 Merit Network founded</li>' +
'<li>1966 ARPANET planning starts</li>' +
'<li>1969 ARPANET carries its first packets</li>' +
'<li>1970 Mark I network at NPL (UK)</li>' +
'<li>1970 Network Information Center (NIC)</li>' +
'<li>1971 Merit Network\'s packet-switched network operational</li>' +
'<li>1971 Tymnet packet-switched network</li>' +
'<li>1972 Internet Assigned Numbers Authority (IANA) established</li>' +
'<li>1973 CYCLADES network demonstrated</li>' +
'<li>1974 Telenet packet-switched network</li>' +
'<li>1976 X.25 protocol approved</li>' +
'<li>1979 Internet Activities Board (IAB)</li>' +
'<li>1980 USENET news using UUCP</li>' +
'<li>1980 Ethernet standard introduced</li>' +
'<li>1981 BITNET established</li>' +
'</ul>' +
'</div>' +
'<div>' +
'Merging the networks and creating the Internet</div>' +
'<div>' +
'<ul>' +
'<li>1981 Computer Science Network (CSNET)</li>' +
'<li>1982 TCP/IP protocol suite formalized</li>' +
'<li>1982 Simple Mail Transfer Protocol (SMTP)</li>' +
'<li>1983 Domain Name System (DNS)</li>' +
'<li>1983 MILNET split off from ARPANET</li>' +
'<li>1986 NSFNET with 56 kbit/s links</li>' +
'<li>1986 Internet Engineering Task Force (IETF)</li>' +
'<li>1987 UUNET founded</li>' +
'<li>1988 NSFNET upgraded to 1.5 Mbit/s (T1)</li>' +
'<li>1988 OSI Reference Model released</li>' +
'<li>1988 Morris worm</li>' +
'<li>1989 Border Gateway Protocol (BGP)</li>' +
'<li>1989 PSINet founded, allows commercial traffic</li>' +
'<li>1989 Federal Internet Exchanges (FIXes)</li>' +
'<li>1990 GOSIP (without TCP/IP)</li>' +
'<li>1990 ARPANET decommissioned</li>' +
'</ul>' +
'</div>' +
'<div>' +
'Popular Internet services</div>' +
'<div>' +
'<ul>' +
'<li>1990 IMDb Internet movie database</li>' +
'<li>1995 Amazon.com online retailer</li>' +
'<li>1995 eBay online auction and shopping</li>' +
'<li>1995 Craigslist classified advertisements</li>' +
'<li>1996 Hotmail free web-based e-mail</li>' +
'<li>1997 Babel Fish automatic translation</li>' +
'<li>1998 Google Search</li>' +
'<li>1999 Napster peer-to-peer file sharing</li>' +
'<li>2001 Wikipedia, the free encyclopedia</li>' +
'<li>2003 LinkedIn business networking</li>' +
'<li>2003 Myspace social networking site</li>' +
'<li>2003 Skype Internet voice calls</li>' +
'<li>2003 iTunes Store</li>' +
'<li>2004 Facebook social networking site</li>' +
'<li>2004 Podcast media file series</li>' +
'<li>2004 Flickr image hosting</li>' +
'<li>2005 YouTube video sharing</li>' +
'<li>2005 Google Earth virtual globe</li>' +
'</ul>' +
'</div>';
return (
<JqxNavigationBar template={innerHtml} width={400} height={460}/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/docs/components/animate/AnimateBoxesExample.js | karatechops/grommet-docs | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import Tiles from 'grommet/components/Tiles';
import Box from 'grommet/components/Box';
import Button from 'grommet/components/Button';
import Animate from 'grommet/components/Animate';
import AddIcon from 'grommet/components/icons/base/Add';
import SubtractIcon from 'grommet/components/icons/base/Subtract';
import Example from '../../Example';
export default class AnimateBoxesExample extends Component {
constructor (props) {
super(props);
this.state = {
boxes: [0,1,2]
};
}
render () {
const { boxes } = this.state;
return (
<Box pad={{between: 'small'}}>
<Box direction='row'>
<Button
icon={<AddIcon />}
onClick={() => this.setState({boxes: [...boxes, boxes.length]})}
/>
<Button
icon={<SubtractIcon />}
onClick={() => this.setState({boxes: boxes.slice(0, -1)})}
/>
</Box>
<Example code={
<Animate
enter={{ animation: 'slide-up', duration: 1000 }}
component={Tiles}
>
{
boxes.map((c, i) => {
return (
<Box
key={`box-${i}`}
style={{ width: 50, height: 50 }}
colorIndex="brand"
/>
);
})
}
</Animate>
} />
</Box>
);
}
};
|
examples/real-world/containers/Root.js | nickhudkins/redux | import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { Router, Route } from 'react-router';
import configureStore from '../store/configureStore';
import App from './App';
import UserPage from './UserPage';
import RepoPage from './RepoPage';
const store = configureStore();
export default class Root extends Component {
render() {
return (
<div>
<Provider store={store}>
{() =>
<Router history={this.props.history}>
<Route path='/' component={App}>
<Route path='/:login/:name'
component={RepoPage} />
<Route path='/:login'
component={UserPage} />
</Route>
</Router>
}
</Provider>
</div>
);
}
}
|
packages/core/src/icons/components/FirstPage.js | iCHEF/gypcrete | import React from 'react';
export default function SvgFirstPage(props) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="-1612 -5393 32 32"
width="1em"
height="1em"
{...props}
>
<path
data-name="\u9577\u65B9\u5F62 9343"
fill="transparent"
d="M-1612-5393h32v32h-32z"
/>
<path
data-name="\u5408\u4F53 514"
d="M-1598.799-5377l8.485-8.485 1.415 1.414-7.071 7.071 7.07 7.071-1.414 1.414z"
/>
<path data-name="\u9577\u65B9\u5F62 9346" d="M-1604-5385h2v16h-2z" />
</svg>
);
}
|
src/containers/Settings/index.js | ayastreb/money-tracker | import React from 'react';
import CurrencyInput from './Currency/Input';
import CurrenchExchangeRate from './Currency/ExchangeRate';
import DataExport from './DataExport';
import DataImport from './DataImport';
import User from './User';
import CollapsibleSection from '../../components/CollapsibleSection';
const Settings = () => (
<div className="container-full-page mt-settings">
<CollapsibleSection name="settings_currency" label="Currency">
<CurrencyInput />
<CurrenchExchangeRate />
</CollapsibleSection>
<CollapsibleSection name="settings_import" label="Data Import">
<DataImport />
</CollapsibleSection>
<CollapsibleSection name="settings_export" label="Data Export">
<DataExport />
</CollapsibleSection>
<CollapsibleSection name="settings_user" label="User">
<User />
</CollapsibleSection>
</div>
);
export default Settings;
|
client/app/scripts/components/node-details/node-details-control-button.js | paulbellamy/scope | import React from 'react';
import { connect } from 'react-redux';
import { doControl } from '../../actions/app-actions';
class NodeDetailsControlButton extends React.Component {
constructor(props, context) {
super(props, context);
this.handleClick = this.handleClick.bind(this);
}
render() {
let className = `node-control-button fa ${this.props.control.icon}`;
if (this.props.pending) {
className += ' node-control-button-pending';
}
return (
<span className={className} title={this.props.control.human} onClick={this.handleClick} />
);
}
handleClick(ev) {
ev.preventDefault();
this.props.dispatch(doControl(this.props.nodeId, this.props.control));
}
}
// Using this instead of PureComponent because of props.dispatch
export default connect()(NodeDetailsControlButton);
|
universal/containers/root/root.prod.js | hex22a/roland | import React, { Component } from 'react';
import { Router } from 'react-router';
export default class Root extends Component {
render() {
const { routes, history, render, environment } = this.props;
return (
<div>
<Router
history={history}
render={render}
routes={routes}
environment={environment}
/>
</div>
);
}
} |
src/svg-icons/editor/border-outer.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorBorderOuter = (props) => (
<SvgIcon {...props}>
<path d="M13 7h-2v2h2V7zm0 4h-2v2h2v-2zm4 0h-2v2h2v-2zM3 3v18h18V3H3zm16 16H5V5h14v14zm-6-4h-2v2h2v-2zm-4-4H7v2h2v-2z"/>
</SvgIcon>
);
EditorBorderOuter = pure(EditorBorderOuter);
EditorBorderOuter.displayName = 'EditorBorderOuter';
EditorBorderOuter.muiName = 'SvgIcon';
export default EditorBorderOuter;
|
src/svg-icons/file/cloud-upload.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let FileCloudUpload = (props) => (
<SvgIcon {...props}>
<path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM14 13v4h-4v-4H7l5-5 5 5h-3z"/>
</SvgIcon>
);
FileCloudUpload = pure(FileCloudUpload);
FileCloudUpload.displayName = 'FileCloudUpload';
FileCloudUpload.muiName = 'SvgIcon';
export default FileCloudUpload;
|
test/react/app.js | jkoomjian/GlobalMobile | // import React from 'react';
// export default App; |
webpack/scenes/Subscriptions/components/SubscriptionsTable/SubscriptionsTableSchema.js | mccun934/katello | /* eslint-disable import/prefer-default-export */
import React from 'react';
import { Icon } from 'patternfly-react';
import { Link } from 'react-router-dom';
import { urlBuilder } from 'foremanReact/common/urlHelpers';
import { translate as __ } from 'foremanReact/common/I18n';
import { entitlementsInlineEditFormatter } from '../../../../move_to_foreman/components/common/table/formatters/EntitlementsInlineEditFormatter';
import { subscriptionTypeFormatter } from './SubscriptionTypeFormatter';
import {
headerFormatter,
cellFormatter,
selectionHeaderCellFormatter,
collapseableAndSelectionCellFormatter,
} from '../../../../move_to_foreman/components/common/table';
function getEntitlementsFormatter(inlineEditController, canManageSubscriptionAllocations) {
if (canManageSubscriptionAllocations) {
return entitlementsInlineEditFormatter(inlineEditController);
}
return cellFormatter;
}
export const createSubscriptionsTableSchema = (
inlineEditController,
selectionController,
groupingController,
hasPermission,
) => [
{
property: 'select',
header: {
label: __('Select all rows'),
formatters: [label => selectionHeaderCellFormatter(selectionController, label)],
},
cell: {
formatters: [
(value, additionalData) => {
// eslint-disable-next-line no-param-reassign
additionalData.disabled = additionalData.rowData.available === -1;
return collapseableAndSelectionCellFormatter(
groupingController,
selectionController,
additionalData,
);
},
],
},
},
{
property: 'id',
header: {
label: __('Name'),
formatters: [headerFormatter],
},
cell: {
formatters: [
(value, { rowData }) => (
<td>
<Link to={urlBuilder('subscriptions', '', rowData.id)}>{rowData.name}</Link>
</td>
),
],
},
},
{
property: 'type',
header: {
label: __('Type'),
formatters: [headerFormatter],
},
cell: {
formatters: [subscriptionTypeFormatter],
},
},
{
property: 'product_id',
header: {
label: __('SKU'),
formatters: [headerFormatter],
},
cell: {
formatters: [cellFormatter],
},
},
{
property: 'contract_number',
header: {
label: __('Contract'),
formatters: [headerFormatter],
},
cell: {
formatters: [cellFormatter],
},
}, // TODO: use date formatter from tomas' PR
{
property: 'start_date',
header: {
label: __('Start Date'),
formatters: [headerFormatter],
},
cell: {
formatters: [cellFormatter],
},
},
{
property: 'end_date',
header: {
label: __('End Date'),
formatters: [headerFormatter],
},
cell: {
formatters: [cellFormatter],
},
},
{
property: 'virt_who',
header: {
label: __('Requires Virt-Who'),
formatters: [headerFormatter],
},
cell: {
formatters: [
(value, { rowData }) => (
<td>
<Icon type="fa" name={rowData.virt_who ? 'check' : 'minus'} />
</td>
),
],
},
},
{
property: 'consumed',
header: {
label: __('Consumed'),
formatters: [headerFormatter],
},
cell: {
formatters: [cellFormatter],
},
},
{
property: 'quantity',
header: {
label: __('Entitlements'),
formatters: [headerFormatter],
},
cell: {
formatters: [getEntitlementsFormatter(inlineEditController, hasPermission)],
},
},
];
|
src/components/button.js | zhangsichu/HybridAppReduxVsIonic | import React from 'react'
import styles from './styles.scss'
import arrowRight from '../images/arrowRight.png'
function Button ({ label, href }) {
return (
<a className={styles.button} href={href}>
<span>{label}</span>
<img src={arrowRight} />
</a>
)
}
Button.propTypes = {
label: React.PropTypes.string.isRequired,
href: React.PropTypes.string.isRequired
}
export default Button
|
src/components/Tabs.js | georgeOsdDev/react-draggable-tab | import React from 'react';
import ReactDom from 'react-dom';
import PropTypes from 'prop-types';
import _ from 'lodash';
import invariant from 'invariant';
import classNames from 'classnames';
import Mousetrap from 'mousetrap';
import CustomDraggable from './CustomDraggable';
import TabStyles from './TabStyles';
import TabContainer from './TabContainer';
import CloseIcon from './CloseIcon';
import StyleOverride from '../helpers/styleOverride';
import Utils from '../helpers/utils';
function tabStateFromProps(props) {
const tabs = [];
let idx = 0;
React.Children.forEach(props.tabs, (tab) => {
invariant(
tab.key,
'There should be unique key in each Tab',
);
tabs[idx] = tab;
idx += 1;
});
return { tabs };
}
class Tabs extends React.Component {
constructor(props) {
super(props);
const { tabs } = tabStateFromProps(this.props);
let selectedTab = '';
if (this.props.selectedTab) {
selectedTab = this.props.selectedTab; // eslint-disable-line prefer-destructuring
} else if (this.props.tabs) {
selectedTab = this.props.tabs[0].key;
}
const hoveredTab = '';
const closedTabs = [];
this.state = {
tabs,
selectedTab,
hoveredTab,
closedTabs,
};
// Dom positons
// do not save in state
this.startPositions = [];
this.dragging = false;
}
isClosed(key) {
return this.state.closedTabs.indexOf(key) > -1;
}
getIndexOfTabByKey(key) {
return _.findIndex(this.state.tabs, tab => tab.key === key);
}
getNextTabKey(key) {
let nextKey;
const current = this.getIndexOfTabByKey(key);
if (current + 1 < this.state.tabs.length) {
nextKey = this.state.tabs[current + 1].key;
if (this.isClosed(nextKey)) {
nextKey = this.getNextTabKey(nextKey);
}
}
return nextKey;
}
getPrevTabKey(key) {
let prevKey;
const current = this.getIndexOfTabByKey(key);
if (current > 0) {
prevKey = this.state.tabs[current - 1].key;
if (this.isClosed(prevKey)) {
prevKey = this.getPrevTabKey(prevKey);
}
}
return prevKey;
}
getCurrentOpenTabs() {
return this.getOpenTabs(this.state.tabs);
}
getOpenTabs(tabs) {
return _.filter(tabs, tab => !this.isClosed(tab.key));
}
moveTabPosition(key1, key2) {
const t1 = this.getIndexOfTabByKey(key1);
const t2 = this.getIndexOfTabByKey(key2);
return Utils.slideArray(this.state.tabs, t1, t2);
}
saveStartPositions() {
// Do not save in state
this.startPositions = _.map(this.state.tabs, (tab) => {
const el = ReactDom.findDOMNode(this.refs[tab.key]);
const pos = el ? el.getBoundingClientRect() : {};
return {
key: tab.key,
pos,
};
});
}
// eslint-disable-next-line class-methods-use-this
cancelEventSafety(e) {
const ev = e;
if (typeof e.preventDefault !== 'function') {
ev.preventDefault = () => {
};
}
if (typeof e.stopPropagation !== 'function') {
ev.stopPropagation = () => {
};
}
ev.preventDefault();
ev.stopPropagation();
return ev;
}
// eslint-disable-next-line class-methods-use-this
componentWillMount() {
}
componentDidMount() {
this.saveStartPositions();
this.bindShortcuts();
}
componentWillUnmount() {
this.constructor.unbindShortcuts();
}
componentWillReceiveProps(nextProps) {
const newState = tabStateFromProps(nextProps);
if (nextProps.selectedTab !== 'undefined') {
newState.selectedTab = nextProps.selectedTab;
}
// reset closedTabs, respect props from application
newState.closedTabs = [];
this.setState(newState);
}
// eslint-disable-next-line class-methods-use-this
componentWillUpdate() {
}
componentDidUpdate() {
this.saveStartPositions();
}
bindShortcuts() {
if (this.props.shortCutKeys) {
if (this.props.shortCutKeys.close) {
Mousetrap.bind(this.props.shortCutKeys.close, (e) => {
const ev = this.cancelEventSafety(e);
if (this.state.selectedTab) {
this.handleCloseButtonClick(this.state.selectedTab, ev);
}
});
}
if (this.props.shortCutKeys.create) {
Mousetrap.bind(this.props.shortCutKeys.create, (e) => {
const ev = this.cancelEventSafety(e);
this.handleAddButtonClick(ev);
});
}
if (this.props.shortCutKeys.moveRight) {
Mousetrap.bind(this.props.shortCutKeys.moveRight, (e) => {
const ev = this.cancelEventSafety(e);
this.moveRight(ev);
});
}
if (this.props.shortCutKeys.moveLeft) {
Mousetrap.bind(this.props.shortCutKeys.moveLeft, (e) => {
const ev = this.cancelEventSafety(e);
this.moveLeft(ev);
});
}
}
}
static unbindShortcuts() {
Mousetrap.reset();
}
handleDragStart() {
this.dragging = true;
}
handleDrag(key, e) {
const deltaX = (e.pageX || e.clientX);
_.each(this.startPositions, (pos) => {
const tempMoved = pos.moved || 0;
const shoudBeSwap =
key !== pos.key &&
pos.pos.left + tempMoved < deltaX &&
deltaX < pos.pos.right + tempMoved;
if (shoudBeSwap) {
const idx1 = this.getIndexOfTabByKey(key);
const idx2 = this.getIndexOfTabByKey(pos.key);
const minus = idx1 > idx2 ? 1 : -1;
const movePx = (minus * (pos.pos.right - pos.pos.left)) - tempMoved;
ReactDom.findDOMNode(this.refs[pos.key]).style.transform = `translate(${movePx}px, 0px)`;
this.startPositions[idx2].moved = movePx;
}
});
}
handleDragStop(key, e) {
const deltaX = (e.pageX || e.clientX);
let swapedTabs = null;
_.each(this.startPositions, (pos) => {
const shoudBeSwap =
key !== pos.key &&
pos.pos.left < deltaX &&
deltaX < pos.pos.right;
if (shoudBeSwap) {
swapedTabs = this.moveTabPosition(key, pos.key);
}
ReactDom.findDOMNode(this.refs[pos.key]).style.transform = 'translate(0px, 0px)';
});
const nextTabs = swapedTabs || this.state.tabs;
const newState = {
tabs: nextTabs,
selectedTab: key,
};
this.dragging = false;
this.setState(newState, () => {
if (swapedTabs) {
this.props.onTabPositionChange(e, key, this.getOpenTabs(nextTabs));
}
});
}
handleTabClick(key, e) {
const isBehindTab = key !== this.state.selectedTab;
const idx = this.getIndexOfTabByKey(key);
const isDragAfter = this.startPositions[idx].moved !== 0;
if (isBehindTab && isDragAfter && this.props.keepSelectedTab) {
e.preventDefault();
return;
}
const classes = (e.target.getAttribute('class') || '').split(' ');
if (classes.indexOf('rdTabCloseIcon') > -1) {
this.cancelEventSafety(e);
} else {
this.setState({ selectedTab: key }, () => {
this.props.onTabSelect(e, key, this.getCurrentOpenTabs());
});
}
}
handleMouseEnter(key, onMouseEnter, e) {
if (!this.dragging) {
this.setState({
hoveredTab: key,
}, () => {
if (_.isFunction(onMouseEnter)) {
onMouseEnter(e);
}
});
}
}
handleMouseLeave(key, onMouseLeave, e) {
if (!this.dragging) {
if (this.state.hoveredTab === key) {
this.setState({
hoveredTab: '',
}, () => {
if (_.isFunction(onMouseLeave)) {
onMouseLeave(e);
}
});
} else if (_.isFunction(onMouseLeave)) {
onMouseLeave(e);
}
}
}
handleCloseButtonClick(key, e) {
const ev = this.cancelEventSafety(e);
const doClose = () => {
let nextSelected;
if (this.state.selectedTab === key) {
nextSelected = this.getNextTabKey(key);
if (!nextSelected) {
nextSelected = this.getPrevTabKey(key);
}
} else {
nextSelected = this.state.selectedTab;
}
const shoudBeNotifyTabChange = this.state.selectedTab !== nextSelected;
this.setState({
closedTabs: this.state.closedTabs.concat([key]),
selectedTab: nextSelected,
}, () => {
const currentOpenTabs = this.getCurrentOpenTabs();
this.props.onTabClose(ev, key, currentOpenTabs);
if (shoudBeNotifyTabChange) {
this.props.onTabSelect(ev, nextSelected, currentOpenTabs);
}
});
};
if (this.props.shouldTabClose(ev, key)) {
doClose();
}
}
handleAddButtonClick(e) {
this.props.onTabAddButtonClick(e, this.getCurrentOpenTabs());
}
moveRight(e) {
let nextSelected = this.getNextTabKey(this.state.selectedTab);
if (!nextSelected) {
nextSelected = this.props.tabs[0] ? this.props.tabs[0].key : '';
}
if (nextSelected !== this.state.selectedTab) {
this.setState({ selectedTab: nextSelected }, () => {
this.props.onTabSelect(e, nextSelected, this.getCurrentOpenTabs());
});
}
}
moveLeft(e) {
let nextSelected = this.getPrevTabKey(this.state.selectedTab);
if (!nextSelected) {
nextSelected = _.last(this.props.tabs) ? _.last(this.props.tabs).key : '';
}
if (nextSelected !== this.state.selectedTab) {
this.setState({ selectedTab: nextSelected }, () => {
this.props.onTabSelect(e, nextSelected, this.getCurrentOpenTabs());
});
}
}
getCloseButton(tab, style, classes, hoverStyleBase) {
if (tab.props.unclosable) {
return '';
}
const onHoverStyle = StyleOverride.merge(hoverStyleBase, tab.props.tabStyles.tabCloseIconOnHover);
return (<CloseIcon
style={style}
hoverStyle={onHoverStyle}
className={classes}
onClick={this.handleCloseButtonClick.bind(this, tab.key)}>×</CloseIcon>);
}
render() {
// override inline tabs styles
const tabInlineStyles = {};
tabInlineStyles.tabWrapper = StyleOverride.merge(TabStyles.tabWrapper, this.props.tabsStyles.tabWrapper);
tabInlineStyles.tabBar = StyleOverride.merge(TabStyles.tabBar, this.props.tabsStyles.tabBar);
tabInlineStyles.tabBarAfter = StyleOverride.merge(TabStyles.tabBarAfter, this.props.tabsStyles.tabBarAfter);
tabInlineStyles.tab = StyleOverride.merge(TabStyles.tab, this.props.tabsStyles.tab);
tabInlineStyles.tabBefore = StyleOverride.merge(TabStyles.tabBefore, this.props.tabsStyles.tabBefore);
tabInlineStyles.tabAfter = StyleOverride.merge(TabStyles.tabAfter, this.props.tabsStyles.tabAfter);
tabInlineStyles.tabTitle = StyleOverride.merge(TabStyles.tabTitle, this.props.tabsStyles.tabTitle);
tabInlineStyles.tabCloseIcon = StyleOverride.merge(TabStyles.tabCloseIcon, this.props.tabsStyles.tabCloseIcon);
tabInlineStyles.tabCloseIconOnHover = StyleOverride.merge(TabStyles.tabCloseIconOnHover, this.props.tabsStyles.tabCloseIconOnHover);
tabInlineStyles.tabActive = StyleOverride.merge(TabStyles.tabActive, this.props.tabsStyles.tabActive);
tabInlineStyles.tabTitleActive = StyleOverride.merge(TabStyles.tabTitleActive, this.props.tabsStyles.tabTitleActive);
tabInlineStyles.tabBeforeActive = StyleOverride.merge(TabStyles.tabBeforeActive, this.props.tabsStyles.tabBeforeActive);
tabInlineStyles.tabAfterActive = StyleOverride.merge(TabStyles.tabAfterActive, this.props.tabsStyles.tabAfterActive);
tabInlineStyles.tabOnHover = StyleOverride.merge(TabStyles.tabOnHover, this.props.tabsStyles.tabOnHover);
tabInlineStyles.tabTitleOnHover = StyleOverride.merge(TabStyles.tabTitleOnHover, this.props.tabsStyles.tabTitleOnHover);
tabInlineStyles.tabBeforeOnHover = StyleOverride.merge(TabStyles.tabBeforeOnHover, this.props.tabsStyles.tabBeforeOnHover);
tabInlineStyles.tabAfterOnHover = StyleOverride.merge(TabStyles.tabAfterOnHover, this.props.tabsStyles.tabAfterOnHover);
// append tabs classNames
const xtabClassNames = {};
xtabClassNames.tabWrapper = classNames('rdTabWrapper', this.props.tabsClassNames.tabWrapper);
xtabClassNames.tabBar = classNames('rdTabBar', this.props.tabsClassNames.tabBar);
xtabClassNames.tabBarAfter = classNames('rdTabBarAfter', this.props.tabsClassNames.tabBarAfter);
xtabClassNames.tab = classNames('rdTab', this.props.tabsClassNames.tab);
xtabClassNames.tabBefore = classNames('rdTabBefore', this.props.tabsClassNames.tabBefore);
xtabClassNames.tabAfter = classNames('rdTabAfter', this.props.tabsClassNames.tabAfter);
xtabClassNames.tabTitle = classNames('rdTabTitle', this.props.tabsClassNames.tabTitle);
xtabClassNames.tabBeforeTitle = classNames('rdTabBeforeTitle', this.props.tabsClassNames.tabBeforeTitle);
xtabClassNames.tabAfterTitle = classNames('rdTabAfterTitle', this.props.tabsClassNames.tabAfterTitle);
xtabClassNames.tabCloseIcon = classNames('rdTabCloseIcon', this.props.tabsClassNames.tabCloseIcon);
const content = [];
const tabs = _.map(this.state.tabs, (tab) => {
if (this.state.closedTabs.indexOf(tab.key) > -1) {
return '';
}
const {
beforeTitle,
title,
afterTitle,
tabClassNames,
tabStyles,
containerStyle,
hiddenContainerStyle,
onMouseEnter,
onMouseLeave,
unclosable,
...others
} = tab.props;
// override inline each tab styles
let tabStyle = StyleOverride.merge(tabInlineStyles.tab, tabStyles.tab);
let tabBeforeStyle = StyleOverride.merge(tabInlineStyles.tabBefore, tabStyles.tabBefore);
let tabAfterStyle = StyleOverride.merge(tabInlineStyles.tabAfter, tabStyles.tabAfter);
let tabTiteleStyle = StyleOverride.merge(tabInlineStyles.tabTitle, tabStyles.tabTitle);
const tabCloseIconStyle = StyleOverride.merge(tabInlineStyles.tabCloseIcon, tabStyles.tabCloseIcon);
let tabClasses = classNames(xtabClassNames.tab, tabClassNames.tab);
const tabBeforeClasses = classNames(xtabClassNames.tabBefore, tabClassNames.tabBefore);
const tabAfterClasses = classNames(xtabClassNames.tabAfter, tabClassNames.tabAfter);
const tabTitleClasses = classNames(xtabClassNames.tabTitle, tabClassNames.tabTitle);
const tabBeforeTitleClasses = classNames(xtabClassNames.tabBeforeTitle, tabClassNames.tabBeforeTitle);
const tabAfterTitleClasses = classNames(xtabClassNames.tabAfterTitle, tabClassNames.tabAfterTitle);
const tabCloseIconClasses = classNames(xtabClassNames.tabCloseIcon, tabClassNames.tabCloseIcon);
if (this.state.selectedTab === tab.key) {
tabStyle = StyleOverride.merge(StyleOverride.merge(tabInlineStyles.tab, tabInlineStyles.tabActive), tabStyles.tabActive);
tabBeforeStyle = StyleOverride.merge(StyleOverride.merge(tabInlineStyles.tabBefore, tabInlineStyles.tabBeforeActive), tabStyles.tabBeforeActive);
tabAfterStyle = StyleOverride.merge(StyleOverride.merge(tabInlineStyles.tabAfter, tabInlineStyles.tabAfterActive), tabStyles.tabAfterActive);
tabTiteleStyle = StyleOverride.merge(StyleOverride.merge(tabInlineStyles.tabTitle, tabInlineStyles.tabTitleActive), tabStyles.tabTitleActive);
tabClasses = classNames(tabClasses, 'rdTabActive', this.props.tabsClassNames.tabActive, tabClassNames.tabActive);
content.push(<TabContainer key={`tabContainer#${tab.key}`} selected={true}
style={containerStyle}>{tab}</TabContainer>);
} else {
if (this.state.hoveredTab === tab.key) {
tabStyle = StyleOverride.merge(StyleOverride.merge(tabStyle, tabInlineStyles.tabOnHover), tabStyles.tabOnHover);
tabBeforeStyle = StyleOverride.merge(StyleOverride.merge(tabBeforeStyle, tabInlineStyles.tabBeforeOnHover), tabStyles.tabBeforeOnHover);
tabAfterStyle = StyleOverride.merge(StyleOverride.merge(tabAfterStyle, tabInlineStyles.tabAfterOnHover), tabStyles.tabAfterOnHover);
tabTiteleStyle = StyleOverride.merge(StyleOverride.merge(tabTiteleStyle, tabInlineStyles.tabTitleOnHover), tabStyles.tabTitleOnHover);
tabClasses = classNames(tabClasses, 'rdTabHover', this.props.tabsClassNames.tabHover, tabClassNames.tabHover);
}
content.push(<TabContainer
key={`tabContainer#${tab.key}`}
selected={false}
style={containerStyle}
hiddenStyle={hiddenContainerStyle}>{tab}</TabContainer>);
}
// title will be shorten with inline style
// {
// overflow: 'hidden',
// whiteSpace: 'nowrap',
// textOverflow: 'ellipsis'
// }
const extraAttribute = {};
if (typeof title === 'string') {
extraAttribute.title = title;
}
const closeButton = this.getCloseButton(tab, tabCloseIconStyle, tabCloseIconClasses, tabInlineStyles.tabCloseIconOnHover);
return (
<CustomDraggable
key={tab.key}
disabled={this.props.disableDrag}
axis="x"
cancel=".rdTabCloseIcon"
start={{ x: 0, y: 0 }}
moveOnStartChange={true}
zIndex={100}
bounds="parent"
onStart={this.handleDragStart.bind(this, tab.key)}
onDrag={this.handleDrag.bind(this, tab.key)}
onStop={this.handleDragStop.bind(this, tab.key)}>
<li style={tabStyle} className={tabClasses}
onClick={this.handleTabClick.bind(this, tab.key)}
onMouseEnter={this.handleMouseEnter.bind(this, tab.key, onMouseEnter)}
onMouseLeave={this.handleMouseLeave.bind(this, tab.key, onMouseLeave)}
ref={tab.key}
{...others}>
<span style={TabStyles.beforeTitle} className={tabBeforeTitleClasses}>{beforeTitle}</span>
<p style={tabTiteleStyle}
className={tabTitleClasses}
{...extraAttribute} >
{title}
</p>
<span style={TabStyles.afterTitle} className={tabAfterTitleClasses}>{afterTitle}</span>
{closeButton}
<span style={tabBeforeStyle} className={tabBeforeClasses}/>
<span style={tabAfterStyle} className={tabAfterClasses}/>
</li>
</CustomDraggable>
);
});
return (
<div style={tabInlineStyles.tabWrapper} className={xtabClassNames.tabWrapper}>
<ul tabIndex="-1" style={tabInlineStyles.tabBar} className={xtabClassNames.tabBar}>
{tabs}
<li className="rdTabAddButton" style={TabStyles.tabAddButton} onClick={this.handleAddButtonClick.bind(this)}>
{this.props.tabAddButton}
</li>
</ul>
<span style={tabInlineStyles.tabBarAfter} className={xtabClassNames.tabBarAfter}/>
{content}
</div>
);
}
}
Tabs.defaultProps = {
tabsClassNames: {
tabWrapper: '',
tabBar: '',
tabBarAfter: '',
tab: '',
tabBefore: '',
tabAfter: '',
tabBeforeTitle: '',
tabTitle: '',
tabAfterTitle: '',
tabCloseIcon: '',
tabActive: '',
tabHover: '',
},
tabsStyles: {},
shortCutKeys: {},
tabAddButton: (<span>{'+'}</span>),
onTabSelect: () => {
},
onTabClose: () => {
},
onTabAddButtonClick: () => {
},
onTabPositionChange: () => {
},
shouldTabClose: () => true,
keepSelectedTab: false,
disableDrag: false,
};
Tabs.propTypes = {
tabs: PropTypes.arrayOf(PropTypes.element),
selectedTab: PropTypes.string,
tabsClassNames: PropTypes.shape({
tabWrapper: PropTypes.string,
tabBar: PropTypes.string,
tabBarAfter: PropTypes.string,
tab: PropTypes.string,
tabBefore: PropTypes.string,
tabAfter: PropTypes.string,
tabBeforeTitle: PropTypes.string,
tabTitle: PropTypes.string,
tabAfterTitle: PropTypes.string,
tabCloseIcon: PropTypes.string,
tabActive: PropTypes.string,
tabHover: PropTypes.string,
}),
tabsStyles: PropTypes.shape({
tabWrapper: PropTypes.object,
tabBar: PropTypes.object,
tabBarAfter: PropTypes.object,
tab: PropTypes.object,
tabBefore: PropTypes.object,
tabAfter: PropTypes.object,
tabTitle: PropTypes.object,
tabActive: PropTypes.object,
tabTitleActive: PropTypes.object,
tabBeforeActive: PropTypes.object,
tabAfterActive: PropTypes.object,
tabOnHover: PropTypes.object,
tabTitleOnHover: PropTypes.object,
tabBeforeOnHover: PropTypes.object,
tabAfterOnHover: PropTypes.object,
tabCloseIcon: PropTypes.object,
tabCloseIconOnHover: PropTypes.object,
}),
shortCutKeys: PropTypes.shape({
close: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
create: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
moveRight: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
moveLeft: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
}),
tabAddButton: PropTypes.element,
onTabSelect: PropTypes.func,
onTabClose: PropTypes.func,
onTabAddButtonClick: PropTypes.func,
onTabPositionChange: PropTypes.func,
shouldTabClose: PropTypes.func,
keepSelectedTab: PropTypes.bool,
disableDrag: PropTypes.bool,
};
export default Tabs;
|
src/components/Weui/dialog/confirm.js | ynu/ecard-wxe | /**
* Created by jf on 15/10/27.
*/
import React from 'react';
import classNames from 'classnames';
import Mask from '../mask/index';
class Confirm extends React.Component {
static propTypes = {
buttons: React.PropTypes.array,
show: React.PropTypes.bool,
title: React.PropTypes.string
};
static defaultProps = {
buttons: [],
show: false,
title: ''
};
renderButtons() {
return this.props.buttons.map((action, idx) => {
const {type, label, ...others} = action;
const className = classNames({
weui_btn_dialog: true,
default: type === 'default',
primary: type === 'primary'
});
return (
<a key={idx} href="javascript:;" {...others} className={className}>{label}</a>
);
});
}
render() {
const {title, show, children} = this.props;
return (
<div className="weui_dialog_confirm" style={{display: show ? 'block' : 'none'}}>
<Mask/>
<div className="weui_dialog">
<div className="weui_dialog_hd">
<strong className="weui_dialog_title">{title}</strong>
</div>
<div className="weui_dialog_bd">
{children}
</div>
<div className="weui_dialog_ft">
{this.renderButtons()}
</div>
</div>
</div>
);
}
}
export default Confirm; |
app/javascript/mastodon/features/report/components/status_check_box.js | WitchesTown/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Toggle from 'react-toggle';
import noop from 'lodash/noop';
import StatusContent from '../../../components/status_content';
import { MediaGallery, Video } from '../../ui/util/async-components';
import Bundle from '../../ui/components/bundle';
export default class StatusCheckBox extends React.PureComponent {
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
checked: PropTypes.bool,
onToggle: PropTypes.func.isRequired,
disabled: PropTypes.bool,
};
render () {
const { status, checked, onToggle, disabled } = this.props;
let media = null;
if (status.get('reblog')) {
return null;
}
if (status.get('media_attachments').size > 0) {
if (status.get('media_attachments').some(item => item.get('type') === 'unknown')) {
} else if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
const video = status.getIn(['media_attachments', 0]);
media = (
<Bundle fetchComponent={Video} loading={this.renderLoadingVideoPlayer} >
{Component => (
<Component
preview={video.get('preview_url')}
src={video.get('url')}
width={239}
height={110}
inline
sensitive={status.get('sensitive')}
onOpenVideo={noop}
/>
)}
</Bundle>
);
} else {
media = (
<Bundle fetchComponent={MediaGallery} loading={this.renderLoadingMediaGallery} >
{Component => <Component media={status.get('media_attachments')} sensitive={status.get('sensitive')} height={110} onOpenMedia={noop} />}
</Bundle>
);
}
}
return (
<div className='status-check-box'>
<div className='status-check-box__status'>
<StatusContent status={status} />
{media}
</div>
<div className='status-check-box-toggle'>
<Toggle checked={checked} onChange={onToggle} disabled={disabled} />
</div>
</div>
);
}
}
|
src/components/course/CoursesPage.js | ashutosh-singh-rawat/react-redux-starter | import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import { bindActionCreators } from 'redux';
import { Link, withRouter } from 'react-router-dom';
import * as courseActions from '../../actions/courseActions';
import CourseList from './CourseList';
class CoursesPage extends React.Component {
constructor(props, context){
super(props, context);
this.state = {
course: {title: ""}
};
this.redirectToAddCoursePage = this.redirectToAddCoursePage.bind(this);
// this.onTitleChange = this.onTitleChange.bind(this);
// this.onClickSave = this.onClickSave.bind(this);
}
// onTitleChange(event) {
// const course = this.state.course;
// course.title = event.target.value;
// this.setState({course: course});
// }
//
// onClickSave() {
// // alert(`Saving ${this.state.course.title}`);
// // this.props.dispatch(courseActions.createCourse(this.state.course));// NOT GOOD WAY
// this.props.actions.createCourse(this.state.course);// GOOD WAY
// }
courseRow(course, index) {
return (
<div key={index}> {course.title} </div>
);
}
redirectToAddCoursePage() {
this.props.history.push('/course');
}
render() {
const { courses, match, location, history } = this.props;
return (
<div className="jumbotron">
<h1>Courses</h1>
<input
type="submit"
value="Add Course"
className="btn btn-primary"
onClick={this.redirectToAddCoursePage}
/>
<CourseList courses={courses}/>
</div>
// <div className="jumbotron">
// <h1>Courses</h1>
// {this.props.courses.map(this.courseRow)}
// </div>
// <h2>Add Course</h2>
// <input
// type="text"
// onChange={this.onTitleChange}
// value={this.state.course.title}
// />
//
// <input
// type="submit"
// value="Save"
// onClick={this.onClickSave}
// />
);
}
}
CoursesPage.propTypes = {
// dispatch: PropTypes.func.isRequired, // required when Ommiting mapDispatchToProps
courses: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired,
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
// createCourse: PropTypes.func.isRequired
};
function mapStateToProps(state, ownProps) {
return{
courses: state.courses //reducer
};
}
function mapDispatchToProps(dispatch) {
// return bindActionCreators({reducer}, dispatch)
return {
// createCourse: course => dispatch(courseActions.createCourse(course))
actions: bindActionCreators(courseActions, dispatch)
};
}
// export default connect(mapStateToProps)(CoursesPage); // Ommiting mapDispatchToProps inject dispatch to props
export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage);
|
src/index.js | scottenriquez/scottie-dot-io | import 'babel-polyfill';
import React from 'react';
import {render} from 'react-dom';
import {Router, browserHistory} from 'react-router';
import routes from './routes';
import './styles/styles.css';
var $ = require('jquery');
window.jQuery = $;
window.$ = $;
import '../node_modules/materialize-css/dist/css/materialize.min.css';
import '../node_modules/materialize-css/dist/js/materialize.min.js';
render(
<Router history={browserHistory} routes={routes} />,
document.getElementById('app')
); |
frontend/js/components/status.js | mcallistersean/b2-issue-tracker | import React from 'react'
import classNames from 'classnames'
export default function({status}) {
let cls = classNames('label', {
'label-danger': status === 'resolved',
'label-success': status === 'open'
})
return <span className={cls}>
{status}
</span>;
}
|
source-frontend/src/Following.js | Everstar/MusicRadio | /**
* Created by tsengkasing on 12/16/2016.
*/
import React from 'react';
import Avatar from 'material-ui/Avatar';
import {Table, TableBody, TableFooter, TableHeader, TableHeaderColumn, TableRow, TableRowColumn}
from 'material-ui/Table';
import { hashHistory } from 'react-router'
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import API from './API';
import $ from 'jquery';
export default class Following extends React.Component {
constructor(props) {
super(props);
this.state = {
current_page : 1,
all_pages : 1,
meta_list : [],
friend_list : [],
disablePreviousButton : true,
disableNextButton : true,
};
}
getFollowing = () => {
const URL = API.Following;
$.ajax({
url : URL,
type : 'GET',
contentType: 'application/json',
dataType: 'json',
headers : {
'target' : 'api',
},
success : function(data, textStatus, jqXHR) {
console.log(data);
let pages = 1;
let temp = data;
if(data.length > 10) {
pages = data.length / 10 + (data.length % 10) > 0 ? 1 : 0;
temp = data.slice(0, 10);
}
console.log('all_pages : ' + pages);
this.setState({
meta_list : data,
friend_list : temp,
all_pages : pages,
});
}.bind(this),
error : function(xhr, textStatus) {
console.log(xhr.status + '\n' + textStatus + '\n');
}
});
};
componentWillMount() {
this.getFollowing();
};
previousPage= () => {
let current = parseInt(this.state.current_page, 10);
this.setState({
current_page : current - 1,
friend_list : this.state.meta_list.slice((current - 2) * 10, (current - 2) * 10 + 10),
disableNextButton: false,
disablePreviousButton: ((current - 1) === 1),
});
};
nextPage = () => {
let current = parseInt(this.state.current_page, 10);
this.setState({
current_page : (current + 1),
friend_list : this.state.meta_list.slice((current - 2) * 10, (current - 2) * 10 + 10),
disableNextButton: ((current + 1) === parseInt(this.state.all_pages, 10)),
disablePreviousButton: false,
});
};
handleRedirectInfoPage = (event) => {
console.log('user_id:'+ event.target.parentNode.parentNode.parentNode.getAttribute('alt'));
hashHistory.push('/user/' + event.target.parentNode.parentNode.parentNode.getAttribute('alt'));
};
handleRedirectRadioPage = (event) => {
console.log('user_id:'+ event.target.parentNode.parentNode.parentNode.getAttribute('alt'));
hashHistory.push('/user/' + event.target.parentNode.parentNode.parentNode.getAttribute('alt') + '/songlist');
};
render() {
return (
<Table
style={{background : 'transparent'}}
selectable={false}>
<TableHeader
displaySelectAll={false}
adjustForCheckbox={false}>
<TableRow>
<TableHeaderColumn>Avatar</TableHeaderColumn>
<TableHeaderColumn>Name</TableHeaderColumn>
<TableHeaderColumn>Info</TableHeaderColumn>
<TableHeaderColumn>Radio</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody
showRowHover={true}
displayRowCheckbox={false}>
{this.state.friend_list.map((row, index) => (
<TableRow key={index}>
<TableRowColumn><Avatar src={row.avator_url} /></TableRowColumn>
<TableRowColumn>{row.username}</TableRowColumn>
<TableRowColumn><RaisedButton label="Info" primary={true} onTouchTap={this.handleRedirectInfoPage} alt={row.id} /></TableRowColumn>
<TableRowColumn><RaisedButton label="Radio" primary={true} onTouchTap={this.handleRedirectRadioPage} alt={row.id} /></TableRowColumn>
</TableRow>
))}
</TableBody>
<TableFooter
adjustForCheckbox={false}>
<TableRow>
<TableRowColumn colSpan="5" style={{textAlign: 'center'}}>
<FlatButton primary={true} label="previous" onTouchTap={this.previousPage} disabled={this.state.disablePreviousButton} />
{this.state.current_page}/{this.state.all_pages}
<FlatButton primary={true} label="next" onTouchTap={this.nextPage} disabled={this.state.disableNextButton} />
</TableRowColumn>
</TableRow>
</TableFooter>
</Table>
);
}
}
|
frontend/src/Artist/Editor/Tags/TagsModal.js | lidarr/Lidarr | import PropTypes from 'prop-types';
import React from 'react';
import Modal from 'Components/Modal/Modal';
import TagsModalContentConnector from './TagsModalContentConnector';
function TagsModal(props) {
const {
isOpen,
onModalClose,
...otherProps
} = props;
return (
<Modal
isOpen={isOpen}
onModalClose={onModalClose}
>
<TagsModalContentConnector
{...otherProps}
onModalClose={onModalClose}
/>
</Modal>
);
}
TagsModal.propTypes = {
isOpen: PropTypes.bool.isRequired,
onModalClose: PropTypes.func.isRequired
};
export default TagsModal;
|
src/components/Modal/ChangePwdModel.js | lethecoa/work-order-pc | import React from 'react';
import {Button, Modal, Form, Input} from 'antd';
import md5 from '../../common/md5.min';
const FormItem = Form.Item;
const formItemLayout = {
labelCol: {span: 10},
wrapperCol: {span: 9}
};
class ChangePwdForm extends React.Component {
state = {
confirmDirty: false,
};
checkOldPwd = (rule, value, callback) => {
if (value && md5(value) !== this.props.pwd) {
callback('原始密码不正确!');
}
callback();
};
checkConfirm = (rule, value, callback) => {
const form = this.props.form;
if (value && this.state.confirmDirty) {
form.validateFields(['confirm'], {force: true});
}
callback();
};
checkPassword = (rule, value, callback) => {
const form = this.props.form;
if (value && value !== form.getFieldValue('password')) {
callback('两次输入密码不一致!');
} else {
callback();
}
};
handleConfirmBlur = (e) => {
const value = e.target.value;
this.setState({confirmDirty: this.state.confirmDirty || !!value});
};
render() {
const {visible, onCancel, onSubmit, form, loading} = this.props;
const {getFieldDecorator} = form;
return (
<Modal
visible={visible}
title="修改密码"
maskClosable={false}
closable={false}
footer={[
<Button key="back" size="large" onClick={onCancel}>取消</Button>,
<Button key="submit" type="primary" size="large" loading={loading} onClick={onSubmit}>提交</Button>,
]}
>
<Form>
<FormItem {...formItemLayout} label="原始密码" hasFeedback>
{getFieldDecorator('passwordOld', {
rules: [{
required: true, message: '请填写原始密码!',
}, {
validator: this.checkOldPwd,
}],
})(
<Input type="password"/>
)}
</FormItem>
<FormItem {...formItemLayout} label="新密码" hasFeedback>
{getFieldDecorator('password', {
rules: [{
required: true, message: '请填写新密码!',
}, {
validator: this.checkConfirm,
}],
})(
<Input type="password"/>
)}
</FormItem>
<FormItem {...formItemLayout} label="确认密码" hasFeedback>
{getFieldDecorator('confirm', {
rules: [{
required: true, message: '请填写确认密码!',
}, {
validator: this.checkPassword,
}],
})(
<Input type="password" onBlur={this.handleConfirmBlur}/>
)}
</FormItem>
</Form>
</Modal>
);
}
}
const ChangePwd = Form.create()(ChangePwdForm);
export default class ChangePwdModel extends React.Component {
state = {
visible: false,
};
showModal = () => {
const form = this.form;
form.resetFields();
this.setState({visible: true});
};
handleCancel = () => {
this.setState({visible: false});
};
handleSubmit = () => {
const form = this.form;
form.validateFields((err, values) => {
if (err) {
return;
}
this.props.saveNewPwd(values.password);
});
};
saveFormRef = (form) => {
this.form = form;
};
render() {
return (
<span>
<a onClick={this.showModal}>修改密码</a>
<ChangePwd
ref={this.saveFormRef}
visible={this.state.visible}
onCancel={this.handleCancel}
onSubmit={this.handleSubmit}
pwd={this.props.pwd}
loading={this.props.loading}
/>
</span>
);
}
}
|
js/jqwidgets/demos/react/app/ribbon/fluidsize/app.js | luissancheza/sice | import React from 'react';
import ReactDOM from 'react-dom';
import JqxRibbon from '../../../jqwidgets-react/react_jqxribbon.js';
class App extends React.Component {
render() {
return (
<JqxRibbon ref='myRibbon'
width={'100%'}
height={350}
position={'top'}
selectionMode={'click'}
animationType={'fade'}
>
<ul>
<li style={{ marginLeft: 30 }}>Browse Books</li>
<li>Shipping</li>
<li>About Us</li>
</ul>
<div>
<div>
<table style={{ width: '100%' }}>
<tr>
<td>
<b>Fiction</b>
</td>
<td>
<b>Biography</b>
</td>
<td>
<b>Science</b>
</td>
</tr>
<tr>
<td>
<a href='#'>Adventure</a>
</td>
<td>
<a href='#'>Biography: General</a>
</td>
<td>
<a href='#'>Astronomy</a>
</td>
</tr>
<tr>
<td>
<a href='#'>Classics</a>
</td>
<td>
<a href='#'>Diaries, Letters & Journals</a>
</td>
<td>
<a href='#'>Biology</a>
</td>
</tr>
<tr>
<td>
<a href='#'>Historical Fiction</a>
</td>
<td>
<a href='#'>Memoirs</a>
</td>
<td>
<a href='#'>Geography</a>
</td>
</tr>
<tr>
<td>
<a href='#'>Romance</a>
</td>
<td>
<b>Food & Drink</b>
</td>
<td>
<a href='#'>Mathematics</a>
</td>
</tr>
<tr>
<td>
<a href='#'>Science Fiction</a>
</td>
<td>
<a href='#'>General Cookery</a>
</td>
<td>
<a href='#'>Physics</a>
</td>
</tr>
<tr>
<td>
<a href='#'>Thrillers</a>
</td>
<td>
<a href='#'>National Cuisine</a>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
<a href='#'>Quick & Easy Cooking</a>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
<a href='#'>Vegetarian Cookery</a>
</td>
<td>
<a href='#'>More books >></a>
</td>
</tr>
</table>
</div>
<div>
<table style={{ width: '100%' }}>
<tr>
<td>
<a href='#'>Countries we ship to</a>
</td>
</tr>
<tr>
<td>
<a href='#'>Delivery options</a>
</td>
</tr>
<tr>
<td>
<a href='#'>Order cancellation and returns</a>
</td>
</tr>
</table>
</div>
<div>
<table style={{ width: '100%' }}>
<tr>
<td>
<a href='#'>Contact us</a>
</td>
<td rowspan='3' style={{ width: 125 }}>
</td>
<td rowspan='3'>
<img src='../../images/bookshop.png' />
</td>
</tr>
<tr>
<td>
<a href='#'>Jobs</a>
</td>
</tr>
<tr>
<td>
<a href='#'>Affiliates</a>
</td>
</tr>
</table>
</div>
</div>
</JqxRibbon>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/components/RadioButton/RadioButton.js | carbon-design-system/carbon-components-react | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import warning from 'warning';
import { settings } from 'carbon-components';
import uid from '../../tools/uniqueId';
const { prefix } = settings;
class RadioButton extends React.Component {
static propTypes = {
/**
* Specify whether the <RadioButton> is currently checked
*/
checked: PropTypes.bool,
/**
* Provide an optional className to be applied to the containing node
*/
className: PropTypes.string,
/**
* Specify whether the <RadioButton> should be checked by default
*/
defaultChecked: PropTypes.bool,
/**
* Specify whether the control is disabled
*/
disabled: PropTypes.bool,
/**
* Provide a unique id for the underlying <input> node
*/
id: PropTypes.string,
/**
* Provide label text to be read by screen readers when interacting with the
* control
*/
labelText: PropTypes.node.isRequired,
/**
* Specify whether the label should be hidden, or not
*/
hideLabel: PropTypes.bool,
/**
* Provide where label text should be placed
*/
labelPosition: PropTypes.string,
/**
* Provide a name for the underlying <input> node
*/
name: PropTypes.string,
/**
* Provide a handler that is invoked when a user clicks on the control
*/
onClick: PropTypes.func,
/**
* Provide an optional `onChange` hook that is called each time the value of
* the underlying <input> changes
*/
onChange: PropTypes.func,
/**
* Specify the value of the <RadioButton>
*/
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
};
static defaultProps = {
labelText: '',
labelPosition: 'right',
onChange: () => {},
value: '',
};
uid = this.props.id || uid();
handleChange = evt => {
this.props.onChange(this.props.value, this.props.name, evt);
};
render() {
const {
className,
labelText,
labelPosition,
innerRef: ref,
hideLabel,
...other
} = this.props;
if (__DEV__) {
warning(
labelPosition !== 'top' && labelPosition !== 'bottom',
'`top`/`bottom` values for `labelPosition` property in the `RadioButton` component is deprecated ' +
'and being removed in the next release of `carbon-components-react`.'
);
}
const innerLabelClasses = classNames({
[`${prefix}--visually-hidden`]: hideLabel,
});
const wrapperClasses = classNames(
className,
`${prefix}--radio-button-wrapper`,
{
[`${prefix}--radio-button-wrapper--label-${labelPosition}`]:
labelPosition !== 'right',
}
);
return (
<div className={wrapperClasses}>
<input
{...other}
type="radio"
className={`${prefix}--radio-button`}
onChange={this.handleChange}
id={this.uid}
ref={ref}
/>
<label
htmlFor={this.uid}
className={`${prefix}--radio-button__label`}
aria-label={labelText}>
<span className={`${prefix}--radio-button__appearance`} />
<span className={innerLabelClasses}>{labelText}</span>
</label>
</div>
);
}
}
export default (() => {
const forwardRef = (props, ref) => <RadioButton {...props} innerRef={ref} />;
forwardRef.displayName = 'RadioButton';
return React.forwardRef(forwardRef);
})();
|
src/components/Feedback/Feedback.js | jbsouvestre/react-starter-kit | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react';
import styles from './Feedback.less';
import withStyles from '../../decorators/withStyles';
@withStyles(styles)
class Feedback {
render() {
return (
<div className="Feedback">
<div className="Feedback-container">
<a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a>
<span className="Feedback-spacer">|</span>
<a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a>
</div>
</div>
);
}
}
export default Feedback;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.