path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
|
info5900groupG/dataishumantool
|
import React from 'react';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
React.render(<HelloWorld />, document.getElementById('react-root'));
|
redux-todos/index.js
|
stoepszli/js-demos
|
import 'todomvc-app-css/index.css';
import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import configureStore from './store/configureStore';
import Root from './containers/Root';
const store = configureStore();
render(
<AppContainer>
<Root
store={ store }
/>
</AppContainer>,
document.getElementById('root')
);
if (module.hot) {
module.hot.accept('./containers/Root', () => {
const RootContainer = require('./containers/Root').default;
render(
<AppContainer>
<RootContainer
store={ store }
/>
</AppContainer>,
document.getElementById('root')
);
});
}
|
app/containers/AthleteSchedule/AthleteTrainingList.js
|
kdprojects/nichesportapp
|
import React from 'react';
import H3 from 'components/H3';
import RaisedButton from 'material-ui/RaisedButton';
import CenteredSection from '../../containers/HomePage/CenteredSection';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn,
} from 'material-ui/Table';
import Loading from 'components/LoadingIndicator';
export class AthleteTrainingList extends React.Component { // eslint-disable-line react/prefer-stateless-function
shouldComponentUpdate() {
return true;
}
calculateTime(dateTime){
let time = dateTime.toTimeString();
let timeString = time.substring(0,9);
let H = +timeString.substr(0, 2);
let h = H % 12 || 12;
let ampm = H < 12 ? "AM" : "PM";
timeString = h + timeString.substr(2, 3) + ampm;
let date = dateTime.toDateString();
let formattedDateTime = date + ', ' + timeString;
return formattedDateTime;
}
render() {
if (this.props.data.loading) {
return (<Loading />)
}
if (this.props.data.error) {
console.log(this.props.data.error)
return (<div>An unexpected error occurred</div>)
}
return (
<CenteredSection>
<Table
fixedHeader={true}
selectable={false}
multiSelectable={false}>
>
<TableHeader
displaySelectAll={false}
adjustForCheckbox={false}
enableSelectAll={false}
>
<TableRow>
<TableHeaderColumn style={{fontSize:"18px",textAlign: 'center'}}>Training Session</TableHeaderColumn>
<TableHeaderColumn style={{fontSize:"18px",textAlign: 'center'}}>Date</TableHeaderColumn>
<TableHeaderColumn style={{fontSize:"18px",textAlign: 'center'}}>Time</TableHeaderColumn>
<TableHeaderColumn style={{fontSize:"18px",textAlign: 'center'}}>Team</TableHeaderColumn>
<TableHeaderColumn style={{fontSize:"18px",textAlign: 'center'}}>Location</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody
displayRowCheckbox={false}
deselectOnClickaway={false}
showRowHover={true}
>
{this.props.data.allTrainings.map((team, index)=>(
<TableRow key={team.id}>
<TableRowColumn style={{textAlign: 'center'}}>{index+1}</TableRowColumn>
<TableRowColumn style={{textAlign: 'center'}}>
{team.trainingDates.length > 0 ?
team.trainingDates.map(trainingDate =>
<div key={trainingDate.id}>{this.calculateTime(new Date(trainingDate.date))}</div>) : ''}
</TableRowColumn>
<TableRowColumn style={{textAlign: 'center'}}>
{team.trainingDates.length > 0 ?
team.trainingDates.map(trainingDate =>
<div key={trainingDate.id}>{this.calculateTime(new Date(trainingDate.date))}</div>) : ''}
</TableRowColumn>
<TableRowColumn style={{textAlign: 'center'}}>{team.address}</TableRowColumn>
<TableRowColumn style={{textAlign: 'center'}}>{team.address}</TableRowColumn>
</TableRow>
))
}
</TableBody>
</Table>
</CenteredSection>
);
}
}
const TrainingsListQuery = gql`query TrainingsListQuery ($userId: ID) {
allTrainings(
filter:{
trainingTeams_some:{
team:{
atheletTeams_some:{
status_in:[APPROVEDBYATHLETE APPROVEDBYCOACH APPROVEDBYINSTITUTE]
athlete:{
user:{
id: $userId
}
}
}
}
}
}
){
id
dateTime
address
numberOfSessions
coach{ id user{ id email firstName lastName } }
institute{ id name }
trainingTeams{ team{ id name atheletTeams{athlete{ user{id}} status }} }
trainingDates{ id date }
}
}`
const TrainingData = graphql(TrainingsListQuery, {
options: (props) => ({ variables: { userId: props.userId } }),
})(AthleteTrainingList);
export default TrainingData;
|
src/components/tracks/individual/_someAnimal/index.js
|
cannoneyed/tmm-glare
|
/* eslint-disable quotes */
import React from 'react'
// const timeline = [{
// time: 0,
// fact: ''
// }]
//
export default function Voyeur() {
return (
<div className="track-info-page">
<div className="track-text voyeur" />
</div>
)
}
|
packages/website/builder/pages/docs/navigation.js
|
yusufsafak/cerebral
|
import React from 'react'
import Search from './search'
function Navigation(props) {
function renderMenu() {
return Object.keys(props.docs).map(function(sectionKey, index) {
return (
<li
key={index}
className={`docs-navigation-item${props.sectionName === sectionKey ? ' active' : ''}`}
>
<a href={`/docs/${sectionKey}`}>{sectionKey.replace('_', ' ')}</a>
<div className="underline" />
</li>
)
})
}
return (
<div id="navigation" className="docs-navigation">
<ul className="docs-navigation-menu">
{renderMenu()}
</ul>
<Search />
<div className="docs-icons">
<a
href="https://github.com/cerebral/cerebral"
className="docs-icon"
target="_new"
>
<div className="docs-icon-github" />
github repo
</a>
<a
href="https://discord.gg/0kIweV4bd2bwwsvH"
className="docs-icon"
target="_new"
>
<div className="docs-icon-discord" />
chat
</a>
<a
href="http://cerebral-website.herokuapp.com/"
className="docs-icon"
target="_new"
style={{ color: '#DD4A68' }}
>
old website
</a>
</div>
</div>
)
}
export default Navigation
|
app/components/main/Footer.js
|
ayqy/ready-to-work
|
import React, { Component } from 'react';
import { Button, Radio, Row, Col } from 'antd';
export default class Header extends Component {
render() {
const padding = '6px';
return (
<div className="main-footer footer">
<Row style={{padding: `${padding} 0`}}>
<Col span={8}>
<Button onClick={this.props.handleSyncClick} style={{marginLeft: padding}} size="small" shape="circle" icon="sync" />
</Col>
<Col span={8} offset={8} style={{textAlign: 'right'}}>
<Button onClick={this.props.handleLoginClick} style={{marginRight: padding}} size="small" shape="circle" icon="user" />
<Button onClick={this.props.handleSettingClick} style={{marginRight: padding}} size="small" shape="circle" icon="setting" />
</Col>
</Row>
</div>
);
}
}
|
app/components/NotFound.js
|
okmttdhr/redux-blog-example
|
import styles from './../styles/global.styl';
import React from 'react';
import CSSModules from 'react-css-modules';
@CSSModules(styles)
export default class NotFound extends React.Component {
render() {
return (
<div styleName="wrapper">
<h1>Not Found</h1>
</div>
);
}
}
|
app/components/PlatformsPageComponents/Chatbot.js
|
rapicastillo/beautifulrising-client
|
/**
*
* AboutPageComponents
*
*/
import React from 'react';
import styled from 'styled-components';
import { FormattedMessage } from 'react-intl';
import { PlatformsSection } from 'components/PlatformsPageComponents';
import VisibilitySensor from 'react-visibility-sensor';
import messages from './messages';
import Markdown from 'react-remarkable';
const Container = styled.div``;
const Viewport = styled.div`
display: inline-block;
`;
const TextContent = styled.div`
width: 30%;
float: left;
`;
const Content = styled.div`
text-align: left;
`;
const ImageContent= styled.div`
width: 69%;
float: right;
height: 400px;
display: inline-block;
`;
const Image = styled.div`
width: 100%;
height: 100%;
background-image: url(${props=> `https://www.beautifulrising.org/${props.source}`})
background-size: contain;
background-position: center;
background-repeat: no-repeat;
`;
const Title = styled.h1``;
const Subtitle = styled.h3``;
export default class Chatbot extends React.Component {
render() {
if (!this.props.content || this.props.content === undefined) return null;
return (
<PlatformsSection id='chatbot' name='chatbot'>
<Container>
<Viewport>
<TextContent>
<Content>
<Title>
{this.props.content.get('title')}
</Title>
<Subtitle>
{this.props.content.get('introduction')}
</Subtitle>
<Subtitle>
<FormattedMessage {...messages.what} />
</Subtitle>
<Markdown source={this.props.content.get('what')} />
<Subtitle>
<FormattedMessage {...messages.how} />
</Subtitle>
<Markdown source={this.props.content.get('how')} />
</Content>
</TextContent>
<ImageContent>
<Image source={this.props.content.get('image')} />
</ImageContent>
</Viewport>
</Container>
</PlatformsSection>
);
}
}
|
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/components/FormComponents/Select.js
|
ChamNDeSilva/carbon-apimgt
|
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
const Select = (props) => (
<div className="form-group">
<select
name={props.name}
value={props.selectedOption}
onChange={props.controlFunc}
className="form-select">
<option value="">{props.placeholder}</option>
{props.options.map(opt => {
return (
<option
key={opt}
value={opt}>{opt}</option>
);
})}
</select>
</div>
);
Select.propTypes = {
name: React.PropTypes.string.isRequired,
options: React.PropTypes.array.isRequired,
selectedOption: React.PropTypes.string,
controlFunc: React.PropTypes.func.isRequired,
placeholder: React.PropTypes.string
};
export default Select;
|
src/ButtonGroup.js
|
xiaoking/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import CustomPropTypes from './utils/CustomPropTypes';
const ButtonGroup = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
vertical: React.PropTypes.bool,
justified: React.PropTypes.bool,
/**
* Display block buttons, only useful when used with the "vertical" prop.
* @type {bool}
*/
block: CustomPropTypes.all([
React.PropTypes.bool,
function(props) {
if (props.block && !props.vertical) {
return new Error('The block property requires the vertical property to be set to have any effect');
}
}
])
},
getDefaultProps() {
return {
block: false,
bsClass: 'button-group',
justified: false,
vertical: false
};
},
render() {
let classes = this.getBsClassSet();
classes['btn-group'] = !this.props.vertical;
classes['btn-group-vertical'] = this.props.vertical;
classes['btn-group-justified'] = this.props.justified;
classes['btn-block'] = this.props.block;
return (
<div
{...this.props}
className={classNames(this.props.className, classes)}>
{this.props.children}
</div>
);
}
});
export default ButtonGroup;
|
dev/6B_SCROLL.js
|
canalplus/react-keys
|
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { StyleSheet, css } from 'aphrodite/no-important';
import { createStore, combineReducers } from 'redux';
import { createStructuredSelector } from 'reselect';
import { connect, Provider } from 'react-redux';
import {
Binder,
keysInit,
keysReducer,
getBinderMarginLeft,
getCurrentSelectedId,
getCurrentBinder,
isVisibleInBinder,
} from '../src';
const styles = StyleSheet.create({
screen: {
display: 'block',
width: 400,
backgroundColor: 'grey',
height: 720,
overflow: 'hidden',
padding: 0,
margin: 0,
},
container: {
height: 220,
width: 360,
overflow: 'hidden',
},
ulStyle: {
listStyle: 'none',
width: 10000,
height: 220,
padding: 0,
margin: 0,
},
card: {
display: 'inline-block',
backgroundColor: 'yellow',
width: 100,
height: 200,
margin: 10,
},
focused: {
backgroundColor: 'green',
},
});
const store = createStore(
combineReducers({
'@@keys': keysReducer,
}),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
keysInit({ store });
const PureCard = ({ id, current, isVisible }) => (
<li id={id} className={css(styles.card, current === id && styles.focused)}>
#{id}
COUCOU = {`${isVisible}`}
</li>
);
const Card = connect((state, props) => ({
current: getCurrentSelectedId()(),
isVisible: isVisibleInBinder(props.binderId, props.id)(),
}))(PureCard);
const GenericBinder = ({ id, priority, downExit, upExit, marginLeft }) => {
return (
<Binder
id={id}
wrapper={`#wrapper-${id}`}
priority={priority || 0}
strategy="mirror"
onDownExit={downExit}
onUpExit={upExit}
visibilityOffset={200}
>
<div id={`wrapper-${id}`} className={css(styles.container)}>
<ul className={css(styles.ulStyle)} style={{ marginLeft }}>
<Card id={`${id}-1`} binderId={id} />
<Card id={`${id}-2`} binderId={id} />
<Card id={`${id}-3`} binderId={id} />
<Card id={`${id}-4`} binderId={id} />
<Card id={`${id}-5`} binderId={id} />
<Card id={`${id}-6`} binderId={id} />
</ul>
</div>
</Binder>
);
};
const ConnectedBinder = connect((state, props) => {
return createStructuredSelector({
marginLeft: getBinderMarginLeft(props.id),
});
})(GenericBinder);
class PureBase extends Component {
constructor(props) {
super(props);
this.state = { position: 0 };
}
componentWillReceiveProps({ binder: { id } }) {
if (id < 3) return;
this.setState({ position: (id - 3) * 220 });
}
render() {
return (
<div style={{ marginTop: -this.state.position }}>
{this.props.children}
</div>
);
}
}
const Base = connect(() => ({ binder: getCurrentBinder()() }))(PureBase);
ReactDOM.render(
<Provider store={store}>
<div className={css(styles.screen)}>
<Base>
<ConnectedBinder id="1" downExit="2" upExit={null} priority={1} />
<ConnectedBinder id="2" downExit="3" upExit="1" />
<ConnectedBinder id="3" downExit="4" upExit="2" />
<ConnectedBinder id="4" downExit="5" upExit="3" />
<ConnectedBinder id="5" downExit="6" upExit="4" />
<ConnectedBinder id="6" downExit="7" upExit="5" />
<ConnectedBinder id="7" downExit="8" upExit="6" />
<ConnectedBinder id="8" downExit="9" upExit="7" />
<ConnectedBinder id="9" downExit="10" upExit="8" />
<ConnectedBinder id="10" downExit="11" upExit="9" />
<ConnectedBinder id="11" downExit={null} upExit="10" />
</Base>
</div>
</Provider>,
document.getElementById('body')
);
|
src/routes/Customisable/components/plugins/invoice-address/invoice-address.plugin.js
|
codingarchitect/react-counter-pair
|
import React from 'react'
import { Form, FormGroup, FormControl, ControlLabel } from 'react-bootstrap'
import InvoiceAddress from './invoice-address.rt'
import extensibleComponent from '../extensible-component'
import FormLayoutPluginRenderer from '../form-layout-plugin-renderer'
const addressForm = {
Address1: (props) => (<FormGroup controlId="formInlineAddress1">
<ControlLabel>Address1</ControlLabel>
<FormControl type="text" placeholder="Address1" />
</FormGroup>),
Address2: (props) => (<FormGroup controlId="formInlineAddress2">
<ControlLabel>Address2</ControlLabel>
<FormControl type="text" placeholder="Address2" />
</FormGroup>),
Address3: (props) => (<FormGroup controlId="formInlineAddress3">
<ControlLabel>Address3</ControlLabel>
<FormControl type="text" placeholder="Address3" />
</FormGroup>),
Address4: (props) => (<FormGroup controlId="formInlineAddress4">
<ControlLabel>Address4</ControlLabel>
<FormControl type="text" placeholder="Address4" />
</FormGroup>),
Address5: (props) => (<FormGroup controlId="formInlineAddress5">
<ControlLabel>Address5</ControlLabel>
<FormControl type="text" placeholder="Address5" />
</FormGroup>),
Country: (props) => (<FormGroup controlId="formInlineCountry">
<ControlLabel>Country</ControlLabel>
<FormControl componentClass="select" placeholder="Country">
<option value="UK">UK</option>
<option value="US">US</option>
<option value="Other">Other</option>
</FormControl>
</FormGroup>),
Postcode: (props) => (<FormGroup controlId="formInlinePostcode">
<ControlLabel>Postcode</ControlLabel>
<FormControl type="text" placeholder="Postcode" />
</FormGroup>)
};
export const pluginMetadata = {
name : "react-counter/soe/soh/invoice-address",
displayName : 'Invoice Address',
sequence : 7,
active : true,
childPluginNames : []
}
export default extensibleComponent(InvoiceAddress, pluginMetadata.name, FormLayoutPluginRenderer, addressForm);
|
src/svg-icons/action/speaker-notes.js
|
barakmitz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSpeakerNotes = (props) => (
<SvgIcon {...props}>
<path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM8 14H6v-2h2v2zm0-3H6V9h2v2zm0-3H6V6h2v2zm7 6h-5v-2h5v2zm3-3h-8V9h8v2zm0-3h-8V6h8v2z"/>
</SvgIcon>
);
ActionSpeakerNotes = pure(ActionSpeakerNotes);
ActionSpeakerNotes.displayName = 'ActionSpeakerNotes';
ActionSpeakerNotes.muiName = 'SvgIcon';
export default ActionSpeakerNotes;
|
test/server/ModalSpec.js
|
RichardLitt/react-bootstrap
|
import React from 'react';
import {assert} from 'chai';
import Modal from '../../src/Modal.js';
describe('Modal', () => {
it('Should be rendered on the server side', function () {
let noOp = () => {};
assert.doesNotThrow(function renderOnServerSide() {
return React.renderToString(
<Modal onRequestHide={noOp}>
<strong>Message</strong>
</Modal>
);
});
});
});
|
src/Divider/Divider.spec.js
|
dsslimshaddy/material-ui
|
// @flow
import React from 'react';
import { assert } from 'chai';
import { createShallow, getClasses } from '../test-utils';
import Divider from './Divider';
describe('<Divider />', () => {
let shallow;
let classes;
before(() => {
shallow = createShallow({ dive: true });
classes = getClasses(<Divider />);
});
it('should render a hr', () => {
const wrapper = shallow(<Divider />);
assert.strictEqual(wrapper.name(), 'hr');
});
it('should render with the root and default class', () => {
const wrapper = shallow(<Divider />);
assert.strictEqual(wrapper.hasClass(classes.root), true);
assert.strictEqual(wrapper.hasClass(classes.default), true, 'should have the default class');
});
it('should set the absolute class', () => {
const wrapper = shallow(<Divider absolute />);
assert.strictEqual(wrapper.hasClass(classes.absolute), true, 'should be absolute');
});
it('should set the inset class', () => {
const wrapper = shallow(<Divider inset />);
assert.strictEqual(wrapper.hasClass(classes.inset), true, 'should have inset class');
});
it('should set the light class', () => {
const wrapper = shallow(<Divider light />);
assert.strictEqual(wrapper.hasClass(classes.light), true, 'should have light class');
});
});
|
src/views/UserEdit/UserForm.js
|
folio-org/ui-users
|
import isEqual from 'lodash/isEqual';
import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl, FormattedMessage } from 'react-intl';
import { Field, FormSpy } from 'react-final-form';
import setFieldData from 'final-form-set-field-data';
import { AppIcon } from '@folio/stripes/core';
import {
Paneset,
Pane,
PaneMenu,
PaneHeaderIconButton,
PaneFooter,
Button,
ExpandAllButton,
Row,
Col,
Headline,
AccordionSet,
AccordionStatus,
HasCommand,
} from '@folio/stripes/components';
import { EditCustomFieldsRecord } from '@folio/stripes/smart-components';
import stripesFinalForm from '@folio/stripes/final-form';
import {
EditUserInfo,
EditExtendedInfo,
EditContactInfo,
EditProxy,
EditServicePoints,
} from '../../components/EditSections';
import { getFullName } from '../../components/util';
import RequestFeeFineBlockButtons from '../../components/RequestFeeFineBlockButtons';
import PermissionsAccordion from '../../components/PermissionsAccordion';
import {
statusFilterConfig,
permissionTypeFilterConfig,
} from '../../components/PermissionsAccordion/helpers/filtersConfig';
import { addressTypesShape } from '../../shapes';
import getProxySponsorWarning from '../../components/util/getProxySponsorWarning';
import css from './UserForm.css';
function validate(values, props) {
const errors = {};
errors.personal = {};
if (!props) {
return errors;
}
if (!values.personal || !values.personal.lastName) {
errors.personal.lastName = <FormattedMessage id="ui-users.errors.missingRequiredField" />;
}
if (!values.username && values.creds && values.creds.password) {
errors.username = <FormattedMessage id="ui-users.errors.missingRequiredUsername" />;
}
if (!props.initialValues.id && (!values.creds || !values.creds.password) && values.username) {
errors.creds = { password: <FormattedMessage id="ui-users.errors.missingRequiredPassword" /> };
}
if (!values.patronGroup) {
errors.patronGroup = <FormattedMessage id="ui-users.errors.missingRequiredPatronGroup" />;
}
if (!values.personal || !values.personal.preferredContactTypeId) {
if (errors.personal) errors.personal.preferredContactTypeId = <FormattedMessage id="ui-users.errors.missingRequiredContactType" />;
else errors.personal = { preferredContactTypeId: <FormattedMessage id="ui-users.errors.missingRequiredContactType" /> };
}
if (values.personal && values.personal.addresses) {
errors.personal.addresses = [];
values.personal.addresses.forEach((addr) => {
const err = (!addr.addressType) ? { addressType: <FormattedMessage id="ui-users.errors.missingRequiredAddressType" /> } : {};
errors.personal.addresses.push(err);
});
}
if (values.servicePoints && values.servicePoints.length > 0 && values.preferredServicePoint === undefined) {
errors.preferredServicePoint = <FormattedMessage id="ui-users.errors.missingRequiredPreferredServicePoint" />;
}
return errors;
}
class UserForm extends React.Component {
static propTypes = {
change: PropTypes.func,
addressTypes: addressTypesShape,
formData: PropTypes.object,
handleSubmit: PropTypes.func.isRequired,
location: PropTypes.object,
history: PropTypes.object,
uniquenessValidator: PropTypes.shape({
reset: PropTypes.func.isRequired,
GET: PropTypes.func.isRequired,
}).isRequired,
match: PropTypes.object,
pristine: PropTypes.bool,
submitting: PropTypes.bool,
invalid: PropTypes.bool,
onCancel: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
initialValues: PropTypes.object.isRequired,
servicePoints: PropTypes.object,
stripes: PropTypes.object,
form: PropTypes.object, // provided by final-form
intl: PropTypes.object,
};
static defaultProps = {
pristine: false,
submitting: false,
};
constructor(props) {
super(props);
this.accordionStatusRef = React.createRef();
this.closeButton = React.createRef();
this.saveButton = React.createRef();
this.cancelButton = React.createRef();
this.keyboardCommands = [
{
name: 'save',
handler: this.handleSaveKeyCommand
},
{
name: 'ignoreEnter',
handler: this.ignoreEnterKey,
shortcut: 'enter'
},
{
name: 'cancel',
handler: this.handleCancel,
shortcut: 'esc'
},
{
name: 'expandAllSections',
handler: this.expandAllSections,
},
{
name: 'collapseAllSections',
handler: this.collapseAllSections,
}
];
this.buttonRefs = [];
this.setButtonRef = el => this.buttonRefs.push(el);
}
handleCancel = () => {
const {
match: {
params
},
location: {
search,
},
history
} = this.props;
const idParam = params.id || '';
if (idParam) {
// if an id param is present, it's an edit view, go back to the user detail page...
history.push(`/users/preview/${idParam}${search}`);
} else {
// if no id param, it's a create form, go back to the top level search view.
history.push(`/users/${search}`);
}
}
getAddFirstMenu() {
const { intl } = this.props;
return (
<PaneMenu>
<PaneHeaderIconButton
id="clickable-closenewuserdialog"
onClick={this.handleCancel}
ref={this.closeButton}
aria-label={intl.formatMessage({ id: 'ui-users.crud.closeNewUserDialog' })}
icon="times"
/>
</PaneMenu>
);
}
ignoreEnterKey = (e) => {
const allowedControls = [
this.closeButton.current,
this.saveButton.current,
this.cancelButton.current,
...this.buttonRefs,
];
if (!allowedControls.includes(e.target)) {
e.preventDefault();
}
};
handleSaveKeyCommand = (e) => {
e.preventDefault();
this.executeSave();
};
executeSave() {
const {
handleSubmit,
onSubmit,
} = this.props;
const submitter = handleSubmit(onSubmit);
submitter();
}
getPaneFooter() {
const {
pristine,
submitting,
onCancel,
} = this.props;
const disabled = pristine || submitting;
const startButton = (
<Button
data-test-user-form-cancel-button
marginBottom0
id="clickable-cancel"
buttonStyle="default mega"
buttonRef={this.cancelButton}
onClick={onCancel}
>
<FormattedMessage id="ui-users.cancel" />
</Button>
);
const endButton = (
<Button
data-test-user-form-submit-button
marginBottom0
id="clickable-save"
buttonStyle="primary mega"
type="submit"
disabled={disabled}
buttonRef={this.saveButton}
>
<FormattedMessage id="ui-users.saveAndClose" />
</Button>
);
return (
<PaneFooter
renderStart={startButton}
renderEnd={endButton}
className={css.paneFooterClass}
innerClassName={css.paneFooterContentClass}
/>
);
}
getActionMenu = ({ onToggle }) => {
const { initialValues, stripes } = this.props;
const showActionMenu = stripes.hasPerm('ui-users.patron_blocks')
|| stripes.hasPerm('ui-users.feesfines.actions.all')
|| stripes.hasPerm('ui-requests.all');
const isEditing = initialValues && initialValues.id;
if (showActionMenu && isEditing) {
return (
<>
<RequestFeeFineBlockButtons
barcode={this.props.initialValues.barcode}
onToggle={onToggle}
userId={this.props.match.params.id}
/>
</>
);
} else {
return null;
}
}
render() {
const {
initialValues,
handleSubmit,
formData,
servicePoints,
onCancel,
stripes,
form,
uniquenessValidator,
} = this.props;
const selectedPatronGroup = form.getFieldState('patronGroup')?.value;
const firstMenu = this.getAddFirstMenu();
const footer = this.getPaneFooter();
const fullName = getFullName(initialValues);
const paneTitle = initialValues.id
? <FormattedMessage id="ui-users.edit" />
: <FormattedMessage id="ui-users.crud.createUser" />;
return (
<HasCommand commands={this.keyboardCommands}>
<form
data-test-form-page
className={css.UserFormRoot}
id="form-user"
onSubmit={handleSubmit}
>
<Paneset>
<Pane
actionMenu={this.getActionMenu}
firstMenu={firstMenu}
footer={footer}
centerContent
appIcon={<AppIcon app="users" appIconKey="users" />}
paneTitle={
<span data-test-header-title>
{paneTitle}
</span>
}
onClose={onCancel}
defaultWidth="fill"
>
{fullName && (
<Headline
size="xx-large"
tag="h2"
data-test-header-title
>
{fullName}
</Headline>
)}
<AccordionStatus ref={this.accordionStatusRef}>
<Row end="xs">
<Col xs>
<ExpandAllButton />
</Col>
</Row>
<AccordionSet
initialStatus={{
editUserInfo: true,
extendedInfo: true,
contactInfo: true,
proxy: false,
permissions: false,
servicePoints: false,
customFields: true,
}}
>
<EditUserInfo
accordionId="editUserInfo"
initialValues={initialValues}
patronGroups={formData.patronGroups}
stripes={stripes}
form={form}
selectedPatronGroup={selectedPatronGroup}
uniquenessValidator={uniquenessValidator}
/>
<EditExtendedInfo
accordionId="extendedInfo"
expanded
userId={initialValues.id}
userFirstName={initialValues.personal.firstName}
userEmail={initialValues.personal.email}
username={initialValues.username}
servicePoints={servicePoints}
addressTypes={formData.addressTypes}
departments={formData.departments}
uniquenessValidator={uniquenessValidator}
/>
<EditContactInfo
accordionId="contactInfo"
addressTypes={formData.addressTypes}
preferredContactTypeId={initialValues.preferredContactTypeId}
/>
<EditCustomFieldsRecord
expanded
formName="userForm"
accordionId="customFields"
backendModuleName="users"
entityType="user"
finalFormCustomFieldsValues={form.getState().values.customFields}
fieldComponent={Field}
changeFinalFormField={form.change}
/>
{initialValues.id &&
<div>
<EditProxy
accordionId="proxy"
sponsors={initialValues.sponsors}
proxies={initialValues.proxies}
fullName={fullName}
/>
<PermissionsAccordion
initialValues={initialValues}
filtersConfig={[
permissionTypeFilterConfig,
statusFilterConfig,
]}
visibleColumns={[
'selected',
'permissionName',
'type',
'status',
]}
accordionId="permissions"
headlineContent={<FormattedMessage id="ui-users.permissions.userPermissions" />}
permToRead="perms.users.get"
permToDelete="perms.users.item.delete"
permToModify="perms.users.item.put"
formName="userForm"
permissionsField="permissions"
form={form}
setButtonRef={this.setButtonRef}
/>
<EditServicePoints
accordionId="servicePoints"
setButtonRef={this.setButtonRef}
{...this.props}
/>
</div>
}
</AccordionSet>
</AccordionStatus>
</Pane>
</Paneset>
<FormSpy
subscription={{ values: true }}
onChange={({ values }) => {
const { mutators } = form;
['sponsors', 'proxies'].forEach(namespace => {
if (values[namespace]) {
values[namespace].forEach((_, index) => {
const warning = getProxySponsorWarning(values, namespace, index);
if (warning) {
mutators.setFieldData(`${namespace}[${index}].proxy.status`, { warning });
}
});
}
});
}}
/>
</form>
</HasCommand>
);
}
}
export default stripesFinalForm({
validate,
mutators: {
setFieldData,
},
initialValuesEqual: (a, b) => isEqual(a, b),
navigationCheck: true,
enableReinitialize: true,
})(injectIntl(UserForm));
|
fields/types/date/DateFilter.js
|
lojack/keystone
|
import _ from 'underscore';
import classNames from 'classnames';
import React from 'react';
import { FormField, FormInput, FormRow, FormSelect, SegmentedControl } from 'elemental';
const TOGGLE_OPTIONS = [
{ label: 'Matches', value: false },
{ label: 'Does NOT Match', value: true }
];
const MODE_OPTIONS = [
{ label: 'On', value: 'on' },
{ label: 'After', value: 'after' },
{ label: 'Before', value: 'before' },
{ label: 'Between', value: 'between' }
];
var NumberFilter = React.createClass({
getInitialState () {
return {
modeValue: MODE_OPTIONS[0].value, // 'on'
modeLabel: MODE_OPTIONS[0].label, // 'On'
inverted: TOGGLE_OPTIONS[0].value,
value: ''
};
},
componentDidMount () {
// focus the text input
React.findDOMNode(this.refs.input).focus();
},
toggleInverted (value) {
this.setState({
inverted: value
});
},
selectMode (mode) {
// TODO: implement w/o underscore
this.setState({
modeValue: mode,
modeLabel: _.findWhere(MODE_OPTIONS, { value: mode }).label
});
// focus the text input after a mode selection is made
React.findDOMNode(this.refs.input).focus();
},
renderToggle () {
return (
<FormField>
<SegmentedControl equalWidthSegments options={TOGGLE_OPTIONS} value={this.state.inverted} onChange={this.toggleInverted} />
</FormField>
);
},
renderControls () {
let controls;
let { field } = this.props;
let { modeLabel, modeValue } = this.state;
let placeholder = field.label + ' is ' + modeLabel.toLowerCase() + '...';
if (modeValue === 'between') {
controls = (
<FormRow>
<FormField width="one-half">
<FormInput ref="input" placeholder="From" />
</FormField>
<FormField width="one-half">
<FormInput placeholder="To" />
</FormField>
</FormRow>
);
} else {
controls = (
<FormField>
<FormInput ref="input" placeholder={placeholder} />
</FormField>
);
}
return controls;
},
render () {
let { modeLabel, modeValue } = this.state;
return (
<div>
{this.renderToggle()}
<FormSelect options={MODE_OPTIONS} onChange={this.selectMode} value={modeValue} />
{this.renderControls()}
</div>
);
}
});
module.exports = NumberFilter;
|
src/svg-icons/hardware/scanner.js
|
kasra-co/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareScanner = (props) => (
<SvgIcon {...props}>
<path d="M19.8 10.7L4.2 5l-.7 1.9L17.6 12H5c-1.1 0-2 .9-2 2v4c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-5.5c0-.8-.5-1.6-1.2-1.8zM7 17H5v-2h2v2zm12 0H9v-2h10v2z"/>
</SvgIcon>
);
HardwareScanner = pure(HardwareScanner);
HardwareScanner.displayName = 'HardwareScanner';
HardwareScanner.muiName = 'SvgIcon';
export default HardwareScanner;
|
app/javascript/mastodon/features/list_editor/index.js
|
abcang/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { connect } from 'react-redux';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { injectIntl } from 'react-intl';
import { setupListEditor, clearListSuggestions, resetListEditor } from '../../actions/lists';
import Account from './components/account';
import Search from './components/search';
import EditListForm from './components/edit_list_form';
import Motion from '../ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
const mapStateToProps = state => ({
accountIds: state.getIn(['listEditor', 'accounts', 'items']),
searchAccountIds: state.getIn(['listEditor', 'suggestions', 'items']),
});
const mapDispatchToProps = dispatch => ({
onInitialize: listId => dispatch(setupListEditor(listId)),
onClear: () => dispatch(clearListSuggestions()),
onReset: () => dispatch(resetListEditor()),
});
export default @connect(mapStateToProps, mapDispatchToProps)
@injectIntl
class ListEditor extends ImmutablePureComponent {
static propTypes = {
listId: PropTypes.string.isRequired,
onClose: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
onInitialize: PropTypes.func.isRequired,
onClear: PropTypes.func.isRequired,
onReset: PropTypes.func.isRequired,
accountIds: ImmutablePropTypes.list.isRequired,
searchAccountIds: ImmutablePropTypes.list.isRequired,
};
componentDidMount () {
const { onInitialize, listId } = this.props;
onInitialize(listId);
}
componentWillUnmount () {
const { onReset } = this.props;
onReset();
}
render () {
const { accountIds, searchAccountIds, onClear } = this.props;
const showSearch = searchAccountIds.size > 0;
return (
<div className='modal-root__modal list-editor'>
<EditListForm />
<Search />
<div className='drawer__pager'>
<div className='drawer__inner list-editor__accounts'>
{accountIds.map(accountId => <Account key={accountId} accountId={accountId} added />)}
</div>
{showSearch && <div role='button' tabIndex='-1' className='drawer__backdrop' onClick={onClear} />}
<Motion defaultStyle={{ x: -100 }} style={{ x: spring(showSearch ? 0 : -100, { stiffness: 210, damping: 20 }) }}>
{({ x }) => (
<div className='drawer__inner backdrop' style={{ transform: x === 0 ? null : `translateX(${x}%)`, visibility: x === -100 ? 'hidden' : 'visible' }}>
{searchAccountIds.map(accountId => <Account key={accountId} accountId={accountId} />)}
</div>
)}
</Motion>
</div>
</div>
);
}
}
|
docs/app/Examples/modules/Rating/Types/RatingExampleStar.js
|
ben174/Semantic-UI-React
|
import React from 'react'
import { Rating } from 'semantic-ui-react'
const RatingExampleStar = () => (
<Rating icon='star' defaultRating={3} maxRating={4} />
)
export default RatingExampleStar
|
src/navigation/auth.js
|
OlivierVillequey/hackathon
|
/**
* Auth Scenes
*
* React Native Starter App
* https://github.com/mcnamee/react-native-starter-app
*/
import React from 'react';
import { Scene, ActionConst } from 'react-native-router-flux';
// Consts and Libs
import { AppConfig } from '@constants/';
// Scenes
import Authenticate from '@containers/auth/AuthenticateView';
import LoginForm from '@containers/auth/Forms/LoginContainer';
import SignUpForm from '@containers/auth/Forms/SignUpContainer';
import ResetPasswordForm from '@containers/auth/Forms/ResetPasswordContainer';
import UpdateProfileForm from '@containers/auth/Forms/UpdateProfileContainer';
import SignUpWithFacebookForm from '@containers/auth/Forms/SignUpWithFacebook'
/* Routes ==================================================================== */
const scenes = (
<Scene key={'authenticate'}>
<Scene
hideNavBar
key={'authLanding'}
component={Authenticate}
type={ActionConst.RESET}
analyticsDesc={'Authentication'}
/>
<Scene
{...AppConfig.navbarProps}
key={'login'}
title={'Login'}
clone
component={LoginForm}
analyticsDesc={'Login'}
/>
<Scene
{...AppConfig.navbarProps}
key={'signUpWithFacebook'}
title={'Sign Up With Facebook'}
clone
component={SignUpWithFacebookForm}
analyticsDesc={'Sign Up Fb'}
/>
<Scene
{...AppConfig.navbarProps}
key={'signUp'}
title={'Sign Up'}
clone
component={SignUpForm}
analyticsDesc={'Sign Up'}
/>
<Scene
{...AppConfig.navbarProps}
key={'passwordReset'}
title={'Password Reset'}
clone
component={ResetPasswordForm}
analyticsDesc={'Password Reset'}
/>
<Scene
{...AppConfig.navbarProps}
key={'updateProfile'}
title={'Update Profile'}
clone
component={UpdateProfileForm}
analyticsDesc={'Update Profile'}
/>
</Scene>
);
export default scenes;
|
src/MainComposition.js
|
tobias2801/app_gestoria
|
import React, { Component } from 'react';
import Header from './components/HeaderComponent';
import Sidebar from './components/SidebarComponent';
import Home from './components/HomeComponent';
import TypeForm from './components/forms/TypeFormComponent';
import ClientForm from './components/forms/ClientFormComponent';
import ArticleForm from './components/forms/ArticleFormComponent';
import SalesForm from './components/forms/SalesFormComponent';
export default class Main extends Component {
constructor() {
super();
this.onChangeView = this.onChangeView.bind(this);
this.state = {
view: <Home />
}
}
onChangeView(e) {
console.log(e.target.id);
let view = null;
switch(e.target.id) {
case 'home':
view = <Home />;
break
case 'new-client':
view = <ClientForm />;
break;
case 'new-article':
view = <ArticleForm />;
break;
case 'new-type':
view = <TypeForm />;
break;
case 'new-sale':
view = <SalesForm />;
break;
}
this.setState({
view
});
}
render() {
return (
<div>
<Header />
<Sidebar changeView={this.onChangeView} />
<div id="main-body">
{this.state.view}
</div>
<p id="firm">Tobías G. Schwarz ©2017</p>
</div>
);
}
}
|
react-fundamentals/es6-react-setup/Wrapper.js
|
gongmingqm10/EggHead
|
import React from 'react';
import ReactDOM from 'react-dom';
class Wrapper extends React.Component {
constructor(props) {
super(props);
}
mount() {
ReactDOM.render(<App/>, document.getElementById(('container')));
}
unmount() {
ReactDOM.unmountComponentAtNode(document.getElementById('container'));
}
render() {
return (
<div>
<button onClick={this.mount.bind(this)}>Mount</button>
<button onClick={this.unmount.bind(this)}>Unmount</button>
<div id="container"></div>
</div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
val: 0
}
this.update = this.update.bind(this);
}
componentWillMount() {
console.log('Mounting');
this.setState({
multiple: 2
})
}
componentDidMount() {
console.log('Mounted');
this.inc = setInterval(this.update, 500);
}
componentWillUnmount() {
console.log('Bye!!!');
clearInterval(this.inc);
}
update() {
this.setState({
val: this.state.val + 1
});
}
render() {
console.log('Rendering');
return (
<button onClick={this.update.bind(this)}>{this.state.val * this.state.multiple}</button>
)
}
}
export default Wrapper;
|
src/components/Proposal/Proposal.js
|
nambawan/g-old
|
import {
FormattedRelative,
FormattedMessage,
defineMessages,
} from 'react-intl';
import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import withStyles from 'isomorphic-style-loader/withStyles';
import s from './Proposal.css';
import UserThumbnail from '../UserThumbnail';
import WorkteamHeader from '../WorkteamHeader';
import { ICONS } from '../../constants';
const messages = defineMessages({
spokesman: {
id: 'spokesman',
defaultMessage: 'Spokesman',
description: 'Spokesman label',
},
});
class Proposal extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
state: PropTypes.string.isRequired,
body: PropTypes.string.isRequired,
publishedAt: PropTypes.string.isRequired,
deletedAt: PropTypes.string,
spokesman: PropTypes.shape({
thumbnail: PropTypes.string,
name: PropTypes.string,
surname: PropTypes.string,
id: PropTypes.string,
}),
workteam: PropTypes.shape({
id: PropTypes.number,
displayName: PropTypes.string,
logo: PropTypes.string,
}),
};
static defaultProps = {
spokesman: null,
deletedAt: null,
workteam: null,
};
render() {
const {
deletedAt,
title,
publishedAt,
body,
spokesman,
workteam,
} = this.props;
return (
<div className={cn(s.root, deletedAt && s.deleted)}>
<div className={s.container}>
{workteam && (
<WorkteamHeader
displayName={workteam.displayName}
id={workteam.id}
logo={workteam.logo}
/>
)}
<div className={s.headline}>{title}</div>
<div className={s.details}>
{spokesman && (
<div>
<UserThumbnail
marked
label={<FormattedMessage {...messages.spokesman} />}
user={spokesman}
/>
</div>
)}
<div className={s.date}>
<svg
version="1.1"
viewBox="0 0 24 24"
width="24px"
height="24px"
role="img"
>
<path
fill="none"
stroke="#666"
strokeWidth="2"
d={ICONS.edit}
/>
</svg>{' '}
<FormattedRelative value={publishedAt} />
</div>
</div>
<div className={s.body} dangerouslySetInnerHTML={{ __html: body }} />
</div>
</div>
);
}
}
export default withStyles(s)(Proposal);
|
app/main.js
|
ibjohansen/k5g.no
|
'use strict';
import React from 'react';
import Router, {Link, Route, DefaultRoute, NotFoundRoute} from 'react-router';
import Home from './pages/home';
import Map from './pages/map';
import Cats from './pages/cats';
require("./styles/normalize.css");
require("./styles/skeleton.css");
require("./styles/app.css");
React.initializeTouchEvents(true);
let injectTapEventPlugin = require("react-tap-event-plugin");
injectTapEventPlugin();
let routes = (
<Route path="/" handler={App}>
<DefaultRoute handler={Home}/>
<Route path="/home" handler={Home}/>
<Route path="/map" handler={Map}/>
<Route path="/cats" handler={Cats}/>
</Route>
);
var App = React.createClass({
render () {
return (
<RouteHandler/>
)
}
});
Router.run(routes, (Handler, state) => {
React.render(<Handler {...state}/>, document.querySelector('#app'));
});
|
src/utils/inputNodeCheck.js
|
manchesergit/material-ui
|
import React from 'react';
import warning from 'warning';
export const HtmlForTagName = 'htmlFor';
export const InputTypeName = 'input';
export const a11yButtonTagsToTest = [HtmlForTagName, 'aria-labelledby', 'aria-describedby'];
/*
* Check if the children have an input node.
* If there is an input node, check that it meets the a11y tag requirements :
* Must have all of the tags listed in the a11yTagsToTest array.
* If any of the tags are missing a warning will be output.
* Input : componentId - the ID of the component being checked or null.
* children - the child nodes of the component being checked or null.
* excludeTag - any tag of which the tests should be expcitly ignored.
*/
export function checkChildrenInputWitha11y(componentId, children, excludeTag) {
if (children !== null) {
// tags to test for in the children
const elementId = componentId !== null ? `Element [id: ${componentId}]:` : '';
const identity = `Material-UI: ${elementId}`;
const message =
'Buttons with a child <input> element should should contain the following property inside the input tag';
React.Children.forEach(children, (child) => {
if (child !== null) {
if (child.type === InputTypeName) {
for (let index = 0; index < a11yButtonTagsToTest.length; index++) {
const tagToTest = a11yButtonTagsToTest[index];
if (((tagToTest !== excludeTag)) && (!child.props.hasOwnProperty(tagToTest))) {
warning(false, `${identity} ${message} : '${tagToTest}'`);
}
}
}
}
});
}
}
|
blueocean-material-icons/src/js/components/svg-icons/image/filter-4.js
|
jenkinsci/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const ImageFilter4 = (props) => (
<SvgIcon {...props}>
<path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm12 10h2V5h-2v4h-2V5h-2v6h4v4zm6-14H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14z"/>
</SvgIcon>
);
ImageFilter4.displayName = 'ImageFilter4';
ImageFilter4.muiName = 'SvgIcon';
export default ImageFilter4;
|
server/sonar-web/src/main/js/apps/permissions/project/components/AllHoldersList.js
|
lbndev/sonarqube
|
/*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// @flow
import React from 'react';
import { connect } from 'react-redux';
import SearchForm from '../../shared/components/SearchForm';
import HoldersList from '../../shared/components/HoldersList';
import {
loadHolders,
grantToUser,
revokeFromUser,
grantToGroup,
revokeFromGroup,
updateQuery,
updateFilter,
selectPermission
} from '../store/actions';
import { translate } from '../../../../helpers/l10n';
import { PERMISSIONS_ORDER_BY_QUALIFIER } from '../constants';
import {
getPermissionsAppUsers,
getPermissionsAppGroups,
getPermissionsAppQuery,
getPermissionsAppFilter,
getPermissionsAppSelectedPermission
} from '../../../../store/rootReducer';
class AllHoldersList extends React.Component {
static propTypes = {
project: React.PropTypes.object.isRequired
};
componentDidMount() {
this.props.loadHolders(this.props.project.key);
}
handleSearch(query) {
this.props.onSearch(this.props.project.key, query);
}
handleFilter(filter) {
this.props.onFilter(this.props.project.key, filter);
}
handleToggleUser(user, permission) {
const hasPermission = user.permissions.includes(permission);
if (hasPermission) {
this.props.revokePermissionFromUser(this.props.project.key, user.login, permission);
} else {
this.props.grantPermissionToUser(this.props.project.key, user.login, permission);
}
}
handleToggleGroup(group, permission) {
const hasPermission = group.permissions.includes(permission);
if (hasPermission) {
this.props.revokePermissionFromGroup(this.props.project.key, group.name, permission);
} else {
this.props.grantPermissionToGroup(this.props.project.key, group.name, permission);
}
}
handleSelectPermission(permission) {
this.props.onSelectPermission(this.props.project.key, permission);
}
render() {
const order = PERMISSIONS_ORDER_BY_QUALIFIER[this.props.project.qualifier];
const permissions = order.map(p => ({
key: p,
name: translate('projects_role', p),
description: translate('projects_role', p, 'desc')
}));
return (
<HoldersList
permissions={permissions}
selectedPermission={this.props.selectedPermission}
users={this.props.users}
groups={this.props.groups}
onSelectPermission={this.handleSelectPermission.bind(this)}
onToggleUser={this.handleToggleUser.bind(this)}
onToggleGroup={this.handleToggleGroup.bind(this)}>
<SearchForm
query={this.props.query}
filter={this.props.filter}
onSearch={this.handleSearch.bind(this)}
onFilter={this.handleFilter.bind(this)}
/>
</HoldersList>
);
}
}
const mapStateToProps = state => ({
users: getPermissionsAppUsers(state),
groups: getPermissionsAppGroups(state),
query: getPermissionsAppQuery(state),
filter: getPermissionsAppFilter(state),
selectedPermission: getPermissionsAppSelectedPermission(state)
});
type OwnProps = {
project: {
organization?: string
}
};
const mapDispatchToProps = (dispatch: Function, ownProps: OwnProps) => ({
loadHolders: projectKey => dispatch(loadHolders(projectKey, ownProps.project.organization)),
onSearch: (projectKey, query) =>
dispatch(updateQuery(projectKey, query, ownProps.project.organization)),
onFilter: (projectKey, filter) =>
dispatch(updateFilter(projectKey, filter, ownProps.project.organization)),
onSelectPermission: (projectKey, permission) =>
dispatch(selectPermission(projectKey, permission, ownProps.project.organization)),
grantPermissionToUser: (projectKey, login, permission) =>
dispatch(grantToUser(projectKey, login, permission, ownProps.project.organization)),
revokePermissionFromUser: (projectKey, login, permission) =>
dispatch(revokeFromUser(projectKey, login, permission, ownProps.project.organization)),
grantPermissionToGroup: (projectKey, groupName, permission) =>
dispatch(grantToGroup(projectKey, groupName, permission, ownProps.project.organization)),
revokePermissionFromGroup: (projectKey, groupName, permission) =>
dispatch(revokeFromGroup(projectKey, groupName, permission, ownProps.project.organization))
});
export default connect(mapStateToProps, mapDispatchToProps)(AllHoldersList);
|
src/svg-icons/action/change-history.js
|
igorbt/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionChangeHistory = (props) => (
<SvgIcon {...props}>
<path d="M12 7.77L18.39 18H5.61L12 7.77M12 4L2 20h20L12 4z"/>
</SvgIcon>
);
ActionChangeHistory = pure(ActionChangeHistory);
ActionChangeHistory.displayName = 'ActionChangeHistory';
ActionChangeHistory.muiName = 'SvgIcon';
export default ActionChangeHistory;
|
src/main.js
|
raffidil/garnanain
|
/**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import localforage from 'localforage';
import 'babel-polyfill';
import 'whatwg-fetch';
import React from 'react';
import ReactDOM from 'react-dom';
import FastClick from 'fastclick';
import { Provider } from 'react-redux';
import store from './store';
import router from './router';
import history from './history';
let routes = require('./routes.json').default; // Loaded with utils/routes-loader.js
const container = document.getElementById('container');
function renderComponent(component) {
ReactDOM.render(<Provider store={store}>{component}</Provider>, container);
}
// Find and render a web page matching the current URL path,
// if such page is not found then render an error page (see routes.json, core/router.js)
function render(location) {
router.resolve(routes, location)
.then(renderComponent)
.catch(error => router.resolve(routes, { ...location, error }).then(renderComponent));
}
// Handle client-side navigation by using HTML5 History API
// For more information visit https://github.com/ReactJSTraining/history/tree/master/docs#readme
history.listen(render);
render(history.location);
// Eliminates the 300ms delay between a physical tap
// and the firing of a click event on mobile browsers
// https://github.com/ftlabs/fastclick
FastClick.attach(document.body);
// Enable Hot Module Replacement (HMR)
if (module.hot) {
module.hot.accept('./routes.json', () => {
routes = require('./routes.json').default; // eslint-disable-line global-require
render(history.location);
});
}
localforage.config({
name: 'Garnanain',
});
|
src/svg-icons/hardware/headset.js
|
andrejunges/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareHeadset = (props) => (
<SvgIcon {...props}>
<path d="M12 1c-4.97 0-9 4.03-9 9v7c0 1.66 1.34 3 3 3h3v-8H5v-2c0-3.87 3.13-7 7-7s7 3.13 7 7v2h-4v8h3c1.66 0 3-1.34 3-3v-7c0-4.97-4.03-9-9-9z"/>
</SvgIcon>
);
HardwareHeadset = pure(HardwareHeadset);
HardwareHeadset.displayName = 'HardwareHeadset';
HardwareHeadset.muiName = 'SvgIcon';
export default HardwareHeadset;
|
src/Parser/ShadowPriest/Modules/Spells/VoidformGraph.js
|
mwwscott0/WoWAnalyzer
|
import React from 'react';
import PropTypes from 'prop-types';
import ChartistGraph from 'react-chartist';
import Chartist from 'chartist';
import 'chartist-plugin-legend';
import './VoidformsTab.css';
const formatDuration = (duration) => {
const seconds = Math.floor(duration % 60);
return `${Math.floor(duration / 60)}:${seconds < 10 ? `0${seconds}` : seconds}`;
};
const MAX_MINDBENDER_MS = 21500;
// changing this value will have a large impact on webbrowser performance. About 200 seems to be best of 2 worlds.
const RESOLUTION_MS = 200;
const TIMESTAMP_ERROR_MARGIN = 500;
const NORMAL_VOIDFORM_MS_THRESHOLD = 70000;
const SURRENDER_TO_MADNESS_VOIDFORM_MS_THRESHOLD = 150000;
// current insanity formula:
// d = 6 + (2/3)*x
// where d = total drain of Insanity over 1 second
// max insanity is 10000 (100 ingame)
const INSANITY_DRAIN_INCREASE = 2 / 3 * 100; // ~66.67;
const INSANITY_DRAIN_INITIAL = 6 * 100; // 600;
const VOIDFORM_MINIMUM_INITIAL_INSANITY = 65 * 100; // 6500;
const T20_4P_DECREASE_DRAIN_MODIFIER_NORMAL = 0.9;
const T20_4P_DECREASE_DRAIN_MODIFIER_SURRENDER_TO_MADNESS = 0.95;
const VoidformGraph = ({
lingeringInsanityStacks,
mindbenderEvents,
voidTorrentEvents,
dispersionEvents,
insanityEvents,
surrenderToMadness = false,
setT20P4 = false,
fightEnd,
...voidform
}) => {
// todo: change ended to end on Voidform for consistency;
const voidFormEnd = voidform.ended === undefined ? fightEnd : voidform.ended;
const includesEndOfFight = voidform.ended === undefined || fightEnd <= voidform.ended + TIMESTAMP_ERROR_MARGIN;
const MAX_TIME_IN_VOIDFORM = surrenderToMadness ? SURRENDER_TO_MADNESS_VOIDFORM_MS_THRESHOLD : NORMAL_VOIDFORM_MS_THRESHOLD;
const labels = [];
const stacksData = [];
const insanityData = [];
const insanityGeneratedData = [];
const insanityDrain = [];
const initialInsanity = insanityEvents.length > 0 ? insanityEvents[0].classResources[0].amount - (insanityEvents[0].resourceChange * 100) - (insanityEvents[0].waste * 100) : VOIDFORM_MINIMUM_INITIAL_INSANITY;
const lingeringInsanityData = [];
const mindbenderData = [];
const voidTorrentData = [];
const dispersionData = [];
const endOfVoidformData = [];
const endData = [];
const INSANITY_DRAIN_MODIFIER = setT20P4 ?
(surrenderToMadness ?
T20_4P_DECREASE_DRAIN_MODIFIER_SURRENDER_TO_MADNESS :
T20_4P_DECREASE_DRAIN_MODIFIER_NORMAL)
: 1;
const INSANITY_DRAIN_START = INSANITY_DRAIN_INITIAL * INSANITY_DRAIN_MODIFIER;
const INSANITY_DRAIN_INCREASE_BY_SECOND = Math.round(INSANITY_DRAIN_INCREASE * INSANITY_DRAIN_MODIFIER);
const atLabel = timestamp => Math.floor((timestamp - voidform.start) / RESOLUTION_MS);
const voidFormIsOver = i => voidform.start + i * RESOLUTION_MS >= voidform.ended;
const fillData = (array, eventStart, eventEnd, data = false) => {
const amountOfSteps = Math.round((eventEnd - eventStart) / RESOLUTION_MS);
const startStep = atLabel(eventStart);
for (let i = 0; i < amountOfSteps; i += 1) {
if (eventStart + i * RESOLUTION_MS >= voidform.ended) break;
array[startStep + i] = data || stacksData[startStep + i];
}
};
const steps = MAX_TIME_IN_VOIDFORM / RESOLUTION_MS;
for (let i = 0; i < steps; i += 1) {
labels[i] = i;
stacksData[i] = null;
lingeringInsanityData[i] = null;
insanityData[i] = null;
insanityGeneratedData[i] = null;
mindbenderData[i] = null;
voidTorrentData[i] = null;
dispersionData[i] = null;
endData[i] = null;
endOfVoidformData[i] = null;
}
voidform.stacks.forEach(({ stack, timestamp }) => {
fillData(stacksData, timestamp, timestamp + 1000, stack);
});
// fill in dispersion gaps & 100s+ voidforms:
for (let i = 0; i <= steps; i += 1) {
if (stacksData[i] === null && (i * RESOLUTION_MS) + voidform.start < voidform.ended) stacksData[i] = stacksData[i - 1];
}
endOfVoidformData[atLabel(voidform.ended) + 1] = 100;
endOfVoidformData[atLabel(voidform.ended)] = 100;
if (lingeringInsanityStacks.length > 0) lingeringInsanityData[0] = lingeringInsanityStacks[0].stack + 2;
lingeringInsanityStacks.forEach(lingering => lingeringInsanityData[atLabel(lingering.timestamp)] = lingering.stack);
dispersionEvents.filter(dispersion => dispersion.start >= voidform.start && dispersion.end <= voidFormEnd + TIMESTAMP_ERROR_MARGIN).forEach(dispersion => fillData(dispersionData, dispersion.start, dispersion.end));
mindbenderEvents.filter(mindbender => mindbender.start >= voidform.start && mindbender.end <= voidFormEnd + MAX_MINDBENDER_MS).forEach(mindbender => fillData(mindbenderData, mindbender.start, mindbender.end));
voidTorrentEvents.filter(voidTorrent => voidTorrent.start >= voidform.start && voidTorrent.end <= voidFormEnd + TIMESTAMP_ERROR_MARGIN).forEach(voidTorrent => fillData(voidTorrentData, voidTorrent.start, voidTorrent.end));
let currentDrain = INSANITY_DRAIN_START;
let lastestDrainIncrease = 0;
for (let i = 0; i < steps; i += 1) {
// set drain to 0 if voidform ended:
if (voidFormIsOver(i)) {
currentDrain = 0;
break;
}
// dont increase if dispersion/voidtorrent is active:
if (dispersionData[i] === null && voidTorrentData[i] === null) {
lastestDrainIncrease += 1;
// only increase drain every second:
if (lastestDrainIncrease % (1000 / RESOLUTION_MS) === 0) {
currentDrain += INSANITY_DRAIN_INCREASE_BY_SECOND;
}
}
insanityDrain[i] = currentDrain;
}
insanityData[0] = initialInsanity;
insanityEvents.forEach(event => insanityData[atLabel(event.timestamp)] = event.classResources[0].amount);
let latestInsanityDataAt = 0;
for (let i = 0; i < steps; i += 1) {
if (insanityData[i] === null) {
insanityData[i] = insanityData[latestInsanityDataAt];
for (let j = latestInsanityDataAt; j <= i; j += 1) {
if (dispersionData[j] === null && voidTorrentData[j] === null) { insanityData[i] -= insanityDrain[j] / (1000 / RESOLUTION_MS); }
}
if (insanityData[i] < 0) insanityData[i] = 0;
} else {
latestInsanityDataAt = i;
}
}
let legends = {
classNames: [
'stacks',
'insanity',
// 'insanityDrain',
'voidtorrent',
'mindbender',
'dispersion',
'endOfVoidform',
],
};
let chartData = {
labels,
series: [
{
className: 'stacks',
name: 'Stacks',
data: Object.keys(stacksData).map(key => stacksData[key]).slice(0, steps),
},
{
className: 'insanity',
name: 'Insanity',
data: Object.keys(insanityData).map(key => insanityData[key] / 100).slice(0, steps),
},
{
className: 'voidtorrent',
name: 'Void Torrent',
data: Object.keys(voidTorrentData).map(key => voidTorrentData[key]).slice(0, steps),
},
// {
// className: 'insanityDrain',
// name: 'InsanityDrain',
// data: Object.keys(insanityDrain).map(key => insanityDrain[key]/100).slice(0, steps),
// },
{
className: 'mindbender',
name: 'Mindbender',
data: Object.keys(mindbenderData).map(key => mindbenderData[key]).slice(0, steps),
},
{
className: 'dispersion',
name: 'Dispersion',
data: Object.keys(dispersionData).map(key => dispersionData[key]).slice(0, steps),
},
{
className: 'endOfVoidform',
name: 'End of Voidform',
data: Object.keys(endOfVoidformData).map(key => endOfVoidformData[key]).slice(0, steps),
},
],
};
if (lingeringInsanityStacks.length > 0) {
chartData = {
...chartData,
series: [
{
className: 'lingeringInsanity',
name: 'Lingering Insanity',
data: Object.keys(lingeringInsanityData).map(key => lingeringInsanityData[key]).slice(0, steps),
},
...chartData.series,
],
};
legends = {
...legends,
classNames: [
'lingeringInsanity',
...legends.classNames,
],
};
}
if (includesEndOfFight) {
const fightEndedAtSecond = atLabel(fightEnd);
endData[fightEndedAtSecond - 1] = 100;
endData[fightEndedAtSecond] = 100;
chartData = {
...chartData,
series: [
...chartData.series,
{
className: 'endOfFight',
name: 'End of Fight',
data: Object.keys(endData).map(key => endData[key]).slice(0, steps),
},
],
};
legends = {
...legends,
classNames: [
...legends.classNames,
'endOfFight',
],
};
}
return (<ChartistGraph
data={chartData}
options={{
low: 0,
high: 100,
series: {
Stacks: {
lineSmooth: Chartist.Interpolation.none({
fillHoles: true,
}),
showPoint: false,
},
// 'insanityDrain': {
// lineSmooth: Chartist.Interpolation.none({
// fillHoles: true,
// }),
// showPoint: false,
// show: false,
// },
Insanity: {
lineSmooth: Chartist.Interpolation.none({
fillHoles: true,
}),
showPoint: false,
},
Mindbender: {
showArea: true,
lineSmooth: Chartist.Interpolation.none({
fillHoles: true,
}),
},
'Void Torrent': {
showArea: true,
},
Dispersion: {
showArea: true,
// lineSmooth: Chartist.Interpolation.step({
// fillHoles: true,
// }),
},
'Lingering Insanity': {
showArea: true,
lineSmooth: Chartist.Interpolation.none({
fillHoles: true,
}),
},
'End of Fight': {
showArea: true,
},
'End of Voidform': {
showArea: true,
},
},
fullWidth: true,
height: '200px',
axisX: {
labelInterpolationFnc: function skipLabels(ms) {
const everySecond = surrenderToMadness ? 10 : 5;
return (ms * (RESOLUTION_MS / 1000)) % everySecond === 0 ? formatDuration(ms * (RESOLUTION_MS / 1000)) : null;
},
offset: 30,
},
axisY: {
onlyInteger: true,
offset: 50,
labelInterpolationFnc: function skipLabels(numberOfStacks) {
return numberOfStacks;
},
},
plugins: [
Chartist.plugins.legend(legends),
],
}}
type="Line"
/>);
};
VoidformGraph.propTypes = {
fightEnd: PropTypes.number,
lingeringInsanityStacks: PropTypes.array,
insanityEvents: PropTypes.array,
mindbenderEvents: PropTypes.array,
voidTorrentEvents: PropTypes.array,
dispersionEvents: PropTypes.array,
surrenderToMadness: PropTypes.bool,
setT20P4: PropTypes.bool.isRequired,
};
export default VoidformGraph;
|
src/decorators/withViewport.js
|
thethirddan/pocket_axe
|
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react'; // eslint-disable-line no-unused-vars
import EventEmitter from 'eventemitter3';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
let EE;
let viewport = {width: 1366, height: 768}; // Default size for server-side rendering
const RESIZE_EVENT = 'resize';
function handleWindowResize() {
if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) {
viewport = {width: window.innerWidth, height: window.innerHeight};
EE.emit(RESIZE_EVENT, viewport);
}
}
function withViewport(ComposedComponent) {
return class WithViewport extends Component {
constructor() {
super();
this.state = {
viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport
};
}
componentDidMount() {
if (!EE) {
EE = new EventEmitter();
window.addEventListener('resize', handleWindowResize);
window.addEventListener('orientationchange', handleWindowResize);
}
EE.on(RESIZE_EVENT, this.handleResize, this);
}
componentWillUnmount() {
EE.removeListener(RESIZE_EVENT, this.handleResize, this);
if (!EE.listeners(RESIZE_EVENT, true)) {
window.removeEventListener('resize', handleWindowResize);
window.removeEventListener('orientationchange', handleWindowResize);
EE = null;
}
}
render() {
return <ComposedComponent {...this.props} viewport={this.state.viewport}/>;
}
handleResize(value) {
this.setState({viewport: value});
}
};
}
export default withViewport;
|
src/JSONArrayNode.js
|
chibicode/react-json-tree
|
import React from 'react';
import PropTypes from 'prop-types';
import JSONNestedNode from './JSONNestedNode';
// Returns the "n Items" string for this node,
// generating and caching it if it hasn't been created yet.
function createItemString(data) {
return `${data.length} ${data.length !== 1 ? 'items' : 'item'}`;
}
// Configures <JSONNestedNode> to render an Array
const JSONArrayNode = ({ data, ...props }) => (
<JSONNestedNode
{...props}
data={data}
nodeType="Array"
nodeTypeIndicator="[]"
createItemString={createItemString}
expandable={data.length > 0}
/>
);
JSONArrayNode.propTypes = {
data: PropTypes.array
};
export default JSONArrayNode;
|
src/js/components/icons/base/AccessWheelchair.js
|
kylebyerly-hp/grommet
|
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-access-wheelchair`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'access-wheelchair');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fillRule="evenodd" d="M8.05024041,4.27066668 C9.13670406,4.17035941 9.98081518,3.2343354 9.98081518,2.13951989 C9.98081517,0.961122081 9.01969309,0 7.84129528,0 C6.66289747,0 5.70181789,0.961122081 5.70181789,2.13951989 C5.70181789,2.49888341 5.80208265,2.86659878 5.96924725,3.17582992 L6.73158244,13.9028415 L14.5830059,13.9049667 L17.8033365,21.4503679 L22.0313726,19.7922379 L21.3766552,18.233225 L19.0104664,19.0873668 L15.8946083,11.8938486 L8.59449231,11.9428971 L8.49427005,10.5844138 L13.7789751,10.5865177 L13.7789751,8.5764834 L8.29267796,8.57433699 L8.05024041,4.27066668 L8.05024041,4.27066668 Z M15.9467171,19.6546554 C14.6215561,22.2742051 11.8479328,24 8.88942116,24 C4.54407658,24 1,20.4559234 1,16.1105788 C1,13.0595805 2.84909637,10.224349 5.60831112,8.96751171 L5.78686655,11.2976367 C4.1548759,12.3260199 3.14882807,14.1815767 3.14882807,16.12656 C3.14882807,19.2788007 5.71979669,21.8497268 8.8719949,21.8497268 C11.7559137,21.8497268 14.2150992,19.6365066 14.5504485,16.7972585 L15.9467171,19.6546554 L15.9467171,19.6546554 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'AccessWheelchair';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
src/svg-icons/image/camera-roll.js
|
andrejunges/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCameraRoll = (props) => (
<SvgIcon {...props}>
<path d="M14 5c0-1.1-.9-2-2-2h-1V2c0-.55-.45-1-1-1H6c-.55 0-1 .45-1 1v1H4c-1.1 0-2 .9-2 2v15c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2h8V5h-8zm-2 13h-2v-2h2v2zm0-9h-2V7h2v2zm4 9h-2v-2h2v2zm0-9h-2V7h2v2zm4 9h-2v-2h2v2zm0-9h-2V7h2v2z"/>
</SvgIcon>
);
ImageCameraRoll = pure(ImageCameraRoll);
ImageCameraRoll.displayName = 'ImageCameraRoll';
ImageCameraRoll.muiName = 'SvgIcon';
export default ImageCameraRoll;
|
src/Dialog/Backdrop.js
|
gutenye/react-mc
|
// @flow
import React from 'react'
import cx from 'classnames'
import type { PropsC } from '../types'
class Backdrop extends React.Component {
props: PropsC
static defaultProps = {
component: 'div',
}
static displayName = 'Dialog.Backdrop'
render() {
const { component: Component, className, ...rest } = this.props
const rootClassName = cx('mdc-dialog__backdrop', className)
return <Component className={rootClassName} {...rest} />
}
}
export default Backdrop
|
src/UI/Keyboard.js
|
alex-wilmer/synth-starter
|
import React from 'react'
import { connect } from 'react-redux'
import { toFreq } from 'tonal-freq'
let Keyboard = ({ dispatch, octave }) => {
return (
<ul
className="piano"
onMouseUp={() => dispatch({ type: `CLEAR_KEYS` })}
>
<li
className="white"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`C` + octave) })}
/>
<li
className="black"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`C#` + octave) })}
/>
<li
className="white"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`D` + octave) })}
/>
<li
className="black"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`D#` + octave) })}
/>
<li
className="white"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`E` + octave) })}
/>
<li
className="white"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`F` + octave) })}
/>
<li
className="black"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`F#` + octave) })}
/>
<li
className="white"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`G` + octave) })}
/>
<li
className="black"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`G#` + octave) })}
/>
<li
className="white"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`A` + octave) })}
/>
<li
className="black"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`A#` + octave) })}
/>
<li
className="white"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`B` + octave) })}
/>
<li
className="white"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`C` + (octave + 1)) })}
/>
<li
className="black"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`C#` + (octave + 1)) })}
/>
<li
className="white"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`D` + (octave + 1)) })}
/>
<li
className="black"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`D#` + (octave + 1)) })}
/>
<li
className="white"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`E` + (octave + 1)) })}
/>
<li
className="white"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`F` + (octave + 1)) })}
/>
<li
className="black"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`F#` + (octave + 1)) })}
/>
<li
className="white"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`G` + (octave + 1)) })}
/>
<li
className="black"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`G#` + (octave + 1)) })}
/>
<li
className="white"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`A` + (octave + 1)) })}
/>
<li
className="black"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`A#` + (octave + 1)) })}
/>
<li
className="white"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`B` + (octave + 1)) })}
/>
<li
className="white"
onMouseDown={() => dispatch({ type: `PLAY_KEY`, key: toFreq(`C` + (octave + 2)) })}
/>
</ul>
)
}
export default connect(state => ({ octave: state.octave }))(Keyboard)
|
docs/app/Examples/views/Statistic/Content/index.js
|
aabustamante/Semantic-UI-React
|
import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const Content = () => (
<ExampleSection title='Content'>
<ComponentExample
title='Value'
description='A statistic can contain a numeric, icon, image, or text value.'
examplePath='views/Statistic/Content/StatisticExampleValues'
/>
<ComponentExample examplePath='views/Statistic/Content/StatisticExampleProps' />
<ComponentExample
title='Label'
description='A statistic can contain a label to help provide context for the presented value.'
examplePath='views/Statistic/Content/StatisticExampleLabels'
/>
</ExampleSection>
)
export default Content
|
docs/app/Examples/collections/Grid/Variations/GridExampleRelaxed.js
|
ben174/Semantic-UI-React
|
import React from 'react'
import { Grid, Image } from 'semantic-ui-react'
const GridExampleRelaxed = () => (
<Grid relaxed columns={4}>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/image.png' />
</Grid.Column>
</Grid>
)
export default GridExampleRelaxed
|
src/js/components/app.js
|
Sinkler/italian-verbs-trainer
|
import React from 'react';
import Pronouns from '../pronouns';
import TensesList from '../tenses';
import Verbs from '../verbs';
import Form from '../containers/form'
import Counts from '../containers/counts'
import Footer from '../containers/footer'
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
tenses: TensesList,
counts: [0, 0]
};
}
//noinspection JSMethodCanBeStatic
componentWillMount() {
var hash = window.location.hash;
if (hash == '#swadesh') {
Verbs.verbs = Verbs.verbs.filter(item => item.is_swadesh);
} else if (hash == '#short') {
Verbs.verbs = Verbs.verbs_short;
}
}
updateForm(is_right) {
var counts = this.state.counts;
//noinspection JSCheckFunctionSignatures
this.setState({counts: [
is_right ? counts[0] + 1 : counts[0],
is_right ? counts[1] : counts[1] + 1
]});
}
updateTenses(id, is_checked) {
//noinspection JSCheckFunctionSignatures
this.setState({
tenses: this.state.tenses.map(item => {
if (item.id == id) {
item.active = is_checked;
}
return item;
})
});
}
render() {
var flag;
try {
/* global twemoji */
flag = twemoji.parse('🇮🇹', {size: 32});
} catch (e) {
flag = '';
}
//noinspection CheckTagEmptyBody,HtmlUnknownAttribute
return (
<div className="row">
<div className="small-12 large-7 large-centered columns">
<div className="text-center">
<h1><span dangerouslySetInnerHTML={{__html: flag}}></span> Italian Verbs Trainer</h1>
</div>
<Form
pronouns={Pronouns.list}
exceptions={Pronouns.exceptions}
verbs={Verbs.verbs}
translations={Verbs.translations}
tenses={this.state.tenses}
update={this.updateForm.bind(this)}/>
<Counts
counts={this.state.counts}/>
<Footer
tenses={this.state.tenses}
update={this.updateTenses.bind(this)}/>
</div>
</div>
);
}
}
export default App;
|
docs/src/app/components/pages/components/FontIcon/Page.js
|
barakmitz/material-ui
|
import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import iconCode from '!raw!material-ui/FontIcon/FontIcon';
import iconReadmeText from './README';
import IconExampleSimple from './ExampleSimple';
import iconExampleSimpleCode from '!raw!./ExampleSimple';
import IconExampleIcons from './ExampleIcons';
import iconExampleIconsCode from '!raw!./ExampleIcons';
const descriptions = {
custom: 'This example uses a custom font (not part of Material-UI). The `className` defines the specific ' +
'icon. The third example has a `hoverColor` defined.',
public: 'This example uses the [Material icons font]' +
'(http://google.github.io/material-design-icons/#icon-font-for-the-web), referenced in the `<head>` of the docs ' +
'site index page. The `className` defines the font, and the `IconFont` tag content defines the specific icon.',
};
const FontIconPage = () => (
<div>
<Title render={(previousTitle) => `Font Icon - ${previousTitle}`} />
<MarkdownElement text={iconReadmeText} />
<CodeExample
title="Custom icon font"
description={descriptions.custom}
code={iconExampleSimpleCode}
>
<IconExampleSimple />
</CodeExample>
<CodeExample
title="Public icon font"
description={descriptions.public}
code={iconExampleIconsCode}
>
<IconExampleIcons />
</CodeExample>
<PropTypeDescription code={iconCode} />
</div>
);
export default FontIconPage;
|
src/svg-icons/editor/vertical-align-top.js
|
igorbt/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorVerticalAlignTop = (props) => (
<SvgIcon {...props}>
<path d="M8 11h3v10h2V11h3l-4-4-4 4zM4 3v2h16V3H4z"/>
</SvgIcon>
);
EditorVerticalAlignTop = pure(EditorVerticalAlignTop);
EditorVerticalAlignTop.displayName = 'EditorVerticalAlignTop';
EditorVerticalAlignTop.muiName = 'SvgIcon';
export default EditorVerticalAlignTop;
|
assets/js/tests/Test.js
|
KiranJKurian/Election-Data-Exploration
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Card, CardText, CardTitle, CardActions } from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import tests from '../tests/tests';
const Test = (props) => {
tests();
return (
<div>
<Card style={{ margin: '1em' }}>
<CardTitle>Tests</CardTitle>
<CardActions>
<FlatButton onClick={tests} label="Test" />
</CardActions>
</Card>
</div>
);
}
export default Test;
|
source/components/Affiliation.js
|
sgmap/cout-embauche
|
import React from 'react'
import './Affiliation.css'
export default () =>
<section id="affiliation">
<a href="https://openfisca.fr?utm_source=affiliation&utm_campaign=widget_embauche" target="_blank">
<img alt="OpenFisca" src="https://www.openfisca.fr/hotlinks/logo-openfisca.svg" />
</a>
<a href="https://beta.gouv.fr" target="_blank">
<img id="logo-SGMAP" alt="Secrétariat Général pour la Modernisation de l'Action Publique" src="https://embauche.beta.gouv.fr/dist/images/marianne.svg" />
</a>
<a id="affiliation-contact" href="mailto:contact@embauche.beta.gouv.fr?subject=A propos du simulateur d'embauche">contact</a>
</section>
|
src/clock.js
|
alecpblack/react-product-list
|
import React, { Component } from 'react';
class Clock extends Component {
constructor(props) {
super(props);
var now = new Date();
this.state = {
now: now,
partOfDay: this.getGreeting(now)
};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(), 1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
this.timerID = null;
}
getGreeting(date) {
var currentHour = date.getHours();
return currentHour < 12
? 'Good morning'
: currentHour < 18
? 'Good afternoon'
: 'Good evening';
}
tick() {
var now = new Date();
this.setState({
now: now,
partOfDay: this.getGreeting(now)
});
}
render() {
return (
<h3>{this.state.partOfDay}. The time is {this.state.now.toLocaleTimeString()}</h3>
);
};
}
export default Clock;
|
app/javascript/mastodon/components/short_number.js
|
ikuradon/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import { toShortNumber, pluralReady, DECIMAL_UNITS } from '../utils/numbers';
import { FormattedMessage, FormattedNumber } from 'react-intl';
// @ts-check
/**
* @callback ShortNumberRenderer
* @param {JSX.Element} displayNumber Number to display
* @param {number} pluralReady Number used for pluralization
* @returns {JSX.Element} Final render of number
*/
/**
* @typedef {object} ShortNumberProps
* @property {number} value Number to display in short variant
* @property {ShortNumberRenderer} [renderer]
* Custom renderer for numbers, provided as a prop. If another renderer
* passed as a child of this component, this prop won't be used.
* @property {ShortNumberRenderer} [children]
* Custom renderer for numbers, provided as a child. If another renderer
* passed as a prop of this component, this one will be used instead.
*/
/**
* Component that renders short big number to a shorter version
*
* @param {ShortNumberProps} param0 Props for the component
* @returns {JSX.Element} Rendered number
*/
function ShortNumber({ value, renderer, children }) {
const shortNumber = toShortNumber(value);
const [, division] = shortNumber;
// eslint-disable-next-line eqeqeq
if (children != null && renderer != null) {
console.warn('Both renderer prop and renderer as a child provided. This is a mistake and you really should fix that. Only renderer passed as a child will be used.');
}
// eslint-disable-next-line eqeqeq
const customRenderer = children != null ? children : renderer;
const displayNumber = <ShortNumberCounter value={shortNumber} />;
// eslint-disable-next-line eqeqeq
return customRenderer != null
? customRenderer(displayNumber, pluralReady(value, division))
: displayNumber;
}
ShortNumber.propTypes = {
value: PropTypes.number.isRequired,
renderer: PropTypes.func,
children: PropTypes.func,
};
/**
* @typedef {object} ShortNumberCounterProps
* @property {import('../utils/number').ShortNumber} value Short number
*/
/**
* Renders short number into corresponding localizable react fragment
*
* @param {ShortNumberCounterProps} param0 Props for the component
* @returns {JSX.Element} FormattedMessage ready to be embedded in code
*/
function ShortNumberCounter({ value }) {
const [rawNumber, unit, maxFractionDigits = 0] = value;
const count = (
<FormattedNumber
value={rawNumber}
maximumFractionDigits={maxFractionDigits}
/>
);
let values = { count, rawNumber };
switch (unit) {
case DECIMAL_UNITS.THOUSAND: {
return (
<FormattedMessage
id='units.short.thousand'
defaultMessage='{count}K'
values={values}
/>
);
}
case DECIMAL_UNITS.MILLION: {
return (
<FormattedMessage
id='units.short.million'
defaultMessage='{count}M'
values={values}
/>
);
}
case DECIMAL_UNITS.BILLION: {
return (
<FormattedMessage
id='units.short.billion'
defaultMessage='{count}B'
values={values}
/>
);
}
// Not sure if we should go farther - @Sasha-Sorokin
default: return count;
}
}
ShortNumberCounter.propTypes = {
value: PropTypes.arrayOf(PropTypes.number),
};
export default React.memo(ShortNumber);
|
src/components/remote/controls.js
|
scholtzm/arnold
|
import React, { Component } from 'react';
import { Grid, Container, Button, Header } from 'semantic-ui-react';
import ActionButton from '../../components/misc/action-button.js';
import input from '../../rpc/api/input.js';
import videoLibrary from '../../rpc/api/video-library.js';
import audioLibrary from '../../rpc/api/audio-library.js';
import player from '../../rpc/api/player.js';
import application from '../../rpc/api/application.js';
class Controls extends Component {
render() {
return (
<Container text>
<Grid>
<Grid.Row columns={3} textAlign='center'>
<Grid.Column>
<div><ActionButton icon='arrow up' asyncAction={input.up} /></div>
<div style={{margin: '5px 0'}}>
<ActionButton icon='arrow left' asyncAction={input.left} />
<ActionButton icon='selected radio' color='green' asyncAction={input.select} />
<ActionButton icon='arrow right' asyncAction={input.right} />
</div>
<div><ActionButton icon='arrow down' asyncAction={input.down} /></div>
<div style={{paddingTop: '10px'}}>
<ActionButton content='Home' asyncAction={input.home} />
{' '}
<ActionButton content='Back' asyncAction={input.back} />
</div>
</Grid.Column>
<Grid.Column>
<Header as='h5'>Playback</Header>
<div style={{paddingTop: '5px'}}>
<Button.Group color='blue'>
<ActionButton icon='play' asyncAction={player.playPause} />
<ActionButton icon='pause' asyncAction={player.playPause} />
<ActionButton icon='stop' asyncAction={player.stop} />
</Button.Group>
</div>
<div style={{paddingTop: '5px'}}>
<Button.Group basic>
<ActionButton icon='volume down' asyncAction={application.setVolume} asyncActionArguments={['decrement']} />
<ActionButton icon='volume off' asyncAction={application.setMute} />
<ActionButton icon='volume up' asyncAction={application.setVolume} asyncActionArguments={['increment']} />
</Button.Group>
</div>
</Grid.Column>
<Grid.Column>
<Header as='h5'>Video Library</Header>
<div style={{paddingTop: '5px'}}>
<ActionButton content='Scan' asyncAction={videoLibrary.scan} />
{' '}
<ActionButton content='Clean' asyncAction={videoLibrary.clean} />
</div>
<Header as='h5'>Audio Library</Header>
<div style={{paddingTop: '5px'}}>
<ActionButton content='Scan' asyncAction={audioLibrary.scan} />
{' '}
<ActionButton content='Clean' asyncAction={audioLibrary.clean} />
</div>
</Grid.Column>
</Grid.Row>
</Grid>
</Container>
);
}
}
export default Controls;
|
src/svg-icons/maps/local-movies.js
|
kittyjumbalaya/material-components-web
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalMovies = (props) => (
<SvgIcon {...props}>
<path d="M18 3v2h-2V3H8v2H6V3H4v18h2v-2h2v2h8v-2h2v2h2V3h-2zM8 17H6v-2h2v2zm0-4H6v-2h2v2zm0-4H6V7h2v2zm10 8h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V7h2v2z"/>
</SvgIcon>
);
MapsLocalMovies = pure(MapsLocalMovies);
MapsLocalMovies.displayName = 'MapsLocalMovies';
MapsLocalMovies.muiName = 'SvgIcon';
export default MapsLocalMovies;
|
src/app.js
|
aeldar/yet-another-react-bootstrap
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from 'containers/App/App.jsx';
import 'static/styles/base.css';
import 'normalize.css';
ReactDOM.render(<App />, document.getElementById('root'));
|
js/ClientApp.js
|
steve-chen-nyc/fem_react
|
import React from 'react'
import { render } from 'react-dom'
import { BrowserRouter, Match } from 'react-router'
import { Provider } from 'react-redux'
import store from './store'
import Landing from './Landing'
import Search from './Search'
import Details from './Details'
import preload from '../public/data.json'
import '../public/normalize.css'
import '../public/style.css'
const App = React.createClass({
render () {
return (
<BrowserRouter>
<Provider store={store}>
<div className='app'>
<Match exactly pattern='/' component={Landing} />
<Match
pattern='/search'
component={(props) => <Search shows={preload.shows}
{...props} />}
/>
<Match
pattern='/details/:id'
component={(props) => {
const shows = preload.shows.filter((show) =>
props.params.id === show.imdbID)
return <Details show={shows[0]} {...props} />
}}
/>
</div>
</Provider>
</BrowserRouter>
)
}
})
render(<App />, document.getElementById('app'))
|
static/src/components/Footer/index.js
|
agelarry/online_quiz
|
import React from 'react';
/* component styles */
import { styles } from './styles.scss';
export const Footer = () =>
<footer className={`${styles}`}>
<div className="container">
<div className="row">
<div className="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<p>© LC 2017</p>
</div>
</div>
</div>
</footer>;
|
app/containers/NotFoundPage/index.js
|
dmitrykrylov/my-test-store
|
/**
* NotFoundPage
*
* This is the page we show when the user visits a url that doesn't have a route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<h1>
Not Found
</h1>
);
}
}
|
docs/app/Examples/elements/Input/Variations/InputExampleActionLabeledButton.js
|
Rohanhacker/Semantic-UI-React
|
import React from 'react'
import { Input } from 'semantic-ui-react'
const InputExampleActionLabeledButton = () => (
<Input
action={{ color: 'teal', labelPosition: 'right', icon: 'copy', content: 'Copy' }}
defaultValue='http://ww.short.url/c0opq'
/>
)
export default InputExampleActionLabeledButton
|
docs/client/components/pages/Undo/CustomUndoEditor/index.js
|
draft-js-plugins/draft-js-plugins-v1
|
import React, { Component } from 'react';
import { EditorState } from 'draft-js';
import Editor from 'draft-js-plugins-editor';
import createUndoPlugin from 'draft-js-undo-plugin';
import editorStyles from './editorStyles.css';
import buttonStyles from './buttonStyles.css';
const theme = {
undo: buttonStyles.button,
redo: buttonStyles.button,
};
const undoPlugin = createUndoPlugin({
undoContent: 'Undo',
redoContent: 'Redo',
theme,
});
const { UndoButton, RedoButton } = undoPlugin;
const plugins = [undoPlugin];
export default class CustomUndoEditor extends Component {
state = {
editorState: EditorState.createEmpty(),
};
onChange = (editorState) => {
this.setState({
editorState,
});
};
focus = () => {
this.refs.editor.focus();
};
render() {
return (
<div>
<div className={ editorStyles.editor } onClick={ this.focus }>
<Editor
editorState={this.state.editorState}
onChange={this.onChange}
plugins={ plugins }
ref="editor"
/>
</div>
<div className={ editorStyles.options }>
<UndoButton />
<RedoButton />
</div>
</div>
);
}
}
|
examples/redirect-using-index/app.js
|
Dodelkin/react-router
|
import React from 'react'
import { createHistory, useBasename } from 'history'
import { Router, Route, IndexRoute, Link } from 'react-router'
const history = useBasename(createHistory)({
basename: '/redirect-using-index'
})
class App extends React.Component {
render() {
return (
<div>
{this.props.children}
</div>
)
}
}
class Index extends React.Component {
render() {
return (
<div>
<h1>You should not see this.</h1>
{this.props.children}
</div>
)
}
}
class Child extends React.Component {
render() {
return (
<div>
<h2>Redirected to "/child"</h2>
<Link to="/">Try going to "/"</Link>
</div>
)
}
}
function redirectToChild(location, replaceState) {
replaceState(null, '/child')
}
React.render((
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Index} onEnter={redirectToChild} />
<Route path="/child" component={Child} />
</Route>
</Router>
), document.getElementById('example'))
|
react/test/testHelper.js
|
koscim/beer-art-reviews
|
import { shallow, mount } from 'enzyme';
import jasmineEnzyme from 'jasmine-enzyme';
import React from 'react';
import $ from 'jquery';
import 'jasmine-ajax';
Object.assign(global, {
jasmineEnzyme,
mount,
React,
shallow,
$
});
beforeEach(() => {
jasmineEnzyme();
});
// function to require all modules for a given context
let requireAll = requireContext => {
requireContext.keys().forEach(requireContext);
};
// require all js files except testHelper.js in the test folder
requireAll(require.context('./', true, /^((?!testHelper).)*\.jsx?$/));
// require all js files except main.js in the src folder
requireAll(require.context('../src/', true, /^((?!main).)*\.jsx?$/));
// output to the browser's console when the tests run
console.info(`TESTS RAN AT ${new Date().toLocaleTimeString()}`);
|
src/parser/monk/mistweaver/modules/spells/Vivify.js
|
FaideWW/WoWAnalyzer
|
// Based on Clearcasting Implementation done by @Blazyb
import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';
import { formatNumber } from 'common/format';
import Analyzer from 'parser/core/Analyzer';
import Combatants from 'parser/shared/modules/Combatants';
import AbilityTracker from 'parser/shared/modules/AbilityTracker';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
const debug = false;
class Vivify extends Analyzer {
static dependencies = {
abilityTracker: AbilityTracker,
combatants: Combatants,
};
remVivifyHealCount = 0;
remVivifyHealing = 0;
gustsHealing = 0;
lastCastTarget = null;
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (SPELLS.VIVIFY.id !== spellId) {
return;
}
this.lastCastTarget = event.targetID;
}
on_byPlayer_heal(event) {
const spellId = event.ability.guid;
if ((spellId === SPELLS.GUSTS_OF_MISTS.id) && (this.lastCastTarget === event.targetID)) {
this.gustsHealing += (event.amount || 0) + (event.absorbed || 0);
}
if ((spellId === SPELLS.VIVIFY.id) && (this.lastCastTarget !== event.targetID)) {
this.remVivifyHealCount += 1;
this.remVivifyHealing += (event.amount || 0 ) + (event.absorbed || 0);
}
}
get averageRemPerVivify() {
const vivifyCasts = this.abilityTracker.getAbility(SPELLS.VIVIFY.id).casts || 0;
return this.remVivifyHealCount / vivifyCasts || 0;
}
get suggestionThresholds() {
return {
actual: this.averageRemPerVivify,
isLessThan: {
minor: 1.5,
average: 1,
major: 0.5,
},
style: 'number',
};
}
on_finished() {
if (debug) {
console.log("rem viv healing: ", this.remVivifyHealing);
console.log("viv gusts healing: ", this.gustsHealing);
}
}
suggestions(when) {
when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => {
return suggest(
<>
You are casting <SpellLink id={SPELLS.VIVIFY.id} /> with less than 2 <SpellLink id={SPELLS.RENEWING_MIST.id} /> out on the raid. To ensure you are gaining the maximum <SpellLink id={SPELLS.VIVIFY.id} /> healing, keep <SpellLink id={SPELLS.RENEWING_MIST.id} /> on cooldown.
</>
)
.icon(SPELLS.VIVIFY.icon)
.actual(`${this.averageRemPerVivify} Unused Uplifting Trance procs`)
.recommended(`${recommended} wasted UT Buffs is recommended`);
});
}
statistic() {
return (
<StatisticBox
postion={STATISTIC_ORDER.CORE(15)}
icon={<SpellIcon id={SPELLS.VIVIFY.id} />}
value={`${this.averageRemPerVivify.toFixed(2)}`}
label={(
<dfn data-tip={`Healing Breakdown:
<ul>
<li>${formatNumber(this.abilityTracker.getAbility(SPELLS.VIVIFY.id).healingEffective)} overall healing from Vivify.</li>
<li>${formatNumber(this.remVivifyHealing)} portion of your Vivify healing to REM targets.</li>
</ul>`}>
Avg REMs per Cast
</dfn>
)}
/>
);
}
}
export default Vivify;
|
ReduxThunkNews/src/js/components/ListContacts.js
|
fengnovo/webpack-react
|
import React from 'react';
import {List, ListItem} from 'material-ui/List';
import ActionGrade from 'material-ui/svg-icons/action/grade';
import Divider from 'material-ui/Divider';
import Avatar from 'material-ui/Avatar';
import {pinkA200, transparent} from 'material-ui/styles/colors';
const ListContacts = ({fetchData}) => (
<List>
{
fetchData && fetchData.map((item) => <ListItem
key={item.id}
primaryText={item.title}
leftIcon={<ActionGrade color={pinkA200} />}
rightAvatar={<Avatar src={item.author.avatar_url} />}
/>)
}
</List>
);
export default ListContacts;
|
src/admin_components/ImportRaceComponent.js
|
chiefwhitecloud/running-man-frontend
|
import React from 'react';
import PropTypes from 'prop-types';
export default class ImportRaceComponent extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleReset = this.handleReset.bind(this);
}
handleSubmit(urls) {
this.props.onSubmit(urls);
}
handleReset(event) {
event.preventDefault();
this.props.onReset();
}
render() {
let display;
if (!this.props.isSubmitted) {
display = <ImportRaceForm onSubmit={this.handleSubmit} />;
} else if (this.props.importStatus === 'Failed') {
display = (<div>{this.props.importStatus} {this.props.errorMessage}
<button onClick={this.handleReset}>Submit Another</button>
</div>);
} else {
display = <div>{this.props.importStatus} {this.props.errorMessage}</div>;
}
return display;
}
}
ImportRaceComponent.propTypes = {
isSubmitted: PropTypes.bool.isRequired,
onSubmit: PropTypes.func.isRequired,
onReset: PropTypes.func.isRequired,
importStatus: PropTypes.string,
errorMessage: PropTypes.string,
}
|
js-old/src/views/Application/TabBar/Tab/tabs.spec.js
|
destenson/ethcore--parity
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import { shallow } from 'enzyme';
import React from 'react';
import sinon from 'sinon';
import Tab from './';
let component;
let instance;
function render (id = 'signer') {
component = shallow(
<Tab
pending={ 5 }
view={ { id } }
/>
);
instance = component.instance();
return component;
}
describe('views/Application/TabBar/Tab', () => {
beforeEach(() => {
render();
});
it('renders defaults', () => {
expect(component).to.be.ok;
});
describe('instance methods', () => {
describe('renderLabel', () => {
it('renders the label with correct label', () => {
expect(
shallow(instance.renderLabel('test')).find('FormattedMessage').props().id
).to.equal('settings.views.test.label');
});
it('renders the bubble when passed', () => {
expect(
shallow(instance.renderLabel('test', 'testBubble')).text()
).to.equal('<FormattedMessage />testBubble');
});
});
describe('renderSignerLabel', () => {
beforeEach(() => {
sinon.stub(instance, 'renderLabel');
});
afterEach(() => {
instance.renderLabel.restore();
});
it('calls renderLabel with the details', () => {
instance.renderSignerLabel();
expect(instance.renderLabel).to.have.been.calledWith('signer');
});
});
});
});
|
app/components/Charts/AreaChart/index.js
|
prudhvisays/season
|
import React from 'react';
import { ComposedChart, Line, Area, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';
import './AreaStyle.css';
class CustomTooltip extends React.Component{
render() {
const { active } = this.props;
if (active) {
const { payload, label } = this.props;
const payload1 = `${payload[0].name}`;
const payload2 = `${payload[1].name}`;
return (
<div className="custom-tooltip">
<p className="desc">{label}</p>
<p className="label">{`${payload1} : ${payload[0].payload[`${payload1}`]}`}</p>
<p className="label">{`${payload2} : ${payload[1].payload[`${payload2}`]}`}</p>
</div>
);
}
return null;
}
}
export default class StackedAreaChart extends React.Component{
render() {
const { data, color} = this.props;
return (
<ComposedChart width={399} height={200} data={data}
margin={{top: 0, right: 0, bottom: 0, left: 0}}>
<XAxis dataKey="name" label="Pages"/>
<YAxis label="Index"/>
<Tooltip content={<CustomTooltip/>}/>
<Legend/>
<CartesianGrid stroke='#f5f5f5'/>
<Bar dataKey='actual' barSize={20} fill={color}/>
<Line type='monotone' dataKey='target' stroke='#ff7300'/>
</ComposedChart>
);
}
}
|
app/src/components/common/CustomSelectionView.js
|
kort/kort-native
|
// customized SelectionView
// credits to thinnakrit --> https://github.com/thinnakrit/React-Native-Selection
import React, { Component } from 'react';
import {
Text,
View,
ScrollView,
TouchableOpacity,
Dimensions,
Modal
} from 'react-native';
import _ from 'lodash';
import Icon from 'react-native-vector-icons/FontAwesome';
class CustomSelectionView extends Component {
static propTypes = {
onSelection: React.PropTypes.func,
isOpen: React.PropTypes.func,
options: React.PropTypes.array,
title: React.PropTypes.string,
mode: React.PropTypes.func,
style: React.PropTypes.object,
iconColor: React.PropTypes.string,
iconSize: React.PropTypes.number,
titleCustomize: React.PropTypes.bool,
}
constructor(props) {
super(props);
this.state = {
modalVisible: false,
title: props.title,
value: 0,
};
}
openOption() {
if (!_.isEmpty(this.props.options)) {
this.setState({ modalVisible: !this.state.modalVisible });
}
this.checkIfOpen();
}
checkIfOpen() {
if (this.state.modalVisible) {
this.props.isOpen(false);
} else {
this.props.isOpen(true);
}
}
onSelected(name, value) {
if (!_.isEmpty(this.props.options)) {
const data = {
value,
name,
};
this.props.onSelection(data);
this.setState({
modalVisible: false,
title: name,
value,
});
}
this.checkIfOpen();
}
checkIcon(icon) {
return (
<View
style={{
marginRight: 10 }}
>
<Icon name={icon} size={this.props.iconSize} color={this.props.iconColor} /></View>
);
}
render() {
const ScreenHeight = Dimensions.get('window').height;
const ScreenWidth = Dimensions.get('window').width;
let { style, options, title, mode, iconColor, iconSize } = this.props;
if (_.isEmpty(options)) {
options = [];
}
const styles = {
main: {
width: ScreenWidth - 80,
marginLeft: 40,
marginTop: 5,
marginBottom: 5,
borderColor: '#657C8E',
borderWidth: 1,
padding: 10,
backgroundColor: '#ffffff',
},
body: {
width: ScreenWidth - 80,
backgroundColor: '#ffffff',
maxHeight: ScreenHeight - this.props.missionHeight,
borderRadius: 10,
borderWidth: 1,
borderColor: '#657C8E',
overflow: 'hidden',
},
option: {
width: ScreenWidth - 80,
padding: 10,
borderBottomWidth: 1,
borderBottomColor: '#657C8E',
flexDirection: 'row',
margin: 0,
backgroundColor: '#ffffff'
},
optionText: {
fontSize: 20,
color: '#657C8E'
},
text: {
fontSize: 20,
color: 'white',
textAlign: 'center'
}
};
if (style.body!== null) {
styles.body = style.body;
}
if (style.option!== null) {
styles.option = style.option;
}
if (style.main!== null) {
styles.main = style.main;
}
let titleSet = '';
if (this.props.titleCustomize === true) {
titleSet = this.props.title;
} else {
titleSet = this.state.title;
}
return (
<View>
<Modal
visible={this.state.modalVisible}
onRequestClose={() =>{
this.setState({ modalVisible: false });
}}
transparent={true}
>
<TouchableOpacity onPress={()=> this.openOption()}>
<View
style={{
width: ScreenWidth,
height: ScreenHeight,
backgroundColor: 'rgba(0,0,0,0.6)',
alignItems: 'center',
justifyContent: 'center'
}}
>
<View style={styles.body}>
<ScrollView>
{_.map(options, (data, k)=>{
let icon = <View />;
if(!_.isEmpty(data.icon)){
icon = this.checkIcon(data.icon)
}
return(
<TouchableOpacity key={k} onPress={()=> this.onSelected(data.name, data.value)}>
<View style={styles.option}>
{icon}
<Text style={styles.optionText} >{data.name}</Text>
</View>
</TouchableOpacity>
)
})}
</ScrollView>
</View>
</View>
</TouchableOpacity>
</Modal>
<TouchableOpacity onPress={()=>this.openOption()}>
<View style={styles.main}>
<Text style={styles.text}>{titleSet}</Text>
</View>
</TouchableOpacity>
</View>
);
}
}
export { CustomSelectionView } ;
|
src/components/UsersCard.js
|
kusaeva/firebase-chat
|
import React from 'react'
import {Row, Col, Card} from 'wix-style-react/dist/src/Grid'
import MessageInput from 'containers/MessageInput'
import Messages from 'containers/Messages'
// function getUser (id) {
// // return 'https://pp.userapi.com/c841220/v841220877/ee41/x-F0a25bkoQ.jpg'
// return
// }
// const user = getUser (message.author)
// const data = {
// ...message,
// author: user.username
// imageUrl: user.profile_picture
// }
const UsersCard = (props) => {
console.log(props.name);
return (
<Card>
<Card.Header title='Side Card'/>
<Card.Content>
<Row>
<Col span={12}>
<Messages messages=
{[{author:'Olga Borzenkova', text:'hduwhqdnsjadjsajdbsajbdsabdsad', time:Date.now(), imageUrl:'https://pp.userapi.com/c841220/v841220877/ee41/x-F0a25bkoQ.jpg'}]}/>
<MessageInput onClick={()=>{console.log('click')}}/>
</Col>
</Row>
</Card.Content>
</Card>
)
}
export default UsersCard
|
src/svg-icons/action/supervisor-account.js
|
manchesergit/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSupervisorAccount = (props) => (
<SvgIcon {...props}>
<path d="M16.5 12c1.38 0 2.49-1.12 2.49-2.5S17.88 7 16.5 7C15.12 7 14 8.12 14 9.5s1.12 2.5 2.5 2.5zM9 11c1.66 0 2.99-1.34 2.99-3S10.66 5 9 5C7.34 5 6 6.34 6 8s1.34 3 3 3zm7.5 3c-1.83 0-5.5.92-5.5 2.75V19h11v-2.25c0-1.83-3.67-2.75-5.5-2.75zM9 13c-2.33 0-7 1.17-7 3.5V19h7v-2.25c0-.85.33-2.34 2.37-3.47C10.5 13.1 9.66 13 9 13z"/>
</SvgIcon>
);
ActionSupervisorAccount = pure(ActionSupervisorAccount);
ActionSupervisorAccount.displayName = 'ActionSupervisorAccount';
ActionSupervisorAccount.muiName = 'SvgIcon';
export default ActionSupervisorAccount;
|
src/components/main/Layout/Layout.js
|
5rabbits/portrait
|
import React from 'react'
import childrenPropType from 'propTypes/children'
const Layout = props =>
<section className="layout-wrapper" id="block-app">
<header className="layout-header" id="block-header">
{props.header}
</header>
<nav className="layout-navigation" id="block-navigation">
{props.navigation}
</nav>
<main className="layout-main" id="block-main">
{props.main}
</main>
</section>
Layout.propTypes = {
header: childrenPropType,
main: childrenPropType,
navigation: childrenPropType,
}
Layout.defaultProps = {
header: null,
main: null,
navigation: null,
}
export default Layout
|
monkey/monkey_island/cc/ui/src/components/report-components/attack/SelectedTechnique.js
|
guardicore/monkey
|
import React from 'react';
import Collapse from '@kunukn/react-collapse';
import AttackReport from '../AttackReport';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faQuestionCircle} from '@fortawesome/free-solid-svg-icons/faQuestionCircle';
import classNames from 'classnames';
class SelectedTechnique extends React.Component {
constructor(props) {
super(props);
this.state = {
techniques: this.props.techniques,
techComponents: this.props.techComponents,
selectedTechnique: this.props.selected
};
}
componentDidUpdate(prevProps) {
if (this.props.selected !== prevProps.selected || this.props.techniques !== prevProps.techniques) {
this.setState({ selectedTechnique: this.props.selected,
techniques: this.props.techniques})
}
}
getSelectedTechniqueComponent(tech_id) {
const TechniqueComponent = this.state.techComponents[tech_id];
return (
<div key={tech_id} className={classNames('collapse-item', {'item--active': true})}>
<button className={classNames('btn-collapse',
'selected-technique',
AttackReport.getComponentClass(tech_id, this.state.techniques))}>
<span>
{AttackReport.getStatusIcon(tech_id, this.state.techniques)}
{this.state.techniques[tech_id].title}
</span>
<span>
<a href={this.state.techniques[tech_id].link} rel="noopener noreferrer" target='_blank' className={'link-to-technique'}>
<FontAwesomeIcon icon={faQuestionCircle}
color={AttackReport.getComponentClass(tech_id, this.state.techniques) === 'collapse-default' ? '#ffffff' : '#000000'}/>
</a>
</span>
</button>
<Collapse
className='collapse-comp'
isOpen={true}
render={() => {
return (<div className={`content ${tech_id}`}>
<TechniqueComponent data={this.state.techniques[tech_id]}/>
</div>)
}}/>
</div>
);
}
render(){
let content = {};
let selectedTechId = this.state.selectedTechnique;
if(selectedTechId === false){
content = 'None. Select a technique from ATT&CK matrix above.';
} else {
content = this.getSelectedTechniqueComponent(selectedTechId)
}
return (
<div>
<h3 className='selected-technique-title'>Selected technique</h3>
<section className='attack-report selected-technique'>
{content}
</section>
</div>
)
}
}
export default SelectedTechnique;
|
public/components/tehtPage/tabsComponents/tehtava/JournalView.js
|
City-of-Vantaa-SmartLab/kupela
|
import React from 'react';
import { connect } from 'react-redux';
const JournalView = (props) => (
<div className="journalViewArea">
<div className="scrollableArea">
<div className="journalTextView">
TILANNEPÄIVÄKIRJA
{props.journalEntries.entries.map((c) =>
<p className="journalEntry">
{c.sender} : {c.time} - {c.message}
</p>
)}
</div>
</div>
</div>
);
const mapStateToProps = ({journal: {journalEntries}}) => ({
journalEntries
});
export default connect(mapStateToProps, null)(JournalView);
|
app/react/src/client/preview/error_display.js
|
enjoylife/storybook
|
import PropTypes from 'prop-types';
import React from 'react';
const mainStyle = {
position: 'fixed',
top: 0,
bottom: 0,
left: 0,
right: 0,
padding: 20,
backgroundColor: 'rgb(187, 49, 49)',
color: '#FFF',
WebkitFontSmoothing: 'antialiased',
};
const headingStyle = {
fontSize: 20,
fontWeight: 600,
letterSpacing: 0.2,
margin: '10px 0',
fontFamily: `
-apple-system, ".SFNSText-Regular", "San Francisco", Roboto, "Segoe UI",
"Helvetica Neue", "Lucida Grande", sans-serif
`,
};
const codeStyle = {
fontSize: 14,
width: '100vw',
overflow: 'auto',
};
const ErrorDisplay = ({ error }) =>
<div style={mainStyle}>
<div style={headingStyle}>{error.message}</div>
<pre style={codeStyle}>
<code>
{error.stack}
</code>
</pre>
</div>;
ErrorDisplay.propTypes = {
error: PropTypes.shape({
message: PropTypes.string,
stack: PropTypes.string,
}).isRequired,
};
export default ErrorDisplay;
|
app/scripts/ExportLinkDialog.js
|
hms-dbmi/higlass
|
import React from 'react';
import PropTypes from 'prop-types';
import Button from './Button';
import Dialog from './Dialog';
import '../styles/ExportLinkDialog.module.scss';
class ExportLinkDialog extends React.Component {
render() {
return (
<Dialog
okayOnly={true}
okayTitle="Done"
onOkay={this.props.onDone}
title="Share view link"
>
<div styleName="export-link-dialog-wrapper">
<input
ref={(element) => {
if (!element) return;
this.input = element;
element.focus();
element.select();
}}
onClick={(event) => {
event.target.select();
}}
placeholder="Generating the link..."
readOnly={true}
value={this.props.url}
/>
<Button
onClick={(event) => {
this.input.select();
document.execCommand('copy');
}}
>
Copy
</Button>
</div>
</Dialog>
);
}
}
ExportLinkDialog.defaultProps = {
onDone: () => {},
url: '',
};
ExportLinkDialog.propTypes = {
onDone: PropTypes.func,
url: PropTypes.string,
};
export default ExportLinkDialog;
|
packages/icons/src/md/editor/FormatShapes.js
|
suitejs/suitejs
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdFormatShapes(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M46 14h-4v20h4v12H34v-4H14v4H2V34h4V14H2V2h12v4h20V2h12v12zM6 6v4h4V6H6zm4 36v-4H6v4h4zm24-4v-4h4V14h-4v-4H14v4h-4v20h4v4h20zm8 4v-4h-4v4h4zm-4-32h4V6h-4v4zM27.47 28H20.5l-1.46 4h-3.25l6.8-18h2.81l6.81 18h-3.26l-1.48-4zm-6.1-2.52h5.22l-2.61-7.66-2.61 7.66z" />
</IconBase>
);
}
export default MdFormatShapes;
|
actor-apps/app-web/src/app/components/activity/UserProfile.react.js
|
shaunstanislaus/actor-platform
|
import React from 'react';
import { PureRenderMixin } from 'react/addons';
import ContactActionCreators from 'actions/ContactActionCreators';
import DialogActionCreators from 'actions/DialogActionCreators';
import PeerStore from 'stores/PeerStore';
import DialogStore from 'stores/DialogStore';
import AvatarItem from 'components/common/AvatarItem.react';
import UserProfileContactInfo from 'components/activity/UserProfileContactInfo.react';
const getStateFromStores = (userId) => {
const thisPeer = PeerStore.getUserPeer(userId);
return {
thisPeer: thisPeer,
isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer)
};
};
var UserProfile = React.createClass({
propTypes: {
user: React.PropTypes.object.isRequired
},
mixins: [PureRenderMixin],
getInitialState() {
return getStateFromStores(this.props.user.id);
},
componentWillMount() {
DialogStore.addNotificationsListener(this.whenNotificationChanged);
},
componentWillUnmount() {
DialogStore.removeNotificationsListener(this.whenNotificationChanged);
},
componentWillReceiveProps(newProps) {
this.setState(getStateFromStores(newProps.user.id));
},
addToContacts() {
ContactActionCreators.addContact(this.props.user.id);
},
removeFromContacts() {
ContactActionCreators.removeContact(this.props.user.id);
},
onNotificationChange(event) {
DialogActionCreators.changeNotificationsEnabled(this.state.thisPeer, event.target.checked);
},
whenNotificationChanged() {
this.setState(getStateFromStores(this.props.user.id));
},
render() {
const user = this.props.user;
const isNotificationsEnabled = this.state.isNotificationsEnabled;
let addToContacts;
if (user.isContact === false) {
addToContacts = <a className="link__blue" onClick={this.addToContacts}>Add to contacts</a>;
} else {
addToContacts = <a className="link__red" onClick={this.removeFromContacts}>Remove from contacts</a>;
}
return (
<div className="activity__body profile">
<div className="profile__name">
<AvatarItem image={user.bigAvatar}
placeholder={user.placeholder}
size="medium"
title={user.name}/>
<h3>{user.name}</h3>
</div>
<div className="notifications">
<label htmlFor="notifications">Enable Notifications</label>
<div className="switch pull-right">
<input checked={isNotificationsEnabled} id="notifications" onChange={this.onNotificationChange} type="checkbox"/>
<label htmlFor="notifications"></label>
</div>
</div>
<UserProfileContactInfo phones={user.phones}/>
<ul className="profile__list profile__list--usercontrols">
<li className="profile__list__item">
{addToContacts}
</li>
</ul>
</div>
);
}
});
export default UserProfile;
|
app/javascript/mastodon/components/setting_text.js
|
pixiv/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
export default class SettingText extends React.PureComponent {
static propTypes = {
settings: ImmutablePropTypes.map.isRequired,
settingKey: PropTypes.array.isRequired,
label: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
};
handleChange = (e) => {
this.props.onChange(this.props.settingKey, e.target.value);
}
render () {
const { settings, settingKey, label } = this.props;
return (
<label>
<span style={{ display: 'none' }}>{label}</span>
<input
className='setting-text'
value={settings.getIn(settingKey)}
onChange={this.handleChange}
placeholder={label}
/>
</label>
);
}
}
|
src/main.js
|
HackDFW/hackdfw-frontend
|
import React from 'react'
import ReactDOM from 'react-dom'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import { syncReduxAndRouter } from 'redux-simple-router'
import routes from './routes'
import Root from './containers/Root'
import configureStore from './redux/configureStore'
const history = createBrowserHistory()
const store = configureStore(window.__INITIAL_STATE__)
syncReduxAndRouter(history, store, (state) => state.router)
// Render the React application to the DOM
ReactDOM.render(
<Root history={history} routes={routes} store={store} />,
document.getElementById('root')
)
|
jenkins-design-language/src/js/components/material-ui/svg-icons/hardware/computer.js
|
alvarolobato/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const HardwareComputer = (props) => (
<SvgIcon {...props}>
<path d="M20 18c1.1 0 1.99-.9 1.99-2L22 6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2H0v2h24v-2h-4zM4 6h16v10H4V6z"/>
</SvgIcon>
);
HardwareComputer.displayName = 'HardwareComputer';
HardwareComputer.muiName = 'SvgIcon';
export default HardwareComputer;
|
packages/icons/src/md/places/ChildCare.js
|
suitejs/suitejs
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdChildCare(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M45.89 25.33c-.51 3.02-2.72 5.47-5.61 6.34a18.026 18.026 0 0 1-4.34 5.78C32.76 40.27 28.59 42 24 42s-8.76-1.73-11.94-4.55c-1.81-1.61-3.3-3.57-4.34-5.78-2.89-.87-5.1-3.32-5.61-6.34C2.04 24.9 2 24.45 2 24c0-.45.04-.9.11-1.33a8.022 8.022 0 0 1 5.61-6.34c1.06-2.23 2.56-4.2 4.39-5.82C15.28 7.71 19.44 6 24 6c4.56 0 8.72 1.71 11.89 4.51 1.83 1.61 3.34 3.59 4.39 5.82 2.89.87 5.1 3.32 5.61 6.34.07.43.11.88.11 1.33 0 .45-.04.9-.11 1.33zM38 28c2.2 0 4-1.8 4-4s-1.8-4-4-4c-.2 0-.39.03-.58.06a13.85 13.85 0 0 0-1.72-3.72C33.2 12.53 28.89 10 24 10s-9.2 2.53-11.71 6.34c-.74 1.14-1.33 2.39-1.72 3.72-.18-.03-.37-.06-.57-.06-2.2 0-4 1.8-4 4s1.8 4 4 4c.2 0 .39-.03.58-.06.39 1.33.97 2.58 1.72 3.72C14.8 35.47 19.11 38 24 38s9.2-2.53 11.71-6.34c.74-1.14 1.33-2.39 1.72-3.72.18.03.37.06.57.06zm-23 0h18c-1.52 3.53-4.97 6-9 6s-7.48-2.47-9-6zm14-4.5a2.5 2.5 0 1 1 0-5 2.5 2.5 0 0 1 0 5zm-10 0a2.5 2.5 0 1 1 0-5 2.5 2.5 0 0 1 0 5z" />
</IconBase>
);
}
export default MdChildCare;
|
src/svg-icons/communication/contacts.js
|
jacklam718/react-svg-iconx
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationContacts = (props) => (
<SvgIcon {...props}>
<path d="M20 0H4v2h16V0zM4 24h16v-2H4v2zM20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 2.75c1.24 0 2.25 1.01 2.25 2.25s-1.01 2.25-2.25 2.25S9.75 10.24 9.75 9 10.76 6.75 12 6.75zM17 17H7v-1.5c0-1.67 3.33-2.5 5-2.5s5 .83 5 2.5V17z"/>
</SvgIcon>
);
CommunicationContacts = pure(CommunicationContacts);
CommunicationContacts.displayName = 'CommunicationContacts';
CommunicationContacts.muiName = 'SvgIcon';
export default CommunicationContacts;
|
src/components/Breadcumn/Header.js
|
flftfqwxf/react-redux-starter-kit
|
import React from 'react'
import { IndexLink, Link } from 'react-router'
import './Header.scss'
export const Header = () => (
<div>
<h1>React Redux Starter Kit</h1>
<IndexLink to='/' activeClassName='route--active'>
Home
</IndexLink>
{' · '}
<Link to='/counter' activeClassName='route--active'>
Counter
</Link>
</div>
)
export default Header
|
packages/@vega/review-tool/src/components/ManageReviewProcess/ManageReviewProcess.js
|
VegaPublish/vega-studio
|
import React from 'react'
import {map, switchMap} from 'rxjs/operators'
import {combineLatest} from 'rxjs'
import lyraClient from 'part:@lyra/base/client'
import withPropsStream from '../../../../utils/withPropsStream'
import {materializePaths} from 'part:@vega/datastores/document-preview'
import ManageReviewItem from './ManageReviewItem'
import styles from './styles/ManageReviewProcess.css'
import Button from 'part:@lyra/components/buttons/default'
import Fieldset from 'part:@lyra/components/fieldsets/default'
import schema from 'part:@lyra/base/schema'
import {WithFormBuilderValue} from 'part:@lyra/form-builder'
import Field from '../Field'
import AddReviewItemDialog from './AddReviewItemDialog'
import observableWithQuery from '../../util/observableWithQuery'
import Spinner from 'part:@lyra/components/loading/spinner'
const noop = () => {}
const humanReadableDecission = {
reject: 'Reject',
publish: 'Publish',
'publish-with-revisions': 'Publish with revisions'
}
function listenReviewItems(reviewProcessId) {
const query = `*[_type == "reviewItem" && reviewProcess._ref == "${reviewProcessId}" && !(_id in path('drafts.**'))]
|order(_createdAt asc)
[0..100]
{...,reviewer->{_id,name}}`
return observableWithQuery(query)
}
function loadProps(props$) {
return props$.pipe(
switchMap(props =>
combineLatest([
materializePaths(props.reviewProcess, [
'_id',
'completedAt',
'decision'
]),
listenReviewItems(props.reviewProcess._id)
]).pipe(
map(([reviewProcess, reviewItems]) => ({
...props,
reviewProcess,
reviewItems
}))
)
)
)
}
type Props = {
reviewProcess: any,
reviewItems: any
}
class ManageReviewProcess extends React.PureComponent<Props, *> {
state = {
isAddingFinalDecision: false,
isAddingReviewer: false,
readOnly: false,
loading: false
}
handleAddReviewerClick = () => {
this.setState({isAddingReviewer: true})
}
handleAddReviewerDialogClose = event => {
this.setState({isAddingReviewer: false})
}
handleProceedToggle = () => {
const {isAddingFinalDecision} = this.state
this.setState({isAddingFinalDecision: !isAddingFinalDecision})
}
handleToggleReadOnly = event => {
this.setState({readOnly: event.target.checked})
}
handleSubmit = () => {
this.setState({
loading: true
})
lyraClient
.patch(this.props.reviewProcess._id)
.set({completedAt: new Date().toISOString()})
.commit()
.then(
this.setState({
isAddingFinalDecision: false,
readOnly: true,
loading: false
})
)
}
handleFocus = nextFocusPath => {
this.setState({focusPath: nextFocusPath})
}
render() {
const {reviewProcess, reviewItems} = this.props
const {completedAt, decision} = reviewProcess
const {loading} = this.state
// Check if review is comleted
const isCompleted = !!completedAt && decision
const {
readOnly,
isAddingReviewer,
isAddingFinalDecision,
focusPath
} = this.state
return (
<div className={styles.root}>
{isAddingReviewer && (
<AddReviewItemDialog
onClose={this.handleAddReviewerDialogClose}
reviewProcess={reviewProcess}
/>
)}
<div className={styles.header}>
<h2>Reviews</h2>
{isCompleted && (
<div className={styles[`decision_${decision}`]}>
Decision:
<h3 className={styles.status}>
{humanReadableDecission[decision] || decision}
</h3>
</div>
)}
</div>
<ul>
{reviewItems.map(reviewItem => (
<ManageReviewItem
key={reviewItem._id}
reviewItem={reviewItem}
readOnly={readOnly}
isCompleted={isCompleted}
/>
))}
</ul>
{!readOnly &&
!isCompleted && (
<div>
<Button onClick={this.handleAddReviewerClick}>
+ Invite reviewer
</Button>
{isAddingFinalDecision && (
<div>
<WithFormBuilderValue
documentId={reviewProcess._id}
typeName="reviewProcess"
schema={schema}
>
{props =>
props.isLoading ? (
<Spinner message="Loading…" />
) : (
<form onSubmit={this.handleProceedToggle}>
<Fieldset>
{loading && (
<Spinner message="Sending final decision" />
)}
<Field
fieldName="content"
type={props.type}
value={props.value}
onChange={props.onChange}
onFocus={this.handleFocus}
onBlur={noop}
focusPath={focusPath}
/>
<br />
<Field
fieldName="decision"
type={props.type}
value={props.value}
onChange={props.onChange}
onFocus={this.handleFocus}
onBlur={noop}
focusPath={focusPath}
/>
<br />
<Button color="primary" onClick={this.handleSubmit}>
Submit
</Button>
<Button onClick={this.handleProceedToggle}>
Cancel
</Button>
</Fieldset>
</form>
)
}
</WithFormBuilderValue>
</div>
)}
{!isAddingFinalDecision && (
<div className={styles.finalDecision}>
<Button
onClick={this.handleProceedToggle}
color="primary"
loading={loading}
>
Proceed to final decision
</Button>
</div>
)}
</div>
)}
{isCompleted && (
<div>
<div className={styles.finalDecisionCompleted}>
<h2>Final decision made: {humanReadableDecission[decision]}</h2>
</div>
<WithFormBuilderValue
documentId={reviewProcess._id}
typeName="reviewProcess"
schema={schema}
>
{props =>
props.isLoading ? (
<Spinner message="Loading…" />
) : (
<Field
fieldName="content"
type={props.type}
value={props.value}
onChange={props.onChange}
onFocus={this.handleFocus}
onBlur={noop}
readOnly
focusPath={focusPath}
/>
)
}
</WithFormBuilderValue>
</div>
)}
</div>
)
}
}
export default withPropsStream(loadProps, ManageReviewProcess)
|
client/views/setupWizard/Pager.stories.js
|
VoiSmart/Rocket.Chat
|
import { action } from '@storybook/addon-actions';
import React from 'react';
import { Pager } from './Pager';
export default {
title: 'components/setupWizard/Pager',
component: Pager,
};
export const _default = () => <Pager disabled={false} isContinueEnabled={false} />;
export const withBackButton = () => <Pager onBackClick={action('backClick')} />;
export const disabled = () => <Pager disabled onBackClick={action('backClick')} />;
export const withContinueDisabled = () => (
<Pager isContinueEnabled={false} onBackClick={action('backClick')} />
);
|
docs/src/app/components/pages/components/Drawer/ExampleUndocked.js
|
lawrence-yu/material-ui
|
import React from 'react';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
import RaisedButton from 'material-ui/RaisedButton';
export default class DrawerUndockedExample extends React.Component {
constructor(props) {
super(props);
this.state = {open: false};
}
handleToggle = () => this.setState({open: !this.state.open});
handleClose = () => this.setState({open: false});
render() {
return (
<div>
<RaisedButton
label="Open Drawer"
onTouchTap={this.handleToggle}
/>
<Drawer
docked={false}
width={200}
open={this.state.open}
onRequestChange={(open) => this.setState({open})}
>
<MenuItem onTouchTap={this.handleClose}>Menu Item</MenuItem>
<MenuItem onTouchTap={this.handleClose}>Menu Item 2</MenuItem>
</Drawer>
</div>
);
}
}
|
node_modules/enzyme/test/_helpers.js
|
Shwrndasink/btholt-react-tutorial
|
/* globals jsdom */
import React from 'react';
/**
* Simple wrapper around mocha describe which allows a boolean to be passed in first which
* determines whether or not the test will be run
*/
export function describeIf(test, a, b) {
if (test) {
describe(a, b);
} else {
describe.skip(a, b);
}
}
/**
* Simple wrapper around mocha it which allows a boolean to be passed in first which
* determines whether or not the test will be run
*/
export function itIf(test, a, b) {
if (test) {
it(a, b);
} else {
it.skip(a, b);
}
}
/**
* Simple wrapper around mocha it which allows an array of possible values to test against.
* Each test will be wrapped in a try/catch block to handle any errors.
*
* @param {Object[]} data
* @param {String} message
* @param {Function} factory
*/
export function itWithData(data, message, factory) {
data.forEach((testCase) => {
it(`${message} ${testCase.message}`, () => factory(testCase));
});
}
function only(a, b) {
describe('(uses jsdom)', () => {
if (typeof jsdom === 'function') {
jsdom();
describe.only(a, b);
} else {
// if jsdom isn't available, skip every test in this describe context
describe.skip(a, b);
}
});
}
function skip(a, b) {
describe('(uses jsdom)', () => {
if (typeof jsdom === 'function') {
jsdom();
describe.skip(a, b);
} else {
// if jsdom isn't available, skip every test in this describe context
describe.skip(a, b);
}
});
}
export function describeWithDOM(a, b) {
describe('(uses jsdom)', () => {
if (global.document) {
describe(a, b);
} else {
// if jsdom isn't available, skip every test in this describe context
describe.skip(a, b);
}
});
}
describeWithDOM.only = only;
describeWithDOM.skip = skip;
/**
* React component used for testing.
*/
class TestHelper extends React.Component {
render() {
return <div />;
}
}
/**
* Possible values for React render() checks.
*/
export function generateEmptyRenderData() {
return [
// Returns true for empty
{ message: 'false', value: false, expectResponse: true },
{ message: 'null', value: null, expectResponse: true },
// Returns false for empty, valid returns
{ message: 'React component', value: <TestHelper />, expectResponse: false },
{ message: 'React element', value: <span />, expectResponse: false },
];
}
|
library/src/pivotal-ui-react/tile-layout/tile-layout.js
|
sjolicoeur/pivotal-ui
|
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import {mergeProps} from 'pui-react-helpers';
import 'pui-css-tile-layout';
export class TileLayout extends React.Component {
static propTypes = {
columns: PropTypes.oneOfType([
PropTypes.number,
PropTypes.object
]),
noGutter: PropTypes.bool
}
getColumnClasses = columns => {
if (columns instanceof Object) {
const classes = [];
for (let breakpoint in columns) {
if (columns.hasOwnProperty(breakpoint)) {
classes.push(`tile-layout-${breakpoint}-${columns[breakpoint]}`);
}
}
return classes;
} else {
return `tile-layout-xs-${columns}`;
}
}
render() {
const {children, columns, noGutter, ...others} = this.props;
const classes = classnames(
this.getColumnClasses(columns),
noGutter ? null : 'tile-gutter',
'tile-layout'
);
const props = mergeProps({className: classes}, others);
return (<div {...props}>
{children}
</div>);
}
}
export class TileLayoutItem extends React.Component {
render() {
return <div {...mergeProps({className: 'tile-item'}, this.props)}/>;
}
}
|
components/dataset/header/index.js
|
sgmap/inspire
|
import React from 'react'
import PropTypes from 'prop-types'
import {translate} from 'react-i18next'
import MarkdownPreview from '../../markdown-preview'
import Warning from '../../warning'
import Infos from './infos'
import LifeCycle from './life-cycle'
const shouldWarn = status => [
'obsolete',
'underDevelopment'
].includes(status)
const Header = ({metadata, i18n: {language}, t}) => (
<div>
{shouldWarn(metadata.status) && (
<div className='warning'>
<Warning>{t(`warnings.${metadata.status}`)}</Warning>
</div>
)}
<section className='row'>
<div className='left'>
<h1>{metadata.title}</h1>
<Infos metadata={metadata} />
</div>
{metadata.inspireTheme && (
<a href={`${metadata.inspireTheme.uri}?lang=${language}`} target='_blank' rel='noopener noreferrer'>
<img
src={`/static/images/datasets/inspire/${metadata.inspireTheme.id}.svg`}
title={metadata.inspireTheme.label[language]}
alt={metadata.inspireTheme.label[language]}
/>
</a>
)}
</section>
<section>
{metadata.description ? (
<MarkdownPreview markdown={metadata.description} />
) : (
<i>{t('noDescription')}</i>
)}
</section>
<section className='origin'>
<h5>{t('labels.dataOrigin')}</h5>
{metadata.lineage ? (
<MarkdownPreview markdown={metadata.lineage} />
) : (
<i>{t('common:enums.unknownData.notSpecified', {
context: 'female'
})}</i>
)}
</section>
<section>
<p>
<b>{t('labels.purpose')}</b> {metadata.purpose || t('common:enums.unknownData.notSpecified')}
</p>
<LifeCycle
updateFrequency={metadata.updateFrequency}
creationDate={metadata.creationDate}
status={metadata.status}
/>
</section>
<style jsx>{`
@import 'colors';
section:not(:last-child) {
margin-bottom: 1em;
}
.warning {
margin-bottom: 1em;
}
.row {
display: flex;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: break-word;
border-bottom: 1px solid $lightgrey;
padding-bottom: 1em;
}
.origin {
border-top: 1px solid $lightgrey;
border-bottom: 1px solid $lightgrey;
padding: 1em 0;
}
.left {
flex: 1;
}
h1 {
font-size: 1.8rem;
font-weight: 500;
margin: 0 0 0.6rem 0;
}
a {
display: block;
padding-left: 15px;
img {
width: 40px;
}
}
`}</style>
</div>
)
Header.propTypes = {
metadata: PropTypes.shape({
title: PropTypes.string.isRequired,
inspireTheme: PropTypes.shape({
id: PropTypes.string.isRequired,
uri: PropTypes.string.isRequired,
label: PropTypes.object.isRequired
}),
updateFrequency: PropTypes.string,
creationDate: PropTypes.string,
status: PropTypes.string
}).isRequired,
i18n: PropTypes.shape({
language: PropTypes.string.isRequired
}).isRequired,
t: PropTypes.func.isRequired
}
export default translate('dataset')(Header)
|
pootle/static/js/shared/components/FormValueInput.js
|
ta2-1/pootle
|
/*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import React from 'react';
import AutosizeTextarea from './AutosizeTextarea';
const FormValueInput = React.createClass({
propTypes: {
handleChange: React.PropTypes.func.isRequired,
autosize: React.PropTypes.bool,
type: React.PropTypes.string,
value: React.PropTypes.string,
},
getDefaultProps() {
return {
autosize: true,
};
},
handleChange(e) {
this.props.handleChange(e.target.name, e.target.value);
},
render() {
if (this.props.type === 'textarea') {
if (this.props.autosize) {
return (
<AutosizeTextarea
onChange={this.handleChange}
{...this.props}
/>
);
}
return (
<textarea
onChange={this.handleChange}
{...this.props}
/>
);
}
return <input onChange={this.handleChange} {...this.props} />;
},
});
export default FormValueInput;
|
src/svg-icons/device/brightness-low.js
|
jacklam718/react-svg-iconx
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBrightnessLow = (props) => (
<SvgIcon {...props}>
<path d="M20 15.31L23.31 12 20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z"/>
</SvgIcon>
);
DeviceBrightnessLow = pure(DeviceBrightnessLow);
DeviceBrightnessLow.displayName = 'DeviceBrightnessLow';
DeviceBrightnessLow.muiName = 'SvgIcon';
export default DeviceBrightnessLow;
|
client/common/components/ToggleButton.js
|
Haaarp/geo
|
import React from 'react';
import uuid from 'uuid';
class ToggleButton extends React.Component {
constructor(props){
super(props);
this.id = uuid();
}
_getButtonClassName(){
return "checkbox-wrap" +
(this.props.className ? (' ' + this.props.className) : "") +
(this.props.disabled ? " btn-disabled" : "");
}
render() {
return (
<div className={this._getButtonClassName()}>
<input
type="checkbox"
className="checkbox"
id={"checkbox" + this.id}
onChange={data => null}
checked={this.props.checked}
onClick={this.props.onClick} />
<label htmlFor={"checkbox" + this.id}>{this.props.label}</label>
</div>
);
}
}
export default ToggleButton;
|
src/svg-icons/hardware/keyboard.js
|
skarnecki/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareKeyboard = (props) => (
<SvgIcon {...props}>
<path d="M20 5H4c-1.1 0-1.99.9-1.99 2L2 17c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-9 3h2v2h-2V8zm0 3h2v2h-2v-2zM8 8h2v2H8V8zm0 3h2v2H8v-2zm-1 2H5v-2h2v2zm0-3H5V8h2v2zm9 7H8v-2h8v2zm0-4h-2v-2h2v2zm0-3h-2V8h2v2zm3 3h-2v-2h2v2zm0-3h-2V8h2v2z"/>
</SvgIcon>
);
HardwareKeyboard = pure(HardwareKeyboard);
HardwareKeyboard.displayName = 'HardwareKeyboard';
export default HardwareKeyboard;
|
src/Parser/Paladin/Holy/Modules/Items/DrapeOfShame.js
|
hasseboulen/WoWAnalyzer
|
import React from 'react';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import HIT_TYPES from 'Parser/Core/HIT_TYPES';
import Wrapper from 'common/Wrapper';
import CoreDrapeOfShame, { DRAPE_OF_SHAME_CRIT_EFFECT } from 'Parser/Core/Modules/Items/Legion/DrapeOfShame';
import ItemHealingDone from 'Main/ItemHealingDone';
import StatValues from '../Features/StatValues';
class DrapeOfShame extends CoreDrapeOfShame {
static dependencies = {
...CoreDrapeOfShame.dependencies,
statValues: StatValues,
};
get estimatedItemLevel() {
if (!this.owner.finished) {
return null;
}
// My DoS
const itemLevel = this.equippedItem.itemLevel;
const statsHps = this.statValues.calculateItemStatsHps(this.baseStats, itemLevel);
const effectHps = this.healing / this.owner.fightDuration * 1000;
const totalHps = statsHps + effectHps;
// An estimated DoS
let estimatedItemLevel = itemLevel;
let estimatedHps = 0;
while (estimatedHps < totalHps) {
estimatedItemLevel += 5;
estimatedHps = this.statValues.calculateItemStatsHps(this.baseStats, estimatedItemLevel);
}
// We need the `estimatedItemLevel` to *beat* the DoS, so the DoS is worth about 0-5 item levels less
return estimatedItemLevel - 5;
}
on_byPlayer_heal(event) {
const spellId = event.ability.guid;
if (this.owner.constructor.abilitiesAffectedByHealingIncreases.indexOf(spellId) === -1 || spellId === SPELLS.BEACON_OF_LIGHT_CAST_AND_HEAL.id) {
return;
}
super.on_byPlayer_heal(event);
}
on_beacon_heal(beaconTransferEvent, healEvent) {
const spellId = healEvent.ability.guid;
if (this.owner.constructor.abilitiesAffectedByHealingIncreases.indexOf(spellId) === -1 || spellId === SPELLS.BEACON_OF_LIGHT_CAST_AND_HEAL.id) {
return;
}
if (healEvent.hitType !== HIT_TYPES.CRIT) {
return;
}
const amount = beaconTransferEvent.amount;
const absorbed = beaconTransferEvent.absorbed || 0;
const overheal = beaconTransferEvent.overheal || 0;
const raw = amount + absorbed + overheal;
const rawNormalPart = raw / this.critEffectBonus.getBonus(healEvent);
const rawDrapeHealing = rawNormalPart * DRAPE_OF_SHAME_CRIT_EFFECT;
const effectiveHealing = Math.max(0, rawDrapeHealing - overheal);
this.healing += effectiveHealing;
}
item() {
const estimatedItemLevel = this.estimatedItemLevel;
return {
item: ITEMS.DRAPE_OF_SHAME,
result: (
<Wrapper>
<ItemHealingDone amount={this.healing} /><br />
<img
src="/img/ilvl.png"
alt="Item level"
className="icon"
/>{' '}{estimatedItemLevel !== null ? `≈${estimatedItemLevel} cloak with similar stats` : 'Calculating...'}
</Wrapper>
),
};
}
}
export default DrapeOfShame;
|
information/blendle-frontend-react-source/app/components/signUp/SignUpContainer.js
|
BramscoChill/BlendleParser
|
import { history } from 'byebye';
import { STATUS_OK, STATUS_PENDING, USER_ID_TAKEN } from 'app-constants';
import React from 'react';
import PropTypes from 'prop-types';
import SignUpStore from 'stores/SignUpStore';
import AuthStore from 'stores/AuthStore';
import SignUpActions from 'actions/SignUpActions';
import SignUpForm from './SignUpForm';
import LoginContainer from 'components/login/LoginContainer';
export default class SignUpContainer extends React.Component {
static propTypes = {
analyticsPayload: PropTypes.object,
onSignUp: PropTypes.func, // deprecated, use the SignUpStore or AuthStore
// when clicking a 'login' link, like in an 'email exists' error message.
// default leads to /login
onToLogin: PropTypes.func,
// provide extra data to send to the signup and confirmation webservice
// this could contain keys like `referrer` or `entry_item`
signUpContext: PropTypes.object,
buttonHTML: PropTypes.string,
verifyEmail: PropTypes.bool,
onLogin: PropTypes.func,
onToReset: PropTypes.func,
showPasswordField: PropTypes.bool,
signUpType: PropTypes.string,
};
static defaultProps = {
verifyEmail: false,
analyticsName: 'Signup Form',
analyticsPayload: {},
signUpContext: {},
showPasswordField: false,
onToLogin() {
history.navigate('/login', { trigger: true });
},
};
constructor(props) {
super(props);
this.state = {
signUpStore: SignUpStore.getState(),
authStore: AuthStore.getState(),
};
SignUpStore.listen(this._onSignUpStore);
AuthStore.listen(this._onAuthStore);
}
componentWillUnmount() {
SignUpStore.unlisten(this._onSignUpStore);
AuthStore.unlisten(this._onAuthStore);
}
_onSignUpStore = (storeState) => {
if (storeState.status === STATUS_OK) {
setTimeout(this.props.onSignUp);
} else {
this.setState({ signUpStore: storeState });
}
};
_onAuthStore = (storeState) => {
this.setState({ authStore: storeState });
};
_onSignUp = (email, options) => {
const context = {
...this.props.signUpContext,
...options,
};
SignUpActions.signUp(email, context, {
verifyEmail: this.props.verifyEmail,
analyticsPayload: this.props.analyticsPayload,
signUpType: this.props.signUpType,
});
};
render() {
if (this.state.signUpStore.error === USER_ID_TAKEN) {
return (
<LoginContainer
email={this.state.signUpStore.email}
onLogin={this.props.onLogin}
onToReset={this.props.onToReset}
analyticsPayload={this.props.analyticsPayload}
/>
);
}
return (
<SignUpForm
buttonHTML={this.props.buttonHTML}
onToLogin={this.props.onToLogin}
error={this.state.signUpStore.error}
onSignUp={this._onSignUp}
isLoading={this.state.signUpStore.status === STATUS_PENDING}
showPasswordField={this.props.showPasswordField}
/>
);
}
}
// WEBPACK FOOTER //
// ./src/js/app/components/signUp/SignUpContainer.js
|
src/svg-icons/image/blur-on.js
|
verdan/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBlurOn = (props) => (
<SvgIcon {...props}>
<path d="M6 13c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm0 4c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm0-8c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm-3 .5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM6 5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm15 5.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zM14 7c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0-3.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zm-11 10c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zm7 7c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zm0-17c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zM10 7c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0 5.5c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5zm8 .5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm0 4c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm0-8c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm0-4c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm3 8.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM14 17c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm0 3.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zm-4-12c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5zm0 8.5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm4-4.5c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5zm0-4c-.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.5z"/>
</SvgIcon>
);
ImageBlurOn = pure(ImageBlurOn);
ImageBlurOn.displayName = 'ImageBlurOn';
ImageBlurOn.muiName = 'SvgIcon';
export default ImageBlurOn;
|
src/components/EditList.js
|
p632-sp-2016/eDocLite
|
/**
* Created by parikhv on 4/10/16.
*/
import React, { Component } from 'react';
import { Input } from 'react-bootstrap';
/**
* This class represents the editor dropdown option for bsSize', 'bsStyle', 'ComponentWidth', 'alignment' for the compnent properties
*/
export default class EditList extends Component {
/**
* EditList dropdown UI render method
*/
render() {
let { value, name, options, onChange } = this.props;
const parse = event => {
return {value: {value: event.target.value, options}};
};
return (
<Input type="select" label={name} defaultValue={value} onChange={event => onChange(parse(event))} >
{options.map((opt, optKey) => {
return ( <option value={opt} key={optKey} >{opt}</option>);
})}
</Input>
);
}
}
|
src/components/Header/NavbarLink.js
|
cape-io/acf-client
|
import React from 'react'
import { Link } from 'redux-history-sync'
function NavbarLink({ children, className, component, href, to }) {
const Comp = component || Link
let Linkelement = (
<Comp to={to} className={className} activeStyle={{
color: '#A94545',
}}>
{children}
</Comp>
)
if (href) {
Linkelement = (
<a href={href}>
{children}
</a>
)
}
return Linkelement
}
export default NavbarLink
|
fields/types/select/SelectColumn.js
|
w01fgang/keystone
|
import React from 'react';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
var SelectColumn = React.createClass({
displayName: 'SelectColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
linkTo: React.PropTypes.string,
},
getValue () {
const value = this.props.data.fields[this.props.col.path];
const option = this.props.col.field.ops.filter(i => i.value === value)[0];
return option ? option.label : null;
},
render () {
const value = this.getValue();
const empty = !value && this.props.linkTo ? true : false;
return (
<ItemsTableCell>
<ItemsTableValue field={this.props.col.type} to={this.props.linkTo} empty={empty}>
{value}
</ItemsTableValue>
</ItemsTableCell>
);
},
});
module.exports = SelectColumn;
|
actor-apps/app-web/src/app/components/dialog/MessagesSection.react.js
|
way1989/actor-platform
|
import React from 'react';
import _ from 'lodash';
import VisibilityStore from 'stores/VisibilityStore';
import MessageActionCreators from 'actions/MessageActionCreators';
import MessageItem from 'components/common/MessageItem.react';
let _delayed = [];
let flushDelayed = () => {
_.forEach(_delayed, (p) => {
MessageActionCreators.setMessageShown(p.peer, p.message);
});
_delayed = [];
};
let flushDelayedDebounced = _.debounce(flushDelayed, 30, 100);
let lastMessageDate;
class MessagesSection extends React.Component {
static propTypes = {
messages: React.PropTypes.array.isRequired,
peer: React.PropTypes.object.isRequired
};
componentWillUnmount() {
VisibilityStore.removeChangeListener(this.onAppVisibilityChange);
}
constructor(props) {
super(props);
VisibilityStore.addChangeListener(this.onAppVisibilityChange);
}
getMessagesListItem = (message) => {
let date = new Date(message.fullDate),
dateDivider;
const month = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
if (typeof lastMessageDate === 'undefined') {
lastMessageDate = new Date(message.fullDate);
}
const isNewDay = date.getDate() !== lastMessageDate.getDate();
if (isNewDay) {
dateDivider = (
<li className="date-divider">{month[date.getMonth()]} {date.getDate()}</li>
);
}
const messageItem = (
<MessageItem key={message.sortKey}
message={message}
newDay={isNewDay}
onVisibilityChange={this.onMessageVisibilityChange}
peer={this.props.peer}/>
);
lastMessageDate = new Date(message.fullDate);
return [dateDivider, messageItem];
}
onAppVisibilityChange = () => {
if (VisibilityStore.isVisible) {
flushDelayed();
}
}
onMessageVisibilityChange = (message, isVisible) => {
if (isVisible) {
_delayed.push({peer: this.props.peer, message: message});
if (VisibilityStore.isVisible) {
flushDelayedDebounced();
}
}
}
render() {
let messages = _.map(this.props.messages, this.getMessagesListItem);
return (
<ul className="messages">
{messages}
</ul>
);
}
}
export default MessagesSection;
|
shared/components/game/boardPanel/turnInfo.react.js
|
marek-sed/cogni
|
import React from 'react';
import moment from 'moment';
import 'moment-duration-format';
const colorMap = {
'': '#383830',
Sender: '#f92672',
Receiver: '#a6e22e' ,
Eavesdropper: '#f2971f'
}
const TurnInfo = ({player: {role}, currentRound: {onTurn}, roundTime}) => {
const roleColor = colorMap[role];
const observedRoleColor = '#f5f4f1';
role = role === 'Eavesdropper' ? 'ED' : role;
const observedRole = role === 'Sender' ? 'Receiver' : 'Sender';
const mineClassName = onTurn === role ? 'role-mine active-mine' : 'role-mine';
const observedClassName = onTurn === observedRole ? 'role-observed active-observed' : 'role-observed';
const formatTime = (time) => moment.duration(time, 'ms').format('ss');
return (
<div className="turn-info">
<div style={{color: roleColor}} className={mineClassName}>{role}</div>
<div className="time">{formatTime(roundTime)}</div>
<div style={{color: observedRoleColor}} className={observedClassName}>{observedRole}</div>
</div>
)
}
TurnInfo.defaultProps = {
myRole: 'Sender',
observedRole: 'Receiver',
onTurn: 'Sender'
}
export default TurnInfo;
|
examples/react/app/assets/javascripts/components/Counter/renderServer.js
|
jdlehman/js_render
|
import {renderToString} from 'react-dom/server';
import React from 'react';
import Counter from './index';
window.renderCounterServer = function(props) {
return renderToString(<Counter {...props} />);
};
|
site/pages/APIPage.js
|
hiddentao/react-dnd
|
import React from 'react';
import Header from '../components/Header';
import PageBody from '../components/PageBody';
import SideBar from '../components/SideBar';
import StaticHTMLBlock from '../components/StaticHTMLBlock';
import { APIPages } from '../Constants';
export default class APIPage {
render() {
return (
<div>
<Header/>
<PageBody hasSidebar>
<SideBar
groups={APIPages}
example={this.props.example}
/>
<StaticHTMLBlock html={this.props.html} />
</PageBody>
</div>
);
}
}
|
docs/app/Examples/modules/Sticky/Usage/index.js
|
shengnian/shengnian-ui-react
|
import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const StickyUsageExamples = () => (
<ExampleSection title='Usage'>
<ComponentExample
title='Sticky offset'
description='Define the offset from the top/bottom of the screen when fixing element to viewport.'
examplePath='modules/Sticky/Usage/StickyExampleOffset'
/>
</ExampleSection>
)
export default StickyUsageExamples
|
src/svg-icons/social/sentiment-satisfied.js
|
mmrtnz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialSentimentSatisfied = (props) => (
<SvgIcon {...props}>
<circle cx="15.5" cy="9.5" r="1.5"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm0-4c-1.48 0-2.75-.81-3.45-2H6.88c.8 2.05 2.79 3.5 5.12 3.5s4.32-1.45 5.12-3.5h-1.67c-.7 1.19-1.97 2-3.45 2z"/>
</SvgIcon>
);
SocialSentimentSatisfied = pure(SocialSentimentSatisfied);
SocialSentimentSatisfied.displayName = 'SocialSentimentSatisfied';
SocialSentimentSatisfied.muiName = 'SvgIcon';
export default SocialSentimentSatisfied;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.