path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
src/svg-icons/av/replay.js
|
skarnecki/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvReplay = (props) => (
<SvgIcon {...props}>
<path d="M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"/>
</SvgIcon>
);
AvReplay = pure(AvReplay);
AvReplay.displayName = 'AvReplay';
export default AvReplay;
|
src/components/Layout.js
|
RanjithNair/FeatureTracker
|
import React from 'react';
import Header from './common/Header';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {signOut} from '../actions/authActions';
class Layout extends React.Component {
constructor(props, context) {
super(props, context);
}
render() {
const {auth, actions, loading, user} = this.props;
return (
<div>
<Header signOut={actions.signOut} auth={auth} loading={loading} user={user} />
{this.props.children}
</div>
);
}
}
Layout.propTypes = {
children: React.PropTypes.object,
actions: React.PropTypes.object.isRequired,
auth: React.PropTypes.object.isRequired,
user: React.PropTypes.object.isRequired,
loading: React.PropTypes.bool.isRequired
};
function mapStateToProps(state, ownProps) {
return {
auth: state.auth,
user: state.user,
loading: state.ajaxCallsInProgress > 0
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators({signOut}, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Layout);
|
tests/components/AttemptComponent.spec.js
|
theosherry/react-hangman
|
import React from 'react'
import skinDeep from 'skin-deep'
import TestUtils from 'react-addons-test-utils'
import Popover from 'material-ui/lib/popover/popover'
import {AttemptComponent} from 'components/AttemptComponent/AttemptComponent'
import classes from 'components/AttemptComponent/AttemptComponent.scss'
function shallowRender (component) {
const renderer = TestUtils.createRenderer()
renderer.render(component)
return renderer.getRenderOutput()
}
function renderWithProps (props = {}) {
return TestUtils.renderIntoDocument(<AttemptComponent {...props} />)
}
function shallowRenderWithProps (props = {}) {
return skinDeep.shallowRender(<AttemptComponent {...props} />)
// return shallowRender(<AttemptComponent {...props} />)
}
describe('(Component) AttemptComponent', function () {
var _component, _props
beforeEach(function () {
_props = {}
_component = shallowRenderWithProps(_props)
})
describe('paper Popover', function () {
it('should have paper popover with text value being attempt prop', function () {
_props = {
..._props,
attempt: 'test'
}
_component = shallowRenderWithProps(_props)
const popover = _component.subTree('Popover')
expect(popover.props.children).to.equal('test')
})
it('should have open prop being true when AttemptComponent active prop is true', function () {
_props = {
..._props,
active: true
}
_component = shallowRenderWithProps(_props)
var popover = _component.subTree('Popover')
expect(popover.props.open).to.equal(true)
})
it('should have open prop being false when AttemptComponent active prop is false', function () {
_props = {
..._props,
active: false
}
_component = shallowRenderWithProps(_props)
var popover = _component.subTree('Popover')
expect(popover.props.open).to.equal(false)
})
})
it('should trigger passed in onMouseEnterCB when component is hovered', function () {
_props = {
..._props,
onMouseEnterCB: sinon.spy()
}
_component = shallowRenderWithProps(_props)
expect(_props.onMouseEnterCB).to.not.have.been.called
_component.props.onMouseEnter()
expect(_props.onMouseEnterCB).to.have.been.called
})
it('should trigger passed in onMouseLeaveCB when component is un-hovered', function () {
_props = {
..._props,
onMouseLeaveCB: sinon.spy()
}
_component = shallowRenderWithProps(_props)
expect(_props.onMouseLeaveCB).to.not.have.been.called
_component.props.onMouseLeave()
expect(_props.onMouseLeaveCB).to.have.been.called
})
})
|
src/containers/pages/reddit/post/content/post-comments/post-comments-header.js
|
vFujin/HearthLounge
|
import React from 'react'
import { connect } from "react-redux";
const PostCommentsHeader = ({post}) => {
return (
<div className="section__header">
<div className="line"/>
<h1>{post.num_comments} {post.num_comments === 1 ? "comment" : "comments"}</h1>
</div>
)
};
const mapStateToProps = state => {
const { post } = state.redditPosts.activePost;
return { post };
};
export default connect(mapStateToProps)(PostCommentsHeader);
|
test/AlertSpec.js
|
rapilabs/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Alert from '../src/Alert';
describe('Alert', function () {
it('Should output a alert with message', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Alert>
<strong>Message</strong>
</Alert>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong'));
});
it('Should have bsType by default', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Alert>
Message
</Alert>
);
assert.ok(React.findDOMNode(instance).className.match(/\balert\b/));
});
it('Should have dismissable style with onDismiss', function () {
let noOp = function () {};
let instance = ReactTestUtils.renderIntoDocument(
<Alert onDismiss={noOp}>
Message
</Alert>
);
assert.ok(React.findDOMNode(instance).className.match(/\balert-dismissable\b/));
});
it('Should call onDismiss callback on dismiss click', function (done) {
let doneOp = function () {
done();
};
let instance = ReactTestUtils.renderIntoDocument(
<Alert onDismiss={doneOp}>
Message
</Alert>
);
ReactTestUtils.Simulate.click(React.findDOMNode(instance).children[0]);
});
it('Should call onDismiss callback on dismissAfter time', function (done) {
let doneOp = function () {
done();
};
ReactTestUtils.renderIntoDocument(
<Alert onDismiss={doneOp} dismissAfter={1}>
Message
</Alert>
);
});
it('Should have a default bsStyle class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Alert>
Message
</Alert>
);
assert.ok(React.findDOMNode(instance).className.match(/\balert-\w+\b/));
});
it('Should have use bsStyle class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Alert bsStyle='danger'>
Message
</Alert>
);
assert.ok(React.findDOMNode(instance).className.match(/\balert-danger\b/));
});
describe('Web Accessibility', function(){
it('Should have alert role', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Alert>Message</Alert>
);
assert.equal(React.findDOMNode(instance).getAttribute('role'), 'alert');
});
it('Should have add ARIAs to button', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Alert onDismiss={()=>{}} closeLabel='close'>Message</Alert>
);
let button = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'button');
assert.equal(React.findDOMNode(button).getAttribute('aria-label'), 'close');
assert.equal(React.findDOMNode(button).children[0].getAttribute('aria-hidden'), 'true');
});
});
});
|
client/src/Weather.js
|
t-gabor/sunshade-control
|
import React from 'react';
import Paper from 'material-ui/Paper';
import './Weather.css';
export default (props) => {
if(!props.weather)
return <Paper className="weather"/>
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(props.weather.observationTime);
return (
<Paper className="weather" >
{props.weather.summary}({props.weather.weatherCode}), {props.weather.temperature}°C<br/>
WindSpeed: {props.weather.windSpeed} km/h<br/>
PrecipIntensity: {props.weather.precipIntensity}<br/>
{d.toString()}
</Paper>);
};
|
docs/app/Examples/elements/Header/Variations/HeaderExampleColored.js
|
aabustamante/Semantic-UI-React
|
import React from 'react'
import { Header } from 'semantic-ui-react'
const HeaderExampleColored = () => (
<div>
<Header as='h4' color='red'>Red</Header>
<Header as='h4' color='orange'>Orange</Header>
<Header as='h4' color='yellow'>Yellow</Header>
<Header as='h4' color='olive'>Olive</Header>
<Header as='h4' color='green'>Green</Header>
<Header as='h4' color='teal'>Teal</Header>
<Header as='h4' color='blue'>Blue</Header>
<Header as='h4' color='purple'>Purple</Header>
<Header as='h4' color='violet'>Violet</Header>
<Header as='h4' color='pink'>Pink</Header>
<Header as='h4' color='brown'>Brown</Header>
<Header as='h4' color='grey'>Grey</Header>
</div>
)
export default HeaderExampleColored
|
src/containers/pageNavigatorContainer/index.js
|
MichaelQQ/Oyasumi
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import PageNavigator from '../../components/pageNavigator';
import { prev, next } from './action';
export const PageNavigatorContainer = ({ ...props }) => {
const { page, maxPage, onPrev, onNext } = props;
return page
? (
<PageNavigator
page={page}
maxPage={maxPage}
onPrev={onPrev}
onNext={onNext}
/>)
: (<div></div>);
};
const mapStateToProps = (state) => ({
page: state.searchInfo.lastPage,
maxPage: state.searchInfo.maxPage,
});
const mapDispatchToProps = (dispatch) => ({
onPrev: (e) => dispatch(prev(e)),
onNext: (e) => dispatch(next(e)),
});
const {
func,
number,
} = PropTypes;
PageNavigatorContainer.propTypes = {
page: number,
maxPage: number,
onPrev: func.isRequired,
onNext: func.isRequired,
};
export default connect(mapStateToProps, mapDispatchToProps)(PageNavigatorContainer);
|
powerauth-webflow/src/main/js/components/loginSca.js
|
lime-company/powerauth-webflow
|
/*
* PowerAuth Web Flow and related software components
* Copyright (C) 2019 Wultra s.r.o.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react';
import ReactDOM from 'react-dom';
import {connect} from 'react-redux';
// Actions
import {
authenticate,
cancel,
checkClientCertificate,
initLoginSca,
organizationConfigurationError,
selectOrganization
} from '../actions/loginScaActions'
// Components
import {Button, FormControl, FormGroup, Panel, Tab, Tabs} from 'react-bootstrap';
import Spinner from './spinner';
import OperationTimeout from "./operationTimeout";
// i18n
import {FormattedMessage} from 'react-intl';
import OrganizationSelect from "./organizationSelect";
/**
* SCA login component handles the user authentication using two factors.
*/
@connect((store) => {
return {
context: store.dispatching.context
}
})
export default class LoginSca extends React.Component {
constructor() {
super();
this.handleLogin = this.handleLogin.bind(this);
this.handleCancel = this.handleCancel.bind(this);
this.organizationChanged = this.organizationChanged.bind(this);
this.verifyClientCertificate = this.verifyClientCertificate.bind(this);
this.init = this.init.bind(this);
this.setDefaultOrganization = this.setDefaultOrganization.bind(this);
this.updateButtonState = this.updateButtonState.bind(this);
this.state = {continueDisabled: true};
}
componentWillMount() {
this.init();
}
init() {
const props = this.props;
const setDefaultOrganization = this.setDefaultOrganization;
props.dispatch(initLoginSca(function(initSucceeded) {
if (initSucceeded) {
// Set the default organization after loading organizations unless chosen organization was previously set
if (props.context.chosenOrganizationId === undefined) {
setDefaultOrganization();
}
}
}));
}
handleLogin(event) {
event.preventDefault();
const organizationId = this.props.context.chosenOrganizationId;
const usernameField = "username" + "_" + organizationId;
const username = ReactDOM.findDOMNode(this.refs[usernameField]);
this.props.dispatch(authenticate(username.value, organizationId));
}
handleCancel(event) {
event.preventDefault();
const organizationId = this.props.context.chosenOrganizationId;
const usernameField = "username" + "_" + organizationId;
const username = ReactDOM.findDOMNode(this.refs[usernameField]);
this.props.dispatch(cancel());
username.value = "";
}
render() {
return (
<div id="login">
{this.props.context.loading ?
<Spinner/>
:
<form onSubmit={this.handleLogin}>
{this.mainPanel()}
</form>
}
</div>
)
}
mainPanel() {
const organizations = this.props.context.organizations;
if (organizations === undefined) {
// Organization list is not loaded yet
return undefined;
}
if (organizations.length === 1) {
return this.singleOrganization();
} else if (organizations.length > 1 && organizations.length < 4) {
return this.fewOrganizations();
} else if (organizations.length >= 4) {
return this.manyOrganizations();
} else {
this.props.dispatch(organizationConfigurationError());
}
}
singleOrganization() {
const organizations = this.props.context.organizations;
return (
<Panel>
{this.banners(true)}
{this.title()}
{this.loginForm(organizations[0].organizationId)}
</Panel>
)
}
fewOrganizations() {
const formatMessage = this.props.intl.formatMessage;
const organizations = this.props.context.organizations;
return (
<Tabs defaultActiveKey={this.props.context.chosenOrganizationId} onSelect={key => this.organizationChanged(key)}>
{organizations.map((org) => {
return (
<Tab key={org.organizationId} eventKey={org.organizationId} title={formatMessage({id: org.displayNameKey})}>
<Panel>
{this.banners(org.organizationId === this.props.context.chosenOrganizationId)}
{this.title()}
{this.loginForm(org.organizationId)}
</Panel>
</Tab>
)
})}
</Tabs>
)
}
manyOrganizations() {
const organizations = this.props.context.organizations;
const chosenOrganizationId = this.props.context.chosenOrganizationId;
const formatMessage = this.props.intl.formatMessage;
let chosenOrganization = organizations[0];
organizations.forEach(function (org) {
// perform i18n, the select component does not support i18n
org.displayName = formatMessage({id: org.displayNameKey});
if (org.organizationId === chosenOrganizationId) {
chosenOrganization = org;
}
});
return (
<Panel>
<OrganizationSelect
organizations={organizations}
chosenOrganization={chosenOrganization}
intl={this.props.intl}
callback={organization => this.organizationChanged(organization.organizationId)}
/>
{this.banners(true)}
{this.title()}
{this.loginForm(chosenOrganizationId)}
</Panel>
)
}
setDefaultOrganization() {
const organizations = this.props.context.organizations;
let defaultOrganizationId = organizations[0].organizationId;
organizations.forEach(function (org) {
if (org.default === true) {
defaultOrganizationId = org.organizationId;
}
});
this.props.dispatch(selectOrganization(defaultOrganizationId));
}
organizationChanged(organizationId) {
this.props.dispatch(selectOrganization(organizationId));
}
updateButtonState() {
if (this.props.context.chosenOrganizationId === undefined) {
return;
}
const usernameField = "username" + "_" + this.props.context.chosenOrganizationId;
if (document.getElementById(usernameField).value.length === 0) {
if (!this.state.continueDisabled) {
this.setState({continueDisabled: true});
}
} else {
if (this.state.continueDisabled) {
this.setState({continueDisabled: false});
}
}
}
verifyClientCertificate() {
const organizationId = this.props.context.chosenOrganizationId;
const certificateVerificationUrl = this.props.context.clientCertificateVerificationUrl;
const dispatch = this.props.dispatch;
const callbackOnSuccess = function() {
// Authentication is performed using client certificate
dispatch(authenticate(null, organizationId));
};
dispatch(checkClientCertificate(certificateVerificationUrl, callbackOnSuccess));
}
banners(timeoutCheckActive) {
return (
<OperationTimeout timeoutCheckActive={timeoutCheckActive}/>
)
}
title() {
return (
<FormGroup className="title">
<FormattedMessage id="login.pleaseLogIn"/>
</FormGroup>
)
}
loginForm(organizationId) {
const usernameField = "username" + "_" + organizationId;
const formatMessage = this.props.intl.formatMessage;
return(
<div>
{this.props.context.error ? (
<FormGroup className="message-error">
<FormattedMessage id={this.props.context.message}/>
{(this.props.context.remainingAttempts > 0) ? (
<div>
<FormattedMessage
id="authentication.attemptsRemaining"/> {this.props.context.remainingAttempts}
</div>
) : undefined }
</FormGroup>
) : undefined }
<FormGroup>
<FormControl autoComplete="new-password" id={usernameField} ref={usernameField} type="text" maxLength={usernameMaxLength}
placeholder={formatMessage({id: 'login.loginNumber'})} autoFocus
onChange={this.updateButtonState.bind(this)}/>
</FormGroup>
{this.props.context.clientCertificateAuthenticationAvailable ? (
<div>
<FormGroup>
<div className="row">
<div className="col-xs-6">
</div>
<div className="col-xs-6">
<Button bsSize="lg" type="submit" bsStyle="success" block>
<FormattedMessage id="loginSca.confirmInit"/>
</Button>
</div>
</div>
</FormGroup>
<hr/>
<FormGroup>
<div className="row">
<div className="col-xs-6 client-certificate-label">
<FormattedMessage id="clientCertificate.login"/>
</div>
<div className="col-xs-6">
{this.props.context.clientCertificateAuthenticationEnabled ? (
<a href="#" onClick={this.verifyClientCertificate} className="btn btn-lg btn-success">
<FormattedMessage id="clientCertificate.use"/>
</a>
) : (
<div className="btn btn-lg btn-default disabled">
<FormattedMessage id="clientCertificate.use"/>
</div>
)}
</div>
</div>
</FormGroup>
<FormGroup>
<div className="row">
<div className="col-xs-6">
<a href="#" onClick={this.handleCancel} className="btn btn-lg btn-default">
<FormattedMessage id="login.cancel"/>
</a>
</div>
</div>
</FormGroup>
</div>
) : (
<FormGroup>
<div className="row buttons">
<div className="col-xs-6">
<a href="#" onClick={this.handleCancel} className="btn btn-lg btn-default">
<FormattedMessage id="login.cancel"/>
</a>
</div>
<div className="col-xs-6">
<Button bsSize="lg" type="submit" bsStyle="success" block disabled={this.state.continueDisabled}>
<FormattedMessage id="loginSca.continue"/>
</Button>
</div>
</div>
</FormGroup>
)}
</div>
)
}
}
|
app/components/ColorChanger/Title/index.js
|
cerebral/cerebral-boilerplate
|
import React from 'react';
import styles from './styles.css';
function Title(props) {
return (
<h1 style={{color: props.color}} className={styles.title}>
{props.children}
</h1>
);
}
Title.propTypes = {
color: React.PropTypes.string.isRequired,
children: React.PropTypes.any.isRequired
};
export default Title;
|
client/modules/App/__tests__/Components/Header.spec.js
|
phumberdroz/pizzastore
|
import React from 'react';
import test from 'ava';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import Header from '../../components/Header/Header';
test('renders the header properly', t => {
const router = {
isActive: sinon.stub().returns(true),
};
const wrapper = shallow(
<Header toggleAddPost={() => {}} />,
{
context: {
router,
},
}
);
t.regex(wrapper.find('Link').first().html(), /MERN Starter Blog/);
t.is(wrapper.find('a').length, 1);
});
test('doesn\'t add post in pages other than home', t => {
const router = {
isActive: sinon.stub().returns(false),
};
const wrapper = shallow(
<Header toggleAddPost={() => {}} />,
{
context: {
router,
},
}
);
t.is(wrapper.find('a').length, 0);
});
test('toggleAddPost called properly', t => {
const router = {
isActive: sinon.stub().returns(true),
};
const toggleAddPost = sinon.spy();
const wrapper = shallow(
<Header toggleAddPost={toggleAddPost} />,
{
context: {
router,
},
}
);
wrapper.find('a').first().simulate('click');
t.truthy(toggleAddPost.calledOnce);
});
|
src/svg-icons/navigation/close.js
|
kasra-co/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationClose = (props) => (
<SvgIcon {...props}>
<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
</SvgIcon>
);
NavigationClose = pure(NavigationClose);
NavigationClose.displayName = 'NavigationClose';
NavigationClose.muiName = 'SvgIcon';
export default NavigationClose;
|
src/server/Server.js
|
scopevale/carpers-paradise
|
import express from 'express';
import stormpath from 'express-stormpath';
import path from 'path';
import favicon from 'serve-favicon';
import logger from 'morgan';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
// my routes
import routes from './routes/index.js';
import booking from './routes/booking.js';
//import error from './routes/error.js';
//import request from 'request';
import React from 'react';
import ReactDOMServer from 'react-dom/Server';
import TestHarness from './TestHarness';
class Server {
constructor(environmentConfig) {
this.env = environmentConfig;
this.port = this.env.port();
this.server = express();
this.init();
}
// errorHandler(req, res) {
// res.send('<!DOCTYPE html>' +
// ReactDOMServer
// .renderToStaticMarkup(
// <TestHarness
// testType='manual'
// pageName='error'
// />
// )
// );
// }
init() {
// Axway data request for usage graph
//
// this.server.use('/axway', (req, res) => {
// var options = {
// url: `http://api-a.ec2.impello.co.uk:8082${req.url}`
// };
//
// req.pipe(request(options))
// .on('error', (e) => {
// console.log(e);
// })
// .pipe(res)
// .on('error', (e) => {
// console.log(e);
// });
// });
// end data request
// automated Selenium tests
// this.server.get('/automated-tests/*', (req, res) => {
// res.send('<!DOCTYPE html>' +
// ReactDOMServer
// .renderToStaticMarkup(
// <TestHarness
// testType='automated'
// pageName='home'
// />
// )
// );
// });
// uncomment after placing your favicon in /build/client/images
this.server.use(favicon(path.join(__dirname, './../../build/client/images', 'favicon.png')));
// console.log(path.join(__dirname, './../../build/client/images', 'favicon.png'));
// console.log(path.join(__dirname, './../../build/client'));
this.server.use(logger('dev'));
this.server.use(bodyParser.json());
this.server.use(bodyParser.urlencoded({ extended: false }));
this.server.use(cookieParser());
this.server.use(express.static(path.join(__dirname, './../../build/client')));
this.server.use('^(/|/home|/index)', routes);
this.server.use('/booking', booking);
// catch 404 and forward to error handler
this.server.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (this.server.get('env') === 'development') {
// this.server.use(null, error);
this.server.use(function (err, req, res, next) {
res.status(err.status || 500);
res.send('<!DOCTYPE html>' +
ReactDOMServer
.renderToStaticMarkup(
<TestHarness
testType='manual'
pageName='error'
/>
)
);
next(err);
// res.render('error', {
// message: err.message,
// error: err
// });
});
}
// production error handler
// no stacktraces leaked to user
this.server.use(function (err, req, res, next) {
res.status(err.status || 500);
res.send('<!DOCTYPE html>' +
ReactDOMServer
.renderToStaticMarkup(
<TestHarness
testType='manual'
pageName='error'
/>
)
);
// res.render('error', {
// message: err.message,
// error: {}
// });
});
}
start() {
stormpath.init(this.server, {
website: true
});
this.server.on('stormpath.ready', () => {
this.server.listen(this.port, 'localhost', (err) => {
if (err) {
return console.error(err);
}
console.log('Listening at http://localhost:' + this.port);
});
});
}
}
export default Server;
|
src/layouts/MetaContainer/metacontainer.js
|
aberkow/gatsby-blog
|
import React from 'react';
|
generators/component/templates/src/app/component.js
|
FountainJS/generator-fountain-react
|
<% if (modules === 'webpack') { -%>
const React = require('react');
export default React.createClass({
<% } -%>
<% if (modules === 'systemjs') { -%>
import React from 'react';
export default React.createClass({
<% } -%>
<% if (modules === 'inject') { -%>
window.<%- className %> = React.createClass({
<% } -%>
getDefaultProps: function () {
return {
text: 'My brand new component!'
};
},
propTypes: {
text: React.PropTypes.string
},
render: function () {
return (
<div>
<h2>{this.props.text}</h2>
</div>
);
}
});
|
client/admin/scenes/protected/project/project-list.js
|
kirinami/portfolio
|
import React, { Component } from 'react';
import { Breadcrumb, BreadcrumbItem } from 'reactstrap';
import { Link } from 'react-router-dom';
import { inject, observer } from 'mobx-react';
import Loading from '../../../components/loading';
@inject('alertStore', 'projectStore')
@observer
export default class ProjectList extends Component {
componentDidMount() {
const { alertStore, projectStore } = this.props;
projectStore
.then(response => alertStore.showSuccess(response.message))
.catch(err => alertStore.showDanger(err.message));
}
async handleRemove(project) {
const { alertStore, projectStore } = this.props;
let response = {};
if (confirm('Remove this project?')) {
response = await projectStore.removeProject(project._id);
}
if (response.success) {
alertStore.showSuccess(response.message);
} else {
alertStore.showDanger(response.message);
}
}
render() {
const { projectStore } = this.props;
const { isLoading, projects } = projectStore;
if (isLoading) {
return <Loading/>;
}
return (
<div className="project-list-component">
<Breadcrumb>
<BreadcrumbItem>
<Link to="/">Dashboard</Link>
</BreadcrumbItem>
<BreadcrumbItem active>Projects</BreadcrumbItem>
</Breadcrumb>
<div className="row mb-3">
<div className="col-md-8">
<div className="py-2" style={{ lineHeight: '1.3rem' }}>
<small className="text-muted">Projects found: {projects.length}</small>
</div>
</div>
<div className="col-md-4">
<Link className="btn btn-block btn-success" to="/project/new"><i className="fa fa-fw fa-plus"/> Create</Link>
</div>
</div>
<div className="row">
{projects.map(project =>
<div key={project._id} className="col-md-6">
<div className="card mb-3">
{/*
<div className="card-img-top" style={{
height: '35vh',
background: `url('${project.image.url}') 50% 50% / cover no-repeat`
}}/>
*/}
<img className="card-img-top" src={`/uploads/projects/${project._id}/${project.image.filename}`} alt=""/>
<div className="card-body">
<h4 className="card-title">{project.title}</h4>
<p className="card-text">{project.description}</p>
</div>
<div className="card-footer bg-white">
<div className="row">
<div className="col-lg-6 mb-2 mb-lg-0 pt-lg-1-9">
<small className="text-muted">{project.updatedAt}</small>
</div>
<div className="col-lg-6 text-lg-right">
<Link className="btn btn-primary mr-1 mb-1 mb-lg-0" to={`/project/edit/${project._id}`}>
<i className="fa fa-fw fa-edit"/> </Link>
<button className="btn btn-danger mb-1 mb-lg-0" onClick={() => this.handleRemove(project)}>
<i className="fa fa-fw fa-trash"/>
</button>
</div>
</div>
</div>
</div>
</div>,
)}
</div>
</div>
);
}
}
|
internals/templates/appContainer.js
|
adoveil/max
|
/**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import styles from './styles.css';
export default class App extends React.Component { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: React.PropTypes.node,
};
render() {
return (
<div className={styles.container}>
{React.Children.toArray(this.props.children)}
</div>
);
}
}
|
src/containers/Root.js
|
ghartong/react_falcor
|
import React from 'react'
import {Provider} from 'react-redux'
import {Router} from 'react-router'
import routes from '../routes'
import createHashHistory from 'history/lib/createHashHistory'
export default class Root extends React.Component {
static propTypes = {
history: React.PropTypes.object.isRequired,
store: React.PropTypes.object.isRequired
}
render() {
return (
<Provider store={this.props.store}>
<div>
<Router history={this.props.history}>
{routes}
</Router>
</div>
</Provider>
)
}
}
|
frontend/src/Settings/Notifications/Notifications/EditNotificationModalContent.js
|
lidarr/Lidarr
|
import PropTypes from 'prop-types';
import React from 'react';
import Alert from 'Components/Alert';
import Form from 'Components/Form/Form';
import FormGroup from 'Components/Form/FormGroup';
import FormInputGroup from 'Components/Form/FormInputGroup';
import FormLabel from 'Components/Form/FormLabel';
import ProviderFieldFormGroup from 'Components/Form/ProviderFieldFormGroup';
import Button from 'Components/Link/Button';
import SpinnerErrorButton from 'Components/Link/SpinnerErrorButton';
import LoadingIndicator from 'Components/Loading/LoadingIndicator';
import ModalBody from 'Components/Modal/ModalBody';
import ModalContent from 'Components/Modal/ModalContent';
import ModalFooter from 'Components/Modal/ModalFooter';
import ModalHeader from 'Components/Modal/ModalHeader';
import { inputTypes, kinds } from 'Helpers/Props';
import NotificationEventItems from './NotificationEventItems';
import styles from './EditNotificationModalContent.css';
function EditNotificationModalContent(props) {
const {
advancedSettings,
isFetching,
error,
isSaving,
isTesting,
saveError,
item,
onInputChange,
onFieldChange,
onModalClose,
onSavePress,
onTestPress,
onDeleteNotificationPress,
...otherProps
} = props;
const {
id,
implementationName,
name,
tags,
fields,
message
} = item;
return (
<ModalContent onModalClose={onModalClose}>
<ModalHeader>
{`${id ? 'Edit' : 'Add'} Connection - ${implementationName}`}
</ModalHeader>
<ModalBody>
{
isFetching &&
<LoadingIndicator />
}
{
!isFetching && !!error &&
<div>Unable to add a new notification, please try again.</div>
}
{
!isFetching && !error &&
<Form {...otherProps}>
{
!!message &&
<Alert
className={styles.message}
kind={message.value.type}
>
{message.value.message}
</Alert>
}
<FormGroup>
<FormLabel>Name</FormLabel>
<FormInputGroup
type={inputTypes.TEXT}
name="name"
{...name}
onChange={onInputChange}
/>
</FormGroup>
<NotificationEventItems
item={item}
onInputChange={onInputChange}
/>
<FormGroup>
<FormLabel>Tags</FormLabel>
<FormInputGroup
type={inputTypes.TAG}
name="tags"
helpText="Only send notifications for artist with at least one matching tag"
{...tags}
onChange={onInputChange}
/>
</FormGroup>
{
fields.map((field) => {
return (
<ProviderFieldFormGroup
key={field.name}
advancedSettings={advancedSettings}
provider="notification"
providerData={item}
section="settings.notifications"
{...field}
onChange={onFieldChange}
/>
);
})
}
</Form>
}
</ModalBody>
<ModalFooter>
{
id &&
<Button
className={styles.deleteButton}
kind={kinds.DANGER}
onPress={onDeleteNotificationPress}
>
Delete
</Button>
}
<SpinnerErrorButton
isSpinning={isTesting}
error={saveError}
onPress={onTestPress}
>
Test
</SpinnerErrorButton>
<Button
onPress={onModalClose}
>
Cancel
</Button>
<SpinnerErrorButton
isSpinning={isSaving}
error={saveError}
onPress={onSavePress}
>
Save
</SpinnerErrorButton>
</ModalFooter>
</ModalContent>
);
}
EditNotificationModalContent.propTypes = {
advancedSettings: PropTypes.bool.isRequired,
isFetching: PropTypes.bool.isRequired,
error: PropTypes.object,
isSaving: PropTypes.bool.isRequired,
isTesting: PropTypes.bool.isRequired,
saveError: PropTypes.object,
item: PropTypes.object.isRequired,
onInputChange: PropTypes.func.isRequired,
onFieldChange: PropTypes.func.isRequired,
onModalClose: PropTypes.func.isRequired,
onSavePress: PropTypes.func.isRequired,
onTestPress: PropTypes.func.isRequired,
onDeleteNotificationPress: PropTypes.func
};
export default EditNotificationModalContent;
|
src/features/ViewMenuItems/Views/TitleHeader.js
|
erhathaway/cellular_automata
|
import React from 'react';
import styled, { css } from 'react-emotion';
import PropTypes from 'prop-types';
// dock top or bottom
const ContainerHorizontal = css`
border-bottom: 1px solid rgba(72, 72, 72, 0.5);
padding-bottom: 5px;
`;
// dock left or right
const ContainerVertical = css`
`;
// has not docked
const ContainerNotDocked = css`
`;
// dock right
const ContainerVerticalRight = css`
text-align: right;
`;
const Container = styled('h2')`
// color: #464646;
color: white;
font-size: 10px;
margin: 0px;
margin-top: 5px;
margin-bottom: 5px;
width: 100%;
text-align: left;
text-transform: uppercase;
letter-spacing: 2.3px;
user-select: none;
${({ menuPlacement }) => ((!menuPlacement || !menuPlacement.includes('hasDocked')) && ContainerNotDocked)}
${({ menuPlacement }) => (menuPlacement && menuPlacement.includes('hasDockedTop') && ContainerHorizontal)}
${({ menuPlacement }) => (menuPlacement && (menuPlacement.includes('hasDockedLeft') || menuPlacement.includes('hasDockedRight')) && ContainerVertical)}
${({ menuPlacement }) => (menuPlacement && (menuPlacement.includes('hasDockedRight')) && ContainerVerticalRight)}
`;
const Component = ({ children, menuPlacement }) => (
<Container menuPlacement={menuPlacement}>
{ children }
</Container>
);
Component.propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node,
]).isRequired,
menuPlacement: PropTypes.string,
};
Component.defaultProps = {
menuPlacement: undefined,
};
export default Component;
|
app/scripts/components/LandingPage/__tests__/AppBar-test.js
|
andela-ekupara/DcManFrontEnd
|
'use strict';
import React from 'react';
import {browserHistory} from 'react-router';
import sinon, {spy, stub} from 'sinon';
import expect from 'expect';
import {mount, shallow} from 'enzyme';
import NavAppBar from '../AppBar.jsx';
import AuthModal from '../../Auth/AuthModal.jsx';
import AppBar from 'material-ui/lib/app-bar';
describe('Nav Bar Tests', function() {
let wrapper;
beforeEach(() => wrapper = shallow(<NavAppBar />));
it('renders the NavAppBar', () => {
expect(wrapper).toExist();
});
it('renders NavAppBar with the correct content', function() {
let component = mount(<NavAppBar />);
expect(component.find('DCMan'))
expect(component.find(AppBar).length).toEqual(2);
expect(component.find(AuthModal).length).toEqual(1);
component.unmount();
});
it('redirects to the homepage on handleTap()', function() {
// Should be handled correctly
let component = mount(<NavAppBar />);
sinon.spy(browserHistory, 'push');
NavAppBar.prototype.handleTap();
expect(browserHistory.push.withArgs('/').called).toBe(true);
browserHistory.push.restore();
component.unmount();
});
});
|
packages/mineral-ui-icons/src/IconSwapVert.js
|
mineral-ui/mineral-ui
|
/* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconSwapVert(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M16 17.01V10h-2v7.01h-3L15 21l4-3.99h-3zM9 3L5 6.99h3V14h2V6.99h3L9 3z"/>
</g>
</Icon>
);
}
IconSwapVert.displayName = 'IconSwapVert';
IconSwapVert.category = 'action';
|
node_modules/react-bootstrap/es/NavItem.js
|
superKaigon/TheCave
|
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import SafeAnchor from './SafeAnchor';
import createChainedFunction from './utils/createChainedFunction';
var propTypes = {
active: PropTypes.bool,
disabled: PropTypes.bool,
role: PropTypes.string,
href: PropTypes.string,
onClick: PropTypes.func,
onSelect: PropTypes.func,
eventKey: PropTypes.any
};
var defaultProps = {
active: false,
disabled: false
};
var NavItem = function (_React$Component) {
_inherits(NavItem, _React$Component);
function NavItem(props, context) {
_classCallCheck(this, NavItem);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleClick = _this.handleClick.bind(_this);
return _this;
}
NavItem.prototype.handleClick = function handleClick(e) {
if (this.props.onSelect) {
e.preventDefault();
if (!this.props.disabled) {
this.props.onSelect(this.props.eventKey, e);
}
}
};
NavItem.prototype.render = function render() {
var _props = this.props,
active = _props.active,
disabled = _props.disabled,
onClick = _props.onClick,
className = _props.className,
style = _props.style,
props = _objectWithoutProperties(_props, ['active', 'disabled', 'onClick', 'className', 'style']);
delete props.onSelect;
delete props.eventKey;
// These are injected down by `<Nav>` for building `<SubNav>`s.
delete props.activeKey;
delete props.activeHref;
if (!props.role) {
if (props.href === '#') {
props.role = 'button';
}
} else if (props.role === 'tab') {
props['aria-selected'] = active;
}
return React.createElement(
'li',
{
role: 'presentation',
className: classNames(className, { active: active, disabled: disabled }),
style: style
},
React.createElement(SafeAnchor, _extends({}, props, {
disabled: disabled,
onClick: createChainedFunction(onClick, this.handleClick)
}))
);
};
return NavItem;
}(React.Component);
NavItem.propTypes = propTypes;
NavItem.defaultProps = defaultProps;
export default NavItem;
|
tests/layouts/CoreLayout.spec.js
|
rui19921122/StationTransformBrowserClient
|
import React from 'react'
import TestUtils from 'react-addons-test-utils'
import CoreLayout from 'layouts/CoreLayout/CoreLayout'
function shallowRender (component) {
const renderer = TestUtils.createRenderer()
renderer.render(component)
return renderer.getRenderOutput()
}
function shallowRenderWithProps (props = {}) {
return shallowRender(<CoreLayout {...props} />)
}
describe('(Layout) Core', function () {
let _component
let _props
let _child
beforeEach(function () {
_child = <h1 className='child'>Child</h1>
_props = {
children : _child
}
_component = shallowRenderWithProps(_props)
})
it('Should render as a <div>.', function () {
expect(_component.type).to.equal('div')
})
})
|
examples/huge-apps/routes/Course/components/Nav.js
|
nhunzaker/react-router
|
import React from 'react'
import { Link } from 'react-router'
const styles = {}
styles.nav = {
borderBottom: '1px solid #aaa'
}
styles.link = {
display: 'inline-block',
padding: 10,
textDecoration: 'none'
}
styles.activeLink = {
...styles.link,
color: 'red'
}
class Nav extends React.Component {
render() {
const { course } = this.props
const pages = [
[ 'announcements', 'Announcements' ],
[ 'assignments', 'Assignments' ],
[ 'grades', 'Grades' ]
]
return (
<nav style={styles.nav}>
{pages.map((page, index) => (
<Link
key={page[0]}
activeStyle={index === 0 ? { ...styles.activeLink, paddingLeft: 0 } : styles.activeLink}
style={index === 0 ? { ...styles.link, paddingLeft: 0 } : styles.link}
to={`/course/${course.id}/${page[0]}`}
>{page[1]}</Link>
))}
</nav>
)
}
}
export default Nav
|
docs/app/Examples/collections/Grid/Content/index.js
|
koenvg/Semantic-UI-React
|
import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const GridContentExamples = () => (
<ExampleSection title='Content'>
<ComponentExample
title='Rows'
description='A row is a horizontal grouping of columns.'
examplePath='collections/Grid/Content/GridExampleRows'
/>
<ComponentExample
title='Columns'
description='Columns each contain gutters giving them equal spacing from other columns.'
examplePath='collections/Grid/Content/GridExampleColumns'
/>
</ExampleSection>
)
export default GridContentExamples
|
src/desktop/components/react/current_auctions/index.js
|
kanaabe/force
|
import CurrentAuctions from './current_auctions'
import invariant from 'invariant'
import React from 'react'
import ReactDOM from 'react-dom'
import { isEmpty, isString } from 'underscore'
export { CurrentAuctions }
export default function mount(
data,
selector = '#react-mount-current-auctions'
) {
const { auctionContextId, sales } = data
const shouldMount = !isEmpty(sales) && isString(selector)
invariant(
shouldMount,
`Error mounting <CurrentAuctions />: sales (${sales.map(
(s) => s.id
)}) or ` + `selector (${selector}) is invalid.`
)
if (shouldMount) {
const mountPoint = document.querySelector(selector)
ReactDOM.render(
<CurrentAuctions auctionContextId={auctionContextId} sales={sales} />,
mountPoint
)
}
}
|
test/ColSpec.js
|
BespokeInsights/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Col from '../src/Col';
describe('Col', function () {
it('Should set Offset of zero', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Col xsOffset={0} smOffset={0} mdOffset={0} lgOffset={0} />
);
let instanceClassName = React.findDOMNode(instance).className;
assert.ok(instanceClassName.match(/\bcol-xs-offset-0\b/));
assert.ok(instanceClassName.match(/\bcol-sm-offset-0\b/));
assert.ok(instanceClassName.match(/\bcol-md-offset-0\b/));
assert.ok(instanceClassName.match(/\bcol-lg-offset-0\b/));
});
it('Should set Pull of zero', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Col xsPull={0} smPull={0} mdPull={0} lgPull={0} />
);
let instanceClassName = React.findDOMNode(instance).className;
assert.ok(instanceClassName.match(/\bcol-xs-pull-0\b/));
assert.ok(instanceClassName.match(/\bcol-sm-pull-0\b/));
assert.ok(instanceClassName.match(/\bcol-md-pull-0\b/));
assert.ok(instanceClassName.match(/\bcol-lg-pull-0\b/));
});
it('Should set Push of zero', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Col xsPush={0} smPush={0} mdPush={0} lgPush={0} />
);
let instanceClassName = React.findDOMNode(instance).className;
assert.ok(instanceClassName.match(/\bcol-xs-push-0\b/));
assert.ok(instanceClassName.match(/\bcol-sm-push-0\b/));
assert.ok(instanceClassName.match(/\bcol-md-push-0\b/));
assert.ok(instanceClassName.match(/\bcol-lg-push-0\b/));
});
});
|
src/routes/RegisterStudent/components/RegisterForm.js
|
gabrielmf/SIR-EDU-2.0
|
import React from 'react'
import { TextField, SelectField, MenuItem, DatePicker, Checkbox, RaisedButton } from 'material-ui'
import Dropzone from 'components/Dropzone'
import MultipleCheckboxes from './MultipleCheckboxes'
import TermOfUse from './TermOfUse'
const specialNeeds = [{name: 'Altas Habilidades/Superdotado'},
{name: 'Deficiência Visual/Cegueira'},
{name: 'Deficiência Física'},
{name: 'Dislexia'},
{name: 'Deficiência Múltipla'},
{name: 'Síndrome de Ritt'},
{name: 'Transtorno do Espectro Autista'},
{name: 'Baixa Visão'},
{name: 'Deficiência Auditiva/Surdez'},
{name: 'Deficiência Intelectual'},
{name: 'Transtorno de Oposição e desafio(TOD)'},
{name: 'Síndrome de Down'},
{name: 'Surdocegueira'},
{name: 'Síndrome do X frágil'},
{name: 'Transtornos psicóticos agudos e transitórios'},
{name: 'Transtorno de conduta'}
];
export default class RegisterForm extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.onImageDrop = this.onImageDrop.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleCheckboxGroup = this.handleCheckboxGroup.bind(this);
this.showTermOfUse = this.showTermOfUse.bind(this);
this.openTermOfUse = false;
}
onImageDrop(field, file) {
this.setState({ [field]: file });
}
handleChange(event, id, valueParam) {
let name = '';
let value = null;
if (event) {
name = event.target.name;
value = event.target.value;
} else {
name = id;
value = valueParam;
}
this.setState({ [name]: value });
}
handleCheckbox = (event, value) => {
this.setState({ [event.target.name]: value });
}
handleSelectChange = (event, index, values, stateProp) => {
this.setState({[stateProp] : values});
}
handleCheckboxGroup(value) {
let newSelectionArray;
if(this.state.specialNeeds && this.state.specialNeeds.indexOf(value) > -1) {
newSelectionArray = this.state.specialNeeds.filter(s => s !== value)
} else {
newSelectionArray = [...this.state.specialNeeds || '', value];
}
this.setState({ specialNeeds: newSelectionArray });
}
handleSubmit(evt) {
evt.preventDefault();
this.props.handleSubmit(this.state);
}
showTermOfUse() {
this.openTermOfUse = true;
}
render() {
return (
<form onSubmit={this.handleSubmit}>
{this.props.step === 0 &&
<div>
<div class="col-md-12">
<label>Imagem do aluno:</label>
<span class="text-center">
<Dropzone
multiple={false}
accept={"image/*"}
name="avatar"
onDrop={this.onImageDrop}
initConfig={this.state.avatar}
text={"Arraste e solte uma imagem ou clique no botão para selecionar um arquivo"}>
</Dropzone>
</span>
</div>
<div class="col-md-6">
<TextField class="col-md-6" fullWidth={true} value={this.state.name || ''} type="text" name="name" onChange={this.handleChange} floatingLabelText="Nome:"/>
<TextField class="col-md-6" fullWidth={true} value={this.state.registration || ''} type="number" name="registration" onChange={this.handleChange} floatingLabelText="Matrícula:"/>
<TextField class="col-md-6" fullWidth={true} value={this.state.classNumber || ''} type="number" name="classNumber" onChange={this.handleChange} floatingLabelText="Turma:"/>
<TextField class="col-md-6" fullWidth={true} value={this.state.shift || ''} type="text" name="shift" onChange={this.handleChange} floatingLabelText="Turno:"/>
<TextField class="col-md-6" fullWidth={true} value={this.state.series || ''} type="text" name="series" onChange={this.handleChange} floatingLabelText="Ano/Série:"/>
<DatePicker class="col-md-6" fullWidth={true} DateTimeFormat={Intl.DateTimeFormat} locale="pt-br"value={this.state.birthdate || {}} name="birthdate" onChange={(evt, value)=>{this.handleChange(evt, 'birthdate', value)}} floatingLabelText="Data Nascimento:"/>
<TextField class="col-md-6" fullWidth={true} value={this.state.motherName || ''} type="text" name="motherName" onChange={this.handleChange} floatingLabelText="Nome da Mãe:"/>
</div>
<div class="col-md-6">
<TextField class="col-md-6" fullWidth={true} value={this.state.relationship || ''} type="text" name="relationship" onChange={this.handleChange} floatingLabelText="Parentesco:"/>
<TextField class="col-md-6" fullWidth={true} value={this.state.phoneNumber || ''} type="number" name="phoneNumber" onChange={this.handleChange} floatingLabelText="Telefone:"/>
<TextField class="col-md-6" fullWidth={true} value={this.state.adress || ''} type="text" name="adress" onChange={this.handleChange} floatingLabelText="Endereço:"/>
<TextField class="col-md-6" fullWidth={true} value={this.state.cid || ''} type="text" name="cid" onChange={this.handleChange} floatingLabelText="CID:"/>
<TextField class="col-md-6" fullWidth={true} name="school" value={this.state.school || ''} type="text" onChange={this.handleChange} floatingLabelText="Escola:"/>
<TextField class="col-md-6" fullWidth={true} value={this.state.fatherName || ''} type="text" name="fatherName" onChange={this.handleChange} floatingLabelText="Nome da Pai:"/>
<TextField class="col-md-6" fullWidth={true} value={this.state.responsible || ''} type="text" name="responsible" onChange={this.handleChange} floatingLabelText="Responsável:"/>
</div>
</div>
}
{this.props.step === 1 &&
<div class="col-md-12">
<TextField fullWidth={true} value={this.state.professorNEE || ''} type="text" name="professorNEE" onChange={this.handleChange} floatingLabelText="Professor NEE:"/>
<TextField fullWidth={true} value={this.state.orientation || ''} type="text" name="orientation" onChange={this.handleChange} floatingLabelText="Orientação Educacional:"/>
<TextField fullWidth={true} value={this.state.coordination || ''} type="text" name="coordination" onChange={this.handleChange} floatingLabelText="Coordenação Pedagógica:"/>
<DatePicker fullWidth={true} DateTimeFormat={Intl.DateTimeFormat} locale="pt-br" value={this.state.routingDate || {}} name="routingDate" onChange={(evt, value)=>{this.handleChange(evt, 'routingDate', value)}} floatingLabelText="Data de encaminhamento a AEE/SIR:"/>
<TextField fullWidth={true} multiLine={true} value={this.state.routingReason || ''} type="text" name="routingReason" onChange={this.handleChange} floatingLabelText="Motivo do encaminhamento:"/>
</div>
}
{this.props.step === 2 &&
<div>
<MultipleCheckboxes specialNeeds={specialNeeds} values={this.state.specialNeeds || []} handleCheckboxGroup={this.handleCheckboxGroup}/>
<TextField fullWidth={true} value={this.state.otherSpecialNeeds || ''} type="text" name="otherSpecialNeeds" onChange={this.handleChange} floatingLabelText="Outras necessidades especiais:"/>
</div>
}
{this.props.step === 3 &&
<div class="col-md-12">
<div>
<label>Inserir documento com aprovação dos pais:</label>
<span class="text-center">
<Dropzone
multiple={false}
name="docParentsAproval"
onDrop={this.onImageDrop}
initConfig={this.state.docParentsAproval}
text={"Arraste e solte um documento ou clique no botão para selecionar um arquivo"}>
</Dropzone>
</span>
</div>
<div style={{marginTop: 20}}>
<Checkbox style={{width: 290, float: 'left', marginTop: 5}}
label="Você concorda com o termo de uso?" name="termOfUse"
checked={this.state.termOfUse || false}
onCheck={this.handleCheckbox}
/>
<TermOfUse/>
<RaisedButton label="Cadastrar" primary={true} type="submit"/>
</div>
</div>
}
<div class="col-md-12">
<input class="hidden" type="submit"/>
</div>
</form>
);
}
}
|
client/lib/js/react/components/asset_action_panel.js
|
enzovici/PoC-TruthChain
|
import React from 'react';
import { Button, DropdownButton, MenuItem } from 'react-bootstrap/lib';
import { safeInvoke } from 'js-utility-belt/es6';
const AssetActionPanel = React.createClass({
propTypes: {
accountList: React.PropTypes.array.isRequired,
activeAccount: React.PropTypes.object.isRequired,
handleActionClick: React.PropTypes.func.isRequired,
actionMessage: React.PropTypes.string,
actionName: React.PropTypes.string,
handleAccountSelection: React.PropTypes.func,
selectAccounts: React.PropTypes.bool
},
getDefaultProps() {
return {
actionMessage: 'Transfer asset to:',
actionName: 'TRANSFER',
selectAccounts: true
};
},
getInitialState() {
return {
selectedAccount: null
};
},
setSelectedAccount(account) {
this.setState({
selectedAccount: account
});
safeInvoke(this.props.handleAccountSelection, account);
},
render() {
const {
accountList,
actionMessage,
actionName,
activeAccount,
handleActionClick,
selectAccounts
} = this.props;
const {
selectedAccount
} = this.state;
const transferButton = (!selectAccounts || selectedAccount) ?
<Button
bsSize="xsmall"
onClick={() => handleActionClick(selectedAccount)}>
{actionName}
</Button> : null;
const accountDropdown = selectAccounts ?
<DropdownButton
active
bsSize="xsmall"
className="filter-dropdown-button"
id="bg-nested-dropdown"
title={selectedAccount ? selectedAccount.name : 'Select account'}>
{
accountList
.filter((account) => account !== activeAccount)
.map((account) => (
<MenuItem
key={account.vk}
onClick={() => this.setSelectedAccount(account)}>
{account.name}
</MenuItem>
))
}
</DropdownButton> : null;
return (
<div className="asset-container-actions">
<div>{actionMessage}</div>
{accountDropdown}
{transferButton}
</div>
);
}
});
export default AssetActionPanel;
|
docs/app/Examples/elements/Label/Content/index.js
|
aabustamante/Semantic-UI-React
|
import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const LabelContent = () => (
<ExampleSection title='Content'>
<ComponentExample
title='Detail'
description='A label can contain a detail'
examplePath='elements/Label/Content/LabelExampleDetail'
/>
<ComponentExample
title='Icon'
description='A label can include an icon'
examplePath='elements/Label/Content/LabelExampleIcon'
/>
<ComponentExample
description='You can also configure an label icon via props'
examplePath='elements/Label/Content/LabelExampleIconShorthand'
/>
<ComponentExample
title='Image'
description='A label can include an image'
examplePath='elements/Label/Content/LabelExampleImage'
/>
<ComponentExample
description='You can also configure an label image via props'
examplePath='elements/Label/Content/LabelExampleImageShorthand'
/>
<ComponentExample
title='Link'
description='A label can be a link or contain an item that links'
examplePath='elements/Label/Content/LabelExampleLink'
/>
<ComponentExample examplePath='elements/Label/Content/LabelExampleLinkDetail' />
</ExampleSection>
)
export default LabelContent
|
admin/client/App/components/Navigation/Secondary/NavItem.js
|
brianjd/keystone
|
/**
* A navigation item of the secondary navigation
*/
import React from 'react';
import { Link } from 'react-router';
const SecondaryNavItem = React.createClass({
displayName: 'SecondaryNavItem',
propTypes: {
children: React.PropTypes.node.isRequired,
className: React.PropTypes.string,
href: React.PropTypes.string.isRequired,
onClick: React.PropTypes.func,
path: React.PropTypes.string,
title: React.PropTypes.string,
},
render () {
return (
<li className={this.props.className} data-list-path={this.props.path}>
<Link
to={this.props.href}
onClick={this.props.onClick}
title={this.props.title}
tabIndex="-1"
>
{this.props.children}
</Link>
</li>
);
},
});
module.exports = SecondaryNavItem;
|
docs/src/app/components/pages/components/Table/Page.js
|
w01fgang/material-ui
|
import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import tableReadmeText from './README';
import TableExampleSimple from './ExampleSimple';
import tableExampleSimpleCode from '!raw!./ExampleSimple';
import TableExampleComplex from './ExampleComplex';
import tableExampleComplexCode from '!raw!./ExampleComplex';
import tableCode from '!raw!material-ui/Table/Table';
import tableRowCode from '!raw!material-ui/Table/TableRow';
import tableRowColumnCode from '!raw!material-ui/Table/TableRowColumn';
import tableHeaderCode from '!raw!material-ui/Table/TableHeader';
import tableHeaderColumnCode from '!raw!material-ui/Table/TableHeaderColumn';
import tableBodyCode from '!raw!material-ui/Table/TableBody';
import tableFooterCode from '!raw!material-ui/Table/TableFooter';
const descriptions = {
simple: 'A simple table demonstrating the hierarchy of the `Table` component and its sub-components.',
complex: 'A more complex example, allowing the table height to be set, and key boolean properties to be toggled.',
};
const TablePage = () => (
<div>
<Title render={(previousTitle) => `Table - ${previousTitle}`} />
<MarkdownElement text={tableReadmeText} />
<CodeExample
title="Simple example"
description={descriptions.simple}
code={tableExampleSimpleCode}
>
<TableExampleSimple />
</CodeExample>
<CodeExample
title="Complex example"
description={descriptions.complex}
code={tableExampleComplexCode}
>
<TableExampleComplex />
</CodeExample>
<PropTypeDescription code={tableCode} header="### Table Properties" />
<PropTypeDescription code={tableRowCode} header="### TableRow Properties" />
<PropTypeDescription code={tableRowColumnCode} header="### TableRowColumn Properties" />
<PropTypeDescription code={tableHeaderCode} header="### TableHeader Properties" />
<PropTypeDescription code={tableHeaderColumnCode} header="### TableHeaderColumn Properties" />
<PropTypeDescription code={tableBodyCode} header="### TableBody Properties" />
<PropTypeDescription code={tableFooterCode} header="### TableFooter Properties" />
</div>
);
export default TablePage;
|
chapter-10/todo_react_motion/src/filter/views/filters.js
|
mocheng/react-and-redux
|
import React from 'react';
import Link from './link.js';
import {FilterTypes} from '../../constants.js'
import './style.css';
const Filters = () => {
return (
<p className="filters">
<Link filter={FilterTypes.ALL}> {FilterTypes.ALL} </Link>
<Link filter={FilterTypes.COMPLETED}> {FilterTypes.COMPLETED} </Link>
<Link filter={FilterTypes.UNCOMPLETED}> {FilterTypes.UNCOMPLETED} </Link>
</p>
);
};
export default Filters;
|
packages/plugins/users-permissions/admin/src/pages/Roles/ProtectedEditPage/index.js
|
wistityhq/strapi
|
import React from 'react';
import { CheckPagePermissions } from '@strapi/helper-plugin';
import pluginPermissions from '../../../permissions';
import RolesEditPage from '../EditPage';
const ProtectedRolesEditPage = () => (
<CheckPagePermissions permissions={pluginPermissions.updateRole}>
<RolesEditPage />
</CheckPagePermissions>
);
export default ProtectedRolesEditPage;
|
src/components/state-badge.component.js
|
Antoine38660/git-point
|
import React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { colors, fonts, normalize } from 'config';
import { translate } from 'utils';
type Props = {
issue: Object,
isMerged: boolean,
text: string,
type: string,
style: Object,
locale: string,
};
const styles = StyleSheet.create({
badge: {
padding: 12,
paddingTop: 3,
paddingBottom: 3,
borderRadius: 20,
},
mergedIssue: {
backgroundColor: colors.purple,
},
openIssue: {
backgroundColor: colors.green,
},
closedIssue: {
backgroundColor: colors.red,
},
text: {
fontSize: normalize(12),
...fonts.fontPrimarySemiBold,
color: colors.white,
},
});
export const StateBadge = ({
issue,
isMerged,
text,
type,
style,
locale,
}: Props) => {
let issueState = type;
let issueText = text;
if (isMerged) {
issueState = 'merged';
issueText = translate('issue.main.states.merged', locale);
} else if (issue && issue.state === 'open') {
issueState = 'open';
issueText = translate('issue.main.states.open', locale);
} else if (issue && issue.state === 'closed') {
issueState = 'closed';
issueText = translate('issue.main.states.closed', locale);
}
let issueStyle = {};
if (issueState === 'merged') {
issueStyle = styles.mergedIssue;
} else if (issueState === 'open') {
issueStyle = styles.openIssue;
} else if (issueState === 'closed') {
issueStyle = styles.closedIssue;
}
return (
<View style={[styles.badge, style, issueStyle]}>
<Text style={styles.text}>{issueText}</Text>
</View>
);
};
|
src/components/icons/user.js
|
ipfs-shipyard/peerpad
|
import React from 'react'
export default ({ className, style }) => (
<svg width='14' height='14' viewBox='0 0 14 14' xmlns='http://www.w3.org/2000/svg' className={className} style={style}>
<g transform='translate(1.000000, 1.000000)' strokeWidth='1' fill='none'>
<circle cx='6' cy='3' r='3' />
<path d='M0.5,11.5 C0.5,11.5 0.586018855,9.26675755 2.03662109,7.66162109 C3.48722333,6.05648464 5.25696067,5.92724609 6,5.92724609 C6.87776618,5.92724609 9.08627,6.31034213 10.2138672,7.66162109 C11.3414644,9.01290006 11.5,11.5 11.5,11.5' strokeLinecap='round' />
</g>
</svg>
)
|
app/components/Footer.js
|
Byte-Code/lm-digital-store-private-test
|
import React from 'react';
import glamorous from 'glamorous';
import { Link } from 'react-router';
import HelpIcon from 'material-ui/svg-icons/action/help-outline';
import HomeIcon from 'material-ui/svg-icons/action/home';
import ArrowIcon from 'material-ui/svg-icons/navigation/arrow-back';
import TutorialButton from './TutorialButton';
import LinkBack from './LinkBack';
const Wrapper = glamorous.div({
position: 'fixed',
display: 'flex',
alignItems: 'center',
bottom: 0,
width: '100%',
height: '140px',
background: '#333333',
'&>*': {
width: '33.33%',
borderRight: '1px solid #67cb33'
},
'&>*:last-child': {
borderRight: 'none'
}
});
const Button = glamorous.div({
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
height: '100px',
width: '100%',
background: 'transparent',
color: '#fff',
cursor: 'pointer',
position: 'relative'
});
const iconStyle = { height: 50, width: 50 };
const Footer = () => (
<Wrapper>
<LinkBack>
<Button>
<ArrowIcon color="#fff" style={iconStyle} />
<p>Indietro</p>
</Button>
</LinkBack>
<Link to="/world">
<Button>
<HomeIcon color="#fff" style={iconStyle} />
<p>Homepage</p>
</Button>
</Link>
<TutorialButton>
<Button>
<HelpIcon color="#fff" style={iconStyle} />
<p>Scopri il Digital Store</p>
</Button>
</TutorialButton>
</Wrapper>
);
export default Footer;
|
lms/static/js/student_account/components/spec/PasswordResetConfirmation_spec.js
|
cpennington/edx-platform
|
/* globals setFixtures */
import ReactDOM from 'react-dom';
import React from 'react';
import sinon from 'sinon'; // eslint-disable-line import/no-extraneous-dependencies
import { PasswordResetConfirmation } from '../PasswordResetConfirmation';
describe('PasswordResetConfirmation', () => {
beforeEach(() => {
setFixtures('<div id="wrapper"></div>');
sinon.stub(window, 'fetch');
});
afterEach(() => {
window.fetch.restore();
});
function init(submitError) {
ReactDOM.render(
React.createElement(PasswordResetConfirmation, {
csrfToken: 'csrfToken',
errorMessage: submitError,
}, null),
document.getElementById('wrapper'),
);
}
function triggerValidation() {
$('#new_password1').focus();
$('#new_password1').val('a');
$('#new_password2').focus();
expect(window.fetch.calledWithMatch(
'/api/user/v1/validation/registration',
{ body: JSON.stringify({ password: 'a' }) },
));
}
function prepareValidation(validationError, done) {
window.fetch.reset();
window.fetch.callsFake(() => {
done();
return Promise.resolve({
json: () => ({ validation_decisions: { password: validationError } }),
});
});
}
it('shows submit error', () => {
init('Submit error.');
expect($('.alert-dialog')).toExist();
expect($('.alert-dialog')).not.toBeHidden();
expect($('.alert-dialog')).toHaveText('Submit error.');
});
describe('validation', () => {
beforeEach((done) => {
init('');
prepareValidation('Validation error.', done);
triggerValidation();
});
it('shows validation error', () => {
expect($('#error-new_password1')).toContainText('Validation error.');
});
});
});
|
app/server/server.js
|
nittmurugan/finddriver
|
import Express from 'express';
import compression from 'compression';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import path from 'path';
import IntlWrapper from '../client/modules/Intl/IntlWrapper';
// Webpack Requirements
import webpack from 'webpack';
import config from '../webpack.config.dev';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
// Initialize the Express App
const app = new Express();
// Run Webpack dev server in development mode
if (process.env.NODE_ENV === 'development') {
const compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
}
// React And Redux Setup
import { configureStore } from '../client/store';
import { Provider } from 'react-redux';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import Helmet from 'react-helmet';
// Import required modules
import routes from '../client/routes';
import { fetchComponentData } from './util/fetchData';
import posts from './routes/post.routes';
import dummyData from './dummyData';
import serverConfig from './config';
// Set native promises as mongoose promise
mongoose.Promise = global.Promise;
// MongoDB Connection
mongoose.connect(serverConfig.mongoURL, (error) => {
if (error) {
console.error('Please make sure Mongodb is installed and running!'); // eslint-disable-line no-console
throw error;
}
// feed some dummy data in DB.
dummyData();
});
// Apply body Parser and server public assets and routes
app.use(compression());
app.use(bodyParser.json({ limit: '20mb' }));
app.use(bodyParser.urlencoded({ limit: '20mb', extended: false }));
app.use(Express.static(path.resolve(__dirname, '../dist')));
app.use('/api', posts);
// Render Initial HTML
const renderFullPage = (html, initialState) => {
const head = Helmet.rewind();
// Import Manifests
const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets);
const chunkManifest = process.env.webpackChunkAssets && JSON.parse(process.env.webpackChunkAssets);
return `
<!doctype html>
<html>
<head>
${head.base.toString()}
${head.title.toString()}
${head.meta.toString()}
${head.link.toString()}
${head.script.toString()}
${process.env.NODE_ENV === 'production' ? `<link rel='stylesheet' href='${assetsManifest['/app.css']}' />` : ''}
<link href='https://fonts.googleapis.com/css?family=Lato:400,300,700' rel='stylesheet' type='text/css'/>
<link rel="shortcut icon" href="http://res.cloudinary.com/hashnode/image/upload/v1455629445/static_imgs/mern/mern-favicon-circle-fill.png" type="image/png" />
</head>
<body>
<div id="root">${html}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
${process.env.NODE_ENV === 'production' ?
`//<![CDATA[
window.webpackManifest = ${JSON.stringify(chunkManifest)};
//]]>` : ''}
</script>
<script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/vendor.js'] : '/vendor.js'}'></script>
<script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/app.js'] : '/app.js'}'></script>
</body>
</html>
`;
};
const renderError = err => {
const softTab = '    ';
const errTrace = process.env.NODE_ENV !== 'production' ?
`:<br><br><pre style="color:red">${softTab}${err.stack.replace(/\n/g, `<br>${softTab}`)}</pre>` : '';
return renderFullPage(`Server Error${errTrace}`, {});
};
// Server Side Rendering based on routes matched by React-router.
app.use((req, res, next) => {
match({ routes, location: req.url }, (err, redirectLocation, renderProps) => {
if (err) {
return res.status(500).end(renderError(err));
}
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
}
if (!renderProps) {
return next();
}
const store = configureStore();
return fetchComponentData(store, renderProps.components, renderProps.params)
.then(() => {
const initialView = renderToString(
<Provider store={store}>
<IntlWrapper>
<RouterContext {...renderProps} />
</IntlWrapper>
</Provider>
);
const finalState = store.getState();
res
.set('Content-Type', 'text/html')
.status(200)
.end(renderFullPage(initialView, finalState));
})
.catch((error) => next(error));
});
});
// start app
app.listen(serverConfig.port, (error) => {
if (!error) {
console.log(`MERN is running on port: ${serverConfig.port}! Build something amazing!`); // eslint-disable-line
}
});
export default app;
|
frontend/src/pages/Home.js
|
pequalsnp/eve-isk-tracker
|
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Grid, Row, Col, Jumbotron } from 'react-bootstrap';
import App from '../components/App'
import Profile from '../components/Profile'
class Home extends Component {
render() {
return (
<App>
<Jumbotron>
<Profile />
</Jumbotron>
</App>
);
}
}
ReactDOM.render(<Home />, document.getElementById('root'));
|
dispatch/static/manager/src/js/components/PollEditor/PollForm.js
|
ubyssey/dispatch
|
import React from 'react'
import { Button, Intent } from '@blueprintjs/core'
import R from 'ramda'
import { TextInput, SelectInput } from '../inputs'
import * as Form from '../Form'
import Poll from './Poll'
require('../../../styles/components/poll_form.scss')
const DEFAULT_ANSWERS = [
{
'name': '',
'vote_count': 0
},
{
'name': '',
'vote_count': 0
}
]
export default class PollForm extends React.Component {
addAnswer() {
this.props.update('answers', this.getAnswers().concat(DEFAULT_ANSWERS[0]))
}
removeAnswer(index) {
this.props.update('answers', R.remove(index, 1, this.getAnswers()))
}
handleUpdateAnswer(e, index) {
this.props.update('answers',
R.adjust(R.assoc('name', e.target.value), index, this.getAnswers())
)
}
getAnswers() {
return this.props.listItem.answers || DEFAULT_ANSWERS
}
renderAnswers() {
const answers = this.getAnswers().map(
(answer, index) => {
return (
<Form.Input
key={index + 1}
label={`Answer ${index + 1} Votes: ${answer.vote_count}`}
padded={false}>
<TextInput
placeholder='Answer'
value={answer.name || ''}
fill={true}
onChange={e => this.handleUpdateAnswer(e, index)} />
<span
className={['poll-form', 'bp3-icon-standard', 'bp3-icon-trash'].join(' ')}
onClick={() => this.removeAnswer(index)}>
<span className={'bp3-icon-standard-text'}>Remove answer</span>
</span>
</Form.Input>
)
}
)
return (
<div>
{answers}
</div>
)
}
renderAddAnswerButton() {
return (
<Button
intent={Intent.SUCCESS}
onClick={() => this.addAnswer()}>
Add answer
</Button>
)
}
renderPollOpenSelect() {
const OPTIONS = [
[true, 'Poll Open'],
[false, 'Poll Closed']
]
return (
<Form.Input
label='Poll Options'
padded={false}>
<div className='c-poll-form__results-select'>
<SelectInput
options={OPTIONS}
value={this.props.listItem.is_open}
onChange={e => this.props.update('is_open', e.target.value)} />
</div>
</Form.Input>
)
}
renderOptions() {
const OPTIONS = [
[true, 'Show results'],
[false, 'Hide results']
]
return (
<div>
<Form.Input
label='Results Options'
padded={false}>
<div className='c-poll-form__results-select'>
<SelectInput
options={OPTIONS}
value={this.props.listItem.show_results}
onChange={e => this.props.update('show_results', e.target.value)} />
</div>
</Form.Input>
{(this.props.listItem.id === 'new') ? null : this.renderPollOpenSelect()}
</div>
)
}
render() {
return (
<div className={'c-poll-form-container'}>
<div className={'c-equal-width'}>
<Form.Container>
<Form.Input
label='Name'
padded={false}
error={this.props.errors.name}>
<TextInput
placeholder='Name'
value={this.props.listItem.name || ''}
fill={true}
onChange={e => this.props.update('name', e.target.value)} />
</Form.Input>
<Form.Input
label='Question'
padded={false}
error={this.props.errors.question}>
<TextInput
placeholder='Question'
value={this.props.listItem.question || ''}
fill={true}
onChange={e => this.props.update('question', e.target.value)} />
</Form.Input>
{this.renderAnswers()}
{this.renderAddAnswerButton()}
{this.renderOptions()}
</Form.Container>
</div>
<div className={'c-equal-width'}>
<Poll
many={false}
id={this.props.listItem.id}
answers={this.props.listItem.answers}
question={this.props.listItem.question} />
</div>
</div>
)
}
}
|
AppVilRecipe/VilRecipes/index.android.js
|
damdamgo/VilRecipe
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import VilRecipes from './App';
AppRegistry.registerComponent('VilRecipes', () => VilRecipes);
|
packages/react-scripts/fixtures/kitchensink/src/features/webpack/LinkedModules.js
|
shrynx/react-super-scripts
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React from 'react';
import './assets/style.css';
import { test, version } from 'test-integrity';
export default () => {
const v = version();
if (!test() || v !== '2.0.0') {
throw new Error('Functionality test did not pass.');
}
return (
<p id="feature-linked-modules">
{v}
</p>
);
};
|
imports/Client/Components/task/Task.js
|
darodriguez15/booksWebDev
|
import React, { Component } from 'react';
import PropTypes from "prop-types";
// Task component - represents a single todo item
export default class Task extends Component {
render() {
return (
<li>{this.props.task.text}</li>
);
}
}
Task.propTypes = {
// This component gets the task to display through a React prop.
// We can use propTypes to indicate it is required
task: PropTypes.object.isRequired,
};
|
src/icons/GlyphMap.js
|
ipfs/webui
|
import React from 'react'
const GlyphMap = props => (
<svg viewBox='0 0 100 100' {...props}>
<path d='M80.45 31.79L60.58 19.4a1 1 0 0 0-.53-.15h-.23a1 1 0 0 0-.59.19c-.47.31-7.45 4.72-13.07 8.26l-6 3.79-.09.05a1.43 1.43 0 0 1-.31-.16c-6-3.74-18.45-11.88-18.95-12.24a1 1 0 0 0-1-.18 1 1 0 0 0-.65.73c-.05.2-.11.49-.11 48a1 1 0 0 0 .51.88c.49.28 12.82 7.88 18.87 11.7a2.67 2.67 0 0 0 3.21 0q4.92-3.12 9.86-6.21L59.63 69c.33-.21.35-.21.69 0q7.5 4.74 15 9.43l4 2.52a1 1 0 0 0 .53.15 1 1 0 0 0 .49-.12 1 1 0 0 0 .51-.88V32.64a1 1 0 0 0-.4-.85zM58.4 24.33v41.09L42 75.67V34.58z' />
</svg>
)
export default GlyphMap
|
fields/types/number/NumberFilter.js
|
andreufirefly/keystone
|
import React from 'react';
import ReactDOM from 'react-dom';
import { FormField, FormInput, FormRow, FormSelect } from 'elemental';
const MODE_OPTIONS = [
{ label: 'Exactly', value: 'equals' },
{ label: 'Greater Than', value: 'gt' },
{ label: 'Less Than', value: 'lt' },
{ label: 'Between', value: 'between' },
];
var NumberFilter = React.createClass({
getInitialState () {
return {
modeValue: MODE_OPTIONS[0].value, // 'matches'
modeLabel: MODE_OPTIONS[0].label, // 'Matches'
value: '',
minValue: '',
maxValue: '',
};
},
componentDidMount () {
// focus the text input
ReactDOM.findDOMNode(this.refs.input).focus();
},
handleChangeBuilder (type) {
const self = this;
return function handleChange (e) {
const { value } = e.target;
const { modeValue } = self.state;
const { onChange } = self.props;
self.setState({
[type]: value,
});
switch (type) {
case 'minValue':
onChange({
mode: modeValue,
value: {
min: value,
max: self.state.maxValue,
},
});
break;
case 'maxValue':
onChange({
mode: modeValue,
value: {
max: value,
min: self.state.minValue,
},
});
break;
case 'value':
onChange({
mode: modeValue,
value,
});
}
};
},
toggleMode (mode) {
this.setState({
modeValue: mode,
modeLabel: MODE_OPTIONS.find(option => option.value === mode).label,
});
// focus the text input after a mode selection is made
ReactDOM.findDOMNode(this.refs.input).focus();
},
renderControls () {
let controls;
const { field } = this.props;
const { modeLabel, modeValue } = this.state;
const placeholder = field.label + ' is ' + modeLabel.toLowerCase() + '...';
if (modeValue === 'between') {
controls = (
<FormRow>
<FormField width="one-half" style={{ marginBottom: 0 }}>
<FormInput type="number" ref="input" placeholder="Min." onChange={this.handleChangeBuilder('minValue')} />
</FormField>
<FormField width="one-half" style={{ marginBottom: 0 }}>
<FormInput type="number" placeholder="Max." onChange={this.handleChangeBuilder('maxValue')} />
</FormField>
</FormRow>
);
} else {
controls = (
<FormField>
<FormInput type="number" ref="input" placeholder={placeholder} onChange={this.handleChangeBuilder('value')} />
</FormField>
);
}
return controls;
},
render () {
const { modeValue } = this.state;
return (
<div>
<FormSelect options={MODE_OPTIONS} onChange={this.toggleMode} value={modeValue} />
{this.renderControls()}
</div>
);
},
});
module.exports = NumberFilter;
|
src/navigation/auth.js
|
shwethadn/StarterApp
|
/**
* Auth Scenes
*
* React Native Starter App
* https://github.com/mcnamee/react-native-starter-app
*/
import React from 'react';
import { Scene, ActionConst } from 'react-native-router-flux';
// Consts and Libs
import { AppConfig } from '@constants/';
// Scenes
import Authenticate from '@containers/auth/AuthenticateView';
import AuthWebView from '@containers/auth/WebView';
import AuthLogin from '@containers/auth/Login/LoginContainer';
/* Routes ==================================================================== */
const scenes = (
<Scene key={'authenticate'}>
<Scene
hideNavBar
key={'authLanding'}
component={Authenticate}
type={ActionConst.RESET}
analyticsDesc={'Authenticate: Authentication'}
/>
<Scene
{...AppConfig.navbarProps}
key={'login'}
title={'Login'}
clone
component={AuthLogin}
analyticsDesc={'AuthLogin: Login'}
/>
<Scene
{...AppConfig.navbarProps}
key={'signUp'}
title={'Sign Up'}
clone
component={AuthWebView}
url={AppConfig.urls.signUp}
analyticsDesc={'AuthWebView: Sign Up'}
/>
<Scene
{...AppConfig.navbarProps}
key={'passwordReset'}
title={'Password Reset'}
clone
component={AuthWebView}
url={AppConfig.urls.resetPassword}
analyticsDesc={'AuthWebView: Password Reset'}
/>
</Scene>
);
export default scenes;
|
docs/src/app/components/pages/components/RefreshIndicator/Page.js
|
barakmitz/material-ui
|
import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import refreshIndicatorReadmeText from './README';
import RefreshIndicatorExampleReady from './ExampleReady';
import refreshIndicatorExampleReadyCode from '!raw!./ExampleReady';
import RefreshIndicatorExampleLoading from './ExampleLoading';
import refreshIndicatorExampleLoadingCode from '!raw!./ExampleLoading';
import refreshIndicatorCode from '!raw!material-ui/RefreshIndicator/RefreshIndicator';
const descriptions = {
ready: 'The `ready` status can be used in response to a pull-to-refresh action, with the `percentage` tracking ' +
'the depth of the "pull". The `size` property determines the icon size in pixels, and the `color` property its ' +
'color, except at `percentage` 100, when the colour switches to the secondary color.',
loading: 'The `loading` status displays an indeterminate indicator, intended to to be used while content is ' +
'loading. The `loadingColor` prop can be used to set the indicator color, which defaults to the secondary color.',
};
const RefreshIndicatorPage = () => (
<div>
<Title render={(previousTitle) => `Refresh Indicator - ${previousTitle}`} />
<MarkdownElement text={refreshIndicatorReadmeText} />
<CodeExample
title="Ready"
description={descriptions.ready}
code={refreshIndicatorExampleReadyCode}
>
<RefreshIndicatorExampleReady />
</CodeExample>
<CodeExample
title="Loading"
description={descriptions.loading}
code={refreshIndicatorExampleLoadingCode}
>
<RefreshIndicatorExampleLoading />
</CodeExample>
<PropTypeDescription code={refreshIndicatorCode} />
</div>
);
export default RefreshIndicatorPage;
|
packages/leaflet/src/basemaps/Tile.js
|
wq/wq.app
|
import React from 'react';
import { TileLayer } from 'react-leaflet';
export default function Tile(props) {
return <TileLayer {...props} />;
}
|
src/app/components/Header.js
|
DavidBanksNZ/react-redux-minesweeper
|
import React from 'react';
const Header = props => (
<div className="app-header">
<h1>React + Redux Minesweeper</h1>
<i className="zmdi zmdi-help app-header-help-icon" onClick={props.onToggleHelp}></i>
</div>
);
export default Header;
|
test/NavbarSpec.js
|
azmenak/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Navbar from '../src/Navbar';
import Nav from '../src/Nav';
describe('Nav', function () {
it('Should create nav element', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Navbar />
);
let nav = React.findDOMNode(instance);
assert.equal(nav.nodeName, 'NAV');
assert.ok(nav.className.match(/\bnavbar\b/));
assert.ok(nav.getAttribute('role'), 'navigation');
});
it('Should add fixedTop variation class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Navbar fixedTop />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-fixed-top'));
});
it('Should add fixedBottom variation class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Navbar fixedBottom />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-fixed-bottom'));
});
it('Should add staticTop variation class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Navbar staticTop />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-static-top'));
});
it('Should add inverse variation class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Navbar inverse />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-inverse'));
});
it('Should add fluid variation class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Navbar fluid />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'container-fluid'));
});
it('Should override role attribute', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Navbar role="banner"/>
);
assert.ok(React.findDOMNode(instance).getAttribute('role'), 'banner');
});
it('Should override node class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Navbar componentClass={'header'}/>
);
assert.equal(React.findDOMNode(instance).nodeName, 'HEADER');
});
it('Should add header with brand', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Navbar brand="Brand" />
);
let header = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-header');
assert.ok(header);
let brand = ReactTestUtils.findRenderedDOMComponentWithClass(header, 'navbar-brand');
assert.ok(brand);
assert.equal(React.findDOMNode(brand).innerText, 'Brand');
});
it('Should add header with brand component', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Navbar brand={<a>Brand</a>} />
);
let header = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-header');
assert.ok(header);
let brand = ReactTestUtils.findRenderedDOMComponentWithClass(header, 'navbar-brand');
assert.ok(brand);
assert.equal(React.findDOMNode(brand).nodeName, 'A');
assert.equal(React.findDOMNode(brand).innerText, 'Brand');
});
it('Should pass navbar prop to navs', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Navbar brand="Brand">
<Nav />
</Navbar>
);
let nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav);
assert.ok(nav.props.navbar);
});
it('Should pass nav prop to ul', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Nav />
);
let navNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'nav'));
assert.ok(navNode);
assert.equal(navNode.nodeName, 'UL');
assert.equal(navNode.parentNode.nodeName, 'NAV');
instance.setProps({navbar: true});
navNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'nav'));
assert.ok(navNode);
assert.equal(navNode.nodeName, 'UL');
assert.equal(navNode.parentNode.nodeName, 'DIV');
});
it('Should add header when toggleNavKey is 0', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Navbar toggleNavKey={0}>
<Nav eventKey={0} />
</Navbar>
);
let header = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-header');
assert.ok(header);
});
it('Should add header when toggleNavKey is 1', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Navbar toggleNavKey={1}>
<Nav eventKey={1} />
</Navbar>
);
let header = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-header');
assert.ok(header);
});
it('Should add header when toggleNavKey is string', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Navbar toggleNavKey={'string'}>
<Nav eventKey={'string'} />
</Navbar>
);
let header = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-header');
assert.ok(header);
});
});
|
client/containers/home/index.js
|
ShannChiang/USzhejiang
|
// import React from 'react';
// import {useDeps} from 'react-simple-di';
// import {composeAll, withTracker, withLifecycle} from 'react-komposer-plus';
// import Home from '../../components/home';
// function composer({context}, onData) {
// const user = context().Meteor.user();
// if (user && Array.isArray(user.emails) && user.emails.length > 0) {
// const isWechatVerified = user.profile.headimgurl && user.emails[0].verified;
// const isWechat = user.profile.headimgurl || user.city;
// const nickname = user.profile.nickname;
// const avatar = isWechat ? user.profile.headimgurl : '';
// onData(null, {
// loggedIn: !!user,
// notWechat: !isWechat,
// isWechatVerified,
// nickname,
// avatar
// });
// } else {
// onData(null, {loggedIn: user});
// }
// }
// function configsComposer({context}, onData) {
// const { Meteor } = context();
// if (Meteor.subscribe('core.configs.user').ready()) {
// const coreConfigs = context().Collections.Packages.findOne({ name: 'core' }).configs;
// onData(null, { title: coreConfigs.appName });
// } else {
// onData(null, { title: '' });
// }
// }
// const lifecycle = {
// componentWillReceiveProps(nextProps) {
// if (nextProps.title) {
// document.title = nextProps.title;
// }
// }
// };
// export default composeAll(
// withLifecycle(lifecycle),
// withTracker(composer),
// withTracker(configsComposer),
// useDeps()
// )(Home);
|
src/sentry/static/sentry/app/icons/icon-search.js
|
gencer/sentry
|
import React from 'react';
import Icon from 'react-icon-base';
function IconSearch(props) {
return (
<Icon viewBox="0 0 14 14" {...props}>
<g stroke="none" fill="currentColor">
<path d="M8.3099521,6.89573854 L11.7071068,10.2928932 C12.0976311,10.6834175 12.0976311,11.3165825 11.7071068,11.7071068 C11.3165825,12.0976311 10.6834175,12.0976311 10.2928932,11.7071068 L6.89573854,8.3099521 C6.20201398,8.74709153 5.38054196,9 4.5,9 C2.01471863,9 0,6.98528137 0,4.5 C0,2.01471863 2.01471863,0 4.5,0 C6.98528137,0 9,2.01471863 9,4.5 C9,5.38054196 8.74709153,6.20201398 8.3099521,6.89573854 L8.3099521,6.89573854 Z M4.5,7 C5.88071187,7 7,5.88071187 7,4.5 C7,3.11928813 5.88071187,2 4.5,2 C3.11928813,2 2,3.11928813 2,4.5 C2,5.88071187 3.11928813,7 4.5,7 Z" />
</g>
</Icon>
);
}
export default IconSearch;
|
client/src/components/view/container/Networks.js
|
docker-manager/docker-manager-tool
|
import React from 'react'
const Networks = ({networks}) => (
<ul className="list-group">
{Object.keys(networks).map(network =>
<li key={network} className="list-group-item">
<table className="table table-striped table-condensed table-responsive text-left">
<tbody>
<tr>
<th>Name</th>
<td><code>{network}</code></td>
</tr>
<tr>
<th>Ip</th>
<td>{networks[network].IPAddress ? networks[network].IPAddress : '-'}</td>
</tr>
<tr>
<th>Gateway</th>
<td>{networks[network].Gateway ? networks[network].Gateway : '-'}</td>
</tr>
<tr>
<th>MacAddress</th>
<td>{networks[network].MacAddress ? networks[network].MacAddress : '-'}</td>
</tr>
</tbody>
</table>
</li>
)}
</ul>
)
export default Networks
|
src/components/__tests__/MetaEmail_test.js
|
varenya/email-client
|
import React from 'react';
import {shallow} from 'enzyme';
import { MetaEmail , Avatar , UserDetails} from '../MetaEmail';
describe('MetaEmail',() => {
let metaEmail = null;
beforeEach(() => {
const sampleProps = {
selected : false,
unread : false,
name : 'Test',
desc : 'Hello Test',
subject : 'TestSubject',
avatar : './src/img/test.jpg'
};
metaEmail = shallow(<MetaEmail {...sampleProps}/>);
})
it("should have proper name,desc,subject",()=>{
const userDetails = shallow(<UserDetails name="Test" subject="TestSubject" desc="Hello Test" />);
expect(userDetails.text()).toContain('Test');
expect(userDetails.text()).toContain('TestSubject');
expect(userDetails.text()).toContain('Hello Test');
});
it("should have a Avatar component",() => {
expect(metaEmail.find(Avatar).length).toEqual(1);
});
it("should have atleast one email-item div",() => {
expect(metaEmail.find('.email-item').length).toEqual(1);
});
it("should show correct classname as per the conditionals",()=>{
const sample = {
selected : true,
unread : false,
name : 'Test',
desc : 'Hello Test',
subject : 'TestSubject',
avatar : './src/img/test.jpg'
};
const Email1 = shallow(<MetaEmail {...sample} />);
sample.unread = true;
const Email2 = shallow(<MetaEmail {...sample} />);
sample.selected = false;
sample.unread = false;
const Email3 = shallow(<MetaEmail {...sample} />);
expect(Email1.props().className).toContain('email-item-selected');
expect(Email2.props().className).toContain('email-item-unread');
expect(Email2.props().className).not.toContain('email-item-selected');
expect(Email3.props().className).not.toContain('email-item-unread email-item-selected');
});
});
describe("Avatar",() => {
let avatar = null;
beforeEach(() => {
avatar = shallow(<Avatar avatar="./img/src/test.jpg"/>)
});
it("should have a email-avatar element",()=>{
expect(avatar.find('.email-avatar').exists()).toBeTruthy();
});
it("should have a img element",()=>{
expect(avatar.find('img').exists()).toBeTruthy();
})
it("should have correct width and height",() => {
expect(avatar.find('.email-avatar').props().width).toEqual("64");
expect(avatar.find('.email-avatar').props().height).toEqual("64");
});
})
|
step4-router/node_modules/react-router/modules/Link.js
|
jintoppy/react-training
|
import React from 'react'
import warning from './routerWarning'
const { bool, object, string, func, oneOfType } = React.PropTypes
function isLeftClickEvent(event) {
return event.button === 0
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey)
}
function isEmptyObject(object) {
for (let p in object)
if (object.hasOwnProperty(p))
return false
return true
}
function createLocationDescriptor(to, { query, hash, state }) {
if (query || hash || state) {
return { pathname: to, query, hash, state }
}
return to
}
/**
* A <Link> is used to create an <a> element that links to a route.
* When that route is active, the link gets the value of its
* activeClassName prop.
*
* For example, assuming you have the following route:
*
* <Route path="/posts/:postID" component={Post} />
*
* You could use the following component to link to that route:
*
* <Link to={`/posts/${post.id}`} />
*
* Links may pass along location state and/or query string parameters
* in the state/query props, respectively.
*
* <Link ... query={{ show: true }} state={{ the: 'state' }} />
*/
const Link = React.createClass({
contextTypes: {
router: object
},
propTypes: {
to: oneOfType([ string, object ]).isRequired,
query: object,
hash: string,
state: object,
activeStyle: object,
activeClassName: string,
onlyActiveOnIndex: bool.isRequired,
onClick: func
},
getDefaultProps() {
return {
onlyActiveOnIndex: false,
className: '',
style: {}
}
},
handleClick(event) {
let allowTransition = true
if (this.props.onClick)
this.props.onClick(event)
if (isModifiedEvent(event) || !isLeftClickEvent(event))
return
if (event.defaultPrevented === true)
allowTransition = false
// If target prop is set (e.g. to "_blank") let browser handle link.
/* istanbul ignore if: untestable with Karma */
if (this.props.target) {
if (!allowTransition)
event.preventDefault()
return
}
event.preventDefault()
if (allowTransition) {
const { to, query, hash, state } = this.props
const location = createLocationDescriptor(to, { query, hash, state })
this.context.router.push(location)
}
},
render() {
const { to, query, hash, state, activeClassName, activeStyle, onlyActiveOnIndex, ...props } = this.props
warning(
!(query || hash || state),
'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated'
)
// Ignore if rendered outside the context of router, simplifies unit testing.
const { router } = this.context
if (router) {
const location = createLocationDescriptor(to, { query, hash, state })
props.href = router.createHref(location)
if (activeClassName || (activeStyle != null && !isEmptyObject(activeStyle))) {
if (router.isActive(location, onlyActiveOnIndex)) {
if (activeClassName)
props.className += props.className === '' ? activeClassName : ` ${activeClassName}`
if (activeStyle)
props.style = { ...props.style, ...activeStyle }
}
}
}
return <a {...props} onClick={this.handleClick} />
}
})
export default Link
|
lib/grid/index.js
|
andyfen/react-native-UIKit
|
import React from 'react';
import {
StyleSheet,
View,
Image,
TouchableOpacity,
ListView,
Dimensions,
} from 'react-native';
import { floor, divide, take, chunk } from 'lodash';
const { width } = Dimensions.get('window');
const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
},
});
const Grid = ({ images, headerContent, footerContent, onPress, itemsPerRow, spacing, style, containerStyle }) => {
const rounded = floor(divide(images.length, itemsPerRow));
const outputRounded = take(images, rounded * itemsPerRow);
const data = chunk(outputRounded, itemsPerRow); // [[],[],[]]
// Fix row cell padding
function paddingFix(i, row) {
if (i === 0) {
return {
// LEFT
marginRight: spacing,
};
} else if (i === row) {
// RIGHT
return {
marginLeft: spacing,
};
}
return {
// CENTER
marginHorizontal: spacing,
};
}
return (
<ListView
enableEmptySections={true}
renderHeader={() => <View style={[ { width }, headerStyle ]}>{headerContent}</View>}
renderFooter={() => <View style={[ { width }, footerStyle ]}>{footerContent}</View>}
dataSource={ds.cloneWithRows(data)}
pageSize={10}
renderRow={(rowData, i) =>
<View key={i} style={styles.container}>
{rowData.map((item, ii) =>
<TouchableOpacity
key={ii}
onPress={() => onPress(item.id)}
style={[ { flex: 1 }, containerStyle ]}
>
<Image
style={[ {
flex: 1,
height: width / (itemsPerRow),
marginVertical: 2,
}, paddingFix(ii, itemsPerRow - 1), style]}
source={{ uri: item.src }}
/>
</TouchableOpacity>
)}
</View>
}
/>
);
};
Grid.defaultProps = {
images: [],
spacing: 2,
rows: 3,
style: {},
containerStyle: {},
headerStyle: {},
footerStyle: {},
};
Grid.propTypes = {
images: React.PropTypes.array.isRequired,
spacing: React.PropTypes.number,
rows: React.PropTypes.number,
headerContent: React.PropTypes.element,
footerContent: React.PropTypes.element,
onPress: React.PropTypes.func,
itemsPerRow: React.PropTypes.number,
};
export default Grid;
|
src/PhotoMessage/PhotoMessage.js
|
Detaysoft/react-chat-elements
|
import React from 'react';
import './PhotoMessage.css';
import FaCloudDownload from 'react-icons/lib/fa/cloud-download';
import FaError from 'react-icons/lib/fa/exclamation-triangle';
const ProgressBar = require('react-progress-bar.js');
const Circle = ProgressBar.Circle;
function PhotoMessage(props) {
var progressOptions = {
strokeWidth: 2.3,
color: '#efe',
trailColor: '#aaa',
trailWidth: 1,
step: (state, circle) => {
circle.path.setAttribute('trail', state.color);
circle.path.setAttribute('trailwidth-width', state.width);
var value = Math.round(circle.value() * 100);
if (value === 0)
circle.setText('');
else
circle.setText(value);
}
};
const error = props.data.status && props.data.status.error === true;
return (
<div className='rce-mbox-photo'>
<div
className='rce-mbox-photo--img'
style={props.data.width && props.data.height && {
width: props.data.width,
height: props.data.height,
}}>
<img
src={props.data.uri}
alt={props.data.alt}
onClick={props.onOpen}
onLoad={props.onLoad}
onError={props.onPhotoError}/>
{
error &&
<div className='rce-mbox-photo--img__block'>
<span
className='rce-mbox-photo--img__block-item rce-mbox-photo--error'>
<FaError/>
</span>
</div>
}
{
!error &&
props.data.status &&
!props.data.status.download &&
<div className='rce-mbox-photo--img__block'>
{
!props.data.status.click &&
<button
onClick={props.onDownload}
className='rce-mbox-photo--img__block-item rce-mbox-photo--download'>
<FaCloudDownload/>
</button>
}
{
typeof props.data.status.loading === 'number' &&
props.data.status.loading !== 0 &&
<Circle
progress={props.data.status.loading}
options={progressOptions}
initialAnimate={true}
containerClassName={'rce-mbox-photo--img__block-item'} />
}
</div>
}
</div>
{
props.text &&
<div className='rce-mbox-text'>
{props.text}
</div>
}
</div>
);
}
PhotoMessage.defaultProps = {
text: '',
data: {},
onDownload: null,
onOpen: null,
onLoad: null,
onPhotoError: null,
};
export default PhotoMessage;
|
src/Parser/Hunter/Marksmanship/Modules/Features/VulnerableUptime.js
|
hasseboulen/WoWAnalyzer
|
import React from 'react';
import Analyzer from 'Parser/Core/Analyzer';
import Enemies from 'Parser/Core/Modules/Enemies';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import { formatPercentage } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import Wrapper from 'common/Wrapper';
class VulnerableUpTime extends Analyzer {
static dependencies = {
enemies: Enemies,
};
get uptimeThreshold() {
return {
actual: this.uptimePercentage,
isLessThan: {
minor: 0.8,
average: 0.75,
major: 0.7,
},
style: 'percentage',
};
}
get uptimePercentage() {
return this.enemies.getBuffUptime(SPELLS.VULNERABLE.id) / this.owner.fightDuration;
}
suggestions(when) {
when(this.uptimeThreshold).addSuggestion((suggest, actual, recommended) => {
return suggest(<Wrapper>Your <SpellLink id={SPELLS.VULNERABLE.id} icon /> uptime can be improved. Make sure you use Windburst or Marked Shot to open the Vulnerable Window to maximize damage with your Aimed Shots</Wrapper>)
.icon(SPELLS.VULNERABLE.icon)
.actual(`${formatPercentage(actual)}% Vulnerable uptime`)
.recommended(`>${formatPercentage(recommended)}% is recommended`);
});
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.VULNERABLE.id} />}
value={`${formatPercentage(this.uptimePercentage)}%`}
label="Vulnerable uptime"
/>
);
}
statisticOrder = STATISTIC_ORDER.CORE(6);
}
export default VulnerableUpTime;
|
src/redux/utils/createDevToolsWindow.js
|
felixSchl/try-neodoc
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import DevTools from '../../containers/DevToolsWindow';
export default function createDevToolsWindow (store) {
const win = window.open(
null,
'redux-devtools', // give it a name so it reuses the same window
`width=400,height=${window.outerHeight},menubar=no,location=no,resizable=yes,scrollbars=no,status=no`
);
// reload in case it's reusing the same window with the old content
win.location.reload();
// wait a little bit for it to reload, then render
setTimeout(() => {
// Wait for the reload to prevent:
// "Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element."
win.document.write('<div id="react-devtools-root"></div>');
win.document.body.style.margin = '0';
ReactDOM.render(
<Provider store={store}>
<DevTools />
</Provider>
, win.document.getElementById('react-devtools-root')
);
}, 10);
}
|
fields/types/location/LocationFilter.js
|
cermati/keystone
|
import React from 'react';
import { findDOMNode } from 'react-dom';
import {
FormField,
FormInput,
Grid,
SegmentedControl,
} from '../../../admin/client/App/elemental';
const INVERTED_OPTIONS = [
{ label: 'Matches', value: false },
{ label: 'Does NOT Match', value: true },
];
function getDefaultValue () {
return {
inverted: INVERTED_OPTIONS[0].value,
street: undefined,
city: undefined,
state: undefined,
code: undefined,
country: undefined,
};
}
var TextFilter = React.createClass({
propTypes: {
filter: React.PropTypes.shape({
inverted: React.PropTypes.boolean,
street: React.PropTypes.string,
city: React.PropTypes.string,
state: React.PropTypes.string,
code: React.PropTypes.string,
country: React.PropTypes.string,
}),
},
statics: {
getDefaultValue: getDefaultValue,
},
getDefaultProps () {
return {
filter: getDefaultValue(),
};
},
updateFilter (key, val) {
const update = {};
update[key] = val;
this.props.onChange(Object.assign(this.props.filter, update));
},
toggleInverted (value) {
this.updateFilter('inverted', value);
findDOMNode(this.refs.focusTarget).focus();
},
updateValue (e) {
this.updateFilter(e.target.name, e.target.value);
},
render () {
const { filter } = this.props;
return (
<div>
<FormField>
<SegmentedControl
equalWidthSegments
onChange={this.toggleInverted}
options={INVERTED_OPTIONS}
value={filter.inverted}
/>
</FormField>
<FormField>
<FormInput
autoFocus
name="street"
onChange={this.updateValue}
placeholder="Address"
ref="focusTarget"
value={filter.street}
/>
</FormField>
<Grid.Row gutter={10}>
<Grid.Col xsmall="two-thirds">
<FormInput
name="city"
onChange={this.updateValue}
placeholder="City"
style={{ marginBottom: '1em' }}
value={filter.city}
/>
</Grid.Col>
<Grid.Col xsmall="one-third">
<FormInput
name="state"
onChange={this.updateValue}
placeholder="State"
style={{ marginBottom: '1em' }}
value={filter.state}
/>
</Grid.Col>
<Grid.Col xsmall="one-third" style={{ marginBottom: 0 }}>
<FormInput
name="code"
onChange={this.updateValue}
placeholder="Postcode"
value={filter.code}
/>
</Grid.Col>
<Grid.Col xsmall="two-thirds" style={{ marginBottom: 0 }}>
<FormInput
name="country"
onChange={this.updateValue}
placeholder="Country"
value={filter.country}
/>
</Grid.Col>
</Grid.Row>
</div>
);
},
});
module.exports = TextFilter;
|
src/tests/App.spec.js
|
openproblems/landingpage
|
import React from 'react';
import { expect } from 'chai';
import sinon from 'sinon';
import { shallow, mount, render } from 'enzyme';
import App from '../components/App';
import Subtitle from '../components/sections/parts/Subtitle';
describe('<App />', () => {
it('renders a <Subtitle /> component', () => {
const wrapper = shallow(<App />);
expect(wrapper.find(Subtitle)).to.have.length(1);
});
it('calls componentDidMount', () => {
sinon.spy(App.prototype, 'componentDidMount');
mount(<App />);
expect(App.prototype.componentDidMount).to.have.property('callCount', 1);
App.prototype.componentDidMount.restore();
});
it('renders the title', () => {
const wrapper = render(<App />);
expect(wrapper.text()).to.contain('React Webpack Boilerplate');
});
});
|
src/collections/Form/FormRadio.js
|
aabustamante/Semantic-UI-React
|
import React from 'react'
import {
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
import Radio from '../../addons/Radio'
import FormField from './FormField'
/**
* Sugar for <Form.Field control={Radio} />.
* @see Form
* @see Radio
*/
function FormRadio(props) {
const { control } = props
const rest = getUnhandledProps(FormRadio, props)
const ElementType = getElementType(FormRadio, props)
return <ElementType {...rest} control={control} />
}
FormRadio._meta = {
name: 'FormRadio',
parent: 'Form',
type: META.TYPES.COLLECTION,
}
FormRadio.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** A FormField control prop. */
control: FormField.propTypes.control,
}
FormRadio.defaultProps = {
as: FormField,
control: Radio,
}
export default FormRadio
|
src/docs/examples/Table/ExampleSimpleTable.js
|
rajeshpillai/zs-react-pattern-lib
|
import React from 'react';
import Table from 'zs-react/Table';
/** SimpleTable */
export default class ExampleSimpleTable extends React.Component {
constructor () {
super();
this.headers = [
"Book", "Author", "Language", "Published", "Sales"
];
this.data = [
["The Lord of the Rings", "J. R. R. Tolkien", "English", "1954–1955", "150 million"],
["Le Petit Prince (The Little Prince)", "Antoine de Saint-Exupéry", "French", "1943", "140 million"],
["Harry Potter and the Philosopher's Stone", "J. K. Rowling", "English", "1997", "107 million"],
["And Then There Were None", "Agatha Christie", "English", "1939", "100 million"],
["Dream of the Red Chamber", "Cao Xueqin", "Chinese", "1754–1791", "100 million"],
["The Hobbit", "J. R. R. Tolkien", "English", "1937", "100 million"],
["She: A History of Adventure", "H. Rider Haggard", "English", "1887", "100 million"],
];
}
render() {
return (
<Table headers = {this.headers} initialData={this.data} />
)
}
}
|
docs/src/app/components/pages/components/TextField/ExampleDisabled.js
|
andrejunges/material-ui
|
import React from 'react';
import TextField from 'material-ui/TextField';
const TextFieldExampleDisabled = () => (
<div>
<TextField
disabled={true}
hintText="Disabled Hint Text"
/><br />
<TextField
disabled={true}
id="text-field-disabled"
defaultValue="Disabled Value"
/><br />
<TextField
disabled={true}
hintText="Disabled Hint Text"
floatingLabelText="Floating Label Text"
/><br />
<TextField
disabled={true}
hintText="Disabled Hint Text"
defaultValue="Disabled With Floating Label"
floatingLabelText="Floating Label Text"
/>
</div>
);
export default TextFieldExampleDisabled;
|
packages/neos-ui-editors/src/Editors/PluginViews/index.js
|
grebaldi/PackageFactory.Guevara
|
import React from 'react';
import PropTypes from 'prop-types';
import backend from '@neos-project/neos-ui-backend-connector';
import {neos} from '@neos-project/neos-ui-decorators';
import {connect} from 'react-redux';
import {selectors, actions} from '@neos-project/neos-ui-redux-store';
import mergeClassNames from 'classnames';
import {$transform} from 'plow-js';
import style from './style.css';
@neos(globalRegistry => {
return {
i18nRegistry: globalRegistry.get('i18n')
};
})
@connect($transform({
activeContentDimensions: selectors.CR.ContentDimensions.active,
personalWorkspace: selectors.CR.Workspaces.personalWorkspaceNameSelector,
focusedNodeIdentifier: selectors.CR.Nodes.focusedNodeIdentifierSelector
}), {
setActiveContentCanvasSrc: actions.UI.ContentCanvas.setSrc
})
class PluginViewsEditor extends React.PureComponent {
static propTypes = {
i18nRegistry: PropTypes.object.isRequired,
className: PropTypes.string,
activeContentDimensions: PropTypes.object.isRequired,
personalWorkspace: PropTypes.string,
focusedNodeIdentifier: PropTypes.string.isRequired,
setActiveContentCanvasSrc: PropTypes.func
};
state = {
isLoading: false,
views: []
};
componentDidMount() {
const {personalWorkspace, activeContentDimensions, focusedNodeIdentifier} = this.props;
if (!focusedNodeIdentifier) {
return;
}
const {loadPluginViews} = backend.get().endpoints;
if (!this.state.views.length) {
this.setState({isLoading: true});
loadPluginViews(focusedNodeIdentifier, personalWorkspace, activeContentDimensions)
.then(views => {
const viewsArray = [];
for (const viewName in views) {
if (views[viewName]) {
viewsArray.push(views[viewName]);
}
}
this.setState({
isLoading: false,
views: viewsArray
});
});
}
}
renderViewListItems() {
const {isLoading, views} = this.state;
if (isLoading) {
return (
<li className={style.pluginViewContainer__listItem}>
{this.props.i18nRegistry.translate('Neos.Neos:Main:loading', 'Loading')}
</li>
);
}
if (views.length > 0) {
return views.map(view =>
<li className={style.pluginViewContainer__listItem} key={view.label}>
<b>{view.label}</b>
{this.renderLocationLabel(Object.prototype.hasOwnProperty.call(view, 'pageNode'))}
{this.renderLink(view.pageNode)}
</li>
);
}
}
renderLocationLabel(onPage) {
let label = 'content.inspector.editors.pluginViewsEditor.';
label += onPage ? 'displayedOnPage' : 'displayedOnCurrentPage';
return this.props.i18nRegistry.translate(label);
}
renderLink(pageNode) {
return (
pageNode ? <a href="#" onClick={this.handleClick(pageNode.uri)}>{pageNode.title}</a> : null
);
}
handleClick = source => () => {
const {setActiveContentCanvasSrc} = this.props;
if (setActiveContentCanvasSrc) {
setActiveContentCanvasSrc(source);
}
}
render() {
const {className} = this.props;
const classNames = mergeClassNames({
[className]: true,
[style.pluginViewContainer]: true
});
return (
<ul className={classNames}>
{this.renderViewListItems()}
</ul>
);
}
}
export default PluginViewsEditor;
|
src/popup/popup.js
|
mazenbesher/sub_player_chrome_extension
|
"use strict";
// Notes
/**
* Subtitle Custom events
* sub-activated, sub-deactivated
* dispatched when a subtitle is (de)activated
* the (de)activated subtitle index can be found as the event detail
*/
// imports
import { config } from 'lib/config';
import { getActiveTabId, parseSRT } from 'lib/utils';
import React from 'react';
import ReactDOM from 'react-dom';
import { SubtitlesNavTabs } from './components/SubtitlesNavTabs';
import { SubtitlePaneContainer } from './components/SubtitlePaneContainer';
import { GeneralSection } from './components/GeneralSection';
const detect = require('charset-detector'); // for detecting encoding
import $ from 'jquery'
import Popper from 'popper.js'
// bootstrap requirements
window.jQuery = $
window.Popper = Popper
require('bootstrap')
require('bootstrap-colorpicker')
// Globals
let activeTabId;
let videoKey;
let subtitleFileNames = { 1: "", 2: "", 3: "" };
// generate react components
ReactDOM.render(
<div>
<SubtitlesNavTabs />
<SubtitlePaneContainer />
<GeneralSection />
</div>,
document.getElementById("react_container")
);
// register global logger function and onerror
let log;
chrome.runtime.getBackgroundPage(bg => {
log = msg => bg.globalLogger("popup", msg, config.popup.debugColor);
});
window.onerror = () => {
chrome.runtime.getBackgroundPage(bg => {
bg.globalWinOnerror("popup", config.popup.debugColor);
})
};
// global-style: enable/disable manual size/position change
getActiveTabId().then(activeTabId => {
chrome.tabs.sendMessage(activeTabId, {
action: "manualResizeState"
}, response => {
if (response) {
const checkbox = document.getElementById("enable_manual_resize");
checkbox.checked = response.state;
checkbox.onchange = (e) => {
if (e.target.checked) {
chrome.tabs.sendMessage(activeTabId, { action: "activatedManualResize" });
} else {
chrome.tabs.sendMessage(activeTabId, { action: "deactivatedManualResize" });
}
};
}
});
});
// global-style: font-size
// getActiveTabId().then(activeTabId => {
// const slider = document.getElementById("global_font_size_slider");
// let sliderChangeHandler = (e) => {
// const newRatio = e.target.value;
// document.getElementById("global_font_size_value").innerText = newRatio;
// for (let index = 1; index <= 3; index++) {
// setSubFontSize(index, document.querySelector(`#font_size_value_${index}`), newRatio);
// update individual sliders
// document.querySelector(`#font_size_slider_${index}`).value = newRatio;
// document.querySelector(`#font_size_value_${index}`).innerText = newRatio;
// }
// };
// slider.onchange = sliderChangeHandler;
// slider.oninput = sliderChangeHandler;
// slider.disabled = false;
// if all subtitles has the same size -> set global slider value
// chrome.tabs.sendMessage(activeTabId, {
// action: "isAllSubSameFontSize",
// }, response => {
// if (response && response.isAllSubSameFontSize == true) {
// slider.value = response.fontSize;
// $(slider).trigger("change"); // to trigger sliderChangeHandler
// }
// });
// });
// set active tab id and search for video when the popup is opened
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
activeTabId = tabs[0].id;
searchForVideos();
});
// hide encoding detection info
document.querySelectorAll(".detected_encoding").forEach(elm => elm.style.visibility = "hidden");
// state and register keyboard events for video playback
const regKeyEventsState = document.getElementById("reg_keyboard_event_state");
const regKeyEventsBtn = document.getElementById("reg_keyboard_event");
getActiveTabId().then(activeTabId => {
regKeyEventsBtn.disabled = true; // enable if video found
regKeyEventsBtn.onclick = () => {
chrome.tabs.sendMessage(activeTabId, { action: "regKeyboardEventForVideoPlayback" });
regKeyEventsBtn.disabled = true;
regKeyEventsState.innerText = "registered!";
};
});
// Unload subtitle
document.querySelectorAll(".unload_curr_subtitle").forEach(elm => {
elm.disabled = true;
elm.onclick = event => unloadSubtitle(elm.dataset.subtitleIndex);
});
// File input
document.querySelectorAll(".subtitle_file_input").forEach(elm => {
elm.disabled = true;
elm.onchange = readFile;
});
// manual encoding checkboxes
let manEncodingCheckboxes = {
1: document.getElementById("manual_encoding_detection_1"),
2: document.getElementById("manual_encoding_detection_2"),
3: document.getElementById("manual_encoding_detection_3")
};
// Body width based on current window width TODO: consider dynamic css instead (media queries [@min-width ...)
// chrome.windows.getCurrent(w => { // w = current window
// document.querySelector("body").style.width = w.width / 2; // half the size of the window
// });
// Sync listeners
for (let index = 1; index <= 3; index++) {
const selector = `#subtitle_controls_${index} input[data-sync-amount]`;
document.querySelectorAll(selector).forEach(elm => {
elm.onclick = () => seek(parseInt(elm.dataset.syncAmount), index);
elm.disabled = true;
});
}
function setUpSyncInfo(index) {
chrome.tabs.sendMessage(activeTabId, { action: "getSubSeek", index: index }, function (response) {
if (response != undefined && response.seeked) {
document.getElementById(`subtitle_seek_${index}`).innerText = response.amount;
}
});
}
function searchForVideos() {
chrome.tabs.sendMessage(activeTabId, { action: "searchForVideos" }, function (response) {
if (response != undefined && response.videoDetected) { // NOTE: response can be undefined if none of the content scripts (possibly in multiple frames) detected a video -> no response is sent back
videoKey = response["videoKey"];
videoFound();
}
});
}
function videoFound() {
// enable file inputs
document.querySelectorAll(".subtitle_file_input").forEach(
elm => elm.disabled = false
);
// check storage to show file name
checkIfVideoHasSubtitleInStorage();
// playback key registration
regKeyEventsBtn.disabled = false;
checkIfKeyEventsAreRegistered();
}
function checkIfKeyEventsAreRegistered() {
chrome.tabs.sendMessage(activeTabId, { action: "getRegKeyEventsState" }, function (response) {
if (response.registered) {
regKeyEventsState.innerText = "registered!";
regKeyEventsBtn.disabled = true;
} else {
regKeyEventsState.innerText = "Not registered";
}
});
}
function checkIfVideoHasSubtitleInStorage() {
for (let index = 1; index <= 3; index++) {
const key = getVideoKey(index);
chrome.storage.local.get(key, function (result) {
if (result[key]) {
setCurrSubFileName(JSON.parse(result[key])["fileName"], index);
enableSyncControls(index);
enableUnloadSubBtn(index);
setUpSyncInfo(index);
document.dispatchEvent(new CustomEvent('sub-activated', { detail: index }));
// enable file input buttons
document.getElementById("subtitle_file_input_" + index).disabled = false;
}
})
}
}
function enableSyncControls(index) {
const selector = `#subtitle_controls_${index} input[data-sync-amount]`;
document.querySelectorAll(selector).forEach((elm, index) => {
elm.disabled = false;
});
}
function enableUnloadSubBtn(index) {
const selector = `.unload_curr_subtitle[data-subtitle-index="${index}"`;
document.querySelector(selector).disabled = false;
}
function setCurrSubFileName(newName, index) {
log(`setting subtitle ${index} to: ${newName}`);
subtitleFileNames[index] = newName;
const id = `current_subtitle_file_name_${index}`;
document.getElementById(id).innerText = newName;
// show detection info from storage if exists
chrome.storage.local.get(newName, result => {
if (result !== undefined && result[newName])
setDetectedEncoding(JSON.parse(result[newName]), index);
})
}
function readFile() {
// this === input element
if (this.files && this.files[0]) {
const index = this.dataset.subtitleIndex;
unloadSubtitle(index);
setCurrSubFileName(this.files[0].name, index);
enableUnloadSubBtn(index);
detectEncoding(this, index).then(encoding => {
log("selected encoding: " + encoding);
var reader = new FileReader();
reader.onload = e => {
// e = ProgressEvent
// e.target = FileReader
parseSRT(e.target.result).then(subtitles => saveAndNotify(subtitles, index));
};
reader.readAsText(this.files[0], encoding);
});
} else {
throw new Error("can't read file"); // TODO handle error in user-friendly way
return false;
}
return true;
}
function setDetectedEncoding(detectRes, index) {
if (detectRes === "hide")
detectRes = null;
log(`setting subtitle ${index} file encoding info`);
document.dispatchEvent(new CustomEvent('set-detected-encoding-info', { detail: detectRes }))
// document.getElementById(containerId).style.visibility = "visible";
// document.querySelector(`#${containerId} .detected_encoding_charset`).innerText = detectRes["charsetName"];
// document.querySelector(`#${containerId} .detected_encoding_lang`).innerText = detectRes["lang"];
// document.querySelector(`#${containerId} .detected_encoding_confidence`).innerText = Math.round(detectRes["confidence"]) + "%";
}
function saveDetectedEncodingInfoForFile(fileName, encodingInfo) {
let toSave = {};
toSave[fileName] = JSON.stringify(encodingInfo);
chrome.storage.local.set(toSave, () => {
log(`saved detected file encodings info for: ${fileName}`);
});
}
function detectEncoding(inputElm, index) {
if (!inputElm.files || !inputElm.files[0]) return;
return new Promise(resolve => {
if (manEncodingCheckboxes[index].checked) {
// is selected manually?
var selectedEncoding = document.getElementById("manual_encoding_input_" + index).value.trim();
if (selectedEncoding.length > 0)
resolve(selectedEncoding);
else
resolve(document.getElementById("encoding_select_" + index).value);
} else {
// else detect
var detectRes;
var reader = new FileReader();
reader.onload = (e) => {
var arrayBuffer = e.target.result;
var bytes = new Uint8Array(arrayBuffer);
detectRes = detect(bytes);
/**
* detectRes sample:
* [ CharsetMatch {
* confidence: 44.92058548738711,
* charsetName: 'windows-1256',
* lang: 'ar' }, ...
* ]
*/
// set DOM elements related to detected encoding
setDetectedEncoding(detectRes[0], index);
saveDetectedEncodingInfoForFile(inputElm.files[0].name, detectRes[0]);
resolve(detectRes[0]["charsetName"]);
};
}
reader.readAsArrayBuffer(inputElm.files[0]);
});
}
function saveAndNotify(subtitles, index) {
let toSave = {};
let key = getVideoKey(index);
toSave[key] = JSON.stringify({
"fileName": subtitleFileNames[index],
"subtitles": subtitles
});
chrome.storage.local.set(toSave, function () {
// when done saving
// send them to content script
chrome.tabs.sendMessage(activeTabId, { action: "srtParsed", subtitles: subtitles, index: index });
enableSyncControls(index);
document.dispatchEvent(new CustomEvent('sub-activated', { detail: index }));
});
}
function seek(value, index) {
// log(`request seeking index: ${index}, value: ${value}`);
// value in ms
chrome.tabs.sendMessage(activeTabId, { action: "seekSubtitle", index: index, amount: value }, function (response) {
document.getElementById(`subtitle_seek_${index}`).innerText = response.seekedValue
});
}
function unloadSubtitle(index) {
document.dispatchEvent(new CustomEvent('sub-deactivated', { detail: index }));
// disable unload sub button
const selector = `button.unload_curr_subtitle[data-subtitle-index="${index}"`;
document.querySelector(selector).disabled = true;
// set file name
setCurrSubFileName("None", index);
log(`unloading subtitle with index ${index}`);
// delete from storage
if (videoKey === null || videoKey === undefined) // double check
return;
let key = getVideoKey(index);
chrome.storage.local.remove(key);
// hide encoding detection info (TODO: should be also deleted from storage?)
setDetectedEncoding("hide", index);
// Send message to active tab to hide subtitle
chrome.tabs.sendMessage(activeTabId, { action: "unloadSubtitle", index: index });
}
function getVideoKey(index) {
if (videoKey != null)
if (index)
return `${videoKey}_${index}`;
else
return `${videoKey}`;
else
throw new Error("called getVideoKey although no videoKey is set!");
}
// TODO these function must be modified
export function loadSubtitle(index, filename, decodedSubtitle) {
unloadSubtitle(index);
setCurrSubFileName(filename, index);
enableUnloadSubBtn(index);
parseSRT(decodedSubtitle).then(subtitles => saveAndNotify(subtitles, index));
}
|
components/ArticleReply/ArticleReply.js
|
cofacts/rumors-site
|
import React from 'react';
import { t } from 'ttag';
import gql from 'graphql-tag';
import { Box } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import { nl2br, linkify } from 'lib/text';
import getTermsString from 'lib/terms';
import { TYPE_NAME, TYPE_REFERENCE_TITLE } from 'constants/replyType';
import ExpandableText from 'components/ExpandableText';
import ArticleReplyFeedbackControl from 'components/ArticleReplyFeedbackControl';
import ArticleReplySummary from 'components/ArticleReplySummary';
import Hyperlinks from 'components/Hyperlinks';
import Avatar from 'components/AppLayout/Widgets/Avatar';
import ReplyInfo from 'components/ReplyInfo';
import ReplyActions from './ReplyActions';
import ReplyShare from './ReplyShare';
const useStyles = makeStyles(theme => ({
content: {
padding: '17px 0',
borderBottom: `1px dashed ${theme.palette.secondary[100]}`,
},
avatar: {
marginRight: theme.spacing(1),
[theme.breakpoints.up('md')]: {
marginRight: theme.spacing(2),
},
},
}));
const ArticleReplyData = gql`
fragment ArticleReplyData on ArticleReply {
# articleId and replyId are required to identify ArticleReply instances
articleId
replyId
canUpdateStatus
createdAt
reply {
id
type
text
reference
user {
id
name
...AvatarData
}
hyperlinks {
...HyperlinkData
}
...ReplyInfo
}
user {
...AvatarData
}
...ArticleReplySummaryData
...ArticleReplyFeedbackControlData
...ReplyActionsData
}
${Hyperlinks.fragments.HyperlinkData}
${ArticleReplyFeedbackControl.fragments.ArticleReplyFeedbackControlData}
${ReplyInfo.fragments.replyInfo}
${Avatar.fragments.AvatarData}
${ArticleReplySummary.fragments.ArticleReplySummaryData}
${ReplyActions.fragments.ReplyActionsData}
`;
const ArticleReplyForUser = gql`
fragment ArticleReplyForUser on ArticleReply {
# articleId and replyId are required to identify ArticleReply instances
articleId
replyId
canUpdateStatus
...ArticleReplyFeedbackControlDataForUser
...ReplyActionsDataForUser
}
${ArticleReplyFeedbackControl.fragments
.ArticleReplyFeedbackControlDataForUser}
${ReplyActions.fragments.ReplyActionsDataForUser}
`;
const ArticleReply = React.memo(({ articleReply }) => {
const { createdAt, reply, replyId } = articleReply;
const { type: replyType } = reply;
const classes = useStyles({ replyType });
const renderFooter = () => {
const articleUrl =
typeof window !== 'undefined'
? // Construct Article URL without search strings (usually gibberish 1st-party trackers)
window.location.origin + window.location.pathname
: '';
const copyText =
typeof window !== 'undefined'
? `${TYPE_NAME[reply.type]}\n` +
`【${t`Reason`}】${(reply.text || '').trim()}\n` +
`↓${t`Details`}↓\n` +
`${articleUrl}\n` +
(TYPE_REFERENCE_TITLE[reply.type]
? `↓${TYPE_REFERENCE_TITLE[reply.type]}↓\n` + `${reply.reference}\n`
: '') +
`--\n` +
`ℹ️ ${getTermsString(/* t: terms subject */ t`This info`)}\n`
: '';
return (
<Box component="footer" display="flex" pt={2}>
<ArticleReplyFeedbackControl
articleReply={articleReply}
className={classes.feedbacks}
/>
<ReplyShare copyText={copyText} />
</Box>
);
};
const renderReference = () => {
if (replyType === 'NOT_ARTICLE') return null;
const reference = reply.reference;
return (
<section className={classes.root}>
<h3>{TYPE_REFERENCE_TITLE[replyType]}</h3>
{reference
? nl2br(linkify(reference))
: `⚠️️ ${t`There is no reference for this reply. Its truthfulness may be doubtful.`}`}
<Hyperlinks
hyperlinks={reply.hyperlinks}
pollingType="replies"
pollingId={replyId}
/>
</section>
);
};
return (
<>
<Box component="header" display="flex" alignItems="center">
<Avatar
user={articleReply.user}
size={30}
mdSize={42}
className={classes.avatar} /*hasLink*/
/>
<Box flexGrow={1}>
<ArticleReplySummary articleReply={articleReply} />
<ReplyInfo reply={reply} articleReplyCreatedAt={createdAt} />
</Box>
<ReplyActions articleReply={articleReply} />
</Box>
<section className={classes.content}>
<ExpandableText lineClamp={10}>
{nl2br(linkify(reply.text))}
</ExpandableText>
</section>
{renderReference()}
{renderFooter()}
</>
);
});
ArticleReply.fragments = {
ArticleReplyData,
ArticleReplyForUser,
};
ArticleReply.displayName = 'ArticleReply';
export default ArticleReply;
|
app/components/Settings.js
|
jakkra/OneAppToRuleThemAll
|
'use-strict';
import React from 'react';
import {
StyleSheet,
View,
Dimensions,
Text,
TextInput,
InteractionManager,
ToastAndroid,
Clipboard,
} from 'react-native';
import { connect } from 'react-redux';
import { updateHueSettings } from '../actions/user';
import Icon from 'react-native-vector-icons/FontAwesome';
import {
MKButton,
} from 'react-native-material-kit';
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: 'white',
},
header: {
flexDirection: 'column',
height: 50,
borderBottomWidth: 0.3,
borderBottomColor: 'lightgray',
alignItems: 'flex-start',
justifyContent: 'center',
},
headerText: {
fontSize: 18,
fontWeight: 'bold',
marginHorizontal: 20,
alignSelf: 'stretch',
width: Dimensions.get('window').width,
color: '#0099CC',
},
row: {
flex: 1,
flexDirection: 'row',
marginHorizontal: 10,
height: 40,
alignItems: 'center',
},
settingsView: {
flex: 1,
flexDirection: 'column',
alignItems: 'center',
width: Dimensions.get('window').width,
},
buttonText: {
fontSize: 20,
fontWeight: 'bold',
color: 'white',
},
labelText: {
marginTop: 50,
fontSize: 18,
color: '#0099CC',
},
textFieldId: {
width: Dimensions.get('window').width - 100,
borderBottomColor: '#0099CC',
color: '#0099CC',
},
textFieldToken: {
width: Dimensions.get('window').width - 100,
color: '#0099CC',
},
saveButton: {
width: 130,
height: 40,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 2,
},
saveButtonText: {
fontSize: 22,
color: 'white',
fontWeight: 'bold',
paddingHorizontal: 2,
alignSelf: 'center',
justifyContent: 'center',
},
});
/**
* Displays the Settings screen.
*/
export default class Settings extends React.Component {
static propTypes = {
handleNavigate: React.PropTypes.func.isRequired,
goBack: React.PropTypes.func.isRequired,
userReducer: React.PropTypes.object.isRequired,
updateHueSettings: React.PropTypes.func.isRequired,
};
constructor(props) {
super(props);
if (this.props.userReducer.user.hueBridgeId !== null &&
this.props.userReducer.user.hueBridgeToken) {
this.state = {
hueBridgeId: this.props.userReducer.user.hueBridgeId,
hueBridgeToken: this.props.userReducer.user.hueBridgeToken,
};
} else {
this.state = {
hueBridgeId: '',
hueBridgeToken: '',
};
}
}
componentDidMount() {
InteractionManager.runAfterInteractions(() => {
console.log(this.props.userReducer);
});
// ToastAndroid.show('Error getting location status', ToastAndroid.SHORT)
}
componentWillReceiveProps(nextProps) {
if (this.props.userReducer.isUpdatingUser === true &&
nextProps.userReducer.isUpdatingUser === false) {
ToastAndroid.show('Successfully updated settings', ToastAndroid.SHORT);
}
}
saveSettings() {
this.props.updateHueSettings(
this.props.userReducer.accessToken,
this.state.hueBridgeId,
this.state.hueBridgeToken
);
}
render() {
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerText}>Settings</Text>
</View>
<View style={styles.settingsView}>
<Text style={styles.labelText}>Hue Bridge Id</Text>
<TextInput
autoCorrect={false}
style={styles.textFieldId}
placeholder={'Bridge ID'}
value={this.state.hueBridgeId}
onChangeText={text => this.setState({ ...{ hueBridgeId: text } })}
onSubmitEditing={() => {
this.updateSettings();
}}
/>
<Text style={styles.labelText}>Hue Bridge Access Token</Text>
<TextInput
autoCorrect={false}
style={styles.textFieldToken}
value={this.state.hueBridgeToken}
placeholder={'Access Token'}
onChangeText={text => this.setState({ ...{ hueBridgeToken: text } })}
/>
<MKButton
style={styles.saveButton}
backgroundColor={'#0099CC'}
shadowRadius={2}
shadowOffset={{ width: 0, height: 2 }}
shadowOpacity={0.7}
shadowColor="black"
onPress={() => {
this.saveSettings();
}}
>
<Text
pointerEvents="none"
style={styles.saveButtonText}
> Save</Text>
</MKButton>
<Text style={styles.labelText}>Your access token! Copy it!</Text>
<MKButton
style={styles.saveButton}
backgroundColor={'#0099CC'}
shadowRadius={2}
shadowOffset={{ width: 0, height: 2 }}
shadowOpacity={0.7}
shadowColor="black"
onPress={() => {
Clipboard.setString(this.props.userReducer.accessToken);
}}
>
<Text
pointerEvents="none"
style={styles.saveButtonText}
> Copy token</Text>
</MKButton>
</View>
</View>
);
}
}
function mapStateToProps(state) {
return {
userReducer: state.user,
};
}
function mapDispatchToProps(dispatch) {
return {
updateHueSettings: (...args) => { dispatch(updateHueSettings(...args)); },
};
}
module.exports = connect(mapStateToProps, mapDispatchToProps)(Settings);
|
src/svg-icons/action/info-outline.js
|
barakmitz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionInfoOutline = (props) => (
<SvgIcon {...props}>
<path d="M11 17h2v-6h-2v6zm1-15C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zM11 9h2V7h-2v2z"/>
</SvgIcon>
);
ActionInfoOutline = pure(ActionInfoOutline);
ActionInfoOutline.displayName = 'ActionInfoOutline';
ActionInfoOutline.muiName = 'SvgIcon';
export default ActionInfoOutline;
|
src/routes/contact/Contact.js
|
edgarallanglez/foxacademia_frontend
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Contact.css';
class Contact extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
};
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>{this.props.title}</h1>
<p>...</p>
</div>
</div>
);
}
}
export default withStyles(s)(Contact);
|
src/components/utils/ColSM4.js
|
Harrison1/several-levels
|
import React from 'react'
const ColSM4 = ({ children }) =>
<div className="col-sm-4 text-center">
{ children }
</div>
export default ColSM4
|
pootle/static/js/stats.js
|
dwaynebailey/pootle
|
/*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import $ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import 'jquery-utils';
import assign from 'object-assign';
import 'sorttable';
import cookie from 'utils/cookie';
import { q } from 'utils/dom';
import Stats from './browser/components/Stats';
import VisibilityToggle from './browser/components/VisibilityToggle';
import msg from './msg';
const stats = {
init(options) {
if (cookie('finished')) {
msg.show({
text: gettext('Congratulations! You have completed this task!'),
level: 'success',
});
cookie('finished', null, { path: '/' });
}
this.retries = 0;
const isExpanded = (options.isInitiallyExpanded ||
window.location.search.indexOf('?details') !== -1);
this.state = {
isExpanded,
checksData: null,
data: options.initialData,
};
this.pootlePath = options.pootlePath;
this.$extraDetails = $('#js-path-summary-more');
this.$expandIcon = $('#js-expand-icon');
$(document).on('click', '#js-path-summary', (e) => {
e.preventDefault();
this.toggleDetailedStats();
});
$(document).on('click', '.js-toggle-more-checks', (e) => {
let count = 0;
e.preventDefault();
$('.js-check').each(function toggleCheck() {
const $check = $(this);
if (count >= 4) {
$check.toggle();
}
count++;
});
$(e.target).parent().toggleClass('collapsed');
});
window.addEventListener('popstate', (e) => {
const state = e.state;
if (state) {
this.setState({ isExpanded: state.isExpanded });
}
});
if (options.hasDisabledItems) {
ReactDOM.render(<VisibilityToggle uiLocaleDir={options.uiLocaleDir} />,
q('.js-mnt-visibility-toggle'));
}
ReactDOM.render(
<Stats
hasMoreContributors={options.topContributorsData.has_more_items}
topContributors={options.topContributorsData.items}
pootlePath={this.pootlePath}
/>,
q('#js-mnt-top-contributors')
);
this.updateUI();
this.updateStatsUI();
},
setState(newState) {
this.state = assign({}, this.state, newState);
this.updateUI();
this.updateChecksToggleUI();
},
updateStatsUI() {
const $table = $('#content table.stats');
if ($table.length) {
// Sort columns based on previously-made selections
const columnSort = sorttable.getSortCookie($table.data('sort-cookie'));
if (columnSort !== null) {
const $th = $(`#${columnSort.columnId}`);
$th.removeClass('sorttable_sorted sorttable_sorted_reverse');
setTimeout(() => {
$th.click();
if (columnSort.order === 'desc') {
$th.click();
}
}, 1);
}
}
},
/* Path summary */
toggleDetailedStats() {
if (!(this.state.checksData)) {
this.setState({ isExpanded: !this.state.isExpanded });
}
this.navigate();
},
updateChecksToggleUI() {
const { isExpanded } = this.state;
const newClass = isExpanded ? 'collapse' : 'expand';
const newText = isExpanded ? gettext('Collapse details') : gettext('Expand details');
this.$expandIcon.attr('class', `icon-${newClass}-stats`);
this.$expandIcon.attr('title', newText);
this.$extraDetails.toggleClass('expand', isExpanded);
},
updateChecksUI() {
let count = 0;
this.$extraDetails.find('.js-check').each(function updateCheck() {
const $check = $(this);
count++;
$check.toggle(count < 5);
});
$('.js-more-checks').addClass('collapsed').toggle(count >= 5);
$('#js-stats-checks').show();
},
updateUI() {
this.updateChecksToggleUI();
this.updateChecksUI();
},
navigate() {
const { isExpanded } = this.state;
const currentURL = `${window.location.pathname}${window.location.search}`;
const path = l(this.pootlePath);
const newURL = isExpanded ? `${path}?details` : path;
if (currentURL !== newURL) {
window.history.pushState({ isExpanded }, '', newURL);
}
},
};
export default stats;
|
test/electron-renderer/ui/LocaleSelector_spec.js
|
petuhovskiy/Google-Play-Music-Desktop-Player-UNOFFICIAL-
|
/* eslint-disable no-unused-expressions */
import React from 'react';
import chai from 'chai';
import fs from 'fs';
import path from 'path';
import { mount } from 'enzyme';
import LocaleSelector from '../../../build/renderer/ui/components/settings/LocaleSelector';
import materialUIContext from './_materialUIContext';
import mockSettings, { getVars } from './_mockSettings';
chai.should();
describe('<LocaleSelector />', () => {
let hooks;
let unhooks;
let fired;
beforeEach(() => {
mockSettings();
hooks = getVars().hooks;
unhooks = getVars().unhooks;
fired = getVars().fired;
});
it('should render a selection menu', () => {
const component = mount(<LocaleSelector />, materialUIContext);
component.find('SelectField').length.should.be.equal(1);
});
it('should initialy render an enabled dropdown menu', () => {
const component = mount(<LocaleSelector />, materialUIContext);
component.find('SelectField').props().disabled.should.be.equal(false);
});
it('should hook into locale events when mounting', () => {
mount(<LocaleSelector />, materialUIContext);
hooks.should.have.property('settings:change:locale');
});
it('should unhook from locale events when unmounting', () => {
mount(<LocaleSelector />, materialUIContext).unmount();
unhooks.should.have.property('settings:change:locale');
});
it('should set the locale setting when the dropdown option changes', () => {
const component = mount(<LocaleSelector />, materialUIContext);
component.find('SelectField').props().onChange(null, null, 'magic_language');
fired['settings:set'].should.be.ok;
fired['settings:set'].length.should.be.equal(1);
fired['settings:set'][0][0].should.be.deep.equal({
key: 'locale',
value: 'magic_language',
});
});
it('should display all possible JSON languages in the dropdown', () => {
const component = mount(<LocaleSelector />, materialUIContext);
const JSONCount = fs.readdirSync(path.resolve(__dirname, '..', '..', '..', 'src', '_locales')).length - 1;
component.find('SelectField').props().children.length.should.be.equal(JSONCount);
});
});
|
test/helpers.js
|
pivotal-cf/react-bootstrap
|
import React from 'react';
import { cloneElement } from 'react';
export function shouldWarn(about) {
console.warn.called.should.be.true;
console.warn.calledWithMatch(about).should.be.true;
console.warn.reset();
}
/**
* Helper for rendering and updating props for plain class Components
* since `setProps` is deprecated.
* @param {ReactElement} element Root element to render
* @param {HTMLElement?} mountPoint Optional mount node, when empty it uses an unattached div like `renderIntoDocument()`
* @return {ComponentInstance} The instance, with a new method `renderWithProps` which will return a new instance with updated props
*/
export function render(element, mountPoint){
let mount = mountPoint || document.createElement('div');
let instance = React.render(element, mount);
if (!instance.renderWithProps) {
instance.renderWithProps = function(newProps) {
return render(
cloneElement(element, newProps), mount);
};
}
return instance;
}
|
ui/web/components/message-list.js
|
Sebi55/whatkindofdeveloperareyou
|
import React from 'react';
import ReactDOM from 'react-dom';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import TypingIndicator from './typing-indicator';
import Message from './message';
class MessageList extends React.Component {
componentDidUpdate() {
var node = this.refs.list;
var messageMargin = 10
if (node.scrollHeight > (node.clientHeight + messageMargin)) {
node.scrollTop = node.scrollHeight;
}
}
render() {
var typing = (this.props.typing) ? <TypingIndicator/> : null
return <div className="messages">
<div ref="list" className="list">
<ReactCSSTransitionGroup transitionName="fadeInUp" transitionEnterTimeout={500} transitionLeaveTimeout={1}>
{this.props.messages.map((message, index) => (
<Message key={index} message={message}/>
))}
{ typing }
</ReactCSSTransitionGroup>
</div>
</div>
}
}
module.exports = MessageList
|
src/index.js
|
bernardAdark/myCrib-doc
|
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app';
import remark from 'remark';
import slug from 'remark-slug';
import content from '../custom/content';
var ast = remark()
.use(slug)
.run(remark().parse(content));
ReactDOM.render(
<App ast={ast} content={content} />,
document.getElementById('app'));
|
js/App/Components/Device/Common/ExcludeDevice.js
|
telldus/telldus-live-mobile-v3
|
/**
* Copyright 2016-present Telldus Technologies AB.
*
* This file is part of the Telldus Live! app.
*
* Telldus Live! app is free : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Telldus Live! app is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>.
*
*/
// @flow
'use strict';
import React from 'react';
import { LayoutAnimation } from 'react-native';
const isEqual = require('react-fast-compare');
import { connect } from 'react-redux';
import {
View,
TouchableButton,
InfoBlock,
} from '../../../../BaseComponents';
import ZWaveIncludeExcludeUI from './ZWaveIncludeExcludeUI';
import CantEnterInclusionExclusionUI from './CantEnterInclusionExclusionUI';
import { widgetAndroidDisableWidget } from '../../../Actions/Widget';
import {
getDeviceManufacturerInfo,
} from '../../../Actions/Devices';
import { LayoutAnimations } from '../../../Lib';
import i18n from '../../../Translations/common';
import Theme from '../../../Theme';
type Props = {
appLayout: Object,
clientId: number,
manufacturerAttributes?: Object,
dispatch: Function,
intl: Object,
onExcludeSuccess: () => void,
onExcludeSuccessImmediate: () => void,
onExcludeTimedoutImmediate: () => void,
onPressCancelExclude: () => void,
processWebsocketMessage: (string, string, string, Object) => any,
onCantEnterExclusionTimeout: () => void,
registerForWebSocketEvents: (Object) => Object,
};
type State = {
showTimer: boolean,
timer: number | null,
status?: string | null,
progress: number,
excludeSucces: boolean,
showThrobber: boolean,
cantEnterExclusion: boolean,
cantEnterLearnMode: boolean,
exclusionDescription?: string,
};
class ExcludeDevice extends View<Props, State> {
props: Props;
state: State;
onPressCancelExclude: () => void;
onPressOkay: () => void;
handleErrorEnterLearnMode: () => void;
startRemoveDevice: () => void;
onPressTryAgain: () => void;
runExclusionTimer: (?number) => void;
constructor(props: Props) {
super(props);
this.state = {
showTimer: true,
timer: null,
status: undefined,
progress: 0,
excludeSucces: false,
showThrobber: false,
cantEnterExclusion: false,
cantEnterLearnMode: false,
exclusionDescription: undefined,
};
this.onPressCancelExclude = this.onPressCancelExclude.bind(this);
this.handleErrorEnterLearnMode = this.handleErrorEnterLearnMode.bind(this);
this.onPressOkay = this.onPressOkay.bind(this);
this.startRemoveDevice = this.startRemoveDevice.bind(this);
this.onPressTryAgain = this.onPressTryAgain.bind(this);
this.runExclusionTimer = this.runExclusionTimer.bind(this);
this.enterExclusionModeTimeout = null;
this.showThrobberTimeout = null;
this.destroyInstanceWebSocket = null;
this.sendSocketMessageMeth = null;
}
componentDidMount() {
const {
registerForWebSocketEvents,
manufacturerAttributes = {},
dispatch,
} = this.props;
const callbacks = {
callbackOnOpen: this.callbackOnOpen,
callbackOnMessage: this.callbackOnMessage,
};
let {
sendSocketMessage,
destroyInstance,
} = registerForWebSocketEvents(callbacks);
this.sendSocketMessageMeth = sendSocketMessage;
this.destroyInstanceWebSocket = destroyInstance;
const {
manufacturerId,
productId,
productTypeId,
} = manufacturerAttributes;
if (typeof manufacturerId !== 'undefined') {
dispatch(getDeviceManufacturerInfo(manufacturerId, productTypeId, productId)).then((res: Object = {}) => {
const {
ExclusionDescription,
} = res;
if (ExclusionDescription) {
this.setState({
exclusionDescription: ExclusionDescription,
});
}
});
}
}
callbackOnOpen = () => {
this.sendFilter('zwave', 'removeNodeFromNetwork');
this.sendFilter('zwave', 'removeNodeFromNetworkStartTimeout');
this.sendFilter('device', 'removed');
this.sendFilter('sensor', 'removed');
}
sendFilter = (module: string, action: string) => {
const message = JSON.stringify({
module: 'filter',
action: 'accept',
data: {
module,
action,
},
});
this.sendSocketMessage(message);
}
sendSocketMessage = (message: string) => {
if (this.sendSocketMessageMeth) {
this.sendSocketMessageMeth(message);
}
}
onPressTryAgain() {
LayoutAnimation.configureNext(LayoutAnimations.linearU(300));
this.setState({
status: undefined,
}, () => {
this.startRemoveDevice();
});
}
stopAddRemoveDevice() {
const message = JSON.stringify({
module: 'client',
action: 'forward',
data: {
'module': 'zwave',
'action': 'removeNodeFromNetworkStop',
},
});
this.sendSocketMessage(message);
const message2 = JSON.stringify({
module: 'client',
action: 'forward',
data: {
'module': 'zwave',
'action': 'addNodeToNetworkStop',
},
});
this.sendSocketMessage(message2);
}
startRemoveDevice() {
const message = JSON.stringify({
module: 'client',
action: 'forward',
data: {
'module': 'zwave',
'action': 'removeNodeFromNetwork',
},
});
this.sendSocketMessage(message);
}
stopRemoveDevice() {
const message = JSON.stringify({
module: 'client',
action: 'forward',
data: {
'module': 'zwave',
'action': 'removeNodeFromNetworkStop',
},
});
this.sendSocketMessage(message);
}
shouldComponentUpdate(nextProps: Object, nextState: Object): boolean {
return !isEqual(this.state, nextState);
}
componentWillUnmount() {
this.clearTimer();
clearTimeout(this.enterExclusionModeTimeout);
clearTimeout(this.showThrobberTimeout);
if (this.destroyInstanceWebSocket) {
this.destroyInstanceWebSocket();
}
}
startEnterExclusionModeTimeout() {
this.enterExclusionModeTimeout = setTimeout(() => {
const { timer, progress } = this.state;
if (timer === null && progress === 0) {
this.cantEnterExclusionMode();
}
}, 10000);
}
cantEnterExclusionMode() {
this.clearTimer();
clearTimeout(this.showThrobberTimeout);
this.setState({
cantEnterExclusion: true,
}, () => {
const { onCantEnterExclusionTimeout } = this.props;
if (onCantEnterExclusionTimeout) {
onCantEnterExclusionTimeout();
}
});
}
startShowThrobberTimeout() {
this.showThrobberTimeout = setTimeout(() => {
const { timer, progress, showThrobber } = this.state;
if (timer === null && progress === 0 && !showThrobber) {
this.setState({
showThrobber: true,
});
}
}, 1000);
}
callbackOnMessage = (msg: Object) => {
const {
intl,
onExcludeSuccessImmediate,
} = this.props;
let message = {};
try {
message = JSON.parse(msg.data);
} catch (e) {
message = msg.data;
}
const { module, action, data } = message;
if (typeof message === 'string') {
if (message === 'validconnection') {
this.startRemoveDevice();
this.startEnterExclusionModeTimeout();
this.startShowThrobberTimeout();
}
} else if (module && action) {
if (module === 'zwave' && action === 'removeNodeFromNetworkStartTimeout') {
clearTimeout(this.enterExclusionModeTimeout);
clearTimeout(this.showThrobberTimeout);
if (this.exclusionTimer) {
clearInterval(this.exclusionTimer);
}
this.exclusionTimer = setInterval(() => {
this.runExclusionTimer(data);
}, 1000);
} else if (module === 'zwave' && action === 'removeNodeFromNetwork') {
clearTimeout(this.enterExclusionModeTimeout);
clearTimeout(this.showThrobberTimeout);
let status = data[0];
if (status === 6) {
if (data[2] > 0) {
this.clearTimer();
if (onExcludeSuccessImmediate) {
onExcludeSuccessImmediate();
} else {
this.setState({
excludeSucces: true,
timer: `${intl.formatMessage(i18n.done)}!`,
status: intl.formatMessage(i18n.messageDeviceExcluded),
progress: 100,
showThrobber: false,
cantEnterLearnMode: false,
});
}
}
}
if (status === 7) {
this.handleErrorEnterLearnMode();
}
}
if (module === 'device' && action === 'removed') {
clearTimeout(this.enterExclusionModeTimeout);
clearTimeout(this.showThrobberTimeout);
this.clearTimer();
if (onExcludeSuccessImmediate) {
onExcludeSuccessImmediate();
} else {
this.setState({
excludeSucces: true,
timer: `${intl.formatMessage(i18n.done)}!`,
status: intl.formatMessage(i18n.messageDeviceExcluded),
progress: 100,
showThrobber: false,
cantEnterLearnMode: false,
});
}
const { id } = data;
widgetAndroidDisableWidget(id, 'DEVICE');
}
if (module === 'sensor' && action === 'removed') {
const { id } = data;
widgetAndroidDisableWidget(id, 'SENSOR');
}
}
}
handleErrorEnterLearnMode() {
const { showThrobber, cantEnterLearnMode } = this.state;
if (showThrobber && cantEnterLearnMode) {
this.cantEnterExclusionMode();
} else {
this.setState({
showThrobber: true,
status: '',
cantEnterLearnMode: true,
});
this.stopAddRemoveDevice();
this.startRemoveDevice();
}
}
runExclusionTimer(data?: number = 60) {
const { timer } = this.state;
if (timer === null || timer > 0) {
const progress = timer ? Math.max((data - timer) / 60, 0) : 0;
this.setState({
timer: timer ? timer - 1 : data,
progress,
status: '',
excludeSucces: false,
showThrobber: false,
cantEnterLearnMode: false,
});
} else if (timer === 0) {
const { onExcludeTimedoutImmediate } = this.props;
this.clearTimer();
if (onExcludeTimedoutImmediate) {
onExcludeTimedoutImmediate();
} else {
this.setState({
timer: null,
status: 'timed out',
showThrobber: false,
cantEnterLearnMode: false,
});
}
}
}
clearTimer() {
clearInterval(this.exclusionTimer);
}
onPressCancelExclude() {
const { onPressCancelExclude } = this.props;
this.clearTimer();
this.stopRemoveDevice();
if (onPressCancelExclude) {
onPressCancelExclude();
}
}
onPressOkay() {
const { onExcludeSuccess } = this.props;
if (onExcludeSuccess) {
onExcludeSuccess();
}
}
render(): Object {
const { intl, appLayout } = this.props;
const {
timer,
status,
progress,
excludeSucces,
showTimer,
showThrobber,
cantEnterExclusion,
exclusionDescription,
} = this.state;
const { formatMessage } = intl;
let timerText = (timer !== null && showTimer) ? `${timer} ${formatMessage(i18n.labelSeconds).toLowerCase()}` : ' ';
timerText = excludeSucces ? timer : timerText;
const {
infoContainer,
infoTextStyle,
statusIconStyle,
padding,
brandDanger,
} = this.getStyles();
if (cantEnterExclusion) {
return (
<CantEnterInclusionExclusionUI
infoMessage={formatMessage(i18n.couldNotEnterExclusionInfo)}
onPressExit={this.onPressCancelExclude}
appLayout={appLayout}
/>
);
}
return (
<View style={{
flex: 1,
}}>
{status === 'timed out' ?
<InfoBlock
text={formatMessage(i18n.noDeviceFoundMessageExclude)}
appLayout={appLayout}
infoContainer={infoContainer}
textStyle={infoTextStyle}
infoIconStyle={statusIconStyle}/>
:
<View style={{
flex: 1,
}}>
<ZWaveIncludeExcludeUI
progress={progress}
status={status}
timer={timerText}
intl={intl}
appLayout={appLayout}
action={'exclude'}
showThrobber={showThrobber}
actionsDescription={exclusionDescription}/>
<TouchableButton
text={excludeSucces ? formatMessage(i18n.defaultPositiveText) : formatMessage(i18n.defaultNegativeText)}
onPress={excludeSucces ? this.onPressOkay : this.onPressCancelExclude}
style={{
marginTop: padding / 2,
}}/>
</View>
}
{status === 'timed out' && (
<View style={{
flex: 1,
}}>
<TouchableButton
text={formatMessage(i18n.tryAgain)}
onPress={this.onPressTryAgain}
style={{
backgroundColor: brandDanger,
marginTop: padding / 2,
}}/>
<TouchableButton
text={formatMessage(i18n.exit)}
onPress={this.onPressCancelExclude}
style={{
marginTop: padding,
}}/>
</View>
)}
</View>
);
}
getStyles(): Object {
const { appLayout } = this.props;
const { height, width } = appLayout;
const isPortrait = height > width;
const deviceWidth = isPortrait ? width : height;
const {
paddingFactor,
brandDanger,
fontSizeFactorFour,
fontSizeFactorNine,
} = Theme.Core;
const padding = deviceWidth * paddingFactor;
const innerPadding = 5 + padding;
const infoTextFontSize = deviceWidth * fontSizeFactorFour;
return {
brandDanger,
padding,
infoContainer: {
margin: padding,
padding: innerPadding,
},
statusIconStyle: {
fontSize: deviceWidth * fontSizeFactorNine,
},
infoTextStyle: {
flex: 1,
fontSize: infoTextFontSize,
flexWrap: 'wrap',
marginLeft: innerPadding,
},
};
}
}
function mapDispatchToProps(dispatch: Function): Object {
return {
dispatch,
};
}
export default (connect(null, mapDispatchToProps)(ExcludeDevice): Object);
|
src/helpers/app/getHead.js
|
expdevelop/d812
|
import React from 'react'
import apple57 from 'images/favicon/apple-icon-57x57.png'
import apple60 from 'images/favicon/apple-icon-60x60.png'
import apple72 from 'images/favicon/apple-icon-72x72.png'
import apple76 from 'images/favicon/apple-icon-76x76.png'
import apple114 from 'images/favicon/apple-icon-114x114.png'
import apple120 from 'images/favicon/apple-icon-120x120.png'
import apple144 from 'images/favicon/apple-icon-144x144.png'
import apple152 from 'images/favicon/apple-icon-152x152.png'
import apple180 from 'images/favicon/apple-icon-180x180.png'
import fav192 from 'images/favicon/android-icon-192x192.png'
import fav32 from 'images/favicon/favicon-32x32.png'
import fav96 from 'images/favicon/favicon-96x96.png'
import fav16 from 'images/favicon/favicon-16x16.png'
import msIcon from 'images/favicon/ms-icon-144x144.png'
//import manifest from 'images/favicon/manifest.json'
const icons = {
apple57,
apple60,
apple72,
apple76,
apple114,
apple120,
apple144,
apple152,
apple180,
fav192,
fav32,
fav96,
fav16
};
let i = 0;
export const link = (()=>{
let data = [];
for (let prop in icons) {
const value = icons[prop];
const num = parseInt(prop.replace(new RegExp('[A-z]', 'gi'), ''));
data.push(
<link key={i++} href={value} sizes={num + 'x' + num}
rel={prop.indexOf('apple') !== -1 ? 'apple-touch-icon' : 'icon'}/>
);
}
// TODO: set manifest as link.
// data.push({
// rel: 'manifest',
// href: manifest
// });
return data
})();
export const meta = [
<meta key={++i} name="msapplication-TileColor" content="#fff"/>,
<meta key={++i} name="msapplication-TileImage" content={msIcon}/>,
<meta key={++i} name="theme-color" content="#fff"/>,
<meta key={++i} name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'/>
];
export default [
...link,
...meta
]
|
react_native_frontend/src/components/goalHelpers/indiGoal.js
|
CUNYTech/BudgetApp
|
import React, { Component } from 'react';
import {
Alert, View, Text, StyleSheet, TouchableOpacity, TextInput, LayoutAnimation, Platform, Dimensions } from 'react-native';
import { Actions } from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/FontAwesome';
import * as Progress from 'react-native-progress';
import dismissKeyboard from 'react-native-dismiss-keyboard';
const { height, width } = Dimensions.get('window');
const CustomLayoutAnimation = {
duration: 200,
create: {
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.opacity,
},
update: {
type: LayoutAnimation.Types.easeInEaseOut,
},
};
const theme = {
accent: '#ffc107',
bg: '#212121',
text: 'white',
font: 'OpenSans',
};
export default class IndiGoal extends Component {
constructor() {
super();
this.state = {
newProgressChange: '',
modalOffset: width * 0.5,
errors: 'transparent',
};
}
async _editGoals() {
if (!Number.isInteger(+this.state.newProgressChange)) {
this.setState({
errors: 'red',
});
return;
}
try {
const ref = this.props.Firebase.database().ref();
const user = this.props.Firebase.auth().currentUser;
const uid = user.uid;
const _this = this;
// const userTotalExpensesRef = ref.child('userReadable/userTotalExpenses').child(uid);
const userGoalsProgressRef = ref.child(`userReadable/userGoals/${uid}/`);
const newProgressChange = +this.state.newProgressChange;
const newProgressTotal = +this.state.newProgressChange + +this.props.element.progress;
this.setState({ progress: newProgressTotal });
if (newProgressTotal > 0) {
userGoalsProgressRef.child(this.props.element.goalKey).update({ progress: `${newProgressTotal}` });
userGoalsProgressRef.once('value').then((snap) => {
const updatedValue = snap.val().progress;
return updatedValue;
}).then((value) => {
this.setState({ progress: value });
});
}
} catch (e) {
}
this.props.updateGoals();
this.toggleEditGoal();
}
deleteGoal() {
const ref = this.props.Firebase.database().ref();
const uid = this.props.Firebase.auth().currentUser.uid;
const userGoalsRef = ref.child(`userReadable/userGoals/${uid}`);
userGoalsRef.child(this.props.element.goalKey).remove();
this.props.updateGoals();
}
toggleEditGoal() {
LayoutAnimation.configureNext(CustomLayoutAnimation);
dismissKeyboard();
if (this.state.modalOffset === 0) {
this.setState({
modalOffset: width * 0.5,
errors: 'transparent',
});
} else {
this.setState({
modalOffset: 0,
errors: 'transparent',
});
}
}
render() {
return (
<View style={{ width: width * 0.9, height: width * 0.4, padding: 10, backgroundColor: 'black', borderWidth: 0.5, borderColor: 'black', borderRadius: 10, margin: 10, overflow: 'hidden' }}>
<Text style={{ backgroundColor: 'transparent', textAlign: 'center', fontSize: 17, color: '#bdbdbd', fontFamily: 'OpenSans' }}>
{ this.props.element.goal }
</Text>
<TouchableOpacity style={{ position: 'absolute', right: 0 }} activeOpacity={0.7} onPress={this.deleteGoal.bind(this)}>
<Icon name="trash" size={20} color="rgba(255,255,255,.3)" style={{ margin: 3, backgroundColor: 'transparent', overflow: 'hidden' }} />
</TouchableOpacity>
<View style={styles.goal} >
<Progress.Bar
color="#ffc107"
height={2}
progress={+this.props.element.progress / +this.props.element.amount}
width={273}
borderColor={'black'}
unfilledColor={'#424242'}
/>
</View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<Text style={{ color: '#bdbdbd' }}>${this.props.element.progress}</Text>
<Text style={{ color: '#bdbdbd' }}>${this.props.element.amount}</Text>
</View>
<TouchableOpacity style={{ alignItems: 'center' }} activeOpacity={0.7} onPress={this.toggleEditGoal.bind(this)}>
<Icon name="plus-square-o" size={30} color="#ffc107" style={{ backgroundColor: 'transparent', overflow: 'hidden' }} />
<Text style={{ color: 'white', fontSize: 10, fontFamily: 'OpenSans' }}>add to goal</Text>
</TouchableOpacity>
<View style={[styles.modal, { top: this.state.modalOffset }]}>
<View style={{ justifyContent: 'center', paddingBottom: 10, alignItems: 'center' }}>
<Text style={{ color: 'white', fontSize: 15, fontFamily: 'OpenSans', padding: 10 }}>
Add to goal
</Text>
<TextInput
keyboardType="numeric"
style={{ height: 40, width: 100, backgroundColor: 'rgba(255,255,255,.6)', borderWidth: 1, textAlign: 'center' }}
placeholder="$"
onChangeText={newProgressChange => this.setState({ newProgressChange })}
value={this.state.newProgressChange}
/>
</View>
<TouchableOpacity
onPress={this._editGoals.bind(this)}
style={styles.addExpenseButton}
>
<Text style={{ textAlign: 'center', color: 'white', fontFamily: 'OpenSans', fontSize: 12 }}>
UPDATE
</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.toggleEditGoal.bind(this)} style={{ position: 'absolute', top: 10, right: 10 }}>
<Text style={{ fontFamily: 'OpenSans', fontSize: 12, color: 'white' }}>
Cancel
</Text>
</TouchableOpacity>
<Text style={{ position: 'absolute', top: 10, left: 10, fontFamily: 'OpenSans', fontSize: 12, color: this.state.errors }}>
invalid input
</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
},
header: {
flex: 0,
flexDirection: 'row',
height: 60,
backgroundColor: '#424242',
justifyContent: 'space-around',
alignItems: 'center',
borderBottomWidth: 1,
borderColor: '#424242',
},
addExpense: {
position: 'absolute',
bottom: 25,
right: 20,
},
addExpenseButton: {
padding: 10,
paddingRight: 50,
paddingLeft: 50,
backgroundColor: 'black',
borderRadius: 10,
borderWidth: 0.5,
borderColor: theme.accent,
overflow: 'hidden',
justifyContent: 'center',
},
section: {
flex: 1,
borderColor: '#e0e0e0',
marginTop: 2,
borderBottomWidth: 1,
backgroundColor: 'white',
},
goal: {
height: 10,
marginRight: 20,
marginLeft: 20,
marginTop: 30,
borderRadius: 0,
alignItems: 'center',
justifyContent: 'center',
},
modal: {
position: 'absolute',
bottom: 0,
right: 0,
left: 0,
backgroundColor: 'rgba(0,0,0,.7)',
justifyContent: 'center',
alignItems: 'center',
},
});
|
website/src/components/EmergencyStopButton.js
|
DTU-R3/ArloBot
|
import React from 'react';
import './EmergencyStopButton.css';
const EmergencyStopButton = (props) => {
const btnClass = props.haltRobot
? 'btn btn-success btn-tight'
: 'btn btn-danger btn-tight';
const btnText = props.haltRobot ? 'Resume' : 'Emergency STOP';
const signal = props.haltRobot ? 'unHaltRobot' : 'haltRobot';
return (
<span className="emergency-button">
<button
type="button"
className={btnClass}
onClick={() => props.sendDataToRobot(signal)}
>
{btnText}
</button>
</span>
);
};
export default EmergencyStopButton;
|
src/components/SearchField/SearchField.js
|
aos2006/tesDeploy
|
import React from 'react';
import { Input } from 'react-toolbox';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './SearchField.css';
import Clear from '-!babel-loader!svg-react-loader!./icons/clear.svg?name=Clear';
import theme from './theme.css';
export const SearchField = props => (
<div>
<Input
type="search"
theme={theme}
value="Loui Vetton"
icon={<Clear className={theme.clear} />}
/>
<span className={s.hint}>Введите продукт который вы хотите найти</span>
</div>
);
export default withStyles(s, theme)(SearchField);
|
docs/src/app/components/pages/components/DatePicker/Page.js
|
pancho111203/material-ui
|
import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import datePickerReadmeText from './README';
import DatePickerExampleSimple from './ExampleSimple';
import datePickerExampleSimpleCode from '!raw!./ExampleSimple';
import DatePickerExampleInline from './ExampleInline';
import datePickerExampleInlineCode from '!raw!./ExampleInline';
import DatePickerExampleToggle from './ExampleToggle';
import datePickerExampleToggleCode from '!raw!./ExampleToggle';
import DatePickerExampleControlled from './ExampleControlled';
import datePickerExampleControlledCode from '!raw!./ExampleControlled';
import DatePickerExampleDisableDates from './ExampleDisableDates';
import datePickerExampleDisableDatesCode from '!raw!./ExampleDisableDates';
import DatePickerExampleInternational from './ExampleInternational';
import datePickerExampleInternationalCode from '!raw!./ExampleInternational';
import datePickerCode from '!raw!material-ui/DatePicker/DatePicker';
const DatePickerPage = () => (
<div>
<Title render={(previousTitle) => `Date Picker - ${previousTitle}`} />
<MarkdownElement text={datePickerReadmeText} />
<CodeExample
title="Simple examples"
code={datePickerExampleSimpleCode}
>
<DatePickerExampleSimple />
</CodeExample>
<CodeExample
title="Inline examples"
code={datePickerExampleInlineCode}
>
<DatePickerExampleInline />
</CodeExample>
<CodeExample
title="Ranged example"
code={datePickerExampleToggleCode}
>
<DatePickerExampleToggle />
</CodeExample>
<CodeExample
title="Controlled example"
code={datePickerExampleControlledCode}
>
<DatePickerExampleControlled />
</CodeExample>
<CodeExample
title="Disabled dates example"
code={datePickerExampleDisableDatesCode}
>
<DatePickerExampleDisableDates />
</CodeExample>
<CodeExample
title="Localised example"
code={datePickerExampleInternationalCode}
>
<DatePickerExampleInternational />
</CodeExample>
<PropTypeDescription code={datePickerCode} />
</div>
);
export default DatePickerPage;
|
actor-apps/app-web/src/app/components/dialog/messages/Document.react.js
|
liruqi/actor-platform-v0.9
|
import React from 'react';
import classnames from 'classnames';
class Document extends React.Component {
static propTypes = {
content: React.PropTypes.object.isRequired,
className: React.PropTypes.string
};
constructor(props) {
super(props);
}
render() {
const { content, className } = this.props;
const documentClassName = classnames(className, 'row');
let availableActions;
if (content.isUploading === true) {
availableActions = <span>Loading...</span>;
} else {
availableActions = <a href={content.fileUrl}>Download</a>;
}
return (
<div className={documentClassName}>
<div className="document row">
<div className="document__icon">
<i className="material-icons">attach_file</i>
</div>
<div className="col-xs">
<span className="document__filename">{content.fileName}</span>
<div className="document__meta">
<span className="document__meta__size">{content.fileSize}</span>
<span className="document__meta__ext">{content.fileExtension}</span>
</div>
<div className="document__actions">
{availableActions}
</div>
</div>
</div>
<div className="col-xs"></div>
</div>
);
}
}
export default Document;
|
test/NavDropdownSpec.js
|
Terminux/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import ReactDOM from 'react-dom';
import MenuItem from '../src/MenuItem';
import NavDropdown from '../src/NavDropdown';
describe('NavDropdown', () => {
it('Should render li when in nav', () => {
const instance = ReactTestUtils.renderIntoDocument(
<NavDropdown title="Title" className="test-class" id='nav-test'>
<MenuItem eventKey="1">MenuItem 1 content</MenuItem>
<MenuItem eventKey="2">MenuItem 2 content</MenuItem>
</NavDropdown>
);
let li = ReactDOM.findDOMNode(instance);
let button = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'dropdown-toggle');
assert.equal(li.nodeName, 'LI');
assert.ok(li.className.match(/\bdropdown\b/));
assert.ok(li.className.match(/\btest-class\b/));
assert.equal(button.nodeName, 'A');
assert.equal(button.innerText.trim(), 'Title');
});
it('is open with explicit prop', () => {
class OpenProp extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false
};
}
render() {
return (
<div>
<button className='outer-button'
onClick={() => this.setState({open: !this.state.open})}>
Outer button
</button>
<NavDropdown
open={this.state.open}
onToggle={() => {}}
title='Prop open control'
id='test-id'>
<MenuItem eventKey='1'>Item 1</MenuItem>
</NavDropdown>
</div>
);
}
}
const instance = ReactTestUtils.renderIntoDocument(<OpenProp />);
const outerToggle = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'outer-button');
const dropdownNode = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'dropdown');
dropdownNode.className.should.not.match(/\bopen\b/);
ReactTestUtils.Simulate.click(outerToggle);
dropdownNode.className.should.match(/\bopen\b/);
ReactTestUtils.Simulate.click(outerToggle);
dropdownNode.className.should.not.match(/\bopen\b/);
});
});
|
services/web-client/src/routes/routes.js
|
andykais/telebum2
|
import React from 'react'
import { Route, Switch } from 'react-router-dom'
import App from 'containers/App'
import Home from 'containers/HomePage'
import NotFound from 'containers/NotFoundPage'
const Routes = (props) =>
<App>
<Switch>
<Route path='/' exact component={Home}/>
<Route path='/test' render={() => <div>test</div>}/>
<Route component={NotFound}/>
</Switch>
</App>
export default Routes
|
src/svg-icons/image/wb-iridescent.js
|
owencm/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageWbIridescent = (props) => (
<SvgIcon {...props}>
<path d="M5 14.5h14v-6H5v6zM11 .55V3.5h2V.55h-2zm8.04 2.5l-1.79 1.79 1.41 1.41 1.8-1.79-1.42-1.41zM13 22.45V19.5h-2v2.95h2zm7.45-3.91l-1.8-1.79-1.41 1.41 1.79 1.8 1.42-1.42zM3.55 4.46l1.79 1.79 1.41-1.41-1.79-1.79-1.41 1.41zm1.41 15.49l1.79-1.8-1.41-1.41-1.79 1.79 1.41 1.42z"/>
</SvgIcon>
);
ImageWbIridescent = pure(ImageWbIridescent);
ImageWbIridescent.displayName = 'ImageWbIridescent';
ImageWbIridescent.muiName = 'SvgIcon';
export default ImageWbIridescent;
|
src/components/searchbox/searchbox.js
|
thinktopography/reframe
|
import PropTypes from 'prop-types'
import React from 'react'
import _ from 'lodash'
class Searchbox extends React.Component {
static propTypes = {
active: PropTypes.bool,
icon: PropTypes.string,
prompt: PropTypes.string,
q: PropTypes.string,
onAbort: PropTypes.func,
onBegin: PropTypes.func,
onChange: PropTypes.func,
onEnd: PropTypes.func,
onIcon: PropTypes.func,
onType: PropTypes.func
}
static defaultProps = {
prompt: 'Search...',
q: '',
onChange: (value) => {}
}
_handleChange = _.throttle(this._handleChange, 500)
render() {
const { icon, q } = this.props
return (
<div className={ this._getClass() }>
<div className="reframe-searchbox-container">
{ icon &&
<div className="reframe-searchbox-extra" onClick={ this._handleIcon.bind(this) }>
<i className={ `fa fa-fw fa-${icon}` } />
</div>
}
<div className="reframe-searchbox-input">
<div className="reframe-searchbox-icon">
<i className="fa fa-search" />
</div>
<div className="reframe-searchbox-field">
<input { ...this._getInput() } />
</div>
{ q.length > 0 &&
<div className="reframe-searchbox-remove-icon" onClick={ this._handleAbort.bind(this) }>
<i className="fa fa-times-circle" />
</div>
}
</div>
</div>
</div>
)
}
_getClass() {
const classes = ['reframe-searchbox']
if(this.props.active) classes.push('active')
return classes.join(' ')
}
_getInput() {
const { prompt, q } = this.props
return {
type: 'text',
placeholder: prompt,
value: q,
onFocus: this._handleBegin.bind(this),
onBlur: this._handleEnd.bind(this),
onChange: this._handleType.bind(this)
}
}
componentDidUpdate(prevProps) {
const { q } = this.props
if(q !== prevProps.q) this._handleChange(q)
}
_handleIcon() {
this.props.onIcon()
}
_handleBegin() {
this.props.onBegin()
}
_handleChange(q) {
this.props.onChange(q)
}
_handleEnd() {
this.props.onEnd()
}
_handleType(e) {
const { onType } = this.props
onType(e.target.value)
}
_handleAbort() {
this.props.onAbort()
}
}
export default Searchbox
|
app/packs/src/components/elements/ElementField.js
|
ComPlat/chemotion_ELN
|
/* eslint-disable react/forbid-prop-types */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Popover, Col, Checkbox, Panel, Form, ButtonGroup, OverlayTrigger, FormGroup, FormControl, ControlLabel, InputGroup } from 'react-bootstrap';
import Select from 'react-select';
import uuid from 'uuid';
import { ButtonTooltip, genUnitSup } from '../../admin/generic/Utils';
import GroupFields from './GroupFields';
import TextFormula from '../generic/TextFormula';
import TableDef from '../generic/TableDef';
const BaseFieldTypes = [
{ value: 'integer', name: 'integer', label: 'Integer' },
{ value: 'text', name: 'text', label: 'Text' },
{ value: 'textarea', name: 'textarea', label: 'Text area' },
{ value: 'select', name: 'select', label: 'Select' },
{ value: 'checkbox', name: 'checkbox', label: 'Checkbox' },
{ value: 'system-defined', name: 'system-defined', label: 'System-Defined' },
{ value: 'formula-field', name: 'formula-field', label: 'Formula-Field' },
];
const ElementFieldTypes = [
{ value: 'drag_molecule', name: 'drag_molecule', label: 'Drag Molecule' },
{ value: 'drag_sample', name: 'drag_sample', label: 'Drag Sample' },
{ value: 'input-group', name: 'input-group', label: 'Input Group' },
{ value: 'text-formula', name: 'text-formula', label: 'Text-Formula' },
{ value: 'table', name: 'table', label: 'Table' },
{ value: 'upload', name: 'upload', label: 'Upload' },
];
const SegmentFieldTypes = [
{ value: 'input-group', name: 'input-group', label: 'Input Group' },
{ value: 'text-formula', name: 'text-formula', label: 'Text-Formula' },
{ value: 'drag_molecule', name: 'drag_molecule', label: 'Drag Molecule' },
{ value: 'table', name: 'table', label: 'Table' },
{ value: 'upload', name: 'upload', label: 'Upload' },
];
class ElementField extends Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleDrop = this.handleDrop.bind(this);
this.handelDelete = this.handelDelete.bind(this);
this.handleMove = this.handleMove.bind(this);
this.handleAddDummy = this.handleAddDummy.bind(this);
this.handleCond = this.handleCond.bind(this);
this.updSubField = this.updSubField.bind(this);
}
updSubField(layerKey, field, cb) {
this.props.onFieldSubFieldChange(layerKey, field, cb);
}
handleChange(e, orig, fe, lk, fc, tp) {
if ((tp === 'select' || tp === 'system-defined') && e === null) { return; }
this.props.onChange(e, orig, fe, lk, fc, tp);
}
handleMove(element) {
const { l, f, isUp } = element;
this.props.onMove(l, f, isUp);
}
handleAddDummy(element) {
this.props.onDummyAdd(element);
}
handleCond(field, lk) {
this.props.onShowFieldCond(field, lk);
//this.setState({ showFieldRestriction: true, element: element });
}
handelDelete(delStr, delKey, delRoot) {
this.props.onDelete(delStr, delKey, delRoot);
}
handleDrop(e) {
this.props.onDrop(e);
}
availableUnits(val) {
const { unitsSystem } = this.props;
const us = (unitsSystem.fields || []).find(e => e.field === val);
if (us === undefined) return null;
const tbl = us.units.map(e => (<div key={uuid.v4()}>{genUnitSup(e.label)}<br /></div>));
const popover = (
<Popover id="popover-positioned-scrolling-left"><b><u>available units</u></b><br />{tbl}</Popover>
);
return (
<OverlayTrigger animation placement="top" root trigger={['hover', 'focus', 'click']} overlay={popover}>
<Button bsSize="xs"><i className="fa fa-table" aria-hidden="true" /></Button>
</OverlayTrigger>
);
}
renderDeleteButton(delStr, delKey, delRoot) {
const msg = `remove this field: [${delKey}] from layer [${delRoot}] `;
const popover = (
<Popover id="popover-positioned-scrolling-left">
{msg} <br />
<div className="btn-toolbar">
<Button bsSize="xsmall" bsStyle="danger" onClick={() => this.handelDelete(delStr, delKey, delRoot)}>
Yes
</Button><span> </span>
<Button bsSize="xsmall" bsStyle="warning" onClick={this.handleClick} >
No
</Button>
</div>
</Popover>
);
return (
<OverlayTrigger animation placement="top" root trigger="focus" overlay={popover}>
<Button bsSize="xs" ><i className="fa fa-trash-o" aria-hidden="true" /></Button>
</OverlayTrigger>
);
}
renderDummyFieldGroup(f) {
return (
<FormGroup controlId={`frmCtrlFid_${this.props.layerKey}_${f.field}`}>
<Col componentClass={ControlLabel} sm={3}>{`(${f.type})`}</Col>
<Col sm={9}><FormControl type="text" name={`f_${f.field}`} defaultValue={`${f.type}, an invisible entry (${f.field})`} disabled /></Col>
</FormGroup>
);
}
renderTextFieldGroup(f, label, field) {
return (
<FormGroup controlId={`frmCtrlFid_${this.props.layerKey}_${f.field}_${field}`}>
<Col componentClass={ControlLabel} sm={3}>{label}</Col>
<Col sm={9}>
<FormControl
type="text"
name={`f_${field}`}
defaultValue={f[field]}
disabled={field === 'field'}
onChange={event => this.handleChange(event, f[field], f.field, this.props.layerKey, field, 'text')}
/>
</Col>
</FormGroup>
);
}
renderComponent() {
const { unitsSystem, layerKey, genericType, allLayers } = this.props;
const unitConfig = (unitsSystem.fields || []).map(_c =>
({ value: _c.field, name: _c.label, label: _c.label }));
let typeOpts = BaseFieldTypes;
switch (genericType) {
case 'Element':
typeOpts = BaseFieldTypes.concat(ElementFieldTypes);
break;
case 'Segment':
typeOpts = BaseFieldTypes.concat(SegmentFieldTypes);
break;
default:
typeOpts = BaseFieldTypes;
}
typeOpts.sort((a, b) => a.value.localeCompare(b.value));
const f = this.props.field;
const hasCond = (f && f.cond_fields && f.cond_fields.length > 0) || false;
const btnCond = hasCond ?
(<ButtonTooltip tip="Restriction Setting" fnClick={() => this.handleCond(f, layerKey)} bs="warning" element={{ l: layerKey, f: null }} fa="fa fa-cogs" place="top" size="sm" />) :
(<ButtonTooltip tip="Restriction Setting" fnClick={() => this.handleCond(f, layerKey)} element={{ l: layerKey, f: null }} fa="fa fa-cogs" place="top" size="sm" />)
const formulaField = (f.type === 'formula-field') ? (
<FormGroup controlId="formControlFieldType">
<Col componentClass={ControlLabel} sm={3}>Formula</Col>
<Col sm={9}>
<div style={{ display: 'flex' }}>
<span style={{ width: '100%' }}>
<FormControl
type="text"
name="f_label"
defaultValue={f.formula}
onChange={event => this.handleChange(event, f.label, f.field, this.props.layerKey, 'formula', 'text')}
/>
</span>
</div>
</Col>
</FormGroup>)
: (<div />);
const selectOptions = (f.type === 'select' || f.type === 'system-defined') ? (
<FormGroup controlId="formControlFieldType">
<Col componentClass={ControlLabel} sm={3}>{f.type === 'select' ? 'Options' : <span />}</Col>
<Col sm={9}>
<div style={{ display: 'flex' }}>
<span style={{ width: '100%' }}>
<Select
className="drop-up"
name={f.field}
multi={false}
options={f.type === 'select' ? this.props.select_options : unitConfig}
value={f.option_layers || ''}
onChange={event => this.handleChange(event, f.option_layers, f.field, layerKey, 'option_layers', f.type)}
/>
</span>
{f.type === 'select' ? null : this.availableUnits(f.option_layers)}
</div>
</Col>
</FormGroup>)
: (<div />);
const skipRequired = ['Segment', 'Dataset'].includes(genericType) || !['integer', 'text'].includes(f.type) ? { display: 'none' } : {};
const groupOptions = ['input-group'].includes(f.type) ? (
<FormGroup controlId={`frmCtrlFid_${layerKey}_${f.field}_sub_fields`}>
<Col componentClass={ControlLabel} sm={3}>{' '}</Col>
<Col sm={9}>
<GroupFields layerKey={layerKey} field={f} updSub={this.updSubField} unitsFields={(unitsSystem.fields || [])} />
</Col>
</FormGroup>
) : null;
const tableOptions = ['table'].includes(f.type) ? (
<FormGroup controlId={`frmCtrlFid_${layerKey}_${f.field}_sub_fields`}>
<Col componentClass={ControlLabel} sm={3}>{' '}</Col>
<Col sm={9}>
<TableDef genericType={genericType} layerKey={layerKey} field={f} updSub={this.updSubField} unitsFields={(unitsSystem.fields || [])} />
<InputGroup>
<InputGroup.Addon>Tables per row</InputGroup.Addon>
<FormControl componentClass="select" defaultValue={f.cols || 1} onChange={event => this.handleChange(event, f.cols, f.field, layerKey, 'cols', f.cols)} >
<option value={1}>1</option>
<option value={2}>2</option>
</FormControl>
</InputGroup>
</Col>
</FormGroup>
) : null;
const textFormula = ['text-formula'].includes(f.type) ? (
<FormGroup controlId={`frmCtrlFid_${layerKey}_${f.field}_text_sub_fields`}>
<Col componentClass={ControlLabel} sm={3}>{' '}</Col>
<Col sm={9}>
<TextFormula layerKey={layerKey} field={f} updSub={this.updSubField} allLayers={allLayers} />
</Col>
</FormGroup>
) : null;
return (
<div>
<Panel>
<Panel.Heading className="template_panel_heading">
<Panel.Title toggle>
{this.props.position}
{['dummy'].includes(f.type) ? '(dummy field)' : f.field}
</Panel.Title>
<ButtonGroup bsSize="xsmall">
{btnCond}
<ButtonTooltip tip="Move Up" fnClick={this.handleMove} element={{ l: layerKey, f: f.field, isUp: true }} fa="fa-arrow-up" place="top" disabled={this.props.position === 1} />
<ButtonTooltip tip="Move Down" fnClick={this.handleMove} element={{ l: layerKey, f: f.field, isUp: false }} fa="fa-arrow-down" place="top" />
{this.renderDeleteButton('Field', f.field, layerKey)}
<ButtonTooltip tip="Add Dummy field" fnClick={this.handleAddDummy} element={{ l: layerKey, f: f.field }} fa="fa fa-plus-circle" place="top" />
</ButtonGroup>
</Panel.Heading>
<Panel.Collapse>
<Panel.Body>
<Form horizontal className="default_style">
{['dummy'].includes(f.type) ? this.renderDummyFieldGroup(f) : null}
{!['dummy'].includes(f.type) ? this.renderTextFieldGroup(f, 'Field Name', 'field') : null}
{!['dummy'].includes(f.type) ? this.renderTextFieldGroup(f, 'Display Name', 'label') : null}
{!['dummy'].includes(f.type) ? this.renderTextFieldGroup(f, 'Hover Info', 'description') : null}
{
['dummy'].includes(f.type) ? null : (
<FormGroup controlId={`frmCtrlFid_${layerKey}_${f.field}_type`}>
<Col componentClass={ControlLabel} sm={3}>Type</Col>
<Col sm={9}>
<div style={{ display: 'flex' }}>
<span style={{ width: '100%' }}>
<Select
className="drop-up"
name={f.field}
multi={false}
options={typeOpts}
value={f.type}
onChange={event => this.handleChange(event, f.type, f.field, layerKey, 'type', 'select')}
/>
</span>
</div>
</Col>
</FormGroup>)
}
{ groupOptions }
{ tableOptions }
{ selectOptions }
{ formulaField }
{ textFormula }
{
['dummy'].includes(f.type) ? null : (
<FormGroup controlId={`frmCtrlFid_${layerKey}_${f.field}_required`} style={skipRequired}>
<Col componentClass={ControlLabel} sm={3}>
Required
</Col>
<Col sm={9}>
<Checkbox
checked={f.required}
onChange={event => this.handleChange(event, f.required, f.field, layerKey, 'required', 'checkbox')}
/>
</Col>
</FormGroup>)
}
{['integer', 'text'].includes(f.type) ? this.renderTextFieldGroup(f, 'Placeholder', 'placeholder') : null}
</Form>
</Panel.Body>
</Panel.Collapse>
</Panel>
</div>
);
}
render() { return <Col md={12}>{this.renderComponent()}</Col>; }
}
ElementField.propTypes = {
genericType: PropTypes.string, // PropTypes.arrayOf(PropTypes.object),
layerKey: PropTypes.string.isRequired,
select_options: PropTypes.array.isRequired,
position: PropTypes.number.isRequired,
field: PropTypes.shape({
field: PropTypes.string,
type: PropTypes.string,
label: PropTypes.string,
}).isRequired,
onDrop: PropTypes.func.isRequired,
onMove: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
onChange: PropTypes.func.isRequired,
unitsSystem: PropTypes.object,
onFieldSubFieldChange: PropTypes.func.isRequired,
onDummyAdd: PropTypes.func.isRequired,
onShowFieldCond: PropTypes.func.isRequired,
};
ElementField.defaultProps = { genericType: 'Element', unitsSystem: [] };
export { ElementField, ElementFieldTypes };
|
src/svg-icons/image/looks-4.js
|
w01fgang/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageLooks4 = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4 14h-2v-4H9V7h2v4h2V7h2v10z"/>
</SvgIcon>
);
ImageLooks4 = pure(ImageLooks4);
ImageLooks4.displayName = 'ImageLooks4';
ImageLooks4.muiName = 'SvgIcon';
export default ImageLooks4;
|
test/TableSpec.js
|
Sipree/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import ReactDOM from 'react-dom';
import Table from '../src/Table';
describe('Table', () => {
it('Should be a table', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Table />
);
assert.equal(ReactDOM.findDOMNode(instance).nodeName, 'TABLE');
assert.ok(ReactDOM.findDOMNode(instance).className.match(/\btable\b/));
});
it('Should have correct class when striped', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Table striped />
);
assert.ok(ReactDOM.findDOMNode(instance).className.match(/\btable-striped\b/));
});
it('Should have correct class when hover', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Table hover />
);
assert.ok(ReactDOM.findDOMNode(instance).className.match(/\btable-hover\b/));
});
it('Should have correct class when bordered', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Table bordered />
);
assert.ok(ReactDOM.findDOMNode(instance).className.match(/\btable-bordered\b/));
});
it('Should have correct class when condensed', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Table condensed />
);
assert.ok(ReactDOM.findDOMNode(instance).className.match(/\btable-condensed\b/));
});
it('Should have responsive wrapper', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Table responsive />
);
assert.ok(ReactDOM.findDOMNode(instance).className.match(/\btable-responsive\b/));
assert.ok(ReactDOM.findDOMNode(instance).firstChild.className.match(/\btable\b/));
});
});
|
news/components/BannerWide.js
|
HKuz/FreeCodeCamp
|
import React from 'react';
const propTypes = {};
function BannerWide() {
return (
<svg
version='1.0'
viewBox='0 0 1024 555'
xmlns='http://www.w3.org/2000/svg'
>
<path
d={
'M0 277.5V555h1024V0H0v277.5zm368.5-144.9c1.3.8 2.8 2.9 3.4 4.6 1.' +
'6 4.6-.6 8.3-14.2 22.6-14.3 15.2-22.8 26.8-30.1 41.1C315.4 225 31' +
'0 248 310 277c0 31.9 5.4 56.7 18 82.5 7.5 15.4 15.7 26.9 29.9 41.' +
'8 11.8 12.5 15.7 18.6 14.5 23.2-.8 3.4-5.9 7.5-9.3 7.5-8.3 0-21.5' +
'-11.3-36.7-31.6-19.9-26.4-30.5-51.1-36.6-85.1-2-11.2-2.3-16.1-2.2' +
'-38.3 0-23.9.1-26.3 2.6-38.1 6.6-30.6 18.8-55.7 39.6-81.6 17.6-21' +
'.7 30.5-30.1 38.7-24.7zm284 .3c6.4 2.9 14.5 10.2 23.6 21.1 28.7 3' +
'4.7 42.1 68.4 46 115.8 4.1 50.3-9.8 95.9-41.4 135.2-13.7 17.1-26.' +
'9 28-33.7 28-2.9 0-7.7-2.7-9-4.9-2.9-5.4-.7-9.2 13.7-24.3 16.8-17' +
'.6 26.7-31.9 34.4-49.7 19.4-45.2 17.8-104.8-4-149.6-8.5-17.4-16.8' +
'-28.8-34.3-47.2-4.9-5.1-9.3-10.4-9.8-11.8-2.2-5.7-.5-10.6 4.5-13.' +
'3 2.8-1.6 5.4-1.4 10 .7zm-172.9 16.5c16.2 4.3 31.4 16.9 38.3 31.7' +
' 3.8 8.2 4.8 11.8 9.1 34.4 2.5 12.8 4.8 18.7 8.4 21 4.5 3 11.4-.3' +
' 12.9-6.2.7-3.3-1-10-4.4-16.7-1.6-3.3-2.9-6.7-2.9-7.8 0-5.6 11.5 ' +
'2.1 23 15.3 16.1 18.7 21.7 36.1 20.8 64.4-.6 16.2-2.9 25-10 36.9-' +
'7.3 12.3-29.1 31.6-35.7 31.6-1.8 0-5.1-2.4-5.1-3.7 0-.3 2.8-3.5 6' +
'.1-7.1 12.2-13.3 16.8-22.2 17.6-34 .8-12.1-3.1-24.7-10-32-1.7-1.7' +
'-3.9-3.2-4.9-3.2-1.6 0-1.6.3-.4 3.8.7 2 1.7 5.6 2.1 8 .6 3.9.4 4.' +
'5-2.8 7.7-3.2 3.2-4 3.5-9.2 3.5-11.2 0-13-3.2-12.1-21 .6-11.8.5-1' +
'2.8-1.7-17.5-3.9-8.1-13.3-16.5-18.4-16.5-2.6 0-3.2 3.3-1 4.7 3.2 ' +
'2 4.7 5.8 4.7 12.3 0 10.1-3.2 15.5-15.2 26-15.3 13.4-18.8 19.4-18' +
'.8 32.4 0 17.4 8.4 32.8 20.8 38.3 3.9 1.7 5.2 2.8 5 4.1-.6 3-7 1.' +
'9-17.1-3-16.1-7.8-28-19-35.6-33.8-5.3-10.1-7.4-18.5-7.5-30-.1-15.' +
'9 3.8-25.3 24-57.6 17.8-28.6 22.1-39.2 21.2-53.1-.7-10.9-8.1-23.8' +
'-15.9-27.9-3-1.5-3.9-4.8-1.6-5.7 2.4-1 11.3-.6 16.3.7zm143.5 239.' +
'5c3.2 3.2 3.9 4.6 3.9 7.7 0 5.1-1.8 8.3-5.9 11.1l-3.4 2.3H512.8c-' +
'114.3 0-108 .3-112.7-5.6-1.4-1.8-2.1-4.1-2.1-7.2 0-3.8.5-5 3.9-8.' +
'3l3.9-3.9h213.4l3.9 3.9z'
}
fill='#006400'
/>
</svg>
);
}
BannerWide.displayName = 'BannerWide';
BannerWide.propTypes = propTypes;
export default BannerWide;
|
server/ViewModels/PointsHistory.js
|
demyanenko/hutel
|
import React from 'react';
import PropTypes from 'prop-types';
import update from 'immutability-helper';
import $ from 'jquery';
import moment from 'moment';
import Divider from 'material-ui/Divider';
import FontIcon from 'material-ui/FontIcon';
import IconButton from 'material-ui/IconButton';
import {List, ListItem} from 'material-ui/List';
import Subheader from 'material-ui/Subheader';
class PointsHistory extends React.Component {
constructor(props) {
super(props);
this.hiddenFields = ['id', 'tagId', 'date', 'submitTimestamp'];
this.state = {};
}
componentWillUnmount() {
for (var pointState of Object.values(this.state)) {
clearTimeout(pointState.timer);
}
}
humanizeDate(value) {
var date = moment(value);
var age = moment.duration(moment().diff(date));
if (age.days() < 0) {
return "In the future";
} else if (age.days() == 0) {
return "Today";
} else if (age.days() == 1) {
return "Yesterday";
} else {
return value + ", " + date.format('ddd') + ", " + age.days() + " days ago";
}
}
pointStateUpdater(pointId, spec) {
return (prevState) => {
var verb = prevState[pointId] ? "$merge" : "$set";
return update(prevState, {
[pointId]: {
[verb]: spec
}
});
};
}
deletePoint(pointId) {
console.log("Deleting point", pointId);
this.setState(this.pointStateUpdater(pointId, {loading: true}),
() => {
$.ajax({
url: "/api/points/" + pointId,
method: "DELETE",
success: () => {
this.setState(
this.pointStateUpdater(pointId, {loading: false}),
() => this.props.notifyPointsChanged());
},
error: (xhr, status, err) => {
console.error(err);
this.setState(this.pointStateUpdater(pointId, {loading: false}));
}
});
});
}
showDeleteButton(pointId) {
var pointState = this.state[pointId];
if (pointState) {
clearTimeout(pointState.timer);
}
var timer = setTimeout(() => {
this.setState(this.pointStateUpdater(pointId, {
deleteButtonVisible: false,
timer: null
}));
}, 3000);
this.setState(this.pointStateUpdater(pointId, {
deleteButtonVisible: true,
timer: timer
}));
}
click() {
console.log("click");
}
clickclick() {
console.log("clickclick");
}
render() {
const style = {
padding: 10,
display: "flex",
flexGrow: 1,
flexDirection: "column",
background: this.props.theme.historyBackground
};
if (this.props.points.length === 0) {
return (
<div style={style}>
<h2>History is empty</h2>
</div>
);
} else {
const dateStyle = {
color: this.props.theme.historyDateText
};
const listItemStyle = {
fontWeight: 500
};
var pointsByDate = this.props.points.reduce((acc, point) => {
(acc[point.date] = acc[point.date] || []).push(point);
return acc;
}, {});
var historyItems = Object.entries(pointsByDate)
.map(([date, points]) => {
var dateItems = points.map(point => {
var fieldTexts = Object.keys(point)
.filter(key => !this.hiddenFields.includes(key))
.map(key => `${key} ${point[key]}`);
var secondaryText = fieldTexts.join(" ");
var pointState = this.state[point.id];
var loading = pointState && pointState.loading;
var deleteButtonVisible = pointState && pointState.deleteButtonVisible;
const loadingIconStyle = {
fontSize: 20
};
var loadingIcon = loading
? <FontIcon
className="material-icons"
style={loadingIconStyle}
>
hourglass_empty
</FontIcon>
: undefined;
var deleteButton = !loading && deleteButtonVisible
? <IconButton
iconClassName="material-icons"
onClick={this.deletePoint.bind(this, point.id)}
>
delete
</IconButton>
: undefined;
return (
<ListItem
key={point.id}
primaryText={point.tagId.toUpperCase()}
secondaryText={secondaryText}
disabled={true}
style={listItemStyle}
onClick={this.showDeleteButton.bind(this, point.id)}
rightIconButton={deleteButton}
rightIcon={loadingIcon}
/>
);
});
return [
<Subheader key={date} style={dateStyle}>{this.humanizeDate(date)}</Subheader>,
...dateItems,
<Divider key={date + '-divider'} />
];
});
return (
<div style={style}>
<List>
{historyItems}
</List>
</div>
);
}
}
}
PointsHistory.propTypes = {
points: PropTypes.array.isRequired,
theme: PropTypes.object,
notifyPointsChanged: PropTypes.func
};
export default PointsHistory;
|
src/ui/app.js
|
steem/qwp-antd
|
import React from 'react'
import PropTypes from 'prop-types'
import pathToRegexp from 'path-to-regexp'
import { connect } from 'dva'
import { Layout, Loader } from 'components'
import { classnames, config, uri } from 'utils'
import { Helmet } from 'react-helmet'
import 'themes/index.less'
import './app.less'
import NProgress from 'nprogress'
import Error from './error'
import { l } from 'utils/localization'
import layout from 'utils/layout'
const { prefix } = config
const { Header, Bread, Footer, Sider, styles } = Layout
class AppContainer extends React.Component {
constructor (props) {
super(props)
}
componentDidMount () {
this.timerCheckWindow = setInterval(this.checkWindowResize.bind(this), 300)
}
componentWillUnmount () {
if (this.timerCheckWindow) {
clearInterval(this.timerCheckWindow)
this.timerCheckWindow = null
}
}
checkWindowResize () {
let node = this.container
if (!node) return
this.resizeState = layout.getResizeState(node, this.resizeState)
let h = layout.calcFullFillHeight(node)
let footer = layout.$('#footer')
let footerHeight = footer.length > 0 ? layout.$(footer).height() : 0
let content = this.content
let contentInner = this.contentInner
if (this.props.app && this.props.app.hasSimscroll) {
let contentScrollHeight = layout.scrollHeight(contentInner)
let contentHeight = layout.$(contentInner).height()
if (this.needUpdateScroll || this.resizeState.needResize || this.contentHeight !== contentHeight || this.contentScrollHeight !== contentScrollHeight) {
this.contentScrollHeight = contentScrollHeight
this.contentHeight = contentHeight
contentInner = layout.$('.content-inner')
if (this.contentScrollHeight + footerHeight < h) {
let newHeight = h - footerHeight - layout.getHeightWithoutContent(content) - layout.getHeightWithoutContent(node)
layout.$(content).height(newHeight)
if (contentInner.length > 0) {
contentInner.height(newHeight - layout.getHeightWithoutContent(contentInner))
}
} else {
layout.$(content).height('auto')
if (contentInner.length > 0) {
contentInner.height('auto')
}
}
}
if (!this.resizeState.needResize && !this.needUpdateScroll) return
this.needUpdateScroll = false
layout.addSimscroll(node, h, {'suppressScrollX': true})
this.hasSimscroll = true
} else if (this.props.app && !this.props.app.hasSimscroll) {
if (this.resizeState.needResize || this.needUpdateScroll || this.hasSimscroll) {
contentInner = layout.$('.content-inner')
let newHeight = h - footerHeight - layout.getHeightWithoutContent(content) - layout.getHeightWithoutContent(node)
layout.$(content).height(newHeight)
if (contentInner.length > 0) {
contentInner.height(newHeight - layout.getHeightWithoutContent(contentInner))
}
layout.setHeight(node, h)
}
if (this.hasSimscroll) {
layout.addSimscroll(node, h, {'suppressScrollX': true, 'scrollTop': 0})
layout.destrySimscroll(node)
this.hasSimscroll = false
}
if (this.needUpdateScroll) this.needUpdateScroll = false
}
}
render () {
let {
children,
dispatch,
app,
loading,
location
} = this.props
const { locationChangedTag, showFooter, localeChangedTag, appSettings, subSystems, hasHeader, notifications, hasBread, hasSiderBar, user, siderFold, darkTheme, isSideBarHidden, siderBarComponentType, menu, siderList } = app
let { pathname } = location
pathname = pathname.startsWith('/') ? pathname : `/${pathname}`
const { iconFontJS, iconFontCSS, logo } = config
const hasPermission = menu.filter((item) => item.path === pathname)
const href = window.location.href
if (this.lastHref !== href) {
this.needUpdateScroll = true
NProgress.start()
if (!loading.global) {
NProgress.done()
this.lastHref = href
}
}
const passwordModalProps = {
maskClosable: false,
appSettings,
wrapClassName: 'vertical-center-modal',
onOk (data) {
data.id = user.id
dispatch({
type: `app/changePassword`,
payload: data,
})
}
}
const headerProps = hasHeader ? {
siderBarComponentType,
menu,
user,
siderFold,
darkTheme,
isSideBarHidden,
hasSiderBar,
appSettings,
subSystems,
notifications,
passwordModalProps,
locationChangedTag,
logout () {
dispatch({ type: 'app/logout' })
},
switchSider () {
dispatch({ type: 'app/switchSider' })
},
} : ''
const siderProps = hasSiderBar ? {
siderBarComponentType,
siderList,
menu,
locationChangedTag,
siderFold,
darkTheme,
hasHeaderNav : appSettings.enableHeaderNav,
changeTheme () {
dispatch({ type: 'app/switchTheme' })
},
} : ''
const breadProps = hasBread ? {
menu,
} : ''
let errorProps
if (app.error) errorProps = { error: app.error }
if (!hasPermission) errorProps = {
error: `You don't have the permission, please contact your service administraotr`
}
let layoutClassName = classnames(styles.layout, { [styles.fold]: hasSiderBar && (isSideBarHidden ? false : siderFold) }, { [styles.sideBarHidden]: !hasSiderBar || isSideBarHidden })
const isLoading = loading.effects['app/init'] || loading.effects['app/navChanged']
return (
<div loc={localeChangedTag}>
<Helmet>
<title>{l('productName')}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href={logo} type="image/x-icon" />
{iconFontJS && <script src={iconFontJS}></script>}
{iconFontCSS && <link rel="stylesheet" href={iconFontCSS} />}
</Helmet>
{isLoading ? <Loader spinning={isLoading} /> : <div className={layoutClassName}>
{hasSiderBar && !isSideBarHidden ? <aside className={classnames(styles.sider, { [styles.light]: !darkTheme })}>
<Sider {...siderProps} />
</aside> : ''}
<div className={styles.main}>
{hasHeader ? <Header {...headerProps} /> : ''}
{hasBread ? <Bread {...breadProps} /> : ''}
<div className={styles.container} ref={n => this.container = n} id="container">
<div className={styles.content} ref={n => this.content = n}>
<div ref={n => this.contentInner = n}>
{errorProps ? <Error {...errorProps} /> : children}
</div>
</div>
{showFooter && <Footer />}
</div>
</div>
</div>
}
</div>
)
}
}
const App = ({ ...props }) => {
return (
<AppContainer {...props}/>
)
}
App.propTypes = {
children: PropTypes.element.isRequired,
location: PropTypes.object,
dispatch: PropTypes.func,
app: PropTypes.object,
loading: PropTypes.object,
}
export default connect(({ app, loading }) => ({ app, loading }))(App)
|
frontend/modules/recipe/components/Ingredients.js
|
rustymyers/OpenEats
|
import React from 'react'
import PropTypes from 'prop-types'
import { Checkbox } from '../../common/components/FormComponents'
const Ingredients = ({ data, check }) => {
let ingredients = data.map((ingredient, i) => {
let quantity = ingredient.customQuantity ? ingredient.customQuantity : ingredient.quantity;
return (
<li className="ingredient" key={ i }>
<Checkbox
name={ ingredient.id }
checked={ ingredient.checked ? ingredient.checked : false }
change={ check }
/>
{ (ingredient.quantity !== 0)
? <span className="quantity">{ quantity } </span>
: null
}
{ (ingredient.measurement)
? <span className="measurement">{ ingredient.measurement } </span>
: null
}
{ (ingredient.title)
? <span className="title">{ ingredient.title }</span>
: null
}
</li>
);
});
return (
<ul className="ingredients" >
{ ingredients }
</ul>
);
};
Ingredients.PropTypes = {
data: PropTypes.arrayOf(PropTypes.shape({
quantity: PropTypes.number.isRequired,
measurement: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
}).isRequired).isRequired
};
export default Ingredients;
|
js/src/components/Controls/Inline/index.js
|
understory-dev/react-draft-wysiwyg
|
/* @flow */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { getSelectionInlineStyle } from 'draftjs-utils';
import { RichUtils, EditorState, Modifier } from 'draft-js';
import { forEach } from '../../../utils/common';
import LayoutComponent from './Component';
export default class Inline extends Component {
static propTypes = {
onChange: PropTypes.func.isRequired,
editorState: PropTypes.object.isRequired,
modalHandler: PropTypes.object,
config: PropTypes.object,
translations: PropTypes.object,
};
state: Object = {
currentStyles: {},
};
componentWillMount(): void {
const { editorState, modalHandler } = this.props;
if (editorState) {
this.setState({
currentStyles: this.changeKeys(getSelectionInlineStyle(editorState)),
});
}
modalHandler.registerCallBack(this.expandCollapse);
}
componentWillReceiveProps(properties: Object): void {
if (properties.editorState &&
this.props.editorState !== properties.editorState) {
this.setState({
currentStyles: this.changeKeys(getSelectionInlineStyle(properties.editorState)),
});
}
}
componentWillUnmount(): void {
const { modalHandler } = this.props;
modalHandler.deregisterCallBack(this.expandCollapse);
}
changeKeys = (style) => {
if (style) {
const st = {};
forEach(style, (key, value) => {
st[key === 'CODE' ? 'monospace' : key.toLowerCase()] = value;
});
return st;
}
}
toggleInlineStyle: Function = (style: string): void => {
const newStyle = style === 'monospace' ? 'CODE' : style.toUpperCase();
const { editorState, onChange } = this.props;
let newState = RichUtils.toggleInlineStyle(
editorState,
newStyle
);
if (style === 'subscript' || style === 'superscript') {
const removeStyle = style === 'subscript' ? 'SUPERSCRIPT' : 'SUBSCRIPT';
const contentState = Modifier.removeInlineStyle(
newState.getCurrentContent(),
newState.getSelection(),
removeStyle
);
newState = EditorState.push(newState, contentState, 'change-inline-style');
}
if (newState) {
onChange(newState);
}
};
expandCollapse: Function = (): void => {
this.setState({
expanded: this.signalExpanded,
});
this.signalExpanded = false;
}
onExpandEvent: Function = (): void => {
this.signalExpanded = !this.state.expanded;
};
doExpand: Function = (): void => {
this.setState({
expanded: true,
});
};
doCollapse: Function = (): void => {
this.setState({
expanded: false,
});
};
render(): Object {
const { config, translations } = this.props;
const { expanded, currentStyles } = this.state
const InlineComponent = config.component || LayoutComponent;
return (
<InlineComponent
config={config}
translations={translations}
currentState={currentStyles}
expanded={expanded}
onExpandEvent={this.onExpandEvent}
doExpand={this.doExpand}
doCollapse={this.doCollapse}
onChange={this.toggleInlineStyle}
/>
);
}
}
// todo: move all controls to separate folder controls
// make subscript less low
|
app/routes.js
|
mlubovac/react-es6-starter
|
import React from 'react';
import {Route, IndexRoute} from 'react-router';
import MasterPage from './components/MasterPage';
import HomePage from './components/HomePage';
import AboutPage from './components/AboutPage';
import ContactPage from './components/ContactPage';
export default (
<Route path='/' component={MasterPage}>
<IndexRoute component={HomePage} />
<Route path='/about' component={AboutPage} />
<Route path='/contact' component={ContactPage} />
</Route>
);
|
src/renderer/components/Settings/index.js
|
protonmail-desktop/application
|
import React from 'react';
import PropTypes from 'prop-types';
import styles from './styles.scss';
export default class Settings extends React.Component {
static propTypes = {
darkTheme: PropTypes.bool.isRequired,
onChangeSetting: PropTypes.func.isRequired,
useProtonMailBeta: PropTypes.bool.isRequired,
};
handleChangeCheckbox({ target }) {
this.props.onChangeSetting(target.name, target.checked);
}
render() {
return (
<div className={styles.Container}>
<h1>Settings</h1>
<div className={styles.FormControl}>
<input
checked={this.props.darkTheme}
id="settings-dark-theme"
name="darkTheme"
type="checkbox"
onChange={this.handleChangeCheckbox.bind(this)}
/>
<label htmlFor="settings-dark-theme">
Dark theme
</label>
</div>
<div className={styles.FormControl}>
<input
checked={this.props.useProtonMailBeta}
id="settings-use-beta"
name="useProtonMailBeta"
type="checkbox"
onChange={this.handleChangeCheckbox.bind(this)}
/>
<label htmlFor="settings-use-beta">
Use beta.protonmail.com
</label>
</div>
</div>
);
}
}
|
docs/app/Examples/collections/Table/Variations/TableExampleFullWidth.js
|
aabustamante/Semantic-UI-React
|
import React from 'react'
import { Button, Checkbox, Icon, Table } from 'semantic-ui-react'
const TableExampleFullWidth = () => {
return (
<Table celled compact definition>
<Table.Header fullWidth>
<Table.Row>
<Table.HeaderCell />
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>Registration Date</Table.HeaderCell>
<Table.HeaderCell>E-mail address</Table.HeaderCell>
<Table.HeaderCell>Premium Plan</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell collapsing>
<Checkbox slider />
</Table.Cell>
<Table.Cell>John Lilki</Table.Cell>
<Table.Cell>September 14, 2013</Table.Cell>
<Table.Cell>jhlilk22@yahoo.com</Table.Cell>
<Table.Cell>No</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell collapsing>
<Checkbox slider />
</Table.Cell>
<Table.Cell>Jamie Harington</Table.Cell>
<Table.Cell>January 11, 2014</Table.Cell>
<Table.Cell>jamieharingonton@yahoo.com</Table.Cell>
<Table.Cell>Yes</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell collapsing>
<Checkbox slider />
</Table.Cell>
<Table.Cell>Jill Lewis</Table.Cell>
<Table.Cell>May 11, 2014</Table.Cell>
<Table.Cell>jilsewris22@yahoo.com</Table.Cell>
<Table.Cell>Yes</Table.Cell>
</Table.Row>
</Table.Body>
<Table.Footer fullWidth>
<Table.Row>
<Table.HeaderCell />
<Table.HeaderCell colSpan='4'>
<Button floated='right' icon labelPosition='left' primary size='small'>
<Icon name='user' /> Add User
</Button>
<Button size='small'>Approve</Button>
<Button disabled size='small'>Approve All</Button>
</Table.HeaderCell>
</Table.Row>
</Table.Footer>
</Table>
)
}
export default TableExampleFullWidth
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.