path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
src/Affix.js | chilts/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import AffixMixin from './AffixMixin';
const Affix = React.createClass({
mixins: [AffixMixin],
render() {
let holderStyle = {
top: this.state.affixPositionTop,
// we don't want to expose the `style` property
...this.props.style // eslint-disable-line react/prop-types
};
return (
<div {...this.props}
className={classNames(this.props.className, this.state.affixClass)}
style={holderStyle}>
{this.props.children}
</div>
);
}
});
export default Affix;
|
resources/js/components/editor.js | ncbrown1/go-playground | import React from 'react';
import { connect } from 'react-redux';
import CodeMirror from 'react-codemirror';
import * as actions from '../actions';
class Editor extends React.Component {
constructor(props){
super(props);
}
shouldComponentUpdate(nextProps, newState) {
return nextProps.forceEditorRender;
}
render() {
let options = {
autofocus: true,
indentUnit: 4,
keymap: 'sublime',
lineNumbers: true,
mode: 'go',
theme: 'monokai',
value: this.props.code
};
return <div id="go-editor">
<CodeMirror value={this.props.code} onChange={this.props.updateCode} options={options} />
</div>;
}
}
// Maps state from store to props
const mapStateToProps = (state, ownProps) => {
return {
code: state.code, // this.props.code
forceEditorRender: state.forceEditorRender
};
};
// Maps actions to props
const mapDispatchToProps = (dispatch) => {
return {
// this.props.updateCode
updateCode: code => dispatch(actions.updateCode(code))
};
};
// Use connect to put them together
export default connect(mapStateToProps, mapDispatchToProps)(Editor); |
src/explore/LoadableStartExploringPage.js | ipfs/webui | import React from 'react'
import Loadable from '@loadable/component'
import ComponentLoader from '../loader/ComponentLoader.js'
const LoadableStartExploringPage = Loadable(() => import('./StartExploringContainer'),
{ fallback: <ComponentLoader/> }
)
export default LoadableStartExploringPage
|
app/javascript/mastodon/components/avatar.js | summoners-riftodon/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { autoPlayGif } from '../initial_state';
export default class Avatar extends React.PureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
size: PropTypes.number.isRequired,
style: PropTypes.object,
inline: PropTypes.bool,
animate: PropTypes.bool,
};
static defaultProps = {
animate: autoPlayGif,
size: 20,
inline: false,
};
state = {
hovering: false,
};
handleMouseEnter = () => {
if (this.props.animate) return;
this.setState({ hovering: true });
}
handleMouseLeave = () => {
if (this.props.animate) return;
this.setState({ hovering: false });
}
render () {
const { account, size, animate, inline } = this.props;
const { hovering } = this.state;
const src = account.get('avatar');
const staticSrc = account.get('avatar_static');
let className = 'account__avatar';
if (inline) {
className = className + ' account__avatar-inline';
}
const style = {
...this.props.style,
width: `${size}px`,
height: `${size}px`,
backgroundSize: `${size}px ${size}px`,
};
if (hovering || animate) {
style.backgroundImage = `url(${src})`;
} else {
style.backgroundImage = `url(${staticSrc})`;
}
return (
<div
className={className}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
style={style}
/>
);
}
}
|
src/components/icons/NoAnswerMobileIcon.js | austinknight/ui-components | import React from 'react';
const NoAnswerMobileIcon = props => (
<svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 24 24" fill="currentColor">
{props.title && <title>{props.title}</title>}
<path d="M15.5,1 L7.5,1 C6.12,1 5,2.12 5,3.5 L5,20.5 C5,21.88 6.12,23 7.5,23 L15.5,23 C16.88,23 18,21.88 18,20.5 L18,3.5 C18,2.12 16.88,1 15.5,1 Z M11.5,22 C10.67,22 10,21.33 10,20.5 C10,19.67 10.67,19 11.5,19 C12.33,19 13,19.67 13,20.5 C13,21.33 12.33,22 11.5,22 Z M16,18 L7,18 L7,4 L16,4 L16,18 Z M15,13.013 L12.487,10.5 L15,7.987 L14.013,7 L11.5,9.513 L8.987,7 L8,7.987 L10.513,10.5 L8,13.013 L8.987,14 L11.5,11.487 L14.013,14 L15,13.013 Z" id="path-1"></path>
</svg>
);
export default NoAnswerMobileIcon; |
src/lib/gui/components/ServerViewHeaderToggle/ServerViewHeaderToggle.js | xclix/chan | import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
const ServerViewHeaderToggle = ({ toggled, serverId, onSwitchButtonClick }) => {
const toggleClassNames = classnames({
'server-view-header-toggle': true,
'server-view-header-toggle--up': toggled
});
return (
<button
className={toggleClassNames}
onClick={() => onSwitchButtonClick(serverId, toggled)}
>
<svg
className="server-view-header-toggle-icon"
width="60px"
height="60px"
>
<title>icons_power/on@3x</title>
<desc>Created with Sketch.</desc>
<defs />
<g
id="Page-1"
stroke="none"
strokeWidth="1"
fill="none"
fillRule="evenodd"
opacity="0.75"
>
<path
className="server-view-header-toggle__icon"
transform="translate(4, 4)"
d="M26.0503929,17 C25.3931535,17 24.8637106,17.5364493 24.8637106,18.1941509
L24.8637106,23.6945939 C24.8637106,24.3559698 25.3968048,24.8887448 26.0503929,
24.8887448 C26.7039809,24.8887448 27.2370751,24.3522955 27.2370751,23.6945939
L27.2370751,18.1941509 C27.2370751,17.5364493 26.7076322,17 26.0503929,17
M18.0357237,27.6738723 C17.7728279,24.8262816 18.9814181,22.2469155 20.9859983
,20.608173 C21.7673829,19.968843 22.9358084,20.5163152 22.9358084,21.5267506
C22.9358084,21.897856 22.7605446,22.2395669 22.4757409,22.4710485 C21.0553735,
23.6358049 20.2009623,25.4729602 20.4090881,27.5011797 C20.6792866,30.143009
22.7824526,32.2814577 25.4041075,32.5754026 C28.8254036,32.9612052 31.7318987,
30.2642612 31.7318987,26.8985927 C31.7318987,25.1128778 30.9103495,23.5145527
29.6286962,22.4673742 C29.3438924,22.2358926 29.1722799,21.8941817 29.1722799,
21.5267506 C29.1722799,20.5273382 30.3224489,19.9614943 31.0965308,20.5861271
C32.9294984,22.0742229 34.1052632,24.3486212 34.1052632,26.8985927 C34.1052632,
31.5612929 30.169093,35.3201494 25.4625287,34.9784017 C21.5702111,34.7028284
18.3972054,31.5833387 18.0357237,27.6738723"
id="Fill-1"
fill="#83878E"
/>
<circle
stroke="#83878E"
id="Oval"
strokeWidth="2"
cx="28"
cy="28"
r="26"
transform="translate(2, 2)"
/>
</g>
</svg>
</button>
);
};
ServerViewHeaderToggle.propTypes = {
toggled: PropTypes.bool.isRequired,
serverId: PropTypes.string.isRequired,
onSwitchButtonClick: PropTypes.func.isRequired
};
export default ServerViewHeaderToggle;
|
examples/NavigationPlayground/js/Banner.js | half-shell/react-navigation | /* @flow */
import React from 'react';
import {
Image,
Platform,
StyleSheet,
Text,
View,
} from 'react-native';
const Banner = () => (
<View style={styles.banner}>
<Image
source={require('./assets/NavLogo.png')}
style={styles.image}
/>
<Text style={styles.title}>React Navigation Examples</Text>
</View>
);
export default Banner;
const styles = StyleSheet.create({
banner: {
backgroundColor: '#673ab7',
flexDirection: 'row',
alignItems: 'center',
padding: 16,
marginTop: Platform.OS === 'ios' ? 20 : 0,
},
image: {
width: 36,
height: 36,
resizeMode: 'contain',
tintColor: '#fff',
margin: 8,
},
title: {
fontSize: 18,
fontWeight: '200',
color: '#fff',
margin: 8,
},
});
|
client/src/shared/MarkdownBlock.js | clembou/github-requests | import React from 'react';
import marked from 'marked';
marked.setOptions({
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false
});
const MarkdownBlock = props => <div dangerouslySetInnerHTML={{ __html: marked(props.body) }} />;
export default MarkdownBlock;
|
index.js | codeocelot/react-class-properties | import React from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component{
constructor(props){
super(props);
this.state = { clickCount: props.initialCount}
}
addOne = () => {
this.setState({ clickCount : this.state.clickCount + 1 });
}
subOne = () => {
this.setState({ clickCount : this.state.clickCount - 1 });
}
render(){
return (
<div>
<h1>Hi world</h1>
<p>Click Count: {this.state.clickCount }</p>
<button type="button" onClick={this.addOne}>+1</button>
<button type="button" onClick={this.subOne}>-1</button>
</div>
)
}
}
ReactDOM.render(<App initialCount={10}/>,document.getElementById('react-app'))
|
Rosa_Madeira/Cliente/src/components/conta/DadoItem.js | victorditadi/IQApp | import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { Icon } from 'native-base';
import { CardSection, Card, Button } from '../common/card_produto';
import { Spinner } from '../common';
import { Container, Content, List, ListItem, InputGroup, Input } from 'native-base';
import { connect } from 'react-redux';
import { Actions } from 'react-native-router-flux';
import {
emailChangedCliente,
nomeChanged,
cepChanged,
enderecoChanged,
telefoneChanged,
cancelarButton,
atualizarInfo } from '../../actions';
class DadoItem extends Component {
onNameChange(text){
this.props.nomeChanged(text);
// console.log(text);
}
onTelefoneChange(text){
this.props.telefoneChanged(text);
// console.log(text);
}
onCepChange(text){
this.props.cepChanged(text);
}
onEnderecoChange(text){
this.props.enderecoChanged(text);
}
onEmailChange(text){
this.props.emailChangedCliente(text);
}
cancelarButton(){
this.props.cancelarButton();
}
atualizarButton(){
// console.log(this.props.dadoItem.codigo_cliente);
const { nome, cep, email, endereco, telefone } = this.props;
const { codigo_cliente } = this.props.dadoItem;
this.props.atualizarInfo(nome, cep, email, endereco, telefone, codigo_cliente);
}
renderRow(form){
if(form == 'listar') return;
if(form == 'update'){
// console.log(this.props);
if(this.props.loading == true) return <Spinner size='large'/>
if(this.props.loading == false){
return (
<View style={{marginLeft: 20, marginTop: 20}}>
<Button onPress={this.atualizarButton.bind(this)}>
Atualizar Dados
</Button>
<View style={{marginTop: 20}}>
<Button onPress={this.cancelarButton.bind(this)}>
Limpar Campos
</Button>
</View>
</View>
);
}
}
}
render(){
// console.log(this.props);
const { cep, endereco, nome_cliente, telefone, email, form, codigo_cliente} = this.props.dadoItem;
// console.log(form);
if(form == 'listar') tipo = true;
if(form == 'update') tipo = false;
return(
<View>
<ListItem>
<InputGroup disabled = {tipo}>
<Input inlineLabel label="Nome" placeholder={nome_cliente} value={this.props.nome} onChangeText={this.onNameChange.bind(this)}/>
</InputGroup>
</ListItem>
<ListItem>
<InputGroup disabled = {tipo}>
<Input inlineLabel label="Endereço" placeholder={endereco} value={this.props.endereco} onChangeText={this.onEnderecoChange.bind(this)}/>
</InputGroup>
</ListItem>
<ListItem>
<InputGroup disabled = {tipo}>
<Input inlineLabel label="CEP" placeholder={cep} value={this.props.cep} onChangeText={this.onCepChange.bind(this)}/>
</InputGroup>
</ListItem>
<ListItem>
<InputGroup disabled = {tipo}>
<Input inlineLabel label="Telefone" placeholder={telefone} value={this.props.telefone} onChangeText={this.onTelefoneChange.bind(this)}/>
</InputGroup>
</ListItem>
<ListItem>
<InputGroup disabled = {tipo}>
<Input inlineLabel label="Email" placeholder={email} value={this.props.email} onChangeText={this.onEmailChange.bind(this)}/>
</InputGroup>
</ListItem>
<View>
{this.renderRow(form)}
</View>
<View style={{justifyContent: 'center', alignItems: 'center', marginTop: 20}}>
<Text style={{fontSize: 20, color: 'black'}}>{this.props.message}</Text>
</View>
</View>
);
}
};
const mapStateToProps = ({conta}) =>{
const { nome, endereco, cep, telefone, email, message, loading } = conta;
return { nome, endereco, cep, telefone, email, message, loading }
}
export default connect(mapStateToProps,
{emailChangedCliente,
nomeChanged,
cepChanged,
enderecoChanged,
telefoneChanged,
cancelarButton,
atualizarInfo})(DadoItem);
|
packages/vx-text/src/text/TextBackground.js | Flaque/vx | import React from 'react';
import cx from 'classnames';
export default function TextBackground({
x = 0,
y = 0,
dx = 0,
dy = 0,
children,
fontSize = 12,
fontFamily = 'Arial',
textAnchor = 'start',
fill = 'white',
stroke = 'none',
strokeWidth = 0,
strokeDasharray,
backgroundFill = 'white',
backgroundStroke = 'magenta',
backgroundStrokeWidth = 3,
backgroundStrokeDasharray,
className,
}) {
return (
<g>
<rect
className={cx('vx-text-background__background', className)}
width="100%"
height="100%"
fill={backgroundFill}
stroke={backgroundStroke}
strokeWidth={backgroundStrokeWidth}
strokeDasharray={backgroundStrokeDasharray}
/>
<text
className={cx('vx-text-background__text', className)}
x={x}
y={y}
dx={dx}
dy={dy}
fontSize={fontSize}
fontFamily={fontFamily}
fill={fill}
stroke={stroke}
strokeWidth={strokeWidth}
strokeDasharray={strokeDasharray}
textAnchor={textAnchor}
>
{children}
</text>
</g>
);
}
|
app/components/HorizontalPlayer/stories.js | scampersand/sonos-front | import React from 'react'
import { storiesOf, action } from '@kadira/storybook'
import HorizontalPlayer from '.'
let props = {
currentTrackInfo: {
album_art: "https://placekitten.com/500/500",
},
transportState: "PLAYING",
}
storiesOf('HorizontalPlayer', module)
.add('playing', () => (
<HorizontalPlayer {...props} />
))
.add('paused', () => (
<HorizontalPlayer {...props} transportState="PAUSED_PLAYBACK" />
))
.add('stopped', () => (
<HorizontalPlayer {...props} transportState="STOPPED" />
))
|
packages/wix-style-react/src/CardGalleryItem/docs/exampleProps.js | wix/wix-style-react | import React from 'react';
import Edit from 'wix-ui-icons-common/Edit';
import Delete from 'wix-ui-icons-common/Delete';
import Email from 'wix-ui-icons-common/Email';
import More from 'wix-ui-icons-common/More';
import { storySettings } from './storySettings';
import PopoverMenu from '../../PopoverMenu';
import { Badge, IconButton } from 'wix-style-react';
const backgroundImageUrl =
'https://static.wixstatic.com/media/89ea07a19c3d415e99a8a8a3c0ab1de8.jpg/v1/fill/w_343,h_343,al_c,q_80,usm_0.66_1.00_0.01/89ea07a19c3d415e99a8a8a3c0ab1de8.jpg';
const getPrimaryActionProps = label => ({
label,
onClick: () => {
alert('Primary action clicked');
},
});
const getSecondaryActionProps = label => ({
label,
onClick: () => {
alert('Secondary action clicked');
},
});
const commonProps = {
badge: (
<Badge size="medium" skin="standard" type="solid" uppercase>
sale
</Badge>
),
title: 'Card Title',
subtitle: 'Card subtitle',
backgroundImageUrl: backgroundImageUrl,
};
export default {
...commonProps,
dataHook: storySettings.dataHook,
primaryActionProps: getPrimaryActionProps('Button'),
secondaryActionProps: getSecondaryActionProps('Text Link'),
settingsMenu: (
<PopoverMenu
triggerElement={({ toggle }) => (
<IconButton
onClick={e => {
e.stopPropagation();
toggle();
}}
skin="light"
size="small"
priority="secondary"
>
<More />
</IconButton>
)}
>
<PopoverMenu.MenuItem text="Edit" prefixIcon={<Edit />} />
<PopoverMenu.MenuItem text="Delete" prefixIcon={<Delete />} />
<PopoverMenu.MenuItem text="Email" prefixIcon={<Email />} />
<PopoverMenu.MenuItem text="Something" disabled />
</PopoverMenu>
),
};
|
actor-apps/app-web/src/app/components/Install.react.js | hmoraes/actor-platform | import React from 'react';
export default class Install extends React.Component {
render() {
return (
<section className="mobile-placeholder col-xs row center-xs middle-xs">
<div>
<img alt="Actor messenger"
className="logo"
src="assets/img/logo.png"
srcSet="assets/img/[email protected] 2x"/>
<h1>Web version of <b>Actor</b> works only on desktop browsers at this time</h1>
<h3>Please install our apps for using <b>Actor</b> on your phone.</h3>
<p>
<a href="//actor.im/ios">iPhone</a> | <a href="//actor.im/android">Android</a>
</p>
</div>
</section>
);
}
}
|
src/entypo/ImageInverted.js | cox-auto-kc/react-entypo | import React from 'react';
import EntypoIcon from '../EntypoIcon';
const iconClass = 'entypo-svgicon entypo--ImageInverted';
let EntypoImageInverted = (props) => (
<EntypoIcon propClass={iconClass} {...props}>
<path d="M18,3H2C1.447,3,1,3.447,1,4v12c0,0.552,0.447,1,1,1h16c0.553,0,1-0.448,1-1V4C19,3.448,18.553,3,18,3z M13.25,6.5c0.69,0,1.25,0.56,1.25,1.25S13.94,9,13.25,9S12,8.44,12,7.75S12.56,6.5,13.25,6.5z M4,14l3.314-7.619l3.769,6.102l3.231-1.605L16,14H4z"/>
</EntypoIcon>
);
export default EntypoImageInverted;
|
src/components/video_list.js | CalinoviciPaul/react | /**
* Created by IrianLaptop on 2/5/2017.
*/
import React from 'react';
import VideoListItem from "./video_list_item";
const VideoList = (props) =>{
const videoItems = props.videos.map((video) => {
return <VideoListItem video={video} key ={video.etag} onVideoSelect={props.onVideoSelect}/>
});
return (
<ul className="col-md-4 list-group">
{videoItems}
</ul>
);
};
export default VideoList;
|
src/svg-icons/av/web-asset.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvWebAsset = (props) => (
<SvgIcon {...props}>
<path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm0 14H5V8h14v10z"/>
</SvgIcon>
);
AvWebAsset = pure(AvWebAsset);
AvWebAsset.displayName = 'AvWebAsset';
AvWebAsset.muiName = 'SvgIcon';
export default AvWebAsset;
|
client/component/table/row/loading-row.js | johngodley/redirection | /**
* External dependencies
*/
import React from 'react';
const Row = ( props ) => {
const { columns } = props;
return (
<tr className="is-placeholder">
{ columns.map( ( item, pos ) => (
<td key={ pos }>
<div className="wpl-placeholder__loading" />
</td>
) ) }
<td>
<div className="wpl-placeholder__loading" />
</td>
</tr>
);
};
const LoadingRow = ( props ) => {
const { headers, rows } = props;
return (
<>
<Row columns={ headers } />
{ rows.slice( 0, -1 ).map( ( item, pos ) => (
<Row columns={ headers } key={ pos } />
) ) }
</>
);
};
export default LoadingRow;
|
app/components/models/scene.react.js | Chaos-Zero/GoemonInternational | import * as THREE from 'three';
import React from 'react';
import ReactDOM from 'react-dom';
import React3 from 'react-three-renderer';
import SettingsAction from 'actions/settings_action';
import OrbitControls from 'components/modelImporter/OrbitControls';
/* scene graph */
class SceneComponent extends React.Component {
static displayName = 'Scene3D';
constructor(props) {
super(props);
this._orbitControlsHandler = this._onControllerChange.bind(this);
this._mouseUpListener = this._onMouseUp.bind(this);
this._renderTrigger = function(){};
this._onManualRenderTriggerCreated = (renderTrigger) => {
this._renderTrigger = renderTrigger;
};
}
componentWillReceiveProps(){
}
componentDidMount(){
this._canvas = ReactDOM.findDOMNode(this.refs.react3);
this._camera = this.refs.camera;
this._orbitControls = new THREE.OrbitControls(this._camera, this._canvas);
if(this.props.forceManualRender === true){
this._orbitControls.addEventListener('change', this._orbitControlsHandler, false);
this._renderTrigger();
}else{
this._canvas.addEventListener('mouseup', this._mouseUpListener, false);
}
}
componentWillUnmount(){
if(this.props.forceManualRender === true){
this._orbitControls.removeEventListener('change', this._orbitControlsHandler, false);
}else{
this._canvas.removeEventListener('mouseup', this._mouseUpListener, false);
}
this._controls.dispose();
}
_onControllerChange(e){
SettingsAction.updateCamera({
position: this._camera.position,
quaternion: this._camera.quaternion
});
}
_onMouseUp(e){
SettingsAction.updateCamera({
position: this._camera.position,
quaternion: this._camera.quaternion
});
}
render() {
let scene = (
<React3
ref='react3'
mainCamera='camera'
width={window.innerWidth}
height={window.innerHeight}
antialias
shadowMapEnabled={true}
clearColor={0xffffff}
forceManualRender={this.props.forceManualRender}
onManualRenderTriggerCreated={this._onManualRenderTriggerCreated}
>
<scene
ref='scene'
>
<perspectiveCamera
ref='camera'
name='camera'
fov={50}
aspect={window.innerWidth / window.innerHeight}
near={1}
far={1000}
position={this.props.cameraPosition}
quaternion={this.props.cameraQuaternion}
/>
<ambientLight
color={new THREE.Color(0x333333)}
/>
<directionalLight
color={new THREE.Color(0xFFFFFF)}
intensity={1.5}
position={new THREE.Vector3(0, 0, 60)}
/>
{this.props.children}
</scene>
</React3>
);
if(this.props.forceManualRender === true){
this._renderTrigger();
}
return scene;
}
}
SceneComponent.propTypes = {
cameraPosition: React.PropTypes.instanceOf(THREE.Vector3),
cameraQuaternion: React.PropTypes.instanceOf(THREE.Quaterion),
forceManualRender: React.PropTypes.bool
};
export default SceneComponent;
|
blueocean-material-icons/src/js/components/svg-icons/action/remove-shopping-cart.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionRemoveShoppingCart = (props) => (
<SvgIcon {...props}>
<path d="M22.73 22.73L2.77 2.77 2 2l-.73-.73L0 2.54l4.39 4.39 2.21 4.66-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h7.46l1.38 1.38c-.5.36-.83.95-.83 1.62 0 1.1.89 2 1.99 2 .67 0 1.26-.33 1.62-.84L21.46 24l1.27-1.27zM7.42 15c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h2.36l2 2H7.42zm8.13-2c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H6.54l9.01 9zM7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2z"/>
</SvgIcon>
);
ActionRemoveShoppingCart.displayName = 'ActionRemoveShoppingCart';
ActionRemoveShoppingCart.muiName = 'SvgIcon';
export default ActionRemoveShoppingCart;
|
src/parser/deathknight/unholy/modules/features/Apocalypse.js | FaideWW/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import Analyzer from 'parser/core/Analyzer';
import EnemyInstances from 'parser/shared/modules/EnemyInstances';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
class Apocalypse extends Analyzer {
static dependencies = {
enemies: EnemyInstances,
};
totalApocalypseCasts = 0;
apocalypseWoundsPopped = 0;
//Logic that both counts the amount of Apocalypse cast by the player, as well as the amount of wounds popped by those apocalypse.
on_byPlayer_cast(event){
const spellId = event.ability.guid;
if(spellId === SPELLS.APOCALYPSE.id){
this.totalApocalypseCasts+=1;
const target = this.enemies.getEntity(event);
const currentTargetWounds = target && target.hasBuff(SPELLS.FESTERING_WOUND.id) ? target.getBuff(SPELLS.FESTERING_WOUND.id).stacks: 0;
if(currentTargetWounds > 4){
this.apocalypseWoundsPopped=this.apocalypseWoundsPopped + 4;
} else {
this.apocalypseWoundsPopped=this.apocalypseWoundsPopped + currentTargetWounds;
}
}
}
suggestions(when) {
const averageWoundsPopped = (this.apocalypseWoundsPopped/this.totalApocalypseCasts).toFixed(1);
//Getting 6 wounds on every Apocalypse isn't difficult and should be expected
when(averageWoundsPopped).isLessThan(4)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span>You are casting <SpellLink id={SPELLS.APOCALYPSE.id} /> with too few <SpellLink id={SPELLS.FESTERING_WOUND.id} /> on the target. When casting <SpellLink id={SPELLS.APOCALYPSE.id} />, make sure to have at least 4 <SpellLink id={SPELLS.FESTERING_WOUND.id} /> on the target.</span>)
.icon(SPELLS.APOCALYPSE.icon)
.actual(`An average ${(actual)} of Festering Wounds were popped by Apocalypse`)
.recommended(`${(recommended)} is recommended`)
.regular(recommended - 1).major(recommended - 2);
});
}
statistic() {
const averageWoundsPopped = (this.apocalypseWoundsPopped/this.totalApocalypseCasts).toFixed(1);
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.APOCALYPSE.id} />}
value={`${averageWoundsPopped}`}
label="Average Wounds Popped with Apocalypse"
tooltip={`You popped ${this.apocalypseWoundsPopped} wounds with ${this.totalApocalypseCasts} casts of Apocalypse.`}
/>
);
}
statisticOrder = STATISTIC_ORDER.CORE(6);
}
export default Apocalypse;
|
react-ui/src/components/Shared/Button.js | civicparty/legitometer | import React, { Component } from 'react';
class Button extends Component {
render() {
return (
<button className="button">
{this.props.text}
</button>
);
}
}
export default Button;
|
src/icons/Bug.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class Bug extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<path d="M374.64,127.327C345.365,88.512,303.062,64,256,64s-89.365,24.512-118.64,63.327c6.354,15.64,15.833,30,28.13,42.297
c24.176,24.176,56.319,37.49,90.51,37.49s66.334-13.314,90.51-37.49C358.807,157.327,368.286,142.966,374.64,127.327z"></path>
<path d="M126.836,142.824c-1.725,2.827-3.396,5.703-4.992,8.644c-2.926-1.84-5.319-3.74-7.745-5.773
c-1.171-0.981-2.954-3.949-4.546-7.35c5.41-11.314,1.181-25.037-9.914-31.261c-11.561-6.484-26.188-2.372-32.674,9.189
c-6.485,11.56-2.371,26.188,9.187,32.673c1.251,0.702,2.539,1.272,3.847,1.729c2.816,6.269,7.32,14.331,13.548,19.547
c4.184,3.507,8.792,7.117,15.204,10.674c-7.195,20.259-11.576,42.303-12.545,65.427c-11.026,0.207-18.619,2.1-25.474,4.122
c-4.16,1.227-8.192,3.395-11.823,5.852c-0.954-0.115-1.923-0.182-2.908-0.182c-13.255,0-24,10.745-24,24s10.745,24,24,24
c12.93,0,23.467-10.227,23.976-23.032c5.046-1.482,9.888-2.659,17.095-2.774c3.167,33.015,13.304,63.483,28.613,89.224
c-14.166,11.006-22.882,23.016-26.605,36.317c0,0-0.75,0.438-1.873,1.366c-0.982,0.794-1.932,1.65-2.804,2.619
c-8.865,9.855-8.062,25.031,1.793,33.895c9.854,8.865,25.028,8.062,33.893-1.793c8.087-8.988,8.095-22.381,0.558-31.395
c3.074-5.562,6.236-9.014,13.67-14.961C171.368,425.235,207.723,445.619,248,448V222.872
C194.764,219.954,149.229,188.138,126.836,142.824z"></path>
<path d="M456,256.114c-0.985,0-1.954,0.066-2.908,0.182c-3.631-2.457-7.663-4.625-11.823-5.852
c-6.854-2.021-14.447-3.915-25.474-4.122c-0.969-23.125-5.35-45.168-12.545-65.427c6.412-3.557,11.021-7.167,15.204-10.674
c6.228-5.216,10.731-13.278,13.548-19.547c1.308-0.458,2.596-1.028,3.847-1.729c11.558-6.485,15.672-21.114,9.187-32.673
c-6.485-11.561-21.113-15.673-32.674-9.189c-11.095,6.225-15.324,19.947-9.914,31.261c-1.592,3.401-3.375,6.369-4.546,7.35
c-2.426,2.033-4.819,3.933-7.745,5.773c-1.596-2.941-3.268-5.817-4.992-8.644c-22.393,45.314-67.928,77.13-121.164,80.048V448
c40.277-2.381,76.632-22.765,103.686-54.42c7.434,5.947,10.596,9.399,13.67,14.961c-7.537,9.014-7.529,22.406,0.558,31.395
c8.864,9.855,24.038,10.658,33.893,1.793c9.854-8.863,10.658-24.039,1.793-33.895c-0.872-0.969-1.821-1.825-2.804-2.619
c-1.123-0.929-1.873-1.366-1.873-1.366c-3.724-13.302-12.439-25.312-26.605-36.317c15.31-25.74,25.446-56.209,28.613-89.224
c7.207,0.115,12.049,1.292,17.095,2.774c0.509,12.806,11.046,23.032,23.976,23.032c13.255,0,24-10.745,24-24
S469.255,256.114,456,256.114z"></path>
</g>
</g>;
} return <IconBase>
<g>
<path d="M374.64,127.327C345.365,88.512,303.062,64,256,64s-89.365,24.512-118.64,63.327c6.354,15.64,15.833,30,28.13,42.297
c24.176,24.176,56.319,37.49,90.51,37.49s66.334-13.314,90.51-37.49C358.807,157.327,368.286,142.966,374.64,127.327z"></path>
<path d="M126.836,142.824c-1.725,2.827-3.396,5.703-4.992,8.644c-2.926-1.84-5.319-3.74-7.745-5.773
c-1.171-0.981-2.954-3.949-4.546-7.35c5.41-11.314,1.181-25.037-9.914-31.261c-11.561-6.484-26.188-2.372-32.674,9.189
c-6.485,11.56-2.371,26.188,9.187,32.673c1.251,0.702,2.539,1.272,3.847,1.729c2.816,6.269,7.32,14.331,13.548,19.547
c4.184,3.507,8.792,7.117,15.204,10.674c-7.195,20.259-11.576,42.303-12.545,65.427c-11.026,0.207-18.619,2.1-25.474,4.122
c-4.16,1.227-8.192,3.395-11.823,5.852c-0.954-0.115-1.923-0.182-2.908-0.182c-13.255,0-24,10.745-24,24s10.745,24,24,24
c12.93,0,23.467-10.227,23.976-23.032c5.046-1.482,9.888-2.659,17.095-2.774c3.167,33.015,13.304,63.483,28.613,89.224
c-14.166,11.006-22.882,23.016-26.605,36.317c0,0-0.75,0.438-1.873,1.366c-0.982,0.794-1.932,1.65-2.804,2.619
c-8.865,9.855-8.062,25.031,1.793,33.895c9.854,8.865,25.028,8.062,33.893-1.793c8.087-8.988,8.095-22.381,0.558-31.395
c3.074-5.562,6.236-9.014,13.67-14.961C171.368,425.235,207.723,445.619,248,448V222.872
C194.764,219.954,149.229,188.138,126.836,142.824z"></path>
<path d="M456,256.114c-0.985,0-1.954,0.066-2.908,0.182c-3.631-2.457-7.663-4.625-11.823-5.852
c-6.854-2.021-14.447-3.915-25.474-4.122c-0.969-23.125-5.35-45.168-12.545-65.427c6.412-3.557,11.021-7.167,15.204-10.674
c6.228-5.216,10.731-13.278,13.548-19.547c1.308-0.458,2.596-1.028,3.847-1.729c11.558-6.485,15.672-21.114,9.187-32.673
c-6.485-11.561-21.113-15.673-32.674-9.189c-11.095,6.225-15.324,19.947-9.914,31.261c-1.592,3.401-3.375,6.369-4.546,7.35
c-2.426,2.033-4.819,3.933-7.745,5.773c-1.596-2.941-3.268-5.817-4.992-8.644c-22.393,45.314-67.928,77.13-121.164,80.048V448
c40.277-2.381,76.632-22.765,103.686-54.42c7.434,5.947,10.596,9.399,13.67,14.961c-7.537,9.014-7.529,22.406,0.558,31.395
c8.864,9.855,24.038,10.658,33.893,1.793c9.854-8.863,10.658-24.039,1.793-33.895c-0.872-0.969-1.821-1.825-2.804-2.619
c-1.123-0.929-1.873-1.366-1.873-1.366c-3.724-13.302-12.439-25.312-26.605-36.317c15.31-25.74,25.446-56.209,28.613-89.224
c7.207,0.115,12.049,1.292,17.095,2.774c0.509,12.806,11.046,23.032,23.976,23.032c13.255,0,24-10.745,24-24
S469.255,256.114,456,256.114z"></path>
</g>
</IconBase>;
}
};Bug.defaultProps = {bare: false} |
docs/src/stories/Readme.js | byumark/react-table | /* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import marked from 'marked'
//
import Readme from '!raw!../../../README.md'
import 'github-markdown-css/github-markdown.css'
export default class Story extends React.Component {
render () {
return <span className='markdown-body' dangerouslySetInnerHTML={{__html: marked(Readme)}} />
}
componentDidMount () {
global.Prism.highlightAll()
}
}
|
src/index.js | ptkach/react-redux | import React from 'react';
import createAll from './components/createAll';
export const { Provider, connect } = createAll(React);
|
src/components/table/EntryTable.js | metasfresh/metasfresh-webui-frontend | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import WidgetTooltip from '../widget/WidgetTooltip';
import MasterWidget from '../widget/MasterWidget';
/**
* @file Class based component.
* @module EntryTable
* @extends Component
*/
export default class EntryTable extends Component {
constructor(props) {
super(props);
this.state = {
tooltipToggled: null,
};
}
/**
* @method widgetTooltipToggle
* @summary ToDo: Describe the method
* @param {*} field
* @param {*} value
* @todo Write the documentation
*/
widgetTooltipToggle = (field, value) => {
const curVal = this.state.tooltipToggled;
let newVal = field;
if (value === false || field === curVal) {
newVal = null;
}
this.setState({
tooltipToggled: newVal,
});
};
/**
* @method renderElements
* @summary ToDo: Describe the method
* @param {*} elements
* @param {*} columnsCount
* @todo Write the documentation
*/
renderElements = (elements, columnsCount) => {
const {
data,
rowData,
extendedData,
addRefToWidgets,
handleBlurWidget,
layout,
dataId,
tabIndex,
fullScreen,
} = this.props;
const { tooltipToggled } = this.state;
const renderedArray = [];
const colWidth = Math.floor(12 / columnsCount);
if (rowData && rowData.size) {
for (let i = 0; i < columnsCount; i += 1) {
const elem = elements.cols[i];
if (elem && elem.fields && elem.fields.length) {
const fieldName = elem.fields ? elem.fields[0].field : '';
const widgetData = [rowData.get(0).fieldsByName[fieldName]];
const relativeDocId = data.ID && data.ID.value;
let tooltipData = null;
let tooltipWidget = elem.fields
? elem.fields.find((field) => {
if (field.type === 'Tooltip') {
tooltipData = rowData.get(0).fieldsByName[field.field];
if (tooltipData && tooltipData.value) {
return field;
}
}
return false;
})
: null;
renderedArray.push(
<td
key={`${fieldName}-cell-${i}`}
className={classnames(
`col-sm-${colWidth}`,
{
[`text-${widgetData.gridAlign}`]: widgetData.gridAlign,
'cell-disabled': widgetData[0].readonly,
'cell-mandatory': widgetData[0].mandatory,
},
`field-${widgetData[0].widgetType}`
)}
>
<MasterWidget
ref={addRefToWidgets}
entity="window"
windowType={layout.windowId}
dataId={dataId}
dataEntry={true}
fieldName={fieldName}
widgetData={widgetData}
isModal={false}
tabId={extendedData.tabId}
rowId={dataId}
relativeDocId={relativeDocId}
isAdvanced={false}
tabIndex={tabIndex}
fullScreen={fullScreen}
onBlurWidget={handleBlurWidget}
{...elem}
/>
{tooltipWidget && (
<WidgetTooltip
widget={tooltipWidget}
data={tooltipData}
fieldName={fieldName}
isToggled={tooltipToggled === fieldName}
onToggle={this.widgetTooltipToggle}
/>
)}
</td>
);
} else {
renderedArray.push(<td key={`__-cell-${i}`} />);
}
}
return renderedArray;
}
return null;
};
/**
* @method render
* @summary ToDo: Describe the method
* @todo Write the documentation
*/
render() {
const { rows } = this.props;
return (
<table className="table js-table layout-fix">
<tbody>
{rows.map((cols, idx) => {
return (
<tr className="table-row" key={`entry-row-${idx}`}>
{this.renderElements(cols, cols.colsCount)}
</tr>
);
})}
</tbody>
</table>
);
}
}
/**
* @typedef {object} Props Component props
* @prop {*} data
* @prop {*} rowData
* @prop {*} extendedData
* @prop {*} addRefToWidget
* @prop {*} handleBlurWidget
* @prop {*} layout
* @prop {*} dataId
* @prop {*} tabIndex
* @prop {*} fullScreen
* @prop {*} rows
* @todo Check props. Which proptype? Required or optional?
*/
EntryTable.propTypes = {
data: PropTypes.any,
rowData: PropTypes.any,
extendedData: PropTypes.any,
addRefToWidgets: PropTypes.any,
handleBlurWidget: PropTypes.any,
layout: PropTypes.any,
dataId: PropTypes.any,
tabIndex: PropTypes.any,
fullScreen: PropTypes.any,
rows: PropTypes.any,
};
|
packages/virtualized/src/virtualize.js | jquense/react-widgets | import React from 'react'
import VirtualList, {
getVirtualListProps,
virtualListPropTypes,
} from './VirtualList'
export default function virtualize(Widget) {
let name = Widget.name || Widget.displayName || 'Widget'
name = name[0] + name.slice(1)
return class extends React.Component {
static displayName = `Virtual${name}`
static propTypes = virtualListPropTypes
render() {
const { listProps, props } = getVirtualListProps(this.props)
return (
<Widget {...props} listComponent={VirtualList} listProps={listProps} />
)
}
}
}
|
app/javascript/mastodon/features/generic_not_found/index.js | yi0713/mastodon | import React from 'react';
import Column from '../ui/components/column';
import MissingIndicator from '../../components/missing_indicator';
const GenericNotFound = () => (
<Column>
<MissingIndicator fullPage />
</Column>
);
export default GenericNotFound;
|
docs/app/Examples/elements/List/Variations/index.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import { Message } from 'semantic-ui-react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const ListVariations = () => (
<ExampleSection title='Types'>
<ComponentExample
title='Horizontal'
description='A list can be formatted to have items appear horizontally'
examplePath='elements/List/Variations/ListExampleHorizontal'
/>
<ComponentExample examplePath='elements/List/Variations/ListExampleHorizontalOrdered' />
<ComponentExample examplePath='elements/List/Variations/ListExampleHorizontalBulleted' />
<ComponentExample
title='Inverted'
description='A list can be inverted to appear on a dark background'
examplePath='elements/List/Variations/ListExampleInverted'
/>
<ComponentExample
title='Selection'
description='A selection list formats list items as possible choices'
examplePath='elements/List/Variations/ListExampleSelection'
/>
<ComponentExample
title='Animated'
description='A list can animate to set the current item apart from the list'
examplePath='elements/List/Variations/ListExampleAnimated'
>
<Message info>
Be sure content can fit on one line, otherwise text content will reflow when hovered.
</Message>
</ComponentExample>
<ComponentExample
title='Relaxed'
description='A list can relax its padding to provide more negative space'
examplePath='elements/List/Variations/ListExampleRelaxed'
/>
<ComponentExample examplePath='elements/List/Variations/ListExampleRelaxedHorizontal' />
<ComponentExample examplePath='elements/List/Variations/ListExampleVeryRelaxed' />
<ComponentExample examplePath='elements/List/Variations/ListExampleVeryRelaxedHorizontal' />
<ComponentExample
title='Divided'
description='A list can show divisions between content'
examplePath='elements/List/Variations/ListExampleDivided'
/>
<ComponentExample
title='Celled'
description='A list can divide its items into cells'
examplePath='elements/List/Variations/ListExampleCelled'
/>
<ComponentExample examplePath='elements/List/Variations/ListExampleCelledOrdered' />
<ComponentExample examplePath='elements/List/Variations/ListExampleCelledHorizontal' />
<ComponentExample
title='Size'
description='A list can vary in size'
examplePath='elements/List/Variations/ListExampleSizes'
/>
</ExampleSection>
)
export default ListVariations
|
packages/ui-toolkit/src/styleguide/logo.js | yldio/joyent-portal | import React from 'react';
export default () => (
<svg
width="100"
height="22"
viewBox="0 0 100 22"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
>
<desc>Created using Figma</desc>
<g id="Canvas" transform="translate(-7602 299)">
<g id="Joyent">
<use
xlinkHref="#path0_fill"
transform="translate(7602 -299)"
fill="#FFF"
id="Vector"
/>
</g>
</g>
<defs>
<path
id="path0_fill"
d="M 19.0191 15.8436C 20.2064 17.1102 21.9142 18.1144 24.3866 18.1144C 26.2771 18.1144 27.8447 17.5596 28.9131 16.478C 29.9815 15.3963 30.555 13.8589 30.555 11.7687L 30.555 0.774118C 30.555 0.630972 30.4988 0.493689 30.3988 0.392469C 30.2989 0.29125 30.1632 0.234386 30.0218 0.234386L 27.1565 0.234386C 27.0151 0.234386 26.8794 0.29125 26.7795 0.392469C 26.6795 0.493689 26.6233 0.630972 26.6233 0.774118L 26.6233 11.5924C 26.6233 13.6331 25.7269 14.5126 24.2868 14.5126C 23.2248 14.5126 22.3539 14.018 21.4915 13.16C 21.4403 13.1089 21.3795 13.0689 21.3127 13.0422C 21.2458 13.0156 21.1743 13.0029 21.1025 13.0049C 21.0307 13.0069 20.96 13.0236 20.8947 13.0539C 20.8295 13.0843 20.7709 13.1277 20.7226 13.1815L 19.0106 15.1168C 18.9228 15.2175 18.875 15.3476 18.8766 15.4819C 18.8782 15.6162 18.9289 15.7451 19.0191 15.8436ZM 32.6982 11.1903L 32.6982 11.1408C 32.6982 7.27026 35.7824 4.11573 39.9371 4.11573C 44.0918 4.11573 47.125 7.2122 47.125 11.0914L 47.125 11.1408C 47.125 15.0114 44.0408 18.166 39.8861 18.166C 35.7314 18.166 32.6982 15.0673 32.6982 11.1882L 32.6982 11.1903ZM 43.3951 11.1903L 43.3951 11.1408C 43.3951 9.15179 41.9783 7.41433 39.8882 7.41433C 37.7238 7.41433 36.4302 9.10234 36.4302 11.0914L 36.4302 11.1408C 36.4302 13.1299 37.8491 14.8674 39.9371 14.8674C 42.1015 14.8652 43.3951 13.1772 43.3951 11.1882L 43.3951 11.1903ZM 61.3075 11.1903L 61.3075 11.1408C 61.3075 7.28746 64.0179 4.11573 67.8922 4.11573C 72.3528 4.11573 74.3855 7.61646 74.3855 11.444C 74.3855 11.601 74.3855 11.7687 74.3685 11.9451C 74.3604 12.082 74.3009 12.2106 74.2022 12.3045C 74.1035 12.3985 73.973 12.4506 73.8375 12.4504L 65.0629 12.4504C 65.4368 14.1879 66.6305 15.0953 68.3213 15.0953C 69.3861 15.1216 70.421 14.7373 71.2164 14.0201C 71.3139 13.9392 71.4367 13.8961 71.5628 13.8984C 71.6889 13.9008 71.8101 13.9485 71.9046 14.033L 73.3214 15.3017C 73.3752 15.3496 73.419 15.4079 73.4501 15.4733C 73.4812 15.5386 73.499 15.6096 73.5024 15.6821C 73.5057 15.7546 73.4946 15.827 73.4697 15.895C 73.4448 15.963 73.4067 16.0252 73.3575 16.078C 72.1361 17.3897 70.4602 18.1767 68.2703 18.1767C 64.2664 18.1638 61.3054 15.3189 61.3054 11.1882L 61.3075 11.1903ZM 70.7109 10.0571C 70.4878 8.33682 69.4916 7.18639 67.9007 7.18639C 66.3098 7.18639 65.3136 8.31962 65.0162 10.0571L 70.7109 10.0571ZM 76.3673 4.8963L 76.3673 17.3166C 76.3673 17.4597 76.4235 17.597 76.5235 17.6982C 76.6234 17.7995 76.7591 17.8563 76.9005 17.8563L 79.6172 17.8563C 79.7586 17.8563 79.8942 17.7995 79.9941 17.6982C 80.0941 17.597 80.1503 17.4597 80.1503 17.3166L 80.1503 10.3323C 80.1503 8.5196 81.2782 7.14769 82.7205 7.14769C 84.1627 7.14769 84.7999 7.8831 84.7999 9.69583L 84.7999 17.323C 84.7999 17.4662 84.8561 17.6035 84.9561 17.7047C 85.0561 17.8059 85.1917 17.8628 85.3331 17.8628L 88.0498 17.8628C 88.1912 17.8628 88.3268 17.8059 88.4268 17.7047C 88.5268 17.6035 88.5829 17.4662 88.5829 17.323L 88.5829 9.12384C 88.5829 6.02737 86.9155 4.11358 84.0565 4.11358C 82.1448 4.11358 81.0212 5.14573 80.1503 6.27896L 80.1503 4.90275C 80.1503 4.7596 80.0941 4.62232 79.9941 4.5211C 79.8942 4.41988 79.7586 4.36301 79.6172 4.36301L 76.8983 4.36301C 76.7569 4.36301 76.6213 4.41988 76.5213 4.5211C 76.4213 4.62232 76.3652 4.7596 76.3652 4.90275L 76.3673 4.8963ZM 96.4251 18.0821C 97.3586 18.1054 98.2832 17.8941 99.1163 17.4671C 99.2046 17.4217 99.2789 17.3525 99.331 17.2672C 99.3831 17.1818 99.4109 17.0836 99.4115 16.9833L 99.4115 15.048C 99.4112 14.9625 99.3909 14.8783 99.3521 14.8024C 99.3134 14.7264 99.2574 14.6609 99.1888 14.6111C 99.1201 14.5613 99.0408 14.5288 98.9573 14.5162C 98.8738 14.5035 98.7885 14.5111 98.7085 14.5384C 98.3315 14.6566 97.939 14.7161 97.5445 14.7147C 96.6948 14.7147 96.3252 14.2846 96.3252 13.4051L 96.3252 7.63796L 98.9272 7.63796C 99.0686 7.63796 99.2042 7.5811 99.3042 7.47988C 99.4042 7.37866 99.4604 7.24138 99.4604 7.09823L 99.4604 4.90275C 99.4604 4.7596 99.4042 4.62232 99.3042 4.5211C 99.2042 4.41988 99.0686 4.36301 98.9272 4.36301L 96.3252 4.36301L 96.3252 1.45362C 96.3252 1.31048 96.2691 1.17319 96.1691 1.07197C 96.0691 0.970753 95.9335 0.913889 95.7921 0.913889L 93.0754 0.913889C 92.934 0.913889 92.7984 0.970753 92.6984 1.07197C 92.5984 1.17319 92.5422 1.31048 92.5422 1.45362L 92.5422 4.36516L 91.1276 4.36516C 90.9862 4.36516 90.8506 4.42203 90.7506 4.52325C 90.6506 4.62447 90.5944 4.76175 90.5944 4.9049L 90.5944 7.09823C 90.5944 7.24138 90.6506 7.37866 90.7506 7.47988C 90.8506 7.5811 90.9862 7.63796 91.1276 7.63796L 92.5422 7.63796L 92.5422 14.0352C 92.5443 17.1575 94.1119 18.0886 96.4251 18.0886L 96.4251 18.0821ZM 8.97427 -6.56228e-08C 7.19933 -6.56228e-08 5.46425 0.532834 3.98844 1.53112C 2.51262 2.52941 1.36237 3.94831 0.683129 5.6084C 0.00388831 7.2685 -0.173832 9.09521 0.172442 10.8576C 0.518716 12.6199 1.37343 14.2387 2.62851 15.5093C 3.88358 16.7799 5.48264 17.6451 7.22348 17.9957C 8.96432 18.3463 10.7687 18.1663 12.4086 17.4787C 14.0484 16.7911 15.45 15.6266 16.4361 14.1326C 17.4222 12.6385 17.9485 10.882 17.9485 9.08513C 17.9485 6.67561 17.003 4.36477 15.32 2.66097C 13.637 0.957181 11.3544 -6.56228e-08 8.97427 -6.56228e-08ZM 14.5904 10.3603C 14.5904 10.4664 14.5487 10.5681 14.4746 10.6431C 14.4005 10.7181 14.3001 10.7602 14.1953 10.7602L 10.6353 10.7602L 10.6353 14.362C 10.6353 14.4681 10.5937 14.5698 10.5196 14.6449C 10.4455 14.7199 10.345 14.762 10.2402 14.762L 7.71044 14.762C 7.65856 14.7629 7.60701 14.7534 7.55876 14.734C 7.5105 14.7147 7.46647 14.686 7.42919 14.6494C 7.39192 14.6129 7.36211 14.5693 7.34149 14.5211C 7.32086 14.4729 7.30982 14.421 7.30899 14.3685L 7.30899 10.7667L 3.75539 10.7667C 3.70297 10.7667 3.65107 10.7561 3.60271 10.7356C 3.55436 10.7151 3.51052 10.6851 3.47375 10.6473C 3.43698 10.6094 3.40801 10.5646 3.38853 10.5153C 3.36906 10.466 3.35946 10.4133 3.36031 10.3603L 3.36031 7.80569C 3.36031 7.69961 3.40193 7.59788 3.47603 7.52287C 3.55012 7.44787 3.65061 7.40573 3.75539 7.40573L 7.30899 7.40573L 7.30899 3.80178C 7.30899 3.6957 7.35061 3.59397 7.4247 3.51896C 7.4988 3.44396 7.59929 3.40182 7.70407 3.40182L 10.2402 3.40182C 10.345 3.40182 10.4455 3.44396 10.5196 3.51896C 10.5937 3.59397 10.6353 3.6957 10.6353 3.80178L 10.6353 7.40358L 14.1932 7.40358C 14.2979 7.40358 14.3984 7.44572 14.4725 7.52072C 14.5466 7.59573 14.5882 7.69746 14.5882 7.80354L 14.5904 10.3603ZM 60.3071 4.36516L 57.533 4.36516C 57.4202 4.36512 57.3102 4.40132 57.219 4.46855C 57.1278 4.53579 57.06 4.63059 57.0254 4.73932L 54.2938 13.446L 51.49 4.73287C 51.4544 4.6257 51.3865 4.53255 51.2957 4.46657C 51.205 4.4006 51.0962 4.36512 50.9845 4.36516L 47.9746 4.36516C 47.8881 4.36549 47.8029 4.38713 47.7265 4.42822C 47.6501 4.4693 47.5847 4.52861 47.536 4.601C 47.4873 4.6734 47.4567 4.75672 47.4469 4.84375C 47.4371 4.93079 47.4483 5.01894 47.4797 5.10058L 52.2971 17.5961C 52.5223 18.1681 52.0571 18.7917 51.2181 18.7917C 50.6354 18.7797 50.0553 18.7076 49.487 18.5767C 49.407 18.5494 49.3217 18.5418 49.2382 18.5545C 49.1547 18.5671 49.0753 18.5997 49.0067 18.6494C 48.938 18.6992 48.882 18.7647 48.8433 18.8407C 48.8046 18.9167 48.7842 19.0008 48.7839 19.0863L 48.7839 21.0216C 48.7845 21.1219 48.8123 21.2201 48.8644 21.3055C 48.9165 21.3908 48.9908 21.46 49.0792 21.5054C 49.8077 21.886 50.7083 22 51.8235 22C 54.2003 22 54.9926 20.4668 55.9527 18.1789L 60.8062 5.09198C 60.836 5.01045 60.8459 4.92286 60.835 4.83665C 60.8242 4.75043 60.7929 4.66815 60.7439 4.59679C 60.6949 4.52543 60.6296 4.46711 60.5535 4.42678C 60.4775 4.38646 60.3929 4.36532 60.3071 4.36516Z"
/>
</defs>
</svg>
);
|
src/App.js | theCoolKidsJavaScriptMeetup/PeoriaHackathon | import React, { Component } from 'react';
import { BrowserRouter as Router } from 'react-router-dom'
import Firebase from 'firebase'
import Navigation from './components/Navigation';
import Footer from './components/Footer';
import Main from './components/Main';
import Sponsors from './components/Sponsors';
import Registration from './components/Registration';
import FAQ from './components/FAQ';
import RegistrationForm from './components/RegistrationForm';
import CreateTeamForm from './components/CreateTeamForm';
import JoinTeamForm from './components/JoinTeamForm';
import RegistrationSuccess from './components/RegistrationSuccess';
import ScrollToTopRoute from './components/ScrollToTopRoute';
import './App.css?ver=1.1';
class App extends Component {
componentWillMount () {
var config = {
apiKey: "AIzaSyAR6WiLvKXj9_nS8NZELe7xhHLVxIov70E",
authDomain: "peoria-hackathon-8b9e7.firebaseapp.com",
databaseURL: "https://peoria-hackathon-8b9e7.firebaseio.com",
projectId: "peoria-hackathon-8b9e7",
storageBucket: "peoria-hackathon-8b9e7.appspot.com",
messagingSenderId: "454113892052"
};
Firebase.initializeApp(config);
}
render() {
return (
<Router>
<div className="App">
<Navigation />
<ScrollToTopRoute exact path="/" component={Main}/>
<ScrollToTopRoute exact path="/sponsors" component={Sponsors}/>
<ScrollToTopRoute exact path="/registration" component={Registration}/>
<ScrollToTopRoute exact path="/faq" component={FAQ}/>
<ScrollToTopRoute path='/register/:id' component={RegistrationForm} />
<ScrollToTopRoute path='/registerTeam/join/:id' component={JoinTeamForm} />
<ScrollToTopRoute path='/registerTeam/create' component={CreateTeamForm} />
<ScrollToTopRoute path='/registered/:id' component={RegistrationSuccess} />
<Footer />
</div>
</Router>
);
}
}
export default App;
|
src/svg-icons/av/pause-circle-filled.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvPauseCircleFilled = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 14H9V8h2v8zm4 0h-2V8h2v8z"/>
</SvgIcon>
);
AvPauseCircleFilled = pure(AvPauseCircleFilled);
AvPauseCircleFilled.displayName = 'AvPauseCircleFilled';
AvPauseCircleFilled.muiName = 'SvgIcon';
export default AvPauseCircleFilled;
|
web/src/components/RecipeSearch.js | Takaitra/RecipeRunt | import React from 'react';
const RecipeSearch = () => {
return (
<div className="section no-pad-bot" id="index-banner">
<div className="container">
<div className="search-wrapper row center">
<input id="search" className="autocomplete"/><i className="material-icons">search</i>
<label htmlFor="search">Autocomplete</label>
</div>
</div>
</div>
);
};
export default RecipeSearch;
|
src/Alert.js | bbc/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
const Alert = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
onDismiss: React.PropTypes.func,
dismissAfter: React.PropTypes.number,
closeLabel: React.PropTypes.string
},
getDefaultProps() {
return {
bsClass: 'alert',
bsStyle: 'info',
closeLabel: 'Close Alert'
};
},
renderDismissButton() {
return (
<button
type="button"
className="close"
onClick={this.props.onDismiss}
aria-hidden="true">
<span>×</span>
</button>
);
},
renderSrOnlyDismissButton() {
return (
<button
type="button"
className="close sr-only"
onClick={this.props.onDismiss}>
{this.props.closeLabel}
</button>
);
},
render() {
let classes = this.getBsClassSet();
let isDismissable = !!this.props.onDismiss;
classes['alert-dismissable'] = isDismissable;
return (
<div {...this.props} role="alert" className={classNames(this.props.className, classes)}>
{isDismissable ? this.renderDismissButton() : null}
{this.props.children}
{isDismissable ? this.renderSrOnlyDismissButton() : null}
</div>
);
},
componentDidMount() {
if (this.props.dismissAfter && this.props.onDismiss) {
this.dismissTimer = setTimeout(this.props.onDismiss, this.props.dismissAfter);
}
},
componentWillUnmount() {
clearTimeout(this.dismissTimer);
}
});
export default Alert;
|
client/components/init/weboob-readme.js | ZeHiro/kresus | import React from 'react';
import { connect } from 'react-redux';
import { get } from '../../store';
import { translate as $t, MIN_WEBOOB_VERSION as minVersion } from '../../helpers';
import ExternalLink from '../ui/external-link';
import LocaleSelector from '../settings/customization/locale-selector';
import { repository } from '../../../package.json';
export default connect(state => {
return {
version: get.weboobVersion(state)
};
})(props => {
const { version } = props;
const installedText = version
? $t('client.weboobinstallreadme.working_version', { version })
: $t('client.weboobinstallreadme.not_working');
return (
<div>
<header>
<LocaleSelector />
<h1>{$t('client.weboobinstallreadme.title', { minVersion })}</h1>
</header>
<div>
{$t('client.weboobinstallreadme.content', { minVersion, installedText })}
<ExternalLink href={`${repository.url}/blob/master/README.md`}>
{'README'} <i className="fa fa-external-link" />
</ExternalLink>
</div>
</div>
);
});
|
src/components/presentational/CartMenu/CartMenu.js | AurimasSk/DemoStore | import React from 'react';
import PropTypes from 'prop-types';
const CartMenu = ( {productsInCart} ) => {
return (
<div>
<div className="cart-menu-overlay-div" />
{productsInCart.length > 0 ? productsInCart.map(currentProduct => {
<h4> {currentProduct.name} </h4>;
})
: <h2> There is no products added into cart yet</h2>
}
</div>
);
};
CartMenu.propTypes = {
productsInCart: PropTypes.array.isRequired
};
export default CartMenu; |
shared/components/App/AsyncEdit/EditRoute.js | deanslamajr/trakta.co | import React from 'react'
import Switch from 'react-router-dom/Switch'
import Route from 'react-router-dom/Route'
import Redirect from 'react-router/Redirect'
import withStyles from 'isomorphic-style-loader/lib/withStyles'
import { compose } from 'redux'
import { connect } from 'react-redux'
import Helmet from 'react-helmet'
import Staging from './AsyncStaging'
import Cleanup from './AsyncCleanup'
import Recorder from './AsyncRecorder'
import Slices from './AsyncSlices'
import config from '../../../../config'
import {
setName as setTrakName,
reset as resetTrak,
setShouldFetchInstances
} from '../../../actions/trak'
import { setStagedSample, setStagedObjectUrl } from '../../../actions/recorder'
import * as selectors from '../../../reducers'
import styles from './styles.css'
class EditRoute extends React.Component {
constructor (props) {
super(props)
const trakNameFromUrl = this.props.match.url.split('/')[2]
this.props.setTrakName(trakNameFromUrl)
this._resetTrak = this._resetTrak.bind(this)
}
_resetTrak () {
this.props.setShouldFetchInstances(true)
this.props.setStagedObjectUrl(undefined)
this.props.setStagedSample({
startTime: 0,
volume: 0,
panning: 0,
duration: 0,
loopCount: 0,
loopPadding: 0
})
this.props.resetTrak()
const { getPlaylistRenderer } = require('../../../../client/lib/PlaylistRenderer')
const playlistRenderer = getPlaylistRenderer()
playlistRenderer.clearPlayer()
}
render () {
return (
<div className={styles.container}>
<Switch>
<Redirect exact from='/e/new' to='/e/new/recorder' />
<Route exact path={this.props.match.url} render={props => (
<React.Fragment>
<Helmet>
<title>{`${this.props.trakName} - ${config('appTitle')}`}</title>
</Helmet>
<Slices
{...props}
addItemToNavBar={this.props.addItemToNavBar}
resetTrak={this._resetTrak}
/>
</React.Fragment>
)} />
<Route path={`${this.props.match.url}/recorder`} render={props => (
<React.Fragment>
<Helmet>
<title>{`${this.props.trakName} - recorder - ${config('appTitle')}`}</title>
</Helmet>
<Recorder {...props} addItemToNavBar={this.props.addItemToNavBar} />
</React.Fragment>
)} />
{
this.props.objectUrl && ([
<Route key={0} path={`${this.props.match.url}/cleanup`} render={props => (
<React.Fragment>
<Helmet>
<title>{`${this.props.trakName} - cleanup - ${config('appTitle')}`}</title>
</Helmet>
<Cleanup {...props} addItemToNavBar={this.props.addItemToNavBar} />
</React.Fragment>
)} />,
<Route key={1} path={`${this.props.match.url}/staging`} render={props => (
<React.Fragment>
<Helmet>
<title>{`${this.props.trakName} - staging - ${config('appTitle')}`}</title>
</Helmet>
<Staging {...props} addItemToNavBar={this.props.addItemToNavBar} />
</React.Fragment>
)} />
])
}
<Redirect to={{ pathname: this.props.match.url }} />
</Switch>
</div>
)
}
}
function mapStateToProps (state) {
return {
objectUrl: selectors.getStagedObjectUrl(state),
trakName: selectors.getTrakName(state)
}
}
const mapActionsToProps = {
setTrakName,
resetTrak,
setStagedSample,
setStagedObjectUrl,
setShouldFetchInstances
}
export { EditRoute }
export default compose(
withStyles(styles),
connect(mapStateToProps, mapActionsToProps)
)(EditRoute)
|
NewsAppDemo/index.android.js | SpadeZach/RNNewsApp | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
//引入外部的组件
var Main = require('./Compoent/Main');
export default class NewsAppDemo extends Component {
render() {
return (
<Main />
);
}
}
const styles = StyleSheet.create({
});
AppRegistry.registerComponent('NewsAppDemo', () => NewsAppDemo);
|
docs/src/pages/demos/text-fields/ComposedTextField.js | AndriusBil/material-ui | /* eslint-disable flowtype/require-valid-file-annotation */
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Input, { InputLabel } from 'material-ui/Input';
import { FormControl, FormHelperText } from 'material-ui/Form';
const styles = theme => ({
container: {
display: 'flex',
flexWrap: 'wrap',
},
formControl: {
margin: theme.spacing.unit,
},
});
class ComposedTextField extends React.Component {
state = {
name: 'Composed TextField',
};
handleChange = event => {
this.setState({ name: event.target.value });
};
render() {
const classes = this.props.classes;
return (
<div className={classes.container}>
<FormControl className={classes.formControl}>
<InputLabel htmlFor="name-simple">Name</InputLabel>
<Input id="name-simple" value={this.state.name} onChange={this.handleChange} />
</FormControl>
<FormControl className={classes.formControl}>
<InputLabel htmlFor="name-helper">Name</InputLabel>
<Input id="name-helper" value={this.state.name} onChange={this.handleChange} />
<FormHelperText>Some important helper text</FormHelperText>
</FormControl>
<FormControl className={classes.formControl} disabled>
<InputLabel htmlFor="name-disabled">Name</InputLabel>
<Input id="name-disabled" value={this.state.name} onChange={this.handleChange} />
<FormHelperText>Disabled</FormHelperText>
</FormControl>
<FormControl className={classes.formControl} error>
<InputLabel htmlFor="name-error">Name</InputLabel>
<Input id="name-error" value={this.state.name} onChange={this.handleChange} />
<FormHelperText>Error</FormHelperText>
</FormControl>
</div>
);
}
}
ComposedTextField.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(ComposedTextField);
|
components/list/List.js | react-toolbox/react-toolbox | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { themr } from 'react-css-themr';
import { LIST } from '../identifiers';
import InjectListItem from './ListItem';
const mergeProp = (propName, child, parent) => (
child[propName] !== undefined
? child[propName]
: parent[propName]
);
const factory = (ListItem) => {
class List extends Component {
static propTypes = {
children: PropTypes.node,
className: PropTypes.string,
ripple: PropTypes.bool, // eslint-disable-line react/no-unused-prop-types
selectable: PropTypes.bool, // eslint-disable-line react/no-unused-prop-types
theme: PropTypes.shape({
list: PropTypes.string,
}),
};
static defaultProps = {
className: '',
ripple: false,
selectable: false,
};
renderItems() {
return React.Children.map(this.props.children, (item) => {
if (item === null || item === undefined) {
return item;
} if (item.type === ListItem) {
const selectable = mergeProp('selectable', item.props, this.props);
const ripple = mergeProp('ripple', item.props, this.props);
return React.cloneElement(item, { selectable, ripple });
}
return React.cloneElement(item);
});
}
render() {
return (
<ul data-react-toolbox="list" className={classnames(this.props.theme.list, this.props.className)}>
{this.renderItems()}
</ul>
);
}
}
return List;
};
const List = factory(InjectListItem);
export default themr(LIST)(List);
export { factory as listFactory };
export { List };
|
Sources/ewsnodejs-server/node_modules/react-transition-group/esm/Transition.js | nihospr01/OpenSpeechPlatform-UCSD | import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom';
import config from './config';
import { timeoutsShape } from './utils/PropTypes';
import TransitionGroupContext from './TransitionGroupContext';
export var UNMOUNTED = 'unmounted';
export var EXITED = 'exited';
export var ENTERING = 'entering';
export var ENTERED = 'entered';
export var EXITING = 'exiting';
/**
* The Transition component lets you describe a transition from one component
* state to another _over time_ with a simple declarative API. Most commonly
* it's used to animate the mounting and unmounting of a component, but can also
* be used to describe in-place transition states as well.
*
* ---
*
* **Note**: `Transition` is a platform-agnostic base component. If you're using
* transitions in CSS, you'll probably want to use
* [`CSSTransition`](https://reactcommunity.org/react-transition-group/css-transition)
* instead. It inherits all the features of `Transition`, but contains
* additional features necessary to play nice with CSS transitions (hence the
* name of the component).
*
* ---
*
* By default the `Transition` component does not alter the behavior of the
* component it renders, it only tracks "enter" and "exit" states for the
* components. It's up to you to give meaning and effect to those states. For
* example we can add styles to a component when it enters or exits:
*
* ```jsx
* import { Transition } from 'react-transition-group';
*
* const duration = 300;
*
* const defaultStyle = {
* transition: `opacity ${duration}ms ease-in-out`,
* opacity: 0,
* }
*
* const transitionStyles = {
* entering: { opacity: 1 },
* entered: { opacity: 1 },
* exiting: { opacity: 0 },
* exited: { opacity: 0 },
* };
*
* const Fade = ({ in: inProp }) => (
* <Transition in={inProp} timeout={duration}>
* {state => (
* <div style={{
* ...defaultStyle,
* ...transitionStyles[state]
* }}>
* I'm a fade Transition!
* </div>
* )}
* </Transition>
* );
* ```
*
* There are 4 main states a Transition can be in:
* - `'entering'`
* - `'entered'`
* - `'exiting'`
* - `'exited'`
*
* Transition state is toggled via the `in` prop. When `true` the component
* begins the "Enter" stage. During this stage, the component will shift from
* its current transition state, to `'entering'` for the duration of the
* transition and then to the `'entered'` stage once it's complete. Let's take
* the following example (we'll use the
* [useState](https://reactjs.org/docs/hooks-reference.html#usestate) hook):
*
* ```jsx
* function App() {
* const [inProp, setInProp] = useState(false);
* return (
* <div>
* <Transition in={inProp} timeout={500}>
* {state => (
* // ...
* )}
* </Transition>
* <button onClick={() => setInProp(true)}>
* Click to Enter
* </button>
* </div>
* );
* }
* ```
*
* When the button is clicked the component will shift to the `'entering'` state
* and stay there for 500ms (the value of `timeout`) before it finally switches
* to `'entered'`.
*
* When `in` is `false` the same thing happens except the state moves from
* `'exiting'` to `'exited'`.
*/
var Transition = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(Transition, _React$Component);
function Transition(props, context) {
var _this;
_this = _React$Component.call(this, props, context) || this;
var parentGroup = context; // In the context of a TransitionGroup all enters are really appears
var appear = parentGroup && !parentGroup.isMounting ? props.enter : props.appear;
var initialStatus;
_this.appearStatus = null;
if (props.in) {
if (appear) {
initialStatus = EXITED;
_this.appearStatus = ENTERING;
} else {
initialStatus = ENTERED;
}
} else {
if (props.unmountOnExit || props.mountOnEnter) {
initialStatus = UNMOUNTED;
} else {
initialStatus = EXITED;
}
}
_this.state = {
status: initialStatus
};
_this.nextCallback = null;
return _this;
}
Transition.getDerivedStateFromProps = function getDerivedStateFromProps(_ref, prevState) {
var nextIn = _ref.in;
if (nextIn && prevState.status === UNMOUNTED) {
return {
status: EXITED
};
}
return null;
} // getSnapshotBeforeUpdate(prevProps) {
// let nextStatus = null
// if (prevProps !== this.props) {
// const { status } = this.state
// if (this.props.in) {
// if (status !== ENTERING && status !== ENTERED) {
// nextStatus = ENTERING
// }
// } else {
// if (status === ENTERING || status === ENTERED) {
// nextStatus = EXITING
// }
// }
// }
// return { nextStatus }
// }
;
var _proto = Transition.prototype;
_proto.componentDidMount = function componentDidMount() {
this.updateStatus(true, this.appearStatus);
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
var nextStatus = null;
if (prevProps !== this.props) {
var status = this.state.status;
if (this.props.in) {
if (status !== ENTERING && status !== ENTERED) {
nextStatus = ENTERING;
}
} else {
if (status === ENTERING || status === ENTERED) {
nextStatus = EXITING;
}
}
}
this.updateStatus(false, nextStatus);
};
_proto.componentWillUnmount = function componentWillUnmount() {
this.cancelNextCallback();
};
_proto.getTimeouts = function getTimeouts() {
var timeout = this.props.timeout;
var exit, enter, appear;
exit = enter = appear = timeout;
if (timeout != null && typeof timeout !== 'number') {
exit = timeout.exit;
enter = timeout.enter; // TODO: remove fallback for next major
appear = timeout.appear !== undefined ? timeout.appear : enter;
}
return {
exit: exit,
enter: enter,
appear: appear
};
};
_proto.updateStatus = function updateStatus(mounting, nextStatus) {
if (mounting === void 0) {
mounting = false;
}
if (nextStatus !== null) {
// nextStatus will always be ENTERING or EXITING.
this.cancelNextCallback();
if (nextStatus === ENTERING) {
this.performEnter(mounting);
} else {
this.performExit();
}
} else if (this.props.unmountOnExit && this.state.status === EXITED) {
this.setState({
status: UNMOUNTED
});
}
};
_proto.performEnter = function performEnter(mounting) {
var _this2 = this;
var enter = this.props.enter;
var appearing = this.context ? this.context.isMounting : mounting;
var _ref2 = this.props.nodeRef ? [appearing] : [ReactDOM.findDOMNode(this), appearing],
maybeNode = _ref2[0],
maybeAppearing = _ref2[1];
var timeouts = this.getTimeouts();
var enterTimeout = appearing ? timeouts.appear : timeouts.enter; // no enter animation skip right to ENTERED
// if we are mounting and running this it means appear _must_ be set
if (!mounting && !enter || config.disabled) {
this.safeSetState({
status: ENTERED
}, function () {
_this2.props.onEntered(maybeNode);
});
return;
}
this.props.onEnter(maybeNode, maybeAppearing);
this.safeSetState({
status: ENTERING
}, function () {
_this2.props.onEntering(maybeNode, maybeAppearing);
_this2.onTransitionEnd(enterTimeout, function () {
_this2.safeSetState({
status: ENTERED
}, function () {
_this2.props.onEntered(maybeNode, maybeAppearing);
});
});
});
};
_proto.performExit = function performExit() {
var _this3 = this;
var exit = this.props.exit;
var timeouts = this.getTimeouts();
var maybeNode = this.props.nodeRef ? undefined : ReactDOM.findDOMNode(this); // no exit animation skip right to EXITED
if (!exit || config.disabled) {
this.safeSetState({
status: EXITED
}, function () {
_this3.props.onExited(maybeNode);
});
return;
}
this.props.onExit(maybeNode);
this.safeSetState({
status: EXITING
}, function () {
_this3.props.onExiting(maybeNode);
_this3.onTransitionEnd(timeouts.exit, function () {
_this3.safeSetState({
status: EXITED
}, function () {
_this3.props.onExited(maybeNode);
});
});
});
};
_proto.cancelNextCallback = function cancelNextCallback() {
if (this.nextCallback !== null) {
this.nextCallback.cancel();
this.nextCallback = null;
}
};
_proto.safeSetState = function safeSetState(nextState, callback) {
// This shouldn't be necessary, but there are weird race conditions with
// setState callbacks and unmounting in testing, so always make sure that
// we can cancel any pending setState callbacks after we unmount.
callback = this.setNextCallback(callback);
this.setState(nextState, callback);
};
_proto.setNextCallback = function setNextCallback(callback) {
var _this4 = this;
var active = true;
this.nextCallback = function (event) {
if (active) {
active = false;
_this4.nextCallback = null;
callback(event);
}
};
this.nextCallback.cancel = function () {
active = false;
};
return this.nextCallback;
};
_proto.onTransitionEnd = function onTransitionEnd(timeout, handler) {
this.setNextCallback(handler);
var node = this.props.nodeRef ? this.props.nodeRef.current : ReactDOM.findDOMNode(this);
var doesNotHaveTimeoutOrListener = timeout == null && !this.props.addEndListener;
if (!node || doesNotHaveTimeoutOrListener) {
setTimeout(this.nextCallback, 0);
return;
}
if (this.props.addEndListener) {
var _ref3 = this.props.nodeRef ? [this.nextCallback] : [node, this.nextCallback],
maybeNode = _ref3[0],
maybeNextCallback = _ref3[1];
this.props.addEndListener(maybeNode, maybeNextCallback);
}
if (timeout != null) {
setTimeout(this.nextCallback, timeout);
}
};
_proto.render = function render() {
var status = this.state.status;
if (status === UNMOUNTED) {
return null;
}
var _this$props = this.props,
children = _this$props.children,
_in = _this$props.in,
_mountOnEnter = _this$props.mountOnEnter,
_unmountOnExit = _this$props.unmountOnExit,
_appear = _this$props.appear,
_enter = _this$props.enter,
_exit = _this$props.exit,
_timeout = _this$props.timeout,
_addEndListener = _this$props.addEndListener,
_onEnter = _this$props.onEnter,
_onEntering = _this$props.onEntering,
_onEntered = _this$props.onEntered,
_onExit = _this$props.onExit,
_onExiting = _this$props.onExiting,
_onExited = _this$props.onExited,
_nodeRef = _this$props.nodeRef,
childProps = _objectWithoutPropertiesLoose(_this$props, ["children", "in", "mountOnEnter", "unmountOnExit", "appear", "enter", "exit", "timeout", "addEndListener", "onEnter", "onEntering", "onEntered", "onExit", "onExiting", "onExited", "nodeRef"]);
return (
/*#__PURE__*/
// allows for nested Transitions
React.createElement(TransitionGroupContext.Provider, {
value: null
}, typeof children === 'function' ? children(status, childProps) : React.cloneElement(React.Children.only(children), childProps))
);
};
return Transition;
}(React.Component);
Transition.contextType = TransitionGroupContext;
Transition.propTypes = process.env.NODE_ENV !== "production" ? {
/**
* A React reference to DOM element that need to transition:
* https://stackoverflow.com/a/51127130/4671932
*
* - When `nodeRef` prop is used, `node` is not passed to callback functions
* (e.g. `onEnter`) because user already has direct access to the node.
* - When changing `key` prop of `Transition` in a `TransitionGroup` a new
* `nodeRef` need to be provided to `Transition` with changed `key` prop
* (see
* [test/CSSTransition-test.js](https://github.com/reactjs/react-transition-group/blob/13435f897b3ab71f6e19d724f145596f5910581c/test/CSSTransition-test.js#L362-L437)).
*/
nodeRef: PropTypes.shape({
current: typeof Element === 'undefined' ? PropTypes.any : PropTypes.instanceOf(Element)
}),
/**
* A `function` child can be used instead of a React element. This function is
* called with the current transition status (`'entering'`, `'entered'`,
* `'exiting'`, `'exited'`), which can be used to apply context
* specific props to a component.
*
* ```jsx
* <Transition in={this.state.in} timeout={150}>
* {state => (
* <MyComponent className={`fade fade-${state}`} />
* )}
* </Transition>
* ```
*/
children: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.element.isRequired]).isRequired,
/**
* Show the component; triggers the enter or exit states
*/
in: PropTypes.bool,
/**
* By default the child component is mounted immediately along with
* the parent `Transition` component. If you want to "lazy mount" the component on the
* first `in={true}` you can set `mountOnEnter`. After the first enter transition the component will stay
* mounted, even on "exited", unless you also specify `unmountOnExit`.
*/
mountOnEnter: PropTypes.bool,
/**
* By default the child component stays mounted after it reaches the `'exited'` state.
* Set `unmountOnExit` if you'd prefer to unmount the component after it finishes exiting.
*/
unmountOnExit: PropTypes.bool,
/**
* By default the child component does not perform the enter transition when
* it first mounts, regardless of the value of `in`. If you want this
* behavior, set both `appear` and `in` to `true`.
*
* > **Note**: there are no special appear states like `appearing`/`appeared`, this prop
* > only adds an additional enter transition. However, in the
* > `<CSSTransition>` component that first enter transition does result in
* > additional `.appear-*` classes, that way you can choose to style it
* > differently.
*/
appear: PropTypes.bool,
/**
* Enable or disable enter transitions.
*/
enter: PropTypes.bool,
/**
* Enable or disable exit transitions.
*/
exit: PropTypes.bool,
/**
* The duration of the transition, in milliseconds.
* Required unless `addEndListener` is provided.
*
* You may specify a single timeout for all transitions:
*
* ```jsx
* timeout={500}
* ```
*
* or individually:
*
* ```jsx
* timeout={{
* appear: 500,
* enter: 300,
* exit: 500,
* }}
* ```
*
* - `appear` defaults to the value of `enter`
* - `enter` defaults to `0`
* - `exit` defaults to `0`
*
* @type {number | { enter?: number, exit?: number, appear?: number }}
*/
timeout: function timeout(props) {
var pt = timeoutsShape;
if (!props.addEndListener) pt = pt.isRequired;
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return pt.apply(void 0, [props].concat(args));
},
/**
* Add a custom transition end trigger. Called with the transitioning
* DOM node and a `done` callback. Allows for more fine grained transition end
* logic. Timeouts are still used as a fallback if provided.
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed.
*
* ```jsx
* addEndListener={(node, done) => {
* // use the css transitionend event to mark the finish of a transition
* node.addEventListener('transitionend', done, false);
* }}
* ```
*/
addEndListener: PropTypes.func,
/**
* Callback fired before the "entering" status is applied. An extra parameter
* `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed.
*
* @type Function(node: HtmlElement, isAppearing: bool) -> void
*/
onEnter: PropTypes.func,
/**
* Callback fired after the "entering" status is applied. An extra parameter
* `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed.
*
* @type Function(node: HtmlElement, isAppearing: bool)
*/
onEntering: PropTypes.func,
/**
* Callback fired after the "entered" status is applied. An extra parameter
* `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed.
*
* @type Function(node: HtmlElement, isAppearing: bool) -> void
*/
onEntered: PropTypes.func,
/**
* Callback fired before the "exiting" status is applied.
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed.
*
* @type Function(node: HtmlElement) -> void
*/
onExit: PropTypes.func,
/**
* Callback fired after the "exiting" status is applied.
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed.
*
* @type Function(node: HtmlElement) -> void
*/
onExiting: PropTypes.func,
/**
* Callback fired after the "exited" status is applied.
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed
*
* @type Function(node: HtmlElement) -> void
*/
onExited: PropTypes.func
} : {}; // Name the function so it is clearer in the documentation
function noop() {}
Transition.defaultProps = {
in: false,
mountOnEnter: false,
unmountOnExit: false,
appear: false,
enter: true,
exit: true,
onEnter: noop,
onEntering: noop,
onEntered: noop,
onExit: noop,
onExiting: noop,
onExited: noop
};
Transition.UNMOUNTED = UNMOUNTED;
Transition.EXITED = EXITED;
Transition.ENTERING = ENTERING;
Transition.ENTERED = ENTERED;
Transition.EXITING = EXITING;
export default Transition; |
server/dashboard/js/components/DashboardEdit.react.js | timofey-barmin/mzbench | import React from 'react';
import DashboardStore from '../stores/DashboardStore';
import BenchStore from '../stores/BenchStore';
import GlobalStore from '../stores/GlobalStore';
import MZBenchRouter from '../utils/MZBenchRouter';
import MZBenchActions from '../actions/MZBenchActions';
import Autosuggest from 'react-autosuggest';
import Misc from '../utils/Misc';
import PropTypes from 'prop-types';
class SimpleSuggestion {
getTagSuggestions(value) {
if (value.indexOf("#") === -1) return [];
let allTags = GlobalStore.getAllTags();
let result = [];
let parts = value.split("#");
let lookup = parts.splice(-1, 1)[0];
let prefix = parts.join("#");
for (var i in allTags) {
if (allTags[i].indexOf(lookup) !== -1) {
result.push(prefix + "#" + allTags[i]);
}
}
return result;
}
getSuggestions(value, allValues) {
let result = [];
for (var i in allValues) {
if (allValues[i].indexOf(value) !== -1) {
result.push(allValues[i]);
}
}
return result;
}
getSuggestionValue(suggestion) {
return suggestion;
}
renderSuggestion(suggestion) {
return (
<span>{suggestion}</span>
);
}
}
class DashboardEdit extends React.Component {
constructor(props) {
super(props);
this._onUp = this._onUp.bind(this);
this._onDown = this._onDown.bind(this);
this._onDelete = this._onDelete.bind(this);
this._onChangeName = this._onChangeName.bind(this);
this._onChangeCriteria = this._onChangeCriteria.bind(this);
this._onChangeMetricFun = this._onChangeMetricFun.bind(this);
this._onChangeXEnvFun = this._onChangeXEnvFun.bind(this);
this._onChangeGroupEnvFun = this._onChangeGroupEnvFun.bind(this);
this._onChangeKind = this._onChangeKind.bind(this);
this._onChangeXAxis = this._onChangeXAxis.bind(this);
this._onChangeDescription = this._onChangeDescription.bind(this);
this._onTagSuggestionsUpdateRequested = this._onTagSuggestionsUpdateRequested.bind(this);
this._onMetricSuggestionsUpdateRequested = this._onMetricSuggestionsUpdateRequested.bind(this);
this._onGroupSuggestionsUpdateRequested = this._onGroupSuggestionsUpdateRequested.bind(this);
this._onXSuggestionsUpdateRequested = this._onXSuggestionsUpdateRequested.bind(this);
this._onCancel = this._onCancel.bind(this);
this._onAddChart = this._onAddChart.bind(this);
this._onSave = this._onSave.bind(this);
this._onChange = this._onChange.bind(this);
this._suggestion = new SimpleSuggestion();
this.autoUpdateHandler = null;
this.state = {suggestions : this._suggestion.getTagSuggestions(props.item.criteria)};
this.state = this._resolveState();
}
componentDidMount() {
BenchStore.onChange(this._onChange);
if (BenchStore.getTimelineId() != this.props.item.criteria)
MZBenchActions.getTimeline({q:this.props.item.criteria,
bench_id: undefined, limit: this.props.benchLimit}, this.props.item.criteria);
}
render() {
let item = this.props.item;
const inputProps = {
placeholder: 'Type a criteria',
value: item.criteria,
onChange : this._onChangeCriteria,
className: "form-control",
type: "text"
};
let total = this.state.total;
let found = total === -1 ? "⏳" : (total == this.props.benchLimit ? `> ${total}` : total);
return (
<div className="fluid-container">
<div className="row">
<div className="form-group col-md-6">
<label>Dashboard name</label>
<input type="text" defaultValue={item.name} onChange={this._onChangeName} className="form-control" placeholder="Type something" />
</div>
<div className="form-group col-md-3">
<label>Search query ({found} matching)</label>
<Autosuggest suggestions={this.state.suggestions}
getSuggestionValue={this._suggestion.getSuggestionValue}
onSuggestionsUpdateRequested={this._onTagSuggestionsUpdateRequested}
renderSuggestion={this._suggestion.renderSuggestion}
inputProps={inputProps} />
</div>
</div>
{item.charts.map(this.renderChart, this)}
<div className="row">
<div className="form-group col-md-9">
<button className="btn btn-info" onClick={this._onAddChart}><span className="glyphicon glyphicon-plus"></span>Add chart</button>
<button type="button" className="btn btn-success" onClick={this._onSave}>Save dashboard</button>
<button type="button" className="btn btn-danger" onClick={this._onCancel}>Cancel</button>
</div>
</div>
</div>
);
}
suggestionProps(placeholder, value, lambda) {
return {
placeholder: placeholder,
value: value,
onChange : lambda,
className: "form-control",
type: "text"
};
}
renderChart(chart, idx) {
const inputProps = this.suggestionProps('Type metric name', chart.metric, this._onChangeMetricFun(chart.id));
const inputXProps = this.suggestionProps('Type env name', chart.x_env, this._onChangeXEnvFun(chart.id));
const inputGroupProps = this.suggestionProps('Type env name', chart.group_env, this._onChangeGroupEnvFun(chart.id));
const kind = Misc.ucfirst(chart.kind) + " " + chart.size;
return (<div className="dashboard-config-row" key={chart.id}>
<div className="row">
<div className="form-group col-md-6">
<label>Metric name for Y</label>
<Autosuggest suggestions={this.state.metric_suggestions[idx]}
getSuggestionValue={this._suggestion.getSuggestionValue}
onSuggestionsUpdateRequested={this._onMetricSuggestionsUpdateRequested(chart.id)}
renderSuggestion={this._suggestion.renderSuggestion}
inputProps={inputProps} />
</div>
<div className="form-group col-md-3">
<label>Kind</label>
<select onChange={this._onChangeKind} rel={chart.id} defaultValue={kind} className="form-control">
<option value="Compare 5">Compare 5</option>
<option value="Compare 10">Compare 10</option>
<option value="Regression 0">Regression</option>
<option value="Group 5">Group 5 (XY chart)</option>
<option value="Group 10">Group 10 (XY chart)</option>
</select>
</div>
<div className="form-group col-md-3">
<button type="button" className="btn btn-danger" rel={chart.id} onClick={this._onDelete}><span className="glyphicon glyphicon-remove"></span></button>
</div>
</div>
<div className="row">
<div className="form-group col-md-6">
<label>{(chart.kind == "compare") ? "Env var for caption (optional)" : "Env var for groups (optional)"}</label>
<Autosuggest suggestions={this.state.group_suggestions[idx]}
getSuggestionValue={this._suggestion.getSuggestionValue}
onSuggestionsUpdateRequested={this._onGroupSuggestionsUpdateRequested(chart.id)}
renderSuggestion={this._suggestion.renderSuggestion}
inputProps={inputGroupProps} />
</div>
{(chart.kind == "group") ?
(<div className="form-group col-md-3">
<label>Env var for X-axis</label>
<Autosuggest suggestions={this.state.x_suggestions[idx]}
getSuggestionValue={this._suggestion.getSuggestionValue}
onSuggestionsUpdateRequested={this._onXSuggestionsUpdateRequested(chart.id)}
renderSuggestion={this._suggestion.renderSuggestion}
inputProps={inputXProps} />
</div>) : (chart.kind == "regression" ?
(<div className="col-md-3"><label>X-axis</label>
<select onChange={this._onChangeXAxis} rel={chart.id} defaultValue={chart.regression_x} className="form-control">
<option value="Number">Number</option>
<option value="Time">Time</option>
</select></div>)
: (<div className="col-md-3"></div>)) }
<div className="form-group col-md-3">
{idx > 0 ? (<button type="button" className="btn btn-info" rel={chart.id} onClick={this._onUp}><span className="glyphicon glyphicon-arrow-up"></span></button>) : null}
{idx > 0 ? (<span> </span>) : null}
{idx < (this.props.item.charts.length - 1) ? (<button type="button" className="btn btn-info" rel={chart.id} onClick={this._onDown}><span className="glyphicon glyphicon-arrow-down"></span></button>) : null}
</div>
</div>
<div className="row">
<div className="form-group col-md-9">
<label>Description (optional)</label>
<textarea rel={chart.id} onChange={this._onChangeDescription} className="form-control" rows="2" defaultValue={chart.description}></textarea>
</div>
</div>
</div>);
}
_onTagSuggestionsUpdateRequested({ value }) {
this.setState({
suggestions: this._suggestion.getTagSuggestions(value)
});
}
_onMetricSuggestionsUpdateRequested(id) {
let idx = this._getIdx(id);
return ({ value }) => {
this.state.metric_suggestions[idx] =
this._suggestion.getSuggestions(value,
this.props.item.charts[idx].kind == "compare" ? this.state.metrics : this.state.results);
this.setState(this.state);
}
}
_onXSuggestionsUpdateRequested(id) {
let idx = this._getIdx(id);
return ({ value }) => {
this.state.x_suggestions[idx] =
this._suggestion.getSuggestions(value, this.state.envs);
this.setState(this.state);
}
}
_onGroupSuggestionsUpdateRequested(id) {
let idx = this._getIdx(id);
return ({ value }) => {
this.state.group_suggestions[idx] =
this._suggestion.getSuggestions(value, this.state.envs);
this.setState(this.state);
}
}
_onChangeName(event) {
MZBenchActions.withSelectedDashboard((d) => {d.name = event.target.value});
}
_onCancel(event) {
event.preventDefault();
if (DashboardStore.isNewSelected()) {
MZBenchActions.resetNewDashboard();
MZBenchActions.selectDashboardById(undefined);
}
MZBenchRouter.navigate("/dashboard", {});
}
_onAddChart(event) {
event.preventDefault();
MZBenchActions.addChartToSelectedDashboard();
}
_onUp(event) {
let idx = this._getIdx(parseInt($(event.target).closest('button').attr("rel")));
MZBenchActions.withSelectedDashboard((d) => {d.charts.splice(idx,0,d.charts.splice(idx-1,1)[0]);});
}
_onDown(event) {
let idx = this._getIdx(parseInt($(event.target).closest('button').attr("rel"))) + 1;
MZBenchActions.withSelectedDashboard((d) => {d.charts.splice(idx,0,d.charts.splice(idx-1,1)[0]);});
}
_onDelete(event) {
let idx = this._getIdx(parseInt($(event.target).closest('button').attr("rel")));
MZBenchActions.withSelectedDashboard((d) => {d.charts.splice(idx, 1)});
}
_onChangeDescription(event) {
let idx = this._getIdx(parseInt($(event.target).attr("rel")));
MZBenchActions.withSelectedDashboard((d) => {d.charts[idx].description = event.target.value});
}
_onChangeMetricFun(id) {
let idx = this._getIdx(id);
return (event, {newValue}) => {
MZBenchActions.withSelectedDashboard((d) => {d.charts[idx].metric = newValue;});
}
}
_onChangeXEnvFun(id) {
let idx = this._getIdx(id);
return (event, {newValue}) => {
MZBenchActions.withSelectedDashboard((d) => {d.charts[idx].x_env = newValue;});
}
}
_onChangeGroupEnvFun(id) {
let idx = this._getIdx(id);
return (event, {newValue}) => {
MZBenchActions.withSelectedDashboard((d) => {d.charts[idx].group_env = newValue;});
}
}
_onChangeKind(event) {
let idx = this._getIdx(parseInt($(event.target).attr("rel")));
let parts = event.target.value.split(" ");
let kind = parts[0].toLowerCase();
let size = parts[1] ? parts[1] : "0";
MZBenchActions.withSelectedDashboard((d) => {d.charts[idx].kind = kind; d.charts[idx].size = size;});
}
_onChangeXAxis(event) {
let idx = this._getIdx(parseInt($(event.target).attr("rel")));
let newValue = event.target.value;
MZBenchActions.withSelectedDashboard((d) => {d.charts[idx].regression_x = newValue;});
}
_onChangeCriteria(event, {newValue}) {
MZBenchActions.withSelectedDashboard((d) => {d.criteria = newValue});
if (this.autoUpdateHandler) {
clearTimeout(this.autoUpdateHandler);
}
this.autoUpdateHandler = setTimeout(() => MZBenchActions.getTimeline({q:newValue, bench_id: undefined, limit: this.props.benchLimit}, newValue), this.props.updateInterval);
}
_onSave(event) {
event.preventDefault();
let notify = $.notify({message: `Saving the dashboard... `}, {type: 'info'});
MZBenchActions.saveSelectedDashboard();
MZBenchRouter.navigate("/dashboard", {});
}
_getIdx(id) {
return this.props.item.charts.reduce((a, x, idx) => x.id === id ? idx : a, -1);
}
_resolveState() {
this.state.total = (this.props.item.criteria == BenchStore.getTimelineId()) ? BenchStore.getTotal() : -1;
let benches = BenchStore.getItems().filter((b) => b.status === "complete" ? 1 : 0);
this.state.metrics = Misc.uniq_fast(benches.reduce((acc_b, b) => {
let groups = b.metrics.groups || [];
return acc_b.concat(groups.reduce((acc_g, g) => {
return acc_g.concat(g.graphs.reduce((acc, graph) => acc.concat(graph.metrics.map((m) => m.name.trim())), []))
}, []));
}, []));
this.state.envs = Misc.uniq_fast(benches.reduce((acc_b, b) => {
let env = b.env || [];
return acc_b.concat(env.map((x) => x.name));
}, []));
this.state.results = Misc.uniq_fast(benches.reduce((acc_b, b) => {
let results = b.results || {};
return acc_b.concat(Object.keys(results));
}, []));
if (!this.state.metric_suggestions) this.state.metric_suggestions = [];
if (!this.state.x_suggestions) this.state.x_suggestions = [];
if (!this.state.group_suggestions) this.state.group_suggestions = [];
for (var i in this.props.item.charts) {
if (!this.state.metric_suggestions[i])
this.state.metric_suggestions[i] =
this._suggestion.getSuggestions(this.props.item.charts[i].metric,
this.props.item.charts[i].kind == "compare" ? this.state.metrics : this.state.results);
if (!this.state.x_suggestions[i])
this.state.x_suggestions[i] =
this._suggestion.getSuggestions(this.props.item.charts[i].x_env, this.state.envs);
if (!this.state.group_suggestions[i])
this.state.group_suggestions[i] =
this._suggestion.getSuggestions(this.props.item.charts[i].group_env, this.state.envs);
}
return this.state;
}
_onChange() {
this.setState(this._resolveState());
}
};
DashboardEdit.propTypes = {
item: PropTypes.object,
updateInterval: PropTypes.number,
benchLimit: PropTypes.number
};
DashboardEdit.defaultProps = {
updateInterval: 500,
benchLimit: 20
};
export default DashboardEdit;
|
admin/client/views/signin.js | nickhsine/keystone | 'use strict';
import classnames from 'classnames';
import React from 'react';
import ReactDOM from 'react-dom';
import SessionStore from '../stores/SessionStore';
import { Alert, Button, Form, FormField, FormInput } from 'elemental';
import { createHistory } from 'history';
var history = createHistory();
var SigninView = React.createClass({
getInitialState () {
return {
email: '',
password: '',
securitycode: '',
isAnimating: false,
isInvalid: false,
invalidMessage: '',
signedOut: window.location.search === '?signedout',
};
},
componentDidMount () {
if (this.state.signedOut && window.history.replaceState) {
history.replaceState({}, window.location.pathname);
}
if (this.refs.email) {
ReactDOM.findDOMNode(this.refs.email).select();
}
},
handleInputChange (e) {
let newState = {};
newState[e.target.name] = e.target.value;
this.setState(newState);
},
handleSubmit (e) {
e.preventDefault();
if (!this.state.email || !this.state.password) {
return this.displayError('Please enter an email address and password to sign in.');
}
if (!this.state.securitycode) {
return this.displayError('Please enter the security code on your mobile to sign in.');
}
SessionStore.signin({
email: this.state.email,
password: this.state.password,
securitycode: this.state.securitycode,
}, (err, data) => {
if (err) {
const error = err.error;
switch (error.clientMessageType) {
case 'SECURITY_CODE_NOT_ENABLED':
this.displayError('The security code of your account is not enabled yet. Please contact the system manager.');
break;
case 'INVALID_SECURITY_CODE':
this.displayError('The security code you entered is invalid. Please try it again.');
break;
case 'NO_EMAIL_OR_PASSWORD':
this.displayError('Please enter an email address and password to sign in.');
break;
case 'NO_SECURITY_CODE':
this.displayError('Please enter the security code on your mobile to sign in.');
break;
case 'INVALID_PASSWORD':
default:
this.displayError('The password and security code you entered are not valid.');
break;
}
} else if (data && data.error) {
this.displayError('The password and security code you entered are not valid.');
} else {
top.location.href = this.props.from ? Keystone.adminPath + this.props.from : Keystone.adminPath;
}
});
},
displayError (message) {
this.setState({
isAnimating: true,
isInvalid: true,
invalidMessage: message,
});
setTimeout(this.finishAnimation, 750);
},
finishAnimation () {
if (!this.isMounted()) return;
if (this.refs.email) {
ReactDOM.findDOMNode(this.refs.email).select();
}
this.setState({
isAnimating: false,
});
},
renderBrand () {
let logo = { src: `${Keystone.adminPath}/images/logo.png`, width: 205, height: 68 };
if (this.props.logo) {
logo = typeof this.props.logo === 'string' ? { src: this.props.logo } : this.props.logo;
// TODO: Deprecate this
if (Array.isArray(logo)) {
logo = { src: logo[0], width: logo[1], height: logo[2] };
}
}
return (
<div className="auth-box__col">
<div className="auth-box__brand">
<a href="/" className="auth-box__brand__logo">
<img src={logo.src} width={logo.width ? logo.width : null} height={logo.height ? logo.height : null} alt={this.props.brand} />
</a>
</div>
</div>
);
},
renderUserInfo () {
if (!this.props.user) return null;
let openKeystoneButton = this.props.userCanAccessKeystone ? <Button href={Keystone.adminPath} type="primary">Open Keystone</Button> : null;
return (
<div className="auth-box__col">
<p>Hi {this.props.user.name.first},</p>
<p>You're already signed in.</p>
{openKeystoneButton}
<Button href={`${Keystone.adminPath}/signout`} type="link-cancel">Sign Out</Button>
</div>
);
},
renderAlert () {
if (this.state.isInvalid) {
return <Alert key="error" type="danger" style={{ textAlign: 'center' }}>{this.state.invalidMessage}</Alert>;
} else if (this.state.signedOut) {
return <Alert key="signed-out" type="info" style={{ textAlign: 'center' }}>You have been signed out.</Alert>;
} else {
/* eslint-disable react/self-closing-comp */
// TODO: This probably isn't the best way to do this, we
// shouldn't be using Elemental classNames instead of components
return <div key="fake" className="Alert Alert--placeholder"> </div>;
/* eslint-enable */
}
},
renderForm () {
if (this.props.user) return null;
return (
<div className="auth-box__col">
<Form method="post" onSubmit={this.handleSubmit} noValidate>
<FormField label="Email" htmlFor="email">
<FormInput type="email" name="email" onChange={this.handleInputChange} value={this.state.email} ref="email" />
</FormField>
<FormField label="Password" htmlFor="password">
<FormInput type="password" name="password" onChange={this.handleInputChange} value={this.state.password} ref="password" />
</FormField>
<FormField label="Security Code" htmlFor="securitycode">
<FormInput autoComplete="off" type="text" name="securitycode" onChange={this.handleInputChange} value={this.state.securitycode} ref="securitycode" />
</FormField>
<Button disabled={this.state.animating} type="primary" submit>Sign In</Button>
{/* <Button disabled={this.state.animating} type="link-text">Forgot Password?</Button> */}
</Form>
</div>
);
},
render () {
let boxClassname = classnames('auth-box', {
'auth-box--has-errors': this.state.isAnimating,
});
return (
<div className="auth-wrapper">
{this.renderAlert()}
<div className={boxClassname}>
<h1 className="u-hidden-visually">{this.props.brand ? this.props.brand : 'Keystone'} Sign In </h1>
<div className="auth-box__inner">
{this.renderBrand()}
{this.renderUserInfo()}
{this.renderForm()}
</div>
</div>
<div className="auth-footer">
<span>Powered by </span>
<a href="http://keystonejs.com" target="_blank" title="The Node.js CMS and web application platform (new window)">KeystoneJS</a>
</div>
</div>
);
},
});
ReactDOM.render(
<SigninView
brand={Keystone.brand}
from={Keystone.from}
logo={Keystone.logo}
user={Keystone.user}
userCanAccessKeystone={Keystone.userCanAccessKeystone}
/>,
document.getElementById('signin-view')
);
|
src/routes/MyVideos/components/MyVideo.js | xiaoyai0622/youTubeApiTest | import React from 'react'
import Tile from '../../../components/Tile'
import Title from '../../../components/Title'
class MyVideo extends React.Component {
componentWillMount() {
}
render() {
console.log(this.props.movies)
if (this.props.movies.myVideo) {
return (
<div>
<Title title="My Videos"/>
<div className="movie-list">
{this.props.movies.myVideo.length==0?(
<h1>The saved list is empty</h1>
):(this.props.movies.myVideo.map(function (movie) {
return (
<Tile id={movie.id.videoId} title={movie.snippet.title} img={movie.snippet.thumbnails.medium.url} isMine={true} save={()=>this.saveMyVideo(movie)}/>)
}.bind(this)))
}
</div>
</div>
);
} else {
return (
<div className="movie-list">
<Title title="Popular Titles"/>
<h2>Loading</h2>
</div>
);
}
}
}
export default MyVideo
|
src/interface/statistics/components/Gauge.js | fyruna/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import { formatPercentage } from 'common/format';
const Gauge = ({ value }) => (
<div className="flex" style={{ textAlign: 'center', marginTop: 12 }}>
<div className="flex-main text-right text-muted" style={{ paddingTop: 23, paddingRight: 8, fontSize: 12 }}>
Low
</div>
<div className="flex-sub" style={{ position: 'relative' }}>
<svg width="98" height="85" viewBox="19 19 101 88" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ fill: 'none' }}>
<path d="M101.459 101.459C119.033 83.8858 119.033 55.3934 101.459 37.8198C83.8859 20.2462 55.3934 20.2462 37.8198 37.8198C20.2463 55.3934 20.2463 83.8858 37.8198 101.459" stroke="#f8b700" strokeWidth="8" strokeLinecap="round" />
<path fillRule="evenodd" clipRule="evenodd" d="M68.6396 28.6396H70.6396V32.6396H68.6396V28.6396Z" fill="#f8b700" />
<path fillRule="evenodd" clipRule="evenodd" d="M87.7656 32.8389L89.5485 33.7451L87.7368 37.3097L85.9539 36.4035L87.7656 32.8389Z" fill="#f8b700" />
<path fillRule="evenodd" clipRule="evenodd" d="M101.207 50.1829L100.077 48.5324L103.378 46.2732L104.508 47.9236L101.207 50.1829Z" fill="#f8b700" />
<path fillRule="evenodd" clipRule="evenodd" d="M106.622 67.3762L106.417 65.3868L110.398 64.9765L110.603 66.966L106.622 67.3762Z" fill="#f8b700" />
<path fillRule="evenodd" clipRule="evenodd" d="M103.658 84.4276L104.376 82.5609L108.11 83.9969L107.392 85.8635L103.658 84.4276Z" fill="#f8b700" />
<path fillRule="evenodd" clipRule="evenodd" d="M52.0547 32.5298L50.2627 33.4179L52.039 37.0019L53.831 36.1137L52.0547 32.5298Z" fill="#f8b700" />
<path fillRule="evenodd" clipRule="evenodd" d="M36.1157 45.9784L34.965 47.6142L38.2354 49.9147L39.3861 48.2789L36.1157 45.9784Z" fill="#f8b700" />
<path fillRule="evenodd" clipRule="evenodd" d="M28.8926 64.968L28.6883 66.9576L32.6626 67.3657L32.8669 65.3761L28.8926 64.968Z" fill="#f8b700" />
<path fillRule="evenodd" clipRule="evenodd" d="M31.3486 84.3921L32.0806 86.2533L35.8031 84.7895L35.0711 82.9282L31.3486 84.3921Z" fill="#f8b700" />
</svg>
<div
style={{
position: 'absolute',
top: 49,
left: '50%',
width: 32,
height: 32,
transform: 'translate(-50%, -50%)',
marginTop: -13,
}}
>
<svg
width="10"
height="32"
viewBox="0 0 10 32"
fill="none"
xmlns="http://www.w3.org/2000/svg"
style={{
fill: 'none',
margin: 0,
transformOrigin: '5px 27px',
transform: `rotate(${-140 + 280 * value}deg)`,
}}
>
<path d="M9 27C9 29.2091 7.20914 31 5 31C2.79086 31 1 29.2091 1 27C1 24.7909 2.79086 23 5 23C7.20914 23 9 24.7909 9 27Z" stroke="#f8b700" strokeWidth="2" />
<path fillRule="evenodd" clipRule="evenodd" d="M6 0L6 23H4L4 0L6 0Z" fill="#f8b700" />
</svg>
</div>
<div className="value" style={{ marginTop: -18, fontSize: '1.25em' }}>
{formatPercentage(value, 0)}%
</div>
</div>
<div className="flex-main text-left text-muted" style={{ paddingTop: 23, paddingLeft: 8, fontSize: 12 }}>
High
</div>
</div>
);
Gauge.propTypes = {
value: PropTypes.number.isRequired,
};
export default Gauge;
|
client/component/rest-api-status/index.js | johngodley/search-regex | /**
* External dependencies
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { translate as __ } from 'i18n-calypso';
import classnames from 'classnames';
/**
* Internal dependencies
*/
import ApiResult from './api-result';
import { Spinner } from 'wp-plugin-components';
import { getRestApi } from 'page/options/options-form';
import { checkApi } from 'state/settings/action';
import './style.scss';
const STATUS_OK = 'ok';
const STATUS_FAIL = 'fail';
const STATUS_LOADING = 'loading';
const STATUS_WARNING_CURRENT = 'warning-current';
const STATUS_WARNING = 'warning-not-selected';
const getApiResult = ( results, name ) => results && results[ name ] ? results[ name ] : {};
const isError = result => result.GET && result.POST && ( result.GET.status === STATUS_FAIL || result.POST.status === STATUS_FAIL );
const isWorking = result => result.GET && result.POST && ( result.GET.status === STATUS_OK && result.POST.status === STATUS_OK );
class RestApiStatus extends React.Component {
static propTypes = {
allowChange: PropTypes.bool,
};
static defaultProps = {
allowChange: true,
};
constructor( props ) {
super( props );
this.state = { showing: false };
}
componentDidMount() {
this.onTry();
}
onTry() {
const { routes } = this.props;
const untested = Object.keys( routes ).map( id => ( { id, url: routes[ id ] } ) );
this.props.onCheckApi( untested.filter( item => item ) );
}
onRetry = ev => {
ev.preventDefault;
this.setState( { showing: false } );
this.onTry();
}
getPercent( apiTest, routes ) {
if ( Object.keys( apiTest ).length === 0 ) {
return 0;
}
const total = routes.length * 2;
let finished = 0;
for ( let index = 0; index < Object.keys( apiTest ).length; index++ ) {
const key = Object.keys( apiTest )[ index ];
if ( apiTest[ key ] && apiTest[ key ].GET && apiTest[ key ].GET.status !== STATUS_LOADING ) {
finished++;
}
if ( apiTest[ key ] && apiTest[ key ].POST && apiTest[ key ].POST.status !== STATUS_LOADING ) {
finished++;
}
}
return Math.round( ( finished / total ) * 100 );
}
getApiStatus( results, routes, current ) {
const failed = Object.keys( results ).filter( key => isError( results[ key ] ) ).length;
if ( failed === 0 ) {
return 'ok';
} else if ( failed < routes.length ) {
return isWorking( results[ current ] ) ? STATUS_WARNING_CURRENT : STATUS_WARNING;
}
return 'fail';
}
getApiStatusText( status ) {
if ( status === STATUS_OK ) {
return __( 'Good' );
} else if ( status === STATUS_WARNING_CURRENT ) {
return __( 'Working but some issues' );
} else if ( status === STATUS_WARNING ) {
return __( 'Not working but fixable' );
}
return __( 'Unavailable' );
}
onShow = () => {
this.setState( { showing: true } );
}
canShowProblem( status ) {
const { showing } = this.state;
return showing || status === STATUS_FAIL || status === STATUS_WARNING;
}
renderError( status ) {
const showing = this.canShowProblem( status );
let message = __( 'There are some problems connecting to your REST API. It is not necessary to fix these problems and the plugin is able to work.' );
if ( status === STATUS_FAIL ) {
message = __( 'Your REST API is not working and the plugin will not be able to continue until this is fixed.' );
} else if ( status === STATUS_WARNING ) {
message = __( 'You are using a broken REST API route. Changing to a working API should fix the problem.' );
}
return (
<div className="api-result-log">
<p>
<strong>{ __( 'Summary' ) }</strong>: { message }
</p>
{ ! showing && (
<p>
<button className="button-secondary" type="button" onClick={ this.onShow }>
{ __( 'Show Problems' ) }
</button>
</p>
) }
</div>
);
}
render() {
const routeNames = getRestApi();
const { apiTest, routes, current, allowChange } = this.props;
const { showing } = this.state;
const percent = this.getPercent( apiTest, routeNames );
const status = this.getApiStatus( apiTest, routeNames, current );
const showProblem = percent >= 100 && this.canShowProblem( status ) || showing;
const statusClass = classnames( {
'api-result-status': true,
'api-result-status_good': status === STATUS_OK && percent >= 100,
'api-result-status_problem': status === STATUS_WARNING_CURRENT && percent >= 100,
'api-result-status_failed': ( status === STATUS_FAIL || status === STATUS_WARNING ) && percent >= 100,
} );
return (
<div className="api-result-wrapper">
<div className="api-result-header">
<strong>REST API:</strong>
<div className="api-result-progress">
<span className={ statusClass }>
{ percent < 100 && __( 'Testing - %s%%', { args: [ percent ] } ) }
{ percent >= 100 && this.getApiStatusText( status ) }
</span>
{ percent < 100 && <Spinner /> }
</div>
{ percent >= 100 && status !== STATUS_OK && <button className="button button-secondary api-result-retry" onClick={ this.onRetry }>{ __( 'Check Again' ) }</button> }
</div>
{ percent >= 100 && status !== STATUS_OK && this.renderError( status ) }
{ showProblem && routeNames.map( ( item, pos ) =>
<ApiResult item={ item } result={ getApiResult( apiTest, item.value ) } routes={ routes } key={ pos } isCurrent={ current === item.value } allowChange={ allowChange } />
) }
</div>
);
}
}
function mapDispatchToProps( dispatch ) {
return {
onCheckApi: api => {
dispatch( checkApi( api ) );
},
};
}
function mapStateToProps( state ) {
const { api: { routes, current }, apiTest } = state.settings;
return {
apiTest,
routes,
current,
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)( RestApiStatus );
|
examples/demos/customHeader.js | Incubity/react-big-calendar | import React from 'react';
import BigCalendar from 'react-big-calendar';
import events from '../events';
let MyOtherNestedComponent = React.createClass({
render(){
return <div>NESTED COMPONENT</div>
}
})
let MyCustomHeader = React.createClass({
render(){
const { label } = this.props
return (
<div>
CUSTOM HEADER:
<div>{ label }</div>
<MyOtherNestedComponent />
</div>
)
}
})
let CustomHeader = React.createClass({
render(){
return (
<BigCalendar
{...this.props}
events={events}
defaultDate={new Date(2015, 3, 1)}
components={{
day: {header: MyCustomHeader},
week: {header: MyCustomHeader},
month: {header: MyCustomHeader}
}}
/>
)
}
})
export default CustomHeader;
|
app/screens/Matches/Match/MatchInfos/StadiumTooltip/StadiumTooltip.js | mbernardeau/Road-to-Russia-2018 | import React from 'react'
import PropTypes from 'prop-types'
import './stadiumTooltip.scss'
const StadiumTooltip = ({ name, photo, city, capacity }) => (
<div className="stadium-tooltip">
<div className="stadium-tooltip-title">
<div>{name}</div>
<div>•</div>
<div>{city}</div>
</div>
{photo && <img className="stadium-tooltip-photo" src={photo.url} alt={name} />}
<div className="stadium-tooltip-title">
<div>Capacité</div>
<div>{capacity.toLocaleString('fr')} places</div>
</div>
</div>
)
StadiumTooltip.defaultProps = {
capacity: 0,
name: '',
city: '',
}
StadiumTooltip.propTypes = {
name: PropTypes.string,
city: PropTypes.string,
photo: PropTypes.shape({
url: PropTypes.string.isRequired,
credit: PropTypes.string,
}),
capacity: PropTypes.number,
}
export default StadiumTooltip
|
packages/website/src/components/content/YouTubeVideo.js | mucsi96/w3c-webdriver | import React from 'react';
import styled from 'styled-components';
const VideoContainer = styled.div`
margin: 25px -20px;
position: relative;
padding-bottom: 56.25%; /*16:9*/
padding-top: 30px;
height: 0;
overflow: hidden;
@media (min-width: 894px) {
margin-right: -18px;
margin-left: -18px;
border-radius: 10px;
}
`;
const VideoIFrame = styled.iframe`
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
`;
const YouTubeVideo = ({ src }) => (
<VideoContainer>
<VideoIFrame
width="560"
height="315"
src={src}
frameBorder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
/>
</VideoContainer>
);
export default YouTubeVideo;
|
src/svg-icons/action/store.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionStore = (props) => (
<SvgIcon {...props}>
<path d="M20 4H4v2h16V4zm1 10v-2l-1-5H4l-1 5v2h1v6h10v-6h4v6h2v-6h1zm-9 4H6v-4h6v4z"/>
</SvgIcon>
);
ActionStore = pure(ActionStore);
ActionStore.displayName = 'ActionStore';
ActionStore.muiName = 'SvgIcon';
export default ActionStore;
|
docs/src/pages/components/portal/SimplePortal.js | lgollut/material-ui | import React from 'react';
import Portal from '@material-ui/core/Portal';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
alert: {
padding: theme.spacing(1),
margin: theme.spacing(1, 0),
border: '1px solid',
},
}));
export default function SimplePortal() {
const classes = useStyles();
const [show, setShow] = React.useState(false);
const container = React.useRef(null);
const handleClick = () => {
setShow(!show);
};
return (
<div>
<button type="button" onClick={handleClick}>
{show ? 'Unmount children' : 'Mount children'}
</button>
<div className={classes.alert}>
It looks like I will render here.
{show ? (
<Portal container={container.current}>
<span>But I actually render here!</span>
</Portal>
) : null}
</div>
<div className={classes.alert} ref={container} />
</div>
);
}
|
app/components/SelectFileForm.js | seungha-kim/grade-sms | // @flow
import React, { Component } from 'react';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import s from './SelectFileForm.css';
import cs from './commonStyles.css';
import HelpText from './HelpText';
type Props = {
showOpenDialog: () => void,
nextStep: () => void,
filePath: ?string,
sheetNames: ?Array<string>,
selectedSheetIndex: ?number,
updateSelectedSheet: (number) => void
};
export default class SelectFileForm extends Component {
fileInput = null;
props: Props;
render() {
const {
showOpenDialog,
nextStep,
filePath,
sheetNames,
selectedSheetIndex,
updateSelectedSheet
} = this.props;
return (
<div className={s.wrap}>
<div className={s.content}>
<HelpText>
성적표 생성에 사용될 시트를 선택하는 과정입니다. <br />
엑셀 파일과 성적 데이터가 들어있는 시트를 선택하세요.
</HelpText>
<TextField
hintText="여기를 클릭해 엑셀 파일을 선택하세요..."
value={filePath || ''}
onClick={showOpenDialog}
fullWidth
floatingLabelText="파일 경로"
/>
<SelectField
disabled={sheetNames == null}
value={selectedSheetIndex}
floatingLabelText="시트"
onChange={(event, index, value) => updateSelectedSheet(value)}
>
{sheetNames != null
? sheetNames.map((name, i) =>
<MenuItem value={i} primaryText={name} key={name} />)
: null}
</SelectField>
</div>
<div className={cs.buttonWrap}>
<RaisedButton label="다음" primary disabled={filePath == null || selectedSheetIndex == null} onClick={nextStep} />
</div>
</div>
);
}
}
|
examples/react-router/src/App.js | algolia/react-instantsearch | import React from 'react';
import qs from 'qs';
import { useLocation, useHistory } from 'react-router-dom';
import {
InstantSearch,
HierarchicalMenu,
Hits,
Menu,
Pagination,
PoweredBy,
RatingMenu,
RefinementList,
SearchBox,
ClearRefinements,
} from 'react-instantsearch-dom';
import algoliasearch from 'algoliasearch/lite';
const searchClient = algoliasearch(
'latency',
'6be0576ff61c053d5f9a3225e2a90f76'
);
const DEBOUNCE_TIME = 700;
const createURL = (state) => `?${qs.stringify(state)}`;
const searchStateToUrl = (location, searchState) =>
searchState ? `${location.pathname}${createURL(searchState)}` : '';
const urlToSearchState = (location) => qs.parse(location.search.slice(1));
function App() {
const location = useLocation();
const history = useHistory();
const [searchState, setSearchState] = React.useState(
urlToSearchState(location)
);
const setStateId = React.useRef();
React.useEffect(() => {
const nextSearchState = urlToSearchState(location);
if (JSON.stringify(searchState) !== JSON.stringify(nextSearchState)) {
setSearchState(nextSearchState);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [location]);
function onSearchStateChange(nextSearchState) {
clearTimeout(setStateId.current);
setStateId.current = setTimeout(() => {
history.push(
searchStateToUrl(location, nextSearchState),
nextSearchState
);
}, DEBOUNCE_TIME);
setSearchState(nextSearchState);
}
return (
<InstantSearch
searchClient={searchClient}
indexName="instant_search"
searchState={searchState}
onSearchStateChange={onSearchStateChange}
createURL={createURL}
>
<div>
<div
style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
marginBottom: 10,
}}
>
<SearchBox />
<PoweredBy />
</div>
<div style={{ display: 'flex' }}>
<div style={{ padding: '0px 20px' }}>
<p>Hierarchical Menu</p>
<HierarchicalMenu
id="categories"
attributes={[
'hierarchicalCategories.lvl0',
'hierarchicalCategories.lvl1',
'hierarchicalCategories.lvl2',
]}
/>
<p>Menu</p>
<Menu attribute="type" />
<p>Refinement List</p>
<RefinementList attribute="brand" />
<p>Range Ratings</p>
<RatingMenu attribute="rating" max={6} />
</div>
<div style={{ display: 'flex', flexDirection: 'column', flex: 1 }}>
<div style={{ display: 'flex', justifyContent: 'space-around' }}>
<ClearRefinements />
</div>
<div>
<Hits />
</div>
<div style={{ alignSelf: 'center' }}>
<Pagination showLast={true} />
</div>
</div>
</div>
</div>
</InstantSearch>
);
}
export default App;
|
src/Option.js | pedroseac/react-select | import React from 'react';
import classNames from 'classnames';
const Option = React.createClass({
propTypes: {
className: React.PropTypes.string, // className (based on mouse position)
isDisabled: React.PropTypes.bool, // the option is disabled
isFocused: React.PropTypes.bool, // the option is focused
isSelected: React.PropTypes.bool, // the option is selected
onSelect: React.PropTypes.func, // method to handle click on option element
onFocus: React.PropTypes.func, // method to handle mouseEnter on option element
onUnfocus: React.PropTypes.func, // method to handle mouseLeave on option element
option: React.PropTypes.object.isRequired, // object that is base for that option
},
blockEvent (event) {
event.preventDefault();
event.stopPropagation();
if ((event.target.tagName !== 'A') || !('href' in event.target)) {
return;
}
if (event.target.target) {
window.open(event.target.href, event.target.target);
} else {
window.location.href = event.target.href;
}
},
handleMouseDown (event) {
event.preventDefault();
event.stopPropagation();
this.props.onSelect(this.props.option, event);
},
handleMouseEnter (event) {
this.props.onFocus(this.props.option, event);
},
handleMouseMove (event) {
if (this.props.focused) return;
this.props.onFocus(this.props.option, event);
},
render () {
var { option } = this.props;
var className = classNames(this.props.className, option.className);
return option.disabled ? (
<div className={className}
onMouseDown={this.blockEvent}
onClick={this.blockEvent}>
{this.props.children}
</div>
) : (
<div className={className}
style={option.style}
onMouseDown={this.handleMouseDown}
onMouseEnter={this.handleMouseEnter}
onMouseMove={this.handleMouseMove}
title={option.title}>
{this.props.children}
</div>
);
}
});
module.exports = Option;
|
src/VibrancyView.android.js | ahanriat/react-native-blur | import React from 'react';
class VibrancyView extends React.Component {
render() {
console.error("VibrancyView is not implemented on Android");
}
}
module.exports = VibrancyView
|
prop-ui-poc/src/components/library/Modals.js | somrajg7/Astoria | import React from 'react';
import {Button, Modal, Panel} from 'react-bootstrap';
import {translate} from 'react-i18next';
var CloseSvgIcon = require('babel!svg-react!../../assets/images/close.svg?name=close');
class Modals extends React.Component {
constructor(props) {
super(props);
// Bind functions
this.closeModal = this.closeModal.bind(this);
this.openModal = this.openModal.bind(this);
this.closeFullModal = this.closeFullModal.bind(this);
this.openFullModal = this.openFullModal.bind(this);
// Set initial state
this.state = {
showModal: false,
showFullModal: false
};
}
closeModal() {
this.setState({showModal: false});
}
openModal() {
this.setState({showModal: true});
}
closeFullModal() {
this.setState({showFullModal: false});
}
openFullModal() {
this.setState({showFullModal: true});
}
render() {
const {t} = this.props;
return (
<div>
<Panel header='Modal' bsStyle='success'>
<Button bsStyle='primary' bsSize='large' onClick={this.openModal}>
Modal
</Button>
<Modal show={this.state.showModal}>
<Modal.Header>
<Modal.Title >Modal title</Modal.Title>
<CloseSvgIcon className='closeIcon' onClick={this.closeModal}/>
</Modal.Header>
<Modal.Body>
Body content goes here
</Modal.Body>
<Modal.Footer>
<Button bsSize='xsmall' onClick={this.closeModal}>Cancel</Button>
<Button bsStyle='primary' bsSize='xsmall'>Save changes</Button>
</Modal.Footer>
</Modal>
</Panel>
<Panel header='Fullscreen Modal' bsStyle='success'>
<Button bsStyle='primary' bsSize='large' onClick={this.openFullModal}>
Fullscreen Modal
</Button>
<Modal dialogClassName='modal-fullscreen' show={this.state.showFullModal}>
<Modal.Header className='fullscreen'>
<Modal.Title >Modal title</Modal.Title>
<CloseSvgIcon className='closeIcon' onClick={this.closeFullModal}/>
</Modal.Header>
<Modal.Body>
Body content goes here
</Modal.Body>
<Modal.Footer>
<Button bsSize='xsmall' onClick={this.closeFullModal}>Cancel</Button>
<Button bsStyle='primary' bsSize='xsmall'>Save changes</Button>
</Modal.Footer>
</Modal>
</Panel>
</div>
);
}
}
export default translate()(Modals);
|
src/NavItem.js | gianpaj/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import SafeAnchor from './SafeAnchor';
const NavItem = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
linkId: React.PropTypes.string,
onSelect: React.PropTypes.func,
active: React.PropTypes.bool,
disabled: React.PropTypes.bool,
href: React.PropTypes.string,
role: React.PropTypes.string,
title: React.PropTypes.node,
eventKey: React.PropTypes.any,
target: React.PropTypes.string,
'aria-controls': React.PropTypes.string
},
getDefaultProps() {
return {
active: false,
disabled: false
};
},
render() {
let {
role,
linkId,
disabled,
active,
href,
title,
target,
children,
tabIndex, //eslint-disable-line
'aria-controls': ariaControls,
...props } = this.props;
let classes = {
active,
disabled
};
let linkProps = {
role,
href,
title,
target,
tabIndex,
id: linkId,
onClick: this.handleClick
};
if (!role && href === '#') {
linkProps.role = 'button';
}
return (
<li {...props} role="presentation" className={classNames(props.className, classes)}>
<SafeAnchor {...linkProps} aria-selected={active} aria-controls={ariaControls}>
{ children }
</SafeAnchor>
</li>
);
},
handleClick(e) {
if (this.props.onSelect) {
e.preventDefault();
if (!this.props.disabled) {
this.props.onSelect(this.props.eventKey, this.props.href, this.props.target);
}
}
}
});
export default NavItem;
|
src/components/molecule.js | OpenChemistry/mongochemclient | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withStyles, Grid, Card, Typography, Link } from '@material-ui/core';
import { has, isNil } from 'lodash-es';
import PageHead from './page-head';
import PageBody from './page-body';
import CardComponent from './item-details-card';
import { formatFormula } from '../utils/formulas';
import { has3dCoords } from '../utils/molecules';
import { wc } from '../utils/webcomponent';
import { getCalculationProperties } from '../utils/calculations';
import { toUpperCase } from '../utils/strings';
import DownloadSelector from './download-selector';
import CollapsibleCard from './collapsible-card';
const styles = theme => ({
moleculeContainer: {
height: 80 * theme.spacing.unit,
width: '100%',
marginBottom: 2 * theme.spacing.unit,
overflow: 'visible'
}
});
class Molecule extends Component {
getName(molecule) {
if (molecule.name)
return molecule.name;
else if (molecule.properties.formula)
return formatFormula(molecule.properties.formula);
return 'Molecule';
}
getMoleculeView(molecule, classes) {
if (has3dCoords(molecule)) {
return (
<oc-molecule
ref={wc(
// Events
{},
//Props
{
cjson: molecule.cjson,
rotate: this.state.rotate,
moleculeRenderer: 'moljs'
}
)}
/>
)
}
else {
const src = `${window.location.origin}/api/v1/molecules/${molecule._id}/svg`
return (
<img src={src} class={classes.moleculeContainer}/>
)
}
}
constructor(props) {
super(props);
this.state = {
rotate: false
}
}
onInteract = () => {
if (this.state.rotate) {
this.setState({...this.state, rotate: false});
}
}
formatLink = (props) => {
return <Link target="_blank" rel="noopener" href={props.wikipediaUrl}>
{!isNil(props.name) ? props.name : 'Wikipedia Page'}
</Link>
}
render = () => {
const {molecule, calculations, onCalculationClick, creator, onCreatorClick, onCalculationUpload, classes} = this.props;
const sections = [];
let moleculeProperties = [];
if (has(molecule, 'properties.formula')) {
moleculeProperties.push({label: 'Formula', value: formatFormula(molecule.properties.formula)});
}
if (has(molecule, 'properties.atomCount')) {
moleculeProperties.push({label: 'Atoms', value: molecule.properties.atomCount});
}
if (has(molecule, 'properties.mass')) {
moleculeProperties.push({label: 'Mass', value: molecule.properties.mass.toFixed(2)});
}
if (has(molecule, 'inchi')) {
moleculeProperties.push({label: 'InChi', value: molecule.inchi});
}
if (has(molecule, 'smiles')) {
moleculeProperties.push({label: 'SMILES', value: molecule.smiles});
}
if (has(molecule, 'wikipediaUrl')) {
moleculeProperties.push({
label: 'Wikipedia',
value: this.formatLink(molecule)
});
}
let first = has(creator, 'firstName') ? creator.firstName : '';
let last = has(creator, 'lastName') ? creator.lastName : '';
moleculeProperties.push({label: 'Creator', value: first + ' ' + last});
const moleculeSection = {
label: 'Molecule Properties',
items: [
{properties: moleculeProperties}
]
};
sections.push(moleculeSection);
const calculationsSection = {
label: 'Calculations',
items: calculations.map(calculation => ({
properties: getCalculationProperties(calculation),
onClick: () => {onCalculationClick(calculation)}
}))
}
console.log('calculations: ', calculations);
sections.push(calculationsSection);
const fileFormats = ['cjson', 'xyz', 'sdf', 'cml'];
const fileOptions = fileFormats.map(format => ({
label: toUpperCase(format),
downloadUrl: `/api/v1/molecules/${molecule._id}/${format}`,
fileName: `molecule_${molecule._id}.${format}`
}));
return (
<div>
<PageHead>
<Typography color="inherit" gutterBottom variant="display1">
{this.getName(molecule)}
</Typography>
</PageHead>
<PageBody>
<Grid container spacing={24}>
<Grid item xs={12} sm={12} md={8}>
<Card className={classes.moleculeContainer}>
{this.getMoleculeView(molecule, classes)}
</Card>
</Grid>
<Grid item xs={12} sm={12} md={4}>
{sections.map((section, i) =>
<CardComponent
key={i}
title={section.label}
items={section.items}
collapsed={section.collapsed}
onCalculationUpload={onCalculationUpload}
/>
)}
<CollapsibleCard title='Download Data'>
<DownloadSelector options={fileOptions}/>
</CollapsibleCard>
</Grid>
</Grid>
</PageBody>
</div>
);
}
}
Molecule.propTypes = {
molecule: PropTypes.object
}
Molecule.defaultProps = {
molecule: null
}
export default withStyles(styles)(Molecule);
|
src/svg-icons/image/assistant.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageAssistant = (props) => (
<SvgIcon {...props}>
<path d="M19 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h4l3 3 3-3h4c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-5.12 10.88L12 17l-1.88-4.12L6 11l4.12-1.88L12 5l1.88 4.12L18 11l-4.12 1.88z"/>
</SvgIcon>
);
ImageAssistant = pure(ImageAssistant);
ImageAssistant.displayName = 'ImageAssistant';
ImageAssistant.muiName = 'SvgIcon';
export default ImageAssistant;
|
client/src/containers/Signup.js | DemocracyGuardians/DGTeam |
import React from 'react';
import { connect } from "react-redux";
import { LocalForm, Control } from 'react-redux-form'
import { Link, withRouter } from 'react-router-dom'
import { Button, Container, Input, Message } from 'semantic-ui-react'
import PropTypes from 'prop-types'
import { RSAA } from 'redux-api-middleware'
import Marked from 'marked'
import agreementMd from '../components/Session/Members_Agreement_md'
import { setLocalProgress } from '../util/localProgress'
import { accountSignupSuccess, accountVerificationEmailSent } from '../actions/accountActions'
import { TEAM_ORG, TEAM_BASE_URL, TEAM_API_RELATIVE_PATH } from '../envvars'
import passwordRegexp from '../util/passwordRegexp'
import parseJsonPayload from '../util/parseJsonPayload'
const baseApiUrl = TEAM_BASE_URL + TEAM_API_RELATIVE_PATH
const loginexistsApiUrl = baseApiUrl+ '/loginexists'
const signupApiUrl = baseApiUrl+ '/signup'
var USER_ALREADY_EXISTS = 'USER_ALREADY_EXISTS'
// Wrap semantic-ui controls for react-redux-forms
const wFirstName = (props) => <Input name='firstName' placeholder='First name' fluid {...props} />
const wLastName = (props) => <Input name='lastName' placeholder='Last name' fluid {...props} />
const wEmail = (props) => <Input name='email' placeholder='Email' fluid {...props} />
const wPassword = (props) => <Input name='password' placeholder='Password' fluid {...props} />
class Signup extends React.Component {
constructor(props) {
super(props)
this.state = {
// this.props.message from parent holds initial message and is usually ''
// this.state.message holds message to display at top of form
message: this.props.message,
// this.props.error from parent indicates whether initial message is an error and is usually false
// this.state.error is a boolean that indicates whether message is an error
error: this.props.error,
emailAlreadyRegistered: false,
showPassword: false,
needToValidatePane1: false,
needToValidatePane2: false,
pane: 1
}
this.validatePane1 = this.validatePane1.bind(this)
this.validatePane2 = this.validatePane2.bind(this)
this.validatePane1Error = this.validatePane1Error.bind(this)
this.validatePane2Error = this.validatePane2Error.bind(this)
this.clearErrors = this.clearErrors.bind(this)
this.onClickNext1 = this.onClickNext1.bind(this)
this.onClickPrev2 = this.onClickPrev2.bind(this)
this.toggleShowPassword = this.toggleShowPassword.bind(this)
}
validatePane1() {
let invalidFields = []
let f = document.querySelector('.Signup form');
['firstName','lastName','email','password'].forEach(function(field) {
let localdot = 'local.' + field
if (!f[localdot].validity.valid) {
invalidFields.push(field)
}
})
return invalidFields
}
validatePane1Error(invalidFields) {
if (invalidFields.length === 1 && invalidFields[0] === 'password') {
this.setState({ error: true, message: 'Password must have at least 8 characters and must include at least one uppercase, one lowercase, one number and one punctuation character', pane: 1 })
} else {
this.setState({ error: true, message: 'The highlighted fields are in error', pane: 1 })
}
}
validatePane2() {
let f = document.querySelector('.Signup form')
if (!f['local.agreement'].checked) {
return false
} else {
return true
}
}
validatePane2Error() {
this.setState({ error: true, message: 'You must agree to the terms of the Members Agreement in order to sign up.', pane: 2 })
}
clearErrors() {
this.setState({ error: false, message: '', emailAlreadyRegistered: false })
}
onClickNext1(event) {
event.preventDefault()
this.setState({ needToValidatePane1: true })
// force rerender, use setTimeout so that html5 required property will kick in on firstName and lastName
this.forceUpdate()
setTimeout(() => {
var invalidFields = this.validatePane1()
if (invalidFields.length > 0) {
this.validatePane1Error(invalidFields)
return
}
let { dispatch } = this.props.store
let f = document.querySelector('.Signup form')
var email = f['local.email'].value
var payload = { email }
const apiAction = {
[RSAA]: {
endpoint: loginexistsApiUrl,
method: 'POST',
credentials: 'include',
types: [
'ignored',
{
type: 'signup_loginexists_success',
payload: (action, state, res) => {
parseJsonPayload.bind(this)(res, action.type, json => {
if (json.exists) {
this.setState({ error: true, message: 'Email '+email+' already has an account', emailAlreadyRegistered: true })
} else {
this.clearErrors()
this.setState({ pane: 2 })
}
})
}
},
{
type: 'signup_loginexists_failure',
payload: (action, state, res) => {
console.error('signup_loginexists_success Unknown error. Maybe server is unavailable.')
this.props.history.push('/systemerror')
}
}
],
body: JSON.stringify(payload),
headers: { 'Content-Type': 'application/json' }
}
}
dispatch(apiAction)
}, 0)
}
onClickPrev2(event) {
event.preventDefault()
var invalidFields = this.validatePane1()
if (invalidFields.length > 0) {
this.validatePane1Error(invalidFields)
return
}
this.clearErrors()
this.setState({ pane: 1 })
}
handleChange(values) {
var invalidFields = this.validatePane1()
if (this.state.pane === 1 && this.state.needToValidatePane1 && invalidFields.length > 0) {
this.validatePane1Error(invalidFields)
return
}
if (this.state.pane === 2 && this.state.needToValidatePane2 && !this.validatePane2()) {
this.validatePane2Error()
return
}
this.clearErrors()
}
handleSubmit(values) {
this.setState({ needToValidatePane2: true })
if (!this.validatePane2()) {
this.validatePane2Error()
return
}
var invalidFields = this.validatePane1()
if (invalidFields.length > 0) {
this.validatePane1Error(invalidFields)
return
}
this.clearErrors()
let { dispatch } = this.props.store
const apiAction = {
[RSAA]: {
endpoint: signupApiUrl,
method: 'POST',
credentials: 'include',
types: [
'SIGNUP_REQUEST',
{
type: 'SIGNUP_SUCCESS',
payload: (action, state, res) => {
parseJsonPayload.bind(this)(res, action.type, json => {
localStorage.setItem("teamAppEmail", values.email)
setLocalProgress({ level:1, tasknum:0, step:0 })
dispatch(accountSignupSuccess(json.account))
dispatch(accountVerificationEmailSent(json.account.email))
this.props.history.push('/verificationsent')
})
}
},
{
type: 'SIGNUP_FAILURE',
payload: (action, state, res) => {
parseJsonPayload.bind(this)(res, action.type, json => {
if (json.error === USER_ALREADY_EXISTS) {
this.setState({ message: 'Email address already has an account', error: true })
} else {
console.error('SIGNUP_FAILURE unrecognized error='+json.error+', msg:'+json.msg)
this.props.history.push('/systemerror')
}
})
}
}
],
body: JSON.stringify(values),
headers: { 'Content-Type': 'application/json' }
}
}
dispatch(apiAction)
}
toggleShowPassword(event) {
event.preventDefault()
this.setState({ showPassword: !this.state.showPassword })
}
render() {
let { pane, error, needToValidatePane1, needToValidatePane2, emailAlreadyRegistered, showPassword } = this.state
let message = this.state.message || (this.state.pane <= 2 ? `Step ${pane} of 2` : '')
let pane1style = { display: (pane === 1 ? 'block' : 'none') }
let pane2style = { display: (pane === 2 ? 'block' : 'none') }
let pane1required = needToValidatePane1
let passwordPattern = needToValidatePane1 ? passwordRegexp : '.*'
let passwordType = showPassword ? 'input' : 'password'
let showHidePasswordText = showPassword ? 'Hide password' : 'Show password'
let emailClass = 'verticalformcontrol ' + (emailAlreadyRegistered ? 'emailError' : '' )
let agreementClass = 'verticalformcontrol checkboxlabelrow ' + (needToValidatePane2 && !this.validatePane2() ? 'checkboxDivError' : '' )
let agreementHtml = Marked(agreementMd);
let hdr = TEAM_ORG+' Team Signup'
return (
<Container text className='Signup verticalformcontainer'>
<LocalForm onSubmit={(values) => this.handleSubmit(values)}
onChange={(values) => this.handleChange(values)}>
<div style={pane1style}>
<Message header={hdr} className='verticalformtopmessage' error={error} content={message} />
<Control.text model=".firstName" type="text" className="verticalformcontrol" component={wFirstName} required={pane1required} />
<Control.text model=".lastName" type="text" className="verticalformcontrol" component={wLastName} required={pane1required} />
<Control.text model=".email" type="email" className={emailClass} component={wEmail} required={pane1required} />
<Control.password model=".password" type={passwordType} className="verticalformcontrol" pattern={passwordPattern} component={wPassword} required={pane1required} />
<div className="showPasswordRow">
<a href="" className="showPasswordLink" onClick={this.toggleShowPassword} >{showHidePasswordText}</a>
</div>
<div className="passwordRules">At least: 1 lowercase, 1 uppercase, 1 number, 1 punctuation, 8 chars total</div>
<div className='verticalformbuttonrow'>
<Button className="verticalformcontrol verticalformbottombutton" onClick={this.onClickNext1} floated='right'>Next</Button>
<div style={{clear:'both' }} ></div>
</div>
<Message className="verticalformbottommessage" >
<span className='innerBlock'>
<div>Already a team member? <Link to="/login">Login here</Link></div>
</span>
</Message>
</div>
<div style={pane2style}>
<Message header={hdr} className='verticalformtopmessage' error={error} content={message} />
<div dangerouslySetInnerHTML={{__html: agreementHtml}} />
<div className={agreementClass}>
<Control.checkbox model=".agreement" />
<label>
I agree to the terms and conditions listed in the above {TEAM_ORG} Members Agreement and thereby become a member of the {TEAM_ORG} team.
</label>
</div>
<div className='verticalformbuttonrow'>
<Button className="verticalformcontrol verticalformbottombutton" onClick={this.onClickPrev2} floated='left'>Prev</Button>
<Button type="submit" className="verticalformcontrol verticalformbottombutton" floated='right'>Finish</Button>
<div style={{clear:'both' }} ></div>
</div>
</div>
</LocalForm>
</Container>
)
}
}
Signup.propTypes = {
store: PropTypes.object.isRequired
}
const mapStateToProps = (state, ownProps) => {
const { message, error } = state || {}
return {
store: ownProps.store,
message,
error
}
}
export default withRouter(connect(mapStateToProps)(Signup));
|
src/main.js | findinstore/instore-webapp | import React from 'react';
import ReactDOM from 'react-dom';
import { useRouterHistory } from 'react-router';
import { createHistory } from 'history';
import makeRoutes from './routes';
import Root from './containers/Root';
import configureStore from './store/configureStore';
const historyConfig = { basename: __BASENAME__ };
const history = useRouterHistory(createHistory)(historyConfig);
const initialState = window.__INITIAL_STATE__;
const store = configureStore({ initialState, history });
// const routes = makeRoutes(store);
const routes = makeRoutes(store);
// Render the React application to the DOM
ReactDOM.render(
<Root history={history} routes={routes} store={store} />,
document.getElementById('root')
);
|
blueocean-material-icons/src/js/components/svg-icons/maps/flight.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const MapsFlight = (props) => (
<SvgIcon {...props}>
<path d="M10.18 9"/><path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/>
</SvgIcon>
);
MapsFlight.displayName = 'MapsFlight';
MapsFlight.muiName = 'SvgIcon';
export default MapsFlight;
|
jenkins-design-language/src/js/components/material-ui/svg-icons/maps/local-car-wash.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const MapsLocalCarWash = (props) => (
<SvgIcon {...props}>
<path d="M17 5c.83 0 1.5-.67 1.5-1.5 0-1-1.5-2.7-1.5-2.7s-1.5 1.7-1.5 2.7c0 .83.67 1.5 1.5 1.5zm-5 0c.83 0 1.5-.67 1.5-1.5 0-1-1.5-2.7-1.5-2.7s-1.5 1.7-1.5 2.7c0 .83.67 1.5 1.5 1.5zM7 5c.83 0 1.5-.67 1.5-1.5C8.5 2.5 7 .8 7 .8S5.5 2.5 5.5 3.5C5.5 4.33 6.17 5 7 5zm11.92 3.01C18.72 7.42 18.16 7 17.5 7h-11c-.66 0-1.21.42-1.42 1.01L3 14v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 18c-.83 0-1.5-.67-1.5-1.5S5.67 15 6.5 15s1.5.67 1.5 1.5S7.33 18 6.5 18zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 13l1.5-4.5h11L19 13H5z"/>
</SvgIcon>
);
MapsLocalCarWash.displayName = 'MapsLocalCarWash';
MapsLocalCarWash.muiName = 'SvgIcon';
export default MapsLocalCarWash;
|
src/App.js | NestorSegura/operationcode_frontend | import React, { Component } from 'react';
import { Route, Router } from 'react-router';
import ReactGA from 'react-ga';
import createHistory from 'history/createBrowserHistory';
import ScrollToTop from 'shared/components/scrollToTop/scrollToTop';
import Home from './scenes/home/home';
const history = createHistory();
ReactGA.initialize('UA-75642413-1');
class App extends Component {
componentDidMount() {
if (process.env.NODE_ENV === 'production') {
// History listening doesn't catch first page load
ReactGA.set({ page: history.location.pathname });
ReactGA.pageview(history.location.pathname);
history.listen((location) => {
ReactGA.set({ page: location.pathname });
ReactGA.pageview(location.pathname);
});
}
}
render() {
return (
<Router history={history}>
<ScrollToTop>
<Route path="/" component={Home} />
</ScrollToTop>
</Router>
);
}
}
export default App;
|
src/main/VisualizationWrapper.js | piotr-gawron/pileup.js | /**
* @flow
*/
'use strict';
import type {TwoBitSource} from './sources/TwoBitDataSource';
import type {GenomeRange, VizWithOptions} from './types';
import React from 'react';
import ReactDOM from 'react-dom';
import d3utils from './viz/d3utils';
import _ from 'underscore';
import d3 from '../lib/minid3';
export type VizProps<T: any> = {
width: number;
height: number;
range: GenomeRange;
referenceSource: TwoBitSource;
source: T;
options: any;
};
type Props = {
range: ?GenomeRange;
visualization: VizWithOptions;
onRangeChange: (newRange: GenomeRange) => void;
referenceSource: TwoBitSource;
source: any;
options: ?Object;
};
type State = {
width: number;
height: number;
updateSize: boolean;
};
class VisualizationWrapper extends React.Component<Props, State> {
props: Props;
state: State;
hasDragBeenInitialized: boolean;
onResizeListener: Object; //listener that handles window.onresize event
constructor(props: Object) {
super(props);
this.hasDragBeenInitialized = false;
this.state = {
updateSize: false,
width: 0,
height: 0
};
}
updateSize(): any {
var thisNode = ReactDOM.findDOMNode(this)
if (thisNode && thisNode instanceof Element) { // check for getContext
var parentDiv = thisNode.parentNode;
if (parentDiv && parentDiv instanceof HTMLElement) { // check for getContext
this.setState({
updateSize: false,
width: parentDiv.offsetWidth,
height: parentDiv.offsetHeight
});
}
}
}
componentDidMount(): any {
//local copy of the listener, so we can remove it
//when pileup is destroyed
this.onResizeListener = () => this.updateSize();
window.addEventListener('resize', this.onResizeListener);
this.updateSize();
if (this.props.range && !this.hasDragBeenInitialized) this.addDragInterface();
}
componentDidUpdate(prevProps: Props, prevState: Object): any {
if (prevState.updateSize) {
this.updateSize();
}
if (this.props.range && !this.hasDragBeenInitialized) this.addDragInterface();
}
componentWillUnmount(): any {
window.removeEventListener('resize', this.onResizeListener);
}
getScale(): any {
if (!this.props.range) return x => x;
return d3utils.getTrackScale(this.props.range, this.state.width);
}
addDragInterface(): any {
this.hasDragBeenInitialized = true;
var div = ReactDOM.findDOMNode(this);
var originalRange, originalScale, dx=0;
var dragstarted = () => {
d3.event.sourceEvent.stopPropagation();
dx = 0;
originalRange = _.clone(this.props.range);
originalScale = this.getScale();
};
var updateRange = () => {
if (!originalScale) return; // can never happen, but Flow don't know.
if (!originalRange) return; // can never happen, but Flow don't know.
var newStart = originalScale.invert(-dx),
intStart = Math.round(newStart),
offsetPx = originalScale(newStart) - originalScale(intStart);
var newRange = {
contig: originalRange.contig,
start: intStart,
stop: intStart + (originalRange.stop - originalRange.start),
offsetPx: offsetPx
};
this.props.onRangeChange(newRange);
};
var dragmove = () => {
dx += d3.event.dx; // these are integers, so no roundoff issues.
updateRange();
};
function dragended() {
updateRange();
}
var drag = d3.behavior.drag()
.on('dragstart', dragstarted)
.on('drag', dragmove)
.on('dragend', dragended);
d3.select(div).call(drag).on('click', this.handleClick.bind(this));
}
handleClick(): any {
if (d3.event.defaultPrevented) {
d3.event.stopPropagation();
}
}
render(): any {
const range = this.props.range;
const component = this.props.visualization.component;
if (!range) {
if (component.displayName != null)
return <EmptyTrack className={component.displayName} />;
else
return <EmptyTrack className='EmptyTrack' />;
}
var options = _.extend(_.clone(this.props.visualization.options),this.props.options);
var el = React.createElement(component, ({
range: range,
source: this.props.source,
referenceSource: this.props.referenceSource,
width: this.state.width,
height: this.state.height,
options: options
} : VizProps<any>));
return <div className='drag-wrapper'>{el}</div>;
}
}
VisualizationWrapper.displayName = 'VisualizationWrapper';
type EmptyTrackProps = {className: string};
class EmptyTrack extends React.Component<EmptyTrackProps> {
render() {
var className = this.props.className + ' empty';
return <div className={className}></div>;
}
}
module.exports = VisualizationWrapper;
|
resources/src/js/sections/Music/index.js | aberon10/thermomusic.com | 'use strict';
// Dependencies
import React from 'react';
import Ajax from '../../Libs/Ajax';
// Components
import ContentSpacing from '../../components/Containers/ContentSpacing';
import CoverArtist from '../../components/Containers/CoverArtist';
import MainContent from '../../components/Main';
import { stringFromCharCode, checkXMLHTTPResponse } from '../../app/utils/Utils';
export default class Music extends React.Component {
constructor(props) {
super(props);
this.state = {
element: null
};
this._updateState = this._updateState.bind(this);
this._loadData = this._loadData.bind(this);
}
componentDidMount() {
this._updateState();
}
componentWillReceiveProps() {
this._updateState();
}
_updateState() {
Ajax.post({
url: '/playlist/get_user_playlists',
responseType: 'json',
data: '',
}).then((response) => {
checkXMLHTTPResponse(response);
this._loadData(response);
}).catch((error) => {
//console.log(error);
});
}
_loadData(resp) {
let listItems = [];
listItems.push({
id: 0,
url: '/music/favorites',
name: 'Favoritos',
element: <div className="cover-artist-image__improved bg-alice-dark">
<i className='cover-artist-icon icon-heart'></i>
</div>
});
for (let i = 0; i < resp.data.length; i++) {
listItems.push({
id: resp.data[i].id_lista,
url: `${encodeURI('/playlist/index/' + resp.data[i].id_lista)}`,
name: stringFromCharCode(resp.data[i].nombre_lista),
element: <div className="cover-artist-image__improved bg-alice-dark">
<i className='cover-artist-icon icon-note'></i>
</div>
});
}
let element = <MainContent>
<ContentSpacing title='Tu Música'>
<CoverArtist data={listItems}></CoverArtist>
</ContentSpacing>
</MainContent>;
this.setState({ element: element });
}
render() {
if (this.state.element) {
return (
<div>{this.state.element}</div>
);
} else {
/*
TODO:
AGREGAR UN LOADING...
*/
return (
<MainContent>
<div>Loading...</div>
</MainContent>
);
}
}
}
|
packages/react/components/messagebar-attachments.js | iamxiaoma/Framework7 | import React from 'react';
import Utils from '../utils/utils';
import Mixins from '../utils/mixins';
import __reactComponentSlots from '../runtime-helpers/react-component-slots.js';
import __reactComponentSetProps from '../runtime-helpers/react-component-set-props.js';
class F7MessagebarAttachments extends React.Component {
constructor(props, context) {
super(props, context);
}
render() {
const props = this.props;
const {
className,
id,
style
} = props;
const classes = Utils.classNames(className, 'messagebar-attachments', Mixins.colorClasses(props));
return React.createElement('div', {
id: id,
style: style,
className: classes
}, this.slots['default']);
}
get slots() {
return __reactComponentSlots(this.props);
}
}
__reactComponentSetProps(F7MessagebarAttachments, Object.assign({
id: [String, Number],
className: String,
style: Object
}, Mixins.colorProps));
F7MessagebarAttachments.displayName = 'f7-messagebar-attachments';
export default F7MessagebarAttachments; |
packages/material-ui-icons/src/ArrowBack.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" /></g>
, 'ArrowBack');
|
src/router.js | markpalfreeman/github-labels | import app from 'ampersand-app'
import React from 'react'
import Router from 'ampersand-router'
import qs from 'qs'
import uuid from 'node-uuid'
import xhr from 'xhr'
import PublicPage from './pages/public'
import ReposPage from './pages/repos'
import RepoDetailPage from './pages/repo-detail'
import Layout from './layout'
import MessagePage from './pages/message'
import config from './config'
export default Router.extend({
routes: {
'': 'public',
'repos': 'repos',
'login': 'login',
'logout': 'logout',
'repo/:user/:name': 'repoDetail',
'auth/callback?:query': 'authCallBack',
'*fourOhFour': 'fourOhFour'
},
renderPage (page, opts = {layout: true}) {
if (opts.layout) {
page = (
<Layout me={app.me}>
{page}
</Layout>
)
}
React.render(page, document.body)
},
public () {
this.renderPage(<PublicPage/>, {layout: false})
},
repos () {
this.renderPage(<ReposPage repos={app.me.repos}/>)
},
repoDetail (user, name) {
const repo = app.me.repos.getByFullName(user + '/' + name)
this.renderPage(<RepoDetailPage repo={repo} labels={repo.labels}/>)
},
login () {
const state = uuid()
window.localStorage.state = state
window.location = 'https://github.com/login/oauth/authorize?' + qs.stringify({
client_id: config.clientId,
redirect_uri: window.location.origin + '/auth/callback',
scope: 'user,repo',
state: state
})
},
logout () {
window.localStorage.clear()
window.location = '/'
},
fourOhFour () {
this.renderPage(<MessagePage title='Page not found.'/>)
},
authCallBack (query) {
query = qs.parse(query)
if (query.state === window.localStorage.state) {
delete localStorage.state
xhr({
url: config.gatekeeperUrl + '/' + query.code,
json: true
}, (err, resp, body) => {
if (err) {
console.log('cannot authenticate')
} else {
app.me.token = body.token
this.redirectTo('/repos')
}
})
this.renderPage(<MessagePage title='Fetching repos...'/>)
}
}
}) |
admin/client/App/shared/Popout/PopoutBody.js | linhanyang/keystone | /**
* Render the body of a popout
*/
import React from 'react';
import blacklist from 'blacklist';
import classnames from 'classnames';
var PopoutBody = React.createClass({
displayName: 'PopoutBody',
propTypes: {
children: React.PropTypes.node.isRequired,
className: React.PropTypes.string,
scrollable: React.PropTypes.bool,
},
render () {
const className = classnames('Popout__body', {
'Popout__scrollable-area': this.props.scrollable,
}, this.props.className);
const props = blacklist(this.props, 'className', 'scrollable');
return (
<div className={className} {...props} />
);
},
});
module.exports = PopoutBody;
|
packages/generator-ext-react/generators/app/templates/js/App.minimal.js | markbrocato/extjs-reactor | import React, { Component } from 'react';
import { Container } from '@extjs/ext-react';
// Enable responsiveConfig app-wide. You can remove this if you don't plan to build a responsive UI.
Ext.require('Ext.plugin.Responsive');
export default class App extends Component {
render() {
return (
<Container fullscreen>
<%= appName %>
</Container>
)
}
} |
components/react-semantify/src/views/card.js | react-douban/douban-book-web | import React from 'react';
import ClassGenerator from '../mixins/classGenerator';
let defaultClassName = 'ui card';
const Card = React.createClass({
mixins: [ClassGenerator],
render: function () {
let {className, ...other} = this.props;
return (
<div {...other} className={this.getClassName(defaultClassName)} >
{this.props.children}
</div>
);
}
});
export default Card;
|
app/components/Counter.js | nickrfer/code-sentinel | // @flow
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import styles from './Counter.css';
class Counter extends Component {
props: {
increment: () => void,
incrementIfOdd: () => void,
incrementAsync: () => void,
decrement: () => void,
counter: number
};
render() {
const { increment, incrementIfOdd, incrementAsync, decrement, counter } = this.props;
return (
<div>
<div className={styles.backButton} data-tid="backButton">
<Link to="/">
<i className="fa fa-arrow-left fa-3x" />
</Link>
</div>
<div className={`counter ${styles.counter}`} data-tid="counter">
{counter}
</div>
<div className={styles.btnGroup}>
<button className={styles.btn} onClick={increment} data-tclass="btn">
<i className="fa fa-plus" />
</button>
<button className={styles.btn} onClick={decrement} data-tclass="btn">
<i className="fa fa-minus" />
</button>
<button className={styles.btn} onClick={incrementIfOdd} data-tclass="btn">odd</button>
<button className={styles.btn} onClick={() => incrementAsync()} data-tclass="btn">async</button>
</div>
</div>
);
}
}
export default Counter;
|
src/components/App.js | hanndbn/appDemo | import React from 'react';
import PropTypes from 'prop-types';
// This is a class-based component because the current
// version of hot reloading won't hot reload a stateless
// component at the top-level.
class App extends React.Component {
componentDidUpdate(){
this.runInit();
}
runInit(){
window.scrollTo(0,0);
$('.customJS').remove();
$('.simplyscrollJS').remove();
let scroller = $("#scroller").clone();
$("#scroller").remove();
let bxslider1 = $(".bxslider1").clone();
$(".bxslider1").remove();
const script = document.createElement("script");
script.className = 'customJS';
script.src = "../../libs/custom.js";
script.async = true;
document.body.appendChild(script);
const script1 = document.createElement("script");
script1.className = 'simplyscrollJS';
script1.src = "../../libs/jquery.simplyscroll.min.js";
script1.async = true;
document.body.appendChild(script1);
$('#bxslider1Div').append(bxslider1);
bxslider1.bxSlider({
pager: !1,
controls: !0,
moveSlides: 1,
hideControlOnEnd: !0,
infiniteLoop: !0,
auto: !0,
pause: 7e3,
speed: 2e3
});
$('#scrollerDiv').append(scroller);
scroller.simplyScroll({orientation: 'vertical'});
$(".i4ewOd-pzNkMb-haAclf").hide();
}
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
App.propTypes = {
children: PropTypes.element
};
export default App;
|
src/svg-icons/image/rotate-90-degrees-ccw.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageRotate90DegreesCcw = (props) => (
<SvgIcon {...props}>
<path d="M7.34 6.41L.86 12.9l6.49 6.48 6.49-6.48-6.5-6.49zM3.69 12.9l3.66-3.66L11 12.9l-3.66 3.66-3.65-3.66zm15.67-6.26C17.61 4.88 15.3 4 13 4V.76L8.76 5 13 9.24V6c1.79 0 3.58.68 4.95 2.05 2.73 2.73 2.73 7.17 0 9.9C16.58 19.32 14.79 20 13 20c-.97 0-1.94-.21-2.84-.61l-1.49 1.49C10.02 21.62 11.51 22 13 22c2.3 0 4.61-.88 6.36-2.64 3.52-3.51 3.52-9.21 0-12.72z"/>
</SvgIcon>
);
ImageRotate90DegreesCcw = pure(ImageRotate90DegreesCcw);
ImageRotate90DegreesCcw.displayName = 'ImageRotate90DegreesCcw';
ImageRotate90DegreesCcw.muiName = 'SvgIcon';
export default ImageRotate90DegreesCcw;
|
web/containers/About/About.js | viatsko/lyn | import React from 'react';
export default class About extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>About</h1>
<p>This is about page content</p>
</div>
);
}
}
|
src/client/src/main.js | dhagan/react-constructor | /*
* Copyright 2015 Alexander Pustovalov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// third-party libs
import '../lib/bootstrap/css/custom/bootstrap.css';
import '../lib/bootstrap/js/bootstrap.js';
import '../lib/font-awesome/css/font-awesome.css';
import '../lib/react-widgets/css/react-widgets.css';
// umyproto libs
import '../css/umyproto.deskpage.css';
import 'babel-core/polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import storeManager from './store/storeManager.js';
import initialState from './store/initialState.js';
import { saveProject } from './actions/applicationActions.js';
import { handleCompilerMessage } from './actions/webSocketActions.js';
import { Provider } from 'react-redux';
import Application from './components/application/Application.js';
//import { fromJS } from 'immutable';
import { init } from './plugin/plugins.js';
import docCookie from './api/cookies.js';
const user = docCookie.getItem("helmet-react-ui-builder-user");
const pass = docCookie.getItem("helmet-react-ui-builder-pass");
init();
const store = storeManager(initialState);
const { protocol, hostname, port } = window.location;
const socket = io.connect(protocol + '//' + hostname + ':' + port);
socket.on( 'invitation', message => console.log(message) );
socket.on( 'compiler.message', stats => {
store.dispatch(handleCompilerMessage(stats));
});
//window.onbeforeunload = function(e) {
// store.dispatch(saveProject());
//};
ReactDOM.render(
<Provider store={store}>
<Application />
</Provider>,
document.getElementById('content')
);
|
.storybook/Image.stories.js | kylpo/kylpo-monorepo | import React from 'react'
import { storiesOf, action } from '@kadira/storybook'
import Image from '../Image'
import Col from '../packages/Col'
storiesOf('Image', module)
.add('without children', () => (
<Image src='https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150' />
))
.add('with children', () => (
<Image
src='https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150'
width={350}
height={150}
>
I am child text
</Image>
))
.add('without children maxWidth', () => (
<Image
src='https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150'
width={350}
maxWidth={150}
height={150}
/>
))
.add('with children maxWidth', () => (
<Image
src='https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150'
width={350}
maxWidth={150}
height={150}
>
I am child text
</Image>
))
.add('with Col centered child', () => (
<Image
src='https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150'
width={350}
height={150}
>
<Col
justifyContent='center'
alignItems='center'
height='100%'
>
I am child text
</Col>
</Image>
))
|
pages/roadmap.js | bmagic/acdh-client | import React from 'react'
import {withReduxSaga} from 'configureStore'
import Layout from 'components/Layout'
import Title from 'components/Title'
import Meta from 'components/Meta'
class RoadmapPage extends React.Component {
render () {
return (
<Layout>
<div id='roadmap-page'>
<Meta title='Feuille de route' description='Ce que vous pouvez et que vous pourrez faire sur ACDH.fr' />
<Title title='Feuille de route' subtitle='Ce que vous pouvez et que vous pourrez faire sur ACDH.fr' />
<section className='section'>
<div className='container'>
<div className='columns'>
<div className='column'>
<div className='content has-text-justified'>
<p>
Le site ACDH.fr est construit en 3 versions : Alpha, Beta et Finale. Chacune d'entre elles marque une étapes importante au niveau technique.
</p>
<h3>Alpha</h3>
<p>
La version Alpha sert à tester le choix technique retenu pour la création du site.
</p>
<p>
Elle intègre donc toutes les fonctionnalités de base de gestion des utilisateurs mais aussi une recherche simple des émissions.
</p>
<h3>Beta</h3>
<p>
Avec l'arrivée de la version Beta, le site se dotera d'un moteur de recheche plus puissant. Afin de pouvoir "nourrir" ce moteur de recherche, je vais lancer en parallèle la transcription des émissions.
</p>
<p>
Cette transcription, en plus de permettre une meilleure indexation des émissions, permettra de les mettre à disposision des personnes sourdes et malentendantes. Je n'ai pas encore retenu de solution technique à la réalisation de cette transcription mais il est probable qu'elle ait un coût important et qu'elle sera donc faite par étape.
</p>
<h3>Version finale</h3>
<p>
La version finale ne signifie pas la fin du développement du site. Elle représente ce que j'ai imaginé pour le site avant de commencer son développement.
</p>
<p>
Cette version sera toujours enrichie des nouvelles fonctionnalités comme l'ajout de filtres.
</p>
</div>
</div>
<div className='column is-1' />
<div className='column'>
<ul className='timeline'>
<li className='timeline-header'>
<span className='tag is-medium is-dark'>Version Alpha</span>
</li>
<li className='timeline-item'>
<div className='timeline-marker is-icon is-primary'>
<i className='fa fa-flag' />
</div>
<div className='timeline-content'>
<p className='heading'>Octobre 2017</p>
<ul>
<li>Création du site de base <i className='fa fa-check' /></li>
<li>Recherche texte simple <i className='fa fa-check' /></li>
<li>Gestion des utilisateurs <i className='fa fa-check' /></li>
</ul>
</div>
</li>
<li className='timeline-item'>
<div className='timeline-marker is-icon is-primary'>
<i className='fa fa-flag' />
</div>
<div className='timeline-content'>
<p className='heading'>Novembre 2017</p>
<ul>
<li>Optimisation mobile</li>
<li>Marquer ses émissions écoutées et favorites</li>
<li>Tri des programmes par pertinence, date, ordre alphabétique</li>
</ul>
</div>
</li>
<li className='timeline-header'>
<span className='tag is-medium is-dark'>Version Beta</span>
</li>
<li className='timeline-item'>
<div className='timeline-marker is-icon'>
<i className='fa fa-flag' />
</div>
<div className='timeline-content'>
<p className='heading'>Décembre 2017</p>
<ul>
<li>Recherche texte avancée avec prédiction</li>
<li>Transcription des émissions</li>
</ul>
</div>
</li>
<li className='timeline-header'>
<span className='tag is-medium is-dark'>Version finale 1.0</span>
</li>
<li className='timeline-item'>
<div className='timeline-marker is-icon'>
<i className='fa fa-flag' />
</div>
<div className='timeline-content'>
<p className='heading'>Janvier 2018</p>
<ul>
<li>Nouvelles fonctionnalités à définir</li>
</ul>
</div>
</li>
</ul>
</div>
</div>
</div>
</section>
</div>
</Layout>
)
}
}
export default withReduxSaga(RoadmapPage)
|
client/src/modules/Login/LoginPage.js | kvago36/graphql-relay | import React, { Component } from 'react';
import { gql, graphql, compose } from 'react-apollo';
import { Header } from 'semantic-ui-react';
import { connect } from 'react-redux';
import { LOGIN } from '../../auth/AuthConstants';
import Login from './Login';
import './LoginPage.css';
class LoginPage extends Component {
constructor(props) {
super(props);
this.state = {
error: false,
success: false,
message: '',
intervalId: '',
count: 3
}
}
ComponentWillUnMount () {
if (this.state.intervalId) {
clearInterval(this.state.intervalId)
};
}
handleSubmit = async ({email, password}) => {
this.setState({success: false, error: false, message: ''});
const result = await this.props.signinUserQuery({
variables: {
email,
password
}
});
if (result.data.signinUser.status === 404) {
this.setState({error: true, message: "Пользователя с такой почтой нет"});
return;
}
if (result.data.signinUser.status === 403) {
this.setState({error: true, message: "Неправильный пароль"});
return;
}
this.props.dispatch({type: LOGIN, token: result.data.signinUser.data.token, user: result.data.signinUser.data.user});
const redirectFromLoginPage = () => {
let count = this.state.count;
if (count === 0) {
clearInterval(this.state.intervalId);
this.props.history.push('/');
} else {
count --;
this.setState({count});
}
}
const intervalId = setInterval(redirectFromLoginPage, 1000);
this.setState({success: true, intervalId});
}
render() {
return (
<div className="form_login">
<div>
<Header size='large'>Авторизация</Header>
<Login count={this.state.count} message={this.state.message} serverError={this.state.error} success={this.state.success} onSubmit={this.handleSubmit} />
</div>
</div>
);
}
}
const SINGIN_USER = gql`
mutation signinUserQuery($email: String!, $password: String!) {
signinUser(email: {
email: $email,
password: $password
}) {
message
status
data {
token
user {
id,
name
}
}
}
}
`
export default compose(
connect(dispatch => ({dispatch})),
graphql(SINGIN_USER, { name: 'signinUserQuery' })
)(LoginPage);
|
docs/app/Examples/modules/Dropdown/States/DropdownExampleError.js | koenvg/Semantic-UI-React | import React from 'react'
import { Dropdown } from 'semantic-ui-react'
const options = [
{ key: 1, text: 'Choice 1', value: 1 },
{ key: 2, text: 'Choice 2', value: 2 },
]
const DropdownExampleError = () => (
<Dropdown text='Dropdown' options={options} error />
)
export default DropdownExampleError
|
packages/components/src/Dialog/Dialog.component.js | Talend/ui | import PropTypes from 'prop-types';
import React from 'react';
import Modal from 'react-bootstrap/lib/Modal';
import classNames from 'classnames';
import './Dialog.scss';
import Action from '../Actions/Action';
import ActionBar from '../ActionBar';
import Inject from '../Inject';
import Progress from '../Progress';
/**
* @param {object} props react props
* @example
<Dialog header="Hello world">content</Dialog>
*/
function Dialog({
action,
actionbar,
backdrop,
keyboard,
autoFocus,
enforceFocus,
restoreFocus,
children,
className,
closeButton,
components,
flex,
footer,
getComponent,
header,
subtitle,
error,
progress,
size,
type,
...props
}) {
const Renderers = Inject.getAll(getComponent, {
ActionBar,
Action,
});
const injected = Inject.all(getComponent, components);
const headerId = 'tc-dialog-header';
const subtext = error || subtitle;
return (
<Modal
backdrop={backdrop}
keyboard={keyboard}
autoFocus={autoFocus}
enforceFocus={enforceFocus}
restoreFocus={restoreFocus}
bsSize={size}
className={classNames({ 'modal-flex': flex }, className)}
role="dialog"
// we disable jsx-a11y/aria-props because the version we use does not consider it valid (bug)
// eslint-disable-next-line jsx-a11y/aria-props
aria-modal="true"
aria-labelledby={header ? headerId : null}
{...props}
>
{injected('before-modal-header')}
{header && (
<Modal.Header
className={classNames({ informative: type === Dialog.TYPES.INFORMATIVE })}
closeButton={closeButton}
>
<Modal.Title id={headerId} componentClass="h1">
{header}
</Modal.Title>
{subtext && subtext.length && (
<h3 className={classNames({ error: error && error.length }, 'modal-subtitle')}>
{subtext}
</h3>
)}
</Modal.Header>
)}
{injected('after-modal-header')}
{progress && <Progress contained {...progress} />}
{injected('before-modal-body')}
<Modal.Body>
{injected('before-children')}
{children}
{injected('after-children')}
</Modal.Body>
{injected('before-modal-body')}
{action && (
<Modal.Footer>
<Renderers.Action {...action} />
</Modal.Footer>
)}
{actionbar && (
<Modal.Footer>
<Renderers.ActionBar {...actionbar} />
</Modal.Footer>
)}
{footer && <Modal.Footer {...footer}>{injected('footer')}</Modal.Footer>}
</Modal>
);
}
Dialog.TYPES = {
DEFAULT: 'default',
INFORMATIVE: 'informative',
};
Dialog.displayName = 'Dialog';
Dialog.defaultProps = {
autoFocus: true,
backdrop: true,
closeButton: true,
enforceFocus: true,
keyboard: true,
restoreFocus: true,
type: Dialog.TYPES.DEFAULT,
};
Dialog.propTypes = {
header: PropTypes.string,
backdrop: PropTypes.bool,
subtitle: PropTypes.string,
error: PropTypes.string,
size: PropTypes.oneOf(['sm', 'small', 'lg', 'large']),
children: PropTypes.element,
show: PropTypes.bool,
action: PropTypes.shape(Action.propTypes),
footer: PropTypes.object,
actionbar: PropTypes.object,
closeButton: PropTypes.bool,
keyboard: PropTypes.bool,
autoFocus: PropTypes.bool,
enforceFocus: PropTypes.bool,
restoreFocus: PropTypes.bool,
getComponent: PropTypes.func,
components: PropTypes.object,
progress: PropTypes.object,
flex: PropTypes.bool,
className: PropTypes.string,
type: PropTypes.oneOf(Object.values(Dialog.TYPES)),
};
export default Dialog;
|
examples/codepush/app/index.js | bugsnag/bugsnag-react-native | import React, { Component } from 'react';
import CodePush from 'react-native-code-push';
import bugsnag from 'lib/bugsnag';
import NativeCrash from 'lib/native_crash';
import {
StyleSheet,
Text,
Button,
View
} from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F7A6C6',
},
welcome: {
fontSize: 28,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 60,
},
});
class BugsnagReactNativeExample extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Bugsnag + React Native
</Text>
<Text style={styles.instructions}>
To get started, click one of the options below:
</Text>
<Button onPress={this.identifyUser}
title="Sign in a user"
accessibilityLabel="Sign in a user" />
<Button onPress={this.triggerHandledError}
title="Trigger handled error"
accessibilityLabel="Trigger a handled error which is sent to Bugsnag" />
<Button onPress={this.triggerReferenceError}
title="Trigger reference error"
accessibilityLabel="Trigger a reference error with an invalid reference" />
<Button onPress={this.triggerNativeException}
title="Trigger native crash"
accessibilityLabel="Trigger a native crash" />
<Button onPress={this.triggerThrowException}
title="Throw JavaScript error"
accessibilityLabel="Throw a JavaScript error" />
</View>
);
}
triggerNativeException() {
NativeCrash.generateCrash();
}
triggerReferenceError() {
bugsnag.leaveBreadcrumb("Starting root computation");
100 / y();
}
triggerThrowException() {
throw new Error("The proposed value has been computed - and was wrong");
}
triggerHandledError() {
try {
decodeURIComponent("%")
} catch (e) {
bugsnag.notify(e)
}
}
identifyUser() {
bugsnag.setUser("123", "John Leguizamo", "[email protected]");
console.warn("Added user information for any future error reports.");
bugsnag.leaveBreadcrumb("Signed in", { type: "user" });
}
};
let codePushOptions = { checkFrequency: CodePush.CheckFrequency.ON_APP_RESUME };
BugsnagReactNativeExample = CodePush(codePushOptions)(BugsnagReactNativeExample);
export default BugsnagReactNativeExample;
|
docs/assets/js/app.js | shibe97/React-AwesomeModal | import React from 'react';
import ReactDOM from 'react-dom';
import Demo from './demo.js';
ReactDOM.render(
<Demo />,
document.getElementById('App')
);
|
node_modules/rc-time-picker/es/Header.js | ZSMingNB/react-news | import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
var Header = function (_Component) {
_inherits(Header, _Component);
function Header(props) {
_classCallCheck(this, Header);
var _this = _possibleConstructorReturn(this, (Header.__proto__ || Object.getPrototypeOf(Header)).call(this, props));
_initialiseProps.call(_this);
var value = props.value,
format = props.format;
_this.state = {
str: value && value.format(format) || '',
invalid: false
};
return _this;
}
_createClass(Header, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var value = nextProps.value,
format = nextProps.format;
this.setState({
str: value && value.format(format) || '',
invalid: false
});
}
}, {
key: 'getClearButton',
value: function getClearButton() {
var _props = this.props,
prefixCls = _props.prefixCls,
allowEmpty = _props.allowEmpty;
if (!allowEmpty) {
return null;
}
return React.createElement('a', {
className: prefixCls + '-clear-btn',
role: 'button',
title: this.props.clearText,
onMouseDown: this.onClear
});
}
}, {
key: 'getProtoValue',
value: function getProtoValue() {
return this.props.value || this.props.defaultOpenValue;
}
}, {
key: 'getInput',
value: function getInput() {
var _props2 = this.props,
prefixCls = _props2.prefixCls,
placeholder = _props2.placeholder;
var _state = this.state,
invalid = _state.invalid,
str = _state.str;
var invalidClass = invalid ? prefixCls + '-input-invalid' : '';
return React.createElement('input', {
className: prefixCls + '-input ' + invalidClass,
ref: 'input',
onKeyDown: this.onKeyDown,
value: str,
placeholder: placeholder,
onChange: this.onInputChange
});
}
}, {
key: 'render',
value: function render() {
var prefixCls = this.props.prefixCls;
return React.createElement(
'div',
{ className: prefixCls + '-input-wrap' },
this.getInput(),
this.getClearButton()
);
}
}]);
return Header;
}(Component);
Header.propTypes = {
format: PropTypes.string,
prefixCls: PropTypes.string,
disabledDate: PropTypes.func,
placeholder: PropTypes.string,
clearText: PropTypes.string,
value: PropTypes.object,
hourOptions: PropTypes.array,
minuteOptions: PropTypes.array,
secondOptions: PropTypes.array,
disabledHours: PropTypes.func,
disabledMinutes: PropTypes.func,
disabledSeconds: PropTypes.func,
onChange: PropTypes.func,
onClear: PropTypes.func,
onEsc: PropTypes.func,
allowEmpty: PropTypes.bool,
defaultOpenValue: PropTypes.object,
currentSelectPanel: PropTypes.string
};
var _initialiseProps = function _initialiseProps() {
var _this2 = this;
this.onInputChange = function (event) {
var str = event.target.value;
_this2.setState({
str: str
});
var _props3 = _this2.props,
format = _props3.format,
hourOptions = _props3.hourOptions,
minuteOptions = _props3.minuteOptions,
secondOptions = _props3.secondOptions,
disabledHours = _props3.disabledHours,
disabledMinutes = _props3.disabledMinutes,
disabledSeconds = _props3.disabledSeconds,
onChange = _props3.onChange,
allowEmpty = _props3.allowEmpty;
if (str) {
var originalValue = _this2.props.value;
var value = _this2.getProtoValue().clone();
var parsed = moment(str, format, true);
if (!parsed.isValid()) {
_this2.setState({
invalid: true
});
return;
}
value.hour(parsed.hour()).minute(parsed.minute()).second(parsed.second());
// if time value not allowed, response warning.
if (hourOptions.indexOf(value.hour()) < 0 || minuteOptions.indexOf(value.minute()) < 0 || secondOptions.indexOf(value.second()) < 0) {
_this2.setState({
invalid: true
});
return;
}
// if time value is disabled, response warning.
var disabledHourOptions = disabledHours();
var disabledMinuteOptions = disabledMinutes(value.hour());
var disabledSecondOptions = disabledSeconds(value.hour(), value.minute());
if (disabledHourOptions && disabledHourOptions.indexOf(value.hour()) >= 0 || disabledMinuteOptions && disabledMinuteOptions.indexOf(value.minute()) >= 0 || disabledSecondOptions && disabledSecondOptions.indexOf(value.second()) >= 0) {
_this2.setState({
invalid: true
});
return;
}
if (originalValue) {
if (originalValue.hour() !== value.hour() || originalValue.minute() !== value.minute() || originalValue.second() !== value.second()) {
// keep other fields for rc-calendar
var changedValue = originalValue.clone();
changedValue.hour(value.hour());
changedValue.minute(value.minute());
changedValue.second(value.second());
onChange(changedValue);
}
} else if (originalValue !== value) {
onChange(value);
}
} else if (allowEmpty) {
onChange(null);
} else {
_this2.setState({
invalid: true
});
return;
}
_this2.setState({
invalid: false
});
};
this.onKeyDown = function (e) {
if (e.keyCode === 27) {
_this2.props.onEsc();
}
};
this.onClear = function () {
_this2.setState({ str: '' });
_this2.props.onClear();
};
};
export default Header; |
examples/react-router-redux/src/index.js | stylesuxx/generator-react-webpack-redux | import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { browserHistory, Router } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import configureStore from './stores';
import routes from './routes';
const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store);
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>,
document.getElementById('app')
);
|
app/javascript/mastodon/features/compose/containers/sensitive_button_container.js | rutan/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import IconButton from '../../../components/icon_button';
import { changeComposeSensitivity } from '../../../actions/compose';
import Motion from '../../ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import { injectIntl, defineMessages } from 'react-intl';
const messages = defineMessages({
marked: { id: 'compose_form.sensitive.marked', defaultMessage: 'Media is marked as sensitive' },
unmarked: { id: 'compose_form.sensitive.unmarked', defaultMessage: 'Media is not marked as sensitive' },
});
const mapStateToProps = state => ({
visible: state.getIn(['compose', 'media_attachments']).size > 0,
active: state.getIn(['compose', 'sensitive']),
disabled: state.getIn(['compose', 'spoiler']),
});
const mapDispatchToProps = dispatch => ({
onClick () {
dispatch(changeComposeSensitivity());
},
});
class SensitiveButton extends React.PureComponent {
static propTypes = {
visible: PropTypes.bool,
active: PropTypes.bool,
disabled: PropTypes.bool,
onClick: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
render () {
const { visible, active, disabled, onClick, intl } = this.props;
return (
<Motion defaultStyle={{ scale: 0.87 }} style={{ scale: spring(visible ? 1 : 0.87, { stiffness: 200, damping: 3 }) }}>
{({ scale }) => {
const icon = active ? 'eye-slash' : 'eye';
const className = classNames('compose-form__sensitive-button', {
'compose-form__sensitive-button--visible': visible,
});
return (
<div className={className} style={{ transform: `scale(${scale})` }}>
<IconButton
className='compose-form__sensitive-button__icon'
title={intl.formatMessage(active ? messages.marked : messages.unmarked)}
icon={icon}
onClick={onClick}
size={18}
active={active}
disabled={disabled}
style={{ lineHeight: null, height: null }}
inverted
/>
</div>
);
}}
</Motion>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(SensitiveButton));
|
src/modules/selects/SelectPlugin/SelectPlugin.js | hellofresh/janus-dashboard | import React from 'react'
import PropTypes from 'prop-types'
import Select from 'react-select'
import 'react-select/dist/react-select.css'
import './SelectPlugin.css'
const propTypes = {
name: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
options: PropTypes.arrayOf(PropTypes.object).isRequired
}
const SelectPlugin = ({ name, onChange, options }) => {
return (
<Select
className='j-select'
name={name}
options={options}
onChange={onChange}
/>
)
}
SelectPlugin.propTypes = propTypes
export default SelectPlugin
|
app/containers/Root.js | FermORG/FermionJS | // @flow
import React from 'react';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import Routes from '../routes';
type RootType = {
store: {},
history: {}
};
export default function Root({ store, history }: RootType) {
return (
<Provider store={store}>
<ConnectedRouter history={history}>
<Routes />
</ConnectedRouter>
</Provider>
);
}
|
src/components/blocks/BlockFeedbackText.js | m0sk1t/react_email_editor | /* eslint-disable */
import React from 'react';
import { connect } from 'react-redux';
import { stylizeBlock } from '../../actions';
const mapStateToProps = (state) => {
return {
config: state.tinymce_config
};
};
const mapDispatchToProps = (dispatch) => {
return {
onPropChange: (prop, val, container, elementIndex) => {
dispatch(stylizeBlock(prop, val, container, elementIndex));
}
};
};
const BlockFeedbackText = connect(
mapStateToProps,
mapDispatchToProps
)(({ id, config, blockOptions, onPropChange }) => {
const initEditable = () => {
window.tinymce.init({
...config,
selector: `#id_${id} td.editable`,
init_instance_callback: (editor) => {
editor.on('change', function (e) {
onPropChange('text', e.target.targetElm.innerHTML, false, 1);
});
}
})
};
const imgLocation = '/';
return (
<table
width="550"
cellPadding="0"
cellSpacing="0"
role="presentation"
>
<tbody>
<tr>
<td
style={blockOptions.elements[0]}
width={blockOptions.elements[0].width.match(/\d+/)[0]}
>
<a
target="_blank"
href={blockOptions.elements[0].like_link}
title={blockOptions.elements[0].like_link}
style={{
"display": blockOptions.elements[0].like_display
}}
>
<img alt="like" src={`${imgLocation}${blockOptions.elements[0].like_source}`} />
</a>
<a
target="_blank"
href={blockOptions.elements[0].neutral_link}
title={blockOptions.elements[0].neutral_link}
style={{
"display": blockOptions.elements[0].neutral_display
}}
>
<img alt="neutral" src={`${imgLocation}${blockOptions.elements[0].neutral_source}`} />
</a>
<a
target="_blank"
href={blockOptions.elements[0].dislike_link}
title={blockOptions.elements[0].dislike_link}
style={{
"display": blockOptions.elements[0].dislike_display
}}
>
<img alt="dislike" src={`${imgLocation}${blockOptions.elements[0].dislike_source}`} />
</a>
</td>
<td
className="editable"
onClick={() => initEditable()}
style={blockOptions.elements[1]}
width={blockOptions.elements[1].width.match(/\d+/)[0]}
dangerouslySetInnerHTML={{__html: blockOptions?blockOptions.elements[1].text:'empty node'}}
></td>
</tr>
</tbody>
</table>
);
});
export default BlockFeedbackText;
|
src/svg-icons/action/compare-arrows.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionCompareArrows = (props) => (
<SvgIcon {...props}>
<path d="M9.01 14H2v2h7.01v3L13 15l-3.99-4v3zm5.98-1v-3H22V8h-7.01V5L11 9l3.99 4z"/>
</SvgIcon>
);
ActionCompareArrows = pure(ActionCompareArrows);
ActionCompareArrows.displayName = 'ActionCompareArrows';
ActionCompareArrows.muiName = 'SvgIcon';
export default ActionCompareArrows;
|
src/components/SettingsWrapper.js | joellanciaux/Griddle | import React from 'react';
// This is a component that wraps all of the other settings components ( SettingsToggle, Settings, etc).
// All of the settings views will be hiddne if isEnabled = false
const SettingsWrapper = ({ SettingsToggle, Settings, isEnabled, isVisible, style, className }) => (
isEnabled ? (
<div style={style} className={className}>
{ SettingsToggle && <SettingsToggle /> }
{ isVisible && <Settings /> }
</div>
) : null
)
export default SettingsWrapper;
|
docs/src/PropTable.js | albertojacini/react-bootstrap | import merge from 'lodash-compat/object/merge';
import React from 'react';
import Glyphicon from '../../src/Glyphicon';
import Label from '../../src/Label';
import Table from '../../src/Table';
let cleanDocletValue = str => str.trim().replace(/^\{/, '').replace(/\}$/, '');
let capitalize = str => str[0].toUpperCase() + str.substr(1);
function getPropsData(component, metadata) {
let componentData = metadata[component] || {};
let props = componentData.props || {};
if (componentData.composes) {
componentData.composes.forEach(other => {
if (other !== component) {
props = merge({}, getPropsData(other, metadata), props);
}
});
}
if (componentData.mixins) {
componentData.mixins.forEach( other => {
if (other !== component && componentData.composes.indexOf(other) === -1) {
props = merge({}, getPropsData(other, metadata), props);
}
});
}
return props;
}
const PropTable = React.createClass({
contextTypes: {
metadata: React.PropTypes.object
},
componentWillMount() {
this.propsData = getPropsData(this.props.component, this.context.metadata);
},
render() {
let propsData = this.propsData;
if ( !Object.keys(propsData).length) {
return <span/>;
}
return (
<Table bordered striped className="prop-table">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Default</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{ this._renderRows(propsData) }
</tbody>
</Table>
);
},
_renderRows(propsData) {
return Object.keys(propsData)
.sort()
.filter(propName => propsData[propName].type && !propsData[propName].doclets.private )
.map(propName => {
let propData = propsData[propName];
return (
<tr key={propName} className="prop-table-row">
<td>
{propName} {this.renderRequiredLabel(propData)}
</td>
<td>
<div>{this.getType(propData)}</div>
</td>
<td>{propData.defaultValue}</td>
<td>
{ propData.doclets.deprecated
&& <div className="prop-desc-heading">
<strong className="text-danger">{'Deprecated: ' + propData.doclets.deprecated + ' '}</strong>
</div>
}
{ this.renderControllableNote(propData, propName) }
<div className="prop-desc" dangerouslySetInnerHTML={{__html: propData.descHtml }} />
</td>
</tr>
);
});
},
renderRequiredLabel(prop) {
if (!prop.required) {
return null;
}
return (
<Label>required</Label>
);
},
renderControllableNote(prop, propName) {
let controllable = prop.doclets.controllable;
let isHandler = this.getDisplayTypeName(prop.type.name) === 'function';
if (!controllable) {
return false;
}
let text = isHandler ? (
<span>
controls <code>{controllable}</code>
</span>
) : (
<span>
controlled by: <code>{controllable}</code>,
initial prop: <code>{'default' + capitalize(propName)}</code>
</span>
);
return (
<div className="prop-desc-heading">
<small>
<em className="text-info">
<Glyphicon glyph="info-sign"/>
{ text }
</em>
</small>
</div>
);
},
getType(prop) {
let type = prop.type || {};
let name = this.getDisplayTypeName(type.name);
let doclets = prop.doclets || {};
switch (name) {
case 'object':
return name;
case 'union':
return type.value.reduce((current, val, i, list) => {
let item = this.getType({ type: val });
if (React.isValidElement(item)) {
item = React.cloneElement(item, {key: i});
}
current = current.concat(item);
return i === (list.length - 1) ? current : current.concat(' | ');
}, []);
case 'array':
let child = this.getType({ type: type.value });
return <span>{'array<'}{ child }{'>'}</span>;
case 'enum':
return this.renderEnum(type);
case 'custom':
return cleanDocletValue(doclets.type || name);
default:
return name;
}
},
getDisplayTypeName(typeName) {
if (typeName === 'func') {
return 'function';
} else if (typeName === 'bool') {
return 'boolean';
}
return typeName;
},
renderEnum(enumType) {
const enumValues = enumType.value || [];
const renderedEnumValues = [];
enumValues.forEach(function renderEnumValue(enumValue, i) {
if (i > 0) {
renderedEnumValues.push(
<span key={`${i}c`}>, </span>
);
}
renderedEnumValues.push(
<code key={i}>{enumValue}</code>
);
});
return (
<span>one of: {renderedEnumValues}</span>
);
}
});
export default PropTable;
|
examples/with-typestyle/pages/index.js | BlancheXu/test | import React from 'react'
import { style } from 'typestyle'
const className = style({ color: 'red' })
const RedText = ({ text }) => <div className={className}>{text}</div>
export default () => <RedText text='Hello Next.js!' />
|
app/containers/Programs/Programs.js | klpdotorg/tada-frontend | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Loadable from 'react-loadable';
import isEmpty from 'lodash.isempty';
import {
getPrograms,
toggleCreateProgramModal,
toggleCreateAssessmentModal,
selectProgram,
} from '../../actions';
import { Loading } from '../../components/common';
const ProgramView = Loadable({
loader: () => {
return import('../../components/Programs/Programs');
},
loading: Loading,
});
class GetPrograms extends Component {
componentDidMount() {
// Fetching all programs
if (isEmpty(this.props.programs)) {
this.props.getPrograms();
}
}
render() {
return <ProgramView {...this.props} />;
}
}
GetPrograms.propTypes = {
getPrograms: PropTypes.func,
programs: PropTypes.object,
};
const mapStateToProps = (state) => {
return {
programs: state.programs.programs,
selectedProgram: Number(state.programs.selectedProgram),
loading: state.programs.loading,
};
};
const Programs = connect(mapStateToProps, {
getPrograms,
openAddAssessmentModal: toggleCreateAssessmentModal,
openCreateProgramModal: toggleCreateProgramModal,
selectProgram,
})(GetPrograms);
export { Programs };
|
public/client-render.js | mookey/consi | 'use strict';
import React from 'react'; // eslint-disable-line
import ReactDOM from 'react-dom';
import { Router } from 'react-router';
import { routes } from '../server/routes';
import createBrowserHistory from 'history/lib/createBrowserHistory';
require('normalize.css');
require('./entry.scss');
ReactDOM.render(
<Router routes={routes} history={createBrowserHistory()} />,
document.getElementById('main')
); |
admin/client/App/screens/List/components/Filtering/ListFiltersAdd.js | benkroeger/keystone | import React from 'react';
import { findDOMNode } from 'react-dom';
import Transition
from 'react-addons-css-transition-group';
import classnames from 'classnames';
import ListFiltersAddForm from './ListFiltersAddForm';
import Popout from '../../../../shared/Popout';
import PopoutList from '../../../../shared/Popout/PopoutList';
import { FormInput } from '../../../../elemental';
import ListHeaderButton from '../ListHeaderButton';
import { setFilter } from '../../actions';
var ListFiltersAdd = React.createClass({
displayName: 'ListFiltersAdd',
propTypes: {
maxHeight: React.PropTypes.number,
},
getDefaultProps () {
return {
maxHeight: 360,
};
},
getInitialState () {
return {
innerHeight: 0,
isOpen: false,
searchString: '',
selectedField: false,
};
},
updateSearch (e) {
this.setState({ searchString: e.target.value });
},
openPopout () {
this.setState({ isOpen: true }, this.focusSearch);
},
closePopout () {
this.setState({
innerHeight: 0,
isOpen: false,
searchString: '',
selectedField: false,
});
},
setPopoutHeight (height) {
this.setState({ innerHeight: Math.min(this.props.maxHeight, height) });
},
navigateBack () {
this.setState({
selectedField: false,
searchString: '',
innerHeight: 0,
}, this.focusSearch);
},
focusSearch () {
findDOMNode(this.refs.search).focus();
},
selectField (field) {
this.setState({
selectedField: field,
});
},
applyFilter (value) {
this.props.dispatch(setFilter(this.state.selectedField.path, value));
this.closePopout();
},
renderList () {
const activeFilterFields = this.props.activeFilters.map(obj => obj.field);
const activeFilterPaths = activeFilterFields.map(obj => obj.path);
const { searchString } = this.state;
let filteredFilters = this.props.availableFilters;
if (searchString) {
filteredFilters = filteredFilters
.filter(filter => filter.type !== 'heading')
.filter(filter => new RegExp(searchString)
.test(filter.field.label.toLowerCase()));
}
const popoutList = filteredFilters.map((el, i) => {
if (el.type === 'heading') {
return (
<PopoutList.Heading key={'heading_' + i}>
{el.content}
</PopoutList.Heading>
);
}
const filterIsActive = activeFilterPaths.length && (activeFilterPaths.indexOf(el.field.path) > -1);
return (
<PopoutList.Item
key={'item_' + el.field.path}
icon={filterIsActive ? 'check' : 'chevron-right'}
iconHover={filterIsActive ? 'check' : 'chevron-right'}
isSelected={!!filterIsActive}
label={el.field.label}
onClick={() => { this.selectField(el.field); }} />
);
});
const formFieldStyles = {
borderBottom: '1px dashed rgba(0, 0, 0, 0.1)',
marginBottom: '1em',
paddingBottom: '1em',
};
return (
<Popout.Pane onLayout={this.setPopoutHeight} key="list">
<Popout.Body>
<div style={formFieldStyles}>
<FormInput
onChange={this.updateSearch}
placeholder="Find a filter..."
ref="search"
value={this.state.searchString}
/>
</div>
{popoutList}
</Popout.Body>
</Popout.Pane>
);
},
renderForm () {
return (
<Popout.Pane onLayout={this.setPopoutHeight} key="form">
<ListFiltersAddForm
activeFilters={this.props.activeFilters}
field={this.state.selectedField}
onApply={this.applyFilter}
onCancel={this.closePopout}
onBack={this.navigateBack}
maxHeight={this.props.maxHeight}
onHeightChange={this.setPopoutHeight}
dispatch={this.props.dispatch}
/>
</Popout.Pane>
);
},
render () {
const { isOpen, selectedField } = this.state;
const popoutBodyStyle = this.state.innerHeight
? { height: this.state.innerHeight }
: null;
const popoutPanesClassname = classnames('Popout__panes', {
'Popout__scrollable-area': !selectedField,
});
return (
<div>
<ListHeaderButton
active={isOpen}
glyph="eye"
id="listHeaderFilterButton"
label="Filter"
onClick={isOpen ? this.closePopout : this.openPopout}
/>
<Popout isOpen={isOpen} onCancel={this.closePopout} relativeToID="listHeaderFilterButton">
<Popout.Header
leftAction={selectedField ? this.navigateBack : null}
leftIcon={selectedField ? 'chevron-left' : null}
title={selectedField ? selectedField.label : 'Filter'}
transitionDirection={selectedField ? 'next' : 'prev'} />
<Transition
className={popoutPanesClassname}
component="div"
style={popoutBodyStyle}
transitionName={selectedField ? 'Popout__pane-next' : 'Popout__pane-prev'}
transitionEnterTimeout={360}
transitionLeaveTimeout={360}
>
{selectedField ? this.renderForm() : this.renderList()}
</Transition>
</Popout>
</div>
);
},
});
module.exports = ListFiltersAdd;
|
src/index.js | remy-guyz-hackeference-2016/front-end | import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import App from './components/App';
import './index.css';
import rootReducer from './store/reducers';
const middleware = [ thunk ];
if (process.env.NODE_ENV !== 'production') {
middleware.push(createLogger());
}
const store = createStore(
rootReducer,
applyMiddleware(...middleware)
);
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
|
ui/src/main/js/components/JobList.js | rdelval/aurora | import React from 'react';
import Icon from 'components/Icon';
import JobListItem from 'components/JobListItem';
import Pagination from 'components/Pagination';
import { isNully } from 'utils/Common';
import { TASK_COUNTS } from 'utils/Job';
// VisibleForTesting
export function searchJob(job, query) {
const taskConfig = job.job.taskConfig;
const jobType = taskConfig.isService ? 'service' : job.job.cronSchedule ? 'cron' : 'adhoc';
return (job.job.key.name.includes(query) ||
taskConfig.tier.startsWith(query) ||
job.job.key.environment.startsWith(query) ||
jobType.startsWith(query));
}
export function JobListSortControl({ onClick }) {
return (<ul className='job-task-stats job-list-sort-control'>
<li>sort by:</li>
{TASK_COUNTS.map((key) => {
const label = key.replace('TaskCount', '');
return (<li key={key} onClick={(e) => onClick(key)}>
<span className={`img-circle ${label}-task`} /> {label}
</li>);
})}
</ul>);
}
export default class JobList extends React.Component {
constructor(props) {
super(props);
this.state = {filter: props.filter, sortBy: props.sortBy};
}
setFilter(e) {
this.setState({filter: e.target.value});
}
setSort(sortBy) {
this.setState({sortBy});
}
render() {
const that = this;
const sortFn = this.state.sortBy ? (j) => j.stats[that.state.sortBy] : (j) => j.job.key.name;
const filterFn = (j) => that.state.filter ? searchJob(j, that.state.filter) : true;
return (<div className='job-list'>
<div className='table-input-wrapper'>
<Icon name='search' />
<input
autoFocus
onChange={(e) => this.setFilter(e)}
placeholder='Search jobs by name, environment, type or tier'
type='text' />
</div>
<JobListSortControl onClick={(key) => this.setSort(key)} />
<table className='psuedo-table'>
<Pagination
data={this.props.jobs}
filter={filterFn}
hideIfSinglePage
isTable
numberPerPage={25}
renderer={(job) => <JobListItem
env={that.props.env}
job={job}
key={`${job.job.key.environment}/${job.job.key.name}`} />}
// Always sort task count sorts in descending fashion (for UX reasons)
reverseSort={!isNully(this.state.sortBy)}
sortBy={sortFn} />
</table>
</div>);
}
}
|
src/frontend/components/Spinner/index.js | Koleso/invoicer | import React from 'react';
import cx from 'helpers/classes';
// CSS
import './index.less';
const Spinner = ({ modifiers }) => {
const bm = 'Spinner';
return (
<div className={cx(bm, '', modifiers)}>
<div className={cx(bm, 'spinner')}></div>
</div>
);
};
export default Spinner;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.