path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
app/components/Toggle/index.js
|
gihrig/react-boilerplate
|
/**
*
* LocaleToggle
*
*/
import React from 'react';
import Select from './Select';
import ToggleOption from '../ToggleOption';
function Toggle(props) {
let content = (<option>--</option>);
// If we have items, render them
if (props.values) {
content = props.values.map((value) => (
<ToggleOption key={value} value={value} message={props.messages[value]} />
));
}
return (
<Select value={props.value} onChange={props.onToggle}>
{content}
</Select>
);
}
Toggle.propTypes = {
onToggle: React.PropTypes.func,
values: React.PropTypes.array,
value: React.PropTypes.string,
messages: React.PropTypes.object,
};
export default Toggle;
|
src/js/Codedojo/Not.js
|
pankiv/news
|
/**
* Created by Vasul on 03.10.2017.
*/
import React from 'react';
const Not = () => {
return (
<h1>Not fount</h1>
)
};
export default Not;
|
src/esm/components/graphics/icons/ellipsis-icon/index.js
|
KissKissBankBank/kitten
|
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["color", "title"];
import React from 'react';
import PropTypes from 'prop-types';
export var EllipsisIcon = function EllipsisIcon(_ref) {
var color = _ref.color,
title = _ref.title,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
return /*#__PURE__*/React.createElement("svg", _extends({
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 16 4",
width: "16",
height: "4",
fill: "none"
}, props), title && /*#__PURE__*/React.createElement("title", null, title), /*#__PURE__*/React.createElement("circle", {
cx: "2",
cy: "2",
r: "2",
fill: color
}), /*#__PURE__*/React.createElement("circle", {
cx: "8",
cy: "2",
r: "2",
fill: color
}), /*#__PURE__*/React.createElement("circle", {
cx: "14",
cy: "2",
r: "2",
fill: color
}));
};
EllipsisIcon.propTypes = {
color: PropTypes.string,
title: PropTypes.string
};
EllipsisIcon.defaultProps = {
color: '#222',
title: ''
};
|
test/PagerSpec.js
|
snadn/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Pager from '../src/Pager';
import PageItem from '../src/PageItem';
describe('Pager', function () {
it('Should output a unordered list as root element with class "pager"', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Pager/>
);
assert.equal(React.findDOMNode(instance).nodeName, 'UL');
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'pager'));
});
it('Should allow "PageItem" as child element', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Pager>
<PageItem href="#">Top</PageItem>
</Pager>
);
assert.equal(React.findDOMNode(instance).children.length, 1);
assert.equal(React.findDOMNode(instance).children[0].nodeName, 'LI');
});
it('Should allow multiple "PageItem" as child elements', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Pager>
<PageItem previous href="#">Previous</PageItem>
<PageItem disabled href="#">Top</PageItem>
<PageItem next href="#">Next</PageItem>
</Pager>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'previous'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'disabled'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'next'));
});
it('Should call "onSelect" when item is clicked', function (done) {
function handleSelect(key, href) {
assert.equal(key, 2);
assert.equal(href, '#next');
done();
}
let instance = ReactTestUtils.renderIntoDocument(
<Pager onSelect={handleSelect}>
<PageItem eventKey={1} href="#prev">Previous</PageItem>
<PageItem eventKey={2} href="#next">Next</PageItem>
</Pager>
);
let items = ReactTestUtils.scryRenderedComponentsWithType(instance, PageItem);
ReactTestUtils.Simulate.click(
ReactTestUtils.findRenderedDOMComponentWithTag(items[1], 'a')
);
});
});
|
pkg/interface/chat/src/js/components/lib/backlog-element.js
|
ngzax/urbit
|
import React, { Component } from 'react';
import classnames from 'classnames';
export class BacklogElement extends Component {
render() {
let props = this.props;
return (
<div className="center mw6">
<div className="db pa3 ma3 ba b--gray4 bg-gray5 b--gray2-d bg-gray1-d white-d flex items-center">
<img className="invert-d spin-active v-mid"
src="/~chat/img/Spinner.png"
width={16}
height={16}
/>
<p className="lh-copy db ml3">
Past messages are being restored
</p>
</div>
</div>
);
}
}
|
src/pages/vida-bela.js
|
vitorbarbosa19/ziro-online
|
import React from 'react'
import BrandGallery from '../components/BrandGallery'
export default () => (
<BrandGallery brand='Vida Bela' />
)
|
src/components/TextInputBEM/TextInputBEM.js
|
coryhouse/ps-react
|
import React from 'react';
import PropTypes from 'prop-types';
import Label from '../Label';
/** Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker. */
function TextInput({htmlId, name, label, type = "text", required = false, onChange, placeholder, value, error, children, ...props}) {
return (
<div className="textinput">
<Label htmlFor={htmlId} label={label} required={required} />
<input
id={htmlId}
type={type}
name={name}
placeholder={placeholder}
value={value}
onChange={onChange}
className={error && 'textinput__input--state-error'}
{...props}/>
{children}
{error && <div className="textinput__error">{error}</div>}
</div>
);
};
TextInput.propTypes = {
/** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */
htmlId: PropTypes.string.isRequired,
/** Input name. Recommend setting this to match object's property so a single change handler can be used. */
name: PropTypes.string.isRequired,
/** Input label */
label: PropTypes.string.isRequired,
/** Input type */
type: PropTypes.oneOf(['text', 'number', 'password']),
/** Mark label with asterisk if set to true */
required: PropTypes.bool,
/** Function to call onChange */
onChange: PropTypes.func.isRequired,
/** Placeholder to display when empty */
placeholder: PropTypes.string,
/** Value */
value: PropTypes.any,
/** String to display when error occurs */
error: PropTypes.string,
/** Child component to display next to the input */
children: PropTypes.node
};
export default TextInput;
|
client/vehicle-finder-spa/src/containers/user-management/single-user.js
|
Del7a/vehicle-finder
|
import React, { Component } from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {setCurrentUser, formChanged} from '../../actions/user';
import {updateSingleUser} from '../../actions/user-management';
import Form from '../../components/profile/info';
class SingleUser extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.formInputChanged = this.formInputChanged.bind(this);
}
componentDidMount() {
if(this.props.match.params.userId) {
const userId = this.props.match.params.userId
const user = this.getCurretnUseFromManagementState(this.props.userManagement.allUsers, userId);
if(user.length > 0) {
this.props.setCurrentUser(user[0]);
}
}
}
handleSubmit(ev) {
ev.preventDefault();
const userId = this.props.match.params.userId
const user = this.getCurretnUseFromManagementState(this.props.userManagement.allUsers, userId)
const userForSubmit = {...user[0], username: this.props.user.username,
email: this.props.user.username,
firstName: this.props.user.firstName,
lastName: this.props.user.lastName
}
this.props.updateSingleUser(userForSubmit)
}
formInputChanged(newFormState) {
this.props.formChanged(newFormState);
}
getCurretnUseFromManagementState(allUsers, targetUserId)
{
return allUsers.filter(function(usr) {
return usr._id === targetUserId
})
}
render(){
const infoMessage = this.props.userManagement.currentInfoMessage !== '' ?
<div className="alert alert-success">
<strong>Success!</strong> {this.props.userManagement.currentInfoMessage}
</div>
: ''
const errorMessage = this.props.userManagement.currentErrorMessage !== '' ?
<div className="alert alert-danger">
{this.props.userManagement.currentErrorMessage}
</div>
: ''
return(
<div>
{infoMessage}
{errorMessage}
{<Form
username={this.props.user.username}
email={this.props.user.email}
firstName={this.props.user.firstName}
lastName={this.props.user.lastName}
handleSubmit={this.handleSubmit}
formInputChanged={this.formInputChanged}
/>}
</div>
)
}
}
function mapStateToProps({user, userManagement}) {
return {user, userManagement};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({formChanged,updateSingleUser, setCurrentUser}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(SingleUser);
|
app/routes/method/CreateRoute.js
|
ryrudnev/dss-wm
|
import React from 'react';
import Helmet from 'react-helmet';
import { Route } from '../../core/router';
import { Model as Method } from '../../entities/Method';
import { Collection as MethodTypes } from '../../entities/MethodType';
import { PageHeader, Row, Col, Panel } from 'react-bootstrap';
import MethodForm from '../../components/MethodForm';
import Progress from 'react-progress-2';
import radio from 'backbone.radio';
const router = radio.channel('router');
export default class MethodCreateRoute extends Route {
breadcrumb = 'Создать способ управления отходами'
onCancel() {
router.request('navigate', `companies/${this.companyFid}`);
}
fetch({ params }) {
this.companyFid = params.fid;
this.methodTypes = new MethodTypes;
return this.methodTypes.fetch();
}
onSubmit(values) {
Progress.show();
const method = new Method(values);
method.forSubjectParam(this.companyFid);
method.save({}, {
success: model => {
Progress.hide();
router.request('navigate', `companies/${this.companyFid}/methods/${model.id}`);
},
});
}
render() {
return (
<div>
<Helmet title="Создание способа управления отходами" />
<PageHeader>Создание способа управления отходами</PageHeader>
<Row>
<Col md={8}>
<Panel>
<MethodForm
create
onSubmit={(values) => this.onSubmit(values)}
onCancel={() => this.onCancel()}
methodTypes={this.methodTypes.toJSON()}
/>
</Panel>
</Col>
</Row>
</div>
);
}
}
|
docs/src/NotFoundPage.js
|
egauci/react-bootstrap
|
import React from 'react';
import NavMain from './NavMain';
import PageHeader from './PageHeader';
import PageFooter from './PageFooter';
const NotFoundPage = React.createClass({
render() {
return (
<div>
<NavMain activePage="" />
<PageHeader
title="404"
subTitle="Hmmm this is awkward." />
<PageFooter />
</div>
);
}
});
export default NotFoundPage;
|
app/containers/LoginPage/index.js
|
gitlab-classroom/classroom-web
|
/*
*
* LoginPage
*
*/
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import styled from 'styled-components';
import selectLoginPage from './selectors';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
import Paper from 'material-ui/Paper';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import { setAppbar } from '../Header/actions';
import { actions as sessionActions } from '../../apis/session';
import { actions as loginPageActions } from './actions';
import Img from '../../components/Img';
import AvatarImg from '../../avatar.jpg';
const PageContainer = styled.div`
display: flex;
flex-direction: column;
`;
const HeaderMessage = styled.h1`
align-self: center;
font-size: 38px;
color: #555;
font-weight: 300;
letter-spacing: 1px;
`;
const LoginContainer = styled(Paper)`
width: 354px;
padding: 40px;
margin-bottom: 80px;
background-color: #f7f7f7;
text-align: center;
align-self: center;
display: flex;
flex-direction: column;
`;
const StyledAvatar = styled(Img)`
width: 96px;
height: 96px;
align-self: center;
border-radius: 48px;
`;
export class LoginPage extends React.Component { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
setAppbar: React.PropTypes.func,
login: React.PropTypes.func,
testLogin: React.PropTypes.func,
}
state = {
username: '',
password: '',
}
componentDidMount() {
this.props.setAppbar({
hide: true,
});
this.props.testLogin();
}
handleUsernameChanged = (event) => {
this.setState({
username: event.target.value,
});
}
handlePasswordChanged = (event) => {
this.setState({
password: event.target.value,
});
}
handleLogin = () => {
const { username, password } = this.state;
this.props.login({
username,
password,
});
}
render() {
return (
<PageContainer>
<HeaderMessage>
<FormattedMessage {...messages.header} />
</HeaderMessage>
<LoginContainer zDepth={1} style={{ backgroundColor: '#f7f7f7' }}>
<StyledAvatar src={AvatarImg} alt="Avatar" />
<TextField
floatingLabelText={<FormattedMessage {...messages.username} />}
style={{ width: '100%' }}
onChange={this.handleUsernameChanged}
/>
<TextField
floatingLabelText={<FormattedMessage {...messages.password} />}
type="password"
style={{ width: '100%', marginTop: -16, marginBottom: 16 }}
onChange={this.handlePasswordChanged}
/>
<RaisedButton
primary
label={<FormattedMessage {...messages.login} />}
onTouchTap={this.handleLogin}
/>
</LoginContainer>
</PageContainer>
);
}
}
const mapStateToProps = selectLoginPage();
function mapDispatchToProps(dispatch) {
return bindActionCreators({
setAppbar,
login: sessionActions.login,
testLogin: loginPageActions.testLogin,
}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(LoginPage);
|
docs/src/app/components/pages/components/Card/ExampleControlled.js
|
ArcanisCz/material-ui
|
import React from 'react';
import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import Toggle from 'material-ui/Toggle';
export default class CardExampleControlled extends React.Component {
constructor(props) {
super(props);
this.state = {
expanded: false,
};
}
handleExpandChange = (expanded) => {
this.setState({expanded: expanded});
};
handleToggle = (event, toggle) => {
this.setState({expanded: toggle});
};
handleExpand = () => {
this.setState({expanded: true});
};
handleReduce = () => {
this.setState({expanded: false});
};
render() {
return (
<Card expanded={this.state.expanded} onExpandChange={this.handleExpandChange}>
<CardHeader
title="URL Avatar"
subtitle="Subtitle"
avatar="images/ok-128.jpg"
actAsExpander={true}
showExpandableButton={true}
/>
<CardText>
<Toggle
toggled={this.state.expanded}
onToggle={this.handleToggle}
labelPosition="right"
label="This toggle controls the expanded state of the component."
/>
</CardText>
<CardMedia
expandable={true}
overlay={<CardTitle title="Overlay title" subtitle="Overlay subtitle" />}
>
<img src="images/nature-600-337.jpg" />
</CardMedia>
<CardTitle title="Card title" subtitle="Card subtitle" expandable={true} />
<CardText expandable={true}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi.
Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque.
Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio.
</CardText>
<CardActions>
<FlatButton label="Expand" onTouchTap={this.handleExpand} />
<FlatButton label="Reduce" onTouchTap={this.handleReduce} />
</CardActions>
</Card>
);
}
}
|
fields/types/titleposition/TitlePositionField.js
|
nickhsine/keystone
|
import Field from '../Field';
import React from 'react';
import Select from 'react-select';
import { FormInput } from 'elemental';
import cx from 'classnames';
/**
* TODO:
* - Custom path support
*/
const CENTER = 'center';
const BOTTOM = 'bottom';
const BOTTOMLEFT = 'bottom-left';
const imageSrc = {
[CENTER]:'title-center',
[BOTTOM]:'title-bottom',
[BOTTOMLEFT]:'title-bottonLeft',
'title-upon-left': 'title-upon-left',
'title-above': 'title-above',
'header-upon': 'header-upon',
'header-above': 'header-above'
};
module.exports = Field.create({
displayName: 'TitlePositionField',
generateRadioGroup (nameValue, ops, value) {
return ops.map((obj, i) => {
const imgStyle = cx({
'image-content': true,
'current': obj.value === value
})
return (
<label key={i} className="col-4 image-container">
<input type="radio" name={nameValue} value={obj.value} />
<img
className={imgStyle}
src={`https://storage.googleapis.com/twreporter-multimedia/images/${imageSrc[obj.value]}.png`}
onClick={() => { this.valueChanged(obj.value); }}
style={{
objectFit: 'cover',
width: '100%',
height: '100%'
}}
/>
</label>
);
});
},
valueChanged (newValue) {
// TODO: This should be natively handled by the Select component
if (this.props.numeric && typeof newValue === 'string') {
newValue = newValue ? Number(newValue) : undefined;
}
this.props.onChange({
path: this.props.path,
value: newValue,
});
this.setState({ active: newValue });
},
renderValue () {
var selected = this.props.ops.find(option => option.value === this.props.value);
return <FormInput noedit>{selected ? selected.label : null}</FormInput>;
},
renderField () {
// TODO: This should be natively handled by the Select component
var ops = (this.props.numeric) ? this.props.ops.map(function (i) { return { label: i.label, value: String(i.value) }; }) : this.props.ops;
var value = (typeof this.props.value === 'number') ? String(this.props.value) : this.props.value;
return <div className="row">{this.generateRadioGroup(this.props.path, ops, value)}</div>;
},
});
|
src/components/Page/BlankState/BlankState.specs.js
|
auth0-extensions/auth0-extension-ui
|
import React from 'react';
import { mount } from 'enzyme';
import { expect } from 'chai';
import BlankState from './';
const { describe, it } = global;
describe('BlankState', () => {
const field = {
title: 'The title',
iconImage: (
<div className="no-content-image">
no image
</div>
),
description: 'The description.'
};
let wrapper;
describe('test elements', () => {
beforeEach((done) => {
wrapper = mount(
<BlankState
title={field.title}
iconImage={field.iconImage}
description={field.description}
>
This is the BlankState children (this usually have buttons as children).
</BlankState>
);
done();
});
it('should render a no-content-section', () => {
expect(wrapper.find('.no-content-section')).to.have.length(1);
});
it('should show title, image field and description', () => {
expect(wrapper.find('.title').text()).to.equal(field.title);
expect(wrapper.find('.description').text()).to.equal(field.description);
expect(wrapper.find('.no-content-image').length).to.equal(1);
});
it('should have children', () => {
expect(wrapper.find('.button-container').length).to.be.above(0);
});
});
});
|
V2-Node/esquenta.v2/UI/src/views/Base/Collapses/Collapses.js
|
leandrocristovao/esquenta
|
import React, { Component } from 'react';
import { Badge, Button, Card, CardBody, CardFooter, CardHeader, Col, Collapse, Fade, Row } from 'reactstrap';
class Collapses extends Component {
constructor(props) {
super(props);
this.onEntering = this.onEntering.bind(this);
this.onEntered = this.onEntered.bind(this);
this.onExiting = this.onExiting.bind(this);
this.onExited = this.onExited.bind(this);
this.toggle = this.toggle.bind(this);
this.toggleAccordion = this.toggleAccordion.bind(this);
this.toggleCustom = this.toggleCustom.bind(this);
this.toggleFade = this.toggleFade.bind(this);
this.state = {
collapse: false,
accordion: [true, false, false],
custom: [true, false],
status: 'Closed',
fadeIn: true,
timeout: 300,
};
}
onEntering() {
this.setState({ status: 'Opening...' });
}
onEntered() {
this.setState({ status: 'Opened' });
}
onExiting() {
this.setState({ status: 'Closing...' });
}
onExited() {
this.setState({ status: 'Closed' });
}
toggle() {
this.setState({ collapse: !this.state.collapse });
}
toggleAccordion(tab) {
const prevState = this.state.accordion;
const state = prevState.map((x, index) => tab === index ? !x : false);
this.setState({
accordion: state,
});
}
toggleCustom(tab) {
const prevState = this.state.custom;
const state = prevState.map((x, index) => tab === index ? !x : false);
this.setState({
custom: state,
});
}
toggleFade() {
this.setState({ fadeIn: !this.state.fadeIn });
}
render() {
return (
<div className="animated fadeIn">
<Row>
<Col xl="6">
<Card>
<CardHeader>
<i className="fa fa-align-justify"></i><strong>Collapse</strong>
<div className="card-header-actions">
<a href="https://reactstrap.github.io/components/collapse/" rel="noreferrer noopener" target="_blank" className="card-header-action">
<small className="text-muted">docs</small>
</a>
</div>
</CardHeader>
<Collapse isOpen={this.state.collapse} onEntering={this.onEntering} onEntered={this.onEntered} onExiting={this.onExiting} onExited={this.onExited}>
<CardBody>
<p>
Anim pariatur cliche reprehenderit,
enim eiusmod high life accusamus terry richardson ad squid. Nihil
anim keffiyeh helvetica, craft beer labore wes anderson cred
nesciunt sapiente ea proident.
</p>
<p>
Donec molestie odio id nisi malesuada, mattis tincidunt velit egestas. Sed non pulvinar risus. Aenean
elementum eleifend nunc, pellentesque dapibus arcu hendrerit fringilla. Aliquam in nibh massa. Cras
ultricies lorem non enim volutpat, a eleifend urna placerat. Fusce id luctus urna. In sed leo tellus.
Mauris tristique leo a nisl feugiat, eget vehicula leo venenatis. Quisque magna metus, luctus quis
sollicitudin vel, vehicula nec ipsum. Donec rutrum commodo lacus ut condimentum. Integer vel turpis
purus. Etiam vehicula, nulla non fringilla blandit, massa purus faucibus tellus, a luctus enim orci non
augue. Aenean ullamcorper nisl urna, non feugiat tortor volutpat in. Vivamus lobortis massa dolor, eget
faucibus ipsum varius eget. Pellentesque imperdiet, turpis sed sagittis lobortis, leo elit laoreet arcu,
vehicula sagittis elit leo id nisi.
</p>
</CardBody>
</Collapse>
<CardFooter>
<Button color="primary" onClick={this.toggle} style={{ marginBottom: '1rem' }}>Toggle</Button>
<h5>Current state: {this.state.status}</h5>
</CardFooter>
</Card>
<Card>
<CardHeader>
<i className="fa fa-align-justify"></i><strong>Fade</strong>
<div className="card-header-actions">
<a href="https://reactstrap.github.io/components/fade/" rel="noreferrer noopener" target="_blank" className="card-header-action">
<small className="text-muted">docs</small>
</a>
</div>
</CardHeader>
<CardBody>
<Fade timeout={this.state.timeout} in={this.state.fadeIn} tag="h5" className="mt-3">
This content will fade in and out as the button is pressed...
</Fade>
</CardBody>
<CardFooter>
<Button color="primary" onClick={this.toggleFade}>Toggle Fade</Button>
</CardFooter>
</Card>
</Col>
<Col xl="6">
<Card>
<CardHeader>
<i className="fa fa-align-justify"></i> Collapse <small>accordion</small>
<div className="card-header-actions">
<Badge>NEW</Badge>
</div>
</CardHeader>
<CardBody>
<div id="accordion">
<Card>
<CardHeader id="headingOne">
<Button block color="link" className="text-left m-0 p-0" onClick={() => this.toggleAccordion(0)} aria-expanded={this.state.accordion[0]} aria-controls="collapseOne">
<h5 className="m-0 p-0">Collapsible Group Item #1</h5>
</Button>
</CardHeader>
<Collapse isOpen={this.state.accordion[0]} data-parent="#accordion" id="collapseOne" aria-labelledby="headingOne">
<CardBody>
1. Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non
cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred
nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft
beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</CardBody>
</Collapse>
</Card>
<Card>
<CardHeader id="headingTwo">
<Button block color="link" className="text-left m-0 p-0" onClick={() => this.toggleAccordion(1)} aria-expanded={this.state.accordion[1]} aria-controls="collapseTwo">
<h5 className="m-0 p-0">Collapsible Group Item #2</h5>
</Button>
</CardHeader>
<Collapse isOpen={this.state.accordion[1]} data-parent="#accordion" id="collapseTwo">
<CardBody>
2. Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non
cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred
nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft
beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</CardBody>
</Collapse>
</Card>
<Card>
<CardHeader id="headingThree">
<Button block color="link" className="text-left m-0 p-0" onClick={() => this.toggleAccordion(2)} aria-expanded={this.state.accordion[2]} aria-controls="collapseThree">
<h5 className="m-0 p-0">Collapsible Group Item #3</h5>
</Button>
</CardHeader>
<Collapse isOpen={this.state.accordion[2]} data-parent="#accordion" id="collapseThree">
<CardBody>
3. Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non
cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred
nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft
beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</CardBody>
</Collapse>
</Card>
</div>
</CardBody>
</Card>
<Card>
<CardHeader>
<i className="fa fa-align-justify"></i> Collapse <small>custom accordion</small>
<div className="card-header-actions">
<Badge>NEW</Badge>
</div>
</CardHeader>
<CardBody>
<div id="exampleAccordion" data-children=".item">
<div className="item">
<Button className="m-0 p-0" color="link" onClick={() => this.toggleCustom(0)} aria-expanded={this.state.custom[0]} aria-controls="exampleAccordion1">
Toggle item
</Button>
<Collapse isOpen={this.state.custom[0]} data-parent="#exampleAccordion" id="exampleAccordion1">
<p className="mb-3">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed pretium lorem non vestibulum scelerisque. Proin a vestibulum sem, eget
tristique massa. Aliquam lacinia rhoncus nibh quis ornare.
</p>
</Collapse>
</div>
<div className="item">
<Button className="m-0 p-0" color="link" onClick={() => this.toggleCustom(1)} aria-expanded={this.state.custom[1]} aria-controls="exampleAccordion2">
Toggle item 2
</Button>
<Collapse isOpen={this.state.custom[1]} data-parent="#exampleAccordion" id="exampleAccordion2">
<p className="mb-3">
Donec at ipsum dignissim, rutrum turpis scelerisque, tristique lectus. Pellentesque habitant morbi tristique senectus et netus et
malesuada fames ac turpis egestas. Vivamus nec dui turpis. Orci varius natoque penatibus et magnis dis parturient montes,
nascetur ridiculus mus.
</p>
</Collapse>
</div>
</div>
</CardBody>
</Card>
</Col>
</Row>
</div>
);
}
}
export default Collapses;
|
fixtures/nesting/src/modern/App.js
|
cpojer/react
|
import React from 'react';
import {useState, Suspense} from 'react';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import HomePage from './HomePage';
import AboutPage from './AboutPage';
import ThemeContext from './shared/ThemeContext';
export default function App() {
const [theme, setTheme] = useState('slategrey');
function handleToggleClick() {
if (theme === 'slategrey') {
setTheme('hotpink');
} else {
setTheme('slategrey');
}
}
return (
<BrowserRouter>
<ThemeContext.Provider value={theme}>
<div style={{fontFamily: 'sans-serif'}}>
<div
style={{
margin: 20,
padding: 20,
border: '1px solid black',
minHeight: 300,
}}>
<button onClick={handleToggleClick}>Toggle Theme Context</button>
<br />
<Suspense fallback={<Spinner />}>
<Switch>
<Route path="/about">
<AboutPage />
</Route>
<Route path="/">
<HomePage />
</Route>
</Switch>
</Suspense>
</div>
</div>
</ThemeContext.Provider>
</BrowserRouter>
);
}
function Spinner() {
return null;
}
|
app/timer/timer.page.js
|
kosich/pomodoro-pi
|
// @flow
import React, { Component } from 'react';
import Timer from './timer.component.js';
export default class TimerPage extends Component {
render() {
return (
<Timer />
);
}
}
|
src/svg-icons/av/video-label.js
|
owencm/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvVideoLabel = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 13H3V5h18v11z"/>
</SvgIcon>
);
AvVideoLabel = pure(AvVideoLabel);
AvVideoLabel.displayName = 'AvVideoLabel';
AvVideoLabel.muiName = 'SvgIcon';
export default AvVideoLabel;
|
stories/components/label/index.js
|
NestorSegura/operationcode_frontend
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import Label from 'shared/components/label/label';
storiesOf('shared/components/label', module)
.add('Default', () => (
<div
style={{
marginTop: '12px',
display: 'flex',
flexDirection: 'row',
justifyContent: 'center',
}}
>
<input type="checkbox" id="check" />
<Label
htmlFor="check"
style={{ marginLeft: '16px' }}
>
clickable
</Label>
</div>
));
|
src/components/Tos/ImportView/__tests__/importView.spec.js
|
City-of-Helsinki/helerm-ui
|
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import Enzyme, { mount } from 'enzyme';
import React from 'react';
import { ImportView } from '../ImportView';
Enzyme.configure({ adapter: new Adapter() });
describe('(Component) ImportView', () => {
let _wrapper;
beforeEach(() => {
_wrapper = mount(
<ImportView
level='phase'
title={''}
targetText={''}
itemsToImportText={''}
phases={{}}
phasesOrder={[]}
actions={{}}
records={{}}
importItems={() => null}
toggleImportView={() => null}
/>
);
});
it('Passes level prop correctly', () => {
expect(_wrapper.props().level).toBeDefined();
expect(_wrapper.prop('level')).toEqual('phase');
});
});
|
www/js/components/Sidebar.js
|
grant/CSE-The-Game
|
import React, { Component } from 'react';
const sidebarItems = [
{
id: 'item1',
name: 'Item 1',
subitems: [{
id: 'subitem1',
name: 'Subitem 1',
}, {
id: 'subitem2',
name: 'Sub 2',
subitems: [{
id: 'subsubitem1',
name: 'sub sub item 1',
}],
}],
},
{
id: 'item2',
name: 'Item 2',
},
];
/**
* A list of buttons on the left side of the screen.
*/
class Sidebar extends Component {
static propTypes = {};
constructor() {
super();
this.state = {
// value at index _n_ is the selection (index of item selected in that column) at column _n_
// so [2, 0] would mean column[0][2] and column[1][0] are selected.
selection: [],
};
}
onItemClick(id:string, columnIndex:number, rowIndex:number) {
// Update the selection to reflect the click
let selection = this.state.selection;
let selectionDepth = selection.length;
if (columnIndex === selectionDepth) {
// If clicked on columnIndex at selectionDepth, expand deeper selection
selection.push(rowIndex);
} else if (columnIndex < selectionDepth) {
if (selection.length - 1 === columnIndex && selection[columnIndex] === rowIndex) {
// Deselect deepest selection
selection.pop();
} else {
// Unselect all up until column index
selection.length = columnIndex;
// Push new shallow selection
selection.push(rowIndex);
}
}
// If clicked on selection, disable the selection
// Update the selection
this.setState({
selection: selection,
});
}
render() {
let state = this.state;
// Subcomponents
let createSidebarItem = (sidebarItem:Object, columnIndex:number, rowIndex:number) => {
let id = sidebarItem.id;
let selected = (columnIndex < state.selection.length && state.selection[columnIndex] === rowIndex) ? 'selected' : '';
return (
<li
className={`${id} sidebarItem ${selected}`}
onClick={this.onItemClick.bind(this, id, columnIndex, rowIndex)}
>
<img className='icon' src={`img/sidebar/${id}.png`}/>
<span className='title'>
{sidebarItem.name}
</span>
</li>
);
};
// Populate column data (note the <=)
let sidebarColumnData = [];
let currentColumn = sidebarItems;
for (let columnIndex = 0; columnIndex <= state.selection.length; ++columnIndex) {
// Push current column if exists
if (currentColumn) {
sidebarColumnData.push(currentColumn);
}
// Look at next selection column
if (columnIndex != state.selection.length) {
currentColumn = currentColumn[state.selection[columnIndex]].subitems;
}
}
return (
<ul
className="Sidebar"
>
{sidebarColumnData.map((columnData, columnIndex) => {
return (
<div className={`column ${columnIndex}`}>
{columnData.map(function (columnDatum, rowIndex) {
return createSidebarItem(columnDatum, columnIndex, rowIndex);
})}
</div>
);
})}
</ul>
);
}
}
export default Sidebar;
|
App/Client/Component/person.js
|
qianyuchang/React-Chat
|
import React from 'react'
import { mockData } from './mockData'
const ArrowIcon=React.createClass({
render:function(){
return(
<i className="arrow fa fa-angle-right"></i>
);
}
});
const QrcodeIcon=React.createClass({
render:function(){
return(
<i className="qrcode fa fa-qrcode"></i>
);
}
});
const SettingItem=React.createClass({
render:function () {
return(
<li className="settingItem">
<span className="icon"><i className={this.props.icon}></i></span>
<span className="settingName">{this.props.children}</span>
<ArrowIcon/>
</li>)
}
});
const SocialGroup=React.createClass({
render:function () {
return(
<ul className="socialGroup tabGroup">
<SettingItem icon="fa fa-picture-o">相册</SettingItem>
</ul>
)
}
});
const SettingGroup=React.createClass({
render:function () {
return(
<div className="settingGroup tabGroup">
<SettingItem icon="fa fa-cog">设置</SettingItem>
</div>
);
}
});
const Account=React.createClass({
getInitialState:function(){
return{
data:{}
}
},
componentDidMount:function(){
this.setState({
data:mockData.AccountInfo
});
},
render:function(){
var that=this;
return(
<div className="account">
<div className="headImage"><img src={that.state.data.headImage} width="60"/></div>
<div className="accountInfo">
<div className="nickName">{that.state.data.nickName}</div>
<div className="accountNumber">{that.state.data.token}</div>
</div>
<QrcodeIcon/>
<ArrowIcon/>
</div>
);
}
});
const Person=React.createClass({
render:function(){
return(
<div className="person">
<Account/>
<SocialGroup/>
<SettingGroup/>
</div>
);
}
});
export default Person;
|
src/collections/Form/FormSelect.js
|
aabustamante/Semantic-UI-React
|
import React from 'react'
import {
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
import Select from '../../addons/Select'
import FormField from './FormField'
/**
* Sugar for <Form.Field control={Select} />.
* @see Form
* @see Select
*/
function FormSelect(props) {
const { control } = props
const rest = getUnhandledProps(FormSelect, props)
const ElementType = getElementType(FormSelect, props)
return <ElementType {...rest} control={control} />
}
FormSelect._meta = {
name: 'FormSelect',
parent: 'Form',
type: META.TYPES.COLLECTION,
}
FormSelect.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** A FormField control prop. */
control: FormField.propTypes.control,
}
FormSelect.defaultProps = {
as: FormField,
control: Select,
}
export default FormSelect
|
video-player/src/components/SearchBar.js
|
HeroSizy/Modern-react-with-redux
|
import React from 'react'
import { Component } from 'react'
class SearchBar extends Component {
constructor(props){
super(props);
//only can manipulate state using '='
//in constructor
this.state = { term: '' };
//to not lose context, use bind
this.onInputChange = this.onInputChange.bind(this);
}
onInputChange(event) {
const term = event.target.value;
//event.target.value => ge t the value
//on the element who triggers the event
// console.log(event.target.value);
this.setState({term});
this.props.onSearchTermChange(term);
}
render() {
return(
<div className="search-bar">
<input
value = {this.state.term}
onChange={this.onInputChange}
/>
<br />
input: {this.state.term}
</div>
);
}
}
export default SearchBar
|
packages/material-ui-icons/src/InsertLink.js
|
cherniavskii/material-ui
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z" /></g>
, 'InsertLink');
|
sample-app/EmployeeDirectory/index.ios.js
|
TGPSKI/cavy
|
import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import { Provider } from 'react-redux';
import { reduxForm } from 'redux-form';
import { Tester, TestHookStore } from 'cavy';
import EmployeeDirectoryApp from 'App/EmployeeDirectoryApp';
import GLOBAL from 'Helpers/globals.js';
if (GLOBAL.TEST_ENABLED) {
var testHookStore = new TestHookStore();
var testSuites = require('Specs/itSuites.js');
var testSuitesArray = [testSuites.filterEmployeeList, testSuites.tapAndEmail];
}
const { store } = () => {
return { form: reduxForm() };
};
class AppWrapper extends Component {
render() {
if (GLOBAL.TEST_ENABLED) {
return (
<Provider store={store}>
<Tester
suites={testSuitesArray}
store={testHookStore}
waitTime={1000}
testStartDelay={1000}
consoleLog={true}
reporter={true}
reRender={true}
reduxStore={store}
>
<EmployeeDirectoryApp />
</Tester>
</Provider>
);
} else {
return (
<Provider store={store}>
<EmployeeDirectoryApp />
</Provider>
);
}
}
}
AppRegistry.registerComponent('EmployeeDirectory', () => AppWrapper);
|
fields/types/azurefile/AzureFileColumn.js
|
asifiqbal84/keystone
|
import React from 'react';
var AzureFileColumn = React.createClass({
renderValue () {
var value = this.props.data.fields[this.props.col.path];
if (!value) return;
return <a href={value.url} target='_blank'>{value.url}</a>;
},
render () {
return (
<td className="ItemList__col">
<div className="ItemList__value ItemList__value--azure-file">{this.renderValue()}</div>
</td>
);
}
});
module.exports = AzureFileColumn;
|
src/js/ui/components/welcome/signUpForm.js
|
heartnotes/heartnotes
|
import $ from 'jquery';
import _ from 'lodash';
import React from 'react';
import Button from '../button';
import ExternalLink from '../externalLink';
import ProgressButton from '../progressButton';
import EmailInput from '../emailInput';
import NewPasswordInput from '../newPasswordInput';
import UserShouldRememberPasswordDialog from '../userShouldRememberPasswordDialog';
import { connectRedux, routing } from '../../helpers/decorators';
import * as Detect from '../../../utils/detect';
const TERMS_URL = Detect.serverHost() + '/terms-and-conditions';
var Component = React.createClass({
propTypes: {
onCreate: React.PropTypes.func.isRequired,
progressCheckVar: React.PropTypes.object.isRequired,
createButtonText: React.PropTypes.string,
},
getDefaultProps: function() {
return {
createButtonText: 'Sign up',
};
},
getInitialState: function() {
return {
id: null,
password: null,
}
},
render: function() {
let { creating } = this.props.data.diary;
var buttonAttrs = {
defaultProgressMsg: 'Signing up...',
checkVar: this.props.progressCheckVar,
onClick: this._createNew,
};
if ( !this.state.terms ||
!_.get(this.state.password, 'length') ||
!_.get(this.state.id, 'length')
) {
buttonAttrs.disabled = true;
}
return (
<div className="sign-up-form">
<form onSubmit={this._createNew}>
<div className="input-fields row">
<EmailInput
onChange={this._setId}
disabled={this.props.progressCheckVar.inProgress}
tabIndex={1} />
</div>
<div className="input-fields row">
<NewPasswordInput
onChange={this._setPassword}
requiredStrength={0}
centeredStrengthMeter={true}
disabled={this.props.progressCheckVar.inProgress}
tabIndex={2} />
</div>
<div className="row terms">
<input type="checkbox" onChange={this._toggleTerms} />
<span>
I agree to the <ExternalLink href={TERMS_URL}>terms and conditions</ExternalLink>.
</span>
</div>
<div className="action row">
<ProgressButton {...buttonAttrs}>{this.props.createButtonText}</ProgressButton>
</div>
</form>
<UserShouldRememberPasswordDialog password={this.state.password} ref="rememberDialog" />
</div>
);
},
_setPassword: function(password) {
this.setState({
password: password
});
},
_setId: function(id) {
this.setState({
id: id,
});
},
_toggleTerms: function(e) {
let checked = $(e.currentTarget).is(':checked');
this.setState({
terms: !!checked,
});
},
_createNew: function(e) {
e.preventDefault();
this.refs.rememberDialog.ask((shouldProceed) => {
if (shouldProceed) {
this.props.onCreate(
this.state.id,
this.state.password
)
.then(() => {
this.setState(this.getInitialState());
});
}
});
},
});
module.exports = connectRedux([
'createDiary'
])(Component);
|
src/index.js
|
shibe97/react-awesome-modal
|
import React, { Component } from 'react';
import style from './style.js';
export default class Modal extends Component {
constructor(props) {
super(props);
let effect = props.effect || 'fadeInDown';
this.setSize(effect);
this.state = {
visible : props.visible,
style : style[effect]
}
}
componentWillReceiveProps({visible, effect = 'fadeInDown'}) {
this.setState({
visible : visible
});
this.setSize(effect);
this.setStyles(effect);
}
setStyles(effect){
if (this.props && this.props.styles) {
style[effect].panel = {
...style[effect].panel,
...this.props.styles
};
}
}
setSize(effect) {
if (this.props && this.props.width) {
if (this.props.width.charAt(this.props.width.length-1) === '%') {
// Use Percentage
const width = this.props.width.slice(0, -1);
style[effect].panel.width = width + '%';
} else if (this.props.width.charAt(this.props.width.length-1) === 'x') {
// Use Pixels
const width = this.props.width.slice(0, -2);
style[effect].panel.width = width + 'px';
} else {
// Defaults
style[effect].panel.width = this.props.width + 'px';
}
}
if (this.props && this.props.height) {
if (this.props.height.charAt(this.props.height.length-1) === '%') {
// Use Percentage
const height = this.props.height.slice(0, -1);
style[effect].panel.height = height + 'vh';
} else if (this.props.height.charAt(this.props.height.length-1) === 'x') {
// Use Pixels
const height = this.props.height.slice(0, -2);
style[effect].panel.height = height + 'px';
} else {
// Defaults
style[effect].panel.height = this.props.height + 'px';
}
}
}
render() {
return (
<div>
<div style={this.state.visible ? this.state.style.container : this.state.style.containerHidden}>
<div style={this.state.visible ? {...this.state.style.panel} : this.state.style.panelHidden}>
{this.props.children}
</div>
<div style={this.state.visible ? this.state.style.mask : this.state.style.maskHidden} onClick={this.props.onClickAway ? this.props.onClickAway : null} />
</div>
</div>
);
}
}
|
chrome/extension/inject.js
|
CKPalk/PA-POC-Video-Contoller
|
import React from 'react'
import ReactDOM from 'react-dom'
import VideoRoot from '../../app/containers/VideoRoot'
import { getUid } from '../../app/utils/helpers'
import { getState, onStateChange } from '../../app/utils/localStorage'
/**
* Whether this youtube video is currently an advertisement.
* @param {Object} video A HTML5 video element
* @return {Boolean} Whether the user is watching an ad
*/
async function videoIsAd(video) {
return !!video
}
function findBestContainer(video) {
const isGoodContainer = ({ offsetWidth, offsetHeight }) => (
offsetWidth === video.offsetWidth &&
offsetHeight === video.offsetHeight
)
let bestContainer = video.parentElement
let container = video.parentElement
while (container) {
if (isGoodContainer(container)) {
bestContainer = container
}
container = container.parentElement
}
return bestContainer
}
function renderOverlayForVideo(video) {
const mount = document.createElement('div')
mount.style.position = 'absolute'
mount.style.top = 0
mount.style.pointerEvents = 'none'
findBestContainer(video).appendChild(mount)
const adID = getUid()
const renderOverlayWithCurrentState = () => {
getState()
.then(state => {
ReactDOM.render(
<VideoRoot
appState={state}
video={video}
adID={adID}
/>,
mount
)
})
}
renderOverlayWithCurrentState()
// When the state changes, we render our overlay with the updated state
onStateChange(renderOverlayWithCurrentState)
}
function handleVideo(video) {
video.onloadstart = () => {
handleVideo(video)
}
if (videoIsAd(video)) {
renderOverlayForVideo(video)
}
}
function locateAndHandleVideos() {
const allVideos = Array(...document.getElementsByTagName('video'))
if (allVideos.length === 0) {
setTimeout(locateAndHandleVideos, 500)
return
}
allVideos.forEach(video => {
video.crossOrigin = 'anonymous'
if (video.readyState === 4) {
handleVideo(video)
} else {
video.onloadeddata = () => {
video.onloadeddata = () => {}
handleVideo(video)
}
}
})
}
window.addEventListener('load', locateAndHandleVideos)
|
web/app/containers/RepoListItem/index.js
|
agapic/TwitchChatStreaming
|
/**
* RepoListItem
*
* Lists the name and the issue count of a repository
*/
import React from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { FormattedNumber } from 'react-intl';
import IssueIcon from './IssueIcon';
import IssueLink from './IssueLink';
import ListItem from 'components/ListItem';
import RepoLink from './RepoLink';
import Wrapper from './Wrapper';
import { selectCurrentUser } from 'containers/App/selectors';
export class RepoListItem extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
const item = this.props.item;
let nameprefix = '';
// If the repository is owned by a different person than we got the data for
// it's a fork and we should show the name of the owner
if (item.owner.login !== this.props.currentUser) {
nameprefix = `${item.owner.login}/`;
}
// Put together the content of the repository
const content = (
<Wrapper>
<RepoLink href={item.html_url} target="_blank">
{nameprefix + item.name}
</RepoLink>
<IssueLink href={`${item.html_url}/issues`} target="_blank">
<IssueIcon />
<FormattedNumber value={item.open_issues_count} />
</IssueLink>
</Wrapper>
);
// Render the content into a list item
return (
<ListItem key={`repo-list-item-${item.full_name}`} item={content} />
);
}
}
RepoListItem.propTypes = {
item: React.PropTypes.object,
currentUser: React.PropTypes.string,
};
export default connect(createSelector(
selectCurrentUser(),
(currentUser) => ({ currentUser })
))(RepoListItem);
|
tp-4/euge/src/pages/posts/Listado.js
|
jpgonzalezquinteros/sovos-reactivo-2017
|
import React from 'react';
import PropTypes from 'prop-types';
import { Layout, Table, Button } from 'antd';
const { Content } = Layout;
const columns = [{
title: 'title',
dataIndex: 'title',
width: '30%',
}, {
title: 'body',
dataIndex: 'body',
width: '20%',
}];
class Listado extends React.Component {
state = {
showPostForm: false,
postSeleccionado: {}
}
componentWillMount(){
this.props.actions.fetchPosts();
}
handlePlusClick = () => {
this.setState({ postSeleccionado: null });
this.setState({ showPostForm: true });
}
handleCloseParametrosForm= () => {
this.setState({ showPostForm: false });
}
render() {
return (
<div className="content-inner">
<Layout >
<Content>
<Button className="editable-add-btn" onClick={this.handlePlusClick}>Nuevo Post</Button>
<Table
columns={columns}
rowKey={record => record.id}
dataSource={this.props.posts}
loading={this.props.trabajando}
/>
</Content>
</Layout>
</div>
);
}
}
Listado.propTypes = {
trabajando: PropTypes.bool.isRequired,
posts:PropTypes.array.isRequired,
actions: PropTypes.shape({
fetchPosts: PropTypes.func,
guardarPost: PropTypes.func,
eliminarPost: PropTypes.func,
}).isRequired,
};
Listado.defaultProps = {
trabajando: false,
posts:[]
};
export default Listado;
|
src/js/components/gallery/ImportAlbumPopup.js
|
nekuno/client
|
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { FACEBOOK_PHOTOS_SCOPE, GOOGLE_PHOTOS_SCOPE } from '../../constants/Constants';
import translate from '../../i18n/Translate';
@translate('ImportAlbumPopup')
export default class ImportAlbumPopup extends Component {
static propTypes = {
onAlbumClickHandler : PropTypes.func,
onFileUploadClickHandler: PropTypes.func,
contentRef: PropTypes.func,
// Injected by @translate:
strings : PropTypes.object
};
onResourceClick(resource, scope) {
this.props.onAlbumClickHandler(resource, scope);
}
render() {
const {contentRef, strings} = this.props;
return (
<div className="popup popup-import-album tablet-fullscreen">
<div ref={contentRef} className="content-block">
<div className="title">{strings.importAlbum}</div>
<br />
<div className="social-icons-row-wrapper social-box">
<div className="icon-wrapper text-facebook" onClick={this.onResourceClick.bind(this, 'facebook', FACEBOOK_PHOTOS_SCOPE)}>
<span className="icon icon-facebook"></span>
</div>
<div className="icon-wrapper text-google" onClick={this.onResourceClick.bind(this, 'google', GOOGLE_PHOTOS_SCOPE)}>
<span className="icon icon-google"></span>
</div>
</div>
<div className="upload-wrapper" onClick={this.props.onFileUploadClickHandler}>
<div className="button button-fill button-round">
<span className="icon icon-uploadthin"></span> <span className="">{strings.uploadFromDevice}</span>
</div>
</div>
</div>
</div>
);
}
}
ImportAlbumPopup.defaultProps = {
strings: {
close : 'Close',
importAlbum : 'Import an album',
uploadFromDevice: 'Upload from device'
}
};
|
12_ReactJS Fundamentals/01_contacter/src/index.js
|
akkirilov/SoftUniProject
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
app/javascript/mastodon/features/ui/components/media_modal.js
|
imas/mastodon
|
import React from 'react';
import ReactSwipeableViews from 'react-swipeable-views';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Video from 'mastodon/features/video';
import classNames from 'classnames';
import { defineMessages, injectIntl } from 'react-intl';
import IconButton from 'mastodon/components/icon_button';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ImageLoader from './image_loader';
import Icon from 'mastodon/components/icon';
import GIFV from 'mastodon/components/gifv';
import { disableSwiping } from 'mastodon/initial_state';
import Footer from 'mastodon/features/picture_in_picture/components/footer';
import { getAverageFromBlurhash } from 'mastodon/blurhash';
const messages = defineMessages({
close: { id: 'lightbox.close', defaultMessage: 'Close' },
previous: { id: 'lightbox.previous', defaultMessage: 'Previous' },
next: { id: 'lightbox.next', defaultMessage: 'Next' },
});
export const previewState = 'previewMediaModal';
export default @injectIntl
class MediaModal extends ImmutablePureComponent {
static propTypes = {
media: ImmutablePropTypes.list.isRequired,
statusId: PropTypes.string,
index: PropTypes.number.isRequired,
onClose: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
onChangeBackgroundColor: PropTypes.func.isRequired,
currentTime: PropTypes.number,
autoPlay: PropTypes.bool,
volume: PropTypes.number,
};
static contextTypes = {
router: PropTypes.object,
};
state = {
index: null,
navigationHidden: false,
zoomButtonHidden: false,
};
handleSwipe = (index) => {
this.setState({ index: index % this.props.media.size });
}
handleTransitionEnd = () => {
this.setState({
zoomButtonHidden: false,
});
}
handleNextClick = () => {
this.setState({
index: (this.getIndex() + 1) % this.props.media.size,
zoomButtonHidden: true,
});
}
handlePrevClick = () => {
this.setState({
index: (this.props.media.size + this.getIndex() - 1) % this.props.media.size,
zoomButtonHidden: true,
});
}
handleChangeIndex = (e) => {
const index = Number(e.currentTarget.getAttribute('data-index'));
this.setState({
index: index % this.props.media.size,
zoomButtonHidden: true,
});
}
handleKeyDown = (e) => {
switch(e.key) {
case 'ArrowLeft':
this.handlePrevClick();
e.preventDefault();
e.stopPropagation();
break;
case 'ArrowRight':
this.handleNextClick();
e.preventDefault();
e.stopPropagation();
break;
}
}
componentDidMount () {
window.addEventListener('keydown', this.handleKeyDown, false);
if (this.context.router) {
const history = this.context.router.history;
history.push(history.location.pathname, previewState);
this.unlistenHistory = history.listen(() => {
this.props.onClose();
});
}
this._sendBackgroundColor();
}
componentDidUpdate (prevProps, prevState) {
if (prevState.index !== this.state.index) {
this._sendBackgroundColor();
}
}
_sendBackgroundColor () {
const { media, onChangeBackgroundColor } = this.props;
const index = this.getIndex();
const blurhash = media.getIn([index, 'blurhash']);
if (blurhash) {
const backgroundColor = getAverageFromBlurhash(blurhash);
onChangeBackgroundColor(backgroundColor);
}
}
componentWillUnmount () {
window.removeEventListener('keydown', this.handleKeyDown);
if (this.context.router) {
this.unlistenHistory();
if (this.context.router.history.location.state === previewState) {
this.context.router.history.goBack();
}
}
this.props.onChangeBackgroundColor(null);
}
getIndex () {
return this.state.index !== null ? this.state.index : this.props.index;
}
toggleNavigation = () => {
this.setState(prevState => ({
navigationHidden: !prevState.navigationHidden,
}));
};
handleStatusClick = e => {
if (e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(`/statuses/${this.props.statusId}`);
}
}
render () {
const { media, statusId, intl, onClose } = this.props;
const { navigationHidden } = this.state;
const index = this.getIndex();
const leftNav = media.size > 1 && <button tabIndex='0' className='media-modal__nav media-modal__nav--left' onClick={this.handlePrevClick} aria-label={intl.formatMessage(messages.previous)}><Icon id='chevron-left' fixedWidth /></button>;
const rightNav = media.size > 1 && <button tabIndex='0' className='media-modal__nav media-modal__nav--right' onClick={this.handleNextClick} aria-label={intl.formatMessage(messages.next)}><Icon id='chevron-right' fixedWidth /></button>;
const content = media.map((image) => {
const width = image.getIn(['meta', 'original', 'width']) || null;
const height = image.getIn(['meta', 'original', 'height']) || null;
if (image.get('type') === 'image') {
return (
<ImageLoader
previewSrc={image.get('preview_url')}
src={image.get('url')}
width={width}
height={height}
alt={image.get('description')}
key={image.get('url')}
onClick={this.toggleNavigation}
zoomButtonHidden={this.state.zoomButtonHidden}
/>
);
} else if (image.get('type') === 'video') {
const { currentTime, autoPlay, volume } = this.props;
return (
<Video
preview={image.get('preview_url')}
blurhash={image.get('blurhash')}
src={image.get('url')}
width={image.get('width')}
height={image.get('height')}
frameRate={image.getIn(['meta', 'original', 'frame_rate'])}
currentTime={currentTime || 0}
autoPlay={autoPlay || false}
volume={volume || 1}
onCloseVideo={onClose}
detailed
alt={image.get('description')}
key={image.get('url')}
/>
);
} else if (image.get('type') === 'gifv') {
return (
<GIFV
src={image.get('url')}
width={width}
height={height}
key={image.get('preview_url')}
alt={image.get('description')}
onClick={this.toggleNavigation}
/>
);
}
return null;
}).toArray();
// you can't use 100vh, because the viewport height is taller
// than the visible part of the document in some mobile
// browsers when it's address bar is visible.
// https://developers.google.com/web/updates/2016/12/url-bar-resizing
const swipeableViewsStyle = {
width: '100%',
height: '100%',
};
const containerStyle = {
alignItems: 'center', // center vertically
};
const navigationClassName = classNames('media-modal__navigation', {
'media-modal__navigation--hidden': navigationHidden,
});
let pagination;
if (media.size > 1) {
pagination = media.map((item, i) => (
<button key={i} className={classNames('media-modal__page-dot', { active: i === index })} data-index={i} onClick={this.handleChangeIndex}>
{i + 1}
</button>
));
}
return (
<div className='modal-root__modal media-modal'>
<div className='media-modal__closer' role='presentation' onClick={onClose} >
<ReactSwipeableViews
style={swipeableViewsStyle}
containerStyle={containerStyle}
onChangeIndex={this.handleSwipe}
onTransitionEnd={this.handleTransitionEnd}
index={index}
disabled={disableSwiping}
>
{content}
</ReactSwipeableViews>
</div>
<div className={navigationClassName}>
<IconButton className='media-modal__close' title={intl.formatMessage(messages.close)} icon='times' onClick={onClose} size={40} />
{leftNav}
{rightNav}
<div className='media-modal__overlay'>
{pagination && <ul className='media-modal__pagination'>{pagination}</ul>}
{statusId && <Footer statusId={statusId} withOpenButton onClose={onClose} />}
</div>
</div>
</div>
);
}
}
|
modules/gob-web/modules/course-table/year.js
|
hawkrives/gobbldygook
|
// @flow
import React from 'react'
import {connect} from 'react-redux'
import {FlatButton} from '../../components/button'
import Semester from './semester'
import {findFirstAvailableSemester} from '../../helpers/find-first-available-semester'
import {expandYear, semesterName} from '@gob/school-st-olaf-college'
import {Student, Schedule} from '@gob/object-student'
import * as theme from '../../theme'
import {
changeStudent,
type ChangeStudentFunc,
} from '../../redux/students/actions/change'
import styled from 'styled-components'
const Container = styled.div`
margin-bottom: var(--page-edge-padding);
`
const Header = styled.header`
${theme.noSelect};
margin: 0;
display: flex;
flex-flow: row nowrap;
justify-content: space-between;
align-items: center;
font-variant-numeric: tabular-nums;
line-height: 1em;
font-weight: 500;
font-size: 0.9em;
`
const TitleText = styled.h1`
${theme.headingNeutral};
white-space: nowrap;
flex: 1;
margin-left: calc(var(--semester-spacing) + var(--semester-side-padding));
`
const TitleButton = styled(FlatButton)`
transition: 0.15s;
min-height: 0;
padding: 0 0.5em;
text-transform: none;
font-weight: 400;
color: var(--gray-500);
& + & {
margin-left: 0.1em;
}
`
const RemoveYearButton = styled(TitleButton)`
&:hover {
color: var(--red-500);
background-color: var(--red-50);
border: solid 1px var(--red-500);
}
`
const SemesterList = styled.div`
flex: 1;
display: flex;
flex-flow: row wrap;
`
const canAddSemester = (nextAvailableSemester?: number) => {
return nextAvailableSemester != null && nextAvailableSemester <= 5
}
type Props = {
student: Student,
year: number,
changeStudent: ChangeStudentFunc,
}
class Year extends React.Component<Props> {
addSemester = () => {
let nextAvailableSemester = findFirstAvailableSemester(
[...this.props.student.schedules.values()],
this.props.year,
)
let s = this.props.student.addSchedule(
new Schedule({
year: this.props.year,
semester: nextAvailableSemester,
index: 1,
active: true,
}),
)
this.props.changeStudent(s)
}
removeYear = () => {
let s = this.props.student.destroySchedulesForYear(this.props.year)
this.props.changeStudent(s)
}
render() {
let {student, year} = this.props
let schedules = student.schedules
.filter(s => s.active === true && s.year === year)
.sortBy(s => s.getTerm())
.toList()
let niceYear = expandYear(year)
let nextSemester = findFirstAvailableSemester(
[...schedules.values()],
year,
)
let isAddSemesterDisabled = !canAddSemester(nextSemester)
return (
<Container>
<Header>
<TitleText>{niceYear}</TitleText>
<>
{!isAddSemesterDisabled && nextSemester != null && (
<TitleButton
type="flat"
title="Add Semester"
onClick={this.addSemester}
>
Add ‘{semesterName(nextSemester)}’
</TitleButton>
)}
<RemoveYearButton
type="flat"
title={`Remove the year ${niceYear}`}
onClick={this.removeYear}
>
Remove Year
</RemoveYearButton>
</>
</Header>
<SemesterList>
{schedules.map(schedule => (
<Semester
key={schedule.semester}
schedule={schedule}
semester={schedule.semester}
student={student}
year={year}
/>
))}
</SemesterList>
</Container>
)
}
}
const connected = connect(
undefined,
{changeStudent},
)(Year)
export {connected as Year}
|
blueocean-material-icons/src/js/components/svg-icons/content/create.js
|
jenkinsci/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const ContentCreate = (props) => (
<SvgIcon {...props}>
<path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/>
</SvgIcon>
);
ContentCreate.displayName = 'ContentCreate';
ContentCreate.muiName = 'SvgIcon';
export default ContentCreate;
|
example/App/VariableHeight.js
|
nkbt/react-collapse
|
import React from 'react';
import {Collapse} from '../../src';
export class VariableHeight extends React.PureComponent {
constructor(props) {
super(props);
this.state = {isOpened: false, height: 100};
}
render() {
const {isOpened, height} = this.state;
return (
<div {...this.props}>
<div className="config">
<label className="label">
Opened:
<input
className="input"
type="checkbox"
checked={isOpened}
onChange={({target: {checked}}) => this.setState({isOpened: checked})} />
</label>
<label className="label">
Content height:
<input
className="input"
type="range"
value={height}
step={50}
min={0}
max={500}
onChange={({target: {value}}) => this.setState({height: parseInt(value, 10)})} />
{height}
</label>
</div>
<Collapse isOpened={isOpened}>
<div style={{height}} className="blob" />
</Collapse>
</div>
);
}
}
|
stories/examples/CardImageCaps.js
|
reactstrap/reactstrap
|
import React from 'react';
import { Card, CardBody, Button, CardTitle, CardText, CardImg } from 'reactstrap';
const Example = (props) => {
return (
<div>
<Card>
<CardImg top width="100%" src="https://picsum.photos/318/180" alt="Card image cap" />
<CardBody>
<CardTitle tag="h5">Card Title</CardTitle>
<CardText>This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</CardText>
<CardText>
<small className="text-muted">Last updated 3 mins ago</small>
</CardText>
</CardBody>
</Card>
<Card>
<CardBody>
<CardTitle tag="h5">Card Title</CardTitle>
<CardText>This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</CardText>
<CardText>
<small className="text-muted">Last updated 3 mins ago</small>
</CardText>
</CardBody>
<CardImg bottom width="100%" src="https://picsum.photos/318/180" alt="Card image cap" />
</Card>
</div>
);
};
export default Example;
|
src/esm/components/structure/cards/summary-card/components/title-tag.js
|
KissKissBankBank/kitten
|
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["text", "icon", "className"];
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Tag } from '../../../../information/tag';
import { LockIcon } from '../../../../graphics/icons/lock-icon';
import { StarIcon } from '../../../../graphics/icons/star-icon';
export var TitleTag = function TitleTag(_ref) {
var text = _ref.text,
icon = _ref.icon,
className = _ref.className,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
var iconDisplay = function () {
switch (icon) {
case 'lock':
return /*#__PURE__*/React.createElement(LockIcon, {
width: "14",
height: "14"
});
case 'star':
default:
return /*#__PURE__*/React.createElement(StarIcon, {
width: "14",
height: "13"
});
}
}();
return /*#__PURE__*/React.createElement(Tag, _extends({
className: classNames('k-SummaryCard__titleTag', className, 'k-u-margin-top-single')
}, props), iconDisplay, /*#__PURE__*/React.createElement("span", null, text));
};
TitleTag.propTypes = {
icon: PropTypes.oneOf(['star', 'lock']),
text: PropTypes.node
};
TitleTag.defaultProps = {
icon: 'star',
text: null
};
|
src/compontent/summary.js
|
PangPangPangPangPang/react-blog
|
/**
* Created by wangyefeng on 03/03/2017.
*/
import React from 'react'
import { hashHistory } from 'react-router'
import './summary.css'
const Summary = (props) => {
const clickDetail = () => {
hashHistory.push(`list/${props.id}`)
}
const renderTag = () => {
const arr = []
for (let i = 0; i < props.tags.length; i += 1) {
arr.push(
<div key={`${i}`} className="summary-tag">
{props.tags[i]}
</div>)
}
return arr
}
return (
<div className="summary-card" onClick={clickDetail}>
{props.name}
<hr className="summary-seperate" />
<div className="summary-tags">
{renderTag()}
</div>
</div>
)
}
Summary.propTypes = {
name: React.PropTypes.string,
tags: React.PropTypes.array,
}
Summary.defaultProps = {
name: '',
tags: [],
}
export default Summary
|
src/parser/paladin/holy/modules/azeritetraits/RadiantIncandescence.js
|
fyruna/WoWAnalyzer
|
import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import { formatNumber, formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS/index';
import TraitStatisticBox, { STATISTIC_ORDER } from 'interface/others/TraitStatisticBox';
import ItemHealingDone from 'interface/others/ItemHealingDone';
import Events from 'parser/core/Events';
import BeaconHealSource from '../beacons/BeaconHealSource.js';
/**
* Radiant Incandescence
* Your Holy Shock criticals deal an additional 1725 damage, or an additional 2715 healing, over 3 sec.
* Example Log: https://www.warcraftlogs.com/reports/vGfw7dYhM1m6n3J4#fight=8&type=healing&source=13&ability=278147&view=events
*/
class RadiantIncandescence extends Analyzer {
static dependencies = {
beaconHealSource: BeaconHealSource,
};
healing = 0;
healingTransfered = 0;
casts = 0;
crits = 0;
damage = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTrait(SPELLS.RADIANT_INCANDESCENCE_TRAIT.id);
if (!this.active) {
return;
}
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.HOLY_SHOCK_CAST), this.onCast);
this.addEventListener(Events.applybuff.by(SELECTED_PLAYER).spell(SPELLS.RADIANT_INCANDESCENCE), this.onCrit);
this.addEventListener(Events.applydebuff.by(SELECTED_PLAYER).spell(SPELLS.RADIANT_INCANDESCENCE_DAMAGE), this.onCrit);
this.addEventListener(Events.heal.by(SELECTED_PLAYER).spell(SPELLS.RADIANT_INCANDESCENCE), this.onHeal);
this.addEventListener(this.beaconHealSource.beacontransfer.by(SELECTED_PLAYER), this.onBeaconTransfer);
this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(SPELLS.RADIANT_INCANDESCENCE_DAMAGE), this.onDamage);
}
onCast(event) {
this.casts += 1;
}
onCrit(event){
this.crits += 1;
}
onHeal(event) {
this.healing += event.amount + (event.absorbed || 0);
this.targetsHit += 1;
}
onBeaconTransfer(event) {
const spellId = event.originalHeal.ability.guid;
if (spellId !== SPELLS.RADIANT_INCANDESCENCE.id) {
return;
}
this.healingTransfered += event.amount + (event.absorbed || 0);
}
onDamage(event){
this.damage += event.amount + (event.absorbed || 0);
}
get critRate() {
return (this.crits / this.casts) || 0;
}
get totalHealing() {
return this.healing + this.healingTransfered;
}
statistic() {
return (
<TraitStatisticBox
position={STATISTIC_ORDER.OPTIONAL()}
trait={SPELLS.RADIANT_INCANDESCENCE.id}
value={(
<>
<ItemHealingDone amount={this.totalHealing} /><br />
{formatPercentage(this.critRate)}% Crit Rate
</>
)}
tooltip={(
<>
Damage Done: <b>{formatNumber(this.damage)}</b><br />
Beacon healing transfered: <b>{formatNumber(this.healingTransfered)}</b><br />
</>
)}
/>
);
}
}
export default RadiantIncandescence;
|
src/svg-icons/communication/stop-screen-share.js
|
igorbt/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationStopScreenShare = (props) => (
<SvgIcon {...props}>
<path d="M21.22 18.02l2 2H24v-2h-2.78zm.77-2l.01-10c0-1.11-.9-2-2-2H7.22l5.23 5.23c.18-.04.36-.07.55-.1V7.02l4 3.73-1.58 1.47 5.54 5.54c.61-.33 1.03-.99 1.03-1.74zM2.39 1.73L1.11 3l1.54 1.54c-.4.36-.65.89-.65 1.48v10c0 1.1.89 2 2 2H0v2h18.13l2.71 2.71 1.27-1.27L2.39 1.73zM7 15.02c.31-1.48.92-2.95 2.07-4.06l1.59 1.59c-1.54.38-2.7 1.18-3.66 2.47z"/>
</SvgIcon>
);
CommunicationStopScreenShare = pure(CommunicationStopScreenShare);
CommunicationStopScreenShare.displayName = 'CommunicationStopScreenShare';
CommunicationStopScreenShare.muiName = 'SvgIcon';
export default CommunicationStopScreenShare;
|
src/components/Account/Courses/CourseList/index.js
|
ndlib/usurper
|
import React from 'react'
import PropTypes from 'prop-types'
import CourseCard from './CourseCard'
import styles from './style.module.css'
const CourseList = (props) => {
if (!props.courses || !props.courses.length) {
return null
}
return (
<div className={styles.courseSection}>
<h3 className={styles.courseSectionTitle}>{props.title}</h3>
<div className={[styles.courseCard, styles.courseHeader].join(' ')}>
<div>Course</div>
<div>Course Reserves</div>
<div>Subject Resources</div>
</div>
{props.courses.map((row) =>
<CourseCard key={row.id} course={row} />,
)}
</div>
)
}
CourseList.propTypes = {
courses: PropTypes.array,
title: PropTypes.string,
}
export default CourseList
|
docs/app/Examples/views/Comment/Variations/CommentExampleMinimal.js
|
koenvg/Semantic-UI-React
|
import React from 'react'
import { Button, Comment, Form, Header } from 'semantic-ui-react'
const CommentExampleMinimal = () => (
<Comment.Group minimal>
<Header as='h3' dividing>Comments</Header>
<Comment>
<Comment.Avatar as='a' src='http://semantic-ui.com/images/avatar/small/matt.jpg' />
<Comment.Content>
<Comment.Author as='a'>Matt</Comment.Author>
<Comment.Metadata>
<span>Today at 5:42PM</span>
</Comment.Metadata>
<Comment.Text>How artistic!</Comment.Text>
<Comment.Actions>
<a>Reply</a>
</Comment.Actions>
</Comment.Content>
</Comment>
<Comment>
<Comment.Avatar as='a' src='http://semantic-ui.com/images/avatar/small/elliot.jpg' />
<Comment.Content>
<Comment.Author as='a'>Elliot Fu</Comment.Author>
<Comment.Metadata>
<span>Yesterday at 12:30AM</span>
</Comment.Metadata>
<Comment.Text>
<p>This has been very useful for my research. Thanks as well!</p>
</Comment.Text>
<Comment.Actions>
<a>Reply</a>
</Comment.Actions>
</Comment.Content>
<Comment.Group>
<Comment>
<Comment.Avatar as='a' src='http://semantic-ui.com/images/avatar/small/jenny.jpg' />
<Comment.Content>
<Comment.Author as='a'>Jenny Hess</Comment.Author>
<Comment.Metadata>
<span>Just now</span>
</Comment.Metadata>
<Comment.Text>Elliot you are always so right :)</Comment.Text>
<Comment.Actions>
<a>Reply</a>
</Comment.Actions>
</Comment.Content>
</Comment>
</Comment.Group>
</Comment>
<Comment>
<Comment.Avatar as='a' src='http://semantic-ui.com/images/avatar/small/joe.jpg' />
<Comment.Content>
<Comment.Author as='a'>Joe Henderson</Comment.Author>
<Comment.Metadata>
<span>5 days ago</span>
</Comment.Metadata>
<Comment.Text>Dude, this is awesome. Thanks so much</Comment.Text>
<Comment.Actions>
<a>Reply</a>
</Comment.Actions>
</Comment.Content>
</Comment>
<Form reply onSubmit={e => e.preventDefault()}>
<Form.TextArea />
<Button content='Add Reply' labelPosition='left' icon='edit' primary />
</Form>
</Comment.Group>
)
export default CommentExampleMinimal
|
client/admin/server.js
|
kirinami/portfolio
|
// Import dependencies
import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter, Route } from 'react-router-dom';
import { Provider } from 'mobx-react';
// Export markup
/* eslint-disable global-require */
module.exports = (initialStates, url) => {
// define initial states
global.initialStates = initialStates;
// delete cache for stores
delete require.cache[require.resolve('./stores')];
// define context and markup
const context = {};
const markup = renderToString(
<Provider {...require('./stores')}>
<StaticRouter basename="/admin" location={url} context={context}>
<Route component={require('./scenes').default}/>
</StaticRouter>
</Provider>,
);
// return render
return {
context,
markup,
};
};
|
src/svg-icons/image/collections.js
|
mtsandeep/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCollections = (props) => (
<SvgIcon {...props}>
<path d="M22 16V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2zm-11-4l2.03 2.71L16 11l4 5H8l3-4zM2 6v14c0 1.1.9 2 2 2h14v-2H4V6H2z"/>
</SvgIcon>
);
ImageCollections = pure(ImageCollections);
ImageCollections.displayName = 'ImageCollections';
ImageCollections.muiName = 'SvgIcon';
export default ImageCollections;
|
examples/self_mounting_components/mount.js
|
abdelouahabb/python-react
|
import React from 'react';
// During the build process webpack aliases this import to the desired component
import Component from '__react_mount_component__';
// During the build process webpack will replace these variable with
// the names passed from the python process
const props = __react_mount_props_variable__;
const container = document.getElementById(__react_mount_container__);
const element = React.createElement(Component, props);
React.render(element, container);
|
react-flux-mui/js/material-ui/src/svg-icons/maps/streetview.js
|
pbogdan/react-flux-mui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsStreetview = (props) => (
<SvgIcon {...props}>
<path d="M12.56 14.33c-.34.27-.56.7-.56 1.17V21h7c1.1 0 2-.9 2-2v-5.98c-.94-.33-1.95-.52-3-.52-2.03 0-3.93.7-5.44 1.83z"/><circle cx="18" cy="6" r="5"/><path d="M11.5 6c0-1.08.27-2.1.74-3H5c-1.1 0-2 .9-2 2v14c0 .55.23 1.05.59 1.41l9.82-9.82C12.23 9.42 11.5 7.8 11.5 6z"/>
</SvgIcon>
);
MapsStreetview = pure(MapsStreetview);
MapsStreetview.displayName = 'MapsStreetview';
MapsStreetview.muiName = 'SvgIcon';
export default MapsStreetview;
|
src/components/PhotoList.js
|
edwinwright/react-project
|
import React from 'react';
import PhotoThumb from './PhotoThumb';
const PhotoList = ({ photos }) => (
<div>
<h1>PhotoList</h1>
<ul>
{photos.map(photo => (
<li key={photo.id}>
<PhotoThumb photo={photo} />
</li>
))}
</ul>
</div>
);
// TODO: Add propTypes
// TODO: Does PhotoThumb need {...this.props} ??
export default PhotoList
|
modules/__tests__/History-test.js
|
cojennin/react-router
|
/*eslint-env mocha */
import expect from 'expect'
import React from 'react'
import History from '../History'
import Router from '../Router'
import Route from '../Route'
import createHistory from 'history/lib/createMemoryHistory'
describe('History Mixin', function () {
let node
beforeEach(function () {
node = document.createElement('div')
})
afterEach(function () {
React.unmountComponentAtNode(node)
})
it('assigns the history to the component instance', function (done) {
let history = createHistory('/')
function assertHistory() {
expect(this.history).toExist()
}
let Component = React.createClass({
mixins: [ History ],
componentWillMount: assertHistory,
render () { return null }
})
React.render((
<Router history={history}>
<Route path="/" component={Component} />
</Router>
), node, done)
})
})
|
app/components/Files.js
|
christianalfoni/TeachKidsCode
|
import React from 'react';
import {Mixin} from 'cerebral-react-immutable-store';
import MTRC from 'markdown-to-react-components';
import {
Row,
Col,
ListGroup,
ListGroupItem,
Button
} from 'react-bootstrap';
var Files = React.createClass({
mixins: [Mixin],
getStatePaths() {
return {
files: ['files'],
currentFileIndex: ['currentFileIndex'],
isLoadingFiles: ['isLoadingFiles']
};
},
renderFile(file, index) {
return (
<ListGroupItem key={index} href="#" active={index === this.state.currentFileIndex} onClick={() => this.signals.currentFileChanged({
currentFileIndex: index
})}>{file.name}</ListGroupItem>
);
},
render() {
if (this.state.isLoadingFiles) {
return (
<h4>Loading files...</h4>
);
}
return (
<Row>
<Col md={4}>
<ListGroup>
{this.state.files.map(this.renderFile)}
</ListGroup>
</Col>
<Col md={8}>
<div><Button bsStyle="primary" onClick={() => this.signals.editCurrentFileClicked()}>Edit</Button></div>
{this.state.files.length ? MTRC(this.state.files[this.state.currentFileIndex].content).tree : null}
</Col>
</Row>
);
}
});
export default Files;
|
generators/js-framework/modules/react/components/Account/Reset.js
|
sahat/boilerplate
|
import React from 'react';
import { connect } from 'react-redux'
import { resetPassword } from '../../actions/auth';
import Messages from '../Messages';
class Reset extends React.Component {
constructor(props) {
super(props);
this.state = { password: '', confirm: '' };
}
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
handleReset(event) {
event.preventDefault();
this.props.dispatch(resetPassword(this.state.password, this.state.confirm, this.props.params.token));
}
render() {
return (
//= RESET_RENDER_INDENT3
);
}
}
const mapStateToProps = (state) => {
return state;
};
export default connect(mapStateToProps)(Reset);
|
src/components/SignIn/index.js
|
Apozhidaev/ergonode
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { signIn } from 'store/app/actions';
import { Link } from 'react-router-dom';
import 'github-fork-ribbon-css/gh-fork-ribbon.css';
import './styles.css';
import ProgressBar from '../ProgressBar';
class SignIn extends Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(e) {
const { onSignIn } = this.props;
e.preventDefault();
if (!this.userName.value.trim() || !this.password.value.trim()) {
return;
}
onSignIn({
name: this.userName.value,
password: this.password.value,
});
}
render() {
const { authorization, errors } = this.props;
const errorViews = errors.map(err => (
<div key={err} className="alert alert-dismissible alert-danger">
{err}
</div>
));
return (
<div>
<a
className="github-fork-ribbon right-bottom fixed"
href="https://github.com/Apozhidaev/terminal"
title="Fork me on GitHub"
target="_blank"
rel="noopener noreferrer"
>
Fork me on GitHub
</a>
<h2 className="mx-3 my-2">
<Link className="logo-header text-primary" to="/">The Terminal</Link>
</h2>
<div className="container mt-4 mt-lg-5">
<form onSubmit={this.onSubmit}>
<div className="form-group row">
<label htmlFor="user" className="col-sm-3 col-md-2 col-form-label">user name</label>
<div className="col-sm-8">
<input
type="text"
className="form-control"
id="user"
placeholder="user name"
ref={(node) => { this.userName = node; }}
/>
</div>
</div>
<div className="form-group row">
<label htmlFor="password" className="col-sm-3 col-md-2 col-form-label">
password
</label>
<div className="col-sm-8">
<input
type="password"
className="form-control"
id="password"
placeholder="password"
ref={(node) => { this.password = node; }}
/>
</div>
</div>
<div className="form-group row">
<div className="offset-sm-3 offset-md-2 col-sm-8">
<div className="row">
<div className="col-4">
<button type="submit" className="btn btn-primary">sign in</button>
</div>
<div className="col-5">
<ProgressBar className="my-3" progress={authorization} />
</div>
</div>
</div>
</div>
</form>
{errorViews}
</div>
</div>
);
}
}
const mapStateToProps = state => ({
authorization: state.services.sso.profileFetching,
profile: state.app.context.profile,
errors: state.app.context.errors,
});
const mapDispatchToProps = ({
onSignIn: signIn,
});
export default connect(mapStateToProps, mapDispatchToProps)(SignIn);
|
src/modules/todo/components/TodoList.js
|
scubism/react_todo_web
|
import React from 'react';
import { provideHooks } from 'redial';
import { connect } from 'react-redux';
import { Link } from 'react-router'
import autobind from 'autobind-decorator'
import Loader from 'react-loaders'
import { listTodos, createTodo, updateTodo, deleteTodo, moveTodo } from '../actions';
import { TodoInlineCreateForm } from './TodoInlineForm'
import TodoListItem from './TodoListItem';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
@provideHooks({
fetch: ({ dispatch }) => dispatch(listTodos({reject: (e) => {alert(e);}}))
})
@connect((state) => {
return {
todos: state.todo.todos,
fetchState: state.todo.fetchState,
focusedTodo: state.todo.focusedTodo,
};
})
@DragDropContext(HTML5Backend)
@autobind
export default class TodoList extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {stagedTodos: null}
}
componentWillReceiveProps(nextProps) {
if (this.props.todos !== nextProps.todos) {
this.state = Object.assign({}, this.state, {stagedTodos: nextProps.todos});
}
}
_beginDrag(dragIndex) {
this.setState({stagedTodos: this.props.todos});
}
_moveItem(dragIndex, hoverIndex) {
let todos = this.state.stagedTodos || this.props.todos;
let converted = [];
let isMoveUp = true;
todos.forEach((todo, index) => {
if (index == dragIndex) {
isMoveUp = false;
} else if (index == hoverIndex) {
if (isMoveUp) {
converted.push(todos[dragIndex]);
converted.push(todos[hoverIndex]);
} else {
converted.push(todos[hoverIndex]);
converted.push(todos[dragIndex]);
}
} else {
converted.push(todo);
}
})
this.setState({stagedTodos: converted});
}
_dropItem(dragIndex) {
let todos = this.state.stagedTodos;
this.props.dispatch(moveTodo(todos[dragIndex], todos, {
reject: ((e) => { alert(e); this.setState({stagedTodos: null});}),
}));
}
_dropCanceled(dragIndex) {
this.setState({stagedTodos: null});
}
render() {
const { todos, fetchState, focusedTodo, dispatch } = this.props;
let stagedTodos = this.state.stagedTodos || todos;
const _beginDrag = this._beginDrag;
const _dropCanceled = this._dropCanceled;
const _moveItem = this._moveItem;
const _dropItem = this._dropItem;
return (
<div className="todo-list">
<div key="loader"
style={{display: (
fetchState[listTodos].fetching ||
fetchState[createTodo].fetching ||
fetchState[updateTodo].fetching ||
fetchState[deleteTodo].fetching
) ? 'block' : 'none'}}
className="loader"
>
<Loader type="line-scale" active="true"/>
</div>
<TodoInlineCreateForm key="create-form" />
<ul key="items" className="todo-list-items">
{stagedTodos.map((todo, index) => {
return (
<TodoListItem
key={todo.id}
index={index}
todo={todo}
dispatch={dispatch}
beginDrag={_beginDrag}
dropCanceled={_dropCanceled}
moveItem={_moveItem}
dropItem={_dropItem}
editing={focusedTodo && focusedTodo.id == todo.id}
/>
);
})}
</ul>
</div>
);
}
}
|
src/RootComponent.js
|
jerryshew/react-uikits
|
import React, { Component } from 'react';
import { HashRouter as Router, Route, NavLink, Switch } from 'react-router-dom';
import { version } from '../package.json';
import {
BasicPage, ButtonPage,
CalendarPage, CarouselPage, CheckBoxPage, CheckBoxGroupPage, ConfirmBoxPage, CardPage, CommentPage, CrumbPage,
DatePickerPage, DateTimePickerPage, DropDownPage,
FormPage,
GridPage,
IconPage, ImagePage, InputPage, ItemPage, InstallPage, InputNumberPage,
LabelPage, LoaderPage, ListPage,
MenuPage, ModalPage,
NoticePage,
OtherPage,
PaginationPage, PinPage, PanelPage, ProgressPage,
RadioPage, RadioGroupPage,
SlideMenuPage, StartPage,
ToastPage, TabPage, TimeInputPage, TimePickerPage, TooltipPage, TablePage, TextPage, TempPage, ThemePage,
ValidatorPage,
} from './page';
import {CN} from './util/tools';
import {NAV_MAP} from './constant';
const NAV_MAP_KEYS = Object.keys(NAV_MAP)
const asideLinks = () => {
return NAV_MAP_KEYS.map(key => {
return (
<div className="group" key={key}>
<h4>{key}</h4>
{NAV_MAP[key].map(item => {
return (
<span key={item.route}>
{item.route === '/component' ?
<NavLink exact to="/component">{item.name}</NavLink>
: <NavLink to={item.route}>{item.name}</NavLink>}
</span>
)
})}
</div>
)
})
}
const Header = props => {
return (
<header className={CN('basic block main-nav')}>
<div className={CN('container')}>
<div className={CN('basic table')}>
<div className="row">
<div className="cell">
<h2><NavLink to="/">React UIKits</NavLink></h2>
</div>
<div className="text-right cell">
<NavLink exact className="link" to="/">首页</NavLink>
<NavLink className="link" to="/component">组件</NavLink>
</div>
</div>
</div>
</div>
</header>
);
}
const Footer = props => {
return (
<footer className="main-footer">
<div className={CN('container')}>
<div className={CN('basic table')}>
<div className="row">
<div className="cell">
<h4>{`React UIKits@${version}`}</h4>
</div>
<div className="text-right cell">
<a href="https://github.com/jerryshew/react-uikits" target="_blank">Github</a>
<a href="http://braavos.me" target="_blank">Blog</a>
<a href="https://github.com/wecatch" target="_blank">team</a>
</div>
</div>
</div>
</div>
</footer>
);
}
const RootPage = props => {
return (
<div className={CN('root-page fluid table absolute-center')}>
<div className="row">
<div className="cell">
<h1 className={CN('field')}>
React UIkits
</h1>
<p className={CN('field')}>基于 React.js 快速搭建企业平台的组件化方案</p>
<NavLink to="/component" className={CN('red button')}>更多...</NavLink>
</div>
</div>
</div>
);
}
const ContentPage = props => {
return (
<div className={CN('container grid main-page')}>
<aside className={CN('column-3 main-aside')}>
{asideLinks()}
</aside>
<article className="column column-13 main-content">
<Route exact path="/component" component={BasicPage}></Route>
<Route path="/start" component={StartPage}></Route>
<Route path="/theme" component={ThemePage}></Route>
<Route path="/install" component={InstallPage}></Route>
<Route path="/component/button" component={ButtonPage}></Route>
<Route path="/component/calendar" component={CalendarPage}></Route>
<Route path="/component/carousel" component={CarouselPage}></Route>
<Route path="/component/checkbox" component={CheckBoxPage}></Route>
<Route path="/component/checkboxgroup" component={CheckBoxGroupPage}></Route>
<Route path="/component/comment" component={CommentPage}></Route>
<Route path="/component/confirmbox" component={ConfirmBoxPage}></Route>
<Route path="/component/datepicker" component={DatePickerPage}></Route>
<Route path="/component/datetimepicker" component={DateTimePickerPage}></Route>
<Route path="/component/dropdown" component={DropDownPage}></Route>
<Route path="/component/form" component={FormPage}></Route>
<Route path="/component/validator" component={ValidatorPage}></Route>
<Route path="/component/grid" component={GridPage}></Route>
<Route path="/component/menu" component={MenuPage}></Route>
<Route path="/component/toast" component={ToastPage}></Route>
<Route path="/component/modal" component={ModalPage}></Route>
<Route path="/component/notice" component={NoticePage}></Route>
<Route path="/component/pagination" component={PaginationPage}></Route>
<Route path="/component/pin" component={PinPage}></Route>
<Route path="/component/panel" component={PanelPage}></Route>
<Route path="/component/progress" component={ProgressPage}></Route>
<Route path="/component/radio" component={RadioPage}></Route>
<Route path="/component/radiogroup" component={RadioGroupPage}></Route>
<Route path="/component/slidemenu" component={SlideMenuPage}></Route>
<Route path="/component/tab" component={TabPage}></Route>
<Route path="/component/timeinput" component={TimeInputPage}></Route>
<Route path="/component/timepicker" component={TimePickerPage}></Route>
<Route path="/component/tooltip" component={TooltipPage}></Route>
<Route path="/component/card" component={CardPage}></Route>
<Route path="/component/crumb" component={CrumbPage}></Route>
<Route path="/component/icon" component={IconPage}></Route>
<Route path="/component/image" component={ImagePage}></Route>
<Route path="/component/input" component={InputPage}></Route>
<Route path="/component/item" component={ItemPage}></Route>
<Route path="/component/label" component={LabelPage}></Route>
<Route path="/component/loader" component={LoaderPage}></Route>
<Route path="/component/other" component={OtherPage}></Route>
<Route path="/component/table" component={TablePage}></Route>
<Route path="/component/text" component={TextPage}></Route>
<Route path="/component/list" component={ListPage}></Route>
<Route path="/component/input-number" component={InputNumberPage}></Route>
<Route path="/temp" component={TempPage}></Route>
</article>
</div>
)
}
const BaseComponent = () => {
return (
<Router>
<article>
<Header/>
<Switch>
<Route exact path="/" component={RootPage}></Route>
<Route path="/component" component={ContentPage}></Route>
<Route path="/start" component={ContentPage}></Route>
<Route path="/theme" component={ContentPage}></Route>
<Route path="/install" component={ContentPage}></Route>
<Route path="/temp" component={ContentPage}></Route>
<Route component={RootPage}></Route>
</Switch>
<Footer/>
</article>
</Router>
)
}
export default BaseComponent
|
cloudapp/src/app/WaterChart.js
|
jbrichau/PoolBuddy
|
import React from 'react';
import { Badge } from 'reactstrap';
import { LineChart, XAxis, YAxis, Legend, Tooltip, CartesianGrid, Line, ReferenceLine } from 'recharts';
class CustomizedAxisTick extends React.Component {
render() {
const { x, y, stroke, payload } = this.props;
return (
<g transform={`translate(${x},${y})`}>
<text x={0} y={0} dy={16} textAnchor="end" fill="#666">{new Date(payload.value).toLocaleString('nl-BE')}</text>
</g>
);
}
};
function CustomizedTooltip(props) {
const { active } = props;
if (active) {
const { payload, label } = props;
return (
<div className="recharts-default-tooltip" style={{'margin': '0px', 'padding': '10px', 'backgroundColor': 'rgb(255, 255, 255)', 'border': '1px solid rgb(204, 204, 204)', 'whiteSpace': 'nowrap'}}>
<p className="recharts-tooltip-label" style={{'margin': '0px'}}>{new Date(label).toLocaleString('nl-BE')}</p>
<ul className="recharts-tooltip-item-list" style={{'padding': '0px', 'margin': '0px'}}>
<li className="recharts-tooltip-item" style={{'display': 'block', 'paddingTop': '4px', 'paddingBottom': '4px', 'color': payload[0].color}}>
<span className="recharts-tooltip-item-name">{payload[0].name}</span>
<span className="recharts-tooltip-item-separator"> : </span>
<span className="recharts-tooltip-item-value">{payload[0].value}</span>
<span className="recharts-tooltip-item-unit"></span>
</li>
</ul>
</div>
);
} else return null;
}
class WaterChart extends React.Component {
render() {
let minReferenceLine, maxReferenceLine;
const ticks = new Array();
if (this.props.minValue)
minReferenceLine = <ReferenceLine y={this.props.minValue} stroke="red" strokeDasharray="3 3" alwaysShow={true}/>;
if (this.props.maxValue)
maxReferenceLine = <ReferenceLine y={this.props.maxValue} stroke="red" strokeDasharray="3 3" alwaysShow={true}/>;
return (
<div>
<h2>{this.props.title} <Badge color="secondary">{this.props.data[this.props.data.length-1][this.props.dataKey].toFixed(2)} {this.props.unit}</Badge></h2>
<LineChart width={1000} height={200} data={this.props.data} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
<XAxis dataKey="timestamp" scale="utcTime" tick={<CustomizedAxisTick />} />
<YAxis />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip content={<CustomizedTooltip />} />
<Legend />
<Line type="monotone" dataKey={this.props.dataKey} stroke={this.props.stroke} strokeWidth="2" dot={false} activeDot={{ r: 8 }} />
{minReferenceLine}
{maxReferenceLine}
</LineChart>
</div>
);
}
}
export default WaterChart;
|
src/client/assets/javascripts/features/mapper/components/Mapper/Mapper.js
|
tlodge/uibuilder
|
import React, { Component } from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actionCreators as mapperActions, viewConstants, selector } from '../..';
import { actionCreators as shapeActions } from 'features/canvas/';
import { actionCreators as sourceActions } from 'features/sources';
import Schema from "../Schema";
import Attributes from "../Attributes";
import Transformer from "../Transformer";
import Properties from "../Properties";
import Birth from "../Birth";
import Death from "../Death";
import "./Mapper.scss";
import { Flex, Box } from 'reflexbox'
import '../../../../../styles/index.scss';
import {schemaLookup} from 'utils';
import Paper from 'react-md/lib/Papers';
import Card from 'react-md/lib/Cards/Card';
import CardTitle from 'react-md/lib/Cards/CardTitle';
import CardActions from 'react-md/lib/Cards/CardActions';
import CardText from 'react-md/lib/Cards/CardText';
const sourceName = (sources, sourceId)=>{
for (source in sources){
if (sourceId === source.id){
return source.name;
}
}
return sourceId;
}
const templateName = (templates, templateId)=>{
for (template in templates){
if (template.id === templateId){
return template.label;
}
}
return templateId;
}
const _shouldExpand = (path, selectedPath)=>{
if (!selectedPath){
return false;
}
return selectedPath.indexOf(path) != -1;
}
@connect(selector, (dispatch) => {
return {
actions: {
...bindActionCreators(mapperActions, dispatch),
...bindActionCreators(sourceActions, dispatch),
...bindActionCreators(shapeActions, dispatch)
}
}
})
export default class Mapper extends Component {
constructor(props){
super(props);
this.state = { activeTabIndex: 0, propertiesExpanded:false, objectsExpanded:false, mapperExpanded:false, mappingsExpanded:false, birthExpanded:false, deathExpanded:false};
this._handleTabChange = this._handleTabChange.bind(this);
this._toggleSelected = this._toggleSelected.bind(this);
}
renderSources() {
const {sources:{sources, selected}} = this.props;
const path = selected;
//const path = selected ? selected.path[0] : null;
const srcs = sources.map((source) =>{
return <Box key={source.id} onClick={this.props.actions.selectSource.bind(null, source.id)}>{source.name}</Box>
});
const schema = path != null ? <Schema {
...{
schema: sources.reduce((acc, source)=>{return (source.id === path) ? source.schema : acc;},{}),
onSelect: this.props.actions.mapFrom.bind(null, path)
}
}
/>: null;
return <Flex flexColumn={true}>
{srcs}
{schema}
</Flex>
}
renderTemplate(templateId, path, selectedPath){
const {canvas:{templatesById}} = this.props;
const template = templatesById[templateId];
return <div key={templateId}>
<li onClick={this._toggleSelected.bind(null, [...path, template.id], template.type, selectedPath)}>
{`${template.label} (${template.type})`}
</li>
{template.type === "group" && _shouldExpand(template.id,selectedPath) && this.renderTree(template.children, [...path, template.id], selectedPath)}
</div>
}
renderTree(templates, path, selectedPath){
return templates.map((id)=>{
return <ul key={id}>{this.renderTemplate(id, [...path], selectedPath)}</ul>;
});
}
renderObjects(){
const {canvas:{selected, templates}} = this.props;
const {path=null} = selected || [];
const tree = this.renderTree(templates, [], path);
return <Flex flexColumn={true}>
<Box>
{tree}
</Box>
</Flex>
}
renderComponents() {
const {canvas:{templatesById, selected}} = this.props;
const {path=null} = selected || [];
const [id, ...rest] = path;
const template = id ? templatesById[id] : null;
const attrs = id != null ? <Attributes {
...{
attributes: Object.keys(schemaLookup(template.type).attributes),
onSelect: this.props.actions.mapToAttribute.bind(null, path)
}
}
/> : null;
const style = id != null ? <Attributes {
...{
attributes: Object.keys(schemaLookup(template.type).style),
onSelect: this.props.actions.mapToStyle.bind(null,path)
}
}
/> : null;
const transforms = id != null ? <Attributes {
...{
attributes: ["rotate", "scale", "translate"],
onSelect: this.props.actions.mapToTransform.bind(null, path)
}
}
/> : null;
return <Flex flexColumn={true}>
{attrs}
{style}
{transforms}
</Flex>
}
renderMapper(){
const {canvas:{templatesById, selected:{path=null}}} = this.props;
if (!path || path.lnegth <= 0)
return null;
const template = templatesById[path[path.length-1]]
return <Box>
<div style={{paddingBottom:7, fontWeight:"bold"}}>{template.label}</div>
<Flex>
<Box col={6}>{this.renderSources()}</Box>
<Box col={6}>{this.renderComponents()}</Box>
</Flex>
</Box>
}
renderMappings(){
const {canvas:{templatesById}, sources:{sources}, mapper:{mappings}} = this.props;
return mappings.map((item,i)=>{
const sourceName = sources.reduce((acc,source)=>{
if (item.from.sourceId === source.id)
return source.name;
return acc;
},item.from.sourceId);
const [id, ...rest] = item.to.path;
const templateName = templatesById[id].label;
return <div onClick={this.props.actions.selectMapping.bind(null,item)} key={i}>{`${sourceName}:${item.from.key}`}->{`${templateName}:${item.to.property}`}</div>
})
}
renderBirthOptions(){
const {canvas:{selected:{path}}} = this.props;
return <Birth path={path}/>
}
renderDeathOptions(){
return <Death />
}
renderProperties(){
const { activeTabIndex } = this.state;
const {canvas:{templatesById, selected:{path}}} = this.props;
const template = templatesById[path[path.length-1]]
return <Properties template={template} updateAttribute={this.props.actions.updateTemplateAttribute.bind(null,path)} updateStyle={this.props.actions.updateTemplateStyle.bind(null,path)}/>
}
render() {
const {mapper:{open, selectedMapping, transformers}, canvas:{selected}, height} = this.props;
const {propertiesExpanded, objectsExpanded, mappingsExpanded, mapperExpanded, birthExpanded, deathExpanded} = this.state;
return (
<div id="mapper" style={{width:viewConstants.MAPPER_WIDTH, boxSizing:'border-box', height: height, overflow:'auto'}}>
<Paper key={1} zDepth={1}>
<Card className="md-block-centered" expanded={objectsExpanded} onExpanderClick={()=>{this.setState({objectsExpanded:!objectsExpanded})}}>
<CardActions expander onClick={()=>{this.setState({objectsExpanded:!objectsExpanded})}}>
objects
</CardActions>
<CardText style={{padding:0}} expandable>
{this.renderObjects()}
</CardText>
</Card>
{selected && <Card className="md-block-centered" defaultExpanded onExpanderClick={()=>{this.setState({propertiesExpanded:!propertiesExpanded})}}>
<CardActions expander onClick={()=>{this.setState({propertiesExpanded:!propertiesExpanded})}}>
properties
</CardActions>
<CardText style={{padding:0}} expandable>
{this.renderProperties()}
</CardText>
</Card>}
{selected && <Card className="md-block-centered" expanded={birthExpanded} onExpanderClick={()=>{this.setState({birthExpanded:!birthExpanded})}}>
<CardActions expander onClick={()=>{this.setState({birthExpanded:!birthExpanded})}}>
birth
</CardActions>
<CardText expandable>
{this.renderBirthOptions()}
</CardText>
</Card>}
{selected && <Card className="md-block-centered" expanded={deathExpanded} onExpanderClick={()=>{this.setState({deathExpanded:!deathExpanded})}}>
<CardActions expander onClick={()=>{this.setState({deathExpanded:!deathExpanded})}}>
death
</CardActions>
<CardText expandable>
{this.renderDeathOptions()}
</CardText>
</Card>}
{selected && <Card className="md-block-centered" expanded={mapperExpanded} onExpanderClick={()=>{this.setState({mapperExpanded:!mapperExpanded})}}>
<CardActions expander onClick={()=>{this.setState({mapperExpanded:!mapperExpanded})}}>
behaviour
</CardActions>
<CardText expandable>
{this.renderMapper()}
{this.renderMappings()}
{selectedMapping && <Transformer selectedMapping={selectedMapping} transformer={transformers[selectedMapping.mappingId]} saveDialog={this.props.actions.saveTransformer.bind(null, selectedMapping.mappingId)} closeDialog={this.props.actions.selectMapping.bind(null,null)}/>}
</CardText>
</Card>}
</Paper>
</div>
);
}
_handleTabChange(activeTabIndex) {
this.setState({ activeTabIndex });
}
_toggleSelected(path,type,selectedPath){
//toogle here by checking laste elements of each path;
if (selectedPath != null && path.length > 0 && type==="group"){
const id1 = selectedPath[selectedPath.length-1];
const id2 = path[path.length-1];
if (id1 === id2){
this.props.actions.templateParentSelected();
return;
}
}
this.props.actions.templateSelected({path:path, type:type});
}
}
|
examples/sections/src/ThemeContext.js
|
styleguidist/react-styleguidist
|
import React from 'react';
/**
* Context that stores selected application theme: 'light' | 'dark'
*/
export default React.createContext('light');
|
examples/with-webpack-bundle-size-analyzer/pages/index.js
|
BlancheXu/test
|
import React from 'react'
import Link from 'next/link'
export default class Index extends React.Component {
static getInitialProps ({ req }) {
if (req) {
// Runs only in the server
const faker = require('faker')
const name = faker.name.findName()
return { name }
}
// Runs only in the client
return { name: 'Arunoda' }
}
render () {
const { name } = this.props
return (
<div>
<h1>Home Page</h1>
<p>Welcome, {name}</p>
<div>
<Link href='/about'>
<a>About Page</a>
</Link>
</div>
</div>
)
}
}
|
src/assets/js/react/components/Template/TemplateUploader.js
|
blueliquiddesigns/gravity-forms-pdf-extended
|
import PropTypes from 'prop-types'
import React from 'react'
import { connect } from 'react-redux'
import {
addTemplate,
updateTemplateParam,
postTemplateUploadProcessing,
clearTemplateUploadProcessing
} from '../../actions/templates'
import classNames from 'classnames'
import Dropzone from 'react-dropzone'
import ShowMessage from '../ShowMessage'
/**
* Handles the uploading of new PDF templates to the server
*
* @package Gravity PDF
* @copyright Copyright (c) 2020, Blue Liquid Designs
* @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
* @since 4.1
*/
/**
* React Component
*
* @since 4.1
*/
export class TemplateUploader extends React.Component {
/**
* @since 4.1
*/
static propTypes = {
genericUploadErrorText: PropTypes.string,
addTemplateText: PropTypes.string,
filenameErrorText: PropTypes.string,
filesizeErrorText: PropTypes.string,
installSuccessText: PropTypes.string,
installUpdatedText: PropTypes.string,
templateSuccessfullyInstalledUpdated: PropTypes.string,
templateInstallInstructions: PropTypes.string,
addNewTemplate: PropTypes.func,
updateTemplateParam: PropTypes.func,
postTemplateUploadProcessing: PropTypes.func,
clearTemplateUploadProcessing: PropTypes.func,
templates: PropTypes.array,
templateUploadProcessingSuccess: PropTypes.object,
templateUploadProcessingError: PropTypes.object
}
/**
* Setup internal component state that doesn't need to be in Redux
*
* @returns {{ajax: boolean, error: string, message: string}}
*
* @since 4.1
*/
state = {
ajax: false,
error: '',
message: ''
}
/**
* Fires appropriate function based on Redux store data
*
* @param {Object} nextProps
*
* @since 4.1
*/
componentWillReceiveProps (nextProps) {
Object.keys(nextProps.templateUploadProcessingSuccess).length > 0 && this.ajaxSuccess(nextProps.templateUploadProcessingSuccess)
Object.keys(nextProps.templateUploadProcessingError).length > 0 && this.ajaxFailed(nextProps.templateUploadProcessingError)
}
/**
* Manages the template file upload
*
* @param {array} acceptedFiles The array of uploaded files we should send to the server
*
* @since 4.1
*/
onDrop = (acceptedFiles) => {
/* Handle file upload and pass in an nonce!!! */
if (acceptedFiles instanceof Array && acceptedFiles.length > 0) {
acceptedFiles.forEach((file) => {
const filename = file.name
/* Do validation */
if (!this.checkFilename(filename) || !this.checkFilesize(file.size)) {
return
}
/* Add our loader */
this.setState({
ajax: true,
error: '',
message: '',
})
/* POST the PDF template to our endpoint for processing */
this.props.postTemplateUploadProcessing(file, filename)
})
}
}
/**
* Checks if the uploaded file has a .zip extension
* We do this instead of mime type checking as it doesn't work in all browsers
*
* @param {string} name
*
* @returns {boolean}
*
* @since 4.1
*/
checkFilename = (name) => {
if (name.substr(name.length - 4) !== '.zip') {
/* Tell use about incorrect file type */
this.setState({
error: this.props.filenameErrorText
})
return false
}
return true
}
/**
* Checks if the file size is larger than 5MB
*
* @param {int} size File size in bytes
*
* @returns {boolean}
*
* @since 4.1
*/
checkFilesize = (size) => {
/* Check the file is no larger than 10MB (convert from bytes to KB) */
if (size / 1024 > 10240) {
/* Tell use about incorrect file type */
this.setState({
error: this.props.filesizeErrorText
})
return false
}
return true
}
/**
* Update our Redux store with the new PDF template details
* If our upload AJAX call to the server passed this function gets fired
*
* @param {Object} response
*
* @since 4.1
*/
ajaxSuccess = (response) => {
/* Update our Redux Store with the new template(s) */
response.body.templates.forEach((template) => {
/* Check if template already in the list before adding to our store */
const matched = this.props.templates.find((item) => {
return (item.id === template.id)
})
if (matched === undefined) {
template.new = true //ensure new templates go to end of list
template.message = this.props.installSuccessText
this.props.addNewTemplate(template)
} else {
this.props.updateTemplateParam(template.id, 'message', this.props.installUpdatedText)
}
})
/* Mark as success and stop AJAX spinner */
this.setState({
ajax: false,
message: this.props.templateSuccessfullyInstalledUpdated
})
/* Clean/Reset our Redux Store state for templateUploadProcessing */
this.props.clearTemplateUploadProcessing()
}
/**
* Show any errors to the user when AJAX request fails for any reason
*
* @param {Object} error
*
* @since 4.1
*/
ajaxFailed = (error) => {
/* Let the user know there was a problem with the upload */
this.setState({
error: (error.response.body && error.response.body.error !== undefined) ? error.response.body.error : this.props.genericUploadErrorText,
ajax: false
})
/* Clean/Reset our Redux Store state for templateUploadProcessing */
this.props.clearTemplateUploadProcessing()
}
/**
* Remove message from state once the timeout has finished
*
* @since 4.1
*/
removeMessage = () => {
this.setState({
message: ''
})
}
/**
* @since 4.1
*/
render () {
return (
<div className="theme add-new-theme gfpdf-dropzone">
<Dropzone
onDrop={this.onDrop}
maxSize={10240000}
>
{({getRootProps, getInputProps, isDragActive}) => {
return (
<div
{...getRootProps()}
className={classNames('dropzone', {'dropzone--isActive': isDragActive})}
>
<input {...getInputProps()} />
<a href="#/template" className={this.state.ajax ? 'doing-ajax' : ''}>
<div className="theme-screenshot"><span/></div>
{this.state.error !== '' ? <ShowMessage text={this.state.error} error={true}/> : null}
{this.state.message !== '' ?
<ShowMessage text={this.state.message} dismissable={true}
dismissableCallback={this.removeMessage}/> : null}
<h2 className="theme-name">{this.props.addTemplateText}</h2>
</a>
<div className="gfpdf-template-install-instructions">{this.props.templateInstallInstructions}</div>
</div>
)
}}
</Dropzone>
</div>
)
}
}
/**
* Map Redux state to props
*
* @param state
* @returns {{templates: Array, templateUploadProcessingSuccess: Object, templateUploadProcessingError: Object}}
*
* @since 5.2
*/
const mapStateToProps = (state) => {
return {
templates: state.template.list,
templateUploadProcessingSuccess: state.template.templateUploadProcessingSuccess,
templateUploadProcessingError: state.template.templateUploadProcessingError
}
}
/**
* Map actions to props
*
* @param {func} dispatch Redux dispatcher
*
* @returns {{addNewTemplate: (function(template)), updateTemplateParam: (function(id=string, name=string, value=*)), postTemplateUploadProcessing: (function(file=object, filename=string)), clearTemplateUploadProcessing: (function())}}
*
* @since 4.1
*/
const mapDispatchToProps = (dispatch) => {
return {
addNewTemplate: (template) => {
dispatch(addTemplate(template))
},
updateTemplateParam: (id, name, value) => {
dispatch(updateTemplateParam(id, name, value))
},
postTemplateUploadProcessing: (file, filename) => {
dispatch(postTemplateUploadProcessing(file, filename))
},
clearTemplateUploadProcessing: () => {
dispatch(clearTemplateUploadProcessing())
}
}
}
/**
* Maps our Redux store to our React component
*
* @since 4.1
*/
export default connect(mapStateToProps, mapDispatchToProps)(TemplateUploader)
|
client/test/components/app.spec.js
|
nicksenger/marvelous
|
/* eslint-env mocha */
import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import { App } from '../../src/js/components/app';
describe('<App />', () => {
it('renders the component', (done) => {
const wrapper = shallow(<App />);
expect(wrapper.find('.background')).to.have.length(1);
done();
});
it('renders the component with menu down', (done) => {
const wrapper = shallow(<App />);
const instance = wrapper.instance();
instance.state.menuUp = true;
instance.forceUpdate();
done();
});
describe('the toggleMenu method', () => {
it('should call setState with the opposite of menuUp', (done) => {
const wrapper = shallow(<App />);
const instance = wrapper.instance();
sinon.stub(instance, 'setState');
instance.toggleMenu();
expect(instance.setState.called).to.equal(true);
expect(instance.setState.calledWith({ menuUp: !instance.state.menuUp })).to.equal(true);
done();
});
});
describe('the component will mount method', () => {
describe('the user has a jwt in local storage', () => {
it('should call the loginCheck action', (done) => {
localStorage.jwt = 'fake-jwt';
const loginCheck = sinon.spy();
const wrapper = shallow(<App loginCheck={loginCheck} />);
const instance = wrapper.instance();
instance.componentWillMount();
expect(instance.props.loginCheck.called).to.equal(true);
expect(instance.props.loginCheck.calledWith('fake-jwt')).to.equal(true);
done();
});
});
describe('the user does not have a jwt in local storage', () => {
it('should not call the loginCheck action', (done) => {
localStorage.jwt = null;
const loginCheck = sinon.spy();
const wrapper = shallow(<App loginCheck={loginCheck} />);
const instance = wrapper.instance();
instance.componentWillMount();
expect(instance.props.loginCheck.called).to.equal(false);
done();
});
});
describe('the user has a false jwt in local storage', () => {
it('should not call the loginCheck action', (done) => {
localStorage.jwt = 'false';
const loginCheck = sinon.spy();
const wrapper = shallow(<App loginCheck={loginCheck} />);
const instance = wrapper.instance();
instance.componentWillMount();
expect(instance.props.loginCheck.called).to.equal(false);
done();
});
});
});
});
|
src/main/js/my-app/src/index.js
|
myapos/ClientManagerSpringBoot
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from './store/configureStore';
import App from './containers/App';
import './index.css';
import * as utils from './utils';
const init = async () => {
const placeholder = document.getElementById('react');
const initialState = {
initRegistrations: [[]],
initDataStudentClasses: [[]],
initDataStudents: [],
// initDataAllStudents_: [],
initPayments: [],
displayInitialMsg: true,
seconds: 0,
timer: null,
setNonTerminalClasses: false,
filteredStudentClassesWithLinks: [[]],
lname: '',
activePage: 0,
searchingStatus: false,
};
ReactDOM.render(<Provider
store={configureStore(initialState)}>
<App />
</Provider>, placeholder);
};
init();
|
front/app/js/rh-components/rh-Spinner.js
|
nudoru/learning-map
|
import React from 'react';
const Spinner = ({type}) => {
let cls = ['spinner'];
if(type) {
cls.push(type);
}
return (<div className={cls.join(' ')}></div>)
};
export default Spinner;
|
src/lexer.js
|
MrCheater/text-resize-and-word-wrap-provider
|
import React from 'react';
let index = 0;
export function lexer(jsxText, props, results, init) {
if(init) {
index = 0;
}
if(!Array.isArray(jsxText)) {
jsxText = [jsxText];
}
const countChildren = jsxText.length;
for(let childIndex = 0; childIndex < countChildren; childIndex++) {
const child = jsxText[childIndex];
if(child === null) {
continue;
}
if(React.isValidElement(child)) {
const type = child.type;
const isDiv = type === 'div';
const isBreakLine = type === 'br';
const isTagA = props.isTagA || (type === 'a');
if(isDiv || isBreakLine) {
index++;
}
let {
children,
...childProps,
} = child.props;
if(isBreakLine) {
children = ' ';
}
if(children) {
lexer(
children,
{
...props,
...childProps,
isTagA,
type
},
results
);
}
if(isDiv || isBreakLine) {
index++;
}
} else {
const str = '' + child;
const words = str.split(' ');
const countWords = words.length;
for(let wordIndex = 0; wordIndex < countWords; wordIndex++) {
results.push({
word : words[wordIndex],
props : {
...props,
isSpanEnd : !(countWords - wordIndex - 1)
},
index
});
}
}
}
}
|
src/components/table_headers.js
|
mdkalish/json_selector
|
import React from 'react';
var SocialMediumHeaderRow = React.createClass({
render: function() {
return (
<tr style={{backgroundColor: '#fa6900'}}>
<th colSpan="4">
{this.props.type}
</th>
</tr>
);
}
});
var ColumnHeadersRow = React.createClass({
getInitialState: function() {
return {picked: false}
},
updatePicked: function() {
var picked = {picked: !this.state.picked}
this.setState(picked)
this.props.updatePicked(picked)
},
render: function() {
var k = Math.random()
return (
<tr colSpan="4" style={{backgroundColor: '#f38630'}}>
<th>Key Name</th>
<th>sObject Value</th>
<th>Fullcontact Value</th>
<th>
<label htmlFor={"updateAll_" + k}>Update sObject?</label>
<input type="checkbox" checked={this.state.picked} onChange={this.updatePicked} id={"updateAll_" + k} />
</th>
</tr>
);
}
});
module.exports = {SocialMediumHeaderRow, ColumnHeadersRow}
|
src/SudokuBoard.js
|
itsjustdanger/sudoku-solver
|
import React from 'react';
import PropTypes from 'prop-types';
import Square from './Square.js';
/* Display component for the sudoku board */
export default class SudokuBoard extends React.Component {
render() {
const board = this.props.board;
const squares = [];
for (const box in board) {
if (box) {
squares.push(
<Square
key={box}
handleChange={this.props.handleChange.bind(this, box)}
value={board[box]} />
);
}
}
return (
<div className="sudoku-board">
<span className="cross-line top"></span>
<span className="cross-line bottom"></span>
<span className="cross-line left"></span>
<span className="cross-line right"></span>
{squares}
</div>
)
}
}
SudokuBoard.propTypes = {
board: PropTypes.object.isRequired,
handleChange: PropTypes.func.isRequired,
}
|
analysis/paladinholy/src/modules/spells/DevotionAuraDamageReduction.js
|
yajinni/WoWAnalyzer
|
import React from 'react';
import { Trans } from '@lingui/macro';
import SPELLS from 'common/SPELLS';
import fetchWcl from 'common/fetchWclApi';
import { SpellIcon } from 'interface';
import { formatThousands, formatNumber } from 'common/format';
import LazyLoadStatisticBox, { STATISTIC_ORDER } from 'parser/ui/LazyLoadStatisticBox';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Combatants from 'parser/shared/modules/Combatants';
import makeWclUrl from 'common/makeWclUrl';
import { SpellLink } from 'interface';
import Events, { EventType } from 'parser/core/Events';
// Source: https://github.com/MartijnHols/HolyPaladin/blob/master/Spells/Talents/60/DevotionAura.md#about-the-passive-effect
const DEVOTION_AURA_PASSIVE_DAMAGE_REDUCTION = .03;
const DEVOTION_AURA_ACTIVE_DAMAGE_REDUCTION = 0.15;
/**
* Falling damage is considered "pure" or w/e damage meaning it doesn't get reduced by damage reductions. The ability description of such an event can look like this: {
"name": "Falling",
"guid": 3,
"type": 1,
"abilityIcon": "inv_axe_02.jpg"
},
* `type: 1` seems to only be used by Falling, but I was unable to verify this. I want to ignore this kind of damage taken. I figured the savest solution would be to filter by ability id instead of type, but if you find another such ability that needs to be ignored and it has `type: 1` while nothing else does, we may want to refactor this.
*/
// const THIS_MIGHT_BE_PURE_ABILITY_TYPE_ID = 1;
const FALLING_DAMAGE_ABILITY_ID = 3;
/**
* Devotion Aura
* Damage dealt to allies within 10 yards is reduced by up to 10%, diminishing as more allies enter the aura.
* While Aura Mastery is active, all affected allies gain 20% damage reduction.
* ---
* See the markdown file next to this module for info about how this is analyzed.
*/
class DevotionAuraDamageReduction extends Analyzer {
static dependencies = {
combatants: Combatants,
};
passiveDamageReduced = 0;
get passiveDrps() {
return (this.passiveDamageReduced / this.owner.fightDuration) * 1000;
}
activeDamageReduced = 0;
get activeDrps() {
return (this.activeDamageReduced / this.owner.fightDuration) * 1000;
}
get totalDamageReduced() {
return this.passiveDamageReduced + this.activeDamageReduced;
}
get totalDrps() {
return (this.totalDamageReduced / this.owner.fightDuration) * 1000;
}
constructor(...args) {
super(...args);
this.addEventListener(Events.damage.to(SELECTED_PLAYER), this.onDamageTaken);
this.addEventListener(Events.applybuff.by(SELECTED_PLAYER), this.onApplyBuff);
this.addEventListener(Events.removebuff.by(SELECTED_PLAYER), this.onRemoveBuff);
}
onDamageTaken(event) {
const spellId = event.ability.guid;
if (spellId === FALLING_DAMAGE_ABILITY_ID) {
return;
}
const isAuraMasteryActive = this.selectedCombatant.hasBuff(
SPELLS.AURA_MASTERY.id,
event.timestamp,
0,
0,
this.owner.playerId,
);
if (!isAuraMasteryActive) {
const damageTaken = event.amount + (event.absorbed || 0);
const damageReduced =
(damageTaken / (1 - this.singleTargetDamageReduction)) * this.totalPassiveDamageReduction;
this.passiveDamageReduced += damageReduced;
}
}
buffsActive = 1;
get singleTargetDamageReduction() {
return DEVOTION_AURA_PASSIVE_DAMAGE_REDUCTION;
}
get totalPassiveDamageReduction() {
return this.singleTargetDamageReduction * this.buffsActive;
}
isApplicableBuffEvent(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.DEVOTION_AURA.id) {
return false;
}
if (this.owner.toPlayer(event)) {
// We already include the selected player by default, if he dies the buff might show up. So to make sure it's not accidentally considered, we exclude it here.
return false;
}
const combatant = this.combatants.players[event.targetID];
if (!combatant) {
// Only players scale the buff, while pets can get it they do not affect the DR split
return false;
}
return true;
}
onApplyBuff(event) {
if (!this.isApplicableBuffEvent(event)) {
return;
}
this.buffsActive += 1;
// this.debug('devo applied to', this.combatants.players[event.targetID].name, this.buffsActive);
}
onRemoveBuff(event) {
if (!this.isApplicableBuffEvent(event)) {
return;
}
this.buffsActive -= 1;
// this.debug('devo removed from', this.combatants.players[event.targetID].name, this.buffsActive);
if (this.buffsActive === 0) {
console.error(
'We lost more Devotion Aura buffs than we gained, this should not be possible as applybuffs are fabricated for all removebuffs.',
);
this.buffsActive = 1;
}
}
get auraMasteryUptimeFilter() {
const buffHistory = this.selectedCombatant.getBuffHistory(
SPELLS.AURA_MASTERY.id,
this.owner.playerId,
);
if (buffHistory.length === 0) {
return null;
}
// WCL's filter requires the timestamp to be relative to fight start
return buffHistory
.map(
buff =>
`(timestamp>=${buff.start - this.owner.fight.start_time} AND timestamp<=${buff.end -
this.owner.fight.start_time})`,
)
.join(' OR ');
}
get filter() {
const playerName = this.owner.player.name;
// Include any damage while selected player has AM, and is above the health requirement,
// and the mitigation percentage is greater than 19% (we use this to reduce the false positives. We use DR-1% to account for rounding)
return `(IN RANGE FROM target.name='${playerName}' AND type='${
EventType.ApplyBuff
}' AND ability.id=${SPELLS.AURA_MASTERY.id} TO target.name='${playerName}' AND type='${
EventType.RemoveBuff
}' AND ability.id=${SPELLS.AURA_MASTERY.id} END)
AND (mitigatedDamage/rawDamage*100)>${DEVOTION_AURA_ACTIVE_DAMAGE_REDUCTION * 100 - 1}`;
}
load() {
return fetchWcl(`report/tables/damage-taken/${this.owner.report.code}`, {
start: this.owner.fight.start_time,
end: this.owner.fight.end_time,
filter: this.filter,
}).then(json => {
console.log('Received AM damage taken', json);
const totalDamageTaken = json.entries.reduce(
(damageTaken, entry) => damageTaken + entry.total,
0,
);
this.activeDamageReduced =
(totalDamageTaken / (1 - DEVOTION_AURA_ACTIVE_DAMAGE_REDUCTION)) *
DEVOTION_AURA_ACTIVE_DAMAGE_REDUCTION;
});
}
statistic() {
const tooltip = (
<Trans id="paladin.holy.modules.talents.devotionAuraDamageReduction.tooltip">
The total estimated damage reduced <strong>by the passive</strong> was{' '}
{formatThousands(this.passiveDamageReduced)} ({formatNumber(this.passiveDrps)} DRPS). This
has high accuracy.
<br />
The total estimated damage reduced <strong>during Aura Mastery</strong> was{' '}
{formatThousands(this.activeDamageReduced)} ({formatNumber(this.activeDrps)} DRPS). This has
a 99% accuracy.
<br />
<br />
This value is calculated using the <i>Optional DRs</i> method. This results in the lowest
possible damage reduction value being shown. This should be the correct value in most
circumstances.
<br />
<br />
Calculating the exact damage reduced by Devotion Aura is very time and resource consuming.
This method uses a very close estimation. The active damage reduced is calculated by taking
the total damage taken of the entire raid during <SpellLink
id={SPELLS.AURA_MASTERY.id}
/>{' '}
and calculating the damage reduced during this time. The passive damage reduction is
calculated by taking the exact damage reduction factor applicable and calculating the damage
reduced if that full effect was applied to the Paladin. Even though the passive damage
reduction is split among other nearby players, using your personal damage taken should
average it out very closely. More extensive tests that go over all damage events have shown
that this is usually a close approximation.
</Trans>
);
return (
<LazyLoadStatisticBox
position={STATISTIC_ORDER.OPTIONAL(60)}
loader={this.load.bind(this)}
icon={<SpellIcon id={SPELLS.DEVOTION_AURA.id} />}
value={<Trans id="paladin.holy.modules.talents.devotionAuraDamageReduction.drps">≈{formatNumber(this.totalDrps)} DRPS</Trans>}
label={<Trans id="paladin.holy.modules.talents.devotionAuraDamageReduction.damageReduction">Damage reduction</Trans>}
tooltip={tooltip}
drilldown={makeWclUrl(this.owner.report.code, {
fight: this.owner.fightId,
type: 'damage-taken',
pins: `2$Off$#244F4B$expression$${this.filter}`,
view: 'events',
})}
/>
);
}
}
export default DevotionAuraDamageReduction;
|
src/routes/hardware/index.js
|
bigearth/www.clone.earth
|
import React from 'react';
import Layout from '../../components/Layout';
import Hardware from './Hardware';
const title = 'Hardware';
export default {
path: '/hardware',
action() {
return {
title,
component: <Layout><Hardware title={title} /></Layout>,
};
},
};
|
app/cards/blog-card.js
|
gon250/personal-web
|
import React from 'react';
export default React.createClass({
render: function (){
let postDate = this.props.blogDate.toString().substring(0,10);
return (
<div className="mdl-grid mdl-cell mdl-cell--12-col mdl-cell--4-col-tablet mdl-card mdl-shadow--4dp">
<div className="mdl-card__title">
<h2 className="mdl-card__title-text">
{this.props.blogTitle}
</h2>
</div>
<div className="mdl-card__supporting-text no-bottom-padding">
<span>Posted {postDate}</span>
<div id="tt2"
onClick={this.props.blogActionShare}
className="icon material-icons portfolio-share-btn"
tabIndex="0">
share
</div>
</div>
<div className="mdl-card__supporting-text blog-card-content"
dangerouslySetInnerHTML={{__html: this.props.blogContent}}>
</div>
<div className="mdl-card__actions mdl-card--border">
<a
href={this.props.blogLink}
target="_blank"
className="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect mdl-button--accent">
View post →
</a>
</div>
</div>
)
}
});
|
src/svg-icons/navigation/chevron-right.js
|
kittyjumbalaya/material-components-web
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationChevronRight = (props) => (
<SvgIcon {...props}>
<path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
</SvgIcon>
);
NavigationChevronRight = pure(NavigationChevronRight);
NavigationChevronRight.displayName = 'NavigationChevronRight';
NavigationChevronRight.muiName = 'SvgIcon';
export default NavigationChevronRight;
|
apps/marketplace/components/Opportunity/EvaluationCriteria.js
|
AusDTO/dto-digitalmarketplace-frontend
|
import React from 'react'
import PropTypes from 'prop-types'
import AUheading from '@gov.au/headings/lib/js/react.js'
import styles from './EvaluationCriteria.scss'
const EvaluationCriteria = props => (
<div className={styles.container}>
<div className="row">
<div
role="columnheader"
id="header_criteria"
className={props.showWeightings ? `col-xs-8 col-sm-9` : `col-xs-12`}
>
<AUheading level={props.titleLevel} size={props.titleSize}>
{props.title}
</AUheading>
</div>
{props.showWeightings && (
<div role="columnheader" id="header_weighting" className="col-xs-4 col-sm-2 col-sm-offset-1">
<strong>Weighting</strong>
</div>
)}
</div>
{props.evaluationCriteria.map(evaluationCriteria => (
<div key={evaluationCriteria.criteria} className="row">
<div
role="cell"
aria-labelledby="header_criteria"
className={props.showWeightings ? `col-xs-8 col-sm-9 ${styles.newLines}` : `col-xs-12 ${styles.newLines}`}
>
{evaluationCriteria.criteria}
</div>
{props.showWeightings && (
<div role="cell" aria-labelledby="header_weighting" className="col-xs-4 col-sm-2 col-sm-offset-1">
{evaluationCriteria.weighting}%
</div>
)}
</div>
))}
</div>
)
EvaluationCriteria.defaultProps = {
evaluationCriteria: [],
showWeightings: true,
title: 'Evaluation criteria',
titleLevel: '2',
titleSize: 'lg'
}
EvaluationCriteria.propTypes = {
evaluationCriteria: PropTypes.array,
showWeightings: PropTypes.bool,
title: PropTypes.string,
titleLevel: PropTypes.string,
titleSize: PropTypes.string
}
export default EvaluationCriteria
|
backend/dynamic-web-apps/voting-app/client/src/components/Signup.js
|
mkermani144/freecodecamp-projects
|
import React, { Component } from 'react';
import { Redirect } from 'react-router';
import Paper from 'material-ui/Paper';
import { Step, Stepper, StepLabel, StepContent } from 'material-ui/Stepper';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
import CircularProgress from 'material-ui/CircularProgress';
import Snackbar from 'material-ui/Snackbar';
import { blue50, blue500 } from 'material-ui/styles/colors';
import './Login-Signup.css';
class Signup extends Component {
constructor() {
super();
this.state = {
stepIndex: 0,
progress: {
visibility: 'hidden'
},
textFieldError: 0,
nextDisabled: true,
username: '',
passwrod: '',
isLoggedIn: false,
submitFailed: false,
};
this.timeout = null;
this.errors = {
0: '',
1: 'Username is already taken',
3: 'Username is too short',
4: 'Username is too long',
5: 'Username is not valid',
6: 'Password must be at least 6 characters length',
7: 'Passwords entered do not match',
}
this.timeout = 0;
this.alive = true;
}
validateUsername = (username) => {
if (username.length < 6) {
return 3;
} else if (username.length > 20) {
return 4;
} else {
const testResult = (/^[a-zA-Z][a-zA-Z0-9_.]{4,18}[a-zA-Z0-9]$/).test(username);
if (testResult) {
return 0;
} else {
return 5;
}
}
}
handleNext = () => {
const { stepIndex } = this.state;
this.setState({
stepIndex: stepIndex + 1,
nextDisabled: stepIndex !== 2,
});
};
handlePrev = () => {
const { stepIndex } = this.state;
if (stepIndex > 0) {
this.setState({
stepIndex: stepIndex - 1,
textFieldError: '',
});
}
};
handleUsernameChange = (e) => {
clearTimeout(this.timeout);
const username = e.target.value;
this.timeout = setTimeout(() => {
const validationResult = this.validateUsername(username);
if (validationResult === 0) {
this.setState({
progress: {
visibility: 'visible',
},
}, async () => {
const response = await fetch('http://localhost:8000/api/findUser', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username
}),
});
const json = await response.json();
this.setState({
progress: {
visibility: 'hidden',
},
username,
textFieldError: +json.userExists,
nextDisabled: +json.userExists !== 0,
});
});
} else {
this.setState({
textFieldError: validationResult,
nextDisabled: true,
});
}
}, 200);
}
handlePasswordChange = (e) => {
const password = e.target.value;
if (password.length >= 6) {
this.setState({
password,
nextDisabled: false,
textFieldError: 0,
});
} else {
this.setState({
nextDisabled: true,
textFieldError: 6,
});
}
}
handlePasswordConfirmChange = (e) => {
const passwordConfirm = e.target.value;
if (passwordConfirm === this.state.password) {
this.setState({
nextDisabled: false,
textFieldError: 0,
});
} else {
this.setState({
nextDisabled: true,
textFieldError: 7,
});
}
}
handleSubmit = async () => {
this.props.logOut();
const response = await fetch('http://localhost:8000/signup', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password
}),
});
if (response.ok) {
this.setState({
isLoggedIn: true,
});
localStorage.setItem('username', this.state.username);
this.props.logIn(1, this.state.username);
const response = await fetch(`http://localhost:8000/api/userpolls/${this.state.username}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
});
const json = await response.json();
json.polls.forEach(poll => this.props.addPoll(poll.id, poll.owner, poll.title, poll.description, Object.keys(poll.choices).map(key => [key, poll.choices[key]])));
} else {
this.setState({
submitFailed: true,
});
}
}
handleSnackbarClose = () => {
this.setState({
submitFailed: false,
});
}
renderStepActions(step) {
const buttonStyle = {
marginTop: '5vmin',
marginLeft: '1vmin',
};
return (
<div className="step-actions">
{step > 0 && (
<FlatButton
label="Back"
disabled={step === 0}
disableTouchRipple={true}
disableFocusRipple={true}
onClick={this.handlePrev}
style={buttonStyle}
/>
)}
<RaisedButton
label={step === 3 ? 'Sign up' : 'Next'}
type='button'
disableTouchRipple={true}
disableFocusRipple={true}
primary={true}
onClick={step === 3 ? this.handleSubmit : this.handleNext}
style={buttonStyle}
disabled={this.state.nextDisabled}
/>
</div>
);
}
render() {
const signupStyle = {
backgroundColor: blue500
};
const paperStyle = {
padding: '5vmin',
width: '60vmin',
backgroundColor: blue50,
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
};
const { stepIndex } = this.state;
return this.state.isLoggedIn ? <Redirect to="/" /> : (
<div className="Signup" style={signupStyle}>
<Paper className="paper" style={paperStyle}>
<form>
<Stepper activeStep={stepIndex} orientation="vertical">
<Step>
<StepLabel>Choose a username</StepLabel>
<StepContent>
<div className="wrapper">
<TextField
name="username"
type="text"
floatingLabelText="Username"
floatingLabelFixed={true}
fullWidth={true}
autoFocus
onChange={this.handleUsernameChange}
errorText={this.errors[this.state.textFieldError]}
/>
<CircularProgress size={20} thickness={2} style={this.state.progress} />
</div>
{this.renderStepActions(0)}
</StepContent>
</Step>
<Step>
<StepLabel>Set a password</StepLabel>
<StepContent>
<div className="wrapper">
<TextField
name="password"
type="password"
floatingLabelText="Password"
floatingLabelFixed={true}
fullWidth={true}
autoFocus
onChange={this.handlePasswordChange}
errorText={this.errors[this.state.textFieldError]}
/>
<CircularProgress size={20} thickness={2} style={{visibility: 'hidden'}} />
</div>
{this.renderStepActions(1)}
</StepContent>
</Step>
<Step>
<StepLabel>Confirm password</StepLabel>
<StepContent>
<div className="wrapper">
<TextField
name="password"
type="password"
floatingLabelText="Password (Again)"
floatingLabelFixed={true}
fullWidth={true}
autoFocus
onChange={this.handlePasswordConfirmChange}
errorText={this.errors[this.state.textFieldError]}
/>
<CircularProgress size={20} thickness={2} style={{visibility: 'hidden'}} />
</div>
{this.renderStepActions(2)}
</StepContent>
</Step>
<Step>
<StepLabel>Finish signup</StepLabel>
<StepContent>
{this.renderStepActions(3)}
</StepContent>
</Step>
</Stepper>
</form>
</Paper>
<Snackbar
open={this.state.submitFailed}
message="Something bad happended. Try again later."
autoHideDuration={4000}
onRequestClose={this.handleSnackbarClose}
/>
</div>
);
}
}
export default Signup;
|
src/components/manage/ManageForm.js
|
oraclesorg/ico-wizard
|
import React from 'react'
import { Link } from 'react-router-dom'
import { FormSpy } from 'react-final-form'
import { FieldArray } from 'react-final-form-arrays'
import { ManageTierBlock } from './ManageTierBlock'
import classNames from 'classnames'
export const ManageForm = ({
handleSubmit,
invalid,
pristine,
handleChange,
canSave,
...props,
}) => (
<form onSubmit={handleSubmit}>
<FieldArray name="tiers">
{({ fields }) => (
<ManageTierBlock
fields={fields}
{...props}
/>
)}
</FieldArray>
<FormSpy subscription={{ values: true }} onChange={handleChange}/>
<div className="steps">
<div className="button-container">
<Link to='#' onClick={handleSubmit}>
<span className={classNames(
'no_arrow',
'button',
'button_fill',
{
'button_disabled': (pristine || invalid) && !canSave
}
)}>Save</span>
</Link>
</div>
</div>
</form>
)
|
src/Spring.js
|
wilfreddenton/react-motion
|
import React from 'react';
import components from './components';
module.exports = components(React);
|
src/Label/Label.driver.js
|
skyiea/wix-style-react
|
import React from 'react';
import ReactDOM from 'react-dom';
const labelDriverFactory = ({element, wrapper, component}) => {
return {
exists: () => !!element,
getTagName: () => element.tagName.toLowerCase(),
getLabelText: () => element.textContent,
getClassList: () => element.className,
getAttr: attrName => element.getAttribute(attrName),
setProps: props => {
const ClonedWithProps = React.cloneElement(component, Object.assign({}, component.props, props), ...(component.props.children || []));
ReactDOM.render(<div ref={r => element = r}>{ClonedWithProps}</div>, wrapper);
}
};
};
export default labelDriverFactory;
|
cm19/ReactJS/your-first-react-app-exercises-master/exercise-13/complete/friend-detail/FriendFlipper.js
|
Brandon-J-Campbell/codemash
|
import React from 'react';
import styles from './FriendFlipper.css';
export default class FriendFlipper extends React.Component {
state = {
flipped: false,
};
handleFlipped = () => {
this.setState(prevProps => {
return {
flipped: !prevProps.flipped,
};
});
};
render() {
return (
<div className={styles.flipWrapper}>
<div className={styles.flipper}>
{this.state.flipped ? null : this.renderFront()}
{!this.state.flipped ? null : this.renderBack()}
</div>
</div>
);
}
renderFront() {
const { friend } = this.props;
return (
<div className={styles.front}>
<div className={styles.frontContents}>
<img src={friend.image} alt={friend.image} />
<button
type="button"
className={styles.flipperNav}
onClick={this.handleFlipped}
>
Details >
</button>
</div>
</div>
);
}
renderBack() {
const { friend } = this.props;
return (
<div className={styles.back}>
<div className={styles.backContents}>
<img src={friend.image} alt={friend.image} />
<div className={styles.backDetails}>
<h3>
ID:
{friend.id}
</h3>
<h3>Colors:</h3>
<ul>
{friend.colors.map(color => (
<li key={color}>{color}</li>
))}
</ul>
</div>
<button
type="button"
className={styles.flipperNav}
onClick={this.handleFlipped}
>
< Back
</button>
</div>
</div>
);
}
}
|
node_modules/react-bootstrap/es/Tab.js
|
rblin081/drafting-client
|
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import _extends from 'babel-runtime/helpers/extends';
import React from 'react';
import PropTypes from 'prop-types';
import TabContainer from './TabContainer';
import TabContent from './TabContent';
import TabPane from './TabPane';
var propTypes = _extends({}, TabPane.propTypes, {
disabled: PropTypes.bool,
title: PropTypes.node,
/**
* tabClassName is used as className for the associated NavItem
*/
tabClassName: PropTypes.string
});
var Tab = function (_React$Component) {
_inherits(Tab, _React$Component);
function Tab() {
_classCallCheck(this, Tab);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Tab.prototype.render = function render() {
var props = _extends({}, this.props);
// These props are for the parent `<Tabs>` rather than the `<TabPane>`.
delete props.title;
delete props.disabled;
delete props.tabClassName;
return React.createElement(TabPane, props);
};
return Tab;
}(React.Component);
Tab.propTypes = propTypes;
Tab.Container = TabContainer;
Tab.Content = TabContent;
Tab.Pane = TabPane;
export default Tab;
|
src/index.js
|
attilad/console-room
|
import React from 'react';
import {render} from 'react-dom';
import HomePage from './containers/HomePage';
render(
<HomePage helloWorld="Hello, Universe!" />, document.getElementById('app')
);
|
blueocean-material-icons/src/js/components/svg-icons/hardware/keyboard-hide.js
|
kzantow/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const HardwareKeyboardHide = (props) => (
<SvgIcon {...props}>
<path d="M20 3H4c-1.1 0-1.99.9-1.99 2L2 15c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-9 3h2v2h-2V6zm0 3h2v2h-2V9zM8 6h2v2H8V6zm0 3h2v2H8V9zm-1 2H5V9h2v2zm0-3H5V6h2v2zm9 7H8v-2h8v2zm0-4h-2V9h2v2zm0-3h-2V6h2v2zm3 3h-2V9h2v2zm0-3h-2V6h2v2zm-7 15l4-4H8l4 4z"/>
</SvgIcon>
);
HardwareKeyboardHide.displayName = 'HardwareKeyboardHide';
HardwareKeyboardHide.muiName = 'SvgIcon';
export default HardwareKeyboardHide;
|
admin/src/components/ListHeader.js
|
lastjune/keystone
|
import classNames from 'classnames';
import React from 'react';
import utils from '../utils.js';
import { Button, Container, Dropdown, FormInput, InputGroup, Pagination } from 'elemental';
import CreateForm from './CreateForm';
import ListColumnsForm from './ListColumnsForm';
import ListDownloadForm from './ListDownloadForm';
import ListFilters from './ListFilters';
import ListFiltersAdd from './ListFiltersAdd';
import ListSort from './ListSort';
import CurrentListStore from '../stores/CurrentListStore';
var ListHeader = React.createClass({
displayName: 'ListHeader',
getInitialState () {
return {
createIsOpen: Keystone.showCreateForm,
manageIsOpen: false,
searchString: '',
...this.getStateFromStore()
};
},
componentDidMount () {
CurrentListStore.addChangeListener(this.updateStateFromStore);
},
componentWillUnmount () {
clearTimeout(this._searchTimeout);
CurrentListStore.removeChangeListener(this.updateStateFromStore);
},
getStateFromStore () {
return {
activeColumns: CurrentListStore.getActiveColumns(),
activeFilters: CurrentListStore.getActiveFilters(),
availableColumns: CurrentListStore.getAvailableColumns(),
currentPage: CurrentListStore.getCurrentPage(),
items: CurrentListStore.getItems(),
list: CurrentListStore.getList(),
pageSize: CurrentListStore.getPageSize(),
ready: CurrentListStore.isReady()
};
},
updateStateFromStore () {
this.setState(this.getStateFromStore());
},
toggleCreateModal (visible) {
this.setState({
createIsOpen: visible
});
},
toggleDownloadModal (visible) {
this.setState({
downloadIsOpen: visible
});
},
toggleManageOpen (filter = !this.state.manageIsOpen) {
this.setState({
manageIsOpen: filter
});
},
updateSearch (e) {
clearTimeout(this._searchTimeout);
this.setState({
searchString: e.target.value
});
var delay = e.target.value.length > 1 ? 250 : 0;
this._searchTimeout = setTimeout(() => {
CurrentListStore.setActiveSearch(this.state.searchString);
}, delay);
},
handleSearchClear () {
CurrentListStore.setActiveSearch('');
this.setState({ searchString: '' });
React.findDOMNode(this.refs.listSearchInput).focus();
},
handleSearchKey (e) {
// clear on esc
if (e.which === 27) {
this.handleSearchClear ();
}
},
handlePageSelect (i) {
CurrentListStore.setCurrentPage(i);
},
renderSearch () {
var searchClearIcon = classNames('ListHeader__search__icon octicon', {
'is-search octicon-search': !this.state.searchString.length,
'is-clear octicon-x': this.state.searchString.length
});
return (
<InputGroup.Section grow className="ListHeader__search">
<FormInput ref="listSearchInput" value={this.state.searchString} onChange={this.updateSearch} onKeyUp={this.handleSearchKey} placeholder="Search" className="ListHeader__searchbar-input" />
<button ref="listSearchClear" type="button" onClick={this.handleSearchClear} disabled={!this.state.searchString.length} className={searchClearIcon} />
</InputGroup.Section>
);
},
renderDownloadButton () {
return (
<InputGroup.Section>
<Button>
Download
<span className="disclosure-arrow" />
</Button>
</InputGroup.Section>
);
},
renderCreateButton () {
var props = { type: 'success' };
if (this.state.list.autocreate) {
props.href = '?new' + Keystone.csrf.query;
} else {
props.onClick = this.toggleCreateModal.bind(this, true);
}
return (
<InputGroup.Section className="ListHeader__create">
<Button {...props} title={'Create ' + this.state.list.singular}>
<span className="ListHeader__create__icon octicon octicon-plus" />
<span className="ListHeader__create__label">
Create
</span>
<span className="ListHeader__create__label--lg">
Create {this.state.list.singular}
</span>
</Button>
</InputGroup.Section>
);
},
renderCreateForm () {
return <CreateForm list={this.state.list} isOpen={this.state.createIsOpen} onCancel={this.toggleCreateModal.bind(this, false)} values={Keystone.createFormData} err={Keystone.createFormErrors} />;
},
renderManagement () {
let { items, manageIsOpen } = this.state;
if (!items.count) return;
let manageUI = manageIsOpen ? (
<div style={{ float: 'left', marginRight: 10 }}>
<InputGroup contiguous style={{ display: 'inline-flex', marginBottom: 0 }}>
<InputGroup.Section>
<Button>Select all</Button>
</InputGroup.Section>
<InputGroup.Section>
<Button>Select none</Button>
</InputGroup.Section>
</InputGroup>
<InputGroup contiguous style={{ display: 'inline-flex', marginBottom: 0, marginLeft: '.5em' }}>
<InputGroup.Section>
<Button>Update</Button>
</InputGroup.Section>
<InputGroup.Section>
<Button>Delete</Button>
</InputGroup.Section>
</InputGroup>
<Button type="link-cancel" onClick={this.toggleManageOpen.bind(this, false)}>Cancel</Button>
</div>
) : (
<Button onClick={this.toggleManageOpen.bind(this, true)} style={{ float: 'left', marginRight: 10 }}>Manage</Button>
);
return manageUI;
},
renderPagination () {
let { currentPage, items, list, manageIsOpen, pageSize } = this.state;
if (manageIsOpen || !items.count) return;
return (
<Pagination
className="ListHeader__pagination"
currentPage={currentPage}
onPageSelect={this.handlePageSelect}
pageSize={pageSize}
plural={list.plural}
singular={list.singular}
style={{ marginBottom: 0 }}
total={items.count}
/>
);
},
render () {
let { currentPage, items, list, pageSize } = this.state;
return (
<div className="ListHeader">
<Container>
<h2 className="ListHeader__title">
{utils.plural(items.count, ('* ' + list.singular), ('* ' + list.plural))}
<ListSort />
</h2>
<InputGroup className="ListHeader__bar">
{this.renderSearch()}
<ListFiltersAdd className="ListHeader__filter" />
<ListColumnsForm className="ListHeader__columns" />
<ListDownloadForm className="ListHeader__download" />
<InputGroup.Section className="ListHeader__expand">
<Button isActive={this.props.tableIsExpanded} onClick={this.props.toggleTableWidth} title="Expand table width">
<span className="octicon octicon-mirror" />
</Button>
</InputGroup.Section>
{this.renderCreateButton()}
</InputGroup>
<ListFilters />
<div style={{ height: 32, marginBottom: '2em' }}>
{this.renderManagement()}
{this.renderPagination()}
<span style={{ clear: 'both', display: 'table' }} />
</div>
</Container>
{this.renderCreateForm()}
</div>
);
}
});
module.exports = ListHeader;
|
cerberus-dashboard/src/components/SecureDataVersionsBrowser/SecureDataVersionsBrowser.js
|
Nike-Inc/cerberus
|
/*
* Copyright (c) 2020 Nike, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import { Component } from 'react';
import { connect } from 'react-redux';
import Loader from '../Loader/Loader';
import ReactPaginate from 'react-paginate';
import Select from 'react-select';
import * as vActions from '../../actions/versionHistoryBrowserActions.js';
import JSONPretty from 'react-json-pretty';
import './SecureDataVersionsBrowser.scss';
class SecureDataVersionsBrowser extends Component {
dispatch = this.props.dispatch;
// When the component mounts fetch the initial history data for the Safe Deposit Box
componentDidMount() {
if (!this.props.hasFetchedPathsWithHistory) {
this.dispatch(vActions.fetchVersionDataForSdb(this.props.safeDepositBoxId, this.props.cerberusAuthToken));
}
}
handlePageClick = (data) => {
let pageNumber = data.selected;
this.dispatch(vActions.updatePageNumber(pageNumber));
this.dispatch(vActions.fetchPathVersionData(this.props.versionPathSelected, this.props.cerberusAuthToken, pageNumber, this.props.versionPathPerPage));
};
handlePerPageSelect = (selected) => {
let perPage = selected.value;
let pageNumber = 0; // default back to the first page
this.dispatch(vActions.updatePerPage(perPage));
this.dispatch(vActions.updatePageNumber(pageNumber));
this.dispatch(vActions.fetchPathVersionData(this.props.versionPathSelected, this.props.cerberusAuthToken, pageNumber, perPage));
};
handleBreadCrumbHomeClick = () => {
this.dispatch(vActions.handleBreadCrumbHomeClick());
};
handleFetchVersion = (versionId) => {
this.dispatch(vActions.fetchVersionedSecureDataForPath(this.props.versionPathSelected, versionId, this.props.cerberusAuthToken));
};
handleDownloadVersion = (versionId) => {
this.dispatch(vActions.downloadSecureFileVersion(this.props.versionPathSelected, versionId, this.props.cerberusAuthToken));
};
handlePathWithHistoryClick = (path) => {
this.dispatch(vActions.fetchPathVersionData(path, this.props.cerberusAuthToken, this.props.versionPathPageNumber, this.props.versionPathPerPage));
};
render() {
const {
cerberusAuthToken,
hasFetchedPathsWithHistory,
pathsWithHistory,
hasFetchedVersionPathData,
versionPathSelected,
versionPathData,
versionPathPerPage,
versionPathPageNumber,
versionPathSecureDataMap
} = this.props;
const {
handlePerPageSelect,
handlePageClick,
handleBreadCrumbHomeClick,
handleFetchVersion,
handleDownloadVersion,
handlePathWithHistoryClick
} = this;
if (!hasFetchedPathsWithHistory) {
return (
<div className="secure-data-versions-browser">
<Loader />
</div>
);
}
return (
<div className="secure-data-versions-browser">
{!versionPathSelected &&
pathsWithHistoryList(pathsWithHistory, cerberusAuthToken, versionPathPageNumber, versionPathPerPage, handlePathWithHistoryClick)
}
{versionPathSelected &&
pathVersionsBrowser(versionPathSelected, hasFetchedVersionPathData, versionPathData, versionPathPerPage,
versionPathPageNumber, versionPathSecureDataMap, handlePerPageSelect, handlePageClick, handleBreadCrumbHomeClick, handleFetchVersion, handleDownloadVersion)
}
</div>
);
}
}
const pathsWithHistoryList = (pathsWithHistory, cerberusAuthToken, versionPathPageNumber, versionPathPerPage, handlePathWithHistoryClick) => {
return (
<div>
<h3 className="ncss-brand">Paths with version history</h3>
<div className="paths-with-history">
{pathsWithHistory && pathsWithHistory.map((path) =>
<div key={path}
className="path clickable ncss-brand"
onClick={() => { handlePathWithHistoryClick(path); }}>{path}</div>
)}
</div>
</div>
);
};
const pathVersionsBrowser = (versionPathSelected,
hasFetchedVersionPathData,
data,
perPage,
pageNumber,
versionPathSecureDataMap,
handlePerPageSelect,
handlePageClick,
handleBreadCrumbHomeClick,
handleFetchVersion,
handleDownloadVersion) => {
if (!hasFetchedVersionPathData) {
return (<Loader />);
}
return (
<div className="version-list-container">
<h3 className="ncss-brand">Version Summaries for Path: {versionPathSelected}</h3>
<div onClick={() => { handleBreadCrumbHomeClick(); }} className="breadcrumb clickable">Back to path list</div>
{pathVersionsBrowserPaginationMenu(data, perPage, pageNumber, handlePerPageSelect, handlePageClick)}
{summaries(data['secure_data_version_summaries'], handleFetchVersion, handleDownloadVersion, versionPathSecureDataMap)}
{pathVersionsBrowserPaginationMenu(data, perPage, pageNumber, handlePerPageSelect, handlePageClick)}
</div>
);
};
const summaries = (summaries, handleFetchVersion, handleDownloadVersion, versionPathSecureDataMap) => {
return (
<div className="path-version-summaries">
{summaries.map((summary, index) =>
generateVersionSummary(summary, index, handleFetchVersion, handleDownloadVersion, versionPathSecureDataMap).map(it => it)
)}
</div>
);
};
const generateVersionSummary = (summary, index, handleFetchVersion, handleDownloadVersion, versionPathSecureDataMap) => {
if (summary.action === 'DELETE') {
return [
<div className="version-summary" key={`${index}-deleted`}>
<div className="type">Type: {summary['type']}</div>
<div className="id">Version: <span className="deleted">DELETED</span></div>
<div className="principal-wrapper">
Deleted by <span className="principal">{summary['action_principal']}</span> on <span className="date">{new Date(summary['action_ts']).toLocaleString()}</span>
</div>
</div>,
versionSummary(summary, index, handleFetchVersion, handleDownloadVersion, versionPathSecureDataMap)
];
}
return [versionSummary(summary, index, handleFetchVersion, handleDownloadVersion, versionPathSecureDataMap)];
};
const versionSummary = (summary, index, handleFetchVersion, handleDownloadVersion, versionPathSecureDataMap) => {
let versionId = summary.id;
let dataForVersion = versionPathSecureDataMap.hasOwnProperty(versionId) ? versionPathSecureDataMap[versionId] : false;
return (
<div className="version-summary" key={index}>
<div className="id">Version: <span className={versionId === 'CURRENT' ? 'current' : ''}>{summary.id}</span></div>
<div className="type">Type: {summary['type']}</div>
{summary.type === 'FILE' &&
<div className="size-in-bytes">Size: {(summary['size_in_bytes'] / 1024).toFixed(2)} KB</div>
}
<div className="principal-wrapper">
Created by <span className="principal">{summary['version_created_by']}</span> on <span className="date">{new Date(summary['version_created_ts']).toLocaleString()}</span>
</div>
{summary.type === 'FILE' ?
(versionDownloadButton(handleDownloadVersion, versionId))
:
(dataForVersion ? secureDataForVersion(dataForVersion) : fetchVersionButton(handleFetchVersion, versionId))
}
</div>
);
};
const secureDataForVersion = (dataForVersion) => {
return (
<div className="secure-data-for-version-wrapper">
<div className="secure-data-for-version">
<JSONPretty json={dataForVersion} space="4"></JSONPretty>
</div>
</div>
);
};
const fetchVersionButton = (handleFetchVersion, versionId) => {
return (
<div
className='btn ncss-btn-dark-grey ncss-brand pt3-sm pr5-sm pb3-sm pl5-sm pt2-lg pb2-lg u-uppercase'
onClick={() => { handleFetchVersion(versionId); }}
>Show this version</div>
);
};
const versionDownloadButton = (handleDownloadVersion, versionId) => {
return (
<div
className='btn ncss-btn-dark-grey ncss-brand pt3-sm pr5-sm pb3-sm pl5-sm pt2-lg pb2-lg u-uppercase'
onClick={() => { handleDownloadVersion(versionId); }}
>Download</div>
);
};
const pathVersionsBrowserPaginationMenu = (pathData, perPage, pageNumber, handlePerPageSelect, handlePageClick) => {
const options = [
{ value: 5, label: '5' },
{ value: 10, label: '10' },
{ value: 25, label: '25' },
{ value: 50, label: '50' },
{ value: 100, label: '100' }
];
if (pageNumber === 0 && pathData.has_next === false) {
return (<div></div>);
}
let selected = options.find(option => option.value === perPage);
return (
<div className="version-pagination-menu paths-with-history-pagination-menu ncss-brand">
<ReactPaginate pageCount={Math.ceil(pathData.total_version_count / perPage)}
pageRangeDisplayed={3}
marginPagesDisplayed={1}
previousLabel={"Prev"}
nextLabel={"Next"}
onPageChange={handlePageClick}
forcePage={pageNumber}
containerClassName={"version-pagination"}
previousClassName={"version-previous-btn"}
nextClassName={"version-next-btn"}
previousLinkClassName={"ncss-btn-black ncss-brand pt2-sm pr5-sm pb2-sm pl5-sm"}
nextLinkClassName={"ncss-btn-black ncss-brand pt2-sm pr5-sm pb2-sm pl5-sm "}
pageClassName={"page-btn"}
breakClassName={"page-btn ncss-btn-light-grey disabled ncss-brand pt2-sm pr5-sm pb2-sm pl5-sm"}
pageLinkClassName={"ncss-btn-light-grey ncss-brand pt2-sm pr5-sm pb2-sm pl5-sm"}
activeClassName={"version-active"}
/>
<Select
className={'version-pagination-per-page-selector'}
onChange={handlePerPageSelect}
value={selected}
placeholder="Show Per Page"
options={options}
searchable={false}
clearable={false} />
</div>
);
};
const mapStateToProps = state => ({
// current sdb
safeDepositBoxId: state.manageSafetyDepositBox.data.id,
// user info
cerberusAuthToken: state.auth.cerberusAuthToken,
// version state
hasFetchedPathsWithHistory: state.versionHistoryBrowser.hasFetchedPathsWithHistory,
pathsWithHistory: state.versionHistoryBrowser.pathsWithHistory,
hasFetchedVersionPathData: state.versionHistoryBrowser.hasFetchedVersionPathData,
versionPathSelected: state.versionHistoryBrowser.versionPathSelected,
versionPathData: state.versionHistoryBrowser.versionPathData,
versionPathPerPage: state.versionHistoryBrowser.versionPathPerPage,
versionPathPageNumber: state.versionHistoryBrowser.versionPathPageNumber,
versionPathSecureDataMap: state.versionHistoryBrowser.versionPathSecureDataMap
});
export default connect(mapStateToProps)(SecureDataVersionsBrowser);
|
actor-apps/app-web/src/app/components/sidebar/HeaderSection.react.js
|
boneyao/actor-platform
|
import React from 'react';
import mixpanel from 'utils/Mixpanel';
import MyProfileActions from 'actions/MyProfileActions';
import LoginActionCreators from 'actions/LoginActionCreators';
import AvatarItem from 'components/common/AvatarItem.react';
import MyProfileModal from 'components/modals/MyProfile.react';
import ActorClient from 'utils/ActorClient';
import classNames from 'classnames';
var getStateFromStores = () => {
return {dialogInfo: null};
};
class HeaderSection extends React.Component {
componentWillMount() {
ActorClient.bindUser(ActorClient.getUid(), this.setUser);
}
constructor() {
super();
this.setUser = this.setUser.bind(this);
this.toggleHeaderMenu = this.toggleHeaderMenu.bind(this);
this.openMyProfile = this.openMyProfile.bind(this);
this.setLogout = this.setLogout.bind(this);
this.state = getStateFromStores();
}
setUser(user) {
this.setState({user: user});
}
toggleHeaderMenu() {
mixpanel.track('Open sidebar menu');
this.setState({isOpened: !this.state.isOpened});
}
setLogout() {
LoginActionCreators.setLoggedOut();
}
render() {
var user = this.state.user;
if (user) {
var headerClass = classNames('sidebar__header', 'sidebar__header--clickable', {
'sidebar__header--opened': this.state.isOpened
});
return (
<header className={headerClass}>
<div className="sidebar__header__user row" onClick={this.toggleHeaderMenu}>
<AvatarItem image={user.avatar}
placeholder={user.placeholder}
size="small"
title={user.name} />
<span className="sidebar__header__user__name col-xs">{user.name}</span>
<span className="sidebar__header__user__expand">
<i className="material-icons">keyboard_arrow_down</i>
</span>
</div>
<ul className="sidebar__header__menu">
<li className="sidebar__header__menu__item" onClick={this.openMyProfile}>
<i className="material-icons">person</i>
<span>Profile</span>
</li>
{/*
<li className="sidebar__header__menu__item" onClick={this.openCreateGroup}>
<i className="material-icons">group_add</i>
<span>Create group</span>
</li>
*/}
<li className="sidebar__header__menu__item hide">
<i className="material-icons">cached</i>
<span>Integrations</span>
</li>
<li className="sidebar__header__menu__item hide">
<i className="material-icons">settings</i>
<span>Settings</span>
</li>
<li className="sidebar__header__menu__item hide">
<i className="material-icons">help</i>
<span>Help</span>
</li>
<li className="sidebar__header__menu__item" onClick={this.setLogout}>
<i className="material-icons">power_settings_new</i>
<span>Log out</span>
</li>
</ul>
<MyProfileModal/>
</header>
);
} else {
return null;
}
}
openMyProfile() {
MyProfileActions.modalOpen();
mixpanel.track('My profile open');
this.setState({isOpened: false});
}
}
export default HeaderSection;
|
src/ModalBody.js
|
andrew-d/react-bootstrap
|
import React from 'react';
import classnames from 'classnames';
class ModalBody extends React.Component {
render() {
return (
<div {...this.props} className={classnames(this.props.className, this.props.modalClassName)}>
{this.props.children}
</div>
);
}
}
ModalBody.propTypes = {
/**
* A css class applied to the Component
*/
modalClassName: React.PropTypes.string
};
ModalBody.defaultProps = {
modalClassName: 'modal-body'
};
export default ModalBody;
|
wrappers/json.js
|
lukevance/personal_site
|
import React from 'react'
module.exports = React.createClass({
propTypes () {
return {
route: React.PropTypes.object,
}
},
render () {
const data = this.props.route.page.data
return (
<div>
<h1>{data.title}</h1>
<p>Raw view of json file</p>
<pre dangerouslySetInnerHTML={{ __html: JSON.stringify(data, null, 4) }} />
</div>
)
},
})
|
lib/ui/components/BottomBar/SearchInput.js
|
500tech/mimic
|
import React from 'react';
import styled from 'styled-components';
import Icon from 'ui/components/common/Icon';
import ActionIcon from 'ui/components/common/ActionIcon';
import IconDropdown from 'ui/components/common/IconDropdown';
import { Div } from 'ui/components/common/base';
import InputControl from 'ui/components/common/InputControl';
const Container = styled(Div)`
width: 300px;
height: 23px;
display: flex;
align-items: center;
border-right: ${(props) => props.theme.lightBorder};
`;
const SearchStyle = {
border: 'none',
height: '19px',
flex: '1',
outline: 'none',
'padding-left': '5px',
'font-size': '13px'
};
class SearchInput extends React.Component {
focusOnField = () => {
if (this.searchInput) {
this.searchInput.select();
}
};
render() {
return (
<Container>
<Icon src="search" onClick={ this.focusOnField }/>
<InputControl
style={ SearchStyle }
value={ this.props.query}
onBlur={ this.props.onBlur }
onFocus={ this.props.onFocus }
onChange={ this.props.onChange }
placeholder="Find"
inputRef={ (node) => this.searchInput = node }/>
{ this.props.query && <ActionIcon action="clear" onClick={ this.props.onClearQuery }/> }
<IconDropdown icon="filter"
value={ this.props.filterValue }
position="right"
align="left"
anchorPoint="bottom"
onChange={ this.props.onFilterChange }
options={ this.props.filterOptions }/>
</Container>
)
}
}
export default SearchInput;
|
sample/components/text-area.js
|
LINKIWI/react-elemental
|
import React from 'react';
import { Label, Spacing, Text, TextArea } from 'react-elemental';
const SampleTextArea = () => (
<div>
<Spacing size="huge" bottom>
<Text size="gamma" color="primary" uppercase>
Text areas
</Text>
<Text>
Allow the user to enter an arbitrary-length text blob.
</Text>
</Spacing>
<Spacing size="huge" bottom>
<Spacing bottom>
<Text size="iota" color="gray70" uppercase bold>
Generic
</Text>
</Spacing>
<Label
label="Text area"
sublabel="Type some monospaced text in here."
/>
<TextArea
placeholder="Type away"
style={{
height: '100px',
width: '600px',
}}
/>
</Spacing>
<Spacing size="huge" bottom>
<Spacing bottom>
<Text size="iota" color="gray70" uppercase bold>
Error state
</Text>
</Spacing>
<Label label="Oh noes" />
<TextArea
error="Some error message here"
placeholder="Bad text"
style={{
height: '100px',
width: '600px',
}}
/>
</Spacing>
<Spacing size="huge" bottom>
<Spacing bottom>
<Text size="iota" color="gray70" uppercase bold>
Secondary style
</Text>
</Spacing>
<Label label="Secondary variant" />
<TextArea
placeholder="The secondary style uses an underline border, similar to a secondary TextField"
style={{ width: '600px' }}
secondary
/>
</Spacing>
</div>
);
export default SampleTextArea;
|
src/svg-icons/maps/beenhere.js
|
w01fgang/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsBeenhere = (props) => (
<SvgIcon {...props}>
<path d="M19 1H5c-1.1 0-1.99.9-1.99 2L3 15.93c0 .69.35 1.3.88 1.66L12 23l8.11-5.41c.53-.36.88-.97.88-1.66L21 3c0-1.1-.9-2-2-2zm-9 15l-5-5 1.41-1.41L10 13.17l7.59-7.59L19 7l-9 9z"/>
</SvgIcon>
);
MapsBeenhere = pure(MapsBeenhere);
MapsBeenhere.displayName = 'MapsBeenhere';
MapsBeenhere.muiName = 'SvgIcon';
export default MapsBeenhere;
|
src/routes/courses/index.js
|
fkn/ndo
|
import React from 'react';
import Layout from '../../components/Layout';
import Courses from './Courses';
import { fetchCourses } from '../../actions/courses';
const title = 'Courses';
async function action({ store }) {
const { user } = store.getState();
if (user) {
await store.dispatch(fetchCourses(user.id));
}
return {
chunks: ['courses'],
title,
component: (
<Layout>
<Courses title={title} />
</Layout>
),
};
}
export default action;
|
src/svg-icons/communication/stay-primary-landscape.js
|
owencm/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationStayPrimaryLandscape = (props) => (
<SvgIcon {...props}>
<path d="M1.01 7L1 17c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2H3c-1.1 0-1.99.9-1.99 2zM19 7v10H5V7h14z"/>
</SvgIcon>
);
CommunicationStayPrimaryLandscape = pure(CommunicationStayPrimaryLandscape);
CommunicationStayPrimaryLandscape.displayName = 'CommunicationStayPrimaryLandscape';
CommunicationStayPrimaryLandscape.muiName = 'SvgIcon';
export default CommunicationStayPrimaryLandscape;
|
WasteApp/js/components/picker/index.js
|
airien/workbits
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Platform } from 'react-native';
import { Container, Header, Title, Content, Button, Icon, Picker, Text } from 'native-base';
import { openDrawer } from '../../actions/drawer';
import styles from './styles';
const Item = Picker.Item;
class NHPicker extends Component {
static propTypes = {
openDrawer: React.PropTypes.func,
}
constructor(props) {
super(props);
this.state = {
selectedItem: undefined,
selected1: 'key1',
results: {
items: [],
},
};
}
onValueChange(value: string) {
this.setState({
selected1: value,
});
}
render() {
return (
<Container style={styles.container}>
<Header>
<Title>Picker</Title>
<Button transparent onPress={this.props.openDrawer}>
<Icon name="ios-menu" />
</Button>
</Header>
<Content padder>
<Text>Select your Payment Mode</Text>
<Picker
iosHeader="Select one"
mode="dropdown"
selectedValue={this.state.selected1}
onValueChange={this.onValueChange.bind(this)} // eslint-disable-line
style={{ marginLeft: (Platform.OS === 'android') ? 0 : -25 }}
>
<Item label="Wallet" value="key0" />
<Item label="ATM Card" value="key1" />
<Item label="Debit Card" value="key2" />
<Item label="Credit Card" value="key3" />
<Item label="Net Banking" value="key4" />
</Picker>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
});
export default connect(mapStateToProps, bindAction)(NHPicker);
|
src/svg-icons/av/album.js
|
pancho111203/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvAlbum = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 14.5c-2.49 0-4.5-2.01-4.5-4.5S9.51 7.5 12 7.5s4.5 2.01 4.5 4.5-2.01 4.5-4.5 4.5zm0-5.5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1z"/>
</SvgIcon>
);
AvAlbum = pure(AvAlbum);
AvAlbum.displayName = 'AvAlbum';
AvAlbum.muiName = 'SvgIcon';
export default AvAlbum;
|
src/svg-icons/places/hot-tub.js
|
nathanmarks/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesHotTub = (props) => (
<SvgIcon {...props}>
<circle cx="7" cy="6" r="2"/><path d="M11.15 12c-.31-.22-.59-.46-.82-.72l-1.4-1.55c-.19-.21-.43-.38-.69-.5-.29-.14-.62-.23-.96-.23h-.03C6.01 9 5 10.01 5 11.25V12H2v8c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-8H11.15zM7 20H5v-6h2v6zm4 0H9v-6h2v6zm4 0h-2v-6h2v6zm4 0h-2v-6h2v6zm-.35-14.14l-.07-.07c-.57-.62-.82-1.41-.67-2.2L18 3h-1.89l-.06.43c-.2 1.36.27 2.71 1.3 3.72l.07.06c.57.62.82 1.41.67 2.2l-.11.59h1.91l.06-.43c.21-1.36-.27-2.71-1.3-3.71zm-4 0l-.07-.07c-.57-.62-.82-1.41-.67-2.2L14 3h-1.89l-.06.43c-.2 1.36.27 2.71 1.3 3.72l.07.06c.57.62.82 1.41.67 2.2l-.11.59h1.91l.06-.43c.21-1.36-.27-2.71-1.3-3.71z"/>
</SvgIcon>
);
PlacesHotTub = pure(PlacesHotTub);
PlacesHotTub.displayName = 'PlacesHotTub';
PlacesHotTub.muiName = 'SvgIcon';
export default PlacesHotTub;
|
app/screens/settings/theme/theme_tile.js
|
mattermost/mattermost-mobile
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import PropTypes from 'prop-types';
import React from 'react';
import {
Dimensions,
TouchableOpacity,
View,
} from 'react-native';
import CompassIcon from '@components/compass_icon';
import {changeOpacity} from '@mm-redux/utils/theme_utils';
import {makeStyleSheetFromTheme} from '@utils/theme';
import ThemeThumbnail from './theme_thumbnail';
const tilePadding = 8;
const ThemeTile = (props) => {
const {
action,
actionValue,
isLandscape,
isTablet,
label,
selected,
activeTheme,
tileTheme,
} = props;
const style = getStyleSheet(activeTheme);
const labelComponent = React.cloneElement(
label,
{style: style.label},
);
const tilesPerLine = isLandscape || isTablet ? 4 : 2;
const {width: deviceWidth} = Dimensions.get('window');
const fullWidth = isLandscape ? deviceWidth - 40 : deviceWidth;
const layoutStyle = {
container: {
width: (fullWidth / tilesPerLine) - tilePadding,
},
thumbnail: {
width: (fullWidth / tilesPerLine) - (tilePadding + 16),
},
};
return (
<TouchableOpacity
style={[style.container, layoutStyle.container]}
onPress={() => action(actionValue)}
>
<View style={[style.imageWrapper, layoutStyle.thumbnail]}>
<ThemeThumbnail
width={layoutStyle.thumbnail.width}
borderColorBase={selected ? activeTheme.sidebarTextActiveBorder : activeTheme.centerChannelBg}
borderColorMix={selected ? activeTheme.sidebarTextActiveBorder : changeOpacity(activeTheme.centerChannelColor, 0.16)}
sidebarBg={tileTheme.sidebarBg}
sidebarText={changeOpacity(tileTheme.sidebarText, 0.48)}
sidebarUnreadText={tileTheme.sidebarUnreadText}
sidebarTextActiveBorder={activeTheme.sidebarTextActiveBorder}
onlineIndicator={tileTheme.onlineIndicator}
awayIndicator={tileTheme.awayIndicator}
dndIndicator={tileTheme.dndIndicator}
centerChannelColor={changeOpacity(tileTheme.centerChannelColor, 0.16)}
centerChannelBg={tileTheme.centerChannelBg}
newMessageSeparator={tileTheme.newMessageSeparator}
buttonBg={tileTheme.buttonBg}
/>
{selected && (
<CompassIcon
name='check-circle'
size={31.2}
style={style.check}
/>
)}
</View>
{labelComponent}
</TouchableOpacity>
);
};
ThemeTile.propTypes = {
action: PropTypes.func,
actionValue: PropTypes.string,
isLandscape: PropTypes.bool.isRequired,
isTablet: PropTypes.bool.isRequired,
label: PropTypes.node.isRequired,
selected: PropTypes.bool,
activeTheme: PropTypes.object.isRequired,
tileTheme: PropTypes.object.isRequired,
};
ThemeTile.defaultProps = {
action: () => true,
};
const getStyleSheet = makeStyleSheetFromTheme((theme) => {
return {
container: {
flexDirection: 'column',
padding: tilePadding,
marginTop: 8,
},
imageWrapper: {
position: 'relative',
alignItems: 'flex-start',
marginBottom: 12,
},
thumbnail: {
resizeMode: 'stretch',
},
check: {
position: 'absolute',
right: 5,
bottom: 5,
color: theme.sidebarTextActiveBorder,
},
label: {
color: theme.centerChannelColor,
fontSize: 15,
},
};
});
export default ThemeTile;
|
src/components/Portfolio/Portfolio.js
|
karim88/karim88.github.io
|
import React, { Component } from 'react';
import './Portfolio.css';
class Portfolio extends Component {
constructor (props) {
super(props);
this.portfolio = props.portfolio.map((project) => {
return <div key={project.id} className="col-md-3 col-lg-4">
<div className="card-img" style={{
backgroundImage: `url(${project.image})`,
backgroundPosition: 'center'
}}>
<div className="technologie-shape"/>
<div className="technologie wow zoomIn">{project.technologie}</div>
<div className="layer">
<a href={project.link} aria-label={`link to ${project.link}`} target="_blank" rel="noopener noreferrer">
<i className="fas fa-link fa-3x link-icon"></i>
</a>
</div>
</div>
</div>
});
}
render() {
return (
<div className="portfolio">
<h2>PORTFOLIO</h2>
<div className="row">
{this.portfolio}
</div>
</div>
);
}
}
export default Portfolio;
|
src/app.js
|
beaudavenport/regex-cafe
|
import React from 'react';
import ReactDOM from 'react-dom';
import lessons from './lessons';
import Lesson from './Lesson';
import Navbar from './Navbar';
import Introduction from './Introduction';
import Faq from './Faq';
class App extends React.Component {
render() {
let lessonsOutput = this.props.lessons.map((lesson) => {
return (<Lesson key={`lesson${lesson.number}`} lesson={lesson} />);
});
return (
<div>
<Navbar />
<div className="container">
<Introduction />
</div>
<div className="container lessons">
{lessonsOutput}
</div>
<div className="container">
<Faq />
</div>
</div>
);
}
}
ReactDOM.render(<App lessons={lessons} />, document.getElementById('content'));
|
src/svg-icons/device/battery-charging-60.js
|
mit-cml/iot-website-source
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBatteryCharging60 = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V11h3.87L13 7v4h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9l1.87-3.5H7v9.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V11h-4v1.5z"/>
</SvgIcon>
);
DeviceBatteryCharging60 = pure(DeviceBatteryCharging60);
DeviceBatteryCharging60.displayName = 'DeviceBatteryCharging60';
DeviceBatteryCharging60.muiName = 'SvgIcon';
export default DeviceBatteryCharging60;
|
src/components/button/button.js
|
thinktopography/reframe
|
import React from 'react'
import PropTypes from 'prop-types'
class Button extends React.Component {
static contextTypes = {
confirm: PropTypes.object,
drawer: PropTypes.object,
flash: PropTypes.object,
modal: PropTypes.object,
router: PropTypes.object
}
static propTypes = {
basic: PropTypes.bool,
className: PropTypes.string,
color: PropTypes.string,
component: PropTypes.any,
confirm: PropTypes.any,
children: PropTypes.any,
disabled: PropTypes.bool,
drawer: PropTypes.any,
error: PropTypes.string,
location: PropTypes.string,
handler: PropTypes.func,
icon: PropTypes.string,
label: PropTypes.string,
link: PropTypes.string,
mobile: PropTypes.bool,
modal: PropTypes.oneOfType([
PropTypes.element,
PropTypes.func
]),
request: PropTypes.shape({
method: PropTypes.string,
endpoint: PropTypes.string,
onFailure: PropTypes.func,
onSuccess: PropTypes.func
}),
route: PropTypes.string,
status: PropTypes.string,
text: PropTypes.string,
onDone: PropTypes.func,
onRequest: PropTypes.func
}
static defaultProps = {
basic: false,
mobile: true,
disabled: false,
onDone: () => {}
}
render() {
const { children, component, icon, label, text } = this.props
return (
<div { ...this._getButton() }>
{ icon && <i className={`fa fa-fw fa-${icon}`} /> }
{ label || text || children }
{ component }
</div>
)
}
_getButton() {
const { disabled, link } = this.props
return {
href: link ? link : null,
className: this._getClass(),
disabled,
target: link ? '_blank' : null,
onClick: !link ? this._handleClick.bind(this) : null
}
}
_getClass() {
const { component, basic, className, color, disabled, mobile, status } = this.props
if(component) return ''
const classes = className ? className.split(' ') : ['ui', color, 'fluid', 'button']
classes.push('reframe-button')
if(mobile !== false) classes.push('mobile')
if(basic) classes.push('basic')
if(disabled) classes.push('disabled')
if(status === 'submitting') classes.push('loading')
return classes.join(' ')
}
componentDidUpdate(prevProps) {
const { flash } = this.context
const { error, status } = this.props
if(prevProps.status !== status && status === 'failure') {
flash.set('error', error)
}
}
_handleClick() {
const { confirm, disabled, drawer, handler, location, modal, request, route, onDone } = this.props
if(disabled) return
const yesHandler = () => {
if(route) this._handleRoute(route)
if(request) this._handleRequest(request)
if(modal) this._handleModal(modal)
if(drawer) this._handleDrawer(drawer, location)
if(handler) this._handleFunction(handler)
}
onDone()
if(confirm) return this.context.confirm.open(confirm, yesHandler)
yesHandler()
}
_handleRoute(route) {
this.context.router.push(route)
}
_handleModal(component) {
this.context.modal.open(component)
}
_handleDrawer(component, location) {
this.context.drawer.open(component, location)
}
_handleFunction(handler) {
handler(() => {})
}
_handleRequest(itemRequest) {
const { onRequest } = this.props
onRequest({
...itemRequest,
body: null,
params: null
})
}
}
export default Button
|
src/app/components/forms/inputs/UiSlider.js
|
backpackcoder/world-in-flames
|
import React from 'react'
import 'script-loader!bootstrap-slider/dist/bootstrap-slider.min.js'
export default class UiSlider extends React.Component {
componentDidMount() {
$(this.refs.slider).bootstrapSlider();
}
render() {
return <input type="text" ref="slider" {...this.props} />
}
}
|
src/modules/components/WaveShapeSelector/index.js
|
ruebel/synth-react-redux
|
import React from 'react';
import PropTypes from 'prop-types';
import Select from '../Select';
import { waveShapes } from '../../../utils/audio';
const WaveShapeSelector = ({ value, change }) => {
const options = waveShapes.map(s => ({ id: s, name: s }));
return (
<div>
<Select
labelKey="name"
onChange={e => change(e.id)}
options={options}
searchable={false}
title="Shape"
value={value}
valueKey="id"
/>
</div>
);
};
WaveShapeSelector.propTypes = {
value: PropTypes.string,
change: PropTypes.func.isRequired
};
export default WaveShapeSelector;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.