path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
examples/styling/aphrodite/src/components/Profile/index.js | pure-ui/styleguide | import React, { Component } from 'react';
import { css } from 'aphrodite';
import Button from '../Button';
import styles from './styles';
class Profile extends Component {
static propTypes = {
avatarUrl: React.PropTypes.string.isRequired,
firstName: React.PropTypes.string.isRequired,
lastName: React.PropTypes.string,
username: React.PropTypes.string.isRequired,
bio: React.PropTypes.string,
};
onAddFriend = () => {
alert(`Add @${this.props.username} as a friend`); // eslint-disable-line no-alert
};
render() {
return (
<div className={css(styles.card)}>
<div className={css(styles.row)}>
<img
className={css(styles.avatar)}
src={this.props.avatarUrl}
alt={`${this.props.firstName} ${this.props.lastName}`}
/>
<div className={css(styles.information)}>
<h1 className={css(styles.name)}>
{this.props.firstName}{(this.props.lastName) ? (` ${this.props.lastName}`) : null}
</h1>
<h2 className={css(styles.username)}>@{this.props.username}</h2>
</div>
</div>
<p className={css(styles.paragraph)}>{this.props.bio}</p>
<div className={css(styles.buttonWrapper)}>
<Button type="secondary" onClick={this.onAddFriend}>
Add friend!
</Button>
</div>
</div>
);
}
}
export default Profile;
|
src/components/Overview/Overview.react.js | isuruAb/chat.susi.ai | import './Overview.css';
import $ from 'jquery';
import allDevices from '../../images/all_devices.png';
import androidMockup from '../../images/android-mockup.jpg';
import bots from '../../images/bots.jpg';
import Close from 'material-ui/svg-icons/navigation/close';
import Footer from '../Footer/Footer.react';
import githubText from '../../images/github-text-logo.png';
import manyLanguages from '../../images/many_languages.png';
import mapAndroid from '../../images/map-android.jpg';
import Modal from 'react-modal';
import openSource from '../../images/open-source.png';
import PlayCircle from 'material-ui/svg-icons/av/play-circle-filled';
import PropTypes from 'prop-types';
import shield from '../../images/shield.svg';
import StaticAppBar from '../StaticAppBar/StaticAppBar.react';
import susiGif from '../../images/susi.gif';
import susiSkill from '../../images/susi_skill.png';
import susiTestGif from '../../images/susi-test.gif';
import { Link } from 'react-router-dom';
import React, { Component } from 'react';
class Overview extends Component{
constructor(props){
super(props);
this.state={
video:false,
}
}
handleTitle = () => {
this.props.history.push('/');
}
// Open Video Dialog and close login and sign up dialog
handleVideo = () => this.setState({
login: false,
signup: false,
video: true
})
// Close all the dialogs
handleClose = () => this.setState({
login: false,
signup: false,
video: false
})
// Close Video Dialog
closeVideo = () => this.setState({
video: false
})
_onReady(event) {
// access to player in all event handlers via event.target
event.target.pauseVideo();
}
componentWillMount(){
document.body.style.backgroundColor = '#fff';
}
componentDidMount() {
// Adding title tag to page
document.title = 'SUSI.AI - Open Source Artificial Intelligence for Personal Assistants, Robots, Help Desks and Chatbots.';
// Scrolling to top of page when component loads
$('html, body').animate({ scrollTop: 0 }, 'fast');
}
render() {
document.body.style.setProperty('background-image', 'none');
const closingStyle = {
position: 'absolute',
zIndex: 120000,
fill: '#fff',
width: '40px',
height: '40px',
right: '20px',
top: '20px',
cursor: 'pointer'
}
return (
<div>
<StaticAppBar {...this.props}
location={this.props.location} closeVideo={this.closeVideo} />
<div className='section'>
<div className='section-container'>
<div className="hero">
<img src={susiGif} style={{ margin: '20px 0' }} alt='Meet SUSI'/>
<h1>
Meet SUSI.AI,
Your Artificial Intelligence for Personal Assistants,
Robots, Help Desks and Chatbots.
</h1>
<p>Ask it questions. Tell it to do things. Always ready to help.</p>
<a onClick={this.handleVideo} style={{
color: '#3367d6',
cursor: 'pointer', position: 'relative'
}}>
<PlayCircle style={{
fill: '#3367d6',
marginRight: '50px'
}} /><span className='watchStyle'>Watch</span>
</a>
</div>
</div>
</div>
<div className="section_copy">
<div className="conversation__description">
<div className="description__heading">Ask it anything.</div>
<p className="description__text">
Search for the capital of Vietnam or
find translations in different languages.
Ask SUSI for your location, and
what the weather’s like when you get there.</p>
</div>
<div className='img-container'>
<img src={susiTestGif} alt='susi-test' className='susi-test' />
</div>
</div>
<div className="section_copy">
<div className="conversation__description">
<div className="description__heading">Tell it to do things.</div>
<p className="description__text">
SUSI can listen to you through the Mic
and answer back on your Speaker.
You can activate the assistant saying
<b> "Hi SUSI"</b> already on many clients and devices.
The more you talk with SUSI the better it gets.
You can even tell SUSI to remember things.</p>
</div>
<div className='img-container'>
<img src={mapAndroid} alt='Map' className='android-mockup' />
</div>
</div>
<div className="section_copy">
<div className="conversation__description">
<div className="description__heading">For your Smartphone</div>
<p className="description__text">SUSI is available for <b>Android</b>
and <b>iOS devices</b>.
Download the App to have access to SUSI on the go.</p>
<div className="description__text store_icons">
<Link className="playstore"
target="_blank" to="https://play.google.com/store/apps/details?id=org.fossasia.susi.ai"> Get It on Google Play
</Link>
<Link className="appstore"
target="_blank" to="https://github.com/fossasia/susi_iOS"> Download on the App Store
</Link>
</div>
</div>
<div className='img-container'>
<img src={androidMockup} alt='Android Mockup' className='android-mockup' />
</div>
</div>
<div className="section_copy">
<div className="column_section">
<div className="conversation__description custom_description">
<div className='img-container'>
<img src={bots} alt='Android Mockup' className='bots-mockup' />
</div>
<div className="description__heading">On many Platforms</div>
<p className="description__text"><b>SUSI.AI</b> already runs on many chat
services and social networks. We are developing plugins for all
major services including
<a href='https://github.com/fossasia/susi_tweetbot'>Twitter</a>,
<a href='https://github.com/fossasia/susi_fbbot'>Facebook</a>,
<a href='https://github.com/fossasia/susi_linebot'>Line</a>,
<a href='https://github.com/fossasia/susi_slackbot'>Slack</a>,
<a href='https://github.com/fossasia/susi_wechatbot'>We Chat</a>,
<a href='https://github.com/fossasia/susi_viberbot'>Viber</a>,
<a href='https://github.com/fossasia/susi_gitterbot'>Gitter</a>.
Just set up SUSI on your channel and add
<b>@susi</b> in your conversations and SUSI is ready to help.
</p>
</div>
</div>
<div className="column_section">
<div className='img-container'>
<img src={allDevices} alt='Android Mockup' className='bots-mockup' />
</div>
<div className="conversation__description custom_description">
<div className="description__heading">For all Devices</div>
<p className="description__text"><b >SUSI.AI</b> is available for any android, iOS device and also you can access the web chat application from this URL <a href="https://chat.susi.ai">https://chat.susi.ai</a>
</p>
</div>
</div>
<div className="column_section">
<div className="conversation__description custom_description">
<div className='img-container'>
<img src={manyLanguages} alt='Android Mockup' className='bots-mockup' />
</div>
<div className="description__heading">Use it in many Languages</div>
<p className="description__text">You can use <b>SUSI.AI</b> in different
languages. You can ask questions in many languages.
SUSI is intelligent to identify and answer your question in your language.
</p>
</div>
</div>
</div>{/* section_copy ends */}
<div className="section_center">
<div className="center__description">
<div className="description__heading">SUSI Skills</div>
<p className="description__text">
SUSI is having many skills. You can look at the collection of skills at
<Link style={{ textDecoration: 'none' }} to="https://skills.susi.ai/" target="_blank"> skills.susi.ai</Link>.
SUSI skills are divided into groups like knowledge,
assistant, problem solving, entertainment, shopping
and small talks. SUSI Skill development is easy and fun. </p>
</div>
<div className='img-container'>
<img src={susiSkill} alt='Skills' className='skillWiki'/>
</div>
</div>
<div className="section_copy safe_and_secure">
<div className="conversation__description">
<div className="description__heading">Safe and secure.</div>
<p className="description__text"><b>SUSI.AI</b> is <b>
<Link style={{ textDecoration: 'none', color: '#000' }}
target="_blank" to="https://github.com/fossasia?utf8=%E2%9C%93&q=susi">Open Source</Link></b>. The code is
always available for security reviews and can be improved by
anyone with the knowledge and understanding online.</p>
<div className="opensource-logos">
<span className="opensource">
<Link to="https://opensource.org/" target="_blank">
<img src={openSource} alt='osi' />
</Link>
</span>
<span className="github_logo">
<Link to="https://github.com/fossasia?utf8=✓&q=susi" target="_blank">
<img src={githubText} alt='ghlogo' />
</Link>
</span>
</div>
</div>
<div className='img-container'>
<img src={shield} alt='Android Mockup' className='shield' />
</div>
</div>
<Footer />
{/* Video */}
<Modal
isOpen={this.state.video}
className="Video-Modal"
onRequestClose={this.handleClose}
contentLabel="Assistant Video"
overlayClassName="Video-Overlay">
<div className="video-container">
<iframe id="player" type="text/html" frameBorder="0" allowFullScreen
src="https://www.youtube.com/embed/tIG5griC-G0?enablejsapi=1&autoplay=1"></iframe>
<Close style={closingStyle} onTouchTap={this.handleClose} />
</div>
</Modal>
</div>
);
};
}
Overview.propTypes = {
history: PropTypes.object,
location: PropTypes.object
}
export default Overview;
|
docs/components/Docs/Nav/dropdown.js | enjoylife/storybook | import PropTypes from 'prop-types';
import React from 'react';
import { browserHistory } from 'react-router';
import './style.css';
class Nav extends React.Component {
handleHeadingChange(event) {
const { sections } = this.props;
const selectedSectionId = event.target.value;
const section = sections.find(s => s.id === selectedSectionId);
const itemId = section.items[0].id;
this.changeRoute(selectedSectionId, itemId);
}
handleNavChange(event) {
const { sections, selectedSection } = this.props;
const selectedSectionId = selectedSection || sections[0].id;
this.changeRoute(selectedSectionId, event.target.value);
}
changeRoute(selectedSectionId, selectedItemId) {
const url = `/${selectedSectionId}/${selectedItemId}/`;
browserHistory.push(url);
}
renderNavOpts(nav) {
return <option value={nav.id} key={nav.id}>{nav.title}</option>;
}
renderHeadingOpts(section) {
return <option value={section.id} key={section.id}>{section.heading}</option>;
}
render() {
const { sections, selectedSection, selectedItem } = this.props;
const selectedSectionId = selectedSection || sections[0].id;
const selectedItemId = selectedItem || sections[0].items[0].id;
const selectedSectionData = sections.find(section => section.id === selectedSectionId);
const navs = selectedSectionData.items;
return (
<div>
<div>
<select value={selectedSectionId} onChange={event => this.handleHeadingChange(event)}>
{sections.map(section => this.renderHeadingOpts(section))}
</select>
</div>
<div>
<select value={selectedItemId} onChange={event => this.handleNavChange(event)}>
{navs.map(nav => this.renderNavOpts(nav))}
</select>
</div>
</div>
);
}
}
Nav.propTypes = {
sections: PropTypes.array, // eslint-disable-line
selectedSection: PropTypes.string.isRequired,
selectedItem: PropTypes.string.isRequired,
};
export default Nav;
|
src/containers/App/index.js | wvfan/HSBC | import * as F from 'firebase';
import React from 'react';
import PropTypes from 'prop-types';
import { Route } from 'react-router';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import _ from 'lodash';
import modifyHistory from 'helpers/modifyHistory';
import Design from 'containers/Design';
import Scanner from 'containers/Scanner';
import Address from 'containers/Address';
import { styles } from './styles.scss';
@connect(
state => ({
system: state.system,
}),
dispatch => bindActionCreators({
}, dispatch),
)
export default class App extends React.Component {
static propTypes = {
history: PropTypes.object,
location: PropTypes.object,
system: PropTypes.object,
};
componentWillMount() {
modifyHistory(this.props.history);
if (DEBUGMODE) {
// While testing with browser, automatically set url for MemoryRouter.
// When running on device, the initial router will be '/'
const path = window.location.href;
const index = (path.indexOf('/', 8) + 1) || (path.length + 1);
this.props.history.replace(path.substr(index - 1));
}
}
render() {
const {
system,
} = this.props;
return (
<div className={`absolute-parent ${styles}`}>
{DEBUGMODE ? <Design /> : ''}
<Route exact path="/" component={Address} />
<Route path="/scanner" component={Scanner} />
<Route path="/address" component={Address} />
</div>
);
}
}
|
src/Paragraph/Paragraph.stories.js | boldr/boldr-ui | import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import Paragraph from './Paragraph';
storiesOf('Paragraph', module)
.add('default', () =>
<Paragraph>
Wolf whatever craft beer, readymade blue bottle raclette squid next level af franzen heirloom
90's XOXO beard. Twee schlitz health goth cray. Biodiesel butcher coloring book venmo
snackwave vexillologist, neutra live-edge enamel pin chia. Roof party church-key fanny pack
sartorial, flannel shabby chic four loko literally tumeric stumptown coloring book. Organic
scenester mumblecore cliche, vice readymade helvetica. Glossier 8-bit disrupt affogato pop-up
post-ironic, la croix cardigan. Gentrify tousled scenester, iceland dreamcatcher master
cleanse kombucha hoodie mlkshk cardigan seitan before they sold out drinking vinegar ethical
kickstarter.
</Paragraph>,
)
.add('lead', () =>
<Paragraph isLead>
Wolf whatever craft beer, readymade blue bottle raclette squid next level af franzen heirloom
90's XOXO beard. Twee schlitz health goth cray. Biodiesel butcher coloring book venmo
snackwave vexillologist, neutra live-edge enamel pin chia. Roof party church-key fanny pack
sartorial, flannel shabby chic four loko literally tumeric stumptown coloring book. Organic
scenester mumblecore cliche, vice readymade helvetica. Glossier 8-bit disrupt affogato pop-up
post-ironic, la croix cardigan. Gentrify tousled scenester, iceland dreamcatcher master
cleanse kombucha hoodie mlkshk cardigan seitan before they sold out drinking vinegar ethical
kickstarter.
</Paragraph>,
)
.add('light', () =>
<div style={{ backgroundColor: '#1B252F' }}>
<Paragraph isLight>
Wolf whatever craft beer, readymade blue bottle raclette squid next level af franzen
heirloom 90's XOXO beard. Twee schlitz health goth cray. Biodiesel butcher coloring book
venmo snackwave vexillologist, neutra live-edge enamel pin chia. Roof party church-key fanny
pack sartorial, flannel shabby chic four loko literally tumeric stumptown coloring book.
Organic scenester mumblecore cliche, vice readymade helvetica. Glossier 8-bit disrupt
affogato pop-up post-ironic, la croix cardigan. Gentrify tousled scenester, iceland
dreamcatcher master cleanse kombucha hoodie mlkshk cardigan seitan before they sold out
drinking vinegar ethical kickstarter.
</Paragraph>
</div>,
);
|
src/routes/home/index.js | rameshrr/dicomviewer | /**
* 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 Home from './Home';
import Layout from '../../components/Layout';
async function action({ fetch }) {
const resp = await fetch('/graphql', {
body: JSON.stringify({
query: '{news{title,link,content}}',
}),
});
const { data } = await resp.json();
if (!data || !data.news) throw new Error('Failed to load the news feed.');
return {
title: 'React Starter Kit',
component: (
<Layout>
<Home news={data.news} />
</Layout>
),
};
}
export default action;
|
assets/node_modules/react-router/es/RouterContext.js | janta-devs/nyumbani | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
import invariant from 'invariant';
import React from 'react';
import getRouteParams from './getRouteParams';
import { ContextProvider } from './ContextUtils';
import { isReactChildren } from './RouteUtils';
var _React$PropTypes = React.PropTypes,
array = _React$PropTypes.array,
func = _React$PropTypes.func,
object = _React$PropTypes.object;
/**
* A <RouterContext> renders the component tree for a given router state
* and sets the history object and the current location in context.
*/
var RouterContext = React.createClass({
displayName: 'RouterContext',
mixins: [ContextProvider('router')],
propTypes: {
router: object.isRequired,
location: object.isRequired,
routes: array.isRequired,
params: object.isRequired,
components: array.isRequired,
createElement: func.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
createElement: React.createElement
};
},
childContextTypes: {
router: object.isRequired
},
getChildContext: function getChildContext() {
return {
router: this.props.router
};
},
createElement: function createElement(component, props) {
return component == null ? null : this.props.createElement(component, props);
},
render: function render() {
var _this = this;
var _props = this.props,
location = _props.location,
routes = _props.routes,
params = _props.params,
components = _props.components,
router = _props.router;
var element = null;
if (components) {
element = components.reduceRight(function (element, components, index) {
if (components == null) return element; // Don't create new children; use the grandchildren.
var route = routes[index];
var routeParams = getRouteParams(route, params);
var props = {
location: location,
params: params,
route: route,
router: router,
routeParams: routeParams,
routes: routes
};
if (isReactChildren(element)) {
props.children = element;
} else if (element) {
for (var prop in element) {
if (Object.prototype.hasOwnProperty.call(element, prop)) props[prop] = element[prop];
}
}
if ((typeof components === 'undefined' ? 'undefined' : _typeof(components)) === 'object') {
var elements = {};
for (var key in components) {
if (Object.prototype.hasOwnProperty.call(components, key)) {
// Pass through the key as a prop to createElement to allow
// custom createElement functions to know which named component
// they're rendering, for e.g. matching up to fetched data.
elements[key] = _this.createElement(components[key], _extends({
key: key }, props));
}
}
return elements;
}
return _this.createElement(components, props);
}, element);
}
!(element === null || element === false || React.isValidElement(element)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The root route must render a single element') : invariant(false) : void 0;
return element;
}
});
export default RouterContext; |
app/static/src/diagnostic/TestTypeResultForm_modules/NewParticleTestForm.js | SnowBeaver/Vision | import React from 'react';
import FormControl from 'react-bootstrap/lib/FormControl';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import Button from 'react-bootstrap/lib/Button';
import Panel from 'react-bootstrap/lib/Panel';
import {findDOMNode} from 'react-dom';
import {hashHistory} from 'react-router';
import {Link} from 'react-router';
import HelpBlock from 'react-bootstrap/lib/HelpBlock';
import {NotificationContainer, NotificationManager} from 'react-notifications';
const TextField = React.createClass({
render: function() {
var label = (this.props.label != null) ? this.props.label: "";
var name = (this.props.name != null) ? this.props.name: "";
var value = (this.props.value != null) ? this.props.value: "";
return (
<FormGroup validationState={this.props.errors[name] ? 'error' : null}>
<ControlLabel>{label}</ControlLabel>
<FormControl type="text"
placeholder={label}
name={name}
value={value}
data-type={this.props["data-type"]}
/>
<HelpBlock className="warning">{this.props.errors[name]}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
);
}
});
var NewParticleTestForm = React.createClass({
getInitialState: function () {
return {
loading: false,
errors: {},
fields: [
'_2um', '_5um', '_10um', '_15um',
'_25um', '_50um', '_100um', 'nas1638',
'iso4406_1', 'iso4406_2', 'iso4406_3'
]
}
},
componentDidMount: function () {
var source = '/api/v1.0/' + this.props.tableName + '/?test_result_id=' + this.props.testResultId;
this.serverRequest = $.authorizedGet(source, function (result) {
var res = (result['result']);
if (res.length > 0) {
var fields = this.state.fields;
fields.push('id');
var data = res[0];
var state = {};
for (var i = 0; i < fields.length; i++) {
var key = fields[i];
if (data.hasOwnProperty(key)) {
state[key] = data[key];
}
}
this.setState(state);
}
}.bind(this), 'json');
},
_create: function () {
var fields = this.state.fields;
var data = {test_result_id: this.props.testResultId};
var url = '/api/v1.0/' + this.props.tableName + '/';
for (var i = 0; i < fields.length; i++) {
var key = fields[i];
data[key] = this.state[key];
}
if ('id' in this.state) {
url += this.state['id'];
delete data.id;
}
return $.authorizedAjax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
beforeSend: function () {
this.setState({loading: true});
}.bind(this)
})
},
_onSubmit: function (e) {
e.preventDefault();
// Do not propagate the submit event of the main form
e.stopPropagation();
if (!this.is_valid()){
NotificationManager.error('Please correct the errors');
e.stopPropagation();
return false;
}
var xhr = this._create();
xhr.done(this._onSuccess)
.fail(this._onError)
.always(this.hideLoading)
},
hideLoading: function () {
this.setState({loading: false});
},
_onSuccess: function (data) {
// this.setState(this.getInitialState());
NotificationManager.success('Test values have been saved successfully.');
if ($.isNumeric(data.result)) {
this.setState({id: data.result});
}
},
_onError: function (data) {
var message = "Failed to create";
var res = data.responseJSON;
if (res.message) {
message = data.responseJSON.message;
}
if (res.error) {
// We get list of errors
if (data.status >= 500) {
message = res.error.join(". ");
} else if (res.error instanceof Object){
// We get object of errors with field names as key
for (var field in res.error) {
var errorMessage = res.error[field];
if (Array.isArray(errorMessage)) {
errorMessage = errorMessage.join(". ");
}
res.error[field] = errorMessage;
}
this.setState({
errors: res.error
});
} else {
message = res.error;
}
}
NotificationManager.error(message);
},
_onChange: function (e) {
var state = {};
if (e.target.type == 'checkbox') {
state[e.target.name] = e.target.checked;
} else if (e.target.type == 'select-one') {
state[e.target.name] = e.target.value;
} else {
state[e.target.name] = e.target.value;
}
var errors = this._validate(e);
state = this._updateFieldErrors(e.target.name, state, errors);
this.setState(state);
},
_validate: function (e) {
var errors = [];
var error;
error = this._validateFieldType(e.target.value, e.target.getAttribute("data-type"));
if (error){
errors.push(error);
}
return errors;
},
_validateFieldType: function (value, type){
var error = "";
if (type != undefined && value){
var typePatterns = {
"float": /^(-|\+?)[0-9]+(\.)?[0-9]*$/
};
if (!typePatterns[type].test(value)){
error = "Invalid " + type + " value";
}
}
return error;
},
_updateFieldErrors: function (fieldName, state, errors){
// Clear existing errors related to the current field as it has been edited
state.errors = this.state.errors;
delete state.errors[fieldName];
// Update errors with new ones, if present
if (Object.keys(errors).length){
state.errors[fieldName] = errors.join(". ");
}
return state;
},
is_valid: function () {
return (Object.keys(this.state.errors).length <= 0);
},
_formGroupClass: function (field) {
var className = "form-group ";
if (field) {
className += " has-error"
}
return className;
},
render: function () {
return (
<div className="form-container">
<form method="post" action="#" onSubmit={this._onSubmit} onChange={this._onChange}>
<div className="row">
<div className="col-md-3">
<TextField label=">2um" name="_2um" value={this.state._2um}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label=">5um" name="_5um" value={this.state._5um}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label=">10um" name="_10um" value={this.state._10um}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label=">15um" name="_15um" value={this.state._15um}
errors={this.state.errors} data-type="float"/>
</div>
</div>
<div className="row">
<div className="col-md-3">
<TextField label=">25um" name="_25um" value={this.state._25um}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label=">50um" name="_50um" value={this.state._50um}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label=">100um" name="_100um" value={this.state._100um}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label="NAS1638" name="nas1638" value={this.state.nas1638}
errors={this.state.errors} data-type="float"/>
</div>
</div>
<div className="row">
<div className="col-md-6 pull-right" >
<Panel header="ISO 4406">
</Panel>
</div>
</div>
<div className="row">
<div className="col-md-2 pull-right">
<TextField label="iso4406-1" name="iso4406_1" value={this.state.iso4406_1}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-2 pull-right">
<TextField label="iso4406-2" name="iso4406_2" value={this.state.iso4406_2}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-2 pull-right">
<TextField label="iso4406-3" name="iso4406_3" value={this.state.iso4406_3}
errors={this.state.errors} data-type="float"/>
</div>
</div>
<div className="row">
<div className="col-md-12 ">
<Button bsStyle="success"
className="pull-right"
type="submit">Save</Button>
<Button bsStyle="danger"
className="pull-right margin-right-xs"
onClick={this.props.handleClose}
>Cancel</Button>
</div>
</div>
</form>
</div>
);
}
});
export default NewParticleTestForm;
|
client/src/components/PublicLanding.js | no-stack-dub-sack/alumni-network | import React from 'react';
import styled from 'styled-components';
class About extends React.Component {
state = {
flashMessageCleared: false
}
componentDidMount = () => {
document.addEventListener('click', this.handleClick);
}
componentWillUnmount = () => {
document.removeEventListener('click', this.handleClick);
}
// 'close' is className of close icon in flash message
handleClick = (e) => {
e.target.classList.contains('close')
? this.setState({ flashMessageCleared: true })
: this.setState({ flashMessageCleared: false });
}
render() {
const { flashMessageCleared } = this.state;
const numMessages = document.getElementsByClassName('flashMessage').length
// handles margins when flash messages are rendered and
// also when subsequently removed. handleClick and state of
// this component are all related to this.
const Container = styled.div`
marginTop: ${numMessages > 0 && !flashMessageCleared
? '50px'
: '145px'} !important;
fontSize: 18px !important;
`;
return (
<Container className="ui raised very piled padded text container segment">
<h1 className="ui header">
{'Welcome to the freeCodeCamp Alumni Network'}
</h1>
<p>
<strong>{'freeCodeCamp'}</strong>{` has an incredible and vibrant
international community. We built this app specifically to try and
cultivate relationships among experienced campers.`}
</p>
<p>
{`Currently, the FCC Forum, Gitter, and other resources provide ample
opportunities for campers at any skill level. We wanted to create an
environment specifically for more experienced campers who are looking
for advanced collaborative projects or mentorship opportunities, as a
mentor or mentee.`}
</p>
<p>
{`Our authentication process verifies the FCC progress of users, and
only admits students who have completed at least one FCC Certificate`}
{' ('}<strong>{'Note:'}</strong>{` You will have to make your FCC
profile public for this validation to work).`}
</p>
<p>
{`Our goal is to create a focused community of like-minded individuals
who can benefit from each others culminated experience and expertise,
whether in new technologies, programming skills, or career advice.`}
</p>
<h2>{'Thanks for visiting, and happy coding!'}</h2>
</Container>
);
}
}
export default About;
|
src/parser/druid/feral/modules/core/Snapshot.js | fyruna/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';
import { formatNumber, formatPercentage } from 'common/format';
import { TooltipElement } from 'common/Tooltip';
import Analyzer from 'parser/core/Analyzer';
import { encodeTargetString } from 'parser/shared/modules/EnemyInstances';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import StatisticsListBox from 'interface/others/StatisticsListBox';
import { PANDEMIC_FRACTION, PROWL_RAKE_DAMAGE_BONUS, TIGERS_FURY_DAMAGE_BONUS, BLOODTALONS_DAMAGE_BONUS } from '../../constants';
const debug = false;
/**
* Feral has a snapshotting mechanic which means the effect of some buffs are maintained over the duration of
* some DoTs even after the buff has worn off.
* Players should follow a number of rules with regards when they refresh a DoT and when they do not, depending
* on what buffs the DoT has snapshot and what buffs are currently active.
*
* The Snapshot class is 'abstract', and shouldn't be directly instantiated. Instead classes should extend
* it to examine how well the combatant is making use of the snapshot mechanic.
*/
/**
* leeway in ms after loss of bloodtalons/prowl buff to count a cast as being buffed.
* Danger of false positives from buffs fading due to causes other than being used to buff a DoT.
*/
const BUFF_WINDOW_TIME = 60;
// leeway in ms between a cast event and debuff apply/refresh for them to be associated
const CAST_WINDOW_TIME = 100;
/**
* Leeway in ms between when a debuff was expected to wear off and when damage events will no longer be counted
* Largest found in logs is 149ms:
* https://www.warcraftlogs.com/reports/8Ddyzh9nRjrxv3JA/#fight=16&source=21
* Moonfire DoT tick at 8:13.300, expected to expire at 8:13.151
*/
const DAMAGE_AFTER_EXPIRE_WINDOW = 200;
class Snapshot extends Analyzer {
// extending class should fill these in:
static spellCastId = null;
static debuffId = null;
static isProwlAffected = false;
static isTigersFuryAffected = false;
static isBloodtalonsAffected = false;
static durationOfFresh = null;
stateByTarget = {};
lastDoTCastEvent;
castCount = 0;
ticks = 0;
ticksWithProwl = 0;
ticksWithTigersFury = 0;
ticksWithBloodtalons = 0;
damageFromProwl = 0;
damageFromTigersFury = 0;
damageFromBloodtalons = 0;
on_byPlayer_cast(event) {
if (this.constructor.spellCastId !== event.ability.guid) {
return;
}
this.castCount += 1;
this.lastDoTCastEvent = event;
}
constructor(...args) {
super(...args);
if (!this.constructor.spellCastId || !this.constructor.debuffId) {
this.active = false;
throw new Error('Snapshot should be extended and provided with spellCastId and debuffId.');
}
}
on_byPlayer_damage(event) {
if (event.targetIsFriendly || this.constructor.debuffId !== event.ability.guid || !event.tick) {
// ignore damage on friendlies, damage not from the tracked DoT, and any non-DoT damage
return;
}
if ((event.amount || 0) + (event.absorbed || 0) === 0) {
// what buffs a zero-damage tick has doesn't matter, so don't count them (usually means target is currently immune to damage)
return;
}
const state = this.stateByTarget[encodeTargetString(event.targetID, event.targetInstance)];
if (!state || event.timestamp > state.expireTime + DAMAGE_AFTER_EXPIRE_WINDOW) {
debug && console.warn(`At ${this.owner.formatTimestamp(event.timestamp, 3)} damage detected from DoT ${this.constructor.debuffId} but no active state recorded for the target. Previous state expired: ${state ? this.owner.formatTimestamp(state.expireTime, 3) : 'n/a'}`);
return;
}
// how much damage is coming from the snapshot buffs combined
const bonusDamage = calculateEffectiveDamage(event, this.calcPowerFromSnapshot(state) - 1);
const additiveBonus = this.additivePowerSum(state);
this.ticks += 1;
if (state.prowl) {
this.ticksWithProwl += 1;
const fractionOfBonus = PROWL_RAKE_DAMAGE_BONUS / additiveBonus;
this.damageFromProwl += bonusDamage * fractionOfBonus;
}
if (state.tigersFury) {
this.ticksWithTigersFury += 1;
const fractionOfBonus = TIGERS_FURY_DAMAGE_BONUS / additiveBonus;
this.damageFromTigersFury += bonusDamage * fractionOfBonus;
}
if (state.bloodtalons) {
this.ticksWithBloodtalons += 1;
const fractionOfBonus = BLOODTALONS_DAMAGE_BONUS / additiveBonus;
this.damageFromBloodtalons += bonusDamage * fractionOfBonus;
}
}
on_byPlayer_applydebuff(event) {
if (this.constructor.debuffId !== event.ability.guid) {
return;
}
this.dotApplied(event);
}
on_byPlayer_refreshdebuff(event) {
if (this.constructor.debuffId !== event.ability.guid) {
return;
}
this.dotApplied(event);
}
dotApplied(event) {
const targetString = encodeTargetString(event.targetID, event.targetInstance);
const stateOld = this.stateByTarget[targetString];
const stateNew = this.makeNewState(event, stateOld);
this.stateByTarget[targetString] = stateNew;
debug && console.log(`DoT ${this.constructor.debuffId} applied at ${this.owner.formatTimestamp(event.timestamp, 3)} Prowl:${stateNew.prowl}, TF: ${stateNew.tigersFury}, BT: ${stateNew.bloodtalons}. Expires at ${this.owner.formatTimestamp(stateNew.expireTime, 3)}`);
this.checkRefreshRule(stateNew);
}
makeNewState(debuffEvent, stateOld) {
const timeRemainOnOld = stateOld ? (stateOld.expireTime - debuffEvent.timestamp) : 0;
const durationNew = this.getDurationOfFresh(debuffEvent);
let expireNew = debuffEvent.timestamp + durationNew;
if (timeRemainOnOld > 0) {
expireNew += Math.min(durationNew * PANDEMIC_FRACTION, timeRemainOnOld);
}
const combatant = this.selectedCombatant;
const stateNew = {
expireTime: expireNew,
pandemicTime: expireNew - durationNew * PANDEMIC_FRACTION,
tigersFury: this.constructor.isTigersFuryAffected &&
combatant.hasBuff(SPELLS.TIGERS_FURY.id),
prowl: this.constructor.isProwlAffected && (
combatant.hasBuff(SPELLS.INCARNATION_KING_OF_THE_JUNGLE_TALENT.id) ||
combatant.hasBuff(SPELLS.PROWL.id, null, BUFF_WINDOW_TIME) ||
combatant.hasBuff(SPELLS.PROWL_INCARNATION.id, null, BUFF_WINDOW_TIME) ||
combatant.hasBuff(SPELLS.SHADOWMELD.id, null, BUFF_WINDOW_TIME)
),
bloodtalons: this.constructor.isBloodtalonsAffected &&
combatant.hasBuff(SPELLS.BLOODTALONS_BUFF.id, null, BUFF_WINDOW_TIME),
power: 1,
startTime: debuffEvent.timestamp,
castEvent: this.lastDoTCastEvent,
// undefined if the first application of this debuff on this target
prev: stateOld,
};
stateNew.power = this.calcPower(stateNew);
if (!stateNew.castEvent ||
stateNew.startTime > stateNew.castEvent.timestamp + CAST_WINDOW_TIME) {
debug && console.warn(`DoT ${this.constructor.debuffId} applied debuff at ${this.owner.formatTimestamp(debuffEvent.timestamp, 3)} doesn't have a recent matching cast event.`);
}
return stateNew;
}
calcPower(stateNew) {
return this.calcPowerFromSnapshot(stateNew);
}
calcPowerFromSnapshot(stateNew) {
let power = 1.0;
if (stateNew.prowl) {
power *= (PROWL_RAKE_DAMAGE_BONUS + 1);
}
if (stateNew.tigersFury) {
power *= (TIGERS_FURY_DAMAGE_BONUS + 1);
}
if (stateNew.bloodtalons) {
power *= (BLOODTALONS_DAMAGE_BONUS + 1);
}
return power;
}
additivePowerSum(stateNew) {
let additive = 0;
if (stateNew.prowl) {
additive += PROWL_RAKE_DAMAGE_BONUS;
}
if (stateNew.tigersFury) {
additive += TIGERS_FURY_DAMAGE_BONUS;
}
if (stateNew.bloodtalons) {
additive += BLOODTALONS_DAMAGE_BONUS;
}
return additive;
}
checkRefreshRule(state) {
debug && console.warn('Expected checkRefreshRule function to be overridden.');
}
getDurationOfFresh(debuffEvent) {
return this.constructor.durationOfFresh;
}
subStatistic(ticksWithBuff, damageIncrease, buffId, buffName, spellName) {
const info = (
// subStatistics for this DoT will be combined, so each should have a unique key
<div className="flex" key={buffId}>
<div className="flex-main">
<SpellLink id={buffId} />
</div>
<div className="flex-sub text-right">
<TooltipElement content={`${formatNumber(damageIncrease / this.owner.fightDuration * 1000)} DPS contributed by ${buffName} on your ${spellName} DoT`}>
{formatPercentage(this.ticks === 0 ? 0 : ticksWithBuff / this.ticks)}%
</TooltipElement>
</div>
</div>
);
return info;
}
generateStatistic(spellName, statisticPosition) {
const subStats = [];
const buffNames = [];
if (this.constructor.isProwlAffected) {
const buffName = 'Prowl';
buffNames.push(buffName);
subStats.push(this.subStatistic(this.ticksWithProwl, this.damageFromProwl, SPELLS.PROWL.id, buffName, spellName));
}
if (this.constructor.isTigersFuryAffected) {
const buffName = 'Tiger\'s Fury';
buffNames.push(buffName);
subStats.push(this.subStatistic(this.ticksWithTigersFury, this.damageFromTigersFury, SPELLS.TIGERS_FURY.id, buffName, spellName));
}
if (this.constructor.isBloodtalonsAffected && this.selectedCombatant.hasTalent(SPELLS.BLOODTALONS_TALENT.id)) {
const buffName = 'Bloodtalons';
buffNames.push(buffName);
subStats.push(this.subStatistic(this.ticksWithBloodtalons, this.damageFromBloodtalons, SPELLS.BLOODTALONS_TALENT.id, buffName, spellName));
}
let buffsComment = '';
buffNames.forEach((name, index) => {
const hasComma = (buffNames.length > 2 && index < buffNames.length - 1);
const hasAnd = (index === buffNames.length - 2);
buffsComment = `${buffsComment}${name}${hasComma ? ', ' : ''}${hasAnd ? ' and ' : ''}`;
});
const isPlural = buffNames.length > 1;
return (
<StatisticsListBox
title={(
<>
<SpellIcon id={this.constructor.spellCastId} noLink /> {spellName} Snapshot
</>
)}
tooltip={`${spellName} maintains the damage bonus from ${buffsComment} if ${isPlural ? 'they were' : 'it was'} present when the DoT was applied. This lists how many of your ${spellName} ticks benefited from ${isPlural ? 'each' : 'the'} buff. ${isPlural ? 'As a tick can benefit from multiple buffs at once these percentages can add up to more than 100%.' : ''}`}
position={statisticPosition}
>
{subStats}
</StatisticsListBox>
);
}
}
export default Snapshot;
|
client/crud.js | yuanyusi/redux | // let's go!
import React from 'react';
import { render } from 'react-dom';
// Import css
import css from './styles/style.styl';
// Import Components
import App from './components/App';
import Single from './components/Single';
import PhotoGrid from './components/PhotoGrid';
import Goals from './components/Goals';
import Targets from './components/Targets';
// import react router deps
import { Provider } from 'react-redux';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { reduxReactRouter, routerStateReducer, ReduxRouter } from 'redux-react-router';
import store, { history } from './store';
const router = (
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Goals}> </IndexRoute>
<Route path="/view/:postId" component={Single}></Route>
<Route path="goals" component={Goals}></Route>
<Route path="photoGrid" component={PhotoGrid}></Route>
<Route path="targets" component={Targets}></Route>
</Route>
</Router>
</Provider>
)
render(router, document.getElementById('root'));
|
app/react-icons/fa/leanpub.js | scampersand/sonos-front | import React from 'react';
import IconBase from 'react-icon-base';
export default class FaLeanpub extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m36.7 10.2l3.1 24.7q-2.6 0-5-1.1-3.9-1.8-7.7-1.8-4.4 0-7.2 2.9-2.9-2.9-7.3-2.9-3.7 0-7.6 1.8-2.5 1.1-4.9 1.1h-0.1l3-24.7q4.4-2.4 9.4-2.4 4.5 0 7.5 2 3-2 7.5-2 5 0 9.3 2.4z m-9.6 19.2q2.5 0 4.5 0.5t5.1 1.8l-2.4-19.8q-3.3-1.5-7.2-1.5-4.3 0-7.2 2.7-2.9-2.7-7.3-2.7-3.8 0-7.1 1.5l-2.4 19.8q2-0.8 3.2-1.2t2.9-0.8 3.4-0.3q3.9 0 7.3 2.1 3.3-2.1 7.2-2.1z m0.8-0.7l-1.1-17.6q-4.1 0.1-6.9 3-3-3-7.3-3-3.4 0-6.5 1.3l-2.2 18.3q2.4-1 4.4-1.5t4.3-0.5q4.1 0 7.3 2 3.3-2.1 7.2-2z"/></g>
</IconBase>
);
}
}
|
src/applications/disability-benefits/view-payments/utils.js | department-of-veterans-affairs/vets-website | import React from 'react';
import { CONTACTS } from '@department-of-veterans-affairs/component-library/Telephone';
const SERVER_ERROR_REGEX = /^5\d{2}$/;
const CLIENT_ERROR_REGEX = /^4\d{2}$/;
export const isServerError = errCode => SERVER_ERROR_REGEX.test(errCode);
export const isClientError = errCode => CLIENT_ERROR_REGEX.test(errCode);
export const ServerErrorAlertContent = (
<>
<h2 slot="headline" className="vads-u-margin-y--0 vads-u-font-size--h3">
We’re sorry. Something went wrong on our end
</h2>
<p className="vads-u-font-size--base">
Please refresh this page or check back later. You can also sign out of
VA.gov and try signing back into this page.
</p>
<p className="vads-u-font-size--base">
If you get this error again, please call the VA.gov help desk at{' '}
<va-telephone contact={CONTACTS.VA_311} />
(TTY: <va-telephone contact={CONTACTS['711']} />
). We’re here Monday through Friday, 8:00 a.m. to 8:00 p.m. ET
</p>
</>
);
export const NoPaymentsContent = (
<>
<h2 slot="headline" className="vads-u-margin-y--0 vads-u-font-size--h3">
We don’t have a record of VA payments for you
</h2>
<p className="vads-u-font-size--base">
We can’t find any VA payments made to you, or returned VA payments. Some
details about payments may not be available online. For example, payments
less than $1 for direct deposit, or $5 for mailed checks, will not show in
your online payment history. If you think this is an error, or if you have
questions about your payment history, please call{' '}
<va-telephone contact={CONTACTS.VA_BENEFITS} />
</p>
<p className="vads-u-font-size--base">
VA pays benefits on the first day of the month for the previous month.
Please wait at least 3 business days (Monday through Friday) before
reporting non-receipt of a payment.
</p>
</>
);
|
geonode/monitoring/frontend/monitoring/src/components/organisms/stats/index.js | francbartoli/geonode | /*
#########################################################################
#
# Copyright (C) 2019 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
*/
import React from 'react';
import HealthCheck from '../../cels/health-check';
import Uptime from '../../cels/uptime';
import Alerts from '../../cels/alerts';
import Errors from '../../cels/errors';
import styles from './styles';
class Stats extends React.Component {
render() {
return (
<div style={styles.content}>
<div style={styles.first}>
<HealthCheck />
<Uptime />
</div>
<div style={styles.second}>
<Alerts />
<Errors />
</div>
</div>
);
}
}
export default Stats;
|
packages/vulcan-core/lib/modules/containers/withComponents.js | VulcanJS/Vulcan | /**
* This HOC will load the global Components.
* If a "components" prop is passed, it will be merged with the global Components.
*
* This allow local replacement of global components, for example if
* you want a specific submit button but only for one specific form.
*/
import React from 'react';
import PropTypes from 'prop-types';
import { mergeWithComponents } from 'meteor/vulcan:lib';
const withComponents = C => {
const WrappedComponent = ({ components, formComponents, ...otherProps }) => {
//if (formComponents){
// console.warn('"formComponents" prop is deprecated, use "components" prop instead (same behaviour)');
//}
const Components = mergeWithComponents(components || formComponents);
return <C Components={Components} {...otherProps} />;
};
WrappedComponent.displayName = `withComponents(${C.displayName})`;
WrappedComponent.propTypes = {
formComponents: PropTypes.object,
components: PropTypes.object
};
return WrappedComponent;
};
export default withComponents; |
frontend/modules/index.js | RyanNoelk/OpenEats | import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { IntlProvider, addLocaleData } from 'react-intl'
import { Router, Route, Switch, Redirect } from 'react-router-dom'
import history from './common/history'
import store from './common/store'
// Load default locale data;
import en from 'react-intl/locale-data/en';
import es from 'react-intl/locale-data/es';
import de from 'react-intl/locale-data/de';
addLocaleData([...en, ...es, ...de]);
const messages = require('../locale/'+process.env.LOCALE+'.json');
// Load components
import NavBar from './header/containers/NavBar'
import Footer from './base/components/Footer'
import NotFound from './base/components/NotFound'
import Login from './account/containers/Login'
import News from './news/components/News'
import List from './list/containers/List'
import Browse from './browse/containers/Browse'
import Form from './recipe_form/containers/Form'
import RecipeView from './recipe/components/RecipeView'
// Load required polyfills
import {
browserSupportsAllFeatures,
loadPolyFills
} from './common/polyfill'
// Load in the base CSS
require("../node_modules/bootstrap-sass/assets/stylesheets/_bootstrap.scss");
require("./base/css/core.css");
require("./base/css/print.css");
const main = (
<IntlProvider locale={ process.env.LOCALE } messages={ messages }>
<Provider store={ store }>
<div>
<div id="content">
<Router history={ history }>
<div>
<NavBar />
<Switch>
<Route exact path='/' component={ News } />
<Route path='/news' component={ News } />
<Route path='/login' component={ Login } />
<Route path='/browse' component={ Browse } />
<Route path='/recipe/create' component={ Form } />
<Route path='/recipe/edit/:id' component={ Form } />
<Route path='/recipe/:recipe' component={ RecipeView } />
<Route path='/list/:listId' component={ List } />
<Route path='/list' component={ List } />
<Route path='/NotFound' component={ NotFound } />
<Redirect path="*" to="/NotFound" />
</Switch>
</div>
</Router>
</div>
<Footer />
</div>
</Provider>
</IntlProvider>
);
const entryPoint = () => {
render(main, document.getElementById('app'))
};
if (browserSupportsAllFeatures()) {
// Browsers that support all features run `entryPoint()` immediately.
entryPoint();
} else {
// All other browsers loads polyfills and then run `entryPoint()`.
loadPolyFills(entryPoint);
}
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/AsyncAwait.js | Clearcover/web-build | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
async function load() {
return [
{ id: 1, name: '1' },
{ id: 2, name: '2' },
{ id: 3, name: '3' },
{ id: 4, name: '4' },
];
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = await load();
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-async-await">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
app/user/profile/ProfileSkillList.js | in42/internship-portal | import React from 'react';
import PropTypes from 'prop-types';
import { Divider } from 'semantic-ui-react';
import EditableProfileSkillListItem from './EditableProfileSkillListItem';
import UnselectedProfileSkillListItem from './UnselectedProfileSkillListItem';
const ProfileSkillList = (props) => {
const editableSkillItems = props.skills.map(item => (
<EditableProfileSkillListItem
key={item}
skill={item}
removeSkill={props.removeSkill}
/>
));
const unselectedSkillItems = props.unselectedSkills.map(item => (
<UnselectedProfileSkillListItem
key={item}
skill={item}
restoreSkill={props.restoreSkill}
/>
));
return (
<div>
{ editableSkillItems }
<Divider />
{ unselectedSkillItems }
</div>
);
};
export default ProfileSkillList;
ProfileSkillList.propTypes = {
skills: PropTypes.arrayOf(PropTypes.string).isRequired,
restoreSkill: PropTypes.func.isRequired,
removeSkill: PropTypes.func.isRequired,
unselectedSkills: PropTypes.arrayOf(PropTypes.string).isRequired,
};
|
actor-apps/app-web/src/app/components/common/Favicon.react.js | boyley/actor-platform | import React from 'react';
export default class Fav extends React.Component {
static propTypes = {
path: React.PropTypes.string
}
constructor(props) {
super(props);
//// Create link element and it's attributes
//let favicon = document.createElement('link');
//let rel = document.createAttribute('rel');
//let type = document.createAttribute('type');
//let href = document.createAttribute('href');
//let id = document.createAttribute('id');
//
//// Set attributes values
//rel.value = 'icon';
//type.value = 'image/png';
//href.value = props.path;
//id.value = 'favicon';
//
//// Set attributes to favicon element
//favicon.setAttributeNode(rel);
//favicon.setAttributeNode(type);
//favicon.setAttributeNode(href);
//favicon.setAttributeNode(id);
//
//// Append favicon to head
//document.head.appendChild(favicon);
}
componentDidUpdate() {
// Clone created element and create href attribute
let updatedFavicon = document.getElementById('favicon').cloneNode(true);
let href = document.createAttribute('href');
// Set new href attribute
href.value = this.props.path;
updatedFavicon.setAttributeNode(href);
// Remove old and add new favicon
document.getElementById('favicon').remove();
document.head.appendChild(updatedFavicon);
}
render() {
return null;
}
}
|
node_modules/react-router/es/withRouter.js | LaurentEtienne/Kfe | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
import invariant from 'invariant';
import React from 'react';
import createReactClass from 'create-react-class';
import hoistStatics from 'hoist-non-react-statics';
import { ContextSubscriber } from './ContextUtils';
import { routerShape } from './PropTypes';
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
export default function withRouter(WrappedComponent, options) {
var withRef = options && options.withRef;
var WithRouter = createReactClass({
displayName: 'WithRouter',
mixins: [ContextSubscriber('router')],
contextTypes: { router: routerShape },
propTypes: { router: routerShape },
getWrappedInstance: function getWrappedInstance() {
!withRef ? process.env.NODE_ENV !== 'production' ? invariant(false, 'To access the wrapped instance, you need to specify ' + '`{ withRef: true }` as the second argument of the withRouter() call.') : invariant(false) : void 0;
return this.wrappedInstance;
},
render: function render() {
var _this = this;
var router = this.props.router || this.context.router;
if (!router) {
return React.createElement(WrappedComponent, this.props);
}
var params = router.params,
location = router.location,
routes = router.routes;
var props = _extends({}, this.props, { router: router, params: params, location: location, routes: routes });
if (withRef) {
props.ref = function (c) {
_this.wrappedInstance = c;
};
}
return React.createElement(WrappedComponent, props);
}
});
WithRouter.displayName = 'withRouter(' + getDisplayName(WrappedComponent) + ')';
WithRouter.WrappedComponent = WrappedComponent;
return hoistStatics(WithRouter, WrappedComponent);
} |
examples/star-wars/js/components/StarWarsShip.js | michaelchum/relay | /**
* This file provided by Facebook is for non-commercial testing and evaluation
* purposes only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import React from 'react';
import Relay from 'react-relay';
class StarWarsShip extends React.Component {
render() {
var {ship} = this.props;
return <div>{ship.name}</div>;
}
}
export default Relay.createContainer(StarWarsShip, {
fragments: {
ship: () => Relay.QL`
fragment on Ship {
name
}
`,
},
});
|
frontend/src/Artist/NoArtist.js | lidarr/Lidarr | import PropTypes from 'prop-types';
import React from 'react';
import Button from 'Components/Link/Button';
import { kinds } from 'Helpers/Props';
import styles from './NoArtist.css';
function NoArtist(props) {
const { totalItems } = props;
if (totalItems > 0) {
return (
<div>
<div className={styles.message}>
All artists are hidden due to the applied filter.
</div>
</div>
);
}
return (
<div>
<div className={styles.message}>
No artists found, to get started you'll want to add a new artist or album or add an existing library location (Root Folder) and update.
</div>
<div className={styles.buttonContainer}>
<Button
to="/settings/mediamanagement"
kind={kinds.PRIMARY}
>
Add Root Folder
</Button>
</div>
<div className={styles.buttonContainer}>
<Button
to="/add/search"
kind={kinds.PRIMARY}
>
Add New Artist
</Button>
</div>
</div>
);
}
NoArtist.propTypes = {
totalItems: PropTypes.number.isRequired
};
export default NoArtist;
|
docs/src/components/Demo/EditorConvertToHTML/index.js | jpuri/react-draft-wysiwyg | /* @flow */
import React, { Component } from 'react';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import Codemirror from 'react-codemirror';
class EditorConvertToHTML extends Component {
constructor(props) {
super(props);
const html = '<p>Hey this <strong>editor</strong> rocks 😀</p>';
const contentBlock = htmlToDraft(html);
if (contentBlock) {
const contentState = ContentState.createFromBlockArray(
contentBlock.contentBlocks
);
const editorState = EditorState.createWithContent(contentState);
this.state = {
editorState,
};
}
}
onEditorStateChange: Function = editorState => {
this.setState({
editorState,
});
};
render() {
const { editorState } = this.state;
return (
<div className="demo-section">
<h3>
1. Controlled editor component with conversion of content from and to
HTML
</h3>
<div className="demo-section-wrapper">
<div className="demo-editor-wrapper">
<Editor
editorState={editorState}
wrapperClassName="demo-wrapper"
editorClassName="demo-editor"
toolbar={{
inline: { inDropdown: true },
list: { inDropdown: true },
textAlign: { inDropdown: true },
link: { inDropdown: true },
history: { inDropdown: true },
}}
onEditorStateChange={this.onEditorStateChange}
/>
<textarea
disabled
className="demo-content no-focus"
value={draftToHtml(convertToRaw(editorState.getCurrentContent()))}
/>
</div>
<Codemirror
value={
"import React, { Component } from 'react';\n" +
"import { EditorState, convertToRaw } from 'draft-js';\n" +
"import { Editor } from 'react-draft-wysiwyg';\n" +
"import draftToHtml from 'draftjs-to-html';\n" +
"import htmlToDraft from 'html-to-draftjs';\n" +
'\n\n' +
'class EditorConvertToHTML extends Component {\n' +
' state = {\n' +
' editorState: EditorState.createEmpty(),\n' +
' }\n' +
'\n' +
' onEditorStateChange: Function = (editorState) => {\n' +
' this.setState({\n' +
' editorState,\n' +
' });\n' +
' };\n' +
'\n' +
' render() {\n' +
' const { editorState } = this.state;\n' +
' return (\n' +
' <div>\n' +
' <Editor\n' +
' editorState={editorState}\n' +
' wrapperClassName="demo-wrapper"\n' +
' editorClassName="demo-editor"\n' +
' onEditorStateChange={this.onEditorStateChange}\n' +
' />\n' +
' <textarea\n' +
' disabled\n' +
' value={draftToHtml(convertToRaw(editorState.getCurrentContent()))}\n' +
' />\n' +
' </div>\n' +
' );\n' +
' }\n' +
'}'
}
options={{
lineNumbers: true,
mode: 'jsx',
readOnly: true,
}}
/>
</div>
</div>
);
}
}
export default EditorConvertToHTML;
|
src/components/header.js | ericaporter/trending-hashtags | import React from 'react';
class Header extends React.Component {
render(){
return (
<div className="row">
<h2>Trending Hashtags</h2>
</div>
);
}
}
export default Header; |
app/javascript/mastodon/features/ui/index.js | anon5r/mastonon | import classNames from 'classnames';
import React from 'react';
import NotificationsContainer from './containers/notifications_container';
import PropTypes from 'prop-types';
import LoadingBarContainer from './containers/loading_bar_container';
import TabsBar from './components/tabs_bar';
import ModalContainer from './containers/modal_container';
import { connect } from 'react-redux';
import { Redirect, withRouter } from 'react-router-dom';
import { isMobile } from '../../is_mobile';
import { debounce } from 'lodash';
import { uploadCompose, resetCompose } from '../../actions/compose';
import { expandHomeTimeline } from '../../actions/timelines';
import { expandNotifications } from '../../actions/notifications';
import { clearHeight } from '../../actions/height_cache';
import { WrappedSwitch, WrappedRoute } from './util/react_router_helpers';
import UploadArea from './components/upload_area';
import ColumnsAreaContainer from './containers/columns_area_container';
import {
Compose,
Status,
GettingStarted,
KeyboardShortcuts,
PublicTimeline,
CommunityTimeline,
AccountTimeline,
AccountGallery,
HomeTimeline,
Followers,
Following,
Reblogs,
Favourites,
DirectTimeline,
HashtagTimeline,
Notifications,
FollowRequests,
GenericNotFound,
FavouritedStatuses,
ListTimeline,
Blocks,
DomainBlocks,
Mutes,
PinnedStatuses,
Lists,
} from './util/async-components';
import { HotKeys } from 'react-hotkeys';
import { me } from '../../initial_state';
import { defineMessages, injectIntl } from 'react-intl';
// Dummy import, to make sure that <Status /> ends up in the application bundle.
// Without this it ends up in ~8 very commonly used bundles.
import '../../components/status';
const messages = defineMessages({
beforeUnload: { id: 'ui.beforeunload', defaultMessage: 'Your draft will be lost if you leave Mastodon.' },
});
const mapStateToProps = state => ({
isComposing: state.getIn(['compose', 'is_composing']),
hasComposingText: state.getIn(['compose', 'text']) !== '',
dropdownMenuIsOpen: state.getIn(['dropdown_menu', 'openId']) !== null,
});
const keyMap = {
help: '?',
new: 'n',
search: 's',
forceNew: 'option+n',
focusColumn: ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
reply: 'r',
favourite: 'f',
boost: 'b',
mention: 'm',
open: ['enter', 'o'],
openProfile: 'p',
moveDown: ['down', 'j'],
moveUp: ['up', 'k'],
back: 'backspace',
goToHome: 'g h',
goToNotifications: 'g n',
goToLocal: 'g l',
goToFederated: 'g t',
goToDirect: 'g d',
goToStart: 'g s',
goToFavourites: 'g f',
goToPinned: 'g p',
goToProfile: 'g u',
goToBlocked: 'g b',
goToMuted: 'g m',
toggleHidden: 'x',
};
class SwitchingColumnsArea extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
location: PropTypes.object,
onLayoutChange: PropTypes.func.isRequired,
};
state = {
mobile: isMobile(window.innerWidth),
};
componentWillMount () {
window.addEventListener('resize', this.handleResize, { passive: true });
}
componentDidUpdate (prevProps) {
if (![this.props.location.pathname, '/'].includes(prevProps.location.pathname)) {
this.node.handleChildrenContentChange();
}
}
componentWillUnmount () {
window.removeEventListener('resize', this.handleResize);
}
handleResize = debounce(() => {
// The cached heights are no longer accurate, invalidate
this.props.onLayoutChange();
this.setState({ mobile: isMobile(window.innerWidth) });
}, 500, {
trailing: true,
});
setRef = c => {
this.node = c.getWrappedInstance().getWrappedInstance();
}
render () {
const { children } = this.props;
const { mobile } = this.state;
return (
<ColumnsAreaContainer ref={this.setRef} singleColumn={mobile}>
<WrappedSwitch>
<Redirect from='/' to='/getting-started' exact />
<WrappedRoute path='/getting-started' component={GettingStarted} content={children} />
<WrappedRoute path='/keyboard-shortcuts' component={KeyboardShortcuts} content={children} />
<WrappedRoute path='/timelines/home' component={HomeTimeline} content={children} />
<WrappedRoute path='/timelines/public' exact component={PublicTimeline} content={children} />
<WrappedRoute path='/timelines/public/media' component={PublicTimeline} content={children} componentParams={{ onlyMedia: true }} />
<WrappedRoute path='/timelines/public/local' exact component={CommunityTimeline} content={children} />
<WrappedRoute path='/timelines/public/local/media' component={CommunityTimeline} content={children} componentParams={{ onlyMedia: true }} />
<WrappedRoute path='/timelines/direct' component={DirectTimeline} content={children} />
<WrappedRoute path='/timelines/tag/:id' component={HashtagTimeline} content={children} />
<WrappedRoute path='/timelines/list/:id' component={ListTimeline} content={children} />
<WrappedRoute path='/notifications' component={Notifications} content={children} />
<WrappedRoute path='/favourites' component={FavouritedStatuses} content={children} />
<WrappedRoute path='/pinned' component={PinnedStatuses} content={children} />
<WrappedRoute path='/search' component={Compose} content={children} componentParams={{ isSearchPage: true }} />
<WrappedRoute path='/statuses/new' component={Compose} content={children} />
<WrappedRoute path='/statuses/:statusId' exact component={Status} content={children} />
<WrappedRoute path='/statuses/:statusId/reblogs' component={Reblogs} content={children} />
<WrappedRoute path='/statuses/:statusId/favourites' component={Favourites} content={children} />
<WrappedRoute path='/accounts/:accountId' exact component={AccountTimeline} content={children} />
<WrappedRoute path='/accounts/:accountId/with_replies' component={AccountTimeline} content={children} componentParams={{ withReplies: true }} />
<WrappedRoute path='/accounts/:accountId/followers' component={Followers} content={children} />
<WrappedRoute path='/accounts/:accountId/following' component={Following} content={children} />
<WrappedRoute path='/accounts/:accountId/media' component={AccountGallery} content={children} />
<WrappedRoute path='/follow_requests' component={FollowRequests} content={children} />
<WrappedRoute path='/blocks' component={Blocks} content={children} />
<WrappedRoute path='/domain_blocks' component={DomainBlocks} content={children} />
<WrappedRoute path='/mutes' component={Mutes} content={children} />
<WrappedRoute path='/lists' component={Lists} content={children} />
<WrappedRoute component={GenericNotFound} content={children} />
</WrappedSwitch>
</ColumnsAreaContainer>
);
}
}
@connect(mapStateToProps)
@injectIntl
@withRouter
export default class UI extends React.PureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
dispatch: PropTypes.func.isRequired,
children: PropTypes.node,
isComposing: PropTypes.bool,
hasComposingText: PropTypes.bool,
location: PropTypes.object,
intl: PropTypes.object.isRequired,
dropdownMenuIsOpen: PropTypes.bool,
};
state = {
draggingOver: false,
};
handleBeforeUnload = (e) => {
const { intl, isComposing, hasComposingText } = this.props;
if (isComposing && hasComposingText) {
// Setting returnValue to any string causes confirmation dialog.
// Many browsers no longer display this text to users,
// but we set user-friendly message for other browsers, e.g. Edge.
e.returnValue = intl.formatMessage(messages.beforeUnload);
}
}
handleLayoutChange = () => {
// The cached heights are no longer accurate, invalidate
this.props.dispatch(clearHeight());
}
handleDragEnter = (e) => {
e.preventDefault();
if (!this.dragTargets) {
this.dragTargets = [];
}
if (this.dragTargets.indexOf(e.target) === -1) {
this.dragTargets.push(e.target);
}
if (e.dataTransfer && e.dataTransfer.types.includes('Files')) {
this.setState({ draggingOver: true });
}
}
handleDragOver = (e) => {
e.preventDefault();
e.stopPropagation();
try {
e.dataTransfer.dropEffect = 'copy';
} catch (err) {
}
return false;
}
handleDrop = (e) => {
e.preventDefault();
this.setState({ draggingOver: false });
if (e.dataTransfer && e.dataTransfer.files.length === 1) {
this.props.dispatch(uploadCompose(e.dataTransfer.files));
}
}
handleDragLeave = (e) => {
e.preventDefault();
e.stopPropagation();
this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el));
if (this.dragTargets.length > 0) {
return;
}
this.setState({ draggingOver: false });
}
closeUploadModal = () => {
this.setState({ draggingOver: false });
}
handleServiceWorkerPostMessage = ({ data }) => {
if (data.type === 'navigate') {
this.context.router.history.push(data.path);
} else {
console.warn('Unknown message type:', data.type);
}
}
componentWillMount () {
window.addEventListener('beforeunload', this.handleBeforeUnload, false);
document.addEventListener('dragenter', this.handleDragEnter, false);
document.addEventListener('dragover', this.handleDragOver, false);
document.addEventListener('drop', this.handleDrop, false);
document.addEventListener('dragleave', this.handleDragLeave, false);
document.addEventListener('dragend', this.handleDragEnd, false);
if ('serviceWorker' in navigator) {
navigator.serviceWorker.addEventListener('message', this.handleServiceWorkerPostMessage);
}
this.props.dispatch(expandHomeTimeline());
this.props.dispatch(expandNotifications());
}
componentDidMount () {
this.hotkeys.__mousetrap__.stopCallback = (e, element) => {
return ['TEXTAREA', 'SELECT', 'INPUT'].includes(element.tagName);
};
}
componentWillUnmount () {
window.removeEventListener('beforeunload', this.handleBeforeUnload);
document.removeEventListener('dragenter', this.handleDragEnter);
document.removeEventListener('dragover', this.handleDragOver);
document.removeEventListener('drop', this.handleDrop);
document.removeEventListener('dragleave', this.handleDragLeave);
document.removeEventListener('dragend', this.handleDragEnd);
}
setRef = c => {
this.node = c;
}
handleHotkeyNew = e => {
e.preventDefault();
const element = this.node.querySelector('.compose-form__autosuggest-wrapper textarea');
if (element) {
element.focus();
}
}
handleHotkeySearch = e => {
e.preventDefault();
const element = this.node.querySelector('.search__input');
if (element) {
element.focus();
}
}
handleHotkeyForceNew = e => {
this.handleHotkeyNew(e);
this.props.dispatch(resetCompose());
}
handleHotkeyFocusColumn = e => {
const index = (e.key * 1) + 1; // First child is drawer, skip that
const column = this.node.querySelector(`.column:nth-child(${index})`);
if (column) {
const status = column.querySelector('.focusable');
if (status) {
status.focus();
}
}
}
handleHotkeyBack = () => {
if (window.history && window.history.length === 1) {
this.context.router.history.push('/');
} else {
this.context.router.history.goBack();
}
}
setHotkeysRef = c => {
this.hotkeys = c;
}
handleHotkeyToggleHelp = () => {
if (this.props.location.pathname === '/keyboard-shortcuts') {
this.context.router.history.goBack();
} else {
this.context.router.history.push('/keyboard-shortcuts');
}
}
handleHotkeyGoToHome = () => {
this.context.router.history.push('/timelines/home');
}
handleHotkeyGoToNotifications = () => {
this.context.router.history.push('/notifications');
}
handleHotkeyGoToLocal = () => {
this.context.router.history.push('/timelines/public/local');
}
handleHotkeyGoToFederated = () => {
this.context.router.history.push('/timelines/public');
}
handleHotkeyGoToDirect = () => {
this.context.router.history.push('/timelines/direct');
}
handleHotkeyGoToStart = () => {
this.context.router.history.push('/getting-started');
}
handleHotkeyGoToFavourites = () => {
this.context.router.history.push('/favourites');
}
handleHotkeyGoToPinned = () => {
this.context.router.history.push('/pinned');
}
handleHotkeyGoToProfile = () => {
this.context.router.history.push(`/accounts/${me}`);
}
handleHotkeyGoToBlocked = () => {
this.context.router.history.push('/blocks');
}
handleHotkeyGoToMuted = () => {
this.context.router.history.push('/mutes');
}
render () {
const { draggingOver } = this.state;
const { children, isComposing, location, dropdownMenuIsOpen } = this.props;
const handlers = {
help: this.handleHotkeyToggleHelp,
new: this.handleHotkeyNew,
search: this.handleHotkeySearch,
forceNew: this.handleHotkeyForceNew,
focusColumn: this.handleHotkeyFocusColumn,
back: this.handleHotkeyBack,
goToHome: this.handleHotkeyGoToHome,
goToNotifications: this.handleHotkeyGoToNotifications,
goToLocal: this.handleHotkeyGoToLocal,
goToFederated: this.handleHotkeyGoToFederated,
goToDirect: this.handleHotkeyGoToDirect,
goToStart: this.handleHotkeyGoToStart,
goToFavourites: this.handleHotkeyGoToFavourites,
goToPinned: this.handleHotkeyGoToPinned,
goToProfile: this.handleHotkeyGoToProfile,
goToBlocked: this.handleHotkeyGoToBlocked,
goToMuted: this.handleHotkeyGoToMuted,
};
return (
<HotKeys keyMap={keyMap} handlers={handlers} ref={this.setHotkeysRef}>
<div className={classNames('ui', { 'is-composing': isComposing })} ref={this.setRef} style={{ pointerEvents: dropdownMenuIsOpen ? 'none' : null }}>
<TabsBar />
<SwitchingColumnsArea location={location} onLayoutChange={this.handleLayoutChange}>
{children}
</SwitchingColumnsArea>
<NotificationsContainer />
<LoadingBarContainer className='loading-bar' />
<ModalContainer />
<UploadArea active={draggingOver} onClose={this.closeUploadModal} />
</div>
</HotKeys>
);
}
}
|
site/src/components/GetSupportButton.js | LastCallMedia/Mannequin | import React from 'react'
import GithubIcon from 'react-icons/lib/go/mark-github'
import './GetSupportButton.scss'
export default function GetSupportButton() {
return (
<a
className="GetSupportButton"
href="https://github.com/LastCallMedia/Mannequin/issues"
>
<GithubIcon className="icon" />
<span className="text">Get Support on Github</span>
</a>
)
}
|
js/jqwidgets/demos/react/app/scheduler/appointmentstatuses/app.js | luissancheza/sice | import React from 'react';
import ReactDOM from 'react-dom';
import JqxScheduler from '../../../jqwidgets-react/react_jqxscheduler.js';
class App extends React.Component {
componentDidMount() {
this.refs.myScheduler.ensureAppointmentVisible('id1');
}
render() {
let appointments = new Array();
let appointment1 = {
id: 'id1',
description: '',
location: '',
subject: 'Appointment with the dentist',
status: 'tentative',
calendar: 'Paula',
start: new Date(2016, 10, 23, 9, 0, 0),
end: new Date(2016, 10, 23, 11, 0, 0)
}
let appointment2 = {
id: 'id2',
description: '',
location: '',
subject: 'Business Plans Review',
calendar: 'Tom',
status: 'tentative',
start: new Date(2016, 10, 24, 10, 0, 0),
end: new Date(2016, 10, 24, 15, 0, 0)
}
let appointment3 = {
id: 'id3',
description: '',
location: '',
subject: 'Lunch with Monica',
status: 'tentative',
calendar: 'Chris',
start: new Date(2016, 10, 27, 11, 0, 0),
end: new Date(2016, 10, 27, 13, 0, 0)
}
let appointment4 = {
id: 'id4',
description: '',
location: '',
subject: 'Meeting John',
status: 'free',
calendar: 'Paula',
start: new Date(2016, 10, 23, 16, 0, 0),
end: new Date(2016, 10, 23, 18, 0, 0)
}
let appointment5 = {
id: 'id5',
description: '',
location: '',
subject: 'Parent-Teacher Conference',
status: 'outOfOffice',
calendar: 'Chris',
start: new Date(2016, 10, 25, 15, 0, 0),
end: new Date(2016, 10, 25, 17, 0, 0)
}
let appointment6 = {
id: 'id6',
description: '',
location: '',
subject: 'Interview with Nancy',
status: 'busy',
calendar: 'Tom',
start: new Date(2016, 10, 26, 14, 0, 0),
end: new Date(2016, 10, 26, 16, 0, 0)
}
appointments.push(appointment1);
appointments.push(appointment2);
appointments.push(appointment3);
appointments.push(appointment4);
appointments.push(appointment5);
appointments.push(appointment6);
// prepare the data
let source =
{
dataType: 'array',
dataFields: [
{ name: 'id', type: 'string' },
{ name: 'description', type: 'string' },
{ name: 'location', type: 'string' },
{ name: 'subject', type: 'string' },
{ name: 'status', type: 'string' },
{ name: 'calendar', type: 'string' },
{ name: 'start', type: 'date' },
{ name: 'end', type: 'date' }
],
id: 'id',
localData: appointments
};
let adapter = new $.jqx.dataAdapter(source);
let resources =
{
colorScheme: 'scheme05',
dataField: 'calendar',
source: new $.jqx.dataAdapter(source)
};
let appointmentDataFields =
{
from: 'start',
to: 'end',
id: 'id',
status: 'status',
description: 'description',
location: 'place',
subject: 'subject',
resourceId: 'calendar'
};
let views =
[
'dayView',
'weekView',
'monthView'
];
return (
<JqxScheduler ref='myScheduler'
width={850} height={600} source={adapter}
date={new $.jqx.date(2016, 11, 23)} showLegend={true}
view={1} resources={resources} views={views}
appointmentDataFields={appointmentDataFields}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
server/sonar-web/src/main/js/apps/overview/main/BugsAndVulnerabilities.js | lbndev/sonarqube | /*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
import { Link } from 'react-router';
import enhance from './enhance';
import LeakPeriodLegend from '../components/LeakPeriodLegend';
import { getMetricName } from '../helpers/metrics';
import { translate } from '../../../helpers/l10n';
import BugIcon from '../../../components/ui/BugIcon';
import VulnerabilityIcon from '../../../components/ui/VulnerabilityIcon';
class BugsAndVulnerabilities extends React.Component {
renderHeader() {
const { component } = this.props;
const bugsDomainUrl = {
pathname: '/component_measures/domain/Reliability',
query: { id: component.key }
};
const vulnerabilitiesDomainUrl = {
pathname: '/component_measures/domain/Security',
query: { id: component.key }
};
return (
<div className="overview-card-header">
<div className="overview-title">
<Link to={bugsDomainUrl}>{translate('metric.bugs.name')}</Link>
{' & '}
<Link to={vulnerabilitiesDomainUrl}>{translate('metric.vulnerabilities.name')}</Link>
</div>
</div>
);
}
renderLeak() {
const { leakPeriod } = this.props;
if (leakPeriod == null) {
return null;
}
return (
<div className="overview-domain-leak">
<LeakPeriodLegend period={leakPeriod} />
<div className="overview-domain-measures">
<div className="overview-domain-measure">
<div className="overview-domain-measure-value">
<span style={{ marginLeft: 30 }}>
{this.props.renderIssues('new_bugs', 'BUG')}
</span>
{this.props.renderRating('new_reliability_rating')}
</div>
<div className="overview-domain-measure-label">
<span className="little-spacer-right"><BugIcon /></span>
{getMetricName('new_bugs')}
</div>
</div>
<div className="overview-domain-measure">
<div className="overview-domain-measure-value">
<span style={{ marginLeft: 30 }}>
{this.props.renderIssues('new_vulnerabilities', 'VULNERABILITY')}
</span>
{this.props.renderRating('new_security_rating')}
</div>
<div className="overview-domain-measure-label">
<span className="little-spacer-right"><VulnerabilityIcon /></span>
{getMetricName('new_vulnerabilities')}
</div>
</div>
</div>
</div>
);
}
renderNutshell() {
return (
<div className="overview-domain-nutshell">
<div className="overview-domain-measures">
<div className="overview-domain-measure">
<div className="display-inline-block text-middle" style={{ paddingLeft: 56 }}>
<div className="overview-domain-measure-value">
{this.props.renderIssues('bugs', 'BUG')}
{this.props.renderRating('reliability_rating')}
</div>
<div className="overview-domain-measure-label">
<span className="little-spacer-right"><BugIcon /></span>
{getMetricName('bugs')}
</div>
</div>
</div>
<div className="overview-domain-measure">
<div className="display-inline-block text-middle">
<div className="overview-domain-measure-value">
{this.props.renderIssues('vulnerabilities', 'VULNERABILITY')}
{this.props.renderRating('security_rating')}
</div>
<div className="overview-domain-measure-label">
<span className="little-spacer-right"><VulnerabilityIcon /></span>
{getMetricName('vulnerabilities')}
</div>
</div>
</div>
</div>
</div>
);
}
render() {
return (
<div className="overview-card overview-card-special">
{this.renderHeader()}
<div className="overview-domain-panel">
{this.renderNutshell()}
{this.renderLeak()}
</div>
</div>
);
}
}
export default enhance(BugsAndVulnerabilities);
|
src/svg-icons/device/signal-wifi-4-bar.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalWifi4Bar = (props) => (
<SvgIcon {...props}>
<path d="M12.01 21.49L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l11.63 14.49.01.01.01-.01z"/>
</SvgIcon>
);
DeviceSignalWifi4Bar = pure(DeviceSignalWifi4Bar);
DeviceSignalWifi4Bar.displayName = 'DeviceSignalWifi4Bar';
export default DeviceSignalWifi4Bar;
|
packages/demos/todomvc/src/components/Footer/index.js | christianalfoni/cerebral | import React from 'react'
import { connect } from '@cerebral/react'
import { state, signal } from 'cerebral/tags'
import counts from '../../computed/counts'
import classnames from 'classnames'
const filters = ['All', 'Active', 'Completed']
export default connect(
{
filter: state`filter`,
counts,
filterClicked: signal`filterClicked`,
clearCompletedClicked: signal`clearCompletedClicked`,
},
function Footer({ filter, counts, filterClicked, clearCompletedClicked }) {
return (
<footer className="footer">
<span className="todo-count">
<strong>
{counts.remaining} {counts.remaining === 1 ? 'item' : 'items'} left
</strong>
</span>
<ul className="filters">
{filters.map(filterName =>
<li key={filterName}>
<a
onClick={() =>
filterClicked({ filter: filterName.toLowerCase() })}
className={classnames({
selected: filter === filterName.toLowerCase(),
})}
>
{filterName}
</a>
</li>
)}
</ul>
{!!counts.completed &&
<button
className="clear-completed"
onClick={() => clearCompletedClicked()}
>
Clear completed ({counts.completed})
</button>}
</footer>
)
}
)
|
src/components/Button/index.js | itsravenous/escape-the-board-room | import React from 'react';
import './style.scss';
const Button = (props) => (
<button
{...props}
className={props.className ? `button ${props.className}` : `button`}
>
{props.children}
</button>
);
Button.propTypes = {
children: React.PropTypes.node,
className: React.PropTypes.string,
};
export default Button;
|
client/routes/Items/components/ItemsPanel.js | patzj/ims | import React from 'react';
import ItemsTable from '../containers/ItemsTable';
export const ItemsPanel = () => {
return (
<div className="col-xs-10 col-xs-offset-1">
<h2 className="pull-left"><span className="glyphicon glyphicon-object-align-bottom"></span> Items</h2>
<div className="pull-right" style={{marginTop: '20px'}}>
<button className="btn btn-success" data-toggle="modal" data-target="#new-item-modal">
<span className="glyphicon glyphicon-plus-sign"></span> New Item
</button>
</div>
<ItemsTable />
</div>
);
};
export default ItemsPanel;
|
app/src/components/Info.js | wtfil/google-music-unofficial-client | import React from 'react';
import formatTime from '../utils/formatTime';
export default class Info extends React.Component {
render() {
const {onLoad, title, tracks, subTitle, image, year, description} = this.props;
const duration = tracks.reduce((summ, item) => summ + item.duration, 0);
const attrs = [year, tracks.length + ' songs', formatTime(duration)]
.filter(Boolean)
.join(' • ');
return <div className='info'>
<img className='info__image' src={image}/>
<div className='info__content'>
<span className='info__title'>{title}</span>
<span className='info__sub-title'>{subTitle}</span>
<span className='info__attrs'>{attrs}</span>
<p className='info__description'>{description}</p>
{onLoad &&
<i onClick={onLoad}className='material-icons pointer'>get_app</i>
}
</div>
</div>
}
}
|
common/components/FavoritePhotoButton.js | jhabdas/12roads | import React from 'react'
import IconButton from 'material-ui/IconButton'
import StarBorder from 'material-ui/svg-icons/toggle/star-border'
import Star from 'material-ui/svg-icons/toggle/star'
const FavoritePhotoButton = (props) => (
<IconButton
tooltip='Favorite Photo'
tooltipPosition='top-left'
touch
>
<StarBorder color='white' />
</IconButton>
)
export default FavoritePhotoButton
|
docs/app/Examples/addons/Radio/index.js | vageeshb/Semantic-UI-React | import React from 'react'
import Types from './Types'
import States from './States'
import Variations from './Variations'
const RadioExamples = () => (
<div>
<Types />
<States />
<Variations />
</div>
)
export default RadioExamples
|
ui/src/containers/DeleteConfirm/index.js | LearningLocker/learninglocker | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Portal from 'react-portal';
import { connect } from 'react-redux';
import { lowerCase } from 'lodash';
import { deleteModel } from 'ui/redux/modules/models';
class DeleteConfirm extends Component {
static propTypes = {
isOpened: PropTypes.bool,
onClickClose: PropTypes.func,
deleteModel: PropTypes.func,
schema: PropTypes.string,
id: PropTypes.string,
onDelete: PropTypes.func,
onDeletedModel: PropTypes.func,
renderMessage: PropTypes.func
}
static defaultProps = {
isOpened: false,
onDeletedModel: () => null,
renderMessage: ({ schema }) =>
(<span>This will delete the {lowerCase(schema)} <b>permanently</b>. Are you sure?</span>)
}
onClick = (e) => {
e.preventDefault();
e.stopPropagation();
if (this.props.onDelete) {
this.props.onDelete(this.props);
} else {
this.props.deleteModel({
schema: this.props.schema,
id: this.props.id,
});
this.props.onClickClose();
}
this.props.onDeletedModel();
this.props.onClickClose();
}
render = () => {
const { isOpened, onClickClose } = this.props;
return (
<Portal isOpened={isOpened}>
<span>
<div className="modal animated fast fadeIn">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header modal-header-bg">
<button type="button" className="close" aria-label="Close" onClick={onClickClose.bind(null)}><span aria-hidden="true">×</span></button>
<h4 className="modal-title">Confirm delete</h4>
</div>
<div
className="modal-body clearfix"
style={{ maxHeight: '500px', overflow: 'auto', textAlign: 'center' }}>
{this.props.renderMessage(this.props)}
</div>
<div className="modal-footer" style={{ textAlign: 'center' }}>
<a
onClick={this.onClick.bind(null)}
className="btn btn-primary btn-sm">
<i className="icon ion-checkmark" /> Confirm
</a>
<a
onClick={onClickClose.bind(null)}
className="btn btn-primary btn-sm">
<i className="icon ion-close-round" /> Cancel
</a>
</div>
</div>
</div>
<div className="modal-backdrop" onClick={onClickClose.bind(null)} />
</div>
</span>
</Portal>
);
}
}
export default connect(() => ({}), { deleteModel })(DeleteConfirm);
|
src/features/DocumentationModal/ShowDocsButton.js | erhathaway/cellular_automata | import React from 'react';
import styled from 'react-emotion';
const Container = styled('button')`
position: fixed;
font-family: 'Roboto', sans-serif;
font-weight: lighter;
font-size: 20px;
outline: none;
background: none;
border: 1px solid rgba(56, 56, 56, 0.4);
border-radius: 50%;
color: #ffffff36;
background-color: #353535;
z-index: 999;
display: none;
box-shadow: 0 8px 10px 1px rgba(0, 0, 0, .14), 0 3px 14px 2px rgba(0, 0, 0, .12), 0 5px 5px -3px rgba(0, 0, 0, .2);
@media (max-width: 800px) {
display: initial;
right: 75px;
bottom: 55px;
width: 60px;
height: 60px;
}
@media (max-width: 500px) {
bottom: 40px;
right: 60px;
width: 50px;
height: 50px;
}
&:hover {
color: green;
cursor: pointer;
}
`;
export default ({ onClick }) => (
<Container onClick={onClick}>
<i className="fas fa-arrows-alt-v" />
</Container>
)
|
src/App.js | babizhu/redux-lesson | import React, { Component } from 'react';
import { NICE, SUPER_NICE } from './colors';
import { createStore } from 'redux'
import { Provider } from 'react-redux'
//import {run} from './base/app';
//import {run} from './mutireducer/app';
import {run} from './async/base/app';
import rootReducer from './sap/rootReducer';
import Sap from './sap/app'
run();
//import TodoApp from './todos/TodoApp';
//
//import todoApp from './todos/reducers/'
//import rootApp from './mutireducer/reducers/'
//console.log( "rootApp = " + rootApp );
//run();
let store = createStore(rootReducer);
export class App extends Component {
render() {
return (
<Provider store={store}>
<Sap/>
</Provider>
);
}
} |
src/components/redux.js | Mahi22/MedTantra | // Component that demonstrates using a part of the Redux store
// outside of Apollo. We can use config.addReducer(key, reducer) in `src/app.js`
// to add custom Redux reducers
// ----------------------
// IMPORTS
/* NPM */
import React from 'react';
import PropTypes from 'prop-types';
// HOC/decorator to listen to Redux store state
import { connect } from 'react-redux';
// ----------------------
// @connect accepts a function that takes the full Redux state, and then
// returns the portion of state that our component cares about. In this example,
// we're listening to `state.counter`, which we can show inside the component
@connect(state => ({ counter: state.counter }))
export default class ReduxCounter extends React.PureComponent {
static propTypes = {
counter: PropTypes.shape({
count: PropTypes.number.isRequired,
}),
};
static defaultProps = {
counter: {
count: 0,
},
}
// Trigger the `INCREMENT_COUNTER` action in Redux, to add 1 to the total.
// Note: by using the `= () {}` format, we're implicitly binding the component
// to `this`, which is why we can use @connect's `.dispatch()` function that's
// passed in as a prop
triggerIncrement = () => {
this.props.dispatch({
type: 'INCREMENT_COUNTER',
});
}
render() {
const { count } = this.props.counter;
return (
<div>
<h2>Listening to Redux counter: {count}</h2>
<button onClick={this.triggerIncrement}>Increment</button>
</div>
);
}
}
|
pollard/components/AddedSongsDisplay.js | spncrlkt/pollard | import React, { Component } from 'react';
import DraggableSong from './DraggableSong';
export default class AddedSongsDisplay extends Component {
getCurrentlyPlayingSongIdx(songs) {
for (var idx = 0; idx < songs.size; idx++) {
if (songs.getIn([idx, 'played'])) {
return idx;
}
}
return -1;
}
render() {
const {
songs,
...rest,
} = this.props;
const playingSongIdx = this.getCurrentlyPlayingSongIdx(songs);
return (
<div id='AddedSongsDisplay'>
{ songs.map((song, idx) => {
const key = song.get('_id') ?
song.get('_id') :
song.get('clientID');
return (
<DraggableSong
key={ key }
idx={ idx }
playingSongIdx={ playingSongIdx }
song={ song }
{...rest} />
);
})}
</div>
);
}
}
|
packages/@lyra/form-builder/src/inputs/BlockEditor/Editor.js | VegaPublish/vega-studio | // @flow
import type {
Block,
BlockContentFeatures,
Marker,
SlateChange,
SlateComponentProps,
SlateMarkProps,
SlateValue,
Type
} from './typeDefs'
import type {Node} from 'react'
import React from 'react'
import ReactDOM from 'react-dom'
import SoftBreakPlugin from 'slate-soft-break'
import {findDOMNode, Editor as SlateEditor} from 'slate-react'
import {isEqual} from 'lodash'
import {isKeyHotkey} from 'is-hotkey'
import {EDITOR_DEFAULT_BLOCK_TYPE, editorValueToBlocks} from '@lyra/block-tools'
import insertBlockOnEnter from 'slate-insert-block-on-enter'
import onPasteFromPart from 'part:@lyra/form-builder/input/block-editor/on-paste?'
import onCopy from 'part:@lyra/form-builder/input/block-editor/on-copy?'
import {VALUE_TO_JSON_OPTS} from './utils/changeToPatches'
import {hasItemFocus} from '../../utils/pathUtils'
import createNodeValidator from './utils/createNodeValidator'
import findInlineByAnnotationKey from './utils/findInlineByAnnotationKey'
import PatchEvent, {insert} from '../../../PatchEvent'
import ListItemOnEnterKeyPlugin from './plugins/ListItemOnEnterKeyPlugin'
import ListItemOnTabKeyPlugin from './plugins/ListItemOnTabKeyPlugin'
import OnDropPlugin from './plugins/OnDropPlugin'
import PastePlugin from './plugins/PastePlugin'
import SetMarksOnKeyComboPlugin from './plugins/SetMarksOnKeyComboPlugin'
import TextBlockOnEnterKeyPlugin from './plugins/TextBlockOnEnterKeyPlugin'
import UpdateCustomNodesPlugin from './plugins/UpdateCustomNodesPlugin'
import UndoRedoPlugin from './plugins/UndoRedoPlugin'
import BlockObject from './nodes/BlockObject'
import ContentBlock from './nodes/ContentBlock'
import Decorator from './nodes/Decorator'
import InlineObject from './nodes/InlineObject'
import Span from './nodes/Span'
import styles from './styles/Editor.css'
type Props = {
blockContentFeatures: BlockContentFeatures,
editorValue: SlateValue,
fullscreen: boolean,
markers: Marker[],
onBlur: (nextPath: []) => void,
onChange: (change: SlateChange) => void,
onEditorBlur: void => void,
onEditorFocus: void => void,
onFocus: (nextPath: []) => void,
onFormBuilderInputBlur: (nextPath: []) => void,
onFormBuilderInputFocus: (nextPath: []) => void,
onPaste?: (
event: SyntheticEvent,
path: [],
type: Type,
value: ?Value
) => {insert?: Value, path?: []},
onPatch: (event: PatchEvent) => void,
onToggleFullScreen: void => void,
readOnly?: boolean,
renderBlockActions?: (block: Block) => React.Node,
renderCustomMarkers?: (Marker[]) => React.Node,
setFocus: void => void,
type: Type,
undoRedoStack: {undo: [], redo: []},
value: Block[]
}
export default class Editor extends React.Component<Props> {
_blockDragMarker: ?HTMLDivElement
_blockActionsMap = {}
_editor: ?(Node & SlateEditor) = null
_plugins = []
constructor(props: Props) {
super(props)
this._plugins = [
ListItemOnEnterKeyPlugin({defaultBlock: EDITOR_DEFAULT_BLOCK_TYPE}),
ListItemOnTabKeyPlugin(),
TextBlockOnEnterKeyPlugin({defaultBlock: EDITOR_DEFAULT_BLOCK_TYPE}),
SetMarksOnKeyComboPlugin({
decorators: props.blockContentFeatures.decorators.map(
item => item.value
)
}),
SoftBreakPlugin({
onlyIn: [EDITOR_DEFAULT_BLOCK_TYPE.type],
shift: true
}),
PastePlugin({blockContentType: props.type}),
insertBlockOnEnter(EDITOR_DEFAULT_BLOCK_TYPE),
UpdateCustomNodesPlugin(),
OnDropPlugin(),
UndoRedoPlugin({
stack: props.undoRedoStack,
onChange: props.onChange,
editorValue: props.editorValue,
blockContentType: props.type
})
]
this._validateNode = createNodeValidator(props.type, this.getValue)
}
componentDidMount() {
const {editorValue, focusPath} = this.props
if ((focusPath || []).length) {
const block = editorValue.document.getDescendant(focusPath[0]._key)
if (!block) {
return
}
// Wait for things to get finshed rendered before scrolling there
setTimeout(
() =>
window.requestAnimationFrame(() => {
const element = findDOMNode(block)
element.scrollIntoView({
behavior: 'instant',
block: 'center',
inline: 'nearest'
})
}),
0
)
}
}
// When focusPath has changed, but the editorValue has another focusBlock,
// select the block according to the focusPath and scroll there
// eslint-disable-next-line complexity
componentWillReceiveProps(nextProps: Props) {
const {focusPath, editorValue, onChange, readOnly} = nextProps
if (!focusPath || focusPath.length === 0) {
return
}
const focusPathIsSingleBlock =
editorValue.focusBlock &&
isEqual(focusPath, [{_key: editorValue.focusBlock.key}])
const focusPathChanged = !isEqual(this.props.focusPath, nextProps.focusPath)
const change = editorValue.change()
const block = editorValue.document.getDescendant(focusPath[0]._key)
let inline
if (focusPathChanged && !focusPathIsSingleBlock) {
if (focusPath[1] && focusPath[1] === 'children' && focusPath[2]) {
// Inline object
inline = editorValue.document.getDescendant(focusPath[2]._key)
this.scrollIntoView(change, inline)
} else if (
// Annotation
focusPath[1] &&
focusPath[1] === 'markDefs' &&
focusPath[2] &&
(inline = findInlineByAnnotationKey(focusPath[2]._key, block))
) {
this.scrollIntoView(change, inline)
} else if (block) {
// Regular block
this.scrollIntoView(change, block)
}
} else if (focusPathChanged && !readOnly) {
// Must be here to set focus after editing interfaces are closed
change.focus()
onChange(change)
}
}
scrollIntoView(change, node) {
const {onChange, readOnly} = this.props
const element = findDOMNode(node)
element.scrollIntoView({
behavior: 'instant',
block: 'center',
inline: 'nearest'
})
if (!readOnly) {
change.collapseToEndOf(node)
onChange(change)
}
}
// When user changes the selection in the editor, update focusPath accordingly.
handleChange = (change: slateChange) => {
const {onChange, onFocus, focusPath} = this.props
const {focusBlock} = change.value
const path = []
if (focusBlock) {
path.push({_key: focusBlock.key})
}
if (path.length && focusPath && focusPath.length === 1) {
return onChange(change, () => onFocus(path))
}
return onChange(change)
}
handleEditorFocus = () => {
const {setFocus} = this.props
setFocus()
}
getValue = () => {
return this.props.value
}
getEditor() {
return this._editor
}
refEditor = (editor: ?SlateEditor) => {
this._editor = editor
}
handleShowBlockDragMarker = (pos: string, node: HTMLDivElement) => {
const editorDOMNode = ReactDOM.findDOMNode(this._editor)
if (editorDOMNode instanceof HTMLElement) {
const editorRect = editorDOMNode.getBoundingClientRect()
const elemRect = node.getBoundingClientRect()
const topPos = elemRect.top - editorRect.top
const bottomPos = topPos + (elemRect.bottom - elemRect.top)
const top =
pos === 'after'
? `${parseInt(bottomPos, 10)}px`
: `${parseInt(topPos, 10)}px`
if (this._blockDragMarker) {
this._blockDragMarker.style.display = 'block'
this._blockDragMarker.style.top = top
}
}
}
handleHideBlockDragMarker = () => {
if (this._blockDragMarker) {
this._blockDragMarker.style.display = 'none'
}
}
handlePaste = event => {
const {focusPath, onPatch, value, type} = this.props
const onPaste = this.props.onPaste || onPasteFromPart
if (onPaste) {
const {editorValue} = this.props
const change = editorValue.change()
const {focusBlock, focusKey, focusText, focusInline} = change.value
const path = []
if (focusBlock) {
path.push({_key: focusBlock.key})
}
if (focusInline || focusText) {
path.push('children')
path.push({_key: focusKey})
}
const result = onPaste({event, value, path, type})
if (result && result.insert) {
onPatch(
PatchEvent.from([
insert([result.insert], 'after', result.path || focusPath)
])
)
return result.insert
}
}
return undefined
}
handleCopy = event => {
if (onCopy) {
return onCopy({event})
}
return undefined
}
handleOnKeyDown = event => {
const isFullscreenKey = isKeyHotkey('mod+enter')
const {onToggleFullScreen} = this.props
if (isFullscreenKey(event)) {
event.preventDefault()
event.stopPropagation()
onToggleFullScreen()
return true
}
return undefined
}
refBlockDragMarker = (blockDragMarker: ?HTMLDivElement) => {
this._blockDragMarker = blockDragMarker
}
renderNode = (props: SlateComponentProps) => {
const {
blockContentFeatures,
editorValue,
focusPath,
markers,
onChange,
onFocus,
onPatch,
readOnly,
value,
renderCustomMarkers,
type
} = this.props
const {node} = props
let childMarkers = markers
.filter(marker => marker.path.length > 0)
.filter(marker => marker.path[0]._key === node.data.get('_key'))
let ObjectClass = BlockObject
let ObjectType = blockContentFeatures.types.blockObjects.find(
memberType => memberType.name === node.type
)
if (node.object === 'inline') {
ObjectClass = InlineObject
ObjectType = blockContentFeatures.types.inlineObjects.find(
memberType => memberType.name === node.type
)
childMarkers = markers.filter(
marker =>
marker.path[2] && marker.path[2]._key === node.data.get('_key')
)
}
if (node.type === 'span') {
childMarkers = markers.filter(
marker =>
marker.path[2] && marker.path[2]._key === node.data.get('_key')
)
// Add any markers for related markDefs here as well
let annotations
if ((annotations = node.data.get('annotations'))) {
const block = editorValue.document.getParent(node.key)
Object.keys(annotations).forEach(key => {
childMarkers = childMarkers.concat(
markers.filter(
marker =>
marker.path[0]._key === block.key &&
marker.path[1] === 'markDefs' &&
marker.path[2]._key === annotations[key]._key
)
)
})
}
}
// Set prop on blocks that are included in focusPath
let hasFormBuilderFocus = false
if (node.object === 'block') {
hasFormBuilderFocus = focusPath
? hasItemFocus(focusPath, {_key: node.key})
: false
}
switch (node.type) {
case 'contentBlock':
return (
<ContentBlock
{...props}
editorValue={editorValue}
onChange={onChange}
onFocus={onFocus}
blockContentFeatures={blockContentFeatures}
hasFormBuilderFocus={hasFormBuilderFocus}
markers={childMarkers}
readOnly={readOnly}
blockActions={this._blockActionsMap[node.key]}
renderCustomMarkers={renderCustomMarkers}
block={
value
? value.find(blk => blk._key === node.key)
: editorValueToBlocks(
{document: {nodes: [node.toJSON(VALUE_TO_JSON_OPTS)]}},
type
)[0]
}
/>
)
case 'span':
return (
<Span
attributes={props.attributes}
blockContentFeatures={blockContentFeatures}
editorValue={editorValue}
markers={childMarkers}
node={props.node}
onChange={onChange}
onFocus={onFocus}
onPatch={onPatch}
readOnly={readOnly}
type={blockContentFeatures.types.span}
>
{props.children}
</Span>
)
default:
return (
<ObjectClass
attributes={props.attributes}
blockContentFeatures={blockContentFeatures}
editor={props.editor}
editorValue={editorValue}
hasFormBuilderFocus={hasFormBuilderFocus}
isSelected={props.isSelected}
markers={childMarkers}
node={props.node}
onChange={onChange}
onDrag={this.handleDrag}
onFocus={onFocus}
onHideBlockDragMarker={this.handleHideBlockDragMarker}
onPatch={onPatch}
onShowBlockDragMarker={this.handleShowBlockDragMarker}
readOnly={readOnly}
blockActions={this._blockActionsMap[node.key]}
renderCustomMarkers={renderCustomMarkers}
type={ObjectType}
/>
)
}
}
renderMark = (props: SlateMarkProps) => {
const {blockContentFeatures} = this.props
const type = props.mark.type
const decorator = blockContentFeatures.decorators.find(
item => item.value === type
)
const CustomComponent =
decorator && decorator.blockEditor && decorator.blockEditor.render
? decorator.blockEditor.render
: null
if (CustomComponent) {
return <CustomComponent {...props} />
}
return decorator ? <Decorator {...props} /> : null
}
render() {
const {
editorValue,
fullscreen,
readOnly,
markers,
renderBlockActions,
value
} = this.props
const hasMarkers =
markers.filter(marker => marker.path.length > 0).length > 0
// Figure out if we have any block actions
let hasBlockActions = false
if (renderBlockActions && value) {
this._blockActionsMap = {}
value.forEach(block => {
const actions = renderBlockActions(block)
if (actions) {
this._blockActionsMap[block._key] = actions
}
})
hasBlockActions = Object.keys(this._blockActionsMap).length > 0
}
const classNames = [
styles.root,
(hasBlockActions || hasMarkers) && styles.hasBlockExtras,
fullscreen ? styles.fullscreen : null
].filter(Boolean)
return (
<div className={classNames.join(' ')}>
<SlateEditor
spellCheck={false}
className={styles.editor}
ref={this.refEditor}
value={editorValue}
onChange={this.handleChange}
onFocus={this.handleEditorFocus}
onCopy={this.handleCopy}
onPaste={this.handlePaste}
onKeyDown={this.handleOnKeyDown}
validateNode={this._validateNode}
plugins={this._plugins}
readOnly={readOnly}
renderNode={this.renderNode}
renderMark={this.renderMark}
/>
<div
className={styles.blockDragMarker}
ref={this.refBlockDragMarker}
style={{display: 'none'}}
/>
</div>
)
}
}
|
src/svg-icons/device/signal-cellular-no-sim.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalCellularNoSim = (props) => (
<SvgIcon {...props}>
<path d="M18.99 5c0-1.1-.89-2-1.99-2h-7L7.66 5.34 19 16.68 18.99 5zM3.65 3.88L2.38 5.15 5 7.77V19c0 1.1.9 2 2 2h10.01c.35 0 .67-.1.96-.26l1.88 1.88 1.27-1.27L3.65 3.88z"/>
</SvgIcon>
);
DeviceSignalCellularNoSim = pure(DeviceSignalCellularNoSim);
DeviceSignalCellularNoSim.displayName = 'DeviceSignalCellularNoSim';
DeviceSignalCellularNoSim.muiName = 'SvgIcon';
export default DeviceSignalCellularNoSim;
|
src/index.js | Tinusw/myMovieCollection | import React from 'react'
import { Provider } from 'react-redux'
import { render } from 'react-dom'
import { Router, browserHistory } from 'react-router'
import routes from './routes'
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './styles/index.scss'
import configureStore from './store/configureStore'
const store = configureStore()
render(
<Provider store={store}>
<Router routes={routes} history={browserHistory} />
</Provider>,
document.getElementById('app')
)
|
src/docs/examples/Label/ExampleRequired.js | alopezitrs/ps-react-analo | import React from 'react';
import Label from 'ps-react/Label';
/** Required label */
export default function ExampleRequired() {
return <Label htmlFor="test" label="test" required />
}
|
test/test_helper.js | manelgavalda/ReduxRoutes | import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
test/mochitest/examples/react/src/App.js | wldcordeiro/debugger.html | import React, { Component } from 'react';
import I from "immutable"
class App extends Component {
componentDidMount() {
this.fields = new I.Map({a:2})
}
onClick = () => {
const f = this.fields
console.log(f)
}
render() {
return (
<div className="App">
<button onClick={this.onClick}>Click Me</button>
</div>
);
}
}
window.clickButton = () => document.querySelector("button").click()
export default App;
|
src/svg-icons/av/stop.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvStop = (props) => (
<SvgIcon {...props}>
<path d="M6 6h12v12H6z"/>
</SvgIcon>
);
AvStop = pure(AvStop);
AvStop.displayName = 'AvStop';
AvStop.muiName = 'SvgIcon';
export default AvStop;
|
examples/todomvc/index.js | edge/redux | import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import App from './containers/App'
import configureStore from './store/configureStore'
import 'todomvc-app-css/index.css'
const store = configureStore()
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
src/svg-icons/image/add-a-photo.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageAddAPhoto = (props) => (
<SvgIcon {...props}>
<path d="M3 4V1h2v3h3v2H5v3H3V6H0V4h3zm3 6V7h3V4h7l1.83 2H21c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H5c-1.1 0-2-.9-2-2V10h3zm7 9c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-3.2-5c0 1.77 1.43 3.2 3.2 3.2s3.2-1.43 3.2-3.2-1.43-3.2-3.2-3.2-3.2 1.43-3.2 3.2z"/>
</SvgIcon>
);
ImageAddAPhoto = pure(ImageAddAPhoto);
ImageAddAPhoto.displayName = 'ImageAddAPhoto';
ImageAddAPhoto.muiName = 'SvgIcon';
export default ImageAddAPhoto;
|
vam-client/src/views/desktop/PatientDemographicsView.js | vistadataproject/nodeVISTAClients | import React from 'react';
import classNames from 'classnames';
import format from 'date-fns/format';
import differenceInYears from 'date-fns/difference_in_years';
import Control from '~/react-views/Control';
import './demographics.css';
class PatientDemographicsView extends Control {
render() {
let patient = this.props.patient;
if(patient) {
return (
<div className={this.className}>
<div className="patientName">{patient.lastName}, {patient.firstName}</div>
<div className="patientStats">
<div className="patientSSN">{patient.ssn}</div>
<div className="patientDOB">{format(patient.dob, 'MMMM DD, YYYY')} ({differenceInYears(new Date(),patient.dob)})</div>
</div>
</div>
)
}
else {
return (
<div className={this.className}>
<div className="noPatient">No patient selected.</div>
</div>
)
}
}
mouseDown(e) {
if(this.props.patient) {
e.preventDefault();
this.el.removeEventListener('mouseup', this.mouseUp);
document.addEventListener('mouseup', this.mouseUp, false);
this.setState({
active:true
});
}
}
mouseUp() {
//release the mouse up
this.el.addEventListener('mouseup', this.mouseUp);
document.removeEventListener('mouseup', this.mouseUp, false);
this.setState({
active:false
})
}
get className() {
return classNames('v-PatientDemographics', {
'hasPatient' : this.props.patient,
'is-active' : this.state.active
}, super.className);
}
}
export default PatientDemographicsView; |
tests/Rules-isInt-spec.js | aesopwolf/formsy | import React from 'react';
import TestUtils from 'react-addons-test-utils';
import Formsy from './..';
import { InputFactory } from './utils/TestInput';
const TestInput = InputFactory({
render() {
return <input value={this.getValue()} readOnly/>;
}
});
const TestForm = React.createClass({
render() {
return (
<Formsy.Form>
<TestInput name="foo" validations="isInt" value={this.props.inputValue}/>
</Formsy.Form>
);
}
});
export default {
'should pass with a default value': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
},
'should pass with an empty string': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue=""/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
},
'should fail with a string': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue="abc"/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should pass with a number as string': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue="+42"/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
},
'should fail string with digits': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue="42 is an answer"/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should pass with an int': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={42}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
},
'should fail with a float': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={Math.PI}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should fail with a float in science notation': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue="-1e3"/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should pass with undefined': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={undefined}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
},
'should pass with null': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={null}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
},
'should pass with a zero': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={0}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
}
};
|
src/svg-icons/editor/pie-chart.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorPieChart = (props) => (
<SvgIcon {...props}>
<path d="M11 2v20c-5.07-.5-9-4.79-9-10s3.93-9.5 9-10zm2.03 0v8.99H22c-.47-4.74-4.24-8.52-8.97-8.99zm0 11.01V22c4.74-.47 8.5-4.25 8.97-8.99h-8.97z"/>
</SvgIcon>
);
EditorPieChart = pure(EditorPieChart);
EditorPieChart.displayName = 'EditorPieChart';
EditorPieChart.muiName = 'SvgIcon';
export default EditorPieChart;
|
src/components/store.js | AdinoyiSadiq/back-office-tool | import React from 'react';
import Inventory from './inventory';
import Cart from './cart';
class Store extends React.Component {
render() {
return (
<div className="content container">
<div className="row">
<Inventory
carpets={this.props.carpets}
juice={this.props.juice}
addToCart={this.props.addToCart}/>
<Cart
carpets={this.props.carpets}
juice={this.props.juice}
cart={this.props.cart}
addToOrder={this.props.addToOrder}
removeFromCart={this.props.removeFromCart}
clearCart={this.props.clearCart}/>
</div>
</div>
);
}
}
export default Store; |
src/index.js | LiveTyping/android-colors | import React from 'react';
import { render } from 'react-dom';
import { createStore, combineReducers, compose, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import createHashHistory from 'history/createHashHistory';
import { Route } from 'react-router';
import { ConnectedRouter, routerReducer, routerMiddleware } from 'react-router-redux';
import injectTapEventPlugin from 'react-tap-event-plugin';
// TODO drop bootstrap
import './bootstrap-grid.css';
import * as reducers from './reducers';
import App from './containers/App';
import './index.css';
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();
const history = createHashHistory();
function initStore(initialState = {}) {
return createStore(
combineReducers({
...reducers,
router: routerReducer,
}),
initialState,
compose(
applyMiddleware(
routerMiddleware(history),
thunk
),
window.devToolsExtension ? window.devToolsExtension() : (f) => f
)
);
}
function mountApplication(mountNode) {
if (!(mountNode instanceof Element)) {
return;
}
render(
<Provider store={initStore()}>
<ConnectedRouter history={history}>
<div>
<Route exact path="/" component={App} />
</div>
</ConnectedRouter>
</Provider>,
mountNode
);
}
mountApplication(document.querySelector('#root'));
|
packages/ringcentral-widgets/components/AlertRenderer/CallingSettingsAlert/index.js | ringcentral/ringcentral-js-widget | import React from 'react';
import PropTypes from 'prop-types';
import callingSettingsMessages from 'ringcentral-integration/modules/CallingSettings/callingSettingsMessages';
import FormattedMessage from '../../FormattedMessage';
import i18n from './i18n';
function CallingSettingsAlert({
message: { message },
currentLocale,
brand,
onCallingSettingsLinkClick,
}) {
switch (message) {
case callingSettingsMessages.saveSuccess:
case callingSettingsMessages.saveSuccessWithSoftphone:
case callingSettingsMessages.webphonePermissionRemoved:
case callingSettingsMessages.emergencyCallingNotAvailable:
return (
<FormattedMessage
message={i18n.getString(message)}
values={{ brand }}
/>
);
case callingSettingsMessages.permissionChanged:
case callingSettingsMessages.phoneNumberChanged: {
const link = onCallingSettingsLinkClick ? (
<a
onClick={(e) => {
e.preventDefault();
onCallingSettingsLinkClick();
}}
>
{i18n.getString('link', currentLocale)}
</a>
) : (
i18n.getString('link', currentLocale)
);
return (
<FormattedMessage
message={i18n.getString(message, currentLocale)}
values={{ link }}
/>
);
}
default:
return null;
}
}
CallingSettingsAlert.propTypes = {
message: PropTypes.shape({
message: PropTypes.string.isRequired,
}).isRequired,
currentLocale: PropTypes.string.isRequired,
brand: PropTypes.string.isRequired,
onCallingSettingsLinkClick: PropTypes.func,
};
CallingSettingsAlert.defaultProps = {
onCallingSettingsLinkClick: undefined,
};
CallingSettingsAlert.handleMessage = ({ message }) =>
message === callingSettingsMessages.saveSuccess ||
message === callingSettingsMessages.saveSuccessWithSoftphone ||
message === callingSettingsMessages.permissionChanged ||
message === callingSettingsMessages.webphonePermissionRemoved ||
message === callingSettingsMessages.phoneNumberChanged ||
message === callingSettingsMessages.emergencyCallingNotAvailable;
export default CallingSettingsAlert;
|
client/containers/DevTools.js | yvanwangl/React-Blog | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor toggleVisibilityKey='ctrl-h'
changePositionKey='ctrl-q'>
<LogMonitor />
</DockMonitor>
);
|
app/containers/Access/index.js | MameeV/suzette | /*
*
* SignIn
*
*/
import React from 'react';
import Helmet from 'react-helmet';
export default class Access extends React.PureComponent {
constructor(props){
super(props);
this.state={
email: "",
password: "",
token: "",
}
}
handleEmail = (event) => {
this.setState({
email: event.target.value
})
}
handlePassword = (event) => {
this.setState({
password: event.target.value
})
}
signin = () => {
var data = new FormData();
data.append ("email", this.state.email);
data.append ("password", this.state.password);
fetch ("http://mrsverbeck.com/api/signin" , {
method: "post",
body: data
})
.then ((response) => {
return response.json();
})
.then ((json) => {
if (json.error) {
alert (json.error);
}
else if (json.token === false)
{
alert ("Invaid Credentials");
}
else if (json.token !== false)
{
sessionStorage.setItem("token", JSON.stringify(json.token));
alert ("Welcome Back!");
this.setState({token: sessionStorage.getItem('token')});
console.log(this.state.token);
}
});
}
render() {
const titleStyle={
width: "100%",
height: "auto",
fontFamily: "Fredericka the Great",
fontStyle: "cursive",
fontWeight: "bold",
fontSize: "40px",
color: "#74D1EA",
textAlign: "center",
paddingTop: "20px",
background: "#3E262A"
}
const headTextStyle={
width: "100%",
height: "80px",
top: "auto",
borderTop:"3px solid #74D1EA",
borderBottom:"3px solid #74D1EA",
background: "#FAE0EE",
display: "flex",
flexDirection: "row",
justifyContent: "center",
fontFamily: "Fredericka the Great",
fontStyle: "cursive",
fontWeight: "bold",
fontSize: "40px",
color: "#3E262A",
textTransform: "uppercase",
textAlign: "center",
paddingTop: "10px"
}
const inputContainer={
display: "flex",
flexDirection: "row",
justifyContent: "center",
background: "#3E262A",
paddingTop: "30px",
paddingLeft: "30px",
paddingBottom: "30px"
}
const input={
width: "25%",
height: "100%",
display: "flex",
flexDirection: "column"
}
const inputEmail={
width: "100%",
display: "flex",
flexWrap: "auto",
background: "#888888",
paddingLeft: "5px"
}
const inputPassword={
width: "100%",
display: "flex",
flexWrap: "auto",
background: "#777777",
paddingLeft: "5px"
}
const inputSubmit={
width: "100%",
height: "auto",
background: "#74D1EA",
}
const issueStyle={
width: "100%",
height: "auto",
fontFamily: "Raleway",
fontWeight: "bold",
fontSize: "18px",
color: "#74D1EA",
textAlign: "center",
paddingTop: "5px",
paddingBottom: "30px",
background: "#3E262A"
}
return (
<div>
<Helmet title="Access" meta={[ { name: 'description', content: 'SignIn Page for Articles Dashboard' }]}/>
<div style={headTextStyle}>
Access the Articles Dashboard
</div>
<main>
<div style={titleStyle}> SignIn for Access </div>
<div style={inputContainer}>
<div style={input}>
<textarea style={inputEmail} onChange={this.handleEmail} value={this.state.email} type="text" placeholder="Enter Your Email Address"/>
<textarea style={inputPassword} onChange={this.handlePassword} value={this.state.password} type="text" placeholder="Enter Your Password"/>
<input style={inputSubmit} onTouchTap={this.signin} type="submit"/>
</div>
</div>
<div style={issueStyle}> If you have a problem signing in, please click the MESSAGE ME button and send information about your issue.
<br/>
You can expect a reply, to your email address, within 24 to 48 hours. </div>
</main>
</div>
);
}
}
|
src/renderer/components/notification.js | sirbrillig/gitnews-menubar | import React from 'react';
import Gridicon from 'gridicons';
import debugFactory from 'debug';
import date from 'date-fns';
import EnsuredImage from './ensured-image';
import MuteIcon from './mute-icon';
const debug = debugFactory('gitnews-menubar');
export default function Notification({
note,
openUrl,
markRead,
markUnread,
token,
muteRepo,
unmuteRepo,
isMuted,
isMuteRequested,
setMuteRequested,
isMultiOpenMode,
isMultiOpenPending,
saveNoteToOpen,
}) {
const isUnread =
note.unread === true ? true : note.gitnewsMarkedUnread === true;
const onClick = () => {
debug('clicked on notification', note);
setMuteRequested(false);
if (isMultiOpenMode) {
saveNoteToOpen(note);
return;
}
markRead(token, note);
openUrl(note.commentUrl);
};
const timeString = date.distanceInWords(
Date.now(),
date.parse(note.updatedAt),
{ addSuffix: true }
);
const noteClasses = [
'notification',
...(isMultiOpenMode && !isMultiOpenPending
? ['notification--multi-open']
: []),
...(isMultiOpenPending ? ['notification--multi-open-clicked'] : []),
...getNoteClasses({ isUnread, isMuted }),
];
const defaultAvatar = `https://avatars.io/twitter/${note.repositoryFullName}`;
const avatarSrc =
note.commentAvatar || note.repositoryOwnerAvatar || defaultAvatar;
const isClosed =
note.api.subject &&
note.api.subject.state &&
note.api.subject.state === 'closed';
const isMerged = note.api.subject && note.api.subject.merged;
const iconType = isMerged || isClosed ? 'checkmark-circle' : 'chat';
const iconText = isMerged || isClosed ? 'closed' : 'open';
const iconClasses = [
'notification__type',
...(isClosed && !isMerged ? ['notification__type--closed'] : []),
...(isMerged ? ['notification__type--merged'] : []),
];
const doMute = event => {
event.preventDefault();
event.stopPropagation();
setMuteRequested(note);
};
const doUnmute = event => {
event.preventDefault();
event.stopPropagation();
unmuteRepo(note.repositoryFullName);
};
if (isMuteRequested) {
return (
<div className={noteClasses.join(' ')}>
<div className="notification__mute-confirm">
<div className="notification__mute-confirm__text">
<div className="notification__mute-confirm__title">
Mute all notifications from {note.repositoryFullName}?
</div>
Notifications from a muted repo will not cause the icon to change.
You can unmute it later.
</div>
<div className="notification__mute-confirm__buttons">
<MuteRepoCancelButton
disabled={isMultiOpenMode}
onClick={() => setMuteRequested(false)}
/>
<MuteRepoButton
disabled={isMultiOpenMode}
onClick={() => {
setMuteRequested(false);
muteRepo(note.repositoryFullName);
}}
/>
</div>
</div>
</div>
);
}
return (
<div className={noteClasses.join(' ')} onClick={onClick}>
{isMultiOpenPending && <MultiOpenPendingNotice />}
<div className={iconClasses.join(' ')}>
<Gridicon icon={iconType} />
<span className="notification__type--text">{iconText}</span>
</div>
<div className="notification__image">
{isUnread && <span className="notification__new-dot" />}
{isMuted && <MuteIcon className="mute-icon" />}
<EnsuredImage src={avatarSrc} />
</div>
<div className="notification__body">
<div className="notification__repo">
<span className="notification__repo-name">
{note.repositoryFullName}
</span>
</div>
<div className="notification__title">{note.title}</div>
<div className="notification__footer">
<span className="notification__time">{timeString}</span>
<span className="notification__actions">
{isMuted ? (
<UnmuteRepoButton disabled={isMultiOpenMode} onClick={doUnmute} />
) : (
<MuteRepoRequestButton
disabled={isMultiOpenMode}
onClick={doMute}
/>
)}
{isUnread ? (
<MarkReadButton
disabled={isMultiOpenMode}
note={note}
token={token}
markRead={markRead}
/>
) : (
<MarkUnreadButton
disabled={isMultiOpenMode}
note={note}
markUnread={markUnread}
/>
)}
</span>
</div>
</div>
</div>
);
}
function MuteRepoCancelButton({ onClick, disabled }) {
return (
<button
className="notification__mute-confirm__cancel btn--cancel"
aria-label="Cancel mute repo"
onClick={onClick}
disabled={disabled}
>
Cancel
</button>
);
}
function MuteRepoButton({ onClick, disabled }) {
return (
<button
className="notification__mute-confirm__confirm btn"
aria-label="Mute notifications from this repo"
onClick={onClick}
disabled={disabled}
>
Mute repo
</button>
);
}
function MuteRepoRequestButton({ onClick, disabled }) {
if (disabled) {
return null;
}
return (
<button
className="notification__mute-repo"
aria-label="Mute notifications from this repo"
onClick={onClick}
disabled={disabled}
>
mute repo
</button>
);
}
function UnmuteRepoButton({ onClick, disabled }) {
if (disabled) {
return null;
}
return (
<button
className="notification__mute-repo"
aria-label="Unmute notifications from this repo"
onClick={onClick}
disabled={disabled}
>
unmute repo
</button>
);
}
function MarkReadButton({ note, token, markRead, disabled }) {
const onClick = event => {
debug('clicked to mark notification as read', note);
event.preventDefault();
event.stopPropagation();
markRead(token, note);
};
if (disabled) {
return null;
}
return (
<button
className="notification__mark-read"
onClick={onClick}
aria-label="Mark notification as read"
disabled={disabled}
>
mark read
</button>
);
}
function MarkUnreadButton({ note, markUnread, disabled }) {
const onClick = event => {
debug('clicked to mark notification as unread', note);
event.preventDefault();
event.stopPropagation();
markUnread(note);
};
if (disabled) {
return null;
}
return (
<button
className="notification__mark-unread"
onClick={onClick}
aria-label="Mark as unread"
disabled={disabled}
>
mark unread
</button>
);
}
function getNoteClasses({ isMuted, isUnread }) {
if (isMuted) {
return ['notification__muted'];
}
if (isUnread) {
return ['notification__unread'];
}
return ['notification__read'];
}
function MultiOpenPendingNotice() {
return (
<div className="multi-open-pending-notice">Release Command key to open</div>
);
}
|
app/javascript/mastodon/features/ui/components/actions_modal.js | koba-lab/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import StatusContent from '../../../components/status_content';
import Avatar from '../../../components/avatar';
import RelativeTimestamp from '../../../components/relative_timestamp';
import DisplayName from '../../../components/display_name';
import IconButton from '../../../components/icon_button';
import classNames from 'classnames';
export default class ActionsModal extends ImmutablePureComponent {
static propTypes = {
status: ImmutablePropTypes.map,
actions: PropTypes.array,
onClick: PropTypes.func,
};
renderAction = (action, i) => {
if (action === null) {
return <li key={`sep-${i}`} className='dropdown-menu__separator' />;
}
const { icon = null, text, meta = null, active = false, href = '#' } = action;
return (
<li key={`${text}-${i}`}>
<a href={href} target='_blank' rel='noopener noreferrer' onClick={this.props.onClick} data-index={i} className={classNames({ active })}>
{icon && <IconButton title={text} icon={icon} role='presentation' tabIndex='-1' inverted />}
<div>
<div className={classNames({ 'actions-modal__item-label': !!meta })}>{text}</div>
<div>{meta}</div>
</div>
</a>
</li>
);
}
render () {
const status = this.props.status && (
<div className='status light'>
<div className='boost-modal__status-header'>
<div className='boost-modal__status-time'>
<a href={this.props.status.get('url')} className='status__relative-time' target='_blank' rel='noopener noreferrer'>
<RelativeTimestamp timestamp={this.props.status.get('created_at')} />
</a>
</div>
<a href={this.props.status.getIn(['account', 'url'])} className='status__display-name'>
<div className='status__avatar'>
<Avatar account={this.props.status.get('account')} size={48} />
</div>
<DisplayName account={this.props.status.get('account')} />
</a>
</div>
<StatusContent status={this.props.status} />
</div>
);
return (
<div className='modal-root__modal actions-modal'>
{status}
<ul className={classNames({ 'with-status': !!status })}>
{this.props.actions.map(this.renderAction)}
</ul>
</div>
);
}
}
|
docs/src/sections/PageHeaderSection.js | Lucifier129/react-bootstrap | import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function PageHeaderSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="page-header">Page header</Anchor> <small>PageHeader</small>
</h2>
<p>A simple shell for an <code>h1</code> to appropriately space out and segment sections of content on a page. It can utilize the <code>h1</code>’s default <code>small</code> element, as well as most other components (with additional styles).</p>
<ReactPlayground codeText={Samples.PageHeader} />
<h3><Anchor id="page-header-props">Props</Anchor></h3>
<PropTable component="PageHeader"/>
</div>
);
}
|
src/pages/Login.js | GamerZUnited/GamerZUninted-FrontEnd | import React from 'react'
import {connect} from 'react-redux'
import {pushState } from 'redux-router'
import * as Actions from '../actions/AppActions'
import TestComponent from '../components/TestComponent';
@connect(
state => ({
login: state.login
})
)
class Login extends React.Component {
componentWillReceiveProps(nextProps){
const {dispatch} = this.props
if(nextProps.login.toJS().logged){
dispatch(pushState(null,'/posts'))
}
}
render() {
const {login, dispatch} = this.props
const handleLogin = (event) => {
const {email, password} = this.refs
dispatch(Actions.login(email.value, password.value))
}
return (
<div>
<div>
<form>
<label>Sign In Please!</label>
<input type="text" placeholder="email" ref="email" required></input>
<input type="password" placeholder="password" ref="password" required></input>
<input type="button" value="Log In" onClick={handleLogin}/>
<a href='/signup'>
<input type="button" value="Sign Up"/>
</a>
</form>
</div>
</div>
)
}
}
export default Login
|
src/components/Provider/index.js | orionsoft/parts | import React from 'react'
import Message from './Message'
import Modal from './Modal'
import MeProvider from './MeProvider'
import PropTypes from 'prop-types'
import ModalContext from './Modal/Context'
export default class OrionsoftProvider extends React.Component {
static propTypes = {
children: PropTypes.node,
meProvider: PropTypes.bool
}
static defaultProps = {
meProvider: true
}
renderMe() {
if (!this.props.meProvider) return this.props.children
return <MeProvider>{this.props.children}</MeProvider>
}
render() {
return (
<Message>
<Modal setRef={modal => (this.modal = modal)} />
<ModalContext.Provider
value={{
showModal: params => this.modal.showModal(params),
updateModal: params => this.modal.updateModal(params)
}}>
{this.renderMe()}
</ModalContext.Provider>
</Message>
)
}
}
|
src/js/services/noti_service/notiProviders/SessionNoti.js | KyberNetwork/KyberWallet |
import React from 'react'
export default class SessionNoti extends React.Component {
setNewTx(tx) {
if (window.kyberBus){
window.kyberBus.broadcast("swap.one.created", {
tx_hash: tx.hash,
display_status: tx.status ? tx.status : "pending",
status: tx.status ? tx.status : "pending",
created_at: new Date().getTime(),
viewed: false
})
}
}
changeStatusTx(tx) {
if (window.kyberBus){
window.kyberBus.broadcast("swap.one.updated", {
tx_hash: tx.hash,
display_status: tx.status ? tx.status : "pending",
status: tx.status ? tx.status : "pending",
updated_at: new Date().getTime(),
viewed: false
})
}
}
}
|
src/components/UserInfo.js | rollo-zhou/look | import React from 'react';
import {
ActivityIndicator,
StyleSheet,
Image,
Text,
View,
ListView,
TouchableOpacity
} from 'react-native';
import Dimensions from 'Dimensions';
const {width, height} = Dimensions.get('window');
import globalVariables from '../globalVariables.js';
import Icon from 'react-native-vector-icons/Ionicons';
import Storage from './Storage.js';
import RCTDeviceEventEmitter from 'RCTDeviceEventEmitter';
import Login from './Login.js';
import List from './LeaderList.js';
const UserInfo = React.createClass({
getInitialState() {
return {
user:{
id:0,
photo:"",
name:"",
byline:"",
fans_count:"",
looks_count:"",
karma_count:"",
fanned_count:0,
},
isThumb:true,
isMe:false,
};
},
getDefaultProps() {
return {
user:{
id:0,
photo:"",
name:"",
byline:"",
fans_count:"",
looks_count:"",
karma_count:"",
fanned_count:0,
},
showImagListOrThumb:function(){},
toLookedPage:function(){},
toUserListPage:function(){},
};
},
module:{
userFanned:null,
user:null,
},
componentWillMount() {
this.setState({user:this.props.user});
globalVariables.getUser((user)=>{
if(user && user.id==this.props.user.id){
this.setState({
user:user,
isMe:true,
});
}else{
this.queryRromServer();
}
});
globalVariables.getUserFanned((fanned)=>{
if(!fanned)return;
this.module.userFanned=fanned;
this.setState({isFaned:!!fanned[this.props.user.id]});
}
);
},
logout(){
globalVariables.logout();
RCTDeviceEventEmitter.emit('Logout');
},
getBtnView(){
if(this.state.isMe){
return(<TouchableOpacity style={styles.addUserView} onPress={this.logout}>
<Text style={styles.LogoutText}>Logout</Text>
</TouchableOpacity>);
}else{
if(this.state.isFaned){
return(<TouchableOpacity style={styles.addedUserView} onPress={this.addUser}>
<Icon name="ios-checkmark-outline" size={25} color={globalVariables.background}/>
</TouchableOpacity>);
}else{
return(<TouchableOpacity style={styles.addUserView} onPress={this.addUser}>
<Text style={styles.addUserText}>+</Text>
</TouchableOpacity>);
}
}
},
getNameView(){
if(this.state.isMe){
return(
<View style={styles.hearder}>
<View style={{flex:1}}></View>
<View style={styles.meName}>
<Text style={styles.userNameTest} > {this.state.user.name}</Text>
</View>
<TouchableOpacity style={styles.more} onPress={this.toMore}>
<Icon name="ios-more-outline" size={35} color={globalVariables.textBase}/>
</TouchableOpacity>
</View>
);
}else{
return false;
}
},
shouldComponentUpdate: function(nextProps, nextState) {
return JSON.stringify(nextState)!=JSON.stringify(this.state);
},
render() {
if(!this.state.user){
return false;
}
return (
<View style={[styles.flexContainer,{paddingTop: this.state.isMe?0:74}]}>
{this.getNameView()}
<View style={styles.mainSection}>
<Image source={{uri:this.state.user.photo}} style={styles.avatar}/>
<View style={styles.userInfoBody}>
<View style={styles.userInfoHeader}>
<TouchableOpacity style={[styles.userInfoView,{flex:4}]} onPress={() => this.toUserListPage("fans")}>
<Text style={styles.numText} > {this.state.user.fans_count}</Text>
<Text style={styles.strText} > FANS </Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.userInfoView,{flex:4}]} onPress={() => this.toUserListPage("fanned")}>
<Text style={styles.numText} > {this.state.user.fanned_count||0}</Text>
<Text style={styles.strText} > FANNED </Text>
</TouchableOpacity>
<View style={[styles.userInfoView,{flex:4}]}>
<Text style={styles.numText} > {this.state.user.looks_count}</Text>
<Text style={styles.strText} > LOOKS</Text>
</View>
<View style={[styles.userInfoView,{flex:5}]}>
<Text style={styles.numText} > {this.state.user.karma_count}</Text>
<Text style={styles.strText} > KARMA</Text>
</View>
</View>
{this.getBtnView()}
</View>
</View>
<View style={styles.mainSection}>
<TouchableOpacity activeOpacity={0.8} onPress={() => this.showImagListOrThumb("thumb")} style={styles.cell}>
<Icon name="ios-apps-outline" color={this.state.isThumb?globalVariables.base:globalVariables.textBase} size={30}/>
</TouchableOpacity>
<TouchableOpacity activeOpacity={0.8} onPress={() => this.showImagListOrThumb("list")} style={styles.cell}>
<Icon name="ios-list-outline" color={this.state.isThumb?globalVariables.textBase:globalVariables.base} size={45}/>
</TouchableOpacity>
<TouchableOpacity activeOpacity={0.8} onPress={() => this.toLookedPage("HYPED")} style={styles.cell}>
<Icon name="ios-flame-outline" color={globalVariables.textBase} size={35}/>
</TouchableOpacity>
<TouchableOpacity activeOpacity={0.8} onPress={() => this.toLookedPage("LOVED")} style={styles.cell}>
<Icon name="ios-heart-outline" color={globalVariables.textBase} size={30}/>
</TouchableOpacity>
</View>
</View>
);
},
showImagListOrThumb(type){
var isThumb=type=='thumb'?true:false;
this.setState({isThumb:isThumb});
this.props.showImagListOrThumb(type);
},
toLookedPage(type){
var count= type=="LOVED"?this.state.user.loved_looks_count:this.state.user.hyped_looks_count;
this.props.toLookedPage(type,count);
},
toUserListPage(type){
this.props.toUserListPage(type);
},
addUser(){
globalVariables.getUser((user)=>{
if(!user){
this.props.navigator.push({
component: Login,
backButtonTitle:' ',
// backButtonIcon:this.state.backIcon,
title: 'Login',
passProps: {
navigator:this.props.navigator,
},
});
return;
}
if(this.state.user && this.state.user.id){
var method=this.state.isFaned?"DELETE":"POST"
this.setState({
isFaned:!this.state.isFaned,
});
globalVariables.queryRromServer(globalVariables.apiUserServer+(this.state.user.id)+"/fan"
,this.addUserProcesssResults
,{
method:method
});
}
});
},
toMore(){
this.props.navigator.push({
component: List,
backButtonTitle:' ',
// backButtonIcon:this.state.backIcon,
title: 'List'
});
},
addUserProcesssResults(data) {
if(!data) return;
if (data.status!="fanned") {
delete this.module.userFanned[this.state.user.id];
this.setState({
isFaned:false,
});
}else{
this.module.userFanned[this.state.user.id]=this.state.user.id;
this.setState({
isFaned:true,
});
}
if (data && data.status){
globalVariables.setUserFanned(this.module.userFanned);
}
},
queryRromServer() {
globalVariables.queryRromServer(globalVariables.apiUserServer+(this.state.uid||this.state.user.id),this.processsResults);
},
processsResults(data) {
if (!data) {
return;
}
this.setState({
user: data.user,
uid:data.id
});
if(this.state.isMe){
globalVariables.userIsLogin((isLogin,user)=>{
if(isLogin){
globalVariables.saveMeInfo(
{
hypedLookIds:data.user.hyped_look_ids||[],
fannedUserIds:data.user.fanned_user_ids||[],
user:data.user||{},
hypedCallBack:()=>{},
fannedCallBack:()=>{},
userCallBack:()=>{}
});
}
});
}
}
});
const styles = StyleSheet.create({
flexContainer: {
// 容器需要添加direction才能变成让子元素flex
flexDirection: 'column',
opacity:0.97,
// padding: 0,
paddingBottom:5,
backgroundColor: globalVariables.background,
width:width,
// justifyContent: 'flex-start',
// paddingTop: 84,
},
mainSection: {
// flex: 1,
flexDirection: 'row',
// paddingBottom: 10,
// alignItems: "center",
justifyContent: 'flex-start',
},
userInfoBody: {
flex: 1,
flexDirection: "column",
justifyContent: "center",
// marginLeft:5,
},
userInfoHeader: {
flexDirection: "row",
alignItems: "center"
},
userInfoView:{
// flex:1,
flexDirection: "column",
alignItems:"center",
},
numText: {
color:globalVariables.base,
fontWeight:'600',
// fontSize:12,
},
strText: {
color:globalVariables.textBase,
fontSize:12,
},
addUserView: {
// width: width-200,
height: 30,
borderWidth: 1,
borderRadius: 3,
borderColor: globalVariables.base,
alignItems:'center',
// margin:20,
marginLeft:20,
marginTop:20,
marginBottom:20,
marginRight:10,
justifyContent: "center",
},
addedUserView: {
// width: width-200,
height: 30,
borderWidth: 1,
borderRadius: 3,
backgroundColor: globalVariables.base,
borderColor: globalVariables.base,
alignItems:'center',
// margin:20,
marginLeft:20,
marginBottom:20,
marginTop:20,
marginRight:10,
justifyContent: "center",
},
LogoutText:{
color:globalVariables.base,
// fontSize:16,
// textAlign:"center",
},
userNameTest:{
fontSize:16,
fontWeight:"600",
color:globalVariables.textBase,
},
addUserText:{
color:globalVariables.base,
fontSize:16,
// textAlign:"center",
},
userInfoText: {
fontSize:12,
// marginLeft:20,
// marginRight:20,
flexDirection: "row",
color:globalVariables.textBase2,
},
avatar: {
borderRadius: 40,
width: 80,
height: 80,
marginRight: 0,
marginLeft:5,
backgroundColor:globalVariables.textBase2,
},
cell: {
flexDirection: 'row',
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
meName:{
flex: 4,
// flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
// height:44,
// marginBottom:10
},
more:{
flex: 1,
alignItems:'center',
justifyContent: 'center',
},
hearder:{
// flex: 1,
// 容器需要添加direction才能变成让子元素flex
flexDirection: 'row',
backgroundColor: globalVariables.background,
// alignItems: 'center',
// justifyContent: 'center',
height:44,
marginBottom:10
}
});
export default UserInfo;
|
web-app/src/pages/show/ShowQuestion.js | Charterhouse/NextBuild2017 | import React from 'react'
import { Alert, Form, FormGroup, FormControl, Col, ControlLabel } from 'react-bootstrap'
import Button from 'react-bootstrap-button-loader'
class ShowQuestion extends React.Component {
constructor (props) {
super(props)
this.state = {
question: '',
guess: '',
isLoading: false,
alert: '',
alertStyle: ''
}
this.handleChange = this.handleChange.bind(this)
this.id = Number(this.props.match.params.id)
this.onSubmit = this.onSubmit.bind(this)
}
componentWillMount () {
this.retrieveQuestion(this.props.match.params.id)
}
async retrieveQuestion (id) {
const { contract } = this.props
const question = await contract.getQuestion(Number(id))
this.setState({ question: question })
}
render () {
return <div className='show-question'>
<h2>{ this.state.question }</h2>
<Form horizontal>
<FormGroup>
<Col sm={2} componentClass={ControlLabel}>Take a guess:</Col>
<Col sm={10}>
<FormControl
type='text'
name='guess'
value={this.state.guess}
placeholder='Enter your answer...'
onChange={this.handleChange}
/>
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={2} sm={10}>
<Button
bsStyle='primary'
bsSize='large'
loading={this.state.isLoading}
disabled={!this.validFormInput()}
onClick={this.onSubmit}>Check My Answer</Button>
</Col>
</FormGroup>
</Form>
{ this.renderAlert() }
</div>
}
renderAlert () {
if (this.state.alert === '') {
return <div />
} else {
return <Alert bsStyle={this.state.alertStyle}>
{ this.state.alert }
</Alert>
}
}
handleChange (event) {
let target = event.target
this.setState({[target.name]: target.value})
}
async onSubmit () {
this.setState({ isLoading: true })
const { contract, accounts: [me] } = this.props
const options = { from: me, gas: 600000 }
await contract.guess(this.id, this.state.guess, options)
const winner = await contract.getWinner(this.id)
if (winner === me) {
this.setState({
alert: 'You Won!',
alertStyle: 'success'
})
} else {
this.setState({
alert: 'Wrong guess, please try again!',
alertStyle: 'danger'
})
}
this.setState({ isLoading: false })
}
validFormInput () {
return this.state.guess !== ''
}
}
export { ShowQuestion }
|
packages/demos/forms-demo/src/components/CurrentView/index.js | yusufsafak/cerebral | import React from 'react'
import { connect } from 'cerebral/react'
import { state } from 'cerebral/tags'
import Simple from '../Simple'
const VIEWS = {
Simple,
}
export default connect(
{
currentView: state`app.currentView`,
},
function CurrentView({ currentView }) {
const View = VIEWS[currentView]
return (
<div style={{ padding: 30, marginTop: 40 }}>
<View />
</div>
)
}
)
|
src/svg-icons/maps/satellite.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsSatellite = (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-2zM5 4.99h3C8 6.65 6.66 8 5 8V4.99zM5 12v-2c2.76 0 5-2.25 5-5.01h2C12 8.86 8.87 12 5 12zm0 6l3.5-4.5 2.5 3.01L14.5 12l4.5 6H5z"/>
</SvgIcon>
);
MapsSatellite = pure(MapsSatellite);
MapsSatellite.displayName = 'MapsSatellite';
MapsSatellite.muiName = 'SvgIcon';
export default MapsSatellite;
|
src/svg-icons/image/assistant.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageAssistant = (props) => (
<SvgIcon {...props}>
<path d="M19 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h4l3 3 3-3h4c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-5.12 10.88L12 17l-1.88-4.12L6 11l4.12-1.88L12 5l1.88 4.12L18 11l-4.12 1.88z"/>
</SvgIcon>
);
ImageAssistant = pure(ImageAssistant);
ImageAssistant.displayName = 'ImageAssistant';
ImageAssistant.muiName = 'SvgIcon';
export default ImageAssistant;
|
site/components/SideBar.js | hiddentao/react-dnd | import React from 'react';
import './SideBar.less';
export default class SideBar {
render() {
return (
<div className="SideBar">
<div className="SideBar-content">
{this.props.groups.map(this.renderGroup, this)}
</div>
</div>
);
}
renderGroup({ title, pages}, index) {
return (
<div className="SideBar-group" key={index}>
<h4 className="SideBar-groupTitle">
{title}
</h4>
{Object.keys(pages).map(key => this.renderLink(pages[key], key))}
</div>
);
}
renderLink({ title, location }, key) {
const arrow = <span className="arrowBullet" />;
let linkClass = 'SideBar-item';
if (this.props.example.location === location) {
linkClass += ' SideBar-item--selected';
}
return (
<a key={key} href={location} target="_self" className={linkClass}>
<span className="SideBar-itemText">{title}</span>
{arrow}
</a>
);
}
} |
js/App/Components/TabViews/TabsView.ios.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 { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import TabViews from './index';
import {
TabBarWithTabVisibility,
} from '../../../BaseComponents';
import {
prepareNavigator,
shouldNavigatorUpdate,
} from '../../Lib/NavigationService';
// NOTE [IMP]: Changing the order or updating the tabs
// need to reflect in places like tab hide/show logic and so
// Eg: Lib/NavigationService/prepareVisibleTabs
const ScreenConfigs = [
{
name: 'Dashboard',
Component: TabViews.Dashboard,
},
{
name: 'Devices',
Component: TabViews.Devices,
},
{
name: 'Sensors',
Component: TabViews.Sensors,
},
{
name: 'Scheduler',
Component: TabViews.Scheduler,
},
{
name: 'MoreOptionsTab',
Component: TabViews.MoreOptionsTab,
},
];
const NavigatorConfigs = {
swipeEnabled: false, // Check if exist in v5
lazy: true,
animationEnabled: false, // Check if exist in v5
tabBar: (props: Object): Object => <TabBarWithTabVisibility {...props}/>,
tabBarOptions: {
allowFontScaling: false,
tabStyle: {
alignItems: 'stretch',
justifyContent: 'space-between',
},
safeAreaInsets: {
top: 0,
bottom: 0,
right: 0,
left: 0,
},
},
};
const Tab = createBottomTabNavigator();
const TabsView = React.memo<Object>((props: Object): Object => {
const {
hiddenTabsCurrentUser = [],
defaultStartScreenKey = 'Dashboard',
} = props.screenProps;
const _ScreenConfigs = ScreenConfigs.filter((sc: Object): boolean => hiddenTabsCurrentUser.indexOf(sc.name) === -1);
const _NavigatorConfigs = {
...NavigatorConfigs,
initialRouteName: defaultStartScreenKey,
};
return prepareNavigator(Tab, {ScreenConfigs: _ScreenConfigs, NavigatorConfigs: _NavigatorConfigs}, props);
}, (prevProps: Object, nextProps: Object): boolean => shouldNavigatorUpdate(prevProps, nextProps, [
'hideHeader',
'showAttentionCapture',
'showAttentionCaptureAddDevice',
'addingNewLocation',
'hiddenTabsCurrentUser',
'defaultStartScreenKey',
]));
module.exports = (TabsView: Object);
|
docs/src/sections/CustomStylesSection.js | mmarcant/react-bootstrap | import React from 'react';
import Anchor from '../Anchor';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function CustomStylesSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="custom-styles">Custom Styles</Anchor>
</h2>
<p>The <code>bsStyle</code> prop, available in many components in React-Bootstrap, is used to map to a Bootstrap class for styling; for example, the Bootstrap class used for <code>Button</code> is <code>`btn-${'{'}bsStyle{'}'}`</code>. Use <code>bootstrapUtils</code> to create a custom class that is used in lieu of the classes provided by Bootstrap:</p>
<ReactPlayground codeText={Samples.CustomButtonStyle} />
</div>
);
}
|
app/components/peoplelist/peoplelist.js | hichameyessou/blip |
/**
* Copyright (c) 2014, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* 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 License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import React from 'react';
import _ from 'lodash';
import cx from 'classnames';
import { translate } from 'react-i18next';
var personUtils = require('../../core/personutils');
var PatientCard = require('../../components/patientcard');
var PeopleList = translate()(React.createClass({
propTypes: {
people: React.PropTypes.array,
uploadUrl: React.PropTypes.string,
onClickPerson: React.PropTypes.func,
onRemovePatient: React.PropTypes.func,
trackMetric: React.PropTypes.func.isRequired,
},
getInitialState: function() {
return {
editing: false
};
},
getDefaultProps: function() {
return {
onClickPerson: function() {}
};
},
render: function() {
var peopleNodes = [];
if (!_.isEmpty(this.props.people)) {
// first sort by fullName
var sortedPeople = _.sortBy(this.props.people, function(person) {
var patient = _.get(person, 'profile.patient', null);
return (patient && patient.isOtherPerson && patient.fullName)
? _.get(patient, 'fullName', '').toLowerCase()
: _.get(person, 'profile.fullName', '').toLowerCase();
});
// then pop the logged-in user to the top if has data
sortedPeople = _.sortBy(sortedPeople, function(person) {
if (!_.isEmpty(person.permissions)) {
if (person.permissions.root) {
return 1;
}
else {
return 2;
}
}
return 2;
});
peopleNodes = _.map(sortedPeople, this.renderPeopleListItem);
}
var classes = cx({
'people-list': true,
'list-group': true,
'people-list-single': (this.props.people && this.props.people.length === 1)
});
var removeControls = this.removeablePersonExists(this.props.people) ? this.renderRemoveControls() : null;
return (
<div>
<ul className={classes}>
{peopleNodes}
<div className="clear"></div>
</ul>
{removeControls}
</div>
);
},
removeablePersonExists: function(patients) {
return Boolean(_.find(patients, personUtils.isRemoveable));
},
renderRemoveControls: function() {
const { t } = this.props;
var key = 'edit';
var text = t('Remove People');
if (this.state.editing) {
key = 'cancel';
text = t('Done');
}
return (
<div className="patient-list-controls">
<button key={key} onClick={this.toggleEdit} className="patient-list-controls-button patient-list-controls-button--secondary" type="button">{text}</button>
</div>
);
},
toggleEdit: function() {
this.setState({
editing: !this.state.editing,
});
},
renderPeopleListItem: function(person, index) {
var peopleListItemContent;
var displayName = this.getPersonDisplayName(person);
var self = this;
var handleClick = function() {
self.props.onClickPerson(person);
};
return (
<li key={person.userid || index} className="patient-list-item">
<PatientCard
href={person.link}
onClick={handleClick}
uploadUrl={this.props.uploadUrl}
isEditing={this.state.editing}
onRemovePatient={this.props.onRemovePatient}
patient={person}
trackMetric={this.props.trackMetric}></PatientCard>
</li>
);
},
getPersonDisplayName: function(person) {
const { t } = this.props;
var fullName;
fullName = personUtils.patientFullName(person);
if (!fullName) {
return t('Anonymous user');
}
return fullName;
}
}));
module.exports = PeopleList;
|
src/svg-icons/image/crop-original.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCropOriginal = (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-2zm0 16H5V5h14v14zm-5.04-6.71l-2.75 3.54-1.96-2.36L6.5 17h11l-3.54-4.71z"/>
</SvgIcon>
);
ImageCropOriginal = pure(ImageCropOriginal);
ImageCropOriginal.displayName = 'ImageCropOriginal';
ImageCropOriginal.muiName = 'SvgIcon';
export default ImageCropOriginal;
|
jenkins-design-language/src/js/components/material-ui/svg-icons/maps/tram.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const MapsTram = (props) => (
<SvgIcon {...props}>
<path d="M19 16.94V8.5c0-2.79-2.61-3.4-6.01-3.49l.76-1.51H17V2H7v1.5h4.75l-.76 1.52C7.86 5.11 5 5.73 5 8.5v8.44c0 1.45 1.19 2.66 2.59 2.97L6 21.5v.5h2.23l2-2H14l2 2h2v-.5L16.5 20h-.08c1.69 0 2.58-1.37 2.58-3.06zm-7 1.56c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm5-4.5H7V9h10v5z"/>
</SvgIcon>
);
MapsTram.displayName = 'MapsTram';
MapsTram.muiName = 'SvgIcon';
export default MapsTram;
|
src/layout/Main.js | Moovashaka/moovaShaka | import React from 'react';
import { ContactForm } from '../components/contactForm.js';
export default class Main extends React.Component {
state = {
fields: {}
};
onChange = updatedValue => {
this.setState({ fields: {
...this.state.fields,
...updatedValue }});
}
render () {
return (
<div>
<header id="page-top">
<div className="header-content headerbanner">
<div className="header-content-inner">
<h1 id="homeHeading"> for Great mobile-first web app development</h1>
<hr />
<p>MoovaShaka can help you build, refine & define your virtual presence</p>
<a href="#about" className="btn btn-primary btn-xl page-scroll">Find Out More</a>
</div>
</div>
</header>
<section className="bg-primary" id="about">
<div className="container">
<div className="row">
<div className="col-lg-8 col-lg-offset-2 text-center">
<h2 className="section-heading">We have what you need!</h2>
<hr className="light" />
<p className="text-faded">At MoovaShaka we have everything needed to get your new web project up and running in no time. We are a multi-disciplinary team
with all the skills & know-how to really get your new project off to a flying start. Simply fill in the contact form below, send mail or phone with
an outline of your requirements and we can arrange a convenient time to iron out the detail. </p>
<p className="text-faded">Need modifications to your existing development? Get in touch & let's see how we can be of service.</p>
<a href="#services" className="page-scroll btn btn-default btn-xl sr-button">Get Started!</a>
</div>
</div>
</div>
</section>
<section id="services">
<div className="container">
<div className="row">
<div className="col-lg-12 text-center">
<h2 className="section-heading">At Your Service</h2>
<hr className="primary" />
</div>
</div>
</div>
<div className="container">
<div className="row">
<div className="col-lg-3 col-md-6 text-center">
<div className="service-box">
<i className="fa fa-4x fa-diamond text-primary sr-icons"></i>
<h3>Bespoke Designs</h3>
<p className="text-muted">Or modify what you already have - HTML5, CSS3, JavaScript, PHP & ReactJS specialities. </p>
</div>
</div>
<div className="col-lg-3 col-md-6 text-center">
<div className="service-box">
<i className="fa fa-4x fa-paper-plane text-primary sr-icons"></i>
<h3>Ready to Shop?</h3>
<p className="text-muted">or ready to sell, whatever you have in mind - together we can bring it to the world.</p>
</div>
</div>
<div className="col-lg-3 col-md-6 text-center">
<div className="service-box">
<i className="fa fa-4x fa-newspaper-o text-primary sr-icons"></i>
<h3>Up to Date</h3>
<p className="text-muted">Our Devs upskill regularly to keep abroad of the latest technologies.</p>
</div>
</div>
<div className="col-lg-3 col-md-6 text-center">
<div className="service-box">
<i className="fa fa-4x fa-heart text-primary sr-icons"></i>
<h3>Made with Love</h3>
<p className="text-muted">We approach our creations with passion and treat our clients with respect</p>
</div>
</div>
</div>
</div>
</section>
<section className="no-padding" id="portfolio">
<div className="container-fluid">
<div className="row no-gutter popup-gallery">
<div className="col-lg-4 col-sm-6">
<a href="https://www.thelifestylementor.co.uk" target="_blank" rel="noopener noreferrer" className="portfolio-box">
<img src="img/portfolio/thumbnails/lifestyleMentorThumb.png" className="img-responsive" alt="" />
<div className="portfolio-box-caption">
<div className="portfolio-box-caption-content">
<div className="project-category text-faded">
Brochure Site
</div>
<div className="project-name">
The LifeStyle Mentor
</div>
</div>
</div>
</a>
</div>
<div className="col-lg-4 col-sm-6">
<a href="https://autoview.netlify.com/" target="_blank" rel="noopener noreferrer" className="portfolio-box">
<img src="img/portfolio/thumbnails/aviewth.png" className="img-responsive" alt="" />
<div className="portfolio-box-caption">
<div className="portfolio-box-caption-content">
<div className="project-category text-faded">
Portfolio Site
</div>
<div className="project-name">
Autoview
</div>
</div>
</div>
</a>
</div>
<div className="col-lg-4 col-sm-6">
<a href="http://www.ribblevalleytyreandautoservices.co.uk" target="_blank" rel="noopener noreferrer" className="portfolio-box">
<img src="img/portfolio/thumbnails/rvtathumb.png" className="img-responsive" alt="" />
<div className="portfolio-box-caption">
<div className="portfolio-box-caption-content">
<div className="project-category text-faded">
Single Page WebApp
</div>
<div className="project-name">
Ribble Valley Tyre and Auto Services
</div>
</div>
</div>
</a>
</div>
</div>
</div>
</section>
<aside className="bg-dark">
<div className="container text-center">
<div className="call-to-action">
<h2>Free consultation with MoovaShaka</h2>
<hr />
<p>We believe in gathering a full understanding of our clients, their needs
and business ambitions. Leave your contact info and a convenient time to talk,
pour a coffee and together we can turn your vision into reality.
</p>
<img src="img/logobanner.png" className="img-responsive" alt="" />
<a href="#contact" className="page-scroll btn btn-default btn-xl sr-button">Talk to us Now!</a>
</div>
</div>
</aside>
<section id="contact">
<div className="container">
<div className="row">
<div className="col-lg-8 col-lg-offset-2 text-center">
<h2 className="section-heading">Let's Get In Touch</h2>
<hr className="primary" />
<p>Ready to start your next project with us? That's great! Give us a call or drop us mail and we will get back to you as soon as possible.</p>
</div>
<div className="col-lg-4 col-lg-offset-2 text-center">
<i className="fa fa-phone fa-3x sr-contact"></i>
<br />
<a href="tel:+44-203-0123-231">+44 (203) 0123 231</a>
</div>
<div className="col-lg-4 text-center">
<i className="fa fa-envelope-o fa-3x sr-contact"></i>
<p><a href="mailto:info@moovashaka.co.uk">feedback@moovashaka.co.uk</a></p>
</div>
</div>
</div> {/*Close container*/}
<div className="container">
<div className="row">
<div className="col align-items-end contactForm">
</div>
</div>
</div>
</section>
< ContactForm onChange={fields => this.onChange(fields)} />
</div>
);
}
}
|
src/components/Dimensions.js | nextensions/photoBooth | const _debounce = require('lodash.debounce')
const React = require('react')
const onElementResize = require('element-resize-event')
function defaultGetDimensions (element) {
return [element.clientWidth, element.clientHeight]
}
/**
* Wraps a react component and adds properties `containerHeight` and
* `containerWidth`. Useful for responsive design. Properties update on
* window resize. **Note** that the parent element must have either a
* height or a width, or nothing will be rendered
*
* Can be used as a
* [higher-order component](http://babeljs.io/blog/2015/06/07/react-on-es6-plus/#property-initializers)
* or as an [ES7 class decorator](https://github.com/wycats/javascript-decorators)
* (see examples)
*
* @param {object} [options]
* @param {function} [options.getHeight] A function that is passed an element and returns element
* height, where element is the wrapper div. Defaults to `(element) => element.clientHeight`
* @param {function} [options.getWidth] A function that is passed an element and returns element
* width, where element is the wrapper div. Defaults to `(element) => element.clientWidth`
* @param {number} [options.debounce] Optionally debounce the `onResize` callback function by
* supplying the delay time in milliseconds. This will prevent excessive dimension
* updates. See
* https://lodash.com/docs#debounce for more information. Defaults to `0`, which disables debouncing.
* @param {object} [options.debounceOpts] Options to pass to the debounce function. See
* https://lodash.com/docs#debounce for all available options. Defaults to `{}`.
* @param {object} [options.containerStyle] A style object for the `<div>` that will wrap your component.
* The dimensions of this `div` are what are passed as props to your component. The default style is
* `{ width: '100%', height: '100%', padding: 0, border: 0 }` which will cause the `div` to fill its
* parent in most cases. If you are using a flexbox layout you will want to change this default style.
* @param {string} [options.className] Control the class name set on the wrapper `<div>`
* @param {boolean} [options.elementResize=false] Set true to watch the wrapper `div` for changes in
* size which are not a result of window resizing - e.g. changes to the flexbox and other layout.
* @return {function} A higher-order component that can be
* used to enhance a react component `Dimensions()(MyComponent)`
*
* @example
* // ES2015
* import React from 'react'
* import Dimensions from 'react-dimensions'
*
* class MyComponent extends React.Component {
* render() (
* <div
* containerWidth={this.props.containerWidth}
* containerHeight={this.props.containerHeight}
* >
* </div>
* )
* }
*
* export default Dimensions()(MyComponent) // Enhanced component
*
* @example
* // ES5
* var React = require('react')
* var Dimensions = require('react-dimensions')
*
* var MyComponent = React.createClass({
* render: function() {(
* <div
* containerWidth={this.props.containerWidth}
* containerHeight={this.props.containerHeight}
* >
* </div>
* )}
* }
*
* module.exports = Dimensions()(MyComponent) // Enhanced component
*
*/
module.exports = function Dimensions ({
getDimensions = defaultGetDimensions,
debounce = 0,
debounceOpts = {},
elementResize = false
} = {}) {
return (ComposedComponent) => {
return class DimensionsHOC extends React.Component {
// ES7 Class properties
// http://babeljs.io/blog/2015/06/07/react-on-es6-plus/#property-initializers
state = {}
// Using arrow functions and ES7 Class properties to autobind
// http://babeljs.io/blog/2015/06/07/react-on-es6-plus/#arrow-functions
// Immediate updateDimensions callback with no debounce
updateDimensionsImmediate = () => {
const dimensions = getDimensions(this._parent)
if (dimensions[0] !== this.state.containerWidth ||
dimensions[1] !== this.state.containerHeight) {
this.setState({
containerWidth: dimensions[0],
containerHeight: dimensions[1]
})
}
}
// Optionally-debounced updateDimensions callback
updateDimensions = debounce === 0 ? this.updateDimensionsImmediate
: _debounce(this.updateDimensionsImmediate, debounce, debounceOpts)
onResize = () => {
if (this.rqf) return
this.rqf = this.getWindow().requestAnimationFrame(() => {
this.rqf = null
this.updateDimensions()
})
}
// If the component is mounted in a different window to the javascript
// context, as with https://github.com/JakeGinnivan/react-popout
// then the `window` global will be different from the `window` that
// contains the component.
// Depends on `defaultView` which is not supported <IE9
getWindow () {
return this.refs.container ? (this.refs.container.ownerDocument.defaultView || window) : window
}
componentDidMount () {
if (!this.refs.wrappedInstance) {
throw new Error('Cannot find wrapped instance')
}
this._parent = this.refs.wrappedInstance.parentNode
this.updateDimensionsImmediate()
if (elementResize) {
// Experimental: `element-resize-event` fires when an element resizes.
// It attaches its own window resize listener and also uses
// requestAnimationFrame, so we can just call `this.updateDimensions`.
onElementResize(this._parent, this.updateDimensions)
} else {
this.getWindow().addEventListener('resize', this.onResize, false)
}
}
componentWillUnmount () {
this.getWindow().removeEventListener('resize', this.onResize)
// TODO: remote element-resize-event listener.
// pending https://github.com/KyleAMathews/element-resize-event/issues/2
}
/**
* Returns the underlying wrapped component instance.
* Useful if you need to access a method or property of the component
* passed to react-dimensions.
*
* @return {object} The rendered React component
**/
getWrappedInstance () {
return this.refs.wrappedInstance
}
render () {
const {containerWidth, containerHeight} = this.state
if (this._parent && !containerWidth && !containerHeight) {
// only trigger a warning about the wrapper div if we already have a reference to it
console.warn('containerWidth and containerHeight were not set')
}
const wrapperStyle = {
overflow: 'visible',
height: 0,
width: 0
}
if (containerWidth || containerHeight) {
return <ComposedComponent
{...this.state}
{...this.props}
updateDimensions={this.updateDimensions}
ref='wrappedInstance'
/>
}
else {
return <div style={wrapperStyle} ref='wrappedInstance'></div>;
}
}
}
}
} |
src/views/fileuploader.react.js | Cron-J/CSV-REE | import React from 'react';
import Dropzone from 'react-dropzone';
class Fileuploader extends React.Component {
constructor(props) {
super(props);
this.state = {error: ''};
}
componentWillReceiveProps(nextProps) {
this.props = nextProps;
}
onDrop = (files, e) => {
if (files.length > 0) {
let extension = '';
extension= files[0].name.split('.').pop();
extension=extension.toLowerCase();
if (this.props.fileFormat.indexOf('.' + extension) < 0) {
this.setState({error: 'Invalid File Format'});
} else {
this.setState({error: ''});
this.props.onFileupload(files[0]);
}
}
}
renderInfo = () => {
if (this.props.fileinfo.name && this.props.fileinfo.name.length > 0) {
return <div><b>File Selected:</b>{this.props.fileinfo.name}<b className="marginleft5">Size</b>:{this.props.fileinfo.size}<b className="marginleft5">Type</b>:{this.props.fileinfo.type}</div>;
}
return '';
}
render() {
const fileFormats = this.props.fileFormat.join(', ');
return (
<div className="container">
<div className="row">
<form>
<Dropzone className="dropzoneContainer" multiple={false} onDrop={this.onDrop.bind(this)} >
<div className="dropzoneMessage">
Click here / Drop the <b>{fileFormats}</b> file
</div>
</Dropzone>
</form>
<div className="errorMessage">
{this.state.error || this.props.error}
</div>
<div className="displayMessage">
{this.renderInfo()}
</div>
</div>
</div>
);
}
}
Fileuploader.propTypes = {
fileFormat: React.PropTypes.arrayOf(React.PropTypes.string),
fileinfo: React.PropTypes.object,
error: React.PropTypes.string,
onFileupload: React.PropTypes.func
};
export default Fileuploader;
|
src/components/ActionMenu/ActionMenu.js | ConciergeAuctions/react-mui-table | // @flow
import React, { Component } from 'react';
import IconMenu from 'material-ui/IconMenu';
import IconButton from 'material-ui/IconButton';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import { lightBlack } from 'material-ui/styles/colors';
import ActionMenuItem from './ActionMenuItem';
import type { ActionMenuState, ActionMenuProps, ToggleOpen, StopPropogation } from './types';
class ActionMenu extends Component {
props: ActionMenuProps
state: ActionMenuState = {
open: false,
};
toggleOpen: ToggleOpen = open => this.setState({ open });
stopPropagation: StopPropogation = event => event.stopPropagation();
render() {
const { actions, item, itemId } = this.props;
return (
<IconMenu
open={this.state.open}
onRequestChange={this.toggleOpen}
useLayerForClickAway
onClick={this.stopPropagation}
iconButtonElement={<IconButton><MoreVertIcon color={lightBlack} /></IconButton>}>
{actions.map((action) => {
let enabled = typeof action.enabled === 'boolean' ? action.enabled : true;
if (typeof action.enabled === 'function') enabled = action.enabled(item);
if (!enabled) return null;
return (
<ActionMenuItem
key={`${action.text}-${itemId}`}
item={item}
icon={action.icon}
handler={action.handler}
toggleMenu={this.toggleOpen}
text={action.text} />
);
})}
</IconMenu>
);
}
}
export default ActionMenu;
|
frontend/src/Settings/ImportLists/ImportLists/ImportListsConnector.js | lidarr/Lidarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { deleteImportList, fetchImportLists, fetchRootFolders } from 'Store/Actions/settingsActions';
import createSortedSectionSelector from 'Store/Selectors/createSortedSectionSelector';
import sortByName from 'Utilities/Array/sortByName';
import ImportLists from './ImportLists';
function createMapStateToProps() {
return createSelector(
createSortedSectionSelector('settings.importLists', sortByName),
(importLists) => importLists
);
}
const mapDispatchToProps = {
fetchImportLists,
deleteImportList,
fetchRootFolders
};
class ListsConnector extends Component {
//
// Lifecycle
componentDidMount() {
this.props.fetchImportLists();
this.props.fetchRootFolders();
}
//
// Listeners
onConfirmDeleteImportList = (id) => {
this.props.deleteImportList({ id });
}
//
// Render
render() {
return (
<ImportLists
{...this.props}
onConfirmDeleteImportList={this.onConfirmDeleteImportList}
/>
);
}
}
ListsConnector.propTypes = {
fetchImportLists: PropTypes.func.isRequired,
deleteImportList: PropTypes.func.isRequired,
fetchRootFolders: PropTypes.func.isRequired
};
export default connect(createMapStateToProps, mapDispatchToProps)(ListsConnector);
|
frontend/app/score.js | bow-fujita/jacc-halloween | /**
* Copyright (C) 2018 Hiro Fujita <bow.fujita@gmail.com>
*/
'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import _ from 'underscore';
import {
Button
, ButtonGroup
} from 'react-bootstrap';
import Header from './header';
import Table from './table';
import Ajax from './ajax';
import Notify from './notify';
import MyButton from './button';
class ScoreRow extends React.Component
{
constructor(props) {
super(props);
this.state = { score: 0 };
}
onClickScore(score) {
this.setState({ score: score });
this.props.onClickScore(this.props.judge.id, score);
}
render() {
const me = this
, currentScore = me.state.score
, buttons = [1,2,3,4,5].map((score) => {
let props = {
key: score
, children: score
, onClick: me.onClickScore.bind(me, score)
}
if (me.state.score == score) {
props.bsStyle = 'primary';
}
return <Button {...props} />;
});
return (
<tr>
<td>{this.props.judge.name}</td>
<td><ButtonGroup>{buttons}</ButtonGroup></td>
</tr>
);
}
};
ScoreRow.propTypes = {
judge: PropTypes.object.isRequired
, onClickScore: PropTypes.func.isRequired
};
class ScoreTable extends React.Component
{
constructor(props) {
super(props);
this.state = { results: [] };
}
getTotal() {
return _.reduce(this.state.results, (score, result) => {
return score + result.score;
}, 0)
}
onClickScore(judge, score) {
let results = this.state.results;
if (!results.length) {
results = this.props.judges.map((judge) => {
return {
judge: judge.id
, score: 0
};
});
}
this.setState({
results: results.map((result) => {
if (result.judge == judge) {
result.score = score;
}
return result;
})
});
}
onSubmit() {
const me = this;
Ajax.post(
`${document.baseURI}api/participant/score/${this.props.participant}`
, { score: this.getTotal() }
)
.done(() => {
Notify.Info('Score is successfully updated!');
});
}
render() {
const onClickScore = this.onClickScore.bind(this)
, total = this.getTotal()
, thead = (
<tr>
<th className='col-xs-9'>Judge</th>
<th className='col-xs-3'>
Total: {total}
<MyButton.Ok disabled={!total}
onClick={this.onSubmit.bind(this)} />
</th>
</tr>
)
, tbody = this.props.judges.map((judge) => {
return (
<ScoreRow key={judge.id}
judge={judge}
onClickScore={onClickScore} />
);
});
return <Table thead={thead} tbody={tbody} />;
}
};
ScoreTable.propTypes = {
participant: PropTypes.string.isRequired
, judges: PropTypes.arrayOf(PropTypes.object).isRequired
};
class ScorePage extends React.Component
{
constructor(props) {
super(props);
this.state = {
judges: []
, participant: {}
};
}
componentDidMount() {
const me = this;
Ajax.getJSON(`${document.baseURI}api/judge`)
.done((data) => me.setState({ judges: data }));
Ajax.getJSON(`${document.baseURI}api/participant/${me.props.participant}`)
.done((data) => me.setState({ participant: data }));
}
render() {
const data = this.state.participant
, title=`#${data.id} - ${data.fullname} (${data.costume})`
, message = data.message || '-'
, buttons = [(
<MyButton.Prev key='prev'
disabled={!data.prev}
href={`${document.baseURI}score/${data.prev}`} />
), (
<MyButton.List key='list'
href={`${document.baseURI}participants`} />
), (
<MyButton.Next key='next'
disabled={!data.next}
href={`${document.baseURI}score/${data.next}`} />
)];
return (
<div className='container'>
<Header title={title} buttons={buttons} />
<p><strong>Message:</strong> {message}</p>
<ScoreTable participant={this.props.participant} judges={this.state.judges} />
</div>
);
}
};
ScorePage.propTypes = {
participant: PropTypes.string.isRequired
};
module.exports = ScorePage;
|
src/svg-icons/content/content-paste.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentContentPaste = (props) => (
<SvgIcon {...props}>
<path d="M19 2h-4.18C14.4.84 13.3 0 12 0c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm7 18H5V4h2v3h10V4h2v16z"/>
</SvgIcon>
);
ContentContentPaste = pure(ContentContentPaste);
ContentContentPaste.displayName = 'ContentContentPaste';
ContentContentPaste.muiName = 'SvgIcon';
export default ContentContentPaste;
|
src/views/Comment/CommentText.js | shengnian/shengnian-ui-react | import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import {
childrenUtils,
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
/**
* A comment can contain text.
*/
function CommentText(props) {
const { className, children, content } = props
const classes = cx(className, 'text')
const rest = getUnhandledProps(CommentText, props)
const ElementType = getElementType(CommentText, props)
return (
<ElementType {...rest} className={classes}>
{childrenUtils.isNil(children) ? content : children}
</ElementType>
)
}
CommentText._meta = {
name: 'CommentText',
parent: 'Comment',
type: META.TYPES.VIEW,
}
CommentText.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
}
export default CommentText
|
admin/client/components/FlashMessages.js | andreufirefly/keystone | import React from 'react';
import { Alert } from 'elemental';
var FlashMessage = React.createClass({
displayName: 'FlashMessage',
propTypes: {
message: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.string,
]),
type: React.PropTypes.string,
},
renderMessage (message) {
if (typeof message === 'string') return <span>{message}</span>;
const title = message.title ? <h4>{message.title}</h4> : null;
const detail = message.detail ? <p>{message.detail}</p> : null;
const list = message.list ? (
<ul style={{ marginBottom: 0 }}>
{message.list.map((item, i) => <li key={`i${i}`}>{item}</li>)}
</ul>
) : null;
return (
<span>
{title}
{detail}
{list}
</span>
);
},
render () {
return <Alert type={this.props.type}>{this.renderMessage(this.props.message)}</Alert>;
},
});
var FlashMessages = React.createClass({
displayName: 'FlashMessages',
propTypes: {
messages: React.PropTypes.oneOfType([
React.PropTypes.bool,
React.PropTypes.shape({
error: React.PropTypes.array,
hilight: React.PropTypes.array,
info: React.PropTypes.array,
success: React.PropTypes.array,
warning: React.PropTypes.array,
}),
]),
},
renderMessages (messages, type) {
if (!messages || !messages.length) return null;
return messages.map((message, i) => {
return <FlashMessage message={message} type={type} key={`i${i}`} />;
});
},
renderTypes (types) {
return Object.keys(types).map(type => this.renderMessages(types[type], type));
},
render () {
if (!this.props.messages) return null;
return (
<div className="flash-messages">
{this.renderTypes(this.props.messages)}
</div>
);
},
});
module.exports = FlashMessages;
|
client/src/App.js | xmas-bunch/amigo-invisible | import React, { Component } from 'react';
import axios from 'axios';
import Message from './components/Message';
import Auth from './components/Auth';
import Gifts from './components/Gifts';
import './App.css';
class App extends Component {
constructor(){
super();
this.state = {
users: [],
user: null,
gifts: [],
message: null
}
}
componentDidMount(){
this.getUsers();
}
deleteMessage() {
this.setState({message: null});
}
getUsers(){
axios.get('/users')
.then(resp => {
this.setState({users: resp.data});
})
.catch(err => {
this.setState({message: err});
});
}
setUser(id) {
let user = this.state.users.find(user => {
return user.id == id;
});
user.isLoggedIn = false;
this.setState({user: user});
}
login(data){
data.username = this.state.user.username;
axios.post('/session', data)
.then(resp => {
resp.data.isLoggedIn = true;
this.setState({user: resp.data});
})
.catch(err => {
this.setState({message: err});
});
}
logout() {
this.deleteMessage();
this.setState({user: null});
}
register(data) {
axios.put(`/users/${this.state.user.id}`, data)
.then(resp => {
let user = this.state.user;
user.hasPassword = true;
user.isLoggedIn = true;
this.setState({
user: user,
message: {response: resp}
});
})
.catch(err => {
this.setState({message: err});
})
}
getGifts(){
axios.get(`users/${this.state.user.id}/gifts`)
.then(resp => {
this.setState({gifts: resp.data});
})
.catch(err => {
this.setState({message: err});
});
}
drawGift() {
axios.post(`users/${this.state.user.id}/gifts`)
.then(resp => {
this.getGifts();
})
.catch(err => {
this.setState({message: err});
})
}
render() {
let mainComponent;
if (this.state.user && this.state.user.isLoggedIn) {
mainComponent = (
<Gifts gifts={this.state.gifts}
getGifts={this.getGifts.bind(this)}
drawGift={this.drawGift.bind(this)}
logout={this.logout.bind(this)}/>
);
} else {
mainComponent = (
<Auth user={this.state.user}
users={this.state.users}
login={this.login.bind(this)}
setUser={this.setUser.bind(this)}
register={this.register.bind(this)}
deleteMessage={this.deleteMessage.bind(this)}
logout={this.logout.bind(this)}/>
);
}
return (
<div className="App">
<div className="App-header">
<img src="http://www.aqueduc.org/medias/billets/vignette1_happy_coaching_de_fin_d_annee.gif" className="App-logo" alt="logo" />
<h2>Aguante la Navidad</h2>
</div>
<Message message={this.state.message}
deleteMessage={this.deleteMessage.bind(this)}/>
{mainComponent}
</div>
);
}
}
export default App;
|
src/components/Layout.js | joellanciaux/Griddle | import React from 'react';
const component = ({Table, Pagination, Filter, SettingsWrapper, Style, className, style}) => (
<div className={className} style={style}>
{Style && <Style />}
<Filter />
<SettingsWrapper />
<Table />
<Pagination />
</div>
)
export default component;
|
src/components/start-game/start-game.js | greaveselliott/rock-paper-scissors | import React from 'react';
import './start-game.scss';
import Logo from '../logo';
import Heading from '../heading';
import ButtonToggleMode from '../button-toggle-mode';
import Button from '../button';
import { connect } from 'react-redux';
import { start_game } from '../../logic/actions';
export const StartGame = ({className, active, on_start_game}) => {
return (
<div className={`${className}${active ? "": "--inactive"}`}>
<div className="ie-center">
<div className="ie-center__inner">
<Logo/>
<Heading title="Pick mode."/>
<ButtonToggleMode/>
<Button click_handler={on_start_game} modifier="--large" text="Start"/>
</div>
</div>
</div>
);
};
const mapDispatchToProps = dispatch => ({
on_start_game: () => dispatch(start_game())
});
const mapStateToProps = state => {
return {
active: state.store.game_started === false
};
};
export default connect(mapStateToProps, mapDispatchToProps)(StartGame); |
src/svg-icons/image/brightness-7.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBrightness7 = (props) => (
<SvgIcon {...props}>
<path d="M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6zm0-10c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z"/>
</SvgIcon>
);
ImageBrightness7 = pure(ImageBrightness7);
ImageBrightness7.displayName = 'ImageBrightness7';
ImageBrightness7.muiName = 'SvgIcon';
export default ImageBrightness7;
|
src/app.js | chaoming56/react-blog | import React from 'react'
import ReactDOM from 'react-dom'
import createStore from './store/createStore'
import AppContainer from './containers/app_container'
/* --------------------
实例化 Store
-------------------- */
const initialState = window.___INITIAL_STATE__
const store = createStore(initialState)
/* --------------------
渲染设置
-------------------- */
const MOUNT_NODE = document.getElementById('root')
let render = () => {
const routes = require('./routes/index').default(store)
ReactDOM.render(
<AppContainer store={store} routes={routes} />,
MOUNT_NODE
)
}
/* --------------------
开发人员工具设置
-------------------- */
if (__DEV__) {
if (window.devToolsExtension) {
window.devToolsExtension.open()
}
}
// 此代码将从生产包中排除
if (__DEV__) {
if (module.hot) {
// 开发环境下的渲染方法
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react').default
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
}
// try/catch 判断渲染
render = () => {
try {
renderApp()
} catch (error) {
renderError(error)
}
}
// 设置模块热替换
module.hot.accept('./routes/index', () =>
setImmediate(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE)
render()
})
)
}
}
/* --------------------
运行起来
-------------------- */
render()
|
src/containers/transitionTo.js | danielriley06/react-redux-chat-example | import React from 'react'
import { connect } from 'react-redux'
import { browserHistory, Router } from 'react-router'
import log from 'middleware/logger'
export function transitionTo (Component) {
class transitionToComponent extends React.Component {
static propTypes = {
auth: React.PropTypes.object.isRequired
}
static contextTypes = {
store: React.PropTypes.any,
router: React.PropTypes.any
}
componentWillMount () {
const { store: { dispatch }, router } = this.context
router.replace({
pathname: '/app'
})
}
render () {
return (<Component {...this.props} />)
}
}
const mapStateToProps = (state) => ({
auth: state.auth
})
return connect(mapStateToProps)(transitionToComponent)
}
|
client/src/components/Signup/ProSignup.js | Darkrender/raptor-ads | import React, { Component } from 'react';
import { Button, Form, Grid, Header, Icon } from 'semantic-ui-react';
import { connect } from 'react-redux';
import classnames from 'classnames';
import { changeSignupField, customerSignup, clearErrors } from '../../actions';
class ProSignup extends Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.getFormClass = this.getFormClass.bind(this);
}
onChange(e) {
this.props.dispatch(changeSignupField(e.target.name, e.target.value));
}
onSubmit(e) {
e.preventDefault();
const data = this.props.signupForm;
data.role = 'professional';
this.props.dispatch(clearErrors());
this.props.dispatch(customerSignup(data));
}
getFormClass(name) {
return classnames({ fieldInvalid: this.props.formErrors[name] });
}
render() {
const {
firstName,
lastName,
email,
password,
passwordConfirmation,
businessName,
} = this.props.signupForm;
const { formErrors } = this.props;
return (
<div>
<div className="signup-buttons">
<Header textAlign="center"><Icon name="travel" />Professional Signup</Header>
</div>
<Grid width={16}>
<Grid.Column width={5} />
<Grid.Column width={11}>
{formErrors.userExists && <span className="formError">{formErrors.userExists}</span>}
{formErrors.firstName && <span className="formError">{formErrors.firstName}</span>}
<Form onSubmit={e => this.onSubmit(e)}>
<Form.Field width="8">
<label htmlFor="firstName">First Name</label>
<input
placeholder="First Name"
name="firstName"
value={firstName}
onChange={e => this.onChange(e)}
className={this.getFormClass('firstName')}
/>
</Form.Field>
{formErrors.lastName && <span className="formError">{formErrors.lastName}</span>}
<Form.Field width="8">
<label htmlFor="lastName">Last Name</label>
<input
placeholder="Last Name"
name="lastName"
value={lastName}
onChange={e => this.onChange(e)}
className={this.getFormClass('lastName')}
/>
</Form.Field>
{formErrors.email && <span className="formError">{formErrors.email}</span>}
<Form.Field width="8">
<label htmlFor="email">Email</label>
<input
placeholder="Email"
name="email"
value={email}
onChange={e => this.onChange(e)}
className={this.getFormClass('email')}
/>
</Form.Field>
<Form.Field width="8">
<label htmlFor="businessName">Business Name</label>
<input
placeholder="Company Name"
name="businessName"
value={businessName}
onChange={e => this.onChange(e)}
/>
</Form.Field>
{formErrors.password && <span className='formError'>{formErrors.password}</span>}
<Form.Field width="8">
<label htmlFor="password">Password</label>
<input
type="password"
placeholder="Password"
name="password"
value={password}
onChange={e => this.onChange(e)}
className={this.getFormClass('password')}
/>
</Form.Field>
{formErrors.passwordConfirmation && <span className='formError'>{formErrors.passwordConfirmation}</span>}
<Form.Field width="8">
<label htmlFor="confirmPassword">Confirm Password</label>
<input
type="password"
placeholder="Confirm Password"
name="passwordConfirmation"
value={passwordConfirmation}
onChange={e => this.onChange(e)}
className={this.getFormClass('passwordConfirmation')}
/>
</Form.Field>
<Form.Field width="8">
<Button type="submit">Sign Up</Button>
</Form.Field>
</Form>
</Grid.Column>
</Grid>
</div>
);
}
}
ProSignup.propTypes = {
signupForm: React.PropTypes.shape({
email: React.PropTypes.string.isRequired,
firstName: React.PropTypes.string.isRequired,
lastName: React.PropTypes.string.isRequired,
password: React.PropTypes.string.isRequired,
passwordConfirmation: React.PropTypes.string.isRequired,
}).isRequired,
dispatch: React.PropTypes.func.isRequired,
};
const mapStateToProps = (state) => {
const { signupForm, formErrors } = state.auth;
return {
signupForm,
formErrors,
};
};
export default connect(mapStateToProps)(ProSignup);
|
src/tick-trade/TickTradeMobile.js | qingweibinary/binary-next-gen | import React from 'react';
import MobilePage from '../containers/MobilePage';
import TickTradeContainer from './TickTradeContainer';
export default (props) => (
<MobilePage>
<TickTradeContainer compact {...props} />
</MobilePage>
);
|
src/svg-icons/hardware/phonelink.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwarePhonelink = (props) => (
<SvgIcon {...props}>
<path d="M4 6h18V4H4c-1.1 0-2 .9-2 2v11H0v3h14v-3H4V6zm19 2h-6c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h6c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1zm-1 9h-4v-7h4v7z"/>
</SvgIcon>
);
HardwarePhonelink = pure(HardwarePhonelink);
HardwarePhonelink.displayName = 'HardwarePhonelink';
HardwarePhonelink.muiName = 'SvgIcon';
export default HardwarePhonelink;
|
src/Grid/components/__tests__/fixtures.js | jmcriffey/react-ui | import React from 'react';
export default {
columns: [{
dataProp: 'id',
name: 'Id',
nameTooltip: 'This is the user id.'
}, {
dataProp: 'name',
name: 'Name',
nameTooltip: 'This is the user\'s name',
render(record, column, row) {
const message = (
`My name is ${record.name} - ` +
`column: ${column} ` +
`row: ${row}`
);
return (
<div>
{message}
</div>
);
}
}],
data: [{
id: 1,
name: 'Cool McCool'
}, {
id: 2,
name: 'Neat O\'Neatihan'
}, {
id: 2,
name: 'Tim'
}]
};
|
src/svg-icons/action/settings-bluetooth.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsBluetooth = (props) => (
<SvgIcon {...props}>
<path d="M11 24h2v-2h-2v2zm-4 0h2v-2H7v2zm8 0h2v-2h-2v2zm2.71-18.29L12 0h-1v7.59L6.41 3 5 4.41 10.59 10 5 15.59 6.41 17 11 12.41V20h1l5.71-5.71-4.3-4.29 4.3-4.29zM13 3.83l1.88 1.88L13 7.59V3.83zm1.88 10.46L13 16.17v-3.76l1.88 1.88z"/>
</SvgIcon>
);
ActionSettingsBluetooth = pure(ActionSettingsBluetooth);
ActionSettingsBluetooth.displayName = 'ActionSettingsBluetooth';
ActionSettingsBluetooth.muiName = 'SvgIcon';
export default ActionSettingsBluetooth;
|
src/Containers/TriggerContainer.js | sashasushko/moira-front | // @flow
import React from 'react';
import type { ContextRouter } from 'react-router-dom';
import type { IMoiraApi } from '../Api/MoiraAPI';
import type { Trigger, TriggerState } from '../Domain/Trigger';
import type { Metric } from '../Domain/Metric';
import type { Event } from '../Domain/Event';
import { withMoiraApi } from '../Api/MoiraApiInjection';
import TriggerInfo from '../Components/TriggerInfo/TriggerInfo';
import MetricList from '../Components/MetricList/MetricList';
import Tabs, { Tab } from '../Components/Tabs/Tabs';
import EventList from '../Components/EventList/EventList';
import Layout, { LayoutPlate, LayoutContent } from '../Components/Layout/Layout';
type Props = ContextRouter & { moiraApi: IMoiraApi };
type State = {|
loading: boolean;
error: boolean;
trigger: ?Trigger;
triggerState: ?TriggerState;
triggerEvents: ?{|
total: number;
list: Array<Event>;
page: number;
size: number;
|};
|};
class TriggerContainer extends React.Component {
props: Props;
state: State = {
loading: true,
error: true,
trigger: null,
triggerState: null,
triggerEvents: null,
};
componentDidMount() {
this.getData();
}
async getData(): Promise<void> {
const { moiraApi, match } = this.props;
const { id } = match.params;
if (typeof id !== 'string') {
return;
}
try {
const trigger = await moiraApi.getTrigger(id);
const triggerState = await moiraApi.getTriggerState(id);
const triggerEvents = await moiraApi.getTriggerEvents(id);
this.setState({ loading: false, trigger, triggerState, triggerEvents });
}
catch (error) {
this.setState({ error: true });
}
}
composeMetrics(): Array<{ name: string; data: Metric }> {
const { metrics } = this.state.triggerState || {};
return metrics ? Object.keys(metrics).map(x => ({ name: x, data: metrics[x] })) : []; // TODO
}
render(): React.Element<*> {
const { loading, error, trigger, triggerEvents } = this.state;
return (
<Layout loading={loading} loadingError={error}>
{trigger && (
<LayoutPlate>
<TriggerInfo data={trigger} />
</LayoutPlate>
)}
{this.composeMetrics().length !== 0 && (
<LayoutContent>
<Tabs value='state'>
<Tab id='state' label='Current state'>
<MetricList items={this.composeMetrics()} status />
</Tab>
<Tab id='events' label='Events history'>
<EventList items={triggerEvents ? triggerEvents.list : []} />
</Tab>
</Tabs>
</LayoutContent>
)}
</Layout>
);
}
}
export default withMoiraApi(TriggerContainer);
|
docs/src/app/components/pages/components/IconButton/ExampleComplex.js | spiermar/material-ui | import React from 'react';
import FontIcon from 'material-ui/FontIcon';
import IconButton from 'material-ui/IconButton';
import ActionHome from 'material-ui/svg-icons/action/home';
const IconButtonExampleComplex = () => (
<div>
<IconButton tooltip="Font Icon">
<FontIcon className="muidocs-icon-action-home" />
</IconButton>
<IconButton tooltip="SVG Icon">
<ActionHome />
</IconButton>
<IconButton
iconClassName="material-icons"
tooltip="Ligature"
>
home
</IconButton>
</div>
);
export default IconButtonExampleComplex;
|
src/svg-icons/image/linked-camera.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageLinkedCamera = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="14" r="3.2"/><path d="M16 3.33c2.58 0 4.67 2.09 4.67 4.67H22c0-3.31-2.69-6-6-6v1.33M16 6c1.11 0 2 .89 2 2h1.33c0-1.84-1.49-3.33-3.33-3.33V6"/><path d="M17 9c0-1.11-.89-2-2-2V4H9L7.17 6H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9h-5zm-5 10c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/>
</SvgIcon>
);
ImageLinkedCamera = pure(ImageLinkedCamera);
ImageLinkedCamera.displayName = 'ImageLinkedCamera';
ImageLinkedCamera.muiName = 'SvgIcon';
export default ImageLinkedCamera;
|
src/js/system/index.js | tpucci/jobads-webapp | import React from 'react';
export default class NotFound extends React.Component {
render() {
return(
<h1>Not found</h1>
);
}
} |
src/components/HomePage.js | t103z/interview | import React from 'react';
import {Link} from 'react-router';
const HomePage = () => {
return (
<div>
<h1>React Slingshot</h1>
<h2>Get Started</h2>
<ol>
<li>Review the <Link to="fuel-savings">demo app</Link></li>
<li>Remove the demo and start coding: npm run remove-demo</li>
</ol>
</div>
);
};
export default HomePage;
|
js/components/ReferenceTypeIcon.js | gilesbradshaw/uaQL | 'use strict';
// @flow
import React from 'react';
import Relay from 'react-relay';
import {createContainer} from 'recompose-relay';
import {compose} from 'recompose';
import ActionGrade from 'material-ui/lib/svg-icons/action/grade';
import ActionAssignment from 'material-ui/lib/svg-icons/action/assignment';
import FileFolder from 'material-ui/lib/svg-icons/file/folder';
import ContentArchive from 'material-ui/lib/svg-icons/content/archive';
import ContentSend from 'material-ui/lib/svg-icons/content/send';
import CommunicationCall from 'material-ui/lib/svg-icons/communication/call';
import ActionHelp from 'material-ui/lib/svg-icons/action/help';
import ActionAlarm from 'material-ui/lib/svg-icons/action/alarm';
const ReferenceTypeIcon = compose(
createContainer(
{
fragments: {
viewer: () => Relay.QL`
fragment on ReferenceDescription {
referenceTypeId {
uaNode {
displayName {
text
}
}
}
}
`
}
}
)
)(({viewer})=> {
switch(viewer.referenceTypeId.uaNode.displayName.text) {
case 'HasComponent' :
return <ActionGrade/>
case 'Organizes' :
return <FileFolder/>
case 'HasSubtype' :
return <ContentArchive/>
case 'HasTypeDefinition' :
return <ContentSend/>
case 'HasNotifier' :
return <CommunicationCall/>
case 'HasProperty' :
return <ActionAssignment/>
case 'HasEventSource' :
return <ActionAlarm/>
}
return <ActionHelp/>
}
);
export default ReferenceTypeIcon;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.