path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
frontend/src/components/tree-view/tree-node-view.js | miurahr/seahub | import React from 'react';
import PropTypes from 'prop-types';
import { permission } from '../../utils/constants';
import TextTranslation from '../../utils/text-translation';
import ItemDropdownMenu from '../dropdown-menu/item-dropdown-menu';
const propTypes = {
repoPermission: PropTypes.bool,
node: PropTypes.object.isRequired,
currentPath: PropTypes.string.isRequired,
paddingLeft: PropTypes.number.isRequired,
isNodeMenuShow: PropTypes.bool.isRequired,
isItemFreezed: PropTypes.bool.isRequired,
onNodeClick: PropTypes.func.isRequired,
onNodeExpanded: PropTypes.func.isRequired,
onNodeCollapse: PropTypes.func.isRequired,
onNodeDragStart: PropTypes.func.isRequired,
freezeItem: PropTypes.func.isRequired,
unfreezeItem: PropTypes.func.isRequired,
onMenuItemClick: PropTypes.func,
onNodeDragMove: PropTypes.func,
onNodeDrop: PropTypes.func,
handleContextClick: PropTypes.func.isRequired,
onNodeDragEnter: PropTypes.func.isRequired,
onNodeDragLeave:PropTypes.func.isRequired,
};
class TreeNodeView extends React.Component {
constructor(props) {
super(props);
this.state = {
isHighlight: false,
isShowOperationMenu: false,
isNodeDropShow: false,
};
}
componentWillReceiveProps(nextProps) {
if (!nextProps.isItemFreezed) {
this.setState({
isShowOperationMenu: false,
isHighlight: false,
});
}
}
onMouseEnter = () => {
if (!this.props.isItemFreezed) {
this.setState({
isShowOperationMenu: true,
isHighlight: true,
});
}
}
onMouseOver = () => {
if (!this.props.isItemFreezed) {
this.setState({
isShowOperationMenu: true,
isHighlight: true,
});
}
}
onMouseLeave = () => {
if (!this.props.isItemFreezed) {
this.setState({
isShowOperationMenu: false,
isHighlight: false,
});
}
}
onNodeClick = () => {
this.props.onNodeClick(this.props.node);
}
onLoadToggle = (e) => {
e.stopPropagation();
let { node } = this.props;
if (node.isExpanded) {
this.props.onNodeCollapse(node);
} else {
this.props.onNodeExpanded(node);
}
}
onNodeDragStart = (e) => {
this.props.onNodeDragStart(e, this.props.node);
}
onNodeDragEnter = (e) => {
if (this.props.node.object.type === 'dir') {
this.setState({isNodeDropShow: true});
}
this.props.onNodeDragEnter(e, this.props.node);
}
onNodeDragMove = (e) => {
this.props.onNodeDragMove(e);
}
onNodeDragLeave = (e) => {
this.setState({isNodeDropShow: false});
this.props.onNodeDragLeave(e, this.props.node);
}
onNodeDrop = (e) => {
e.stopPropagation();
this.setState({isNodeDropShow: false});
this.props.onNodeDrop(e, this.props.node);
}
unfreezeItem = () => {
this.setState({isShowOperationMenu: false});
this.props.unfreezeItem();
}
onMenuItemClick = (operation, event, node) => {
this.props.onMenuItemClick(operation, node);
}
onItemMouseDown = (event) => {
event.stopPropagation();
if (event.button === 2) {
return;
}
}
onItemContextMenu = (event) => {
this.handleContextClick(event);
}
handleContextClick = (event) => {
this.props.handleContextClick(event, this.props.node);
this.setState({isShowOperationMenu: false});
}
getNodeTypeAndIcon = () => {
let { node } = this.props;
let icon = '';
let type = '';
if (node.object.type === 'dir') {
icon = <i className="far fa-folder"></i>;
type = 'dir';
} else {
let index = node.object.name.lastIndexOf('.');
if (index === -1) {
icon = <i className="far fa-file"></i>;
type = 'file';
} else {
let suffix = node.object.name.slice(index).toLowerCase();
if (suffix === '.png' || suffix === '.jpg' || suffix === '.jpeg' || suffix === '.gif' || suffix === '.bmp') {
icon = <i className="far fa-image"></i>;
type = 'image';
}
else if (suffix === '.md' || suffix === '.markdown') {
icon = <i className="far fa-file-alt"></i>;
type = 'file';
}
else {
icon = <i className="far fa-file"></i>;
type = 'file';
}
}
}
return {icon, type};
}
caculateMenuList(node) {
let { NEW_FOLDER, NEW_FILE, COPY, MOVE, RENAME, DELETE, OPEN_VIA_CLIENT} = TextTranslation;
if (node.object.type === 'dir') {
return [NEW_FOLDER, NEW_FILE, COPY, MOVE, RENAME, DELETE];
}
return [RENAME, DELETE, COPY, MOVE, OPEN_VIA_CLIENT];
}
renderChildren = () => {
let { node, paddingLeft } = this.props;
if (!node.hasChildren()) {
return '';
}
return (
<div className="children" style={{paddingLeft: paddingLeft}}>
{node.children.map(item => {
return (
<TreeNodeView
key={item.path}
node={item}
paddingLeft={paddingLeft}
repoPermission={this.props.repoPermission}
currentPath={this.props.currentPath}
isNodeMenuShow={this.props.isNodeMenuShow}
isItemFreezed={this.props.isItemFreezed}
onNodeClick={this.props.onNodeClick}
onNodeCollapse={this.props.onNodeCollapse}
onNodeExpanded={this.props.onNodeExpanded}
freezeItem={this.props.freezeItem}
onMenuItemClick={this.props.onMenuItemClick}
unfreezeItem={this.unfreezeItem}
onNodeDragStart={this.props.onNodeDragStart}
onNodeDragMove={this.props.onNodeDragMove}
onNodeDrop={this.props.onNodeDrop}
onNodeDragEnter={this.props.onNodeDragEnter}
onNodeDragLeave={this.props.onNodeDragLeave}
handleContextClick={this.props.handleContextClick}
/>
);
})}
</div>
);
}
render() {
let { currentPath, node, isNodeMenuShow } = this.props;
let { type, icon } = this.getNodeTypeAndIcon();
let hlClass = this.state.isHighlight ? 'tree-node-inner-hover ' : '';
if (node.path === currentPath) {
hlClass = 'tree-node-hight-light';
}
return (
<div className="tree-node">
<div
type={type}
className={`tree-node-inner text-nowrap ${hlClass} ${node.path === '/'? 'hide': ''} ${this.state.isNodeDropShow ? 'tree-node-drop' : ''}`}
title={node.object.name}
onMouseEnter={this.onMouseEnter}
onMouseOver={this.onMouseOver}
onMouseLeave={this.onMouseLeave}
onMouseDown={this.onItemMouseDown}
onContextMenu={this.onItemContextMenu}
onClick={this.onNodeClick}
>
<div className="tree-node-text" draggable="true" onDragStart={this.onNodeDragStart} onDragEnter={this.onNodeDragEnter} onDragLeave={this.onNodeDragLeave} onDragOver={this.onNodeDragMove} onDrop={this.onNodeDrop}>{node.object.name}</div>
<div className="left-icon">
{type === 'dir' && (!node.isLoaded || (node.isLoaded && node.hasChildren())) && (
<i
className={`folder-toggle-icon fa ${node.isExpanded ? 'fa-caret-down' : 'fa-caret-right'}`}
onMouseDown={e => e.stopPropagation()}
onClick={this.onLoadToggle}
></i>
)}
<i className="tree-node-icon">{icon}</i>
</div>
{isNodeMenuShow && (
<div className="right-icon">
{((this.props.repoPermission || permission) && this.state.isShowOperationMenu) && (
<ItemDropdownMenu
item={this.props.node}
toggleClass={'fas fa-ellipsis-v'}
getMenuList={this.caculateMenuList}
onMenuItemClick={this.onMenuItemClick}
freezeItem={this.props.freezeItem}
unfreezeItem={this.unfreezeItem}
/>
)}
</div>
)}
</div>
{node.isExpanded && this.renderChildren()}
</div>
);
}
}
TreeNodeView.propTypes = propTypes;
export default TreeNodeView;
|
src/components/calendar/CheckoutForm.js | ChrisWhiten/react-rink | import React from 'react';
import PropTypes from 'prop-types';
import {injectStripe} from 'react-stripe-elements';
import Snackbar from 'material-ui/Snackbar';
import {
Form,
Col,
// Checkbox,
} from 'react-bootstrap';
import PersonalInfoSection from './PersonalInfoSection';
import CardSection from './CardSection';
import DateAndTimeSection from './DateAndTimeSection';
import NumberOfGuestsSection from './NumberOfGuestsSection';
import './styles/CheckoutForm.css';
class CheckoutForm extends React.Component {
constructor(props) {
super(props);
this.state = {
active: false,
cost: 0,
showSnackbar: false,
snackbarMessage: '',
};
this.payLater = this.payLater.bind(this);
this.onGuestCountChange = this.onGuestCountChange.bind(this);
this.hideSnackbar = this.hideSnackbar.bind(this);
}
componentWillReceiveProps(nextProps) {
if (nextProps.booking && this.props.booking && nextProps.booking.id !== this.props.booking.id) {
this.personalInfoRef.clear();
}
}
onGuestCountChange(guestCount) {
this.setState({
cost: guestCount * 2400,
});
}
renderCurrency(c) {
let dollarAmount = c/100;
if (c % 100 === 0) {
return parseInt(dollarAmount, 10).toString();
}
return dollarAmount.toFixed(2);
}
validateForm() {
if (!this.personalInfoRef.state.firstName) {
this.setState({
showSnackbar: true,
snackbarMessage: 'Please provide a first name',
});
return false;
}
if (!this.personalInfoRef.state.lastName) {
this.setState({
showSnackbar: true,
snackbarMessage: 'Please provide a last name',
});
return false;
}
if (!this.personalInfoRef.state.email) {
this.setState({
showSnackbar: true,
snackbarMessage: 'Please provide an email',
});
return false;
}
if (!this.personalInfoRef.state.phoneNumber) {
this.setState({
showSnackbar: true,
snackbarMessage: 'Please provide a phone number',
});
return false;
}
if (!this.guestsSection.state.numberOfGuests) {
this.setState({
showSnackbar: true,
snackbarMessage: 'Please select how many guests will join',
});
return false;
}
return true;
}
hideSnackbar() {
this.setState({
showSnackbar: false,
});
}
payLater() {
const defaultCost = 2400;
console.log('pay later');
console.log(this.personalInfoRef.state);
console.log(this.guestsSection.state);
console.warn(this.props.booking);
if (!this.validateForm()) {
return;
}
if (this.props.payLater) {
this.props.payLater({
leaderFirstName: this.personalInfoRef.state.firstName,
leaderLastName: this.personalInfoRef.state.lastName,
leaderEmail: this.personalInfoRef.state.email,
leaderPhoneNumber: this.personalInfoRef.state.phoneNumber,
slotCount: this.guestsSection.state.numberOfGuests,
locationName: this.props.location.locationName,
locationId: this.props.location.locationId,
start: new Date(this.props.booking.availabilitySlot.startTime).getTime(),
duration: this.props.booking.availabilitySlot.duration,
bookingCost: defaultCost * this.guestsSection.state.numberOfGuests,
checkedIn: 0,
}, (bookingCreated => {
console.log('made it to checkoutform bookingCreated', bookingCreated);
}));
}
}
_handleSubmit = (ev) => {
// We don't want to let default form submission happen here, which would refresh the page.
ev.preventDefault();
if (!this.validateForm()) {
return;
}
// Within the context of `Elements`, this call to createToken knows which Element to
// tokenize, since there's only one in this group.
this.props.stripe.createToken({name: 'Jenny Rosen'}).then(({token}) => {
console.log('Received Stripe token:', token);
// this isn't the same thing, but hacking it together to get the flow right.
// TODO: fix me
const defaultCost = 2400;
const bookingCost = defaultCost * this.guestsSection.state.numberOfGuests;
this.props.createPaidBooking({
leaderFirstName: this.personalInfoRef.state.firstName,
leaderLastName: this.personalInfoRef.state.lastName,
leaderEmail: this.personalInfoRef.state.email,
leaderPhoneNumber: this.personalInfoRef.state.phoneNumber,
slotCount: this.guestsSection.state.numberOfGuests,
locationName: this.props.location.locationName,
locationId: this.props.location.locationId,
start: new Date(this.props.booking.availabilitySlot.startTime).getTime(),
duration: this.props.booking.availabilitySlot.duration,
payments: [bookingCost],
bookingCost: bookingCost,
checkedIn: 0,
}, (bookingCreated => {
console.log('made it to checkoutform bookingCreated', bookingCreated);
}));
});
// However, this line of code will do the same thing:
// this.props.stripe.createToken({type: 'card', name: 'Jenny Rosen'});
}
render() {
let slotCount = 0;
if (this.props.booking && this.props.booking.availabilitySlot) {
slotCount = this.props.booking.availabilitySlot.totalSlots;
if (this.props.booking.availabilitySlot.bookings) {
this.props.booking.availabilitySlot.bookings.forEach(b => {
slotCount -= b.slotCount;
});
}
}
return (
<Form onSubmit={this._handleSubmit}>
<DateAndTimeSection location={this.props.location} booking={this.props.booking} />
<Col sm={6} md={6} xs={12} smOffset={3} mdOffset={3} className='checkout-form-container'>
<NumberOfGuestsSection
ref={(guestsSection) => this.guestsSection = guestsSection}
slotCount={slotCount}
onGuestCountChange={this.onGuestCountChange}
/>
<PersonalInfoSection ref={(personalInfoRef) => this.personalInfoRef = personalInfoRef} />
<Col sm={12} md={12} xs={12}>
{/* <Checkbox>
Yes, I have read and agree with the waiver
</Checkbox> */}
<CardSection />
<button className='checkout-button' disabled={!this.state.cost}>Confirm order <small>(${this.renderCurrency(this.state.cost)})</small></button>
<div className='pay-later-button' onClick={this.payLater}><a>Or confirm now and pay on-site</a></div>
</Col>
</Col>
<Snackbar
open={this.state.showSnackbar}
message={this.state.snackbarMessage}
autoHideDuration={4000}
onRequestClose={this.hideSnackbar}
/>
</Form>
);
}
}
CheckoutForm.propTypes = {
booking: PropTypes.object,
screenHeight: PropTypes.number,
};
export default injectStripe(CheckoutForm);
// export default CheckoutForm |
react/dashboard_example/src/components/Header/Header.js | webmaster444/webmaster444.github.io | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 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 withStyles from 'isomorphic-style-loader/lib/withStyles';
import {
Nav,
NavItem,
NavDropdown,
MenuItem,
ProgressBar,
} from 'react-bootstrap';
import Navbar, {Brand} from 'react-bootstrap/lib/Navbar';
import history from '../../core/history';
import $ from "jquery";
import Sidebar from '../Sidebar';
const logo = require('./logo.png');
function Header() {
return (
<div id="wrapper" className="content">
<Navbar fluid={true} style={ {margin: 0} }>
<Brand>
<span>
<img src={logo} alt="Start React" title="Start React" />
<span> SB Admin React - </span>
<a href="http://startreact.com/" title="Start React" rel="home">StartReact.com</a>
<button type="button" className="navbar-toggle" onClick={() => {toggleMenu();}} style={{position: 'absolute', right: 0, top: 0}}>
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
</span>
</Brand>
<ul className="nav navbar-top-links navbar-right">
<NavDropdown bsClass="dropdown" title={<span><i className="fa fa-envelope fa-fw"></i></span>} id="navDropdown1">
<MenuItem style={ {width: 300} } eventKey="1">
<div> <strong>John Smith</strong> <span className="pull-right text-muted"> <em>Yesterday</em> </span> </div>
<div> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="2">
<div> <strong>John Smith</strong> <span className="pull-right text-muted"> <em>Yesterday</em> </span> </div>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="3">
<div> <strong>John Smith</strong> <span className="pull-right text-muted"> <em>Yesterday</em> </span> </div>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="4" className="text-center">
<strong>Read All Messages</strong> <i className="fa fa-angle-right"></i>
</MenuItem>
</NavDropdown>
<NavDropdown title={<span><i className="fa fa-tasks fa-fw"></i> </span>} id = 'navDropdown2222'>
<MenuItem eventKey="1" style={ {width: 300} }>
<div>
<p> <strong>Task 1</strong> <span className="pull-right text-muted">40% Complete</span> </p>
<div>
<ProgressBar bsStyle="success" now={40} />
</div>
</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="2">
<div>
<p> <strong>Task 2</strong> <span className="pull-right text-muted">20% Complete</span> </p>
<div>
<ProgressBar bsStyle="info" now={20} />
</div>
</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="3">
<div>
<p> <strong>Task 3</strong> <span className="pull-right text-muted">60% Complete</span> </p>
<div>
<ProgressBar bsStyle="warning" now={60} />
</div>
</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="4">
<div>
<p> <strong>Task 4</strong> <span className="pull-right text-muted">80% Complete</span> </p>
<div>
<ProgressBar bsStyle="danger" now={80} />
</div>
</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="5">
<strong>See All Tasks</strong> <i className="fa fa-angle-right"></i>
</MenuItem>
</NavDropdown>
<NavDropdown title={<i className="fa fa-bell fa-fw"></i>} id = 'navDropdown3'>
<MenuItem eventKey="1" style={ {width: 300} }>
<div> <i className="fa fa-comment fa-fw"></i> New Comment <span className="pull-right text-muted small">4 minutes ago</span> </div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="2">
<div> <i className="fa fa-twitter fa-fw"></i> 3 New Followers <span className="pull-right text-muted small">12 minutes ago</span> </div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="3">
<div> <i className="fa fa-envelope fa-fw"></i> Message Sent <span className="pull-right text-muted small">4 minutes ago</span> </div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="4">
<div> <i className="fa fa-tasks fa-fw"></i> New Task <span className="pull-right text-muted small">4 minutes ago</span> </div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="5">
<div> <i className="fa fa-upload fa-fw"></i> Server Rebooted <span className="pull-right text-muted small">4 minutes ago</span> </div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="6">
<strong>See All Alerts</strong> <i className="fa fa-angle-right"></i>
</MenuItem>
</NavDropdown>
<NavDropdown title={<i className="fa fa-user fa-fw"></i> } id = 'navDropdown4'>
<MenuItem eventKey="1">
<span> <i className="fa fa-user fa-fw"></i> User Profile </span>
</MenuItem>
<MenuItem eventKey="2">
<span><i className="fa fa-gear fa-fw"></i> Settings </span>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey = "3" href = 'http://www.strapui.com' >
<span> <i className = "fa fa-eye fa-fw" /> Premium React Themes </span>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey = "4" onClick = {(event) => { history.push('/login');}}>
<span> <i className = "fa fa-sign-out fa-fw" /> Logout </span>
</MenuItem>
</NavDropdown>
</ul>
<Sidebar />
</Navbar>
</div>
);
}
function toggleMenu(){
if($(".navbar-collapse").hasClass('collapse')){
$(".navbar-collapse").removeClass('collapse');
}
else{
$(".navbar-collapse").addClass('collapse');
}
}
export default Header;
|
src/App.js | robreczarek/clouds-stepone-app | import React, { Component } from 'react';
import Logout from './Logout';
import Nav from './Nav';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<h2>Sample Recruitment App</h2>
</div>
<Nav />
<Logout />
<div className="content">
{this.props.children}
</div>
</div>
);
}
}
export default App;
|
src/js/contexts/ResponsiveContext/ResponsiveContext.js | grommet/grommet | import React from 'react';
import { ResponsiveContextPropTypes } from './propTypes';
export const ResponsiveContext = React.createContext(undefined);
ResponsiveContext.propTypes = ResponsiveContextPropTypes;
|
old-or-not-typescript/React-RxJS/src/routes/Login.js | janaagaard75/framework-investigations | import React from 'react';
const Login = () => (
<div className="jumbotron text-center">
<h1>Login</h1>
</div>
);
export default Login;
|
storybook/stories/Tabs.story.js | entria/entria-components | import React from 'react';
import { storiesOf } from '@kadira/storybook';
import { Tabs, Tab, RoutedTabs, ScrollableRoutedTabs } from '../../src';
const stories = storiesOf('Tabs', module);
stories.add('default', () =>
<div style={styles.wrapper}>
<Tabs>
<Tab label="Tab 1">
<div style={styles.tabComponent}>Component 1</div>
</Tab>
<Tab label="Tab 2">
<div style={styles.tabComponent}>Component 2</div>
</Tab>
<Tab label="Tab 3">
<div style={styles.tabComponent}>Component 3</div>
</Tab>
</Tabs>
</div>
);
stories.add('RoutedTabs', () =>
<div style={styles.wrapper}>
<p style={styles.message}>I change the route when you click me!</p>
<RoutedTabs
tabs={[
{
route: '/route-1',
label: 'Tab 1',
component: <div style={styles.tabComponent}>Component 1</div>,
},
{
route: '/route-2',
label: 'Tab 2',
component: <div style={styles.tabComponent}>Component 2</div>,
},
{
route: '/route-3',
label: 'Tab 3',
component: <div style={styles.tabComponent}>Component 3</div>,
},
]}
/>
</div>
);
stories.add('ScrollableRoutedTabs', () =>
<div style={styles.wrapper}>
<p style={styles.message}>I change the route when you click me!</p>
<ScrollableRoutedTabs
tabs={[
{
route: '/route-1',
label: 'Tab 1',
component: <div style={styles.tabComponent}>Component 1</div>,
},
{
route: '/route-2',
label: 'Tab 2',
component: <div style={styles.tabComponent}>Component 2</div>,
},
{
route: '/route-3',
label: 'Tab 3',
component: <div style={styles.tabComponent}>Component 3</div>,
},
{
route: '/route-4',
label: 'Tab 4',
component: <div style={styles.tabComponent}>Component 4</div>,
},
{
route: '/route-5',
label: 'Tab 5',
component: <div style={styles.tabComponent}>Component 5</div>,
},
{
route: '/route-6',
label: 'Tab 6',
component: <div style={styles.tabComponent}>Component 6</div>,
},
{
route: '/route-7',
label: 'Tab 7',
component: <div style={styles.tabComponent}>Component 7</div>,
},
{
route: '/route-8',
label: 'Tab 8',
component: <div style={styles.tabComponent}>Component 8</div>,
},
{
route: '/route-9',
label: 'Tab 9',
component: <div style={styles.tabComponent}>Component 9</div>,
},
]}
/>
</div>
);
const styles = {
wrapper: {
padding: 20,
},
message: {
marginBottom: 30,
},
tabComponent: {
padding: 20,
},
};
|
docs/src/Root.js | westonplatter/react-bootstrap | import React from 'react';
import Router from 'react-router';
const Root = React.createClass({
statics: {
/**
* Get the list of pages that are renderable
*
* @returns {Array}
*/
getPages() {
return [
'index.html',
'introduction.html',
'getting-started.html',
'components.html',
'support.html'
];
}
},
getDefaultProps() {
return {
assetBaseUrl: ''
};
},
childContextTypes: {
metadata: React.PropTypes.object
},
getChildContext() {
return { metadata: this.props.propData };
},
render() {
// Dump out our current props to a global object via a script tag so
// when initialising the browser environment we can bootstrap from the
// same props as what each page was rendered with.
let browserInitScriptObj = {
__html:
`window.INITIAL_PROPS = ${JSON.stringify(this.props)};
// console noop shim for IE8/9
(function (w) {
var noop = function () {};
if (!w.console) {
w.console = {};
['log', 'info', 'warn', 'error'].forEach(function (method) {
w.console[method] = noop;
});
}
}(window));`
};
let head = {
__html: `<title>React-Bootstrap</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="${this.props.assetBaseUrl}/assets/bundle.css" rel="stylesheet">
<link href="${this.props.assetBaseUrl}/assets/favicon.ico?v=2" type="image/x-icon" rel="shortcut icon">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-shim.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-sham.js"></script>
<![endif]-->`
};
return (
<html>
<head dangerouslySetInnerHTML={head} />
<body>
<Router.RouteHandler propData={this.props.propData} />
<script dangerouslySetInnerHTML={browserInitScriptObj} />
<script src={`${this.props.assetBaseUrl}/assets/bundle.js`} />
</body>
</html>
);
}
});
export default Root;
|
src/svg-icons/device/signal-wifi-2-bar.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalWifi2Bar = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" 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"/><path d="M4.79 12.52l7.2 8.98H12l.01-.01 7.2-8.98C18.85 12.24 16.1 10 12 10s-6.85 2.24-7.21 2.52z"/>
</SvgIcon>
);
DeviceSignalWifi2Bar = pure(DeviceSignalWifi2Bar);
DeviceSignalWifi2Bar.displayName = 'DeviceSignalWifi2Bar';
export default DeviceSignalWifi2Bar;
|
src/components/Subscribe.js | ViniciusAtaide/reduxchat | import React, { Component } from 'react';
export default class Subscribe extends Component {
render() {
return (
<h1>Subscribe</h1>
);
}
} |
app/javascript/mastodon/features/compose/components/emoji_picker_dropdown.js | yukimochi/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { EmojiPicker as EmojiPickerAsync } from '../../ui/util/async-components';
import Overlay from 'react-overlays/lib/Overlay';
import classNames from 'classnames';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { supportsPassiveEvents } from 'detect-passive-events';
import { buildCustomEmojis, categoriesFromEmojis } from '../../emoji/emoji';
import { assetHost } from 'mastodon/utils/config';
const messages = defineMessages({
emoji: { id: 'emoji_button.label', defaultMessage: 'Insert emoji' },
emoji_search: { id: 'emoji_button.search', defaultMessage: 'Search...' },
custom: { id: 'emoji_button.custom', defaultMessage: 'Custom' },
recent: { id: 'emoji_button.recent', defaultMessage: 'Frequently used' },
search_results: { id: 'emoji_button.search_results', defaultMessage: 'Search results' },
people: { id: 'emoji_button.people', defaultMessage: 'People' },
nature: { id: 'emoji_button.nature', defaultMessage: 'Nature' },
food: { id: 'emoji_button.food', defaultMessage: 'Food & Drink' },
activity: { id: 'emoji_button.activity', defaultMessage: 'Activity' },
travel: { id: 'emoji_button.travel', defaultMessage: 'Travel & Places' },
objects: { id: 'emoji_button.objects', defaultMessage: 'Objects' },
symbols: { id: 'emoji_button.symbols', defaultMessage: 'Symbols' },
flags: { id: 'emoji_button.flags', defaultMessage: 'Flags' },
});
let EmojiPicker, Emoji; // load asynchronously
const listenerOptions = supportsPassiveEvents ? { passive: true } : false;
const backgroundImageFn = () => `${assetHost}/emoji/sheet_13.png`;
const notFoundFn = () => (
<div className='emoji-mart-no-results'>
<Emoji
emoji='sleuth_or_spy'
set='twitter'
size={32}
sheetSize={32}
backgroundImageFn={backgroundImageFn}
/>
<div className='emoji-mart-no-results-label'>
<FormattedMessage id='emoji_button.not_found' defaultMessage='No matching emojis found' />
</div>
</div>
);
class ModifierPickerMenu extends React.PureComponent {
static propTypes = {
active: PropTypes.bool,
onSelect: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
};
handleClick = e => {
this.props.onSelect(e.currentTarget.getAttribute('data-index') * 1);
}
componentWillReceiveProps (nextProps) {
if (nextProps.active) {
this.attachListeners();
} else {
this.removeListeners();
}
}
componentWillUnmount () {
this.removeListeners();
}
handleDocumentClick = e => {
if (this.node && !this.node.contains(e.target)) {
this.props.onClose();
}
}
attachListeners () {
document.addEventListener('click', this.handleDocumentClick, false);
document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
removeListeners () {
document.removeEventListener('click', this.handleDocumentClick, false);
document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
setRef = c => {
this.node = c;
}
render () {
const { active } = this.props;
return (
<div className='emoji-picker-dropdown__modifiers__menu' style={{ display: active ? 'block' : 'none' }} ref={this.setRef}>
<button onClick={this.handleClick} data-index={1}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={1} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={2}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={2} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={3}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={3} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={4}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={4} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={5}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={5} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={6}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={6} backgroundImageFn={backgroundImageFn} /></button>
</div>
);
}
}
class ModifierPicker extends React.PureComponent {
static propTypes = {
active: PropTypes.bool,
modifier: PropTypes.number,
onChange: PropTypes.func,
onClose: PropTypes.func,
onOpen: PropTypes.func,
};
handleClick = () => {
if (this.props.active) {
this.props.onClose();
} else {
this.props.onOpen();
}
}
handleSelect = modifier => {
this.props.onChange(modifier);
this.props.onClose();
}
render () {
const { active, modifier } = this.props;
return (
<div className='emoji-picker-dropdown__modifiers'>
<Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={modifier} onClick={this.handleClick} backgroundImageFn={backgroundImageFn} />
<ModifierPickerMenu active={active} onSelect={this.handleSelect} onClose={this.props.onClose} />
</div>
);
}
}
@injectIntl
class EmojiPickerMenu extends React.PureComponent {
static propTypes = {
custom_emojis: ImmutablePropTypes.list,
frequentlyUsedEmojis: PropTypes.arrayOf(PropTypes.string),
loading: PropTypes.bool,
onClose: PropTypes.func.isRequired,
onPick: PropTypes.func.isRequired,
style: PropTypes.object,
placement: PropTypes.string,
arrowOffsetLeft: PropTypes.string,
arrowOffsetTop: PropTypes.string,
intl: PropTypes.object.isRequired,
skinTone: PropTypes.number.isRequired,
onSkinTone: PropTypes.func.isRequired,
};
static defaultProps = {
style: {},
loading: true,
frequentlyUsedEmojis: [],
};
state = {
modifierOpen: false,
placement: null,
};
handleDocumentClick = e => {
if (this.node && !this.node.contains(e.target)) {
this.props.onClose();
}
}
componentDidMount () {
document.addEventListener('click', this.handleDocumentClick, false);
document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
componentWillUnmount () {
document.removeEventListener('click', this.handleDocumentClick, false);
document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
setRef = c => {
this.node = c;
}
getI18n = () => {
const { intl } = this.props;
return {
search: intl.formatMessage(messages.emoji_search),
categories: {
search: intl.formatMessage(messages.search_results),
recent: intl.formatMessage(messages.recent),
people: intl.formatMessage(messages.people),
nature: intl.formatMessage(messages.nature),
foods: intl.formatMessage(messages.food),
activity: intl.formatMessage(messages.activity),
places: intl.formatMessage(messages.travel),
objects: intl.formatMessage(messages.objects),
symbols: intl.formatMessage(messages.symbols),
flags: intl.formatMessage(messages.flags),
custom: intl.formatMessage(messages.custom),
},
};
}
handleClick = (emoji, event) => {
if (!emoji.native) {
emoji.native = emoji.colons;
}
if (!(event.ctrlKey || event.metaKey)) {
this.props.onClose();
}
this.props.onPick(emoji);
}
handleModifierOpen = () => {
this.setState({ modifierOpen: true });
}
handleModifierClose = () => {
this.setState({ modifierOpen: false });
}
handleModifierChange = modifier => {
this.props.onSkinTone(modifier);
}
render () {
const { loading, style, intl, custom_emojis, skinTone, frequentlyUsedEmojis } = this.props;
if (loading) {
return <div style={{ width: 299 }} />;
}
const title = intl.formatMessage(messages.emoji);
const { modifierOpen } = this.state;
const categoriesSort = [
'recent',
'people',
'nature',
'foods',
'activity',
'places',
'objects',
'symbols',
'flags',
];
categoriesSort.splice(1, 0, ...Array.from(categoriesFromEmojis(custom_emojis)).sort());
return (
<div className={classNames('emoji-picker-dropdown__menu', { selecting: modifierOpen })} style={style} ref={this.setRef}>
<EmojiPicker
perLine={8}
emojiSize={22}
sheetSize={32}
custom={buildCustomEmojis(custom_emojis)}
color=''
emoji=''
set='twitter'
title={title}
i18n={this.getI18n()}
onClick={this.handleClick}
include={categoriesSort}
recent={frequentlyUsedEmojis}
skin={skinTone}
showPreview={false}
showSkinTones={false}
backgroundImageFn={backgroundImageFn}
notFound={notFoundFn}
autoFocus
emojiTooltip
/>
<ModifierPicker
active={modifierOpen}
modifier={skinTone}
onOpen={this.handleModifierOpen}
onClose={this.handleModifierClose}
onChange={this.handleModifierChange}
/>
</div>
);
}
}
export default @injectIntl
class EmojiPickerDropdown extends React.PureComponent {
static propTypes = {
custom_emojis: ImmutablePropTypes.list,
frequentlyUsedEmojis: PropTypes.arrayOf(PropTypes.string),
intl: PropTypes.object.isRequired,
onPickEmoji: PropTypes.func.isRequired,
onSkinTone: PropTypes.func.isRequired,
skinTone: PropTypes.number.isRequired,
button: PropTypes.node,
};
state = {
active: false,
loading: false,
};
setRef = (c) => {
this.dropdown = c;
}
onShowDropdown = ({ target }) => {
this.setState({ active: true });
if (!EmojiPicker) {
this.setState({ loading: true });
EmojiPickerAsync().then(EmojiMart => {
EmojiPicker = EmojiMart.Picker;
Emoji = EmojiMart.Emoji;
this.setState({ loading: false });
}).catch(() => {
this.setState({ loading: false, active: false });
});
}
const { top } = target.getBoundingClientRect();
this.setState({ placement: top * 2 < innerHeight ? 'bottom' : 'top' });
}
onHideDropdown = () => {
this.setState({ active: false });
}
onToggle = (e) => {
if (!this.state.loading && (!e.key || e.key === 'Enter')) {
if (this.state.active) {
this.onHideDropdown();
} else {
this.onShowDropdown(e);
}
}
}
handleKeyDown = e => {
if (e.key === 'Escape') {
this.onHideDropdown();
}
}
setTargetRef = c => {
this.target = c;
}
findTarget = () => {
return this.target;
}
render () {
const { intl, onPickEmoji, onSkinTone, skinTone, frequentlyUsedEmojis, button } = this.props;
const title = intl.formatMessage(messages.emoji);
const { active, loading, placement } = this.state;
return (
<div className='emoji-picker-dropdown' onKeyDown={this.handleKeyDown}>
<div ref={this.setTargetRef} className='emoji-button' title={title} aria-label={title} aria-expanded={active} role='button' onClick={this.onToggle} onKeyDown={this.onToggle} tabIndex={0}>
{button || <img
className={classNames('emojione', { 'pulse-loading': active && loading })}
alt='🙂'
src={`${assetHost}/emoji/1f602.svg`}
/>}
</div>
<Overlay show={active} placement={placement} target={this.findTarget}>
<EmojiPickerMenu
custom_emojis={this.props.custom_emojis}
loading={loading}
onClose={this.onHideDropdown}
onPick={onPickEmoji}
onSkinTone={onSkinTone}
skinTone={skinTone}
frequentlyUsedEmojis={frequentlyUsedEmojis}
/>
</Overlay>
</div>
);
}
}
|
src/index.js | nnecec/anteact | /* eslint-disable import/default */
import React from 'react';
import {render} from 'react-dom';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router';
import routes from './routes';
import configureStore from './store/configureStore';
require('./favicon.ico'); // Tell webpack to load favicon.ico
import './styles/index.less'; // Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page.
import { syncHistoryWithStore } from 'react-router-redux';
const store = configureStore();
// Create an enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore(browserHistory, store);
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>, document.getElementById('root')
);
|
packages/material-ui-icons/src/AddToPhotos.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9h-4v4h-2v-4H9V9h4V5h2v4h4v2z" /></g>
, 'AddToPhotos');
|
client/scripts/components/user/revise/entity-section/index.js | kuali/research-coi | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import styles from './style';
import classNames from 'classnames';
import React from 'react';
import EntityToReview from '../entity-to-review';
import {BlueButton} from '../../../blue-button';
import {EntityForm} from '../../entities/entity-form';
import {DisclosureStore} from '../../../../stores/disclosure-store';
import {DisclosureActions} from '../../../../actions/disclosure-actions';
import PIReviewActions from '../../../../actions/pi-review-actions';
let nextFakeEntityId = -1;
export default class EntitySection extends React.Component {
constructor() {
super();
const storeState = DisclosureStore.getState();
this.state = {
appState: storeState.applicationState
};
this.onChange = this.onChange.bind(this);
this.submitEntity = this.submitEntity.bind(this);
}
componentDidMount() {
DisclosureStore.listen(this.onChange);
DisclosureActions.setCurrentDisclosureId(this.props.disclosureId);
this.onChange();
}
componentWillUnmount() {
DisclosureStore.unlisten(this.onChange);
}
onChange() {
const storeState = DisclosureStore.getState();
this.setState({
appState: storeState.applicationState
});
}
submitEntity(entity) {
entity.id = nextFakeEntityId--;
PIReviewActions.addEntity(entity);
}
render() {
const {entitiesToReview, className} = this.props;
const entities = entitiesToReview.map((entitytoReview, index) => {
return (
<EntityToReview
key={entitytoReview.id}
entity={entitytoReview}
respondedTo={entitytoReview.respondedTo}
revised={entitytoReview.revised}
className={classNames(
styles.override,
styles.entity,
{[styles.last]: index === entitiesToReview.length - 1}
)}
appState={this.state.appState}
/>
);
});
let entityForm;
if (this.state.appState.newEntityFormStep >= 0) {
entityForm = (
<EntityForm
step={this.state.appState.newEntityFormStep}
entity={this.state.appState.entityInProgress}
editing={true}
appState={this.state.appState}
className={'fill'}
onSubmit={this.submitEntity}
duringRevision={true}
/>
);
}
let addSection;
if (this.state.appState.newEntityFormStep < 0) {
addSection = (
<div className={styles.addSection}>
<BlueButton onClick={DisclosureActions.newEntityInitiated}>
+ Add Another Entity
</BlueButton>
</div>
);
}
return (
<div className={`${styles.container} ${className}`}>
<div className={styles.title}>
FINANCIAL ENTITIES
</div>
<div className={styles.body}>
{entities}
</div>
<div className={'flexbox row'}>
<span style={{minWidth: 45}} />
{entityForm}
<span className={styles.spacer} />
</div>
{addSection}
</div>
);
}
}
EntitySection.propTypes = {
entitiesToReview: React.PropTypes.array.isRequired,
className: React.PropTypes.string,
disclosureId: React.PropTypes.number.isRequired
};
EntitySection.defaultProps = {
className: '',
};
|
actor-apps/app-web/src/app/components/sidebar/RecentSection.react.js | stonegithubs/actor-platform | import _ from 'lodash';
import React from 'react';
import { Styles, RaisedButton } from 'material-ui';
import ActorTheme from 'constants/ActorTheme';
import DialogActionCreators from 'actions/DialogActionCreators';
import DialogStore from 'stores/DialogStore';
import CreateGroupActionCreators from 'actions/CreateGroupActionCreators';
import RecentSectionItem from './RecentSectionItem.react';
import CreateGroupModal from 'components/modals/CreateGroup.react';
import CreateGroupStore from 'stores/CreateGroupStore';
const ThemeManager = new Styles.ThemeManager();
const LoadDialogsScrollBottom = 100;
const getStateFromStore = () => {
return {
isCreateGroupModalOpen: CreateGroupStore.isModalOpen(),
dialogs: DialogStore.getAll()
};
};
class RecentSection extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
this.state = getStateFromStore();
DialogStore.addChangeListener(this.onChange);
DialogStore.addSelectListener(this.onChange);
CreateGroupStore.addChangeListener(this.onChange);
ThemeManager.setTheme(ActorTheme);
}
componentWillUnmount() {
DialogStore.removeChangeListener(this.onChange);
DialogStore.removeSelectListener(this.onChange);
CreateGroupStore.removeChangeListener(this.onChange);
}
onChange = () => {
this.setState(getStateFromStore());
}
openCreateGroup = () => {
CreateGroupActionCreators.openModal();
}
onScroll = event => {
if (event.target.scrollHeight - event.target.scrollTop - event.target.clientHeight <= LoadDialogsScrollBottom) {
DialogActionCreators.onDialogsEnd();
}
}
render() {
let dialogs = _.map(this.state.dialogs, (dialog, index) => {
return (
<RecentSectionItem dialog={dialog} key={index}/>
);
}, this);
let createGroupModal;
if (this.state.isCreateGroupModalOpen) {
createGroupModal = <CreateGroupModal/>;
}
return (
<section className="sidebar__recent">
<ul className="sidebar__list sidebar__list--recent" onScroll={this.onScroll}>
{dialogs}
</ul>
<footer>
<RaisedButton label="Create group" onClick={this.openCreateGroup} style={{width: '100%'}}/>
{createGroupModal}
</footer>
</section>
);
}
}
export default RecentSection;
|
packages/shared/ReactSharedInternals.js | rickbeerendonk/react | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
const ReactSharedInternals =
React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
// Prevent newer renderers from RTE when used with older react package versions.
// Current owner and dispatcher used to share the same ref,
// but PR #14548 split them out to better support the react-debug-tools package.
if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
ReactSharedInternals.ReactCurrentDispatcher = {
current: null,
};
}
if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) {
ReactSharedInternals.ReactCurrentBatchConfig = {
suspense: null,
};
}
export default ReactSharedInternals;
|
demo.js | tweinfeld/backscatter | import _ from 'underscore';
import Backbone from 'backbone';
import Backscatter from './lib/backscatter.js';
import React from 'react';
class MyCustomComponent extends React.Component {
render(){
return <div>{ this.props.title }, { this.props.name }</div>
}
}
// This model is an example of an existing model that's extended to enable backscatter updates (see "createFactory")
let MyExistingModel = Backbone.Model.extend({ defaults: { id: "name", name: "John Doe" } });
let A = new Backscatter.Model({ id: "title", "title": `Howdy` }),
B = new (Backscatter.createFactory(MyExistingModel)),
C = new Backscatter.Model({ "a": A, "b": B }),
D = new Backscatter.Collection([C]);
let renderComponent = function(){
React.render(React.createElement(MyCustomComponent, { title: D.at(0).get('a').get('title'), name: D.at(0).get('b').get('name') }), document.querySelector('body'));
};
// Set backscatter to render your component whenever there are changes to your model
D.backscatterOn(_.debounce(function(...[target, name]){
console.log(`We've got a change on "${target.id}" with event name "${name}"`)
renderComponent();
}));
// Perform a change somewhere in your model, and let backscatter react
setTimeout(function(){
// Let's touch our model somewhere in a deep nested location
A.set({ "title": `Hello` })
}, 1000);
setTimeout(function(){
// Let's touch our model somewhere else in a deep nested location
B.set({ "name": `Mark Smith` })
}, 2000);
renderComponent(); |
guess/app/app.js | ekepes/reactplay | import React from 'react';
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var GuessBox = React.createClass({
getInitialState: function() {
return {
answer: getRandomInt(1, 10),
guess: 0,
message: ""
};
},
handleChange: function(event) {
this.setState({ guess: event.target.value });
},
checkGuess: function() {
if (this.state.guess != 0) {
if (this.state.guess == this.state.answer) {
this.setState({ message: "You guessed it!" });
} else if (this.state.guess < this.state.answer) {
this.setState({ message: "You guessed too low." });
} else if (this.state.guess > this.state.answer) {
this.setState({ message: "You guessed too high." });
} else {
this.setState({ message: "Please enter a guess!" });
}
}
},
render: function() {
return (
<div className="well clearfix">
<h1>Guess My Number!</h1>
<label>Guess (1-10):</label>
<input id="guess-field" type="number" min="1" max="10" onChange={this.handleChange}></input>
<button className="btn btn-default pull-right" onClick={this.checkGuess}>Guess</button>
<div>
<strong>{ this.state.message }</strong>
</div>
</div>
);
}
});
export default GuessBox;
|
demo.js | jrowny/react-absolute-grid | 'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
// import Perf from 'react-addons-perf';
import createAbsoluteGrid from './index.js';
import SampleDisplay from './demo/SampleDisplay.jsx';
import * as data from './demo/sampleData.js';
import * as _ from 'lodash';
demo();
/**
* This demo is meant to show you all of the things that are possible with ReactAbsoluteGrid
* If implemented in a Flux project, the grid would be in a render method with the
* event handlers calling Actions which would update a Store. For the sake of brevity,
* the "store" is implemented locally and the changes re-rendered manually
*
* TODO: implement inside a react component rather than doing this all manually
**/
function demo() {
let sampleItems = data.screens;
let render;
let zoom = 0.7;
//We set a property on each item to let the grid know not to show it
var onFilter = function(event){
var search = new RegExp(event.target.value, 'i');
sampleItems = sampleItems.map(function(item){
const isMatched = !item.name.match(search);
if(!item.filtered || isMatched !== item.filtered) {
return {
...item,
filtered: isMatched
}
}
return item;
});
render();
};
//Change the item's sort order
var onMove = function(source, target){
source = _.find(sampleItems, {key: parseInt(source, 10)});
target = _.find(sampleItems, {key: parseInt(target, 10)});
const targetSort = target.sort;
//CAREFUL, For maximum performance we must maintain the array's order, but change sort
sampleItems = sampleItems.map(function(item){
//Decrement sorts between positions when target is greater
if(item.key === source.key) {
return {
...item,
sort: targetSort
}
} else if(target.sort > source.sort && (item.sort <= target.sort && item.sort > source.sort)){
return {
...item,
sort: item.sort - 1
};
//Increment sorts between positions when source is greater
} else if (item.sort >= target.sort && item.sort < source.sort){
return {
...item,
sort: item.sort + 1
};
}
return item;
});
//Perf.start();
render();
//Perf.stop();
//Perf.printWasted();
};
var onMoveDebounced = _.debounce(onMove, 40);
var unMountTest = function(){
if(ReactDOM.unmountComponentAtNode(document.getElementById('Demo'))){
ReactDOM.render(<button onClick={unMountTest}>Remount</button>, document.getElementById('UnmountButton'));
}else{
render();
ReactDOM.render(<button onClick={unMountTest}>Test Unmount</button>, document.getElementById('UnmountButton'));
}
};
const AbsoluteGrid = createAbsoluteGrid(SampleDisplay);
render = function(){
ReactDOM.render(<AbsoluteGrid items={sampleItems}
onMove={onMoveDebounced}
dragEnabled={true}
zoom={zoom}
responsive={true}
verticalMargin={42}
itemWidth={230}
itemHeight={409}/>, document.getElementById('Demo'));
};
var renderDebounced = _.debounce(render, 150);
//Update the zoom value
var onZoom = function(event){
zoom = parseFloat(event.target.value);
renderDebounced();
};
ReactDOM.render(<input onChange={onZoom} type='range' min='0.3' max='1.5' step='0.1' defaultValue={zoom}/>, document.getElementById('Zoom'));
ReactDOM.render(<input placeholder='Filter eg: calendar' onChange={onFilter} type='text'/>, document.getElementById('Filter'));
ReactDOM.render(<button onClick={unMountTest}>Test Unmount</button>, document.getElementById('UnmountButton'));
render();
}
|
app/components/Seat/ButtonJoinSeat.js | acebusters/ab-web | import React from 'react';
import PropTypes from 'prop-types';
import {
ButtonIcon,
ButtonStyle,
ButtonText,
ButtonWrapper,
SeatWrapper,
} from './styles';
const ButtonJoinSeat = ({ coords, onClickHandler }) => (
<SeatWrapper coords={coords}>
<ButtonWrapper onClick={onClickHandler}>
<ButtonStyle>
<ButtonIcon className="fa fa-plus" aria-hidden="true" />
<ButtonText>Join</ButtonText>
</ButtonStyle>
</ButtonWrapper>
</SeatWrapper>
);
ButtonJoinSeat.propTypes = {
coords: PropTypes.array,
onClickHandler: PropTypes.func,
};
export default ButtonJoinSeat;
|
js/views/login/LogoutView.js | n8e/memoirs | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay';
import { hashHistory } from 'react-router';
import LogoutMutation from '../../mutations/LogoutMutation';
class LogoutView extends Component {
componentDidMount() {
const onSuccess = () => { hashHistory.push('/login'); };
Relay.Store.commitUpdate(new LogoutMutation({
viewer: this.props.viewer,
}), { onSuccess });
}
render() {
return (<noscript />);
}
}
LogoutView.propTypes = {
viewer: PropTypes.shape({
userInfo: PropTypes.shape({
userName: PropTypes.string,
}),
}).isRequired,
};
export default Relay.createContainer(LogoutView, {
fragments: {
viewer: () => Relay.QL`
fragment on User {
${LogoutMutation.getFragment('viewer')}
userInfo {
userName
}
}
`,
},
});
|
definitions/npm/react-redux_v5.x.x/flow_v0.30.x-v0.52.x/test_Provider.js | hansonw/flow-typed | // @flow
import React from 'react'
import { Provider } from 'react-redux'
// $ExpectError
<Provider />; // missing store
|
fields/types/password/PasswordColumn.js | Tangcuyu/keystone | import React from 'react';
import ItemsTableCell from '../../../admin/client/components/ItemsTable/ItemsTableCell';
import ItemsTableValue from '../../../admin/client/components/ItemsTable/ItemsTableValue';
var PasswordColumn = React.createClass({
displayName: 'PasswordColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
return value ? '********' : '';
},
render () {
return (
<ItemsTableCell>
<ItemsTableValue field={this.props.col.type}>
{this.renderValue()}
</ItemsTableValue>
</ItemsTableCell>
);
},
});
module.exports = PasswordColumn;
|
web/app/admin/invites.js | bitemyapp/serials | // @flow
import React from 'react'
import {Link} from 'react-router'
import {invitesAll, invitesAdd, invitesSend, invitesDelete, Invite} from '../model/invite'
import {userApiURL} from '../model/user'
import {reloadHandler} from '../data/load'
import {makeUpdate} from '../data/update'
import {toDateString} from '../helpers'
import {sortBy, reverse} from 'lodash'
import {Routes} from '../router'
// should farm them out to other display components
// should have model functions that do all the lifting
// but it needs to reload too ... hmm ...
type InvitesProps = {
invites: Array<any>
}
export class Invites extends React.Component {
props: InvitesProps;
static load(params) {
return {invites: invitesAll()}
}
addInvites(emails:Array<string>) {
Promise.all(emails.map(e => invitesAdd(e)))
.then(reloadHandler)
}
sendInvite(code:string) {
invitesSend(code)
.then(reloadHandler)
}
deleteInvite(code:string) {
invitesDelete(code)
.then(reloadHandler)
}
render():React.Element {
var invites = sortBy(this.props.invites || [], i => i.created).reverse()
return <div>
<h2>Invites</h2>
<InvitesList invites={invites}
onSend={this.sendInvite.bind(this)}
onDelete={this.deleteInvite.bind(this)}
/>
<BulkInvites onAdd={this.addInvites.bind(this)}/>
</div>
}
}
export class InvitesList extends React.Component {
render():React.Element {
return <table>
<tr>
<th>Email</th>
<th>Code</th>
<th>User</th>
<th></th>
<th>Sent</th>
<th>Created</th>
<th></th>
</tr>
{this.props.invites.map(this.renderRow.bind(this))}
</table>
}
renderRow(invite:Invite):React.Element {
var sent = " "
if (invite.sent) {
sent = toDateString(invite.sent)
}
return <tr>
<td>{invite.email}</td>
<td><Link to={Routes.signup} params={{code: invite.code}}>{invite.code}</Link></td>
<td><UserCell invite={invite} onSend={this.props.onSend}/></td>
<td><InvitesSend invite={invite} onSend={this.props.onSend}/></td>
<td>{sent}</td>
<td>{toDateString(invite.created)}</td>
<td><a onClick={() => this.props.onDelete(invite.code)}>
<span className="fa fa-trash"></span>
</a></td>
</tr>
}
}
class UserCell extends React.Component {
render():React.Element {
var invite = this.props.invite
if (invite.signup) {
return <a href={userApiURL(invite.signup.userId)}>{toDateString(invite.userId)}</a>
}
return <span/>
}
}
export class InvitesSend extends React.Component {
render():React.Element {
var invite = this.props.invite
return <a onClick={this.props.onSend.bind(null, invite.code)}>
<span className="fa fa-paper-plane"></span>
</a>
}
}
export class BulkInvites extends React.Component {
props: {
onAdd:(emails:Array<string>)=>void;
};
constructor(props:any) {
super(props)
this.state = {
text: ""
}
}
onClickAdd() {
var emails = this.state.text.split(/[,\s]+/)
this.props.onAdd(emails)
this.setState({text: ""})
}
render():React.Element {
var update = e => this.setState({text: e.target.value})
return <div>
<div><textarea rows="4" value={this.state.text} onChange={update} placeholder="comma or whitespace separated emails"></textarea></div>
<div><button onClick={this.onClickAdd.bind(this)}>Add Invites</button></div>
</div>
}
}
|
react/features/desktop-picker/components/DesktopPickerPane.js | bgrozev/jitsi-meet | /* @flow */
import { Checkbox } from '@atlaskit/checkbox';
import Spinner from '@atlaskit/spinner';
import React, { Component } from 'react';
import { Platform } from '../../base/react';
import { translate } from '../../base/i18n';
import DesktopSourcePreview from './DesktopSourcePreview';
/**
* The type of the React {@code Component} props of {@link DesktopPickerPane}.
*/
type Props = {
/**
* The handler to be invoked when a DesktopSourcePreview is clicked.
*/
onClick: Function,
/**
* The handler to be invoked when a DesktopSourcePreview is double clicked.
*/
onDoubleClick: Function,
/**
* The handler to be invoked if the users checks the audio screen sharing checkbox.
*/
onShareAudioChecked: Function,
/**
* The id of the DesktopCapturerSource that is currently selected.
*/
selectedSourceId: string,
/**
* An array of DesktopCapturerSources.
*/
sources: Array<Object>,
/**
* The source type of the DesktopCapturerSources to display.
*/
type: string,
/**
* Used to obtain translations.
*/
t: Function
};
/**
* React component for showing a grid of DesktopSourcePreviews.
*
* @extends Component
*/
class DesktopPickerPane extends Component<Props> {
/**
* Initializes a new DesktopPickerPane instance.
*
* @param {Object} props - The read-only properties with which the new
* instance is to be initialized.
*/
constructor(props: Props) {
super(props);
this._onShareAudioCheck = this._onShareAudioCheck.bind(this);
}
_onShareAudioCheck: (Object) => void;
/**
* Function to be called when the Checkbox is used.
*
* @param {boolean} checked - Checkbox status (checked or not).
* @returns {void}
*/
_onShareAudioCheck({ target: { checked } }) {
this.props.onShareAudioChecked(checked);
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const {
onClick,
onDoubleClick,
selectedSourceId,
sources,
type,
t
} = this.props;
const classNames
= `desktop-picker-pane default-scrollbar source-type-${type}`;
const previews
= sources
? sources.map(source => (
<DesktopSourcePreview
key = { source.id }
onClick = { onClick }
onDoubleClick = { onDoubleClick }
selected = { source.id === selectedSourceId }
source = { source }
type = { type } />))
: (
<div className = 'desktop-picker-pane-spinner'>
<Spinner
isCompleting = { false }
size = 'medium' />
</div>
);
let checkBox;
// Only display the share audio checkbox if we're on windows and on
// desktop sharing tab.
// App window and Mac OS screen sharing doesn't work with system audio.
if (type === 'screen' && Platform.OS === 'windows') {
checkBox = (<Checkbox
label = { t('dialog.screenSharingAudio') }
name = 'share-system-audio'
onChange = { this._onShareAudioCheck } />);
}
return (
<div className = { classNames }>
{ previews }
{ checkBox }
</div>
);
}
}
export default translate(DesktopPickerPane);
|
app/static/scripts/layout/footer/main.js | joshleeb/Tobio-PreRelease | import React from 'react';
require('./styles.scss');
export default class Footer extends React.Component {
constructor() {
super();
}
render() {
return (
<footer id="footer">
<div className="content">
<p id="version">Tobio <small>PreRelease 0.2.0</small></p>
</div>
<div className="copyright">
<a href="http://hydrogen252.com" target="_blank">Hydrogen252 Ventures</a><br />
<small>Copyright 2016 <a href="http://joshleeb.com" target="_blank">Josh Leeb-du Toit</a></small>
</div>
</footer>
)
}
}
|
src/DayColumn.js | manishksmd/react-scheduler-smartdata | import PropTypes from 'prop-types';
import React from 'react';
import { findDOMNode } from 'react-dom';
import cn from 'classnames';
import Selection, { getBoundsForNode, isEvent } from './Selection';
import dates from './utils/dates';
import { isSelected } from './utils/selection';
import localizer from './localizer'
import { notify } from './utils/helpers';
import { accessor, elementType, dateFormat } from './utils/propTypes';
import { accessor as get } from './utils/accessors';
import Img from './img/doctor.png';
import getStyledEvents, { positionFromDate, startsBefore } from './utils/dayViewLayout'
import TimeColumn from './TimeColumn'
import AppointmentBox from './AppointmentBox';
function snapToSlot(date, step){
var roundTo = 1000 * 60 * step;
return new Date(Math.floor(date.getTime() / roundTo) * roundTo)
}
function startsAfter(date, max) {
return dates.gt(dates.merge(max, date), max, 'minutes')
}
class DaySlot extends React.Component {
constructor(props) {
super(props);
this.hoverDialogActions = this.hoverDialogActions.bind(this);
}
static propTypes = {
events: PropTypes.array.isRequired,
step: PropTypes.number.isRequired,
min: PropTypes.instanceOf(Date).isRequired,
max: PropTypes.instanceOf(Date).isRequired,
now: PropTypes.instanceOf(Date),
rtl: PropTypes.bool,
titleAccessor: accessor,
// @Appointment field info declaration
patientNameAccessor: accessor,
clinicianImageAccessor: accessor,
clinicianNameAccessor: accessor,
appointmentTypeAccessor: accessor,
appointmentTimeAccessor: accessor,
appointmentAddressAccessor: accessor,
coPayAccessor: accessor,
soapNoteTitleAccessor: accessor,
setProfileTitleAccessor: accessor,
staffsAccessor: accessor,
isRecurrenceAccessor: accessor,
isRecurrenceEditAccessor: accessor,
isEditAccessor: accessor,
isDeleteAccessor: accessor,
isCancelAccessor: accessor,
isUnCancelAccessor: accessor,
isApproveAccessor: accessor,
cancellationReasonAccessor: accessor,
isAppointmentRenderedAccessor: accessor,
isVideoCallAccessor: accessor,
isAppoinmentCancelledAccessor: accessor,
practitionerNameAccessor: accessor,
allDayAccessor: accessor.isRequired,
startAccessor: accessor.isRequired,
endAccessor: accessor.isRequired,
selectRangeFormat: dateFormat,
eventTimeRangeFormat: dateFormat,
culture: PropTypes.string,
selected: PropTypes.object,
selectable: PropTypes.oneOf([true, false, 'ignoreEvents']),
eventOffset: PropTypes.number,
onSelecting: PropTypes.func,
onSelectSlot: PropTypes.func.isRequired,
onSelectEvent: PropTypes.func.isRequired,
className: PropTypes.string,
dragThroughEvents: PropTypes.bool,
eventPropGetter: PropTypes.func,
dayWrapperComponent: elementType,
eventComponent: elementType,
eventWrapperComponent: elementType.isRequired,
resource: PropTypes.string,
};
static defaultProps = { dragThroughEvents: true };
state = { selecting: false };
componentDidMount() {
this.props.selectable
&& this._selectable()
}
componentWillUnmount() {
this._teardownSelectable();
}
componentWillReceiveProps(nextProps) {
if (nextProps.selectable && !this.props.selectable)
this._selectable();
if (!nextProps.selectable && this.props.selectable)
this._teardownSelectable();
}
render() {
const {
min,
max,
step,
now,
selectRangeFormat,
culture,
...props
} = this.props
this._totalMin = dates.diff(min, max, 'minutes')
let { selecting, startSlot, endSlot } = this.state
let style = this._slotStyle(startSlot, endSlot)
let selectDates = {
start: this.state.startDate,
end: this.state.endDate
};
let lastNodeOfWeek = document.getElementsByClassName('rbc-day-slot');
let len = lastNodeOfWeek.length;
// @Week add class to last column - for sat
let lastelement = len < 1 ? '' : lastNodeOfWeek[len-1];
if(lastelement.classList !== undefined) {
lastelement.classList.add('custom-class-sat')
}
// @Week add class to last column - for friday
let secondLastElement = len < 2 ? '' : lastNodeOfWeek[len-2];
if(secondLastElement.classList !== undefined) {
secondLastElement.classList.add('custom-class-sat')
}
return (
<TimeColumn
{...props}
className={cn(
'rbc-day-slot',
dates.isToday(max) && 'rbc-today'
)}
now={now}
min={min}
max={max}
step={step}
>
{this.renderEvents()}
{selecting &&
<div className='rbc-slot-selection' style={style}>
<span>
{ localizer.format(selectDates, selectRangeFormat, culture) }
</span>
</div>
}
</TimeColumn>
);
}
renderEvents = () => {
let {
events
, min
, max
, culture
, eventPropGetter
, selected, eventTimeRangeFormat, eventComponent
, eventWrapperComponent: EventWrapper
, rtl: isRtl
, step
, startAccessor
, endAccessor
, titleAccessor
, isRecurrenceAccessor
, isAppointmentRenderedAccessor
, isVideoCallAccessor
, isAppoinmentCancelledAccessor } = this.props;
let EventComponent = eventComponent
let styledEvents = getStyledEvents({
events, startAccessor, endAccessor, min, totalMin: this._totalMin, step
})
return styledEvents.map(({ event, style }, idx) => {
let start = get(event, startAccessor)
let end = get(event, endAccessor)
let continuesPrior = startsBefore(start, min)
let continuesAfter = startsAfter(end, max)
let title = get(event, titleAccessor)
// @Appointment associate appointment data with the fields
, isRecurrence = get(event, isRecurrenceAccessor)
let isAppointmentRendered = get(event, isAppointmentRenderedAccessor);
let isVideoCall = get(event, isVideoCallAccessor);
let isAppoinmentCancelled = get(event, isAppoinmentCancelledAccessor);
let label = localizer.format({ start, end }, eventTimeRangeFormat, culture)
let _isSelected = isSelected(event, selected)
let viewClass = '';
let getEndHour = end.getHours();
let maxEndHourForHoverup = max.getHours();
if (getEndHour > (maxEndHourForHoverup - 6)) {
viewClass = this.props.view === 'week' ? 'appointment_box dayslot hoverup' : 'appointment_box hoverup';
} else {
viewClass = this.props.view === 'week' ? 'appointment_box dayslot' : 'appointment_box';
}
let dayClass = this.props.view === 'day' ? 'colwrap' : '';
if (eventPropGetter)
var { style: xStyle, className } = eventPropGetter(event, start, end, _isSelected)
let { height, top, width, xOffset } = style
return (
<EventWrapper event={event} key={'evt_' + idx}>
<div
style={{
...xStyle,
top: `${top}%`,
height: `${height}%`,
[isRtl ? 'right' : 'left']: `${Math.max(0, xOffset)}%`,
width: `${width}%`
}}
// title={label + ': ' + title }
//onClick={(e) => this._select(event, e)}
className={cn(`rbc-event ${dayClass}`, className, {
'rbc-selected': _isSelected,
'rbc-event-continues-earlier': continuesPrior,
'rbc-event-continues-later': continuesAfter
})}
>
{/* <div className="rbc-event-label">{label}</div> */}
<div className='rbc-event-label rbc-event-content textoverflow'>
{isRecurrence ? <i className="fa fa-repeat pr5" aria-hidden="true"></i> : ''}
{isAppointmentRendered ? <i className="fa fa-check-circle-o pr5" aria-hidden="true"></i> : ''}
{isVideoCall ? <i className="fa fa-video-camera pr5" aria-hidden="true"></i> : ''}
{isAppoinmentCancelled ? <i className="fa fa-ban pr5" aria-hidden="true"></i> : ''}
{ EventComponent
? <EventComponent event={event} />
: title
} {label}
</div>
<AppointmentBox
{...this.props}
event={event}
popupClassName={viewClass}
hoverDialogActions={this.hoverDialogActions}
/>
</div>
</EventWrapper>
)
})
};
_slotStyle = (startSlot, endSlot) => {
let top = ((startSlot / this._totalMin) * 100);
let bottom = ((endSlot / this._totalMin) * 100);
return {
top: top + '%',
height: bottom - top + '%'
}
};
_selectable = () => {
let node = findDOMNode(this);
let selector = this._selector = new Selection(()=> findDOMNode(this))
let maybeSelect = (box) => {
let onSelecting = this.props.onSelecting
let current = this.state || {};
let state = selectionState(box);
let { startDate: start, endDate: end } = state;
if (onSelecting) {
if (
(dates.eq(current.startDate, start, 'minutes') &&
dates.eq(current.endDate, end, 'minutes')) ||
onSelecting({ start, end }) === false
)
return
}
this.setState(state)
}
let selectionState = ({ y }) => {
let { step, min, max } = this.props;
let { top, bottom } = getBoundsForNode(node)
let mins = this._totalMin;
let range = Math.abs(top - bottom)
let current = (y - top) / range;
current = snapToSlot(minToDate(mins * current, min), step)
if (!this.state.selecting)
this._initialDateSlot = current
let initial = this._initialDateSlot;
if (dates.eq(initial, current, 'minutes'))
current = dates.add(current, step, 'minutes')
let start = dates.max(min, dates.min(initial, current))
let end = dates.min(max, dates.max(initial, current))
return {
selecting: true,
startDate: start,
endDate: end,
startSlot: positionFromDate(start, min, this._totalMin),
endSlot: positionFromDate(end, min, this._totalMin)
}
}
selector.on('selecting', maybeSelect)
selector.on('selectStart', maybeSelect)
selector.on('mousedown', (box) => {
if (this.props.selectable !== 'ignoreEvents') return
return !isEvent(findDOMNode(this), box)
})
selector
.on('click', (box) => {
if (!isEvent(findDOMNode(this), box))
this._selectSlot({ ...selectionState(box), action: 'click' })
this.setState({ selecting: false })
})
selector
.on('select', () => {
if (this.state.selecting) {
this._selectSlot({ ...this.state, action: 'select' })
this.setState({ selecting: false })
}
})
};
_teardownSelectable = () => {
if (!this._selector) return
this._selector.teardown();
this._selector = null;
};
_selectSlot = ({ startDate, endDate, action }) => {
let current = startDate
, slots = [];
while (dates.lte(current, endDate)) {
slots.push(current)
current = dates.add(current, this.props.step, 'minutes')
}
notify(this.props.onSelectSlot, {
slots,
start: startDate,
end: endDate,
resourceId: this.props.resource,
action
})
};
_select = (...args) => {
notify(this.props.onSelectEvent, args)
};
hoverDialogActions(event, e, action) {
e.preventDefault();
event.action = action;
this._select(event, e);
}
}
function minToDate(min, date){
var dt = new Date(date)
, totalMins = dates.diff(dates.startOf(date, 'day'), date, 'minutes');
dt = dates.hours(dt, 0);
dt = dates.minutes(dt, totalMins + min);
dt = dates.seconds(dt, 0)
return dates.milliseconds(dt, 0)
}
export default DaySlot;
|
src/components/StreamItemView/index.js | Reditr-Software/reditr | import React from 'react'
import moment from 'moment'
import { AllHtmlEntities as Entities } from 'html-entities'
import PropTypes from 'prop-types'
import { Link } from 'react-router-dom'
import style from '../../utilities/Style'
import reddit from '../../api/reddit'
import CommentModel from '../../models/CommentModel'
import StreamCommentView from '../StreamCommentView'
import VoteView from '../VoteView'
import { prettyNumber } from '../../utilities/Common'
import MediaParserView from '../MediaParserView'
class StreamItemView extends React.Component {
static contextTypes = {
setViewerState: PropTypes.func,
router: PropTypes.object
}
static propTypes = {
post: PropTypes.object,
inColumn: PropTypes.bool,
onHoverEnter: PropTypes.func,
onHoverLeave: PropTypes.func
}
static defaultProps = {
onHoverEnter() {},
onHoverLeave() {}
}
static style() {
const streamTitle = {
fontWeight: 'normal',
color: '#333',
textDecoration: 'none',
fontSize: '15px'
}
const streamTitleLink = {
...streamTitle,
'&:hover': {
color: 'black',
textDecoration: 'underline'
}
}
return {
streamTitle,
streamTitleLink
}
}
constructor(props) {
super(props)
// get the vote direction
let voteDir = 0
switch (this.props.post.get('likes')) {
case null:
voteDir = 0
break
case true:
voteDir = 1
break
case false:
voteDir = -1
break
}
// set default
this.state = {
topComments: [],
isLoading: true,
showNSFW: false
}
if (this.props.postIds) {
this.props.postIds[this.props.post.get('id')] = this
}
}
componentDidMount() {
this.loadComments()
}
onMouseEnter = e => {
this.props.onHoverEnter(this.props.post, e.currentTarget)
}
onMouseLeave = e => {
this.props.onHoverLeave()
}
loadComments() {
let permalink = this.props.post.get('permalink')
if (permalink) {
// if permalink exists, proceed
reddit.getPostFromPermalink(this.props.post.get('permalink'), null, (err, data) => {
let comments = data.body[1].data.children
let maxComments = Math.min(comments.length, 5)
var first, second
for (var i = 0; i < maxComments; i++) {
var checking = comments[i]
if (checking.data.body == '[removed]') continue
if (!first) {
first = checking
} else if (!second) {
second = checking
} else {
var newFirst = first.data.body.length < second.data.body.length ? first : second
var rejected = newFirst == first ? second : first
first = newFirst
second = rejected.data.body.length < checking.data.body.length ? rejected : checking
}
}
var topComments = []
if (first) topComments.push(first)
if (second) topComments.push(second)
this.setState({
isLoading: false,
topComments: topComments,
comments: comments
})
})
} else {
this.setState({ isLoading: false, topComments: [] })
}
}
enableNSFW() {
this.setState({
showNSFW: true
})
}
didDisappear(post) {
this.setState({ hidden: true, height: post.clientHeight })
}
didAppear() {
this.setState({ hidden: false })
}
openInPostView = () => {
if (this.props.inColumn) {
this.context.router.history.push(this.props.post.get('permalink'))
}
}
renderMedia = () => {
const post = this.props.post
let postMedia = false
if (!this.props.inColumn) {
if (post.get('over_18') && !this.state.showNSFW) {
postMedia = (
<div onClick={this.enableNSFW.bind(this)} className="nsfw-btn">
Show NSFW Content
</div>
)
} else if (this.state.hidden) {
postMedia = false
} else {
postMedia = <MediaParserView onClick={url => this.context.setViewerState(url)} url={post.get('url')} post={post} />
}
}
return postMedia
}
renderTopComments = () => {
const post = this.props.post
const topComments = this.state.topComments
let commentsView = []
// if no comments, say no comments
if (topComments.length == 0) {
commentsView = <span className="no-comments">No comments!</span>
} else {
var commentCount = post.get('num_comments')
topComments.forEach(comment => {
commentCount--
let commentObj = new CommentModel(comment)
commentsView.push(<StreamCommentView key={commentObj.get('id')} comment={commentObj} />)
})
if (this.state.comments.length > 2) {
commentCount = commentCount <= 0 ? '' : prettyNumber(commentCount)
commentsView.push(
<Link key="more" text={Entities.decode(post.get('title'))} to={post.get('permalink')} className="view-more-comments">
<div className="icon">{commentCount} More Comments</div>
</Link>
)
}
}
return commentsView
}
renderDetails = () => {
const post = this.props.post
if (this.props.inColumn) {
const styles = {
container: {
clear: 'both',
fontSize: '12px',
display: 'flex',
justifyContent: 'space-between',
width: '100%',
marginTop: '5px'
}
}
return (
<div style={styles.container} className="mini-details">
<Link to={'/user/' + post.get('author')} className="stream-item-author">
{post.get('author')}
</Link>
<span>
{moment
.unix(post.get('created_utc'))
.fromNow()
.replace(/ ago/, '')
.replace(/ day(s|)/, 'd')
.replace(/ hour(s|)/, 'h')
.replace(/ week(s|)/, 'w')
.replace(/ (minute|min)(s|)/, 'm')
}
</span>
</div>
)
} else {
return (
<div className="mini-details">
<Link to={'/user/' + post.get('author')} className="stream-item-author">
{post.get('author')}
</Link>
<span> posted in </span>
<Link to={'/r/' + post.get('subreddit')} className="stream-item-subreddit">
{'/r/' + post.get('subreddit')}
</Link>
<span> {moment.unix(post.get('created_utc')).fromNow()}</span>
</div>
)
}
}
renderThumbnail = () => {
const post = this.props.post
if (this.props.inColumn && post.get('thumbnail') && post.get('domain').indexOf('self.') === -1) {
const styles = {
thumbnail: {
float: 'left',
width: '50px',
height: '50px',
borderRadius: '4px',
border: '1px solid #fefefe',
backgroundImage: `url(${post.get('thumbnail')})`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: '50% 50%',
marginRight: '5px',
marginBottom: '5px'
}
}
return <div style={styles.thumbnail} />
}
}
renderTitle = () => {
const post = this.props.post
if (this.props.inColumn) {
return <span className={this.props.classes.streamTitle}>{Entities.decode(post.get('title'))}</span>
} else {
return (
<a className={this.props.classes.streamTitleLink} href={post.get('url')} target="_blank">
{Entities.decode(post.get('title'))}
</a>
)
}
}
render() {
const post = this.props.post
// WARN: if it is a comment, ignore for now
if (post.kind == 't1') {
return false
}
let styles = {
container: {
minHeight: this.state.height || 'auto'
},
voteContainer: {
borderLeft: '1px solid #efefef'
}
}
if (this.props.inColumn) {
styles.container = {
...styles.container,
cursor: 'pointer',
margin: 0,
borderRadius: 0,
borderTop: 'none',
borderLeft: 'none',
borderRight: 'none',
borderBottom: '1px solid #efefef',
minHeight: '90px'
}
styles.voteContainer = {
...styles.voteContainer,
width: '50px',
fontSize: '12px'
}
styles.content = {
width: 'calc(100% - 50px)',
boxSizing: 'border-box'
}
}
if (this.state.hidden) {
return (
<div style={styles.container} onClick={this.openInPostView} className="stream-item-view hidden" data-postid={post.get('id')}>
<div className="stream-item-top">
<div style={styles.voteContainer} className="stream-item-sidebar">
<VoteView item={this.props.post} />
</div>
<div className="stream-item-content">
<a href={post.get('url')} target="_blank" className={this.props.classes.streamTitle}>
{Entities.decode(post.get('title'))}
</a>
</div>
</div>
</div>
)
}
return (
<div
style={styles.container}
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}
onClick={this.openInPostView}
className="stream-item-view"
data-postid={post.get('id')}>
<div className="stream-item-top">
<div style={styles.voteContainer} className="stream-item-sidebar">
<VoteView item={this.props.post} />
</div>
<div style={styles.content} className="stream-item-content">
{this.renderThumbnail()}
{this.renderTitle()}
<span className="stream-item-domain">({post.get('domain')})</span>
{this.renderMedia()}
{this.renderDetails()}
</div>
</div>
{this.props.inColumn ? null : (
<div className="stream-item-comments">{this.state.isLoading ? <div className="loading">Loading...</div> : this.renderTopComments()}</div>
)}
</div>
)
}
}
export default style(StreamItemView)
|
vj4/ui/components/scratchpad/ScratchpadRecordsContainer.js | vijos/vj4 | import React from 'react';
import { connect } from 'react-redux';
import Tabs, { TabPane } from 'rc-tabs';
import TabContent from 'rc-tabs/lib/TabContent';
import ScrollableInkTabBar from 'rc-tabs/lib/ScrollableInkTabBar';
import i18n from 'vj/utils/i18n';
import request from 'vj/utils/request';
import Icon from 'vj/components/react/IconComponent';
import Panel from './PanelComponent';
import PanelButton from './PanelButtonComponent';
import ScratchpadRecordsTable from './ScratchpadRecordsTableContainer';
const mapDispatchToProps = dispatch => ({
loadSubmissions() {
dispatch({
type: 'SCRATCHPAD_RECORDS_LOAD_SUBMISSIONS',
payload: request.get(Context.getSubmissionsUrl),
});
},
handleClickClose() {
dispatch({
type: 'SCRATCHPAD_UI_SET_VISIBILITY',
payload: {
uiElement: 'records',
visibility: false,
},
});
},
handleClickRefresh() {
this.loadSubmissions();
},
});
@connect(null, mapDispatchToProps)
export default class ScratchpadRecordsContainer extends React.PureComponent {
componentDidMount() {
this.props.loadSubmissions();
}
render() {
return (
<Panel
title={(
<span>
<Icon name="flag" />
{' '}
{i18n('Records')}
</span>
)}
>
<Tabs
className="scratchpad__panel-tab flex-col flex-fill"
activeKey="all"
animation="slide-horizontal"
renderTabBar={() => (
<ScrollableInkTabBar
extraContent={(
<span>
<PanelButton
data-tooltip={i18n('Refresh Records')}
data-tooltip-pos="top right"
onClick={() => this.props.handleClickRefresh()}
>
{i18n('Refresh')}
</PanelButton>
<PanelButton
onClick={() => this.props.handleClickClose()}
>
<Icon name="close" />
</PanelButton>
</span>
)}
/>
)}
renderTabContent={() => <TabContent />}
>
<TabPane tab={<span>{i18n('All')}</span>} key="all">
<ScratchpadRecordsTable />
</TabPane>
</Tabs>
</Panel>
);
}
}
|
packages/react-jsx-highstock/src/components/Scrollbar/Scrollbar.js | AlexMayants/react-jsx-highcharts | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Hidden from 'react-jsx-highcharts/src/components/Hidden';
import getModifiedProps from 'react-jsx-highcharts/src/utils/getModifiedProps';
class Scrollbar extends Component {
static propTypes = {
update: PropTypes.func, // Provided by ChartProvider
enabled: PropTypes.bool.isRequired
};
static defaultProps = {
enabled: true
};
constructor (props) {
super(props);
this.updateScrollbar = this.updateScrollbar.bind(this);
}
componentDidMount () {
const { children, ...rest } = this.props;
this.updateScrollbar({
...rest
});
}
componentDidUpdate (prevProps) {
const modifiedProps = getModifiedProps(prevProps, this.props);
if (modifiedProps !== false) {
this.updateScrollbar(modifiedProps);
}
}
componentWillUnmount () {
this.updateScrollbar({
enabled: false
});
}
updateScrollbar (config) {
this.props.update({
scrollbar: config
}, true);
}
render () {
const { children } = this.props;
if (!children) return null;
return (
<Hidden>{children}</Hidden>
);
}
}
export default Scrollbar;
|
src/lib/reactors/Legend/PolylineSymbol.js | EsriJapan/photospot-finder | // Copyright (c) 2016 Yusuke Nunokawa (https://ynunokawa.github.io)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// 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 THE
// AUTHORS OR COPYRIGHT HOLDERS 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';
class PolylineSymbol extends React.Component {
constructor (props) {
super(props);
}
render () {
return (
<div className="react-webmap-legend-row">
<div className="react-webmap-legend-cell react-webmap-legend-symbol">
<svg overflow="hidden" width="30" height="30">
<defs></defs>
<path fill="none" fillOpacity="0" stroke={this.props.color} strokeOpacity={this.props.opacity} strokeWidth={this.props.width} strokeLinecap="butt" strokeLinejoin="miter" strokeMiterlimit="4" d="M-15 0L 15 0" strokeDasharray={this.props.dasharray} transform="matrix(1.00000000,0.00000000,0.00000000,1.00000000,15.00000000,15.00000000)"></path>
</svg>
</div>
<div className="react-webmap-legend-cell react-webmap-legend-label">
{this.props.label}
</div>
</div>
);
}
}
PolylineSymbol.propTypes = {
color: React.PropTypes.string,
opacity: React.PropTypes.string,
width: React.PropTypes.string,
dasharray: React.PropTypes.string,
label: React.PropTypes.string
};
PolylineSymbol.displayName = 'PolylineSymbol';
export default PolylineSymbol;
|
js/jqwidgets/jqwidgets-react/react_jqxmaskedinput.js | luissancheza/sice | /*
jQWidgets v5.3.2 (2017-Sep)
Copyright (c) 2011-2017 jQWidgets.
License: http://jqwidgets.com/license/
*/
import React from 'react';
const JQXLite = window.JQXLite;
export const jqx = window.jqx;
export default class JqxMaskedInput extends React.Component {
componentDidMount() {
let options = this.manageAttributes();
this.createComponent(options);
};
manageAttributes() {
let properties = ['disabled','height','mask','promptChar','readOnly','rtl','theme','textAlign','value','width'];
let options = {};
for(let item in this.props) {
if(item === 'settings') {
for(let itemTwo in this.props[item]) {
options[itemTwo] = this.props[item][itemTwo];
}
} else {
if(properties.indexOf(item) !== -1) {
options[item] = this.props[item];
}
}
}
return options;
};
createComponent(options) {
if(!this.style) {
for (let style in this.props.style) {
JQXLite(this.componentSelector).css(style, this.props.style[style]);
}
}
if(this.props.className !== undefined) {
let classes = this.props.className.split(' ');
for (let i = 0; i < classes.length; i++ ) {
JQXLite(this.componentSelector).addClass(classes[i]);
}
}
if(!this.template) {
JQXLite(this.componentSelector).html(this.props.template);
}
JQXLite(this.componentSelector).jqxMaskedInput(options);
};
setOptions(options) {
JQXLite(this.componentSelector).jqxMaskedInput('setOptions', options);
};
getOptions() {
if(arguments.length === 0) {
throw Error('At least one argument expected in getOptions()!');
}
let resultToReturn = {};
for(let i = 0; i < arguments.length; i++) {
resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxMaskedInput(arguments[i]);
}
return resultToReturn;
};
on(name,callbackFn) {
JQXLite(this.componentSelector).on(name,callbackFn);
};
off(name) {
JQXLite(this.componentSelector).off(name);
};
disabled(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxMaskedInput('disabled', arg)
} else {
return JQXLite(this.componentSelector).jqxMaskedInput('disabled');
}
};
height(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxMaskedInput('height', arg)
} else {
return JQXLite(this.componentSelector).jqxMaskedInput('height');
}
};
mask(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxMaskedInput('mask', arg)
} else {
return JQXLite(this.componentSelector).jqxMaskedInput('mask');
}
};
promptChar(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxMaskedInput('promptChar', arg)
} else {
return JQXLite(this.componentSelector).jqxMaskedInput('promptChar');
}
};
readOnly(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxMaskedInput('readOnly', arg)
} else {
return JQXLite(this.componentSelector).jqxMaskedInput('readOnly');
}
};
rtl(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxMaskedInput('rtl', arg)
} else {
return JQXLite(this.componentSelector).jqxMaskedInput('rtl');
}
};
theme(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxMaskedInput('theme', arg)
} else {
return JQXLite(this.componentSelector).jqxMaskedInput('theme');
}
};
textAlign(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxMaskedInput('textAlign', arg)
} else {
return JQXLite(this.componentSelector).jqxMaskedInput('textAlign');
}
};
value(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxMaskedInput('value', arg)
} else {
return JQXLite(this.componentSelector).jqxMaskedInput('value');
}
};
width(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxMaskedInput('width', arg)
} else {
return JQXLite(this.componentSelector).jqxMaskedInput('width');
}
};
clear() {
JQXLite(this.componentSelector).jqxMaskedInput('clear');
};
destroy() {
JQXLite(this.componentSelector).jqxMaskedInput('destroy');
};
focus() {
JQXLite(this.componentSelector).jqxMaskedInput('focus');
};
val(value) {
if (value !== undefined) {
JQXLite(this.componentSelector).jqxMaskedInput('val', value)
} else {
return JQXLite(this.componentSelector).jqxMaskedInput('val');
}
};
render() {
let id = 'jqxMaskedInput' + JQXLite.generateID();
this.componentSelector = '#' + id;
return (
<div id={id}>{this.props.value}{this.props.children}</div>
)
};
};
|
src/app.js | Lorde-Y/happybuild | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import Root from 'container/root';
import './styles/app.less';
import { AppContainer } from 'react-hot-loader';
const render = (Component) => {
ReactDOM.render(
<Provider store={store}>
<Component />
</Provider>,
document.getElementById('app')
);
};
render(Root);
// ReactDOM.render(
// <Canvas />,
// document.getElementById('app')
// );
// Hot Module Replacement API
if (module.hot) {
module.hot.accept('./container/root', () => {
const NewApp = require('./container/root').default;
render(NewApp)
});
}
// import Routes from './Routes.jsx';
// export default function Root(props) {
// return (
// <Provider store={props.store}>
// <Router history={props.history} routes={Routes} />
// </Provider>
// );
// }
// const store = ...
// const history = ...
// const Root = require('./Root.jsx').default;
// const $root = document.getElementById('root');
// ReactDOM.render(
// <AppContainer>
// <Root store={store} history={history} />
// </AppContainer>,
// $root
// );
// if (module.hot) {
// module.hot.accept('./Root.jsx', () => {
// /* [Seems hacky] Running require tiggers hot reload */
// require('./components/Root.jsx').default;
// ReactDOM.render(
// <AppContainer>
// <Root store={store} history={history} />
// </AppContainer>,
// $root
// );
// });
// }
//
//
//
// https://github.com/gaearon/react-hot-boilerplate/pull/61
//
// import { AppContainer } from 'react-hot-loader';
// import { createStore } from 'redux';
// import { Provider } from 'react-redux';
// import App from './app';
// import appReducer from './reducer';
// const store = createStore(appReducer);
// ReactDOM.render(
// <AppContainer>
// <Provider store={store}>
// <App />
// </Provider>
// </AppContainer>,
// rootEl
// );
// if (module.hot) {
// module.hot.accept('./reducer', () => {
// // redux store has a method replaceReducer
// store.replaceReducer(appReducer);
// });
// module.hot.accept('./app', () => {
// ReactDOM.render(
// <AppContainer>
// <Provider store={store}>
// <App />
// </Provider>
// </AppContainer>,
// rootEl
// );
// });
// }
// edit: if you’re using webpack 1, I believe you’ll need to re-require the module. (I’m using webpack2)
// if (module.hot) {
// module.hot.accept('./reducer', () => {
// const nextStore = require('./reducer');
// store.replaceReducer(nextStore);
// });
// } |
app/javascript/flavours/glitch/features/compose/components/oekaki.js | Kirishima21/mastodon | import React from 'react';
import Button from '../../../components/button';
export default class CustomEmojiOekaki extends React.PureComponent {
onClick(e) {
e.preventDefault();
window.open('https://mamemomonga.github.io/mastodon-custom-emoji-oekaki/#kirishima.cloud');
}
render () {
return (
<div className='emoji-oekaki'>
<Button text='☆絵文字でお絵かき☆' onClick={this.onClick} className='custom-emoji-oekaki' />
</div>
);
}
}
|
src/components/tools/ToolDescription.js | mitmedialab/MediaCloud-Web-Tools | import PropTypes from 'prop-types';
import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
const ToolDescription = (props) => {
const { name, description, screenshotUrl, url, className } = props;
const { formatMessage } = props.intl;
return (
<a href={url}>
<div className={`tool-description ${className}`}>
<h2><FormattedMessage {...name} /></h2>
<p><FormattedMessage {...description} /></p>
<img src={screenshotUrl} alt={formatMessage(name)} width="100%" />
</div>
</a>
);
};
ToolDescription.propTypes = {
// from composition chain
intl: PropTypes.object.isRequired,
// from parent
name: PropTypes.object.isRequired, // a msg to intl
description: PropTypes.object.isRequired, // a msg to intl
screenshotUrl: PropTypes.string.isRequired,
className: PropTypes.string.isRequired,
url: PropTypes.string.isRequired,
};
export default injectIntl(ToolDescription);
|
client/scripts/components/user/revise/revise/index.js | kuali/research-coi | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import styles from './style';
import React from 'react';
import {isEmpty} from 'lodash';
import {AppHeader} from '../../../app-header';
import {PIReviewStore} from '../../../../stores/pi-review-store';
import RevisionHeader from '../revision-header';
import QuestionnaireSection from '../questionnaire-section';
import FileSection from '../file-section';
import EntitySection from '../entity-section';
import DeclarationSection from '../declaration-section';
import SidePanel from '../side-panel';
import PIReviewActions from '../../../../actions/pi-review-actions';
import {DisclosureActions} from '../../../../actions/disclosure-actions';
export class Revise extends React.Component {
constructor() {
super();
const storeState = PIReviewStore.getState();
this.state = {
disclosure: storeState.disclosure,
applicationState: storeState.applicationState,
files: storeState.files
};
this.onChange = this.onChange.bind(this);
this.onConfirm = this.onConfirm.bind(this);
}
componentDidMount() {
PIReviewStore.listen(this.onChange);
PIReviewActions.loadDisclosure(this.props.params.id);
DisclosureActions.setCurrentDisclosureId(this.props.params.id);
}
componentWillUnmount() {
PIReviewStore.unlisten(this.onChange);
}
onChange() {
const storeState = PIReviewStore.getState();
this.setState({
disclosure: storeState.disclosure,
applicationState: storeState.applicationState,
files: storeState.files
});
}
onConfirm() {
PIReviewActions.confirm(this.props.params.id);
}
render() {
const {configState} = this.context;
let questionnaireJsx;
let entitiesJsx;
let declarationsJsx;
let submittedDate;
let lastReviewDate;
let disclosureType;
let disclosureFilesJsx;
if (this.state.disclosure) {
lastReviewDate = this.state.disclosure.lastReviewDate;
submittedDate = this.state.disclosure.submittedDate;
disclosureType = this.state.disclosure.typeCd;
const {
questions,
entities,
declarations,
id: disclosureId,
configId
} = this.state.disclosure;
if (!isEmpty(questions)) {
questionnaireJsx = (
<QuestionnaireSection
questions={questions}
/>
);
}
if (!isEmpty(entities)) {
entitiesJsx = (
<EntitySection
entitiesToReview={entities}
disclosureId={parseInt(disclosureId)}
/>
);
}
if (!isEmpty(declarations)) {
declarationsJsx = (
<DeclarationSection
declarationsToReview={declarations}
configId={configId}
necessaryEntities={entities}
/>
);
}
if (this.state.files) {
disclosureFilesJsx = (
<FileSection
files={this.state.files}
disclosureId={disclosureId}
/>
);
}
}
return (
<div className={'flexbox column'} style={{height: '100%'}}>
<AppHeader
className={`${styles.override} ${styles.header}`}
moduleName={'Conflict Of Interest'}
/>
<div
className={
`fill flexbox column ${styles.container} ${this.props.className}`
}
>
<RevisionHeader
disclosureType={disclosureType}
submittedDate={submittedDate}
returnedDate={lastReviewDate}
/>
<div className={'flexbox row fill'}>
<span className={`fill ${styles.disclosure}`}>
{questionnaireJsx}
{entitiesJsx}
{declarationsJsx}
{disclosureFilesJsx}
</span>
<SidePanel
certificationText={configState.config.general.certificationOptions.text}
showingCertification={this.state.applicationState.showingCertification}
submitEnabled={this.state.applicationState.canSubmit}
onConfirm={this.onConfirm}
/>
</div>
</div>
</div>
);
}
}
Revise.contextTypes = {
configState: React.PropTypes.object
};
|
samples/06.recomposing-ui/c.smart-display/src/MicrophoneIcon.js | billba/botchat | import React from 'react';
export default ({ className, size = 22 }) => (
<svg className={(className || '') + ''} height={size} viewBox="0 0 58 58" width={size}>
<path d="M 44 28 C 43.448 28 43 28.447 43 29 L 43 35 C 43 42.72 36.72 49 29 49 C 21.28 49 15 42.72 15 35 L 15 29 C 15 28.447 14.552 28 14 28 C 13.448 28 13 28.447 13 29 L 13 35 C 13 43.485 19.644 50.429 28 50.949 L 28 56 L 23 56 C 22.448 56 22 56.447 22 57 C 22 57.553 22.448 58 23 58 L 35 58 C 35.552 58 36 57.553 36 57 C 36 56.447 35.552 56 35 56 L 30 56 L 30 50.949 C 38.356 50.429 45 43.484 45 35 L 45 29 C 45 28.447 44.552 28 44 28 Z" />
<path d="M 28.97 44.438 L 28.97 44.438 C 23.773 44.438 19.521 40.033 19.521 34.649 L 19.521 11.156 C 19.521 5.772 23.773 1.368 28.97 1.368 L 28.97 1.368 C 34.166 1.368 38.418 5.772 38.418 11.156 L 38.418 34.649 C 38.418 40.033 34.166 44.438 28.97 44.438 Z" />
<path d="M 29 46 C 35.065 46 40 41.065 40 35 L 40 11 C 40 4.935 35.065 0 29 0 C 22.935 0 18 4.935 18 11 L 18 35 C 18 41.065 22.935 46 29 46 Z M 20 11 C 20 6.037 24.038 2 29 2 C 33.962 2 38 6.037 38 11 L 38 35 C 38 39.963 33.962 44 29 44 C 24.038 44 20 39.963 20 35 L 20 11 Z" />
</svg>
);
|
src/components/google_map.js | nfcortega89/airtime | import React, { Component } from 'react';
class GoogleMap extends Component {
componentDidMount() {
// create an embeded google map
// this.refs.map is where map will be rendered to
new google.maps.Map(this.refs.map, {
zoom: 12,
center: {
lat: this.props.lat,
lng: this.props.lon
},
mapTypeId: 'satellite'
})
}
render() {
// this.refs.map
return <div ref="map" />
}
}
export default GoogleMap;
|
source/pages/users/show.js | simonewebdesign/react-router-page-js | import React from 'react';
export default class UserShowPage extends React.Component {
render() {
return <div>Showing user with id: { this.props.params.id }</div>;
}
}
|
client/trello/src/app/routes/login/Login.js | Madmous/Trello-Clone | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { push } from 'react-router-redux';
import { Link } from 'react-router';
import { LoginForm } from './components/index';
import './Login.css';
const propTypes = {
isAuthenticatingSuccessful: PropTypes.bool.isRequired,
isAuthenticated: PropTypes.bool.isRequired,
loginActions: PropTypes.object.isRequired
}
export default class Login extends Component {
componentWillMount() {
const { isAuthenticated, dispatch } = this.props;
if (isAuthenticated) {
dispatch(push('/'));
}
}
componentDidMount () {
document.title = 'Login to Trello Clone';
}
authenticate = (formInput) => {
const { loginActions, location } = this.props;
loginActions.authenticate(formInput, location);
}
render () {
return (
<div className="Login">
<LoginForm onSubmit={ this.authenticate } />
<p>Don't have an account? <Link to={`/signup`}>Create a Trello Clone Account</Link></p>
</div>
);
}
}
Login.propTypes = propTypes; |
example/example.js | AaronCCWong/react-remark | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import ReactRemark from 'react-remark';
class App extends Component {
render () {
const example = [
'# React Remark\n\n ***\n This is a react component that wraps [Remarkable](https://github.com/jonschlinkert/remarkable). ',
'Anything that is possible with Remarkable should be possible with this component.\n\n',
'Even embedding html into markdown works!\n\n Go to google with this link: <a href="https://www.google.com/">Google</a>\n\n',
'Check out the code for this [example](https://github.com/AaronCCWong/react-remark/tree/master/example/example.js).'
].join('');
return (
<div>
<ReactRemark html source={example} />
</div>
);
}
};
ReactDOM.render(<App />, document.getElementById('app'));
|
src/panes/components/GeneralPane.js | trezy/eidetica | // Module imports
import React from 'react'
// Component imports
import KBDContainer from './KBDContainer'
import Pane from './Pane'
import Switch from './Switch'
// Component constants
/* eslint-disable import/no-extraneous-dependencies */
const {
app,
BrowserWindow,
globalShortcut,
} = require('electron').remote
/* eslint-enable */
class GeneralPane extends Pane {
/***************************************************************************\
Private methods
\***************************************************************************/
state = {
altIsPressed: false,
commandIsPressed: false,
controlIsPressed: false,
keyIsPressed: false,
recordedShortcut: [],
recordingShortcut: false,
shiftIsPressed: false,
autoUpdate: this.config.get('autoUpdate'),
deleteAfterUpload: this.config.get('deleteAfterUpload'),
filenameHandling: this.config.get('filenameHandling'),
launchAtLogin: app.getLoginItemSettings().openAtLogin,
shortcut: this.config.get('shortcut'),
}
/***************************************************************************\
Private methods
\***************************************************************************/
_cancelRecording = () => {
this.setState({ recordingShortcut: false })
BrowserWindow.getFocusedWindow().emit('shortcut-reset')
}
_handleKeydown = event => {
const {
recordedShortcut,
recordingShortcut,
} = this.state
if (recordingShortcut) {
const newState = {
recordedShortcut: recordedShortcut.slice(0),
recordingShortcut: true,
}
let addToShortcut
let shouldCancel = false
switch (event.key) {
case '+':
addToShortcut = 'Plus'
newState.keyIsPressed = '+'
newState.recordingShortcut = false
break
case 'Alt':
addToShortcut = 'Alt'
newState.altIsPressed = true
break
case 'Control':
addToShortcut = 'Control'
newState.controlIsPressed = true
break
case 'Escape':
shouldCancel = true
break
case 'Meta':
addToShortcut = 'Super'
newState.commandIsPressed = true
break
case 'Shift':
addToShortcut = 'Shift'
newState.shiftIsPressed = true
break
default:
if (event.code.indexOf('Key') !== -1) {
addToShortcut = event.code.replace('Key', '')
} else {
addToShortcut = event.key
}
newState.keyIsPressed = addToShortcut
newState.recordingShortcut = false
}
if (shouldCancel) {
return this._cancelRecording()
}
if (recordedShortcut.indexOf(addToShortcut) === -1) {
newState.recordedShortcut.push(addToShortcut)
if (!newState.recordingShortcut) {
this._updateShortcut(newState.recordedShortcut.join('+'))
}
this.setState(newState)
}
}
return false
}
_handleKeyup = event => {
const { recordedShortcut } = this.state
if (this.state.recordingShortcut) {
const newState = { recordedShortcut: recordedShortcut.slice(0) }
let removeFromShortcut
switch (event.key) {
case '+':
removeFromShortcut = 'Plus'
newState.keyIsPressed = false
break
case 'Alt':
removeFromShortcut = 'Alt'
newState.altIsPressed = false
break
case 'Control':
removeFromShortcut = 'Control'
newState.controlIsPressed = false
break
case 'Meta':
removeFromShortcut = 'Super'
newState.commandIsPressed = false
break
case 'Shift':
removeFromShortcut = 'Shift'
newState.shiftIsPressed = false
break
default:
removeFromShortcut = this.state.keyIsPressed
newState.keyIsPressed = false
}
newState.recordedShortcut.splice(newState.recordedShortcut.indexOf(removeFromShortcut), 1)
this.setState(newState)
}
}
_startRecording = () => {
globalShortcut.unregister(this.state.shortcut)
this.setState({
altIsPressed: false,
commandIsPressed: false,
controlIsPressed: false,
keyIsPressed: false,
recordedShortcut: [],
recordingShortcut: true,
shiftIsPressed: false,
})
}
_toggleLaunchAtLogin = ({ target: { checked: shouldLaunchAtLogin } }) => {
this.setState({ launchAtLogin: shouldLaunchAtLogin })
app.setLoginItemSettings({ openAtLogin: shouldLaunchAtLogin })
}
_updateShortcut (shortcut) {
this.setState({ shortcut })
this.config.set('shortcut', shortcut)
BrowserWindow.getFocusedWindow().emit('shortcut-updated')
}
/***************************************************************************\
Public methods
\***************************************************************************/
constructor (props) {
super(props)
window.addEventListener('keydown', this._handleKeydown)
window.addEventListener('keyup', this._handleKeyup)
}
render () {
const {
autoUpdate,
launchAtLogin,
recordedShortcut,
recordingShortcut,
shortcut,
} = this.state
const keys = recordingShortcut ? recordedShortcut : shortcut.split('+')
return (
<React.Fragment>
<header>
<h1>General Settings</h1>
</header>
<section className="setting">
<header>Keyboard Shortcut</header>
<div className="control">
<KBDContainer
editable
keys={keys}
onCancel={this._cancelRecording}
onChange={this._startRecording}
recording={recordingShortcut} />
</div>
<div className="body">
<p>This is the description!</p>
</div>
</section>
<section className="setting">
<header>Launch at Login</header>
<div className="control">
<Switch
checked={launchAtLogin}
id="launchAtLogin"
onChange={this._toggleLaunchAtLogin} />
</div>
<div className="body">
<p>This is the description!</p>
</div>
</section>
<section className="setting">
<header>Automatically Check for Updates</header>
<div className="control">
<Switch
checked={autoUpdate}
id="autoUpdate"
onChange={({ target: { checked } }) => this._updateSetting('autoUpdate', checked)} />
</div>
<div className="body">
<p>This is the description!</p>
</div>
</section>
</React.Fragment>
)
}
}
export default GeneralPane
|
src/components/common/svg-icons/maps/directions-boat.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsDirectionsBoat = (props) => (
<SvgIcon {...props}>
<path d="M20 21c-1.39 0-2.78-.47-4-1.32-2.44 1.71-5.56 1.71-8 0C6.78 20.53 5.39 21 4 21H2v2h2c1.38 0 2.74-.35 4-.99 2.52 1.29 5.48 1.29 8 0 1.26.65 2.62.99 4 .99h2v-2h-2zM3.95 19H4c1.6 0 3.02-.88 4-2 .98 1.12 2.4 2 4 2s3.02-.88 4-2c.98 1.12 2.4 2 4 2h.05l1.89-6.68c.08-.26.06-.54-.06-.78s-.34-.42-.6-.5L20 10.62V6c0-1.1-.9-2-2-2h-3V1H9v3H6c-1.1 0-2 .9-2 2v4.62l-1.29.42c-.26.08-.48.26-.6.5s-.15.52-.06.78L3.95 19zM6 6h12v3.97L12 8 6 9.97V6z"/>
</SvgIcon>
);
MapsDirectionsBoat = pure(MapsDirectionsBoat);
MapsDirectionsBoat.displayName = 'MapsDirectionsBoat';
MapsDirectionsBoat.muiName = 'SvgIcon';
export default MapsDirectionsBoat;
|
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/FlowNone.js | mroch/flow | import React from 'react';
class MyComponent extends React.Component {
static defaultProps: DefaultProps = {};
props: Props;
state: State = {};
defaultProps: T;
static props: T;
static state: T;
a: T;
b = 5;
c: T = 5;
method() {}
}
const expression = () =>
class extends React.Component {
static defaultProps: DefaultProps = {};
props: Props;
state: State = {};
defaultProps: T;
static props: T;
static state: T;
a: T;
b = 5;
c: T = 5;
method() {}
}
|
frontend/src/pages/sys-admin/users/user-nav.js | miurahr/seahub | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from '@reach/router';
import { siteRoot, gettext } from '../../../utils/constants';
const propTypes = {
currentItem: PropTypes.string.isRequired
};
class Nav extends React.Component {
constructor(props) {
super(props);
this.navItems = [
{name: 'info', urlPart: '', text: gettext('Info')},
{name: 'owned-repos', urlPart: 'owned-libraries', text: gettext('Owned Libraries')},
{name: 'shared-repos', urlPart: 'shared-libraries', text: gettext('Shared Libraries')},
{name: 'links', urlPart: 'shared-links', text: gettext('Shared Links')},
{name: 'groups', urlPart: 'groups', text: gettext('Groups')}
];
}
render() {
const { currentItem, email, userName } = this.props;
return (
<div>
<div className="cur-view-path">
<h3 className="sf-heading"><Link to={`${siteRoot}sys/users/`}>{gettext('Users')}</Link> / {userName}</h3>
</div>
<ul className="nav border-bottom mx-4">
{this.navItems.map((item, index) => {
return (
<li className="nav-item mr-2" key={index}>
<Link to={`${siteRoot}sys/users/${encodeURIComponent(email)}/${item.urlPart}`} className={`nav-link ${currentItem == item.name ? ' active' : ''}`}>{item.text}</Link>
</li>
);
})}
</ul>
</div>
);
}
}
Nav.propTypes = propTypes;
export default Nav;
|
docs/app/Examples/modules/Popup/Variations/PopupExampleHideOnScroll.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import { Button, Popup } from 'semantic-ui-react'
const PopupExampleHideOnScroll = () => (
<div>
<Popup
trigger={<Button icon>Click me</Button>}
content='Hide the popup on any scroll event'
on='click'
hideOnScroll
/>
<Popup
trigger={<Button icon>Hover me</Button>}
content='Hide the popup on any scroll event'
hideOnScroll
/>
</div>
)
export default PopupExampleHideOnScroll
|
server/sonar-web/src/main/js/apps/overview/meta/MetaOrganizationKey.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 { translate } from '../../../helpers/l10n';
const MetaOrganizationKey = ({ component }) => {
return (
<div className="overview-meta-card">
<h4 className="overview-meta-header">
{translate('organization_key')}
</h4>
<input
className="overview-key"
type="text"
value={component.organization}
readOnly={true}
onClick={e => e.target.select()}
/>
</div>
);
};
export default MetaOrganizationKey;
|
packages/vx-demo/components/tiles/bargroup.js | Flaque/vx | import React from 'react';
import { BarGroup } from '@vx/shape';
import { Group } from '@vx/group';
import { AxisBottom } from '@vx/axis';
import { cityTemperature } from '@vx/mock-data';
import { scaleBand, scaleLinear, scaleOrdinal } from '@vx/scale';
import { timeParse, timeFormat } from 'd3-time-format';
import { extent, max } from 'd3-array';
const data = cityTemperature.slice(0, 8);
const keys = Object.keys(data[0]).filter(d => d !== 'date');
const parseDate = timeParse("%Y%m%d");
const format = timeFormat("%b %d");
const formatDate = (date) => format(parseDate(date));
// accessors
const x0 = d => d.date;
const y = d => d.value;
export default ({
width,
height,
events = false,
margin = {
top: 40
}
}) => {
if (width < 10) return null;
// bounds
const xMax = width;
const yMax = height - margin.top - 100;
// // scales
const x0Scale = scaleBand({
rangeRound: [0, xMax],
domain: data.map(x0),
padding: 0.2,
tickFormat: () => (val) => formatDate(val)
});
const x1Scale = scaleBand({
rangeRound: [0, x0Scale.bandwidth()],
domain: keys,
padding: .1
});
const yScale = scaleLinear({
rangeRound: [yMax, 0],
domain: [0, max(data, (d) => {
return max(keys, (key) => d[key])
})],
});
const zScale = scaleOrdinal({
domain: keys,
range: ['#aeeef8', '#e5fd3d', '#9caff6']
})
return (
<svg width={width} height={height}>
<rect
x={0}
y={0}
width={width}
height={height}
fill={`#612efb`}
rx={14}
/>
<BarGroup
top={margin.top}
data={data}
keys={keys}
height={yMax}
x0={x0}
x0Scale={x0Scale}
x1Scale={x1Scale}
yScale={yScale}
zScale={zScale}
rx={4}
onClick={data => event => {
if (!events) return;
alert(`clicked: ${JSON.stringify(data)}`)
}}
/>
<AxisBottom
scale={x0Scale}
top={yMax + margin.top}
stroke='#e5fd3d'
tickStroke='#e5fd3d'
hideAxisLine
tickLabelComponent={(
<text
fill='#e5fd3d'
fontSize={11}
textAnchor="middle"
/>
)}
/>
</svg>
);
}
|
src/svg-icons/navigation/arrow-upward.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationArrowUpward = (props) => (
<SvgIcon {...props}>
<path d="M4 12l1.41 1.41L11 7.83V20h2V7.83l5.58 5.59L20 12l-8-8-8 8z"/>
</SvgIcon>
);
NavigationArrowUpward = pure(NavigationArrowUpward);
NavigationArrowUpward.displayName = 'NavigationArrowUpward';
NavigationArrowUpward.muiName = 'SvgIcon';
export default NavigationArrowUpward;
|
project-templates/reactfiber/externals/react-fiber/fixtures/dom/src/components/fixtures/input-change-events/RangeKeyboardFixture.js | ItsAsbreuk/itsa-cli | import React from 'react';
import Fixture from '../../Fixture';
class RangeKeyboardFixture extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
keydownCount: 0,
changeCount: 0,
};
}
componentDidMount() {
this.input.addEventListener('keydown', this.handleKeydown, false)
}
componentWillUnmount() {
this.input.removeEventListener('keydown', this.handleKeydown, false)
}
handleChange = () => {
this.setState(({ changeCount }) => {
return {
changeCount: changeCount + 1
}
})
}
handleKeydown = (e) => {
// only interesting in arrow key events
if (![37, 38, 39, 40].includes(e.keyCode))
return;
this.setState(({ keydownCount }) => {
return {
keydownCount: keydownCount + 1
}
})
}
handleReset = () => {
this.setState({
keydownCount: 0,
changeCount: 0,
})
}
render() {
const { keydownCount, changeCount } = this.state;
const color = keydownCount === changeCount ? 'green' : 'red';
return (
<Fixture>
<input
type='range'
ref={r => this.input = r}
onChange={this.handleChange}
/>
{' '}
<p style={{ color }}>
<code>onKeyDown</code>{' calls: '}<strong>{keydownCount}</strong>
{' vs '}
<code>onChange</code>{' calls: '}<strong>{changeCount}</strong>
</p>
<button onClick={this.handleReset}>Reset counts</button>
</Fixture>
)
}
}
export default RangeKeyboardFixture;
|
examples/single-animation.js | ddcat1115/select | /* eslint no-console: 0 */
import React from 'react';
import Select, { Option } from 'rc-select';
import 'rc-select/assets/index.less';
import ReactDOM from 'react-dom';
function onChange(value) {
console.log(`selected ${value}`);
}
const c1 = (
<div>
<div style={{ height: 150 }}/>
<h2>Single Select</h2>
<div style={{ width: 300 }}>
<Select
allowClear
placeholder="placeholder"
defaultValue="lucy"
style={{ width: 500 }}
animation="slide-up"
showSearch={false}
onChange={onChange}
>
<Option value="jack">
<b
style={{
color: 'red',
}}
>
jack
</b>
</Option>
<Option value="lucy">lucy</Option>
<Option value="disabled" disabled>disabled</Option>
<Option value="yiminghe">yiminghe</Option>
</Select>
</div>
</div>
);
ReactDOM.render(c1, document.getElementById('__react-content'));
|
server.js | mtomcal/starship-browser | import express from 'express';
import React from 'react';
import Router from 'react-router';
import ServerBootstrap from './views/ServerBootstrap.jsx';
import Routes from './views/Routes.jsx';
var {
RouteHandler, // <-- not the usual RouteHandler!
run
} = require('react-router-async-props');
let app = express();
function server() {
// LOAD static assets
app.use('/static', express['static'](__dirname + '/static'));
app.all('/*', function(req, res, next) {
run(Routes, req.path, function (Handler, state, asyncProps) {
var entry = React.renderToString(<Handler />);
var html = React.renderToStaticMarkup(<ServerBootstrap asyncProps={asyncProps} bodyHTML={entry} />);
res.send('<!DOCTYPE html>' + html);
});
});
app.listen(3000);
}
module.exports = server;
|
src/entry.js | MatthewKosloski/lugar | import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import createStore from './store';
import AppContainer from './containers/AppContainer';
let store = createStore();
let app = (
<Provider store={store}>
<AppContainer/>
</Provider>
);
render(app, document.getElementById('app')); |
src/components/routes/Resources/Resources.js | sievins/sarahs-footsteps | import React from 'react'
import PropTypes from 'prop-types'
import { join, map } from 'lodash'
import { sliding } from 'utils/lists'
import ResourcePair from './ResourcePair'
Resources.propTypes = {
resources: PropTypes.arrayOf(PropTypes.shape({
logo: PropTypes.string.isRequired,
link: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
})).isRequired,
}
const createKey = resourcePair => join(map(resourcePair, 'link'))
function Resources({ resources }) {
return (
<div>
{
sliding(resources, 2).map(pair => (
<ResourcePair resources={pair} key={createKey(pair)} />
))
}
</div>
)
}
export default Resources
|
src/routes/home_todelete/index.js | jackinf/skynda.me | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 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 fetch from '../../core/fetch';
export default {
path: '/',
async action() {
const resp = await fetch('/graphql', {
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: '{news{title,link,contentSnippet}}',
}),
credentials: 'include',
});
const { data } = await resp.json();
if (!data || !data.news) throw new Error('Failed to load the news feed.');
return {
title: 'React Starter Kit',
component: <Home news={data.news} />,
};
},
};
|
app/shared/resource-type-filter/ResourceTypeFilterContainer.js | fastmonkeys/respa-ui | import includes from 'lodash/includes';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import injectT from '../../i18n/injectT';
import ResourceTypeFilterButton from './ResourceTypeFilterButton';
class ResourceTypeFilterContainer extends Component {
static propTypes = {
selectedResourceTypes: PropTypes.arrayOf(PropTypes.string).isRequired,
onSelectResourceType: PropTypes.func.isRequired,
onUnselectResourceType: PropTypes.func.isRequired,
resourceTypes: PropTypes.arrayOf(PropTypes.string).isRequired,
t: PropTypes.func.isRequired,
};
handleClick = (resourceType) => {
const {
selectedResourceTypes,
onSelectResourceType,
onUnselectResourceType,
} = this.props;
if (includes(selectedResourceTypes, resourceType)) {
onUnselectResourceType(resourceType);
} else {
onSelectResourceType(resourceType);
}
}
render() {
const { t, selectedResourceTypes, resourceTypes } = this.props;
return (
<div className="resource-type-filter-container">
<h6>{t('ResourceTypeFilter.title')}</h6>
{ resourceTypes.map(resourceType => (
<ResourceTypeFilterButton
active={includes(selectedResourceTypes, resourceType)}
key={`resource-type-${resourceType}`}
onClick={this.handleClick}
resourceType={resourceType}
/>
))}
</div>
);
}
}
ResourceTypeFilterContainer = injectT(ResourceTypeFilterContainer); // eslint-disable-line
export default ResourceTypeFilterContainer;
|
src/index.js | henyouqian/sale | import React from 'react';
import { render } from 'react-dom';
import { App } from './App';
render(<App />, document.getElementById('root'));
|
src/index.js | vladlen-g/ride-with-me | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route, browserHistory, Redirect } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import configure from './store';
import App from './views/App/App.jsx';
import Home from './views/Home/Home.jsx';
import About from './views/About/About.jsx';
const store = configure();
const history = syncHistoryWithStore(browserHistory, store);
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route component={App} path="/">
<Route component={Home} path="home"/>
<Route component={About} path="about" />
</Route>
</Router>
</Provider>,
document.getElementById('root')
);
|
src/components/Blog/Blog.react.js | uday96/chat.susi.ai | import './Blog.css';
import 'font-awesome/css/font-awesome.min.css';
import PropTypes from 'prop-types';
import htmlToText from 'html-to-text';
import $ from 'jquery';
import { Card, CardMedia, CardTitle, CardText, CardActions } from 'material-ui/Card';
import susi from '../../images/susi-logo.svg';
import dateFormat from 'dateformat';
import StaticAppBar from '../StaticAppBar/StaticAppBar.react';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import Next from 'material-ui/svg-icons/hardware/keyboard-arrow-right';
import Previous from 'material-ui/svg-icons/hardware/keyboard-arrow-left';
import React, { Component } from 'react';
import renderHTML from 'react-render-html';
import Loading from 'react-loading-animation';
import Footer from '../Footer/Footer.react';
import {
ShareButtons,
generateShareIcon
} from 'react-share';
function arrDiff(a1, a2) {
var a = [], diff = [];
for (var f = 0; f < a1.length; f++) {
a[a1[f]] = true;
}
for (var z = 0; z < a2.length; z++) {
if (a[a2[z]]) {
delete a[a2[z]];
} else {
a[a2[z]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
};
class Blog extends Component {
constructor(props) {
super(props);
this.state = {
posts: [],
postRendered: false,
startPage: 0,
nextDisplay: 'visible',
prevDisplay: 'hidden',
}
}
componentDidMount() {
// Adding title tag to page
document.title = 'Blog Posts about Open Source Artificial Intelligence for Personal Assistants, Robots, Help Desks and Chatbots - SUSI.AI';
// Scrolling to top of page when component loads
$('html, body').animate({ scrollTop: 0 }, 'fast');
// Ajax call to convert the RSS feed to JSON format
$.ajax({
url: 'https://api.rss2json.com/v1/api.json',
method: 'GET',
dataType: 'json',
data: {
'rss_url': 'http://blog.fossasia.org/tag/susi-ai/feed/',
'api_key': 'qsmzjtyycc49whsfvf5ikzottxrbditq3burojhd', // put your api key here
'count': 50
}
}).done(function (response) {
if (response.status !== 'ok') { throw response.message; }
this.setState({ posts: response.items, postRendered: true });
}.bind(this));
}
scrollStep() {
if (window.pageYOffset === 0) {
clearInterval(this.state.intervalId);
}
window.scroll(0, window.pageYOffset - 1000);
}
// Function to scroll to top of page
scrollToTop() {
let intervalId = setInterval(this.scrollStep.bind(this), 16.66);
this.setState({ intervalId: intervalId });
}
// Function to navigate to previous page
previousPage = () => {
let current = this.state.startPage;
if (current - 10 === 0) {
this.setState({ startPage: current - 10, prevDisplay: 'hidden', nextDisplay: 'visible' })
}
else {
this.setState({ startPage: current - 10, prevDisplay: 'visible', nextDisplay: 'visible' })
}
this.scrollToTop();
}
// Function to navigate to next page
nextPage = () => {
let current = this.state.startPage;
let size = this.state.posts.length;
console.log(size)
if (current + 10 === size - 10) {
this.setState({ startPage: current + 10, nextDisplay: 'hidden', prevDisplay: 'visible' })
}
else {
this.setState({ startPage: current + 10, prevDisplay: 'visible', nextDisplay: 'visible' })
}
this.scrollToTop();
}
render() {
const {
FacebookShareButton,
TwitterShareButton,
} = ShareButtons;
const FacebookIcon = generateShareIcon('facebook');
const TwitterIcon = generateShareIcon('twitter');
const nextStyle = {
visibility: this.state.nextDisplay,
marginLeft: '10px'
}
const prevStyle = {
visibility: this.state.prevDisplay
}
const loadingStyle = {
marginTop: '20px',
position: 'relative',
}
const allCategories = ['FOSSASIA', 'GSoC', 'SUSI.AI',
'Tutorial', 'Android', 'API', 'App generator', 'CodeHeat', 'Community', 'Event',
'Event Management', 'loklak', 'Meilix', 'Open Event', 'Phimpme', 'Pocket Science Lab', 'yaydoc'];
return (
<div>
<StaticAppBar {...this.props}
location={this.props.location} />
<div className='head_section'>
<div className='container'>
<div className="heading">
<h1>Blog</h1>
<p>Latest Blog Posts on SUSI.AI</p>
</div>
</div>
</div>
<Loading
style={loadingStyle}
isLoading={!this.state.postRendered} />
{!this.state.postRendered &&
(<div><center>Fetching Blogs..</center></div>)}
{this.state.postRendered && (<div>
<div style={{ width: '100%' }}>
{
this.state.posts
.slice(this.state.startPage, this.state.startPage + 10)
.map((posts, i) => {
let description = htmlToText.fromString(posts.description).split('…');
let content = posts.content;
let category = [];
posts.categories.forEach((cat) => {
let k = 0;
for (k = 0; k < allCategories.length; k++) {
if (cat === allCategories[k]) {
category.push(cat);
}
}
});
var tags = arrDiff(category, posts.categories)
let fCategory = category.map((cat) =>
<span key={cat} ><a className="tagname" href={'http://blog.fossasia.org/category/' + cat.replace(/\s+/g, '-').toLowerCase()}
rel="noopener noreferrer">{cat}</a></span>
);
let ftags = tags.map((tag) =>
<span key={tag} ><a className="tagname" href={'http://blog.fossasia.org/tag/' + tag.replace(/\s+/g, '-').toLowerCase()}
rel="noopener noreferrer">{tag}</a></span>
);
let htmlContent = content.replace(/<img.*?>/, '');
htmlContent = renderHTML(htmlContent);
let image = susi
let regExp = /\[(.*?)\]/;
let imageUrl = regExp.exec(description[0]);
if (imageUrl) {
image = imageUrl[1]
}
let date = posts.pubDate.split(' ');
let d = new Date(date[0]);
return (
<div key={i} className="section_blog">
<Card style={{ width: '100%', padding: '0' }}>
<CardMedia
overlay={
<CardTitle
className="noUnderline"
subtitle={renderHTML('<a href="' + posts.link + '" >Published on ' + dateFormat(d, 'dddd, mmmm dS, yyyy') + '</a>')} />
}>
<img className="featured_image"
src={image}
alt={posts.title}
/>
</CardMedia>
<CardTitle className="noUnderline" title={posts.title} subtitle={renderHTML('by <a href="http://blog.fossasia.org/author/' + posts.author + '" >' + posts.author + '</a>')} />
<CardText style={{ fontSize: '16px' }}> {htmlContent}
</CardText>
<div className="social-btns">
<TwitterShareButton
url={posts.guid}
title={posts.title}
via='asksusi'
hashtags={posts.categories.slice(0, 4)} >
<TwitterIcon
size={32}
round={true} />
</TwitterShareButton>
<FacebookShareButton url={posts.link}>
<FacebookIcon size={32} round={true} />
</FacebookShareButton>
</div>
<CardActions className="cardActions">
<span className="calendarContainer">
<i className="fa fa-calendar tagIcon"></i>
{renderHTML('<a href="' + posts.link + '">' + dateFormat(d, 'mmmm dd, yyyy') + '</a>')}
</span>
<span className="authorsContainer">
<i className="fa fa-user tagIcon"></i>
<a
rel="noopener noreferrer"
href={'http://blog.fossasia.org/author/' + posts.author}
>
{posts.author}
</a></span>
<span className='categoryContainer'>
<i className="fa fa-folder-open-o tagIcon"></i>
{fCategory}
</span>
<span className='tagsContainer'>
<i className="fa fa-tags tagIcon"></i>
{ftags}
</span>
</CardActions>
</Card>
</div>
)
})
}
</div>
<div className="blog_navigation">
<FloatingActionButton
style={prevStyle}
backgroundColor={'#4285f4'}
onTouchTap={this.previousPage}>
<Previous />
</FloatingActionButton>
<FloatingActionButton
style={nextStyle}
backgroundColor={'#4285f4'}
onTouchTap={this.nextPage}>
<Next />
</FloatingActionButton>
</div>
<div className="post_bottom"></div>
<Footer />
</div>)}
</div>
);
}
}
Blog.propTypes = {
history: PropTypes.object,
location: PropTypes.object
}
export default Blog;
|
app/views/Setup/Setup.js | lishengzxc/random | import styles from './Setup.scss';
import React from 'react';
import MessageBox from '../../views/MessageBox/MessageBox';
import clearTeamActionCreators from '../../actions/clearTeam-action-creators';
var Setup = React.createClass({
clear: function () {
MessageBox.open('确认要清空所有数据吗ಥ_ಥ', function () {
clearTeamActionCreators.emitClearTeam();
window.location.href = '#/';
});
},
render: function () {
return (
<div className="in">
<button className={styles.button} onClick={this.clear}>清除数据</button>
</div>
)
}
});
export default Setup; |
actor-apps/app-web/src/app/components/ToolbarSection.react.js | vanloswang/actor-platform | import React from 'react';
import ReactMixin from 'react-mixin';
import { IntlMixin } from 'react-intl';
import classnames from 'classnames';
import ActivityActionCreators from 'actions/ActivityActionCreators';
import DialogStore from 'stores/DialogStore';
import ActivityStore from 'stores/ActivityStore';
//import AvatarItem from 'components/common/AvatarItem.react';
const getStateFromStores = () => {
return {
dialogInfo: DialogStore.getSelectedDialogInfo(),
isActivityOpen: ActivityStore.isOpen()
};
};
@ReactMixin.decorate(IntlMixin)
class ToolbarSection extends React.Component {
state = {
dialogInfo: null,
isActivityOpen: false
};
constructor(props) {
super(props);
DialogStore.addSelectedChangeListener(this.onChange);
ActivityStore.addChangeListener(this.onChange);
}
componentWillUnmount() {
DialogStore.removeSelectedChangeListener(this.onChange);
ActivityStore.removeChangeListener(this.onChange);
}
onClick = () => {
if (!this.state.isActivityOpen) {
ActivityActionCreators.show();
} else {
ActivityActionCreators.hide();
}
};
onChange = () => {
this.setState(getStateFromStores());
};
render() {
const info = this.state.dialogInfo;
const isActivityOpen = this.state.isActivityOpen;
let infoButtonClassName = classnames('button button--icon', {
'button--active': isActivityOpen
});
if (info != null) {
return (
<header className="toolbar row">
<div className="toolbar__peer col-xs">
<span className="toolbar__peer__title">{info.name}</span>
<span className="toolbar__peer__presence">{info.presence}</span>
</div>
<div className="toolbar__controls">
<div className="toolbar__controls__search pull-left hide">
<i className="material-icons">search</i>
<input className="input input--search" placeholder={this.getIntlMessage('search')} type="search"/>
</div>
<div className="toolbar__controls__buttons pull-right">
<button className={infoButtonClassName} onClick={this.onClick}>
<i className="material-icons">info</i>
</button>
<button className="button button--icon hide">
<i className="material-icons">more_vert</i>
</button>
</div>
</div>
</header>
);
} else {
return (
<header className="toolbar"/>
);
}
}
}
export default ToolbarSection;
|
examples/create-react-app-example/src/index.js | gvmani/socket.io | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
|
app/modules/header/index.js | donofkarma/react-starter | import React from 'react';
import Navigation from 'modules/navigation';
import { SiteHeader } from './style';
class Header extends React.Component {
render() {
return (
<SiteHeader className={this.props.className}>
<h1>React Starter</h1>
<Navigation />
</SiteHeader>
);
}
}
export default Header;
|
src/components/Topbar.js | shockry/editest | import React, { Component } from 'react';
import '../css/Topbar.css';
import UploadButton from './UploadButton';
import DownloadButton from './DownloadButton';
import MainNavbar from './MainNavbar';
class Topbar extends Component {
constructor(props) {
super(props);
this.setOriginalImage = this.setOriginalImage.bind(this);
this.state = {
originalImage: null
};
}
render() {
return (
<div className="topbar">
<UploadButton canvas={this.props.canvas} imgElement={this.props.imgElement} setOriginalImage={this.setOriginalImage}/>
<DownloadButton canvas={this.props.canvas}/>
<MainNavbar canvas={this.props.canvas} originalImage={this.state.originalImage}/>
</div>
);
}
setOriginalImage(img) {
this.setState({originalImage: img});
}
}
export default Topbar;
|
_deprecated/src/components/App.js | paigekehoe/paigekehoe.github.io | import React from 'react';
import Interactive from 'react-interactive';
import { Switch, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
import PageNotFound from './PageNotFound';
import Breadcrumbs from './Breadcrumbs';
import Header from './Header';
import s from '../styles/app.style';
export default function App() {
return (
<div style={s.root}>
<Header />
<h1 style={s.title}>Paige Kehoe</h1>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route component={PageNotFound} />
</Switch>
</div>
);
}
|
client/components/dashboard/ReplyModal.js | creativcoder/rio | import { Modal, Button, Popover, OverlayTrigger, Tooltip } from 'react-bootstrap';
import React from 'react';
import Tweetbox from './Tweetbox';
class ReplyModal extends React.Component {
constructor(props) {
super(props);
this.state = { showModal : false };
this.open = this.open.bind(this);
this.close = this.close.bind(this);
}
open() {
this.setState({ showModal: true });
}
close() {
this.setState({ showModal: false });
}
render() {
return (
<div>
<i onClick={this.open} className="fa fa-reply" aria-hidden="true"></i>
<Modal show={this.state.showModal} onHide={this.close}>
<Modal.Header closeButton>
<Modal.Title>Reply to @{this.props.entities.alias}!</Modal.Title>
</Modal.Header>
<Modal.Body>
<div>
<Tweetbox entities={this.props.entities}/>
</div>
</Modal.Body>
</Modal>
</div>
);
}
}
export default ReplyModal;
|
app/components/Badge.js | Nakan4u/pokemons-finder | import React, { Component } from 'react';
export default class Badge extends Component {
makeBackground (type) {
var obj = {};
switch (type) {
case 'normal':
obj.backgroundColor = 'aliceblue';
break;
case 'fighting':
obj.backgroundColor = 'bisque';
break;
case 'flying':
obj.backgroundColor = 'brown';
break;
case 'poison':
obj.backgroundColor = 'chartreuse';
break;
case 'ground':
obj.backgroundColor = 'darkgoldenrod';
break;
case 'rock':
obj.backgroundColor = 'darkgrey';
break;
case 'bug':
obj.backgroundColor = 'darkmagenta';
break;
case 'ghost':
obj.backgroundColor = 'darkseagreen';
break;
case 'steel':
obj.backgroundColor = 'dimgray';
break;
case 'fire':
obj.backgroundColor = 'gold';
break;
case 'water':
obj.backgroundColor = 'deepskyblue';
break;
case 'grass':
obj.backgroundColor = 'forestgreen';
break;
case 'electric':
obj.backgroundColor = 'khaki';
break;
case 'psychic':
obj.backgroundColor = 'lavender';
break;
case 'ice':
obj.backgroundColor = 'lightblue';
break;
case 'dragon':
obj.backgroundColor = 'lightgreen';
break;
case 'dark':
obj.backgroundColor = 'indigo';
break;
case 'fairy':
obj.backgroundColor = 'lightpink';
break;
case 'unknown':
obj.backgroundColor = 'silver';
break;
case 'shadow':
obj.backgroundColor = 'black';
break;
default:
obj.backgroundColor = 'grey';
}
return obj;
}
}
Badge.propTypes = {
pokemon: React.PropTypes.object.isRequired,
getPokemonsListByTypeHandler: React.PropTypes.func.isRequired
};
|
src/interface/home/Page.js | fyruna/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Trans } from '@lingui/macro';
import { Link, Route, Switch } from 'react-router-dom';
import lazyLoadComponent from 'common/lazyLoadComponent';
import retryingPromise from 'common/retryingPromise';
import NewsIcon from 'interface/icons/Megaphone';
import PremiumIcon from 'interface/icons/Premium';
import { ReactComponent as Logo } from 'interface/images/logo.svg';
import FingerprintFilledIcon from 'interface/icons/FingerprintFilled';
import HelpWantedIcon from 'interface/icons/Information';
import GitHubIcon from 'interface/icons/GitHubMarkLarge';
import DiscordIcon from 'interface/icons/DiscordTiny';
import { hasPremium } from 'interface/selectors/user';
import ErrorBoundary from 'interface/common/ErrorBoundary';
import Ad from 'interface/common/Ad';
import './Home.scss';
import ReportSelectionHeader from './ReportSelectionHeader';
import NotFound from './NotFound';
const News = lazyLoadComponent(() => retryingPromise(() => import(/* webpackChunkName: 'News' */ 'interface/news').then(exports => exports.default)));
const NewsPage = lazyLoadComponent(() => retryingPromise(() => import(/* webpackChunkName: 'News' */ 'interface/news/Page').then(exports => exports.default)));
const SpecListing = lazyLoadComponent(() => retryingPromise(() => import(/* webpackChunkName: 'SpecListing' */ 'interface/SpecListing').then(exports => exports.default)));
const Premium = lazyLoadComponent(() => retryingPromise(() => import(/* webpackChunkName: 'Premium' */ 'interface/premium/Page').then(exports => exports.default)));
const About = lazyLoadComponent(() => retryingPromise(() => import(/* webpackChunkName: 'About' */ 'interface/about').then(exports => exports.default)));
const HelpWanted = lazyLoadComponent(() => retryingPromise(() => import(/* webpackChunkName: 'HelpWanted' */ 'interface/helpwanted').then(exports => exports.default)));
const ContributorPage = lazyLoadComponent(() => retryingPromise(() => import(/* webpackChunkName: 'ContributorPage' */ 'interface/contributor/Page').then(exports => exports.default)));
class Home extends React.PureComponent {
static propTypes = {
location: PropTypes.shape({
pathname: PropTypes.string.isRequired,
}).isRequired,
premium: PropTypes.bool,
};
static defaultProps = {
premium: false,
};
get pages() {
return [
{
icon: NewsIcon,
name: <Trans>News</Trans>,
url: 'news',
},
{
icon: FingerprintFilledIcon,
name: <Trans>Specs</Trans>,
url: 'specs',
},
{
icon: Logo,
name: <Trans>About</Trans>,
url: 'about',
},
{
icon: PremiumIcon,
name: <Trans>Premium</Trans>,
url: 'premium',
},
{
icon: HelpWantedIcon,
name: <Trans>Help wanted</Trans>,
url: 'help-wanted',
},
{
icon: GitHubIcon,
name: <Trans>Source code</Trans>,
url: 'https://github.com/WoWAnalyzer/WoWAnalyzer',
},
{
icon: DiscordIcon,
name: <Trans>Discord</Trans>,
url: 'https://wowanalyzer.com/discord',
},
];
}
render() {
const { location, premium } = this.props;
const url = location.pathname === '/' ? 'news' : location.pathname.replace(/^\/|\/$/g, '');
return (
<div className="home-page">
<ReportSelectionHeader />
<main className="container">
{premium === false && (
<div style={{ marginTop: 40 }}>
<Ad />
</div>
)}
<nav>
<ul>
{this.pages.map(page => {
const Icon = page.icon;
const isRelativeLink = !page.url.includes('://');
const content = (
<>
<Icon className="icon" />
{page.name}
</>
);
return (
<li key={page.url} className={page.url === url ? 'active' : undefined}>
{isRelativeLink ? (
<Link to={`/${page.url}`}>{content}</Link>
) : (
<a href={page.url}>{content}</a>
)}
</li>
);
})}
</ul>
</nav>
<ErrorBoundary>
<Switch>
<Route
path="/"
exact
component={News}
/>
<Route
path="/news"
component={News}
/>
<Route
path="/news/:articleId"
render={({ match }) => (
<NewsPage
articleId={decodeURI(match.params.articleId.replace(/\+/g, ' '))}
/>
)}
/>
<Route
path="/specs"
component={SpecListing}
/>
<Route
path="/premium"
component={Premium}
/>
<Route
path="/about"
component={About}
/>
<Route
path="/help-wanted"
component={HelpWanted}
/>
<Route
path="/contributor/:id"
render={({ match }) => (
<ContributorPage
contributorId={decodeURI(match.params.id.replace(/\+/g, ' '))}
/>
)}
/>
<Route component={NotFound} />
</Switch>
</ErrorBoundary>
{premium === false && (
<div style={{ marginTop: 40 }}>
<Ad />
</div>
)}
</main>
</div>
);
}
}
const mapStateToProps = state => ({
premium: hasPremium(state),
});
export default connect(
mapStateToProps
)(Home);
|
app/components/Inputs/TextInput/TextInput.js | hbibkrim/neon-wallet | // @flow
import React from 'react'
import classNames from 'classnames'
import { omit } from 'lodash-es'
import ErrorIcon from '../../../assets/icons/errorRed.svg'
import styles from './TextInput.scss'
type Props = {
className?: string,
type: string,
textInputClassName?: string,
activeStyles?: string,
placeholder: string,
error?: string,
id: string,
renderBefore?: Function,
renderAfter?: Function,
onFocus?: Function,
onBlur?: Function,
label: string,
shouldRenderErrorIcon?: boolean,
}
type State = {
active: boolean,
}
export default class TextInput extends React.Component<Props, State> {
static defaultProps = {
type: 'text',
shouldRenderErrorIcon: true,
}
state = {
active: false,
}
render() {
const passDownProps = omit(
this.props,
'className',
'textInputClassName',
'activeStyles',
'renderBefore',
'renderAfter',
'shouldRenderErrorIcon',
)
const { error, label, textInputClassName, activeStyles } = this.props
const className = classNames(styles.textInput, this.props.className, {
[activeStyles || styles.active]: this.state.active,
[styles.error]: !!error,
})
return (
<div className={styles.textInputContainer}>
{label && <label className={styles.label}> {label} </label>}
<div className={className}>
{this.renderBefore()}
<input
{...passDownProps}
className={classNames(styles.input, textInputClassName)}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
/>
{error &&
this.props.shouldRenderErrorIcon && (
<ErrorIcon className={styles.errorIcon} />
)}
{error && <div className={styles.errorMessage}>{error}</div>}
{this.renderAfter()}
</div>
</div>
)
}
renderBefore = () => {
if (!this.props.renderBefore) {
return null
}
return (
<div className={styles.beforeInput}>
{this.props.renderBefore({ active: this.state.active })}
</div>
)
}
renderAfter = () => {
if (!this.props.renderAfter) {
return null
}
return (
<div className={styles.afterInput}>
{this.props.renderAfter({ active: this.state.active })}
</div>
)
}
handleFocus = (event: Object, ...args: Array<any>) => {
this.setState({ active: true })
event.persist()
return this.props.onFocus && this.props.onFocus(event, ...args)
}
handleBlur = (event: Object, ...args: Array<any>) => {
this.setState({ active: false })
event.persist()
return this.props.onBlur && this.props.onBlur(event, ...args)
}
}
|
src/components/topic/snapshots/foci/builder/FocusBuilderWizard.js | mitmedialab/MediaCloud-Web-Tools | import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import Stepper from '@material-ui/core/Stepper';
import Step from '@material-ui/core/Step';
import StepLabel from '@material-ui/core/StepLabel';
import { FormattedMessage, injectIntl } from 'react-intl';
import BackLinkingControlBar from '../../../BackLinkingControlBar';
import FocusForm1TechniqueContainer from './FocusForm1TechniqueContainer';
import FocusForm2ConfigureContainer from './FocusForm2ConfigureContainer';
import FocusForm3DescribeContainer from './FocusForm3DescribeContainer';
import FocusForm4ConfirmContainer from './FocusForm4ConfirmContainer';
import { goToCreateFocusStep } from '../../../../../actions/topicActions';
const localMessages = {
backToFociManager: { id: 'backToFociManager', defaultMessage: 'back to Subtopic Builder' },
step0Name: { id: 'focus.create.step0Name', defaultMessage: 'Pick a Technique' },
step1Name: { id: 'focus.create.step1Name', defaultMessage: 'Configure' },
step2Name: { id: 'focus.create.step2Name', defaultMessage: 'Describe' },
step3Name: { id: 'focus.create.step3Name', defaultMessage: 'Confirm' },
};
class FocusBuilderWizard extends React.Component {
UNSAFE_componentWillMount = () => {
const { startStep, goToStep } = this.props;
goToStep(startStep || 0);
}
shouldComponentUpdate = (nextProps) => {
const { currentStep } = this.props;
return currentStep !== nextProps.currentStep;
}
componentWillUnmount = () => {
const { handleUnmount } = this.props;
handleUnmount();
}
render() {
const { topicId, currentStep, location, initialValues, onDone } = this.props;
const steps = [
FocusForm1TechniqueContainer,
FocusForm2ConfigureContainer,
FocusForm3DescribeContainer,
FocusForm4ConfirmContainer,
];
const CurrentStepComponent = steps[currentStep];
return (
<div className="focus-builder-wizard">
<BackLinkingControlBar message={localMessages.backToFociManager} linkTo={`/topics/${topicId}/snapshot/foci`}>
<Stepper activeStep={currentStep}>
<Step>
<StepLabel><FormattedMessage {...localMessages.step0Name} /></StepLabel>
</Step>
<Step>
<StepLabel><FormattedMessage {...localMessages.step1Name} /></StepLabel>
</Step>
<Step>
<StepLabel><FormattedMessage {...localMessages.step2Name} /></StepLabel>
</Step>
<Step>
<StepLabel><FormattedMessage {...localMessages.step3Name} /></StepLabel>
</Step>
</Stepper>
</BackLinkingControlBar>
<CurrentStepComponent topicId={topicId} location={location} initialValues={initialValues} onDone={onDone} />
</div>
);
}
}
FocusBuilderWizard.propTypes = {
// from parent
topicId: PropTypes.number.isRequired,
initialValues: PropTypes.object,
startStep: PropTypes.number,
location: PropTypes.object,
onDone: PropTypes.func.isRequired,
// from state
currentStep: PropTypes.number.isRequired,
// from dispatch
goToStep: PropTypes.func.isRequired,
handleUnmount: PropTypes.func.isRequired,
};
const mapStateToProps = state => ({
currentStep: state.topics.selected.focalSets.create.workflow.currentStep,
});
const mapDispatchToProps = dispatch => ({
goToStep: (step) => {
dispatch(goToCreateFocusStep(step));
},
handleUnmount: () => {
dispatch(goToCreateFocusStep(0)); // reset for next time
},
});
export default
injectIntl(
connect(mapStateToProps, mapDispatchToProps)(
FocusBuilderWizard
)
);
|
graphwalker-studio/src/main/js/components/sidemenu/editor-menu.js | KristianKarl/graphwalker-project | import React, { Component } from 'react';
import { connect } from "react-redux";
import { Button, ButtonGroup } from "@blueprintjs/core";
import { toggleProperties} from "../../redux/actions";
class EditorMenu extends Component {
render() {
return (
<ButtonGroup minimal={true} vertical={true} large={true}>
<Button disabled={this.props.isMenuDisabled} className="sidemenu-button" icon="properties" onClick={ this.props.toggleProperties } />
</ButtonGroup>
);
}
}
const mapStateToProps = ({ test: { models }}) => {
return {
isMenuDisabled: models.length === 0
}
}
export default connect(mapStateToProps, { toggleProperties })(EditorMenu);
|
app/components/TextInput/index.js | rahsheen/scalable-react-app | /**
*
* TextInput
*
*/
import React from 'react';
import styles from './styles.css';
import classNames from 'classnames';
class TextInput extends React.Component { // eslint-disable-line react/prefer-stateless-function
value() {
return this.field.value;
}
render() {
const { errorText } = this.props;
const fieldError = errorText ? (
<div
className={styles.errorMessage}
>
{errorText}
</div>
) : null;
return (
<div>
<input
className={classNames(styles.input, this.props.className, { [styles.inputError]: this.props.errorText })}
placeholder={this.props.placeholder}
ref={(f) => { this.field = f; }}
type="text"
/>
{fieldError}
</div>
);
}
}
TextInput.propTypes = {
errorText: React.PropTypes.string,
placeholder: React.PropTypes.string,
className: React.PropTypes.string,
};
export default TextInput;
|
src/svg-icons/editor/format-indent-increase.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatIndentIncrease = (props) => (
<SvgIcon {...props}>
<path d="M3 21h18v-2H3v2zM3 8v8l4-4-4-4zm8 9h10v-2H11v2zM3 3v2h18V3H3zm8 6h10V7H11v2zm0 4h10v-2H11v2z"/>
</SvgIcon>
);
EditorFormatIndentIncrease = pure(EditorFormatIndentIncrease);
EditorFormatIndentIncrease.displayName = 'EditorFormatIndentIncrease';
EditorFormatIndentIncrease.muiName = 'SvgIcon';
export default EditorFormatIndentIncrease;
|
static/src/components/islands/IslandLog.js | hammerandchisel/airhornbot | // @flow
// jscs:disable maximumLineLength
import React from 'react';
type Props = {
paused: boolean
};
export default ({paused}: Props): React.Element => (
<svg className={`island log ${paused ? 'paused' : ''}`} xmlns="http://www.w3.org/2000/svg" width="259" height="209">
<g fill="none" fill-rule="evenodd">
<path fill="#FFE6A7" d="M1.5012 81.2279v57.903l118.413 68.367 136.734-78.942v-57.903L1.5012 81.2279z"/>
<path fill="#EDD194" d="M118.8135 76.3652v130.5l1.101.633 136.734-78.942v-57.903l-137.835 5.712z"/>
<path stroke="#5E4634" strokeWidth="3" d="M256.6494 70.6514v57.906l-136.734 78.942-118.416-68.367v-57.906" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#C7E082" d="M1.5012 81.2279v20.403l118.413 68.37 136.734-78.945v-20.403L1.5012 81.2279z"/>
<path fill="#B0CC64" d="M119.8134 76.3235v93.618l.102.06 136.734-78.945v-20.406l-136.836 5.673z"/>
<path stroke="#5E4634" strokeWidth="3" d="M256.6494 73.6514v17.406l-136.734 78.942-118.416-68.367v-20.406" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#B7D86F" d="M1.5012 81.2279l118.413 68.367 136.734-78.942-118.413-68.367-136.734 78.942z"/>
<path stroke="#5E4634" strokeWidth="3" d="M119.9151 149.5949L1.4991 81.2279l136.734-78.945 118.416 68.37-136.734 78.942zm0 0v57.906m-5.0829-88.8003v3.249m-57.1155-44.385v3.249m161.3796-10.1622v3.249m-90.0216 34.4529v3.249m4.7883-6.4989v3.249M99.2985 42.3533v3.249" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#EBEBEB" d="M132.3141 38.8256h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338"/>
<path stroke="#5E4634" strokeWidth="3" d="M132.3141 38.8256h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338z" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#EBEBEB" d="M191.0727 60.9152h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338"/>
<path stroke="#5E4634" strokeWidth="3" d="M191.0727 60.9152h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338z" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#EDD194" d="M160.2915 81.4802l13.47-7.698c1.707-.978 3.933-.729 5.217.765.957 1.113 1.551 2.673 1.551 4.398 0 2.31-1.065 4.323-2.64 5.364l-13.533 8.703"/>
<path stroke="#5E4634" strokeWidth="3" d="M160.2915 81.4802l13.47-7.698c1.707-.978 3.933-.729 5.217.765.957 1.113 1.551 2.673 1.551 4.398 0 2.31-1.065 4.323-2.64 5.364l-13.533 8.703" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#FFE6A7" d="M167.5194 87.2708c0 3.444-2.325 6.237-5.193 6.237-2.868 0-5.19-2.793-5.19-6.237s2.322-6.237 5.19-6.237c2.868 0 5.193 2.793 5.193 6.237"/>
<path stroke="#5E4634" strokeWidth="3" d="M167.5194 87.2708c0 3.444-2.325 6.237-5.193 6.237-2.868 0-5.19-2.793-5.19-6.237s2.322-6.237 5.19-6.237c2.868 0 5.193 2.793 5.193 6.237z" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#DCFAFF" d="M130.9788 89.6828c-13.386 7.728-33.633 8.568-45.225 1.875-11.592-6.693-10.14-18.384 3.246-26.112 13.386-7.728 33.633-8.568 45.225-1.875 11.592 6.693 10.14 18.384-3.246 26.112"/>
<path stroke="#5E4634" strokeWidth="3" d="M130.9788 89.6828c-13.386 7.728-33.633 8.568-45.225 1.875-11.592-6.693-10.14-18.384 3.246-26.112 13.386-7.728 33.633-8.568 45.225-1.875 11.592 6.693 10.14 18.384-3.246 26.112z" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#DCFAFF" d="M165.1434 50.429c-4.131 2.385-10.383 2.646-13.962.579-3.579-2.067-3.129-5.676 1.002-8.061 4.134-2.385 10.383-2.646 13.962-.579 3.579 2.067 3.129 5.676-1.002 8.061"/>
<path stroke="#5E4634" strokeWidth="3" d="M165.1434 50.429c-4.131 2.385-10.383 2.646-13.962.579-3.579-2.067-3.129-5.676 1.002-8.061 4.134-2.385 10.383-2.646 13.962-.579 3.579 2.067 3.129 5.676-1.002 8.061z" strokeLinecap="round" strokeLinejoin="round"/>
</g>
</svg>
);
|
src/components/NoMatch.js | uxlayouts/spidermonkey | import React from 'react'
const NoMatch = ({ location }) => (
<div className="container-fluid padding-top-3 padding-bottom-3">
<h3>Sorry, we could not find: <code>{location.pathname}</code></h3>
</div>
)
export default NoMatch
|
projects/twitch-web/src/components/App.js | unindented/twitch-x | import React from 'react'
import PropTypes from 'prop-types'
import Root from 'twitch-ui/src/components/Root'
import Navigation from 'twitch-ui/src/components/Navigation'
import Main from 'twitch-ui/src/components/Main'
export default function App (props) {
const {children} = props
return (
<Root>
<Navigation />
<Main>
{children}
</Main>
</Root>
)
}
App.propTypes = {
children: PropTypes.node
}
|
fields/types/textarea/TextareaField.js | helloworld3q3q/keystone | import Field from '../Field';
import React from 'react';
import { FormInput } from 'elemental';
module.exports = Field.create({
displayName: 'TextareaField',
statics: {
type: 'Textarea',
},
renderField () {
const { height, path, style, value } = this.props;
const styles = {
height: height,
...style,
};
return (
<FormInput
autoComplete="off"
multiline
name={this.getInputName(path)}
onChange={this.valueChanged}
ref="focusTarget"
style={styles}
value={value}
/>
);
},
});
|
src/LeftHalf.js | takng/REACT-STOCK | import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import ContentAdd from 'material-ui/svg-icons/content/add';
import { Button, Card, Row, Col } from 'react-materialize';
import {LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend} from 'recharts';
//const d = []
export default ({ stocks, handleAdd, lows, fluctuate }) => {
console.log(stocks.regularMarketChangePercent)
if (stocks.regularMarketChangePercent >= 1) {
return (
<div className="left-half">
<article>
<div className = "stats" >
<h1 className = "stats"> Stock Details</h1>
</div>
<div><br/></div>
<table className ="bordered">
<tbody>
<tr>
<td>Name</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.longName}</td>
</tr>
<tr>
<td>Symbol</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.symbol}</td>
</tr>
<tr>
<td>Price</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketPrice}</td>
</tr>
<tr>
<td>Previous Close</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketPreviousClose}</td>
</tr>
<tr>
<td>Open</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketOpen}</td>
</tr>
<tr>
<td>High</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketDayHigh}</td>
</tr>
<tr>
<td>Low</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketDayLow}</td>
</tr>
<tr>
<td>52 Week High</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.fiftyTwoWeekHigh}</td>
</tr>
<tr>
<td>52 Week Low</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.fiftyTwoWeekLow}</td>
</tr>
<tr>
<td>Percentage Change</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td className = "percentage">{stocks.regularMarketChangePercent}</td>
</tr>
<tr className= "last-tr">
<td>Volume</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketVolume}</td>
</tr>
</tbody>
</table>
<div><br/></div>
<LineChart width={500} height={300} data={lows}>
<Line type="monotone" dataKey="price" stroke="#026ed1" />
<CartesianGrid stroke="#ccc" />
<XAxis dataKey="Date" />
<Tooltip />
<YAxis />
</LineChart>
<div className = "button">
<RaisedButton
label="Add Stock"
labelPosition="before"
icon={<ContentAdd/>}
onClick= {handleAdd}
/>
</div>
</article>
</div>
)
} else if (stocks.regularMarketChangePercent < 0){
return (
<div className="left-half">
<article>
<div className = "stats" >
<h1 className = "stats"> Stock Details</h1>
</div>
<div><br/></div>
<table className ="bordered">
<tbody>
<tr>
<td>Name</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.longName}</td>
</tr>
<tr>
<td>Symbol</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.symbol}</td>
</tr>
<tr>
<td>Price</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketPrice}</td>
</tr>
<tr>
<td>Previous Close</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketPreviousClose}</td>
</tr>
<tr>
<td>Open</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketOpen}</td>
</tr>
<tr>
<td>High</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketDayHigh}</td>
</tr>
<tr>
<td>Low</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketDayLow}</td>
</tr>
<tr>
<td>52 Week High</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.fiftyTwoWeekHigh}</td>
</tr>
<tr>
<td>52 Week Low</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.fiftyTwoWeekLow}</td>
</tr>
<tr>
<td>Percent Change</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td className = "percent">{stocks.regularMarketChangePercent}</td>
</tr>
<tr className= "last-tr">
<td>Volume</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketVolume}</td>
</tr>
</tbody>
</table>
<div><br/></div>
<LineChart width={500} height={300} data={lows}>
<Line type="monotone" dataKey="price" stroke="#026ed1" />
<CartesianGrid stroke="#ccc" />
<XAxis dataKey="Date" />
<Tooltip />
<YAxis />
</LineChart>
<div className = "button">
<RaisedButton
label="Add Stock"
labelPosition="before"
icon={<ContentAdd/>}
onClick= {handleAdd}
/>
</div>
</article>
</div>
)
} else {
return (
<div className="left-half">
<article>
<div className = "stats" >
<h1 className = "stats"> Stock Details</h1>
</div>
<div><br/></div>
<table className ="bordered">
<tbody>
<tr>
<td>Name</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.longName}</td>
</tr>
<tr>
<td>Symbol</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.symbol}</td>
</tr>
<tr>
<td>Price</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketPrice}</td>
</tr>
<tr>
<td>Previous Close</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketPreviousClose}</td>
</tr>
<tr>
<td>Open</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketOpen}</td>
</tr>
<tr>
<td>High</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketDayHigh}</td>
</tr>
<tr>
<td>Low</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketDayLow}</td>
</tr>
<tr>
<td>52 Week High</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.fiftyTwoWeekHigh}</td>
</tr>
<tr>
<td>52 Week Low</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.fiftyTwoWeekLow}</td>
</tr>
<tr>
<td>Percent Change</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketChangePercent}</td>
</tr>
<tr className= "last-tr">
<td>Volume</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>{stocks.regularMarketVolume}</td>
</tr>
</tbody>
</table>
<div><br/></div>
<LineChart width={500} height={300} data={lows}>
<Line type="monotone" dataKey="price" stroke="#026ed1" />
<CartesianGrid stroke="#ccc" />
<XAxis dataKey="Date" />
<Tooltip />
<YAxis />
</LineChart>
<div className = "button">
<RaisedButton
label="Add Stock"
labelPosition="before"
icon={<ContentAdd/>}
onClick= {handleAdd}
/>
</div>
</article>
</div>
)
}
}
|
jenkins-design-language/src/js/components/material-ui/svg-icons/action/schedule.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionSchedule = (props) => (
<SvgIcon {...props}>
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/>
</SvgIcon>
);
ActionSchedule.displayName = 'ActionSchedule';
ActionSchedule.muiName = 'SvgIcon';
export default ActionSchedule;
|
docs/app/Examples/elements/Image/States/ImageExampleDisabled.js | koenvg/Semantic-UI-React | import React from 'react'
import { Image } from 'semantic-ui-react'
const ImageExampleDisabled = () => (
<Image src='/assets/images/wireframe/image.png' size='medium' disabled />
)
export default ImageExampleDisabled
|
docs/app/Examples/views/Comment/Types/CommentExampleComment.js | clemensw/stardust | import React from 'react'
import { Button, Comment, Form, Header } from 'semantic-ui-react'
const CommentExampleComment = () => (
<Comment.Group>
<Header as='h3' dividing>Comments</Header>
<Comment>
<Comment.Avatar src='http://semantic-ui.com/images/avatar/small/matt.jpg' />
<Comment.Content>
<Comment.Author as='a'>Matt</Comment.Author>
<Comment.Metadata>
<div>Today at 5:42PM</div>
</Comment.Metadata>
<Comment.Text>How artistic!</Comment.Text>
<Comment.Actions>
<Comment.Action>Reply</Comment.Action>
</Comment.Actions>
</Comment.Content>
</Comment>
<Comment>
<Comment.Avatar src='http://semantic-ui.com/images/avatar/small/elliot.jpg' />
<Comment.Content>
<Comment.Author as='a'>Elliot Fu</Comment.Author>
<Comment.Metadata>
<div>Yesterday at 12:30AM</div>
</Comment.Metadata>
<Comment.Text>
<p>This has been very useful for my research. Thanks as well!</p>
</Comment.Text>
<Comment.Actions>
<Comment.Action>Reply</Comment.Action>
</Comment.Actions>
</Comment.Content>
<Comment.Group>
<Comment>
<Comment.Avatar src='http://semantic-ui.com/images/avatar/small/jenny.jpg' />
<Comment.Content>
<Comment.Author as='a'>Jenny Hess</Comment.Author>
<Comment.Metadata>
<div>Just now</div>
</Comment.Metadata>
<Comment.Text>
Elliot you are always so right :)
</Comment.Text>
<Comment.Actions>
<Comment.Action>Reply</Comment.Action>
</Comment.Actions>
</Comment.Content>
</Comment>
</Comment.Group>
</Comment>
<Comment>
<Comment.Avatar src='http://semantic-ui.com/images/avatar/small/joe.jpg' />
<Comment.Content>
<Comment.Author as='a'>Joe Henderson</Comment.Author>
<Comment.Metadata>
<div>5 days ago</div>
</Comment.Metadata>
<Comment.Text>
Dude, this is awesome. Thanks so much
</Comment.Text>
<Comment.Actions>
<Comment.Action>Reply</Comment.Action>
</Comment.Actions>
</Comment.Content>
</Comment>
<Form reply onSubmit={e => e.preventDefault()}>
<Form.TextArea />
<Button content='Add Reply' labelPosition='left' icon='edit' primary />
</Form>
</Comment.Group>
)
export default CommentExampleComment
|
examples/quick-start/components/user-form.js | davidkpiano/redux-simple-form | import React from 'react';
import { LocalForm, Form, actions, Control, Field, Errors } from 'react-redux-form';
import { connect } from 'react-redux';
import icepick from 'icepick';
window.i = icepick;
const required = (val) => !!(val && val.length);
function hasToBeTrue(value) {
if (value === false || typeof value !== 'boolean') {
return false;
}
return true;
}
// control
class UserForm extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(user) {
const { dispatch } = this.props;
// Do whatever you like in here.
// You can use actions such as:
// dispatch(actions.submit('user', somePromise));
// etc.
const somePromise = new Promise((resolve) => {
/* eslint-disable no-console */
console.log(user);
/* eslint-enable no-console */
setTimeout(() => { resolve(true); }, 1000);
});
dispatch(actions.submit('user', somePromise));
}
render() {
return (
<Form model="user" onSubmit={this.handleSubmit}>
<div>
<label>First name:</label>
<Control.text
model="user.firstName"
validators={{len: (val) => val.length > 8}}
mapProps={{
className: ({fieldValue}) => fieldValue.focus
? 'focused'
: ''
}}
/>
<Errors model=".firstName" messages={{
len: 'len must be > 8'
}} />
</div>
<div>
<label>Last name:</label>
<Control model="user.lastName" validators={{required}}/>
</div>
<Field model="user.bag">
<label>
<input type="radio" value="plastic" />
<span>Plastic</span>
</label>
<label>
<input type="radio" value="paper" />
<span>Paper</span>
</label>
</Field>
<Control.button model="user" disabled={{ valid: false }}>
Finish registration!
</Control.button>
<input type="reset" value="Reset" title="reset"/>
</Form>
);
}
}
UserForm.propTypes = {
dispatch: React.PropTypes.func.isRequired,
user: React.PropTypes.shape({
firstName: React.PropTypes.string.isRequired,
lastName: React.PropTypes.string.isRequired,
}).isRequired,
};
export default connect(s=>s)(UserForm);
|
src/client/spinner.js | eiriklv/hacker-menu | import React from 'react'
export default class Spinner extends React.Component {
render () {
return (
<div className='spinner'>
Loading...
</div>
)
}
}
|
src/components/layouts/main-layout.js | mberneti/ReactAdmin | import React from 'react';
import Menu from './menu';
import Header from './header';
const mainLayout = props => {
return (
<div id="wrapper">
{props.alert}
<nav className="navbar navbar-default navbar-static-top" role="navigation">
<Header fullname={props.fullname} />
<Menu />
</nav>
{props.children}
</div>
);
};
export default mainLayout; |
plugins/Files/js/components/addfolderbutton.js | NebulousLabs/New-Sia-UI | import React from 'react'
const AddFolderButton = ({ actions }) => {
const handleClick = () => actions.showAddFolderDialog()
return (
<div onClick={handleClick} className='addfolder-button'>
<i className='fa fa-folder fa-2x' />
<span> New Folder </span>
</div>
)
}
export default AddFolderButton
|
ios/versioned-react-native/ABI10_0_0/Libraries/Modal/Modal.js | jolicloud/exponent | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Modal
* @flow
*/
'use strict';
const I18nManager = require('I18nManager');
const Platform = require('Platform');
const PropTypes = require('react/lib/ReactPropTypes');
const React = require('React');
const StyleSheet = require('StyleSheet');
const UIManager = require('UIManager');
const View = require('View');
const deprecatedPropType = require('deprecatedPropType');
const requireNativeComponent = require('requireNativeComponent');
const RCTModalHostView = requireNativeComponent('RCTModalHostView', null);
/**
* The Modal component is a simple way to present content above an enclosing view.
*
* _Note: If you need more control over how to present modals over the rest of your app,
* then consider using a top-level Navigator. Go [here](/react-native/docs/navigator-comparison.html) to compare navigation options._
*
* ```javascript
* import React, { Component } from 'react';
* import { Modal, Text, TouchableHighlight, View } from 'react-native';
*
* class ModalExample extends Component {
*
* constructor(props) {
* super(props);
* this.state = {modalVisible: false};
* }
*
* setModalVisible(visible) {
* this.setState({modalVisible: visible});
* }
*
* render() {
* return (
* <View style={{marginTop: 22}}>
* <Modal
* animationType={"slide"}
* transparent={false}
* visible={this.state.modalVisible}
* onRequestClose={() => {alert("Modal has been closed.")}}
* >
* <View style={{marginTop: 22}}>
* <View>
* <Text>Hello World!</Text>
*
* <TouchableHighlight onPress={() => {
* this.setModalVisible(!this.state.modalVisible)
* }}>
* <Text>Hide Modal</Text>
* </TouchableHighlight>
*
* </View>
* </View>
* </Modal>
*
* <TouchableHighlight onPress={() => {
* this.setModalVisible(true)
* }}>
* <Text>Show Modal</Text>
* </TouchableHighlight>
*
* </View>
* );
* }
* }
* ```
*/
class Modal extends React.Component {
static propTypes = {
/**
* The `animationType` prop controls how the modal animates.
*
* - `slide` slides in from the bottom
* - `fade` fades into view
* - `none` appears without an animation
*/
animationType: PropTypes.oneOf(['none', 'slide', 'fade']),
/**
* The `transparent` prop determines whether your modal will fill the entire view. Setting this to `true` will render the modal over a transparent background.
*/
transparent: PropTypes.bool,
/**
* The `visible` prop determines whether your modal is visible.
*/
visible: PropTypes.bool,
/**
* The `onRequestClose` prop allows passing a function that will be called once the modal has been dismissed.
*
* _On the Android platform, this is a required function._
*/
onRequestClose: Platform.OS === 'android' ? PropTypes.func.isRequired : PropTypes.func,
/**
* The `onShow` prop allows passing a function that will be called once the modal has been shown.
*/
onShow: PropTypes.func,
animated: deprecatedPropType(
PropTypes.bool,
'Use the `animationType` prop instead.'
),
};
static defaultProps = {
visible: true,
};
render(): ?ReactElement<any> {
if (this.props.visible === false) {
return null;
}
const containerStyles = {
backgroundColor: this.props.transparent ? 'transparent' : 'white',
top: Platform.OS === 'android' && Platform.Version >= 19 ? UIManager.RCTModalHostView.Constants.StatusBarHeight : 0,
};
let animationType = this.props.animationType;
if (!animationType) {
// manually setting default prop here to keep support for the deprecated 'animated' prop
animationType = 'none';
if (this.props.animated) {
animationType = 'slide';
}
}
return (
<RCTModalHostView
animationType={animationType}
transparent={this.props.transparent}
onRequestClose={this.props.onRequestClose}
onShow={this.props.onShow}
style={styles.modal}
onStartShouldSetResponder={this._shouldSetResponder}
>
<View style={[styles.container, containerStyles]}>
{this.props.children}
</View>
</RCTModalHostView>
);
}
// We don't want any responder events bubbling out of the modal.
_shouldSetResponder(): boolean {
return true;
}
}
const side = I18nManager.isRTL ? 'right' : 'left';
const styles = StyleSheet.create({
modal: {
position: 'absolute',
},
container: {
position: 'absolute',
[side] : 0,
top: 0,
}
});
module.exports = Modal;
|
src/components/conversation/MessageGif/MessageGif.js | rlesniak/tind3r.com | // @flow
import React, { Component } from 'react';
import { observable, action } from 'mobx';
import { observer } from 'mobx-react';
import cx from 'classnames';
import each from 'lodash/each';
import map from 'lodash/map';
import axios from 'axios';
import './MessageGif.scss';
const fetchGipy = query => axios.get(`http://api.giphy.com/v1/gifs/search?q=${encodeURI(query)}&api_key=dc6zaTOxFJmzC`);
type PropsType = {
onSelect: (body: string, data: Object) => void,
onToggle: (state: boolean) => void,
}
@observer
class MessageGif extends Component {
componentDidMount() {
if (this.inputRef) {
this.inputRef.focus();
}
document.addEventListener('mousedown', this.onMouseDown);
}
onMouseDown = (e: any) => {
if (this.wrapperRef && !this.wrapperRef.contains(e.target)) {
this.props.onToggle(false);
}
}
props: PropsType;
inputRef: ?any;
wrapperRef: ?any;
@observable text: string = '';
@observable gifs: Array<Object> = [];
handleChange = (e: SyntheticInputEvent) => {
this.text = e.target.value;
}
handleKeydown = async (e: SyntheticInputEvent) => {
if (e.keyCode === 13) {
const { data } = await fetchGipy(this.text);
this.gifs = [];
each(data.data, action((gif) => {
this.gifs.push({
id: gif.id,
url: gif.images.downsized.url,
fixedHeight: gif.images.fixed_height,
});
}));
}
}
handleSelect = (gif: Object) => {
const url = `${gif.fixedHeight.url}?width=${gif.fixedHeight.width}&height=${gif.fixedHeight.height}`;
this.props.onSelect(url, {
type: 'GIF',
gif_id: gif.id,
});
this.props.onToggle(false);
}
render() {
return (
<div
className={cx('message-gif')}
ref={(ref) => { this.wrapperRef = ref; }}
>
<div className="message-gif__input">
<input
ref={(ref) => { this.inputRef = ref; }}
onChange={this.handleChange}
onKeyDown={this.handleKeydown}
placeholder="Search here"
className="pt-input pt-intent-primary"
/>
</div>
<div className="message-gif__list">
{map(this.gifs, gif => (
<div key={gif.id} className="message-gif__list-item" onClick={() => this.handleSelect(gif)}>
<img alt="gif" src={gif.url} />
</div>
))}
</div>
</div>
);
}
}
export default MessageGif;
|
imports/ui/home/components/committee_form.js | dououFullstack/atomic | import React from 'react';
import Modal from 'react-modal';
import { Field, reduxForm } from 'redux-form';
import ReactMarkdown from 'react-markdown';
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
readme: false,
invitation: false,
};
}
readme() {
this.setState({
readme: true,
invitation: false,
});
}
invitation() {
this.setState({
readme: false,
invitation: true,
});
}
render() {
const input = this.props.readme;
const style = {
overlay : {
position : 'fixed',
top : 0,
left : 0,
right : 0,
bottom : 60,
backgroundColor : 'rgba(255, 255, 255, 0.75)'
},
content : {
position : 'absolute',
top : '10px',
left : '10px',
right : '10px',
bottom : '10px',
border : '1px solid #ccc',
background : '#fff',
overflow : 'auto',
WebkitOverflowScrolling : 'touch',
borderRadius : '4px',
outline : 'none',
padding : '20px'
}
}
return (
<form className="new-form" onSubmit={this.props.handleSubmit}>
<Modal
isOpen={this.state.readme}
style={style}
>
<div className="invitation-title">入会须知</div>
<ReactMarkdown source={input} />
<button type="submit" onClick={()=> this.setState({readme: false, invitation:false})} className="weui-btn weui-btn_primary" style={{width: '70%', marginTop: 30, marginBottom: 10}}>我已阅读</button>
</Modal>
<Modal
isOpen={this.state.invitation}
style={style}
>
<div className="content">
<div className="invitation-title">《中国核电》杂志第三届理事会</div>
<div className="invitation-title">邀 请 函 </div>
<p> </p>
<p> 目前,核电发展一直受到中国政府的高度重视。在国家“一带一路”发展战略的推动下,中国核电迎来了快速发展的机遇期,核电必将成为中国能源结构化发展的重要保障。</p>
<p> 《中国核电》杂志(CN11-5660/TL)创刊于2008年1月,是国内唯一一本公开出版的核电类杂志。杂志由吴邦国同志题写刊名,中国核工业集团公司主管,中国原子能出版传媒有限公司主办。</p>
<p> 杂志社每期都赠阅刊物给国务院有关部门及相关直属机构等,并送国际原子能机构等国际相关机构,以及国内外相关核电站和相关核电设备制造商等。杂志宗旨是宣传我国核电建设的方针政策;研讨我国核电建设的规划和如何加快我国核电发展等相关重大问题;分析讨论核电站的安全性、可靠性、经济性;介绍与我国核电工程建设有关的法规、标准;交流核电工作管理和建设经验;宣传我国核电自主研发、设计建造和设备国产化的最新进展;报道国内外核电建设和运行的最新动态和信息;跟踪国内外先进核电技术;加强与国际相关组织机构的信息与技术交流;普及核电知识等。</p>
<p> 杂志由理事会、学术委员会、编辑委员会、杂志社等机构组成,作为理事会成员单位,可在杂志上优先发表论文,并可每期获赠一定数量的杂志;也可从本杂志获取相关咨询服务;成员单位在杂志上刊登广告可以享受一定的优惠;杂志作为我国核电行业宣传的平台,每年定期组织理事会成员单位的交流活动。为了把《中国核电》杂志办成国内外具有影响力的核心刊物,我们诚挚邀请我国从事核电产业的企事业单位、科研院所、大专院校共同关心和支持《中国核电》出版发行工作。</p>
<p> 目前,《中国核电》杂志理事会已有成员71家,其中理事长单位1家,副理事长单位8家,常务理事单位9家,理事会单位53家。谨此,特邀请贵单位加入《中国核电》杂志理事会。</p>
<p> 联系人:王 丹 电 话:010-88828694 E-mail:[email protected]</p>
<div style={{textAlign: 'right'}}>《中国核电》杂志理事会</div>
<button type="submit" onClick={()=> this.setState({readme: false, invitation:false})} className="weui-btn weui-btn_primary" style={{width: '70%', marginTop: 30, marginBottom: 10}}>我已阅读</button>
</div>
</Modal>
<div className="weui-cells__title">申请入会</div>
<div className="weui-cells weui-cells_form">
<div className="weui-cell">
<div className="weui-cell__hd">
<label className="weui-label">单位名称</label>
</div>
<div className="weui-cell__bd">
<Field name="unit" component="input" type="text"/>
</div>
</div>
<div className="weui-cell">
<div className="weui-cell__hd">
<label className="weui-label">入会级别</label>
</div>
<div className="weui-cell__bd">
<Field name="title" component="input" placeholder="副理事长 / 常务理事 / 理事" type="text"/>
</div>
</div>
<div className="weui-cell">
<div className="weui-cell__hd"><label className="weui-label">联系人</label></div>
<div className="weui-cell__bd">
<Field name="linkman" component="input" type="text"/>
</div>
</div>
<div className="weui-cell">
<div className="weui-cell__hd">
<label className="weui-label">联系方式</label>
</div>
<div className="weui-cell__bd">
<Field name="address" component="input" type="text"/>
</div>
</div>
</div>
<div onClick={this.readme.bind(this)} style={{textAlign: 'center', width: '100%', marginTop: 10}}>
<div className="inline field">
<div className="ui checkbox">
<input type="checkbox" checked name="example"/>
<label>入会须知</label>
</div>
</div>
</div>
<div onClick={this.invitation.bind(this)} style={{textAlign: 'center', width: '100%', marginTop: 10}}>
<div className="inline field">
<div className="ui checkbox">
<input type="checkbox" checked name="example"/>
<label> 邀 请 函 </label>
</div>
</div>
</div>
<button type="submit" className="weui-btn weui-btn_primary" style={{width: '70%', marginTop: 10, marginBottom: 25}}>提交申请</button>
</form>
);
}
}
export default reduxForm({ form: 'committeeNew' })(Form);
|
app/javascript/mastodon/features/compose/components/text_icon_button.js | increments/mastodon | import React from 'react';
import PropTypes from 'prop-types';
export default class TextIconButton extends React.PureComponent {
static propTypes = {
label: PropTypes.string.isRequired,
title: PropTypes.string,
active: PropTypes.bool,
onClick: PropTypes.func.isRequired,
ariaControls: PropTypes.string,
};
handleClick = (e) => {
e.preventDefault();
this.props.onClick();
}
render () {
const { label, title, active, ariaControls } = this.props;
return (
<button title={title} aria-label={title} className={`text-icon-button ${active ? 'active' : ''}`} aria-expanded={active} onClick={this.handleClick} aria-controls={ariaControls}>
{label}
</button>
);
}
}
|
assets/javascripts/kitten/components/embed/responsive-iframe-container/stories.js | KissKissBankBank/kitten | import React from 'react'
import { ResponsiveIframeContainer } from './index'
import { COLORS } from 'kitten'
import { DocsPage } from 'storybook/docs-page'
export default {
title: 'Embed/ResponsiveIframeContainer',
component: ResponsiveIframeContainer,
parameters: {
docs: {
page: () => (
<DocsPage
filepath={__filename}
importString="ResponsiveIframeContainer"
/>
),
},
},
decorators: [
story => <div className="story-Container story-Grid">{story()}</div>,
],
argTypes: {
ratio: {
name: 'ratio',
control: 'number',
},
children: {
name: 'children',
control: null,
},
},
args: {
ratio: 67.5,
children: <iframe style={{ backgroundColor: COLORS.line1 }} />,
},
}
export const Default = args => <ResponsiveIframeContainer {...args} />
|
upgrade-guides/v0.12-v0.13/es5/src/components/Master.js | lore/lore | /**
* This component serves as the root of your application, and should typically be the only
* component subscribed to the store.
*
* It is also a good place to fetch the current user. Once you have configured 'models/currentUser'
* to fetch the current user (by pointing it to the correct API endpoint) uncomment the commented
* out code below in order to fetch the user, display a loading experience while they're being
* fetched, and store the user in the applications context so that components can retrieve it
* without having to pass it down through props or extract it from the Redux store directly.
**/
import React from 'react';
import createReactClass from 'create-react-class';
import PropTypes from 'prop-types';
import { connect } from 'lore-hook-connect';
import PayloadStates from '../constants/PayloadStates';
import RemoveLoadingScreen from './RemoveLoadingScreen';
import '../../assets/css/main.css';
export default connect(function(getState, props) {
return {
// user: getState('currentUser')
};
}, { subscribe: true })(
createReactClass({
displayName: 'Master',
// propTypes: {
// user: PropTypes.object.isRequired
// },
// childContextTypes: {
// user: PropTypes.object
// },
// getChildContext() {
// return {
// user: this.props.user
// };
// },
componentDidMount() {
// If you want to play with the router through the browser's dev console then
// uncomment out this line. React Router automatically provides 'router'
// to any components that are "routes" (such as Master and Layout), so this
// is a good location to attach it to the global lore object.
// lore.router = this.props.router;
},
render() {
// const { user } = this.props;
// if (user.state === PayloadStates.FETCHING) {
// return null;
// }
return (
<div>
<RemoveLoadingScreen/>
{React.cloneElement(this.props.children)}
</div>
);
}
})
);
|
src/parser/demonhunter/havoc/modules/spells/MetaBuffUptime.js | sMteX/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS/index';
import SpellIcon from 'common/SpellIcon';
import { formatPercentage, formatDuration } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
/*
example report: https://www.warcraftlogs.com/reports/KGJgZPxanBX82LzV/#fight=4&source=20
* */
class MetaBuffUptime extends Analyzer {
get buffUptime() {
return this.selectedCombatant.getBuffUptime(SPELLS.METAMORPHOSIS_HAVOC_BUFF.id) / this.owner.fightDuration;
}
get buffDuration() {
return this.selectedCombatant.getBuffUptime(SPELLS.METAMORPHOSIS_HAVOC_BUFF.id);
}
statistic() {
return (
<StatisticBox
position={STATISTIC_ORDER.CORE(3)}
icon={<SpellIcon id={SPELLS.METAMORPHOSIS_HAVOC_BUFF.id} />}
value={`${formatPercentage(this.buffUptime)}%`}
label="Metamorphosis Uptime"
tooltip={`The Metamorphosis buff total uptime was ${formatDuration(this.buffDuration / 1000)}.`}
/>
);
}
}
export default MetaBuffUptime;
|
src/ReactPureLoggerComponent.js | D-Andreev/react-logger | import React from 'react';
import Logger from './logger/Logger';
export default class ReactPureLoggerComponent extends React.PureComponent {
constructor(props, options) {
super(props);
this.logger = new Logger(options);
this.displayName = props.displayName;
}
componentWillMount() {
this.logger.log(this.displayName, 'componentWillMount');
}
componentDidMount() {
this.logger.log(this.displayName, 'componentDidMount');
}
componentWillReceiveProps(nextProps) {
this.logger.log(this.displayName, 'componentWillReceiveProps', {nextProps});
}
shouldComponentUpdate(nextProps, nextState) {
this.logger.log(this.displayName, 'shouldComponentUpdate', {nextProps, nextState});
return true;
}
componentWillUpdate(nextProps, nextState) {
this.logger.log(this.displayName, 'componentWillUpdate', {nextProps, nextState});
}
componentDidUpdate(prevProps, prevState) {
this.logger.log(this.displayName, 'componentDidUpdate', {prevProps, prevState});
}
componentWillUnmount() {
this.logger.log(this.displayName, 'componentWillUnmount');
}
}
|
src/AppBar/index.js | reactivers/react-material-design | /**
* Created by Utku on 25/03/2017.
*/
import React from 'react';
import PropTypes from 'prop-types';
import '@material/toolbar/dist/mdc.toolbar.css';
import classNames from 'classnames';
export class AppBarTitle extends React.PureComponent {
static propTypes = {
iconAlignment: PropTypes.string,
icon : PropTypes.node,
title : PropTypes.string
}
render() {
const {className,icon, iconAlignment, title,...rest} = this.props
const style = Object.assign({
display: "flex",
justifyContent: 'center',
alignItems: 'center'
}, this.props.style);
return (
<span style={style} {...rest} className={className}>
{icon && (!iconAlignment || iconAlignment !== "right") && icon}
<span className="mdc-toolbar__title">{title}</span>
{icon && iconAlignment && iconAlignment.toLowerCase() === "right" && icon}
</span>
)
}
}
export class AppBar extends React.PureComponent {
static propTypes = {
leftElements : PropTypes.node,
rightElements : PropTypes.node,
middleElements : PropTypes.node,
barColor : PropTypes.string,
fixed : PropTypes.bool
}
render() {
const {className,fixed, style, barColor, leftElements, rightElements, middleElements,...otherProps} = this.props
const classes = classNames("mdc-toolbar", {"mdc-toolbar--fixed": fixed},className);
let barStyle = Object.assign({}, style, {backgroundColor: barColor});
return (
<header className={classes} style={barStyle} {...otherProps}>
{leftElements &&
<section className="mdc-toolbar__section mdc-toolbar__section--align-start">
{leftElements}
</section>}
{middleElements &&
<section className="mdc-toolbar__section">
{middleElements}
</section>}
{rightElements &&
<section className="mdc-toolbar__section mdc-toolbar__section--align-end">
{rightElements}
</section>}
</header>
)
}
} |
src/app/components/task/SingleChoiceTask.js | meedan/check-web | import React, { Component } from 'react';
import Box from '@material-ui/core/Box';
import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Button from '@material-ui/core/Button';
import { FormattedMessage } from 'react-intl';
import ParsedText from '../ParsedText';
import { FormattedGlobalMessage } from '../MappedMessage';
import { safelyParseJSON } from '../../helpers';
import { StyledSmallTextField } from '../../styles/js/shared';
class SingleChoiceTask extends Component {
constructor(props) {
super(props);
this.state = {
response: null,
responseOther: null,
taskAnswerDisabled: true,
};
}
handleSubmitResponse() {
if (!this.state.taskAnswerDisabled) {
const response = this.state.response ? this.state.response.trim() : this.props.response;
this.props.onSubmit(response);
this.setState({ taskAnswerDisabled: true });
}
}
canSubmit() {
const response = this.state.response ? this.state.response.trim() : this.props.response;
const can_submit = !!response;
this.setState({ taskAnswerDisabled: !can_submit });
return can_submit;
}
handleCancelResponse() {
this.setState({
response: null,
responseOther: null,
otherSelected: false,
focus: false,
}, this.canSubmit);
if (this.props.onDismiss) {
this.props.onDismiss();
}
}
handleSelectRadio(e) {
this.setState({
focus: true,
response: e.target.value,
responseOther: '',
otherSelected: false,
taskAnswerDisabled: false,
});
}
handleSelectRadioOther() {
// TODO Use React ref
const input = document.querySelector('.task__option_other_text_input input');
if (input) {
input.focus();
}
this.setState({
focus: true,
response: '',
responseOther: '',
otherSelected: true,
taskAnswerDisabled: true,
});
}
handleEditOther(e) {
const { value } = e.target;
this.setState({
focus: true,
response: value,
responseOther: value,
otherSelected: true,
}, this.canSubmit);
}
handleKeyPress(e) {
if (e.key === 'Enter' && !e.shiftKey) {
if (this.canSubmit()) {
this.setState({ taskAnswerDisabled: true });
this.handleSubmitResponse();
}
e.preventDefault();
}
}
renderOptions(response, jsonoptions) {
const { fieldset } = this.props;
const options = safelyParseJSON(jsonoptions);
const editable = !response || this.props.mode === 'edit_response';
const submitCallback = this.handleSubmitResponse.bind(this);
const cancelCallback = this.handleCancelResponse.bind(this);
const keyPressCallback = this.handleKeyPress.bind(this);
const actionBtns = (
<div>
<Button onClick={cancelCallback}>
<FormattedMessage id="tasks.cancelEdit" defaultMessage="Cancel" />
</Button>
<Button
className="task__submit"
color="primary"
onClick={submitCallback}
disabled={this.state.taskAnswerDisabled}
>
{ fieldset === 'tasks' ?
<FormattedMessage id="tasks.answer" defaultMessage="Answer Task" /> :
<FormattedGlobalMessage messageKey="save" />
}
</Button>
</div>
);
if (Array.isArray(options) && options.length > 0) {
const otherIndex = options.findIndex(item => item.other);
const other = otherIndex >= 0 ? options.splice(otherIndex, 1).pop() : null;
const responseIndex =
options.findIndex(item => item.label === response || item.label === this.state.response);
let responseOther = '';
if (typeof this.state.responseOther !== 'undefined' && this.state.responseOther !== null) {
({ responseOther } = this.state);
} else if (responseIndex < 0) {
responseOther = response;
}
const responseOtherSelected = this.state.otherSelected || responseOther
? responseOther
: 'none';
const responseSelected = this.state.response === null ? response : this.state.response;
return (
<div className="task__options">
<FormGroup>
<RadioGroup
name="response"
onChange={this.handleSelectRadio.bind(this)}
value={responseSelected}
>
{options.map((item, index) => (
<FormControlLabel
key={`task__options--radiobutton-${index.toString()}`}
id={index.toString()}
value={item.label}
label={
<ParsedText text={item.label} />
}
control={
<Radio disabled={!editable} />
}
/>
))}
</RadioGroup>
<Box
display="flex"
justifyContent="flex-start"
alignItems="center"
className="task__options_other"
>
{other ?
<RadioGroup
name="task__option_other_radio"
key="task__option_other_radio"
className="task__option_other_radio"
value={responseOtherSelected}
onChange={this.handleSelectRadioOther.bind(this)}
>
<FormControlLabel
value={responseOther}
control={
<Radio disabled={!editable} />
}
label={editable ?
<StyledSmallTextField
key="task__option_other_text_input"
className="task__option_other_text_input"
placeholder={other.label}
value={responseOther}
name="response"
onKeyPress={keyPressCallback}
onChange={this.handleEditOther.bind(this)}
multiline
/> :
<ParsedText text={responseOther} />
}
/>
</RadioGroup>
: null}
</Box>
{(this.state.focus && editable) || this.props.mode === 'edit_response'
? actionBtns
: null}
</FormGroup>
</div>
);
}
return null;
}
render() {
const {
response,
jsonoptions,
} = this.props;
return (
<div>
{this.props.mode === 'respond' ? this.renderOptions(response, jsonoptions) : null}
{this.props.mode === 'show_response' && response
? this.renderOptions(response, jsonoptions)
: null}
{this.props.mode === 'edit_response'
? this.renderOptions(response, jsonoptions)
: null}
</div>
);
}
}
export default SingleChoiceTask;
|
src/FormControls/Static.js | mcraiganthony/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import InputBase from '../InputBase';
import childrenValueValidation from '../utils/childrenValueInputValidation';
class Static extends InputBase {
getValue() {
const {children, value} = this.props;
return children ? children : value;
}
renderInput() {
return (
<p {...this.props} className={classNames(this.props.className, 'form-control-static')} ref="input" key="input">
{this.getValue()}
</p>
);
}
}
Static.propTypes = {
value: childrenValueValidation,
children: childrenValueValidation
};
export default Static;
|
app/components/inputgroup/inputgroup.js | tidepool-org/blip | import PropTypes from 'prop-types';
import React from 'react';
import _ from 'lodash';
import cx from 'classnames';
import Select from 'react-select';
import DatePicker from '../datepicker';
// Input with label and validation error message
class InputGroup extends React.Component {
static propTypes = {
name: PropTypes.string,
label: PropTypes.node,
items: PropTypes.array,
text: PropTypes.node,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.bool,
PropTypes.object // dates for datepicker input type are objects
]),
error: PropTypes.string,
type: PropTypes.string.isRequired,
placeholder: PropTypes.string,
rows: PropTypes.number,
disabled: PropTypes.bool,
multi: PropTypes.bool,
autoFocus: PropTypes.bool,
defaultChecked: PropTypes.bool,
onChange: PropTypes.func
};
DEFAULT_TEXTAREA_ROWS = 3;
render() {
var className = this.getClassName();
var label = this.renderLabel();
var input = this.renderInput();
var message = this.renderMessage();
return (
<div className={className}>
<div>
{label}
{input}
</div>
{message}
</div>
);
}
renderLabel = () => {
var text = this.props.label;
var htmlFor = this.props.name;
if (this.props.type === 'checkbox' ||
this.props.type === 'radios') {
// Label part of input
return null;
}
if (text) {
return (
<label
className="input-group-label"
htmlFor={htmlFor}
ref="label">{text}</label>
);
}
return null;
};
renderInput = () => {
var type = this.props.type;
if (type === 'textarea') {
return this.renderTextArea();
}
if (type === 'checkbox') {
return this.renderCheckbox();
}
if (type === 'radios') {
return this.renderRadios();
}
if (type === 'select') {
return this.renderSelect();
}
if (type === 'datepicker') {
return this.renderDatePicker();
}
if (type === 'explanation') {
return this.renderExplanation();
}
return (
<input
type={type}
className="input-group-control form-control"
id={this.props.name}
name={this.props.name}
value={this.props.value}
placeholder={this.props.placeholder}
onChange={this.handleChange}
disabled={this.props.disabled}
autoFocus={!!this.props.autoFocus}
ref="control"/>
);
};
renderTextArea = () => {
var rows = this.props.rows || this.DEFAULT_TEXTAREA_ROWS;
return (
<textarea
className="input-group-control form-control"
id={this.props.name}
name={this.props.name}
value={this.props.value}
placeholder={this.props.placeholder}
rows={rows}
onChange={this.handleChange}
disabled={this.props.disabled}
ref="control"></textarea>
);
};
renderCheckbox = () => {
return (
<label
className="input-group-checkbox-label"
htmlFor={this.props.name}
ref="label">
<input
type="checkbox"
className="input-group-checkbox-control"
id={this.props.name}
name={this.props.name}
checked={this.props.value}
onChange={this.handleChange}
disabled={this.props.disabled}
defaultChecked={this.props.defaultChecked}
ref="control"/>
{' '}
{this.props.label}
</label>
);
};
renderRadios = () => {
var self = this;
var radios = _.map(this.props.items, function(radio, index) {
var id = self.props.name + index;
var checked = (self.props.value === radio.value);
return (
<label
className="input-group-radio-label"
htmlFor={id}
key={id}
ref={'label' + index}>
<input
type="radio"
className="input-group-radio-control"
id={id}
name={self.props.name}
value={radio.value}
checked={checked}
onChange={self.handleChange}
disabled={self.props.disabled}
ref={'control' + index}/>
{' '}
{radio.label}
</label>
);
});
return (
<div className="input-group-radios">
{radios}
</div>
);
};
renderSelect = () => {
var isMultiSelect = this.props.multi || false;
var classNames = cx({
'input-group-control': true,
'form-control': true,
'Select': true,
});
let valueArray = [];
if (!_.isEmpty(this.props.value)) {
// Select all provided values that have a corresponding option value
valueArray = _.intersectionBy(
this.props.items,
_.map(this.props.value.split(','), value => ({ value })),
'value'
);
}
return (
<Select
className={classNames}
classNamePrefix="Select"
name={this.props.name}
id={this.props.name}
isMulti={isMultiSelect}
isClearable={isMultiSelect}
closeMenuOnSelect={!isMultiSelect}
placeholder={this.props.placeholder}
value={valueArray}
onChange={this.handleChange}
isDisabled={this.props.disabled}
options={this.props.items}
/>
);
};
renderDatePicker = () => {
return (
<DatePicker
name={this.props.name}
value={this.props.value}
disabled={this.props.disabled}
onChange={this.handleChange} />
);
};
renderExplanation = () => {
return <div className='input-group-explanation'>
{this.props.text}
</div>;
};
renderMessage = () => {
var error = this.props.error;
if (error) {
return (
<div
className="input-group-message form-help-block"
ref="message">{error}</div>
);
}
return null;
};
getClassName = () => {
var className = 'input-group form-group clearfix';
if (this.props.error) {
className += ' input-group-error';
}
return className;
};
handleChange = (e) => {
var target = (e !== null) ? e.target || e : {};
var attributes = {
name: target.name || this.props.name,
value: target.value || null,
};
if (this.props.type === 'checkbox') {
// "Normalize" checkbox change events to use `value` like other inputs
attributes.value = target.checked;
}
if (this.props.type === 'select' && this.props.multi) {
// Target comes in as an array of objects when using react-select's 'multi' attribute
attributes.value = target;
}
var changeCallback = this.props.onChange;
if (changeCallback) {
changeCallback(attributes);
}
};
}
module.exports = InputGroup;
|
packages/icons/src/md/action/Label.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdLabel(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M34.27 11.69A4.015 4.015 0 0 0 31 10l-22 .02c-2.21 0-4 1.77-4 3.98v20c0 2.21 1.79 3.98 4 3.98L31 38c1.35 0 2.54-.67 3.27-1.69L43 24l-8.73-12.31z" />
</IconBase>
);
}
export default MdLabel;
|
src/workshops/presentation/attendee/AnttendeeView.js | GrayTurtle/rocket-workshop | import React from 'react';
import PropTypes from 'prop-types';
import Icon from 'react-icons-kit';
import { ic_keyboard_arrow_left } from 'react-icons-kit/md/ic_keyboard_arrow_left';
import { ic_keyboard_arrow_right } from 'react-icons-kit/md/ic_keyboard_arrow_right';
import { connect } from 'react-redux';
import { firebaseConnect, isLoaded, isEmpty } from 'react-redux-firebase';
import Step from '../step';
import '../assets/css/present.css';
import './assets/css/AnttendeeView.css';
class AttendeeView extends React.Component {
constructor(props) {
super(props);
this.state = {
workshop: null,
activeStep: 0,
status: 'WORKING',
mode: 'PRESENT'
};
}
componentWillReceiveProps(nextProps) {
if (!isEmpty(nextProps.workshop)) {
const { match: { params: { organizerId, workshopId, attendeeId } } } = nextProps;
const workshop = nextProps.workshop.organizers[organizerId].workshops[workshopId];
const attendee = workshop.attendee[attendeeId];
this.setState({
workshop,
attendee,
activeStep: attendee.step,
status: attendee.status
});
}
}
onClick = () => {
const { activeStep, status, workshop } = this.state;
const { firebase, match: { params: { organizerId, workshopId, attendeeId } } } = this.props;
if (status === 'WORKING') {
this.setState({
status: 'COMPLETE'
}, () => {
firebase.set(`organizers/${organizerId}/workshops/${workshopId}/attendee/${attendeeId}/status`, 'COMPLETE');
});
} else if (status === 'COMPLETE') {
if (activeStep + 1 === workshop.steps.length) return;
this.setState({
activeStep: activeStep + 1,
status: activeStep + 1 > workshop.step ? 'ROCKET' : 'WORKING'
}, () => {
firebase.set(`organizers/${organizerId}/workshops/${workshopId}/attendee/${attendeeId}/step`, activeStep + 1);
firebase.set(`organizers/${organizerId}/workshops/${workshopId}/attendee/${attendeeId}/status`, 'WORKING');
});
}
}
goBack = () => {
const { activeStep } = this.state;
this.setState({
activeStep: activeStep > 0 ? activeStep - 1 : 0,
});
}
goFoward = () => {
const { activeStep, workshop: { steps } } = this.state;
this.setState({
activeStep: activeStep < steps.length - 1 ? activeStep + 1 : activeStep,
});
}
render() {
const { workshop, status, activeStep } = this.state;
if (isEmpty(workshop)) return <div></div>;
return (
<div className="presentation">
<div className="presentation-header">{workshop.title}</div>
<div className="presentation-toolbar">
<div className="back" onClick={this.goBack}>
<Icon size={18} icon={ic_keyboard_arrow_left} />
</div>
<div className="current-step">{ activeStep + 1 } of { workshop.steps.length }</div>
<div className="back" onClick={this.goFoward}>
<Icon size={18} icon={ic_keyboard_arrow_right} />
</div>
<div className={`action-attendee ${status.toLowerCase()}`} onClick={this.onClick}>{status === 'WORKING' ? 'Complete' : 'Next Step'}</div>
</div>
<Step step={workshop.steps[activeStep]} />
</div>
);
}
}
const wrapped = firebaseConnect(({ match: { params }}) => ([
`/organizers/${params.organizerId}/workshops/${params.workshopId}`
]))(AttendeeView);
export default connect(
({ firebase: { data }}) => ({ workshop: !isEmpty(data) && data })
)(wrapped); |
src/chat/attachments/PhotoLibrary.js | elarasu/roverz-chat | import React from 'react';
import {
StyleSheet,
Text,
TouchableOpacity,
View,
Modal,
KeyboardAvoidingView,
TextInput,
Platform,
Image,
} from 'react-native';
import PropTypes from 'prop-types';
import { Icon } from 'react-native-elements';
import CameraRollPicker from 'react-native-camera-roll-picker';
import { isIphoneX } from 'react-native-iphone-x-helper';
import { Actions } from 'react-native-router-flux';
import NavBar, {
NavButton,
NavButtonText,
NavTitle,
} from 'react-native-nav';
import { AppColors } from '../../theme/';
import ImageUtil from './ImageUtil';
import t from '../../i18n';
const styles = StyleSheet.create({
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
},
overlay: {
position: 'absolute',
padding: 16,
right: 0,
left: 0,
alignItems: 'center',
},
captureButton: {
padding: 15,
backgroundColor: 'white',
borderRadius: 40,
},
messageContainer: {
flex: 1,
flexDirection: 'row',
marginBottom: (Platform.OS === 'ios') ? 16 : 0,
},
textInput: {
backgroundColor: '#F5F5F5',
borderRadius: 3,
padding: 5,
marginRight: 8,
height: 40,
flex: 1,
fontSize: 16,
fontFamily: 'OpenSans-Regular',
},
sendButton: {
height: 40,
width: 40,
},
buttonsSpace: {
width: 30,
},
});
export default class PhotoLibrary extends React.Component {
constructor(props) {
super(props);
this._images = [];
const groupId = this.props.groupId;
this.state = {
groupId,
modalPreviewVisible: false,
imageData: {},
imageMessage: '',
};
this.selectImages = this.selectImages.bind(this);
}
setImages(images) {
this._images = images;
}
getImages() {
return this._images;
}
setPreviewModalVisible(visible = false) {
this.setState({ modalPreviewVisible: visible });
}
selectImages(images) {
this.setImages(images);
}
selectPictureForPreview = (data) => {
this.setState({
imageData: data,
previewImageUri: data.path,
modalPreviewVisible: true,
});
const images = this.getImages().map(image => ({
image: image.uri,
}));
this.props.onSend(images);
this.setImages([]);
this.setPreviewModalVisible(true);
}
sendImageMessages() {
const images = this.getImages().map(image => ({
image: image.uri,
}));
if (images && images.length > 0) {
if (images.length === 1) {
const data = { path: images[0].image };
this.selectPictureForPreview(data);
} else {
for (let i = 0; i < images.length; i += 1) {
const data = { path: images[i].image };
const _progressCallback = this.props.progressCallback;
new ImageUtil().uploadImage(data, this.state.groupId, true, this.state.imageMessage,
(fuFileName, fuPercent, fuMsg) => {
// console.log(fuFileName, ':', fuPercent, ':', fuMsg);
const fileNameCount = fuFileName;
const percentage = Math.round(Number(parseFloat(fuPercent).toFixed(2) * 100));
if (_progressCallback) {
_progressCallback(fileNameCount, fuMsg, percentage, images.length, i);
}
});
}
this.props.onSend(images);
this.setImages([]);
Actions.pop();
}
}
}
sendLibraryImage() {
const _progressCallback = this.props.progressCallback;
new ImageUtil().uploadImage(this.state.imageData, this.state.groupId, true, this.state.imageMessage,
(fuFileName, fuPercent, fuMsg) => {
// console.log(fuFileName, ':', fuPercent, ':', fuMsg);
const percentage = Math.round(Number(parseFloat(fuPercent).toFixed(2) * 100));
if (_progressCallback) {
_progressCallback(fuFileName, fuMsg, percentage, 1, 0);
}
});
this.setState({
imageData: {},
imageMessage: '',
});
Actions.pop();
}
renderNavBar() {
return (
<NavBar style={{
statusBar: {
backgroundColor: '#FFF',
},
navBar: {
backgroundColor: '#FFF',
marginTop: isIphoneX() ? 25 : null,
},
}}
>
<NavButton onPress={() => {
this.setState({ imageData: {} });
Actions.pop({ duration: 0 });
}}
>
<NavButtonText style={{
color: '#000',
}}
>
{t('lbl_nav_cancel')}
</NavButtonText>
</NavButton>
<NavTitle style={{
color: '#000',
}}
>
{t('lbl_nav_camera_roll')}
</NavTitle>
<NavButton onPress={() => {
this.sendImageMessages();
}}
>
<NavButtonText style={{
color: '#000',
}}
>
{t('lbl_nav_send')}
</NavButtonText>
</NavButton>
</NavBar>
);
}
renderPreview() {
return (
<Modal
animationType={'none'}
transparent={false}
visible={this.state.modalPreviewVisible}
onRequestClose={() => {
this.setPreviewModalVisible(false);
}}
>
<Image
style={styles.preview}
source={{ uri: this.state.previewImageUri }}
/>
<KeyboardAvoidingView
behavior={(Platform.OS === 'ios') ? 'padding' : 'height'}
style={[styles.overlay, {
bottom: 0,
backgroundColor: 'rgba(0,0,0,0.4)',
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
}]}
>
<View
style={styles.messageContainer}
>
<TextInput
placeholder={t('ph_image_caption')}
style={[styles.textInput]}
onChangeText={(text) => { this.setState({ imageMessage: text }); }}
value={this.state.imageMessage}
underlineColorAndroid={'transparent'}
/>
<TouchableOpacity
style={[styles.sendButton]}
onPress={() => {
this.setPreviewModalVisible(false);
this.sendLibraryImage();
}}
>
<Icon
name="send"
size={34}
color={AppColors.brand().third}
/>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
<TouchableOpacity
style={[styles.captureButton, {
position: 'absolute',
top: isIphoneX() ? 40 : 20,
left: 20,
}]}
onPress={() => {
this.setPreviewModalVisible(false);
this.setState({ imageData: {} });
}}
>
<Icon
name="arrow-back"
size={20}
color="#000"
width={20}
/>
</TouchableOpacity>
</Modal>
);
}
render() {
return (
<View
style={{
flex: 1,
}}
>
{this.renderPreview()}
{this.renderNavBar()}
<CameraRollPicker
maximum={10}
assetType={'All'}
pageSize={2}
imagesPerRow={3}
callback={this.selectImages}
selected={[]}
selectedMarker={
<View
style={{
height: '100%',
backgroundColor: 'rgba(0,0,0,0.3)',
width: '100%',
position: 'absolute',
justifyContent: 'center',
alignItems: 'center',
zIndex: 200,
}}
>
<Icon
name="done"
type="MaterialIcons"
size={45}
color={'#fff'}
/>
</View>
}
/>
</View>
);
}
}
PhotoLibrary.defaultProps = {
onSend: () => {},
containerStyle: {},
textStyle: {},
groupId: null,
progressCallback: () => {},
};
PhotoLibrary.propTypes = {
onSend: React.PropTypes.func,
containerStyle: View.propTypes.style,
textStyle: Text.propTypes.style,
groupId: PropTypes.string,
progressCallback: PropTypes.func,
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.