path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
example/App/VariableHeight.js | nkbt/react-collapse | import React from 'react';
import {Collapse} from '../../src';
export class VariableHeight extends React.PureComponent {
constructor(props) {
super(props);
this.state = {isOpened: false, height: 100};
}
render() {
const {isOpened, height} = this.state;
return (
<div {...this.props}>
<div className="config">
<label className="label">
Opened:
<input
className="input"
type="checkbox"
checked={isOpened}
onChange={({target: {checked}}) => this.setState({isOpened: checked})} />
</label>
<label className="label">
Content height:
<input
className="input"
type="range"
value={height}
step={50}
min={0}
max={500}
onChange={({target: {value}}) => this.setState({height: parseInt(value, 10)})} />
{height}
</label>
</div>
<Collapse isOpened={isOpened}>
<div style={{height}} className="blob" />
</Collapse>
</div>
);
}
}
|
stories/examples/CardImageCaps.js | reactstrap/reactstrap | import React from 'react';
import { Card, CardBody, Button, CardTitle, CardText, CardImg } from 'reactstrap';
const Example = (props) => {
return (
<div>
<Card>
<CardImg top width="100%" src="https://picsum.photos/318/180" alt="Card image cap" />
<CardBody>
<CardTitle tag="h5">Card Title</CardTitle>
<CardText>This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</CardText>
<CardText>
<small className="text-muted">Last updated 3 mins ago</small>
</CardText>
</CardBody>
</Card>
<Card>
<CardBody>
<CardTitle tag="h5">Card Title</CardTitle>
<CardText>This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</CardText>
<CardText>
<small className="text-muted">Last updated 3 mins ago</small>
</CardText>
</CardBody>
<CardImg bottom width="100%" src="https://picsum.photos/318/180" alt="Card image cap" />
</Card>
</div>
);
};
export default Example;
|
src/esm/components/structure/cards/summary-card/components/title-tag.js | KissKissBankBank/kitten | import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["text", "icon", "className"];
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Tag } from '../../../../information/tag';
import { LockIcon } from '../../../../graphics/icons/lock-icon';
import { StarIcon } from '../../../../graphics/icons/star-icon';
export var TitleTag = function TitleTag(_ref) {
var text = _ref.text,
icon = _ref.icon,
className = _ref.className,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
var iconDisplay = function () {
switch (icon) {
case 'lock':
return /*#__PURE__*/React.createElement(LockIcon, {
width: "14",
height: "14"
});
case 'star':
default:
return /*#__PURE__*/React.createElement(StarIcon, {
width: "14",
height: "13"
});
}
}();
return /*#__PURE__*/React.createElement(Tag, _extends({
className: classNames('k-SummaryCard__titleTag', className, 'k-u-margin-top-single')
}, props), iconDisplay, /*#__PURE__*/React.createElement("span", null, text));
};
TitleTag.propTypes = {
icon: PropTypes.oneOf(['star', 'lock']),
text: PropTypes.node
};
TitleTag.defaultProps = {
icon: 'star',
text: null
}; |
src/compontent/summary.js | PangPangPangPangPang/react-blog | /**
* Created by wangyefeng on 03/03/2017.
*/
import React from 'react'
import { hashHistory } from 'react-router'
import './summary.css'
const Summary = (props) => {
const clickDetail = () => {
hashHistory.push(`list/${props.id}`)
}
const renderTag = () => {
const arr = []
for (let i = 0; i < props.tags.length; i += 1) {
arr.push(
<div key={`${i}`} className="summary-tag">
{props.tags[i]}
</div>)
}
return arr
}
return (
<div className="summary-card" onClick={clickDetail}>
{props.name}
<hr className="summary-seperate" />
<div className="summary-tags">
{renderTag()}
</div>
</div>
)
}
Summary.propTypes = {
name: React.PropTypes.string,
tags: React.PropTypes.array,
}
Summary.defaultProps = {
name: '',
tags: [],
}
export default Summary
|
src/parser/paladin/holy/modules/azeritetraits/RadiantIncandescence.js | fyruna/WoWAnalyzer | import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import { formatNumber, formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS/index';
import TraitStatisticBox, { STATISTIC_ORDER } from 'interface/others/TraitStatisticBox';
import ItemHealingDone from 'interface/others/ItemHealingDone';
import Events from 'parser/core/Events';
import BeaconHealSource from '../beacons/BeaconHealSource.js';
/**
* Radiant Incandescence
* Your Holy Shock criticals deal an additional 1725 damage, or an additional 2715 healing, over 3 sec.
* Example Log: https://www.warcraftlogs.com/reports/vGfw7dYhM1m6n3J4#fight=8&type=healing&source=13&ability=278147&view=events
*/
class RadiantIncandescence extends Analyzer {
static dependencies = {
beaconHealSource: BeaconHealSource,
};
healing = 0;
healingTransfered = 0;
casts = 0;
crits = 0;
damage = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTrait(SPELLS.RADIANT_INCANDESCENCE_TRAIT.id);
if (!this.active) {
return;
}
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.HOLY_SHOCK_CAST), this.onCast);
this.addEventListener(Events.applybuff.by(SELECTED_PLAYER).spell(SPELLS.RADIANT_INCANDESCENCE), this.onCrit);
this.addEventListener(Events.applydebuff.by(SELECTED_PLAYER).spell(SPELLS.RADIANT_INCANDESCENCE_DAMAGE), this.onCrit);
this.addEventListener(Events.heal.by(SELECTED_PLAYER).spell(SPELLS.RADIANT_INCANDESCENCE), this.onHeal);
this.addEventListener(this.beaconHealSource.beacontransfer.by(SELECTED_PLAYER), this.onBeaconTransfer);
this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(SPELLS.RADIANT_INCANDESCENCE_DAMAGE), this.onDamage);
}
onCast(event) {
this.casts += 1;
}
onCrit(event){
this.crits += 1;
}
onHeal(event) {
this.healing += event.amount + (event.absorbed || 0);
this.targetsHit += 1;
}
onBeaconTransfer(event) {
const spellId = event.originalHeal.ability.guid;
if (spellId !== SPELLS.RADIANT_INCANDESCENCE.id) {
return;
}
this.healingTransfered += event.amount + (event.absorbed || 0);
}
onDamage(event){
this.damage += event.amount + (event.absorbed || 0);
}
get critRate() {
return (this.crits / this.casts) || 0;
}
get totalHealing() {
return this.healing + this.healingTransfered;
}
statistic() {
return (
<TraitStatisticBox
position={STATISTIC_ORDER.OPTIONAL()}
trait={SPELLS.RADIANT_INCANDESCENCE.id}
value={(
<>
<ItemHealingDone amount={this.totalHealing} /><br />
{formatPercentage(this.critRate)}% Crit Rate
</>
)}
tooltip={(
<>
Damage Done: <b>{formatNumber(this.damage)}</b><br />
Beacon healing transfered: <b>{formatNumber(this.healingTransfered)}</b><br />
</>
)}
/>
);
}
}
export default RadiantIncandescence; |
src/svg-icons/communication/stop-screen-share.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationStopScreenShare = (props) => (
<SvgIcon {...props}>
<path d="M21.22 18.02l2 2H24v-2h-2.78zm.77-2l.01-10c0-1.11-.9-2-2-2H7.22l5.23 5.23c.18-.04.36-.07.55-.1V7.02l4 3.73-1.58 1.47 5.54 5.54c.61-.33 1.03-.99 1.03-1.74zM2.39 1.73L1.11 3l1.54 1.54c-.4.36-.65.89-.65 1.48v10c0 1.1.89 2 2 2H0v2h18.13l2.71 2.71 1.27-1.27L2.39 1.73zM7 15.02c.31-1.48.92-2.95 2.07-4.06l1.59 1.59c-1.54.38-2.7 1.18-3.66 2.47z"/>
</SvgIcon>
);
CommunicationStopScreenShare = pure(CommunicationStopScreenShare);
CommunicationStopScreenShare.displayName = 'CommunicationStopScreenShare';
CommunicationStopScreenShare.muiName = 'SvgIcon';
export default CommunicationStopScreenShare;
|
src/components/Account/Courses/CourseList/index.js | ndlib/usurper | import React from 'react'
import PropTypes from 'prop-types'
import CourseCard from './CourseCard'
import styles from './style.module.css'
const CourseList = (props) => {
if (!props.courses || !props.courses.length) {
return null
}
return (
<div className={styles.courseSection}>
<h3 className={styles.courseSectionTitle}>{props.title}</h3>
<div className={[styles.courseCard, styles.courseHeader].join(' ')}>
<div>Course</div>
<div>Course Reserves</div>
<div>Subject Resources</div>
</div>
{props.courses.map((row) =>
<CourseCard key={row.id} course={row} />,
)}
</div>
)
}
CourseList.propTypes = {
courses: PropTypes.array,
title: PropTypes.string,
}
export default CourseList
|
docs/app/Examples/views/Comment/Variations/CommentExampleMinimal.js | koenvg/Semantic-UI-React | import React from 'react'
import { Button, Comment, Form, Header } from 'semantic-ui-react'
const CommentExampleMinimal = () => (
<Comment.Group minimal>
<Header as='h3' dividing>Comments</Header>
<Comment>
<Comment.Avatar as='a' src='http://semantic-ui.com/images/avatar/small/matt.jpg' />
<Comment.Content>
<Comment.Author as='a'>Matt</Comment.Author>
<Comment.Metadata>
<span>Today at 5:42PM</span>
</Comment.Metadata>
<Comment.Text>How artistic!</Comment.Text>
<Comment.Actions>
<a>Reply</a>
</Comment.Actions>
</Comment.Content>
</Comment>
<Comment>
<Comment.Avatar as='a' src='http://semantic-ui.com/images/avatar/small/elliot.jpg' />
<Comment.Content>
<Comment.Author as='a'>Elliot Fu</Comment.Author>
<Comment.Metadata>
<span>Yesterday at 12:30AM</span>
</Comment.Metadata>
<Comment.Text>
<p>This has been very useful for my research. Thanks as well!</p>
</Comment.Text>
<Comment.Actions>
<a>Reply</a>
</Comment.Actions>
</Comment.Content>
<Comment.Group>
<Comment>
<Comment.Avatar as='a' src='http://semantic-ui.com/images/avatar/small/jenny.jpg' />
<Comment.Content>
<Comment.Author as='a'>Jenny Hess</Comment.Author>
<Comment.Metadata>
<span>Just now</span>
</Comment.Metadata>
<Comment.Text>Elliot you are always so right :)</Comment.Text>
<Comment.Actions>
<a>Reply</a>
</Comment.Actions>
</Comment.Content>
</Comment>
</Comment.Group>
</Comment>
<Comment>
<Comment.Avatar as='a' src='http://semantic-ui.com/images/avatar/small/joe.jpg' />
<Comment.Content>
<Comment.Author as='a'>Joe Henderson</Comment.Author>
<Comment.Metadata>
<span>5 days ago</span>
</Comment.Metadata>
<Comment.Text>Dude, this is awesome. Thanks so much</Comment.Text>
<Comment.Actions>
<a>Reply</a>
</Comment.Actions>
</Comment.Content>
</Comment>
<Form reply onSubmit={e => e.preventDefault()}>
<Form.TextArea />
<Button content='Add Reply' labelPosition='left' icon='edit' primary />
</Form>
</Comment.Group>
)
export default CommentExampleMinimal
|
client/admin/server.js | kirinami/portfolio | // Import dependencies
import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter, Route } from 'react-router-dom';
import { Provider } from 'mobx-react';
// Export markup
/* eslint-disable global-require */
module.exports = (initialStates, url) => {
// define initial states
global.initialStates = initialStates;
// delete cache for stores
delete require.cache[require.resolve('./stores')];
// define context and markup
const context = {};
const markup = renderToString(
<Provider {...require('./stores')}>
<StaticRouter basename="/admin" location={url} context={context}>
<Route component={require('./scenes').default}/>
</StaticRouter>
</Provider>,
);
// return render
return {
context,
markup,
};
};
|
src/svg-icons/image/collections.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCollections = (props) => (
<SvgIcon {...props}>
<path d="M22 16V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2zm-11-4l2.03 2.71L16 11l4 5H8l3-4zM2 6v14c0 1.1.9 2 2 2h14v-2H4V6H2z"/>
</SvgIcon>
);
ImageCollections = pure(ImageCollections);
ImageCollections.displayName = 'ImageCollections';
ImageCollections.muiName = 'SvgIcon';
export default ImageCollections;
|
examples/self_mounting_components/mount.js | abdelouahabb/python-react | import React from 'react';
// During the build process webpack aliases this import to the desired component
import Component from '__react_mount_component__';
// During the build process webpack will replace these variable with
// the names passed from the python process
const props = __react_mount_props_variable__;
const container = document.getElementById(__react_mount_container__);
const element = React.createElement(Component, props);
React.render(element, container); |
react-flux-mui/js/material-ui/src/svg-icons/maps/streetview.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsStreetview = (props) => (
<SvgIcon {...props}>
<path d="M12.56 14.33c-.34.27-.56.7-.56 1.17V21h7c1.1 0 2-.9 2-2v-5.98c-.94-.33-1.95-.52-3-.52-2.03 0-3.93.7-5.44 1.83z"/><circle cx="18" cy="6" r="5"/><path d="M11.5 6c0-1.08.27-2.1.74-3H5c-1.1 0-2 .9-2 2v14c0 .55.23 1.05.59 1.41l9.82-9.82C12.23 9.42 11.5 7.8 11.5 6z"/>
</SvgIcon>
);
MapsStreetview = pure(MapsStreetview);
MapsStreetview.displayName = 'MapsStreetview';
MapsStreetview.muiName = 'SvgIcon';
export default MapsStreetview;
|
src/components/PhotoList.js | edwinwright/react-project | import React from 'react';
import PhotoThumb from './PhotoThumb';
const PhotoList = ({ photos }) => (
<div>
<h1>PhotoList</h1>
<ul>
{photos.map(photo => (
<li key={photo.id}>
<PhotoThumb photo={photo} />
</li>
))}
</ul>
</div>
);
// TODO: Add propTypes
// TODO: Does PhotoThumb need {...this.props} ??
export default PhotoList
|
app/components/Files.js | christianalfoni/TeachKidsCode | import React from 'react';
import {Mixin} from 'cerebral-react-immutable-store';
import MTRC from 'markdown-to-react-components';
import {
Row,
Col,
ListGroup,
ListGroupItem,
Button
} from 'react-bootstrap';
var Files = React.createClass({
mixins: [Mixin],
getStatePaths() {
return {
files: ['files'],
currentFileIndex: ['currentFileIndex'],
isLoadingFiles: ['isLoadingFiles']
};
},
renderFile(file, index) {
return (
<ListGroupItem key={index} href="#" active={index === this.state.currentFileIndex} onClick={() => this.signals.currentFileChanged({
currentFileIndex: index
})}>{file.name}</ListGroupItem>
);
},
render() {
if (this.state.isLoadingFiles) {
return (
<h4>Loading files...</h4>
);
}
return (
<Row>
<Col md={4}>
<ListGroup>
{this.state.files.map(this.renderFile)}
</ListGroup>
</Col>
<Col md={8}>
<div><Button bsStyle="primary" onClick={() => this.signals.editCurrentFileClicked()}>Edit</Button></div>
{this.state.files.length ? MTRC(this.state.files[this.state.currentFileIndex].content).tree : null}
</Col>
</Row>
);
}
});
export default Files;
|
generators/js-framework/modules/react/components/Account/Reset.js | sahat/boilerplate | import React from 'react';
import { connect } from 'react-redux'
import { resetPassword } from '../../actions/auth';
import Messages from '../Messages';
class Reset extends React.Component {
constructor(props) {
super(props);
this.state = { password: '', confirm: '' };
}
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
handleReset(event) {
event.preventDefault();
this.props.dispatch(resetPassword(this.state.password, this.state.confirm, this.props.params.token));
}
render() {
return (
//= RESET_RENDER_INDENT3
);
}
}
const mapStateToProps = (state) => {
return state;
};
export default connect(mapStateToProps)(Reset);
|
src/components/SignIn/index.js | Apozhidaev/ergonode | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { signIn } from 'store/app/actions';
import { Link } from 'react-router-dom';
import 'github-fork-ribbon-css/gh-fork-ribbon.css';
import './styles.css';
import ProgressBar from '../ProgressBar';
class SignIn extends Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(e) {
const { onSignIn } = this.props;
e.preventDefault();
if (!this.userName.value.trim() || !this.password.value.trim()) {
return;
}
onSignIn({
name: this.userName.value,
password: this.password.value,
});
}
render() {
const { authorization, errors } = this.props;
const errorViews = errors.map(err => (
<div key={err} className="alert alert-dismissible alert-danger">
{err}
</div>
));
return (
<div>
<a
className="github-fork-ribbon right-bottom fixed"
href="https://github.com/Apozhidaev/terminal"
title="Fork me on GitHub"
target="_blank"
rel="noopener noreferrer"
>
Fork me on GitHub
</a>
<h2 className="mx-3 my-2">
<Link className="logo-header text-primary" to="/">The Terminal</Link>
</h2>
<div className="container mt-4 mt-lg-5">
<form onSubmit={this.onSubmit}>
<div className="form-group row">
<label htmlFor="user" className="col-sm-3 col-md-2 col-form-label">user name</label>
<div className="col-sm-8">
<input
type="text"
className="form-control"
id="user"
placeholder="user name"
ref={(node) => { this.userName = node; }}
/>
</div>
</div>
<div className="form-group row">
<label htmlFor="password" className="col-sm-3 col-md-2 col-form-label">
password
</label>
<div className="col-sm-8">
<input
type="password"
className="form-control"
id="password"
placeholder="password"
ref={(node) => { this.password = node; }}
/>
</div>
</div>
<div className="form-group row">
<div className="offset-sm-3 offset-md-2 col-sm-8">
<div className="row">
<div className="col-4">
<button type="submit" className="btn btn-primary">sign in</button>
</div>
<div className="col-5">
<ProgressBar className="my-3" progress={authorization} />
</div>
</div>
</div>
</div>
</form>
{errorViews}
</div>
</div>
);
}
}
const mapStateToProps = state => ({
authorization: state.services.sso.profileFetching,
profile: state.app.context.profile,
errors: state.app.context.errors,
});
const mapDispatchToProps = ({
onSignIn: signIn,
});
export default connect(mapStateToProps, mapDispatchToProps)(SignIn);
|
src/modules/todo/components/TodoList.js | scubism/react_todo_web | import React from 'react';
import { provideHooks } from 'redial';
import { connect } from 'react-redux';
import { Link } from 'react-router'
import autobind from 'autobind-decorator'
import Loader from 'react-loaders'
import { listTodos, createTodo, updateTodo, deleteTodo, moveTodo } from '../actions';
import { TodoInlineCreateForm } from './TodoInlineForm'
import TodoListItem from './TodoListItem';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
@provideHooks({
fetch: ({ dispatch }) => dispatch(listTodos({reject: (e) => {alert(e);}}))
})
@connect((state) => {
return {
todos: state.todo.todos,
fetchState: state.todo.fetchState,
focusedTodo: state.todo.focusedTodo,
};
})
@DragDropContext(HTML5Backend)
@autobind
export default class TodoList extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {stagedTodos: null}
}
componentWillReceiveProps(nextProps) {
if (this.props.todos !== nextProps.todos) {
this.state = Object.assign({}, this.state, {stagedTodos: nextProps.todos});
}
}
_beginDrag(dragIndex) {
this.setState({stagedTodos: this.props.todos});
}
_moveItem(dragIndex, hoverIndex) {
let todos = this.state.stagedTodos || this.props.todos;
let converted = [];
let isMoveUp = true;
todos.forEach((todo, index) => {
if (index == dragIndex) {
isMoveUp = false;
} else if (index == hoverIndex) {
if (isMoveUp) {
converted.push(todos[dragIndex]);
converted.push(todos[hoverIndex]);
} else {
converted.push(todos[hoverIndex]);
converted.push(todos[dragIndex]);
}
} else {
converted.push(todo);
}
})
this.setState({stagedTodos: converted});
}
_dropItem(dragIndex) {
let todos = this.state.stagedTodos;
this.props.dispatch(moveTodo(todos[dragIndex], todos, {
reject: ((e) => { alert(e); this.setState({stagedTodos: null});}),
}));
}
_dropCanceled(dragIndex) {
this.setState({stagedTodos: null});
}
render() {
const { todos, fetchState, focusedTodo, dispatch } = this.props;
let stagedTodos = this.state.stagedTodos || todos;
const _beginDrag = this._beginDrag;
const _dropCanceled = this._dropCanceled;
const _moveItem = this._moveItem;
const _dropItem = this._dropItem;
return (
<div className="todo-list">
<div key="loader"
style={{display: (
fetchState[listTodos].fetching ||
fetchState[createTodo].fetching ||
fetchState[updateTodo].fetching ||
fetchState[deleteTodo].fetching
) ? 'block' : 'none'}}
className="loader"
>
<Loader type="line-scale" active="true"/>
</div>
<TodoInlineCreateForm key="create-form" />
<ul key="items" className="todo-list-items">
{stagedTodos.map((todo, index) => {
return (
<TodoListItem
key={todo.id}
index={index}
todo={todo}
dispatch={dispatch}
beginDrag={_beginDrag}
dropCanceled={_dropCanceled}
moveItem={_moveItem}
dropItem={_dropItem}
editing={focusedTodo && focusedTodo.id == todo.id}
/>
);
})}
</ul>
</div>
);
}
}
|
src/RootComponent.js | jerryshew/react-uikits | import React, { Component } from 'react';
import { HashRouter as Router, Route, NavLink, Switch } from 'react-router-dom';
import { version } from '../package.json';
import {
BasicPage, ButtonPage,
CalendarPage, CarouselPage, CheckBoxPage, CheckBoxGroupPage, ConfirmBoxPage, CardPage, CommentPage, CrumbPage,
DatePickerPage, DateTimePickerPage, DropDownPage,
FormPage,
GridPage,
IconPage, ImagePage, InputPage, ItemPage, InstallPage, InputNumberPage,
LabelPage, LoaderPage, ListPage,
MenuPage, ModalPage,
NoticePage,
OtherPage,
PaginationPage, PinPage, PanelPage, ProgressPage,
RadioPage, RadioGroupPage,
SlideMenuPage, StartPage,
ToastPage, TabPage, TimeInputPage, TimePickerPage, TooltipPage, TablePage, TextPage, TempPage, ThemePage,
ValidatorPage,
} from './page';
import {CN} from './util/tools';
import {NAV_MAP} from './constant';
const NAV_MAP_KEYS = Object.keys(NAV_MAP)
const asideLinks = () => {
return NAV_MAP_KEYS.map(key => {
return (
<div className="group" key={key}>
<h4>{key}</h4>
{NAV_MAP[key].map(item => {
return (
<span key={item.route}>
{item.route === '/component' ?
<NavLink exact to="/component">{item.name}</NavLink>
: <NavLink to={item.route}>{item.name}</NavLink>}
</span>
)
})}
</div>
)
})
}
const Header = props => {
return (
<header className={CN('basic block main-nav')}>
<div className={CN('container')}>
<div className={CN('basic table')}>
<div className="row">
<div className="cell">
<h2><NavLink to="/">React UIKits</NavLink></h2>
</div>
<div className="text-right cell">
<NavLink exact className="link" to="/">首页</NavLink>
<NavLink className="link" to="/component">组件</NavLink>
</div>
</div>
</div>
</div>
</header>
);
}
const Footer = props => {
return (
<footer className="main-footer">
<div className={CN('container')}>
<div className={CN('basic table')}>
<div className="row">
<div className="cell">
<h4>{`React UIKits@${version}`}</h4>
</div>
<div className="text-right cell">
<a href="https://github.com/jerryshew/react-uikits" target="_blank">Github</a>
<a href="http://braavos.me" target="_blank">Blog</a>
<a href="https://github.com/wecatch" target="_blank">team</a>
</div>
</div>
</div>
</div>
</footer>
);
}
const RootPage = props => {
return (
<div className={CN('root-page fluid table absolute-center')}>
<div className="row">
<div className="cell">
<h1 className={CN('field')}>
React UIkits
</h1>
<p className={CN('field')}>基于 React.js 快速搭建企业平台的组件化方案</p>
<NavLink to="/component" className={CN('red button')}>更多...</NavLink>
</div>
</div>
</div>
);
}
const ContentPage = props => {
return (
<div className={CN('container grid main-page')}>
<aside className={CN('column-3 main-aside')}>
{asideLinks()}
</aside>
<article className="column column-13 main-content">
<Route exact path="/component" component={BasicPage}></Route>
<Route path="/start" component={StartPage}></Route>
<Route path="/theme" component={ThemePage}></Route>
<Route path="/install" component={InstallPage}></Route>
<Route path="/component/button" component={ButtonPage}></Route>
<Route path="/component/calendar" component={CalendarPage}></Route>
<Route path="/component/carousel" component={CarouselPage}></Route>
<Route path="/component/checkbox" component={CheckBoxPage}></Route>
<Route path="/component/checkboxgroup" component={CheckBoxGroupPage}></Route>
<Route path="/component/comment" component={CommentPage}></Route>
<Route path="/component/confirmbox" component={ConfirmBoxPage}></Route>
<Route path="/component/datepicker" component={DatePickerPage}></Route>
<Route path="/component/datetimepicker" component={DateTimePickerPage}></Route>
<Route path="/component/dropdown" component={DropDownPage}></Route>
<Route path="/component/form" component={FormPage}></Route>
<Route path="/component/validator" component={ValidatorPage}></Route>
<Route path="/component/grid" component={GridPage}></Route>
<Route path="/component/menu" component={MenuPage}></Route>
<Route path="/component/toast" component={ToastPage}></Route>
<Route path="/component/modal" component={ModalPage}></Route>
<Route path="/component/notice" component={NoticePage}></Route>
<Route path="/component/pagination" component={PaginationPage}></Route>
<Route path="/component/pin" component={PinPage}></Route>
<Route path="/component/panel" component={PanelPage}></Route>
<Route path="/component/progress" component={ProgressPage}></Route>
<Route path="/component/radio" component={RadioPage}></Route>
<Route path="/component/radiogroup" component={RadioGroupPage}></Route>
<Route path="/component/slidemenu" component={SlideMenuPage}></Route>
<Route path="/component/tab" component={TabPage}></Route>
<Route path="/component/timeinput" component={TimeInputPage}></Route>
<Route path="/component/timepicker" component={TimePickerPage}></Route>
<Route path="/component/tooltip" component={TooltipPage}></Route>
<Route path="/component/card" component={CardPage}></Route>
<Route path="/component/crumb" component={CrumbPage}></Route>
<Route path="/component/icon" component={IconPage}></Route>
<Route path="/component/image" component={ImagePage}></Route>
<Route path="/component/input" component={InputPage}></Route>
<Route path="/component/item" component={ItemPage}></Route>
<Route path="/component/label" component={LabelPage}></Route>
<Route path="/component/loader" component={LoaderPage}></Route>
<Route path="/component/other" component={OtherPage}></Route>
<Route path="/component/table" component={TablePage}></Route>
<Route path="/component/text" component={TextPage}></Route>
<Route path="/component/list" component={ListPage}></Route>
<Route path="/component/input-number" component={InputNumberPage}></Route>
<Route path="/temp" component={TempPage}></Route>
</article>
</div>
)
}
const BaseComponent = () => {
return (
<Router>
<article>
<Header/>
<Switch>
<Route exact path="/" component={RootPage}></Route>
<Route path="/component" component={ContentPage}></Route>
<Route path="/start" component={ContentPage}></Route>
<Route path="/theme" component={ContentPage}></Route>
<Route path="/install" component={ContentPage}></Route>
<Route path="/temp" component={ContentPage}></Route>
<Route component={RootPage}></Route>
</Switch>
<Footer/>
</article>
</Router>
)
}
export default BaseComponent |
cloudapp/src/app/WaterChart.js | jbrichau/PoolBuddy | import React from 'react';
import { Badge } from 'reactstrap';
import { LineChart, XAxis, YAxis, Legend, Tooltip, CartesianGrid, Line, ReferenceLine } from 'recharts';
class CustomizedAxisTick extends React.Component {
render() {
const { x, y, stroke, payload } = this.props;
return (
<g transform={`translate(${x},${y})`}>
<text x={0} y={0} dy={16} textAnchor="end" fill="#666">{new Date(payload.value).toLocaleString('nl-BE')}</text>
</g>
);
}
};
function CustomizedTooltip(props) {
const { active } = props;
if (active) {
const { payload, label } = props;
return (
<div className="recharts-default-tooltip" style={{'margin': '0px', 'padding': '10px', 'backgroundColor': 'rgb(255, 255, 255)', 'border': '1px solid rgb(204, 204, 204)', 'whiteSpace': 'nowrap'}}>
<p className="recharts-tooltip-label" style={{'margin': '0px'}}>{new Date(label).toLocaleString('nl-BE')}</p>
<ul className="recharts-tooltip-item-list" style={{'padding': '0px', 'margin': '0px'}}>
<li className="recharts-tooltip-item" style={{'display': 'block', 'paddingTop': '4px', 'paddingBottom': '4px', 'color': payload[0].color}}>
<span className="recharts-tooltip-item-name">{payload[0].name}</span>
<span className="recharts-tooltip-item-separator"> : </span>
<span className="recharts-tooltip-item-value">{payload[0].value}</span>
<span className="recharts-tooltip-item-unit"></span>
</li>
</ul>
</div>
);
} else return null;
}
class WaterChart extends React.Component {
render() {
let minReferenceLine, maxReferenceLine;
const ticks = new Array();
if (this.props.minValue)
minReferenceLine = <ReferenceLine y={this.props.minValue} stroke="red" strokeDasharray="3 3" alwaysShow={true}/>;
if (this.props.maxValue)
maxReferenceLine = <ReferenceLine y={this.props.maxValue} stroke="red" strokeDasharray="3 3" alwaysShow={true}/>;
return (
<div>
<h2>{this.props.title} <Badge color="secondary">{this.props.data[this.props.data.length-1][this.props.dataKey].toFixed(2)} {this.props.unit}</Badge></h2>
<LineChart width={1000} height={200} data={this.props.data} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
<XAxis dataKey="timestamp" scale="utcTime" tick={<CustomizedAxisTick />} />
<YAxis />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip content={<CustomizedTooltip />} />
<Legend />
<Line type="monotone" dataKey={this.props.dataKey} stroke={this.props.stroke} strokeWidth="2" dot={false} activeDot={{ r: 8 }} />
{minReferenceLine}
{maxReferenceLine}
</LineChart>
</div>
);
}
}
export default WaterChart;
|
src/client/assets/javascripts/features/mapper/components/Mapper/Mapper.js | tlodge/uibuilder | import React, { Component } from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actionCreators as mapperActions, viewConstants, selector } from '../..';
import { actionCreators as shapeActions } from 'features/canvas/';
import { actionCreators as sourceActions } from 'features/sources';
import Schema from "../Schema";
import Attributes from "../Attributes";
import Transformer from "../Transformer";
import Properties from "../Properties";
import Birth from "../Birth";
import Death from "../Death";
import "./Mapper.scss";
import { Flex, Box } from 'reflexbox'
import '../../../../../styles/index.scss';
import {schemaLookup} from 'utils';
import Paper from 'react-md/lib/Papers';
import Card from 'react-md/lib/Cards/Card';
import CardTitle from 'react-md/lib/Cards/CardTitle';
import CardActions from 'react-md/lib/Cards/CardActions';
import CardText from 'react-md/lib/Cards/CardText';
const sourceName = (sources, sourceId)=>{
for (source in sources){
if (sourceId === source.id){
return source.name;
}
}
return sourceId;
}
const templateName = (templates, templateId)=>{
for (template in templates){
if (template.id === templateId){
return template.label;
}
}
return templateId;
}
const _shouldExpand = (path, selectedPath)=>{
if (!selectedPath){
return false;
}
return selectedPath.indexOf(path) != -1;
}
@connect(selector, (dispatch) => {
return {
actions: {
...bindActionCreators(mapperActions, dispatch),
...bindActionCreators(sourceActions, dispatch),
...bindActionCreators(shapeActions, dispatch)
}
}
})
export default class Mapper extends Component {
constructor(props){
super(props);
this.state = { activeTabIndex: 0, propertiesExpanded:false, objectsExpanded:false, mapperExpanded:false, mappingsExpanded:false, birthExpanded:false, deathExpanded:false};
this._handleTabChange = this._handleTabChange.bind(this);
this._toggleSelected = this._toggleSelected.bind(this);
}
renderSources() {
const {sources:{sources, selected}} = this.props;
const path = selected;
//const path = selected ? selected.path[0] : null;
const srcs = sources.map((source) =>{
return <Box key={source.id} onClick={this.props.actions.selectSource.bind(null, source.id)}>{source.name}</Box>
});
const schema = path != null ? <Schema {
...{
schema: sources.reduce((acc, source)=>{return (source.id === path) ? source.schema : acc;},{}),
onSelect: this.props.actions.mapFrom.bind(null, path)
}
}
/>: null;
return <Flex flexColumn={true}>
{srcs}
{schema}
</Flex>
}
renderTemplate(templateId, path, selectedPath){
const {canvas:{templatesById}} = this.props;
const template = templatesById[templateId];
return <div key={templateId}>
<li onClick={this._toggleSelected.bind(null, [...path, template.id], template.type, selectedPath)}>
{`${template.label} (${template.type})`}
</li>
{template.type === "group" && _shouldExpand(template.id,selectedPath) && this.renderTree(template.children, [...path, template.id], selectedPath)}
</div>
}
renderTree(templates, path, selectedPath){
return templates.map((id)=>{
return <ul key={id}>{this.renderTemplate(id, [...path], selectedPath)}</ul>;
});
}
renderObjects(){
const {canvas:{selected, templates}} = this.props;
const {path=null} = selected || [];
const tree = this.renderTree(templates, [], path);
return <Flex flexColumn={true}>
<Box>
{tree}
</Box>
</Flex>
}
renderComponents() {
const {canvas:{templatesById, selected}} = this.props;
const {path=null} = selected || [];
const [id, ...rest] = path;
const template = id ? templatesById[id] : null;
const attrs = id != null ? <Attributes {
...{
attributes: Object.keys(schemaLookup(template.type).attributes),
onSelect: this.props.actions.mapToAttribute.bind(null, path)
}
}
/> : null;
const style = id != null ? <Attributes {
...{
attributes: Object.keys(schemaLookup(template.type).style),
onSelect: this.props.actions.mapToStyle.bind(null,path)
}
}
/> : null;
const transforms = id != null ? <Attributes {
...{
attributes: ["rotate", "scale", "translate"],
onSelect: this.props.actions.mapToTransform.bind(null, path)
}
}
/> : null;
return <Flex flexColumn={true}>
{attrs}
{style}
{transforms}
</Flex>
}
renderMapper(){
const {canvas:{templatesById, selected:{path=null}}} = this.props;
if (!path || path.lnegth <= 0)
return null;
const template = templatesById[path[path.length-1]]
return <Box>
<div style={{paddingBottom:7, fontWeight:"bold"}}>{template.label}</div>
<Flex>
<Box col={6}>{this.renderSources()}</Box>
<Box col={6}>{this.renderComponents()}</Box>
</Flex>
</Box>
}
renderMappings(){
const {canvas:{templatesById}, sources:{sources}, mapper:{mappings}} = this.props;
return mappings.map((item,i)=>{
const sourceName = sources.reduce((acc,source)=>{
if (item.from.sourceId === source.id)
return source.name;
return acc;
},item.from.sourceId);
const [id, ...rest] = item.to.path;
const templateName = templatesById[id].label;
return <div onClick={this.props.actions.selectMapping.bind(null,item)} key={i}>{`${sourceName}:${item.from.key}`}->{`${templateName}:${item.to.property}`}</div>
})
}
renderBirthOptions(){
const {canvas:{selected:{path}}} = this.props;
return <Birth path={path}/>
}
renderDeathOptions(){
return <Death />
}
renderProperties(){
const { activeTabIndex } = this.state;
const {canvas:{templatesById, selected:{path}}} = this.props;
const template = templatesById[path[path.length-1]]
return <Properties template={template} updateAttribute={this.props.actions.updateTemplateAttribute.bind(null,path)} updateStyle={this.props.actions.updateTemplateStyle.bind(null,path)}/>
}
render() {
const {mapper:{open, selectedMapping, transformers}, canvas:{selected}, height} = this.props;
const {propertiesExpanded, objectsExpanded, mappingsExpanded, mapperExpanded, birthExpanded, deathExpanded} = this.state;
return (
<div id="mapper" style={{width:viewConstants.MAPPER_WIDTH, boxSizing:'border-box', height: height, overflow:'auto'}}>
<Paper key={1} zDepth={1}>
<Card className="md-block-centered" expanded={objectsExpanded} onExpanderClick={()=>{this.setState({objectsExpanded:!objectsExpanded})}}>
<CardActions expander onClick={()=>{this.setState({objectsExpanded:!objectsExpanded})}}>
objects
</CardActions>
<CardText style={{padding:0}} expandable>
{this.renderObjects()}
</CardText>
</Card>
{selected && <Card className="md-block-centered" defaultExpanded onExpanderClick={()=>{this.setState({propertiesExpanded:!propertiesExpanded})}}>
<CardActions expander onClick={()=>{this.setState({propertiesExpanded:!propertiesExpanded})}}>
properties
</CardActions>
<CardText style={{padding:0}} expandable>
{this.renderProperties()}
</CardText>
</Card>}
{selected && <Card className="md-block-centered" expanded={birthExpanded} onExpanderClick={()=>{this.setState({birthExpanded:!birthExpanded})}}>
<CardActions expander onClick={()=>{this.setState({birthExpanded:!birthExpanded})}}>
birth
</CardActions>
<CardText expandable>
{this.renderBirthOptions()}
</CardText>
</Card>}
{selected && <Card className="md-block-centered" expanded={deathExpanded} onExpanderClick={()=>{this.setState({deathExpanded:!deathExpanded})}}>
<CardActions expander onClick={()=>{this.setState({deathExpanded:!deathExpanded})}}>
death
</CardActions>
<CardText expandable>
{this.renderDeathOptions()}
</CardText>
</Card>}
{selected && <Card className="md-block-centered" expanded={mapperExpanded} onExpanderClick={()=>{this.setState({mapperExpanded:!mapperExpanded})}}>
<CardActions expander onClick={()=>{this.setState({mapperExpanded:!mapperExpanded})}}>
behaviour
</CardActions>
<CardText expandable>
{this.renderMapper()}
{this.renderMappings()}
{selectedMapping && <Transformer selectedMapping={selectedMapping} transformer={transformers[selectedMapping.mappingId]} saveDialog={this.props.actions.saveTransformer.bind(null, selectedMapping.mappingId)} closeDialog={this.props.actions.selectMapping.bind(null,null)}/>}
</CardText>
</Card>}
</Paper>
</div>
);
}
_handleTabChange(activeTabIndex) {
this.setState({ activeTabIndex });
}
_toggleSelected(path,type,selectedPath){
//toogle here by checking laste elements of each path;
if (selectedPath != null && path.length > 0 && type==="group"){
const id1 = selectedPath[selectedPath.length-1];
const id2 = path[path.length-1];
if (id1 === id2){
this.props.actions.templateParentSelected();
return;
}
}
this.props.actions.templateSelected({path:path, type:type});
}
} |
examples/sections/src/ThemeContext.js | styleguidist/react-styleguidist | import React from 'react';
/**
* Context that stores selected application theme: 'light' | 'dark'
*/
export default React.createContext('light');
|
examples/with-webpack-bundle-size-analyzer/pages/index.js | BlancheXu/test | import React from 'react'
import Link from 'next/link'
export default class Index extends React.Component {
static getInitialProps ({ req }) {
if (req) {
// Runs only in the server
const faker = require('faker')
const name = faker.name.findName()
return { name }
}
// Runs only in the client
return { name: 'Arunoda' }
}
render () {
const { name } = this.props
return (
<div>
<h1>Home Page</h1>
<p>Welcome, {name}</p>
<div>
<Link href='/about'>
<a>About Page</a>
</Link>
</div>
</div>
)
}
}
|
src/assets/js/react/components/Template/TemplateUploader.js | blueliquiddesigns/gravity-forms-pdf-extended | import PropTypes from 'prop-types'
import React from 'react'
import { connect } from 'react-redux'
import {
addTemplate,
updateTemplateParam,
postTemplateUploadProcessing,
clearTemplateUploadProcessing
} from '../../actions/templates'
import classNames from 'classnames'
import Dropzone from 'react-dropzone'
import ShowMessage from '../ShowMessage'
/**
* Handles the uploading of new PDF templates to the server
*
* @package Gravity PDF
* @copyright Copyright (c) 2020, Blue Liquid Designs
* @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
* @since 4.1
*/
/**
* React Component
*
* @since 4.1
*/
export class TemplateUploader extends React.Component {
/**
* @since 4.1
*/
static propTypes = {
genericUploadErrorText: PropTypes.string,
addTemplateText: PropTypes.string,
filenameErrorText: PropTypes.string,
filesizeErrorText: PropTypes.string,
installSuccessText: PropTypes.string,
installUpdatedText: PropTypes.string,
templateSuccessfullyInstalledUpdated: PropTypes.string,
templateInstallInstructions: PropTypes.string,
addNewTemplate: PropTypes.func,
updateTemplateParam: PropTypes.func,
postTemplateUploadProcessing: PropTypes.func,
clearTemplateUploadProcessing: PropTypes.func,
templates: PropTypes.array,
templateUploadProcessingSuccess: PropTypes.object,
templateUploadProcessingError: PropTypes.object
}
/**
* Setup internal component state that doesn't need to be in Redux
*
* @returns {{ajax: boolean, error: string, message: string}}
*
* @since 4.1
*/
state = {
ajax: false,
error: '',
message: ''
}
/**
* Fires appropriate function based on Redux store data
*
* @param {Object} nextProps
*
* @since 4.1
*/
componentWillReceiveProps (nextProps) {
Object.keys(nextProps.templateUploadProcessingSuccess).length > 0 && this.ajaxSuccess(nextProps.templateUploadProcessingSuccess)
Object.keys(nextProps.templateUploadProcessingError).length > 0 && this.ajaxFailed(nextProps.templateUploadProcessingError)
}
/**
* Manages the template file upload
*
* @param {array} acceptedFiles The array of uploaded files we should send to the server
*
* @since 4.1
*/
onDrop = (acceptedFiles) => {
/* Handle file upload and pass in an nonce!!! */
if (acceptedFiles instanceof Array && acceptedFiles.length > 0) {
acceptedFiles.forEach((file) => {
const filename = file.name
/* Do validation */
if (!this.checkFilename(filename) || !this.checkFilesize(file.size)) {
return
}
/* Add our loader */
this.setState({
ajax: true,
error: '',
message: '',
})
/* POST the PDF template to our endpoint for processing */
this.props.postTemplateUploadProcessing(file, filename)
})
}
}
/**
* Checks if the uploaded file has a .zip extension
* We do this instead of mime type checking as it doesn't work in all browsers
*
* @param {string} name
*
* @returns {boolean}
*
* @since 4.1
*/
checkFilename = (name) => {
if (name.substr(name.length - 4) !== '.zip') {
/* Tell use about incorrect file type */
this.setState({
error: this.props.filenameErrorText
})
return false
}
return true
}
/**
* Checks if the file size is larger than 5MB
*
* @param {int} size File size in bytes
*
* @returns {boolean}
*
* @since 4.1
*/
checkFilesize = (size) => {
/* Check the file is no larger than 10MB (convert from bytes to KB) */
if (size / 1024 > 10240) {
/* Tell use about incorrect file type */
this.setState({
error: this.props.filesizeErrorText
})
return false
}
return true
}
/**
* Update our Redux store with the new PDF template details
* If our upload AJAX call to the server passed this function gets fired
*
* @param {Object} response
*
* @since 4.1
*/
ajaxSuccess = (response) => {
/* Update our Redux Store with the new template(s) */
response.body.templates.forEach((template) => {
/* Check if template already in the list before adding to our store */
const matched = this.props.templates.find((item) => {
return (item.id === template.id)
})
if (matched === undefined) {
template.new = true //ensure new templates go to end of list
template.message = this.props.installSuccessText
this.props.addNewTemplate(template)
} else {
this.props.updateTemplateParam(template.id, 'message', this.props.installUpdatedText)
}
})
/* Mark as success and stop AJAX spinner */
this.setState({
ajax: false,
message: this.props.templateSuccessfullyInstalledUpdated
})
/* Clean/Reset our Redux Store state for templateUploadProcessing */
this.props.clearTemplateUploadProcessing()
}
/**
* Show any errors to the user when AJAX request fails for any reason
*
* @param {Object} error
*
* @since 4.1
*/
ajaxFailed = (error) => {
/* Let the user know there was a problem with the upload */
this.setState({
error: (error.response.body && error.response.body.error !== undefined) ? error.response.body.error : this.props.genericUploadErrorText,
ajax: false
})
/* Clean/Reset our Redux Store state for templateUploadProcessing */
this.props.clearTemplateUploadProcessing()
}
/**
* Remove message from state once the timeout has finished
*
* @since 4.1
*/
removeMessage = () => {
this.setState({
message: ''
})
}
/**
* @since 4.1
*/
render () {
return (
<div className="theme add-new-theme gfpdf-dropzone">
<Dropzone
onDrop={this.onDrop}
maxSize={10240000}
>
{({getRootProps, getInputProps, isDragActive}) => {
return (
<div
{...getRootProps()}
className={classNames('dropzone', {'dropzone--isActive': isDragActive})}
>
<input {...getInputProps()} />
<a href="#/template" className={this.state.ajax ? 'doing-ajax' : ''}>
<div className="theme-screenshot"><span/></div>
{this.state.error !== '' ? <ShowMessage text={this.state.error} error={true}/> : null}
{this.state.message !== '' ?
<ShowMessage text={this.state.message} dismissable={true}
dismissableCallback={this.removeMessage}/> : null}
<h2 className="theme-name">{this.props.addTemplateText}</h2>
</a>
<div className="gfpdf-template-install-instructions">{this.props.templateInstallInstructions}</div>
</div>
)
}}
</Dropzone>
</div>
)
}
}
/**
* Map Redux state to props
*
* @param state
* @returns {{templates: Array, templateUploadProcessingSuccess: Object, templateUploadProcessingError: Object}}
*
* @since 5.2
*/
const mapStateToProps = (state) => {
return {
templates: state.template.list,
templateUploadProcessingSuccess: state.template.templateUploadProcessingSuccess,
templateUploadProcessingError: state.template.templateUploadProcessingError
}
}
/**
* Map actions to props
*
* @param {func} dispatch Redux dispatcher
*
* @returns {{addNewTemplate: (function(template)), updateTemplateParam: (function(id=string, name=string, value=*)), postTemplateUploadProcessing: (function(file=object, filename=string)), clearTemplateUploadProcessing: (function())}}
*
* @since 4.1
*/
const mapDispatchToProps = (dispatch) => {
return {
addNewTemplate: (template) => {
dispatch(addTemplate(template))
},
updateTemplateParam: (id, name, value) => {
dispatch(updateTemplateParam(id, name, value))
},
postTemplateUploadProcessing: (file, filename) => {
dispatch(postTemplateUploadProcessing(file, filename))
},
clearTemplateUploadProcessing: () => {
dispatch(clearTemplateUploadProcessing())
}
}
}
/**
* Maps our Redux store to our React component
*
* @since 4.1
*/
export default connect(mapStateToProps, mapDispatchToProps)(TemplateUploader)
|
src/main/js/my-app/src/index.js | myapos/ClientManagerSpringBoot | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from './store/configureStore';
import App from './containers/App';
import './index.css';
import * as utils from './utils';
const init = async () => {
const placeholder = document.getElementById('react');
const initialState = {
initRegistrations: [[]],
initDataStudentClasses: [[]],
initDataStudents: [],
// initDataAllStudents_: [],
initPayments: [],
displayInitialMsg: true,
seconds: 0,
timer: null,
setNonTerminalClasses: false,
filteredStudentClassesWithLinks: [[]],
lname: '',
activePage: 0,
searchingStatus: false,
};
ReactDOM.render(<Provider
store={configureStore(initialState)}>
<App />
</Provider>, placeholder);
};
init();
|
front/app/js/rh-components/rh-Spinner.js | nudoru/learning-map | import React from 'react';
const Spinner = ({type}) => {
let cls = ['spinner'];
if(type) {
cls.push(type);
}
return (<div className={cls.join(' ')}></div>)
};
export default Spinner; |
src/lexer.js | MrCheater/text-resize-and-word-wrap-provider | import React from 'react';
let index = 0;
export function lexer(jsxText, props, results, init) {
if(init) {
index = 0;
}
if(!Array.isArray(jsxText)) {
jsxText = [jsxText];
}
const countChildren = jsxText.length;
for(let childIndex = 0; childIndex < countChildren; childIndex++) {
const child = jsxText[childIndex];
if(child === null) {
continue;
}
if(React.isValidElement(child)) {
const type = child.type;
const isDiv = type === 'div';
const isBreakLine = type === 'br';
const isTagA = props.isTagA || (type === 'a');
if(isDiv || isBreakLine) {
index++;
}
let {
children,
...childProps,
} = child.props;
if(isBreakLine) {
children = ' ';
}
if(children) {
lexer(
children,
{
...props,
...childProps,
isTagA,
type
},
results
);
}
if(isDiv || isBreakLine) {
index++;
}
} else {
const str = '' + child;
const words = str.split(' ');
const countWords = words.length;
for(let wordIndex = 0; wordIndex < countWords; wordIndex++) {
results.push({
word : words[wordIndex],
props : {
...props,
isSpanEnd : !(countWords - wordIndex - 1)
},
index
});
}
}
}
} |
src/components/table_headers.js | mdkalish/json_selector | import React from 'react';
var SocialMediumHeaderRow = React.createClass({
render: function() {
return (
<tr style={{backgroundColor: '#fa6900'}}>
<th colSpan="4">
{this.props.type}
</th>
</tr>
);
}
});
var ColumnHeadersRow = React.createClass({
getInitialState: function() {
return {picked: false}
},
updatePicked: function() {
var picked = {picked: !this.state.picked}
this.setState(picked)
this.props.updatePicked(picked)
},
render: function() {
var k = Math.random()
return (
<tr colSpan="4" style={{backgroundColor: '#f38630'}}>
<th>Key Name</th>
<th>sObject Value</th>
<th>Fullcontact Value</th>
<th>
<label htmlFor={"updateAll_" + k}>Update sObject?</label>
<input type="checkbox" checked={this.state.picked} onChange={this.updatePicked} id={"updateAll_" + k} />
</th>
</tr>
);
}
});
module.exports = {SocialMediumHeaderRow, ColumnHeadersRow}
|
src/SudokuBoard.js | itsjustdanger/sudoku-solver | import React from 'react';
import PropTypes from 'prop-types';
import Square from './Square.js';
/* Display component for the sudoku board */
export default class SudokuBoard extends React.Component {
render() {
const board = this.props.board;
const squares = [];
for (const box in board) {
if (box) {
squares.push(
<Square
key={box}
handleChange={this.props.handleChange.bind(this, box)}
value={board[box]} />
);
}
}
return (
<div className="sudoku-board">
<span className="cross-line top"></span>
<span className="cross-line bottom"></span>
<span className="cross-line left"></span>
<span className="cross-line right"></span>
{squares}
</div>
)
}
}
SudokuBoard.propTypes = {
board: PropTypes.object.isRequired,
handleChange: PropTypes.func.isRequired,
}
|
analysis/paladinholy/src/modules/spells/DevotionAuraDamageReduction.js | yajinni/WoWAnalyzer | import React from 'react';
import { Trans } from '@lingui/macro';
import SPELLS from 'common/SPELLS';
import fetchWcl from 'common/fetchWclApi';
import { SpellIcon } from 'interface';
import { formatThousands, formatNumber } from 'common/format';
import LazyLoadStatisticBox, { STATISTIC_ORDER } from 'parser/ui/LazyLoadStatisticBox';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Combatants from 'parser/shared/modules/Combatants';
import makeWclUrl from 'common/makeWclUrl';
import { SpellLink } from 'interface';
import Events, { EventType } from 'parser/core/Events';
// Source: https://github.com/MartijnHols/HolyPaladin/blob/master/Spells/Talents/60/DevotionAura.md#about-the-passive-effect
const DEVOTION_AURA_PASSIVE_DAMAGE_REDUCTION = .03;
const DEVOTION_AURA_ACTIVE_DAMAGE_REDUCTION = 0.15;
/**
* Falling damage is considered "pure" or w/e damage meaning it doesn't get reduced by damage reductions. The ability description of such an event can look like this: {
"name": "Falling",
"guid": 3,
"type": 1,
"abilityIcon": "inv_axe_02.jpg"
},
* `type: 1` seems to only be used by Falling, but I was unable to verify this. I want to ignore this kind of damage taken. I figured the savest solution would be to filter by ability id instead of type, but if you find another such ability that needs to be ignored and it has `type: 1` while nothing else does, we may want to refactor this.
*/
// const THIS_MIGHT_BE_PURE_ABILITY_TYPE_ID = 1;
const FALLING_DAMAGE_ABILITY_ID = 3;
/**
* Devotion Aura
* Damage dealt to allies within 10 yards is reduced by up to 10%, diminishing as more allies enter the aura.
* While Aura Mastery is active, all affected allies gain 20% damage reduction.
* ---
* See the markdown file next to this module for info about how this is analyzed.
*/
class DevotionAuraDamageReduction extends Analyzer {
static dependencies = {
combatants: Combatants,
};
passiveDamageReduced = 0;
get passiveDrps() {
return (this.passiveDamageReduced / this.owner.fightDuration) * 1000;
}
activeDamageReduced = 0;
get activeDrps() {
return (this.activeDamageReduced / this.owner.fightDuration) * 1000;
}
get totalDamageReduced() {
return this.passiveDamageReduced + this.activeDamageReduced;
}
get totalDrps() {
return (this.totalDamageReduced / this.owner.fightDuration) * 1000;
}
constructor(...args) {
super(...args);
this.addEventListener(Events.damage.to(SELECTED_PLAYER), this.onDamageTaken);
this.addEventListener(Events.applybuff.by(SELECTED_PLAYER), this.onApplyBuff);
this.addEventListener(Events.removebuff.by(SELECTED_PLAYER), this.onRemoveBuff);
}
onDamageTaken(event) {
const spellId = event.ability.guid;
if (spellId === FALLING_DAMAGE_ABILITY_ID) {
return;
}
const isAuraMasteryActive = this.selectedCombatant.hasBuff(
SPELLS.AURA_MASTERY.id,
event.timestamp,
0,
0,
this.owner.playerId,
);
if (!isAuraMasteryActive) {
const damageTaken = event.amount + (event.absorbed || 0);
const damageReduced =
(damageTaken / (1 - this.singleTargetDamageReduction)) * this.totalPassiveDamageReduction;
this.passiveDamageReduced += damageReduced;
}
}
buffsActive = 1;
get singleTargetDamageReduction() {
return DEVOTION_AURA_PASSIVE_DAMAGE_REDUCTION;
}
get totalPassiveDamageReduction() {
return this.singleTargetDamageReduction * this.buffsActive;
}
isApplicableBuffEvent(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.DEVOTION_AURA.id) {
return false;
}
if (this.owner.toPlayer(event)) {
// We already include the selected player by default, if he dies the buff might show up. So to make sure it's not accidentally considered, we exclude it here.
return false;
}
const combatant = this.combatants.players[event.targetID];
if (!combatant) {
// Only players scale the buff, while pets can get it they do not affect the DR split
return false;
}
return true;
}
onApplyBuff(event) {
if (!this.isApplicableBuffEvent(event)) {
return;
}
this.buffsActive += 1;
// this.debug('devo applied to', this.combatants.players[event.targetID].name, this.buffsActive);
}
onRemoveBuff(event) {
if (!this.isApplicableBuffEvent(event)) {
return;
}
this.buffsActive -= 1;
// this.debug('devo removed from', this.combatants.players[event.targetID].name, this.buffsActive);
if (this.buffsActive === 0) {
console.error(
'We lost more Devotion Aura buffs than we gained, this should not be possible as applybuffs are fabricated for all removebuffs.',
);
this.buffsActive = 1;
}
}
get auraMasteryUptimeFilter() {
const buffHistory = this.selectedCombatant.getBuffHistory(
SPELLS.AURA_MASTERY.id,
this.owner.playerId,
);
if (buffHistory.length === 0) {
return null;
}
// WCL's filter requires the timestamp to be relative to fight start
return buffHistory
.map(
buff =>
`(timestamp>=${buff.start - this.owner.fight.start_time} AND timestamp<=${buff.end -
this.owner.fight.start_time})`,
)
.join(' OR ');
}
get filter() {
const playerName = this.owner.player.name;
// Include any damage while selected player has AM, and is above the health requirement,
// and the mitigation percentage is greater than 19% (we use this to reduce the false positives. We use DR-1% to account for rounding)
return `(IN RANGE FROM target.name='${playerName}' AND type='${
EventType.ApplyBuff
}' AND ability.id=${SPELLS.AURA_MASTERY.id} TO target.name='${playerName}' AND type='${
EventType.RemoveBuff
}' AND ability.id=${SPELLS.AURA_MASTERY.id} END)
AND (mitigatedDamage/rawDamage*100)>${DEVOTION_AURA_ACTIVE_DAMAGE_REDUCTION * 100 - 1}`;
}
load() {
return fetchWcl(`report/tables/damage-taken/${this.owner.report.code}`, {
start: this.owner.fight.start_time,
end: this.owner.fight.end_time,
filter: this.filter,
}).then(json => {
console.log('Received AM damage taken', json);
const totalDamageTaken = json.entries.reduce(
(damageTaken, entry) => damageTaken + entry.total,
0,
);
this.activeDamageReduced =
(totalDamageTaken / (1 - DEVOTION_AURA_ACTIVE_DAMAGE_REDUCTION)) *
DEVOTION_AURA_ACTIVE_DAMAGE_REDUCTION;
});
}
statistic() {
const tooltip = (
<Trans id="paladin.holy.modules.talents.devotionAuraDamageReduction.tooltip">
The total estimated damage reduced <strong>by the passive</strong> was{' '}
{formatThousands(this.passiveDamageReduced)} ({formatNumber(this.passiveDrps)} DRPS). This
has high accuracy.
<br />
The total estimated damage reduced <strong>during Aura Mastery</strong> was{' '}
{formatThousands(this.activeDamageReduced)} ({formatNumber(this.activeDrps)} DRPS). This has
a 99% accuracy.
<br />
<br />
This value is calculated using the <i>Optional DRs</i> method. This results in the lowest
possible damage reduction value being shown. This should be the correct value in most
circumstances.
<br />
<br />
Calculating the exact damage reduced by Devotion Aura is very time and resource consuming.
This method uses a very close estimation. The active damage reduced is calculated by taking
the total damage taken of the entire raid during <SpellLink
id={SPELLS.AURA_MASTERY.id}
/>{' '}
and calculating the damage reduced during this time. The passive damage reduction is
calculated by taking the exact damage reduction factor applicable and calculating the damage
reduced if that full effect was applied to the Paladin. Even though the passive damage
reduction is split among other nearby players, using your personal damage taken should
average it out very closely. More extensive tests that go over all damage events have shown
that this is usually a close approximation.
</Trans>
);
return (
<LazyLoadStatisticBox
position={STATISTIC_ORDER.OPTIONAL(60)}
loader={this.load.bind(this)}
icon={<SpellIcon id={SPELLS.DEVOTION_AURA.id} />}
value={<Trans id="paladin.holy.modules.talents.devotionAuraDamageReduction.drps">≈{formatNumber(this.totalDrps)} DRPS</Trans>}
label={<Trans id="paladin.holy.modules.talents.devotionAuraDamageReduction.damageReduction">Damage reduction</Trans>}
tooltip={tooltip}
drilldown={makeWclUrl(this.owner.report.code, {
fight: this.owner.fightId,
type: 'damage-taken',
pins: `2$Off$#244F4B$expression$${this.filter}`,
view: 'events',
})}
/>
);
}
}
export default DevotionAuraDamageReduction;
|
src/routes/hardware/index.js | bigearth/www.clone.earth |
import React from 'react';
import Layout from '../../components/Layout';
import Hardware from './Hardware';
const title = 'Hardware';
export default {
path: '/hardware',
action() {
return {
title,
component: <Layout><Hardware title={title} /></Layout>,
};
},
};
|
app/cards/blog-card.js | gon250/personal-web | import React from 'react';
export default React.createClass({
render: function (){
let postDate = this.props.blogDate.toString().substring(0,10);
return (
<div className="mdl-grid mdl-cell mdl-cell--12-col mdl-cell--4-col-tablet mdl-card mdl-shadow--4dp">
<div className="mdl-card__title">
<h2 className="mdl-card__title-text">
{this.props.blogTitle}
</h2>
</div>
<div className="mdl-card__supporting-text no-bottom-padding">
<span>Posted {postDate}</span>
<div id="tt2"
onClick={this.props.blogActionShare}
className="icon material-icons portfolio-share-btn"
tabIndex="0">
share
</div>
</div>
<div className="mdl-card__supporting-text blog-card-content"
dangerouslySetInnerHTML={{__html: this.props.blogContent}}>
</div>
<div className="mdl-card__actions mdl-card--border">
<a
href={this.props.blogLink}
target="_blank"
className="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect mdl-button--accent">
View post →
</a>
</div>
</div>
)
}
});
|
src/svg-icons/navigation/chevron-right.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationChevronRight = (props) => (
<SvgIcon {...props}>
<path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
</SvgIcon>
);
NavigationChevronRight = pure(NavigationChevronRight);
NavigationChevronRight.displayName = 'NavigationChevronRight';
NavigationChevronRight.muiName = 'SvgIcon';
export default NavigationChevronRight;
|
apps/marketplace/components/Opportunity/EvaluationCriteria.js | AusDTO/dto-digitalmarketplace-frontend | import React from 'react'
import PropTypes from 'prop-types'
import AUheading from '@gov.au/headings/lib/js/react.js'
import styles from './EvaluationCriteria.scss'
const EvaluationCriteria = props => (
<div className={styles.container}>
<div className="row">
<div
role="columnheader"
id="header_criteria"
className={props.showWeightings ? `col-xs-8 col-sm-9` : `col-xs-12`}
>
<AUheading level={props.titleLevel} size={props.titleSize}>
{props.title}
</AUheading>
</div>
{props.showWeightings && (
<div role="columnheader" id="header_weighting" className="col-xs-4 col-sm-2 col-sm-offset-1">
<strong>Weighting</strong>
</div>
)}
</div>
{props.evaluationCriteria.map(evaluationCriteria => (
<div key={evaluationCriteria.criteria} className="row">
<div
role="cell"
aria-labelledby="header_criteria"
className={props.showWeightings ? `col-xs-8 col-sm-9 ${styles.newLines}` : `col-xs-12 ${styles.newLines}`}
>
{evaluationCriteria.criteria}
</div>
{props.showWeightings && (
<div role="cell" aria-labelledby="header_weighting" className="col-xs-4 col-sm-2 col-sm-offset-1">
{evaluationCriteria.weighting}%
</div>
)}
</div>
))}
</div>
)
EvaluationCriteria.defaultProps = {
evaluationCriteria: [],
showWeightings: true,
title: 'Evaluation criteria',
titleLevel: '2',
titleSize: 'lg'
}
EvaluationCriteria.propTypes = {
evaluationCriteria: PropTypes.array,
showWeightings: PropTypes.bool,
title: PropTypes.string,
titleLevel: PropTypes.string,
titleSize: PropTypes.string
}
export default EvaluationCriteria
|
backend/dynamic-web-apps/voting-app/client/src/components/Signup.js | mkermani144/freecodecamp-projects | import React, { Component } from 'react';
import { Redirect } from 'react-router';
import Paper from 'material-ui/Paper';
import { Step, Stepper, StepLabel, StepContent } from 'material-ui/Stepper';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
import CircularProgress from 'material-ui/CircularProgress';
import Snackbar from 'material-ui/Snackbar';
import { blue50, blue500 } from 'material-ui/styles/colors';
import './Login-Signup.css';
class Signup extends Component {
constructor() {
super();
this.state = {
stepIndex: 0,
progress: {
visibility: 'hidden'
},
textFieldError: 0,
nextDisabled: true,
username: '',
passwrod: '',
isLoggedIn: false,
submitFailed: false,
};
this.timeout = null;
this.errors = {
0: '',
1: 'Username is already taken',
3: 'Username is too short',
4: 'Username is too long',
5: 'Username is not valid',
6: 'Password must be at least 6 characters length',
7: 'Passwords entered do not match',
}
this.timeout = 0;
this.alive = true;
}
validateUsername = (username) => {
if (username.length < 6) {
return 3;
} else if (username.length > 20) {
return 4;
} else {
const testResult = (/^[a-zA-Z][a-zA-Z0-9_.]{4,18}[a-zA-Z0-9]$/).test(username);
if (testResult) {
return 0;
} else {
return 5;
}
}
}
handleNext = () => {
const { stepIndex } = this.state;
this.setState({
stepIndex: stepIndex + 1,
nextDisabled: stepIndex !== 2,
});
};
handlePrev = () => {
const { stepIndex } = this.state;
if (stepIndex > 0) {
this.setState({
stepIndex: stepIndex - 1,
textFieldError: '',
});
}
};
handleUsernameChange = (e) => {
clearTimeout(this.timeout);
const username = e.target.value;
this.timeout = setTimeout(() => {
const validationResult = this.validateUsername(username);
if (validationResult === 0) {
this.setState({
progress: {
visibility: 'visible',
},
}, async () => {
const response = await fetch('http://localhost:8000/api/findUser', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username
}),
});
const json = await response.json();
this.setState({
progress: {
visibility: 'hidden',
},
username,
textFieldError: +json.userExists,
nextDisabled: +json.userExists !== 0,
});
});
} else {
this.setState({
textFieldError: validationResult,
nextDisabled: true,
});
}
}, 200);
}
handlePasswordChange = (e) => {
const password = e.target.value;
if (password.length >= 6) {
this.setState({
password,
nextDisabled: false,
textFieldError: 0,
});
} else {
this.setState({
nextDisabled: true,
textFieldError: 6,
});
}
}
handlePasswordConfirmChange = (e) => {
const passwordConfirm = e.target.value;
if (passwordConfirm === this.state.password) {
this.setState({
nextDisabled: false,
textFieldError: 0,
});
} else {
this.setState({
nextDisabled: true,
textFieldError: 7,
});
}
}
handleSubmit = async () => {
this.props.logOut();
const response = await fetch('http://localhost:8000/signup', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password
}),
});
if (response.ok) {
this.setState({
isLoggedIn: true,
});
localStorage.setItem('username', this.state.username);
this.props.logIn(1, this.state.username);
const response = await fetch(`http://localhost:8000/api/userpolls/${this.state.username}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
});
const json = await response.json();
json.polls.forEach(poll => this.props.addPoll(poll.id, poll.owner, poll.title, poll.description, Object.keys(poll.choices).map(key => [key, poll.choices[key]])));
} else {
this.setState({
submitFailed: true,
});
}
}
handleSnackbarClose = () => {
this.setState({
submitFailed: false,
});
}
renderStepActions(step) {
const buttonStyle = {
marginTop: '5vmin',
marginLeft: '1vmin',
};
return (
<div className="step-actions">
{step > 0 && (
<FlatButton
label="Back"
disabled={step === 0}
disableTouchRipple={true}
disableFocusRipple={true}
onClick={this.handlePrev}
style={buttonStyle}
/>
)}
<RaisedButton
label={step === 3 ? 'Sign up' : 'Next'}
type='button'
disableTouchRipple={true}
disableFocusRipple={true}
primary={true}
onClick={step === 3 ? this.handleSubmit : this.handleNext}
style={buttonStyle}
disabled={this.state.nextDisabled}
/>
</div>
);
}
render() {
const signupStyle = {
backgroundColor: blue500
};
const paperStyle = {
padding: '5vmin',
width: '60vmin',
backgroundColor: blue50,
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
};
const { stepIndex } = this.state;
return this.state.isLoggedIn ? <Redirect to="/" /> : (
<div className="Signup" style={signupStyle}>
<Paper className="paper" style={paperStyle}>
<form>
<Stepper activeStep={stepIndex} orientation="vertical">
<Step>
<StepLabel>Choose a username</StepLabel>
<StepContent>
<div className="wrapper">
<TextField
name="username"
type="text"
floatingLabelText="Username"
floatingLabelFixed={true}
fullWidth={true}
autoFocus
onChange={this.handleUsernameChange}
errorText={this.errors[this.state.textFieldError]}
/>
<CircularProgress size={20} thickness={2} style={this.state.progress} />
</div>
{this.renderStepActions(0)}
</StepContent>
</Step>
<Step>
<StepLabel>Set a password</StepLabel>
<StepContent>
<div className="wrapper">
<TextField
name="password"
type="password"
floatingLabelText="Password"
floatingLabelFixed={true}
fullWidth={true}
autoFocus
onChange={this.handlePasswordChange}
errorText={this.errors[this.state.textFieldError]}
/>
<CircularProgress size={20} thickness={2} style={{visibility: 'hidden'}} />
</div>
{this.renderStepActions(1)}
</StepContent>
</Step>
<Step>
<StepLabel>Confirm password</StepLabel>
<StepContent>
<div className="wrapper">
<TextField
name="password"
type="password"
floatingLabelText="Password (Again)"
floatingLabelFixed={true}
fullWidth={true}
autoFocus
onChange={this.handlePasswordConfirmChange}
errorText={this.errors[this.state.textFieldError]}
/>
<CircularProgress size={20} thickness={2} style={{visibility: 'hidden'}} />
</div>
{this.renderStepActions(2)}
</StepContent>
</Step>
<Step>
<StepLabel>Finish signup</StepLabel>
<StepContent>
{this.renderStepActions(3)}
</StepContent>
</Step>
</Stepper>
</form>
</Paper>
<Snackbar
open={this.state.submitFailed}
message="Something bad happended. Try again later."
autoHideDuration={4000}
onRequestClose={this.handleSnackbarClose}
/>
</div>
);
}
}
export default Signup;
|
src/components/manage/ManageForm.js | oraclesorg/ico-wizard | import React from 'react'
import { Link } from 'react-router-dom'
import { FormSpy } from 'react-final-form'
import { FieldArray } from 'react-final-form-arrays'
import { ManageTierBlock } from './ManageTierBlock'
import classNames from 'classnames'
export const ManageForm = ({
handleSubmit,
invalid,
pristine,
handleChange,
canSave,
...props,
}) => (
<form onSubmit={handleSubmit}>
<FieldArray name="tiers">
{({ fields }) => (
<ManageTierBlock
fields={fields}
{...props}
/>
)}
</FieldArray>
<FormSpy subscription={{ values: true }} onChange={handleChange}/>
<div className="steps">
<div className="button-container">
<Link to='#' onClick={handleSubmit}>
<span className={classNames(
'no_arrow',
'button',
'button_fill',
{
'button_disabled': (pristine || invalid) && !canSave
}
)}>Save</span>
</Link>
</div>
</div>
</form>
)
|
src/Spring.js | wilfreddenton/react-motion | import React from 'react';
import components from './components';
module.exports = components(React);
|
src/Label/Label.driver.js | skyiea/wix-style-react | import React from 'react';
import ReactDOM from 'react-dom';
const labelDriverFactory = ({element, wrapper, component}) => {
return {
exists: () => !!element,
getTagName: () => element.tagName.toLowerCase(),
getLabelText: () => element.textContent,
getClassList: () => element.className,
getAttr: attrName => element.getAttribute(attrName),
setProps: props => {
const ClonedWithProps = React.cloneElement(component, Object.assign({}, component.props, props), ...(component.props.children || []));
ReactDOM.render(<div ref={r => element = r}>{ClonedWithProps}</div>, wrapper);
}
};
};
export default labelDriverFactory;
|
cm19/ReactJS/your-first-react-app-exercises-master/exercise-13/complete/friend-detail/FriendFlipper.js | Brandon-J-Campbell/codemash | import React from 'react';
import styles from './FriendFlipper.css';
export default class FriendFlipper extends React.Component {
state = {
flipped: false,
};
handleFlipped = () => {
this.setState(prevProps => {
return {
flipped: !prevProps.flipped,
};
});
};
render() {
return (
<div className={styles.flipWrapper}>
<div className={styles.flipper}>
{this.state.flipped ? null : this.renderFront()}
{!this.state.flipped ? null : this.renderBack()}
</div>
</div>
);
}
renderFront() {
const { friend } = this.props;
return (
<div className={styles.front}>
<div className={styles.frontContents}>
<img src={friend.image} alt={friend.image} />
<button
type="button"
className={styles.flipperNav}
onClick={this.handleFlipped}
>
Details >
</button>
</div>
</div>
);
}
renderBack() {
const { friend } = this.props;
return (
<div className={styles.back}>
<div className={styles.backContents}>
<img src={friend.image} alt={friend.image} />
<div className={styles.backDetails}>
<h3>
ID:
{friend.id}
</h3>
<h3>Colors:</h3>
<ul>
{friend.colors.map(color => (
<li key={color}>{color}</li>
))}
</ul>
</div>
<button
type="button"
className={styles.flipperNav}
onClick={this.handleFlipped}
>
< Back
</button>
</div>
</div>
);
}
}
|
node_modules/react-bootstrap/es/Tab.js | rblin081/drafting-client | import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import _extends from 'babel-runtime/helpers/extends';
import React from 'react';
import PropTypes from 'prop-types';
import TabContainer from './TabContainer';
import TabContent from './TabContent';
import TabPane from './TabPane';
var propTypes = _extends({}, TabPane.propTypes, {
disabled: PropTypes.bool,
title: PropTypes.node,
/**
* tabClassName is used as className for the associated NavItem
*/
tabClassName: PropTypes.string
});
var Tab = function (_React$Component) {
_inherits(Tab, _React$Component);
function Tab() {
_classCallCheck(this, Tab);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Tab.prototype.render = function render() {
var props = _extends({}, this.props);
// These props are for the parent `<Tabs>` rather than the `<TabPane>`.
delete props.title;
delete props.disabled;
delete props.tabClassName;
return React.createElement(TabPane, props);
};
return Tab;
}(React.Component);
Tab.propTypes = propTypes;
Tab.Container = TabContainer;
Tab.Content = TabContent;
Tab.Pane = TabPane;
export default Tab; |
src/index.js | attilad/console-room | import React from 'react';
import {render} from 'react-dom';
import HomePage from './containers/HomePage';
render(
<HomePage helloWorld="Hello, Universe!" />, document.getElementById('app')
);
|
blueocean-material-icons/src/js/components/svg-icons/hardware/keyboard-hide.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const HardwareKeyboardHide = (props) => (
<SvgIcon {...props}>
<path d="M20 3H4c-1.1 0-1.99.9-1.99 2L2 15c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-9 3h2v2h-2V6zm0 3h2v2h-2V9zM8 6h2v2H8V6zm0 3h2v2H8V9zm-1 2H5V9h2v2zm0-3H5V6h2v2zm9 7H8v-2h8v2zm0-4h-2V9h2v2zm0-3h-2V6h2v2zm3 3h-2V9h2v2zm0-3h-2V6h2v2zm-7 15l4-4H8l4 4z"/>
</SvgIcon>
);
HardwareKeyboardHide.displayName = 'HardwareKeyboardHide';
HardwareKeyboardHide.muiName = 'SvgIcon';
export default HardwareKeyboardHide;
|
admin/src/components/ListHeader.js | lastjune/keystone | import classNames from 'classnames';
import React from 'react';
import utils from '../utils.js';
import { Button, Container, Dropdown, FormInput, InputGroup, Pagination } from 'elemental';
import CreateForm from './CreateForm';
import ListColumnsForm from './ListColumnsForm';
import ListDownloadForm from './ListDownloadForm';
import ListFilters from './ListFilters';
import ListFiltersAdd from './ListFiltersAdd';
import ListSort from './ListSort';
import CurrentListStore from '../stores/CurrentListStore';
var ListHeader = React.createClass({
displayName: 'ListHeader',
getInitialState () {
return {
createIsOpen: Keystone.showCreateForm,
manageIsOpen: false,
searchString: '',
...this.getStateFromStore()
};
},
componentDidMount () {
CurrentListStore.addChangeListener(this.updateStateFromStore);
},
componentWillUnmount () {
clearTimeout(this._searchTimeout);
CurrentListStore.removeChangeListener(this.updateStateFromStore);
},
getStateFromStore () {
return {
activeColumns: CurrentListStore.getActiveColumns(),
activeFilters: CurrentListStore.getActiveFilters(),
availableColumns: CurrentListStore.getAvailableColumns(),
currentPage: CurrentListStore.getCurrentPage(),
items: CurrentListStore.getItems(),
list: CurrentListStore.getList(),
pageSize: CurrentListStore.getPageSize(),
ready: CurrentListStore.isReady()
};
},
updateStateFromStore () {
this.setState(this.getStateFromStore());
},
toggleCreateModal (visible) {
this.setState({
createIsOpen: visible
});
},
toggleDownloadModal (visible) {
this.setState({
downloadIsOpen: visible
});
},
toggleManageOpen (filter = !this.state.manageIsOpen) {
this.setState({
manageIsOpen: filter
});
},
updateSearch (e) {
clearTimeout(this._searchTimeout);
this.setState({
searchString: e.target.value
});
var delay = e.target.value.length > 1 ? 250 : 0;
this._searchTimeout = setTimeout(() => {
CurrentListStore.setActiveSearch(this.state.searchString);
}, delay);
},
handleSearchClear () {
CurrentListStore.setActiveSearch('');
this.setState({ searchString: '' });
React.findDOMNode(this.refs.listSearchInput).focus();
},
handleSearchKey (e) {
// clear on esc
if (e.which === 27) {
this.handleSearchClear ();
}
},
handlePageSelect (i) {
CurrentListStore.setCurrentPage(i);
},
renderSearch () {
var searchClearIcon = classNames('ListHeader__search__icon octicon', {
'is-search octicon-search': !this.state.searchString.length,
'is-clear octicon-x': this.state.searchString.length
});
return (
<InputGroup.Section grow className="ListHeader__search">
<FormInput ref="listSearchInput" value={this.state.searchString} onChange={this.updateSearch} onKeyUp={this.handleSearchKey} placeholder="Search" className="ListHeader__searchbar-input" />
<button ref="listSearchClear" type="button" onClick={this.handleSearchClear} disabled={!this.state.searchString.length} className={searchClearIcon} />
</InputGroup.Section>
);
},
renderDownloadButton () {
return (
<InputGroup.Section>
<Button>
Download
<span className="disclosure-arrow" />
</Button>
</InputGroup.Section>
);
},
renderCreateButton () {
var props = { type: 'success' };
if (this.state.list.autocreate) {
props.href = '?new' + Keystone.csrf.query;
} else {
props.onClick = this.toggleCreateModal.bind(this, true);
}
return (
<InputGroup.Section className="ListHeader__create">
<Button {...props} title={'Create ' + this.state.list.singular}>
<span className="ListHeader__create__icon octicon octicon-plus" />
<span className="ListHeader__create__label">
Create
</span>
<span className="ListHeader__create__label--lg">
Create {this.state.list.singular}
</span>
</Button>
</InputGroup.Section>
);
},
renderCreateForm () {
return <CreateForm list={this.state.list} isOpen={this.state.createIsOpen} onCancel={this.toggleCreateModal.bind(this, false)} values={Keystone.createFormData} err={Keystone.createFormErrors} />;
},
renderManagement () {
let { items, manageIsOpen } = this.state;
if (!items.count) return;
let manageUI = manageIsOpen ? (
<div style={{ float: 'left', marginRight: 10 }}>
<InputGroup contiguous style={{ display: 'inline-flex', marginBottom: 0 }}>
<InputGroup.Section>
<Button>Select all</Button>
</InputGroup.Section>
<InputGroup.Section>
<Button>Select none</Button>
</InputGroup.Section>
</InputGroup>
<InputGroup contiguous style={{ display: 'inline-flex', marginBottom: 0, marginLeft: '.5em' }}>
<InputGroup.Section>
<Button>Update</Button>
</InputGroup.Section>
<InputGroup.Section>
<Button>Delete</Button>
</InputGroup.Section>
</InputGroup>
<Button type="link-cancel" onClick={this.toggleManageOpen.bind(this, false)}>Cancel</Button>
</div>
) : (
<Button onClick={this.toggleManageOpen.bind(this, true)} style={{ float: 'left', marginRight: 10 }}>Manage</Button>
);
return manageUI;
},
renderPagination () {
let { currentPage, items, list, manageIsOpen, pageSize } = this.state;
if (manageIsOpen || !items.count) return;
return (
<Pagination
className="ListHeader__pagination"
currentPage={currentPage}
onPageSelect={this.handlePageSelect}
pageSize={pageSize}
plural={list.plural}
singular={list.singular}
style={{ marginBottom: 0 }}
total={items.count}
/>
);
},
render () {
let { currentPage, items, list, pageSize } = this.state;
return (
<div className="ListHeader">
<Container>
<h2 className="ListHeader__title">
{utils.plural(items.count, ('* ' + list.singular), ('* ' + list.plural))}
<ListSort />
</h2>
<InputGroup className="ListHeader__bar">
{this.renderSearch()}
<ListFiltersAdd className="ListHeader__filter" />
<ListColumnsForm className="ListHeader__columns" />
<ListDownloadForm className="ListHeader__download" />
<InputGroup.Section className="ListHeader__expand">
<Button isActive={this.props.tableIsExpanded} onClick={this.props.toggleTableWidth} title="Expand table width">
<span className="octicon octicon-mirror" />
</Button>
</InputGroup.Section>
{this.renderCreateButton()}
</InputGroup>
<ListFilters />
<div style={{ height: 32, marginBottom: '2em' }}>
{this.renderManagement()}
{this.renderPagination()}
<span style={{ clear: 'both', display: 'table' }} />
</div>
</Container>
{this.renderCreateForm()}
</div>
);
}
});
module.exports = ListHeader;
|
cerberus-dashboard/src/components/SecureDataVersionsBrowser/SecureDataVersionsBrowser.js | Nike-Inc/cerberus | /*
* Copyright (c) 2020 Nike, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import { Component } from 'react';
import { connect } from 'react-redux';
import Loader from '../Loader/Loader';
import ReactPaginate from 'react-paginate';
import Select from 'react-select';
import * as vActions from '../../actions/versionHistoryBrowserActions.js';
import JSONPretty from 'react-json-pretty';
import './SecureDataVersionsBrowser.scss';
class SecureDataVersionsBrowser extends Component {
dispatch = this.props.dispatch;
// When the component mounts fetch the initial history data for the Safe Deposit Box
componentDidMount() {
if (!this.props.hasFetchedPathsWithHistory) {
this.dispatch(vActions.fetchVersionDataForSdb(this.props.safeDepositBoxId, this.props.cerberusAuthToken));
}
}
handlePageClick = (data) => {
let pageNumber = data.selected;
this.dispatch(vActions.updatePageNumber(pageNumber));
this.dispatch(vActions.fetchPathVersionData(this.props.versionPathSelected, this.props.cerberusAuthToken, pageNumber, this.props.versionPathPerPage));
};
handlePerPageSelect = (selected) => {
let perPage = selected.value;
let pageNumber = 0; // default back to the first page
this.dispatch(vActions.updatePerPage(perPage));
this.dispatch(vActions.updatePageNumber(pageNumber));
this.dispatch(vActions.fetchPathVersionData(this.props.versionPathSelected, this.props.cerberusAuthToken, pageNumber, perPage));
};
handleBreadCrumbHomeClick = () => {
this.dispatch(vActions.handleBreadCrumbHomeClick());
};
handleFetchVersion = (versionId) => {
this.dispatch(vActions.fetchVersionedSecureDataForPath(this.props.versionPathSelected, versionId, this.props.cerberusAuthToken));
};
handleDownloadVersion = (versionId) => {
this.dispatch(vActions.downloadSecureFileVersion(this.props.versionPathSelected, versionId, this.props.cerberusAuthToken));
};
handlePathWithHistoryClick = (path) => {
this.dispatch(vActions.fetchPathVersionData(path, this.props.cerberusAuthToken, this.props.versionPathPageNumber, this.props.versionPathPerPage));
};
render() {
const {
cerberusAuthToken,
hasFetchedPathsWithHistory,
pathsWithHistory,
hasFetchedVersionPathData,
versionPathSelected,
versionPathData,
versionPathPerPage,
versionPathPageNumber,
versionPathSecureDataMap
} = this.props;
const {
handlePerPageSelect,
handlePageClick,
handleBreadCrumbHomeClick,
handleFetchVersion,
handleDownloadVersion,
handlePathWithHistoryClick
} = this;
if (!hasFetchedPathsWithHistory) {
return (
<div className="secure-data-versions-browser">
<Loader />
</div>
);
}
return (
<div className="secure-data-versions-browser">
{!versionPathSelected &&
pathsWithHistoryList(pathsWithHistory, cerberusAuthToken, versionPathPageNumber, versionPathPerPage, handlePathWithHistoryClick)
}
{versionPathSelected &&
pathVersionsBrowser(versionPathSelected, hasFetchedVersionPathData, versionPathData, versionPathPerPage,
versionPathPageNumber, versionPathSecureDataMap, handlePerPageSelect, handlePageClick, handleBreadCrumbHomeClick, handleFetchVersion, handleDownloadVersion)
}
</div>
);
}
}
const pathsWithHistoryList = (pathsWithHistory, cerberusAuthToken, versionPathPageNumber, versionPathPerPage, handlePathWithHistoryClick) => {
return (
<div>
<h3 className="ncss-brand">Paths with version history</h3>
<div className="paths-with-history">
{pathsWithHistory && pathsWithHistory.map((path) =>
<div key={path}
className="path clickable ncss-brand"
onClick={() => { handlePathWithHistoryClick(path); }}>{path}</div>
)}
</div>
</div>
);
};
const pathVersionsBrowser = (versionPathSelected,
hasFetchedVersionPathData,
data,
perPage,
pageNumber,
versionPathSecureDataMap,
handlePerPageSelect,
handlePageClick,
handleBreadCrumbHomeClick,
handleFetchVersion,
handleDownloadVersion) => {
if (!hasFetchedVersionPathData) {
return (<Loader />);
}
return (
<div className="version-list-container">
<h3 className="ncss-brand">Version Summaries for Path: {versionPathSelected}</h3>
<div onClick={() => { handleBreadCrumbHomeClick(); }} className="breadcrumb clickable">Back to path list</div>
{pathVersionsBrowserPaginationMenu(data, perPage, pageNumber, handlePerPageSelect, handlePageClick)}
{summaries(data['secure_data_version_summaries'], handleFetchVersion, handleDownloadVersion, versionPathSecureDataMap)}
{pathVersionsBrowserPaginationMenu(data, perPage, pageNumber, handlePerPageSelect, handlePageClick)}
</div>
);
};
const summaries = (summaries, handleFetchVersion, handleDownloadVersion, versionPathSecureDataMap) => {
return (
<div className="path-version-summaries">
{summaries.map((summary, index) =>
generateVersionSummary(summary, index, handleFetchVersion, handleDownloadVersion, versionPathSecureDataMap).map(it => it)
)}
</div>
);
};
const generateVersionSummary = (summary, index, handleFetchVersion, handleDownloadVersion, versionPathSecureDataMap) => {
if (summary.action === 'DELETE') {
return [
<div className="version-summary" key={`${index}-deleted`}>
<div className="type">Type: {summary['type']}</div>
<div className="id">Version: <span className="deleted">DELETED</span></div>
<div className="principal-wrapper">
Deleted by <span className="principal">{summary['action_principal']}</span> on <span className="date">{new Date(summary['action_ts']).toLocaleString()}</span>
</div>
</div>,
versionSummary(summary, index, handleFetchVersion, handleDownloadVersion, versionPathSecureDataMap)
];
}
return [versionSummary(summary, index, handleFetchVersion, handleDownloadVersion, versionPathSecureDataMap)];
};
const versionSummary = (summary, index, handleFetchVersion, handleDownloadVersion, versionPathSecureDataMap) => {
let versionId = summary.id;
let dataForVersion = versionPathSecureDataMap.hasOwnProperty(versionId) ? versionPathSecureDataMap[versionId] : false;
return (
<div className="version-summary" key={index}>
<div className="id">Version: <span className={versionId === 'CURRENT' ? 'current' : ''}>{summary.id}</span></div>
<div className="type">Type: {summary['type']}</div>
{summary.type === 'FILE' &&
<div className="size-in-bytes">Size: {(summary['size_in_bytes'] / 1024).toFixed(2)} KB</div>
}
<div className="principal-wrapper">
Created by <span className="principal">{summary['version_created_by']}</span> on <span className="date">{new Date(summary['version_created_ts']).toLocaleString()}</span>
</div>
{summary.type === 'FILE' ?
(versionDownloadButton(handleDownloadVersion, versionId))
:
(dataForVersion ? secureDataForVersion(dataForVersion) : fetchVersionButton(handleFetchVersion, versionId))
}
</div>
);
};
const secureDataForVersion = (dataForVersion) => {
return (
<div className="secure-data-for-version-wrapper">
<div className="secure-data-for-version">
<JSONPretty json={dataForVersion} space="4"></JSONPretty>
</div>
</div>
);
};
const fetchVersionButton = (handleFetchVersion, versionId) => {
return (
<div
className='btn ncss-btn-dark-grey ncss-brand pt3-sm pr5-sm pb3-sm pl5-sm pt2-lg pb2-lg u-uppercase'
onClick={() => { handleFetchVersion(versionId); }}
>Show this version</div>
);
};
const versionDownloadButton = (handleDownloadVersion, versionId) => {
return (
<div
className='btn ncss-btn-dark-grey ncss-brand pt3-sm pr5-sm pb3-sm pl5-sm pt2-lg pb2-lg u-uppercase'
onClick={() => { handleDownloadVersion(versionId); }}
>Download</div>
);
};
const pathVersionsBrowserPaginationMenu = (pathData, perPage, pageNumber, handlePerPageSelect, handlePageClick) => {
const options = [
{ value: 5, label: '5' },
{ value: 10, label: '10' },
{ value: 25, label: '25' },
{ value: 50, label: '50' },
{ value: 100, label: '100' }
];
if (pageNumber === 0 && pathData.has_next === false) {
return (<div></div>);
}
let selected = options.find(option => option.value === perPage);
return (
<div className="version-pagination-menu paths-with-history-pagination-menu ncss-brand">
<ReactPaginate pageCount={Math.ceil(pathData.total_version_count / perPage)}
pageRangeDisplayed={3}
marginPagesDisplayed={1}
previousLabel={"Prev"}
nextLabel={"Next"}
onPageChange={handlePageClick}
forcePage={pageNumber}
containerClassName={"version-pagination"}
previousClassName={"version-previous-btn"}
nextClassName={"version-next-btn"}
previousLinkClassName={"ncss-btn-black ncss-brand pt2-sm pr5-sm pb2-sm pl5-sm"}
nextLinkClassName={"ncss-btn-black ncss-brand pt2-sm pr5-sm pb2-sm pl5-sm "}
pageClassName={"page-btn"}
breakClassName={"page-btn ncss-btn-light-grey disabled ncss-brand pt2-sm pr5-sm pb2-sm pl5-sm"}
pageLinkClassName={"ncss-btn-light-grey ncss-brand pt2-sm pr5-sm pb2-sm pl5-sm"}
activeClassName={"version-active"}
/>
<Select
className={'version-pagination-per-page-selector'}
onChange={handlePerPageSelect}
value={selected}
placeholder="Show Per Page"
options={options}
searchable={false}
clearable={false} />
</div>
);
};
const mapStateToProps = state => ({
// current sdb
safeDepositBoxId: state.manageSafetyDepositBox.data.id,
// user info
cerberusAuthToken: state.auth.cerberusAuthToken,
// version state
hasFetchedPathsWithHistory: state.versionHistoryBrowser.hasFetchedPathsWithHistory,
pathsWithHistory: state.versionHistoryBrowser.pathsWithHistory,
hasFetchedVersionPathData: state.versionHistoryBrowser.hasFetchedVersionPathData,
versionPathSelected: state.versionHistoryBrowser.versionPathSelected,
versionPathData: state.versionHistoryBrowser.versionPathData,
versionPathPerPage: state.versionHistoryBrowser.versionPathPerPage,
versionPathPageNumber: state.versionHistoryBrowser.versionPathPageNumber,
versionPathSecureDataMap: state.versionHistoryBrowser.versionPathSecureDataMap
});
export default connect(mapStateToProps)(SecureDataVersionsBrowser); |
actor-apps/app-web/src/app/components/sidebar/HeaderSection.react.js | boneyao/actor-platform | import React from 'react';
import mixpanel from 'utils/Mixpanel';
import MyProfileActions from 'actions/MyProfileActions';
import LoginActionCreators from 'actions/LoginActionCreators';
import AvatarItem from 'components/common/AvatarItem.react';
import MyProfileModal from 'components/modals/MyProfile.react';
import ActorClient from 'utils/ActorClient';
import classNames from 'classnames';
var getStateFromStores = () => {
return {dialogInfo: null};
};
class HeaderSection extends React.Component {
componentWillMount() {
ActorClient.bindUser(ActorClient.getUid(), this.setUser);
}
constructor() {
super();
this.setUser = this.setUser.bind(this);
this.toggleHeaderMenu = this.toggleHeaderMenu.bind(this);
this.openMyProfile = this.openMyProfile.bind(this);
this.setLogout = this.setLogout.bind(this);
this.state = getStateFromStores();
}
setUser(user) {
this.setState({user: user});
}
toggleHeaderMenu() {
mixpanel.track('Open sidebar menu');
this.setState({isOpened: !this.state.isOpened});
}
setLogout() {
LoginActionCreators.setLoggedOut();
}
render() {
var user = this.state.user;
if (user) {
var headerClass = classNames('sidebar__header', 'sidebar__header--clickable', {
'sidebar__header--opened': this.state.isOpened
});
return (
<header className={headerClass}>
<div className="sidebar__header__user row" onClick={this.toggleHeaderMenu}>
<AvatarItem image={user.avatar}
placeholder={user.placeholder}
size="small"
title={user.name} />
<span className="sidebar__header__user__name col-xs">{user.name}</span>
<span className="sidebar__header__user__expand">
<i className="material-icons">keyboard_arrow_down</i>
</span>
</div>
<ul className="sidebar__header__menu">
<li className="sidebar__header__menu__item" onClick={this.openMyProfile}>
<i className="material-icons">person</i>
<span>Profile</span>
</li>
{/*
<li className="sidebar__header__menu__item" onClick={this.openCreateGroup}>
<i className="material-icons">group_add</i>
<span>Create group</span>
</li>
*/}
<li className="sidebar__header__menu__item hide">
<i className="material-icons">cached</i>
<span>Integrations</span>
</li>
<li className="sidebar__header__menu__item hide">
<i className="material-icons">settings</i>
<span>Settings</span>
</li>
<li className="sidebar__header__menu__item hide">
<i className="material-icons">help</i>
<span>Help</span>
</li>
<li className="sidebar__header__menu__item" onClick={this.setLogout}>
<i className="material-icons">power_settings_new</i>
<span>Log out</span>
</li>
</ul>
<MyProfileModal/>
</header>
);
} else {
return null;
}
}
openMyProfile() {
MyProfileActions.modalOpen();
mixpanel.track('My profile open');
this.setState({isOpened: false});
}
}
export default HeaderSection;
|
src/ModalBody.js | andrew-d/react-bootstrap | import React from 'react';
import classnames from 'classnames';
class ModalBody extends React.Component {
render() {
return (
<div {...this.props} className={classnames(this.props.className, this.props.modalClassName)}>
{this.props.children}
</div>
);
}
}
ModalBody.propTypes = {
/**
* A css class applied to the Component
*/
modalClassName: React.PropTypes.string
};
ModalBody.defaultProps = {
modalClassName: 'modal-body'
};
export default ModalBody;
|
wrappers/json.js | lukevance/personal_site | import React from 'react'
module.exports = React.createClass({
propTypes () {
return {
route: React.PropTypes.object,
}
},
render () {
const data = this.props.route.page.data
return (
<div>
<h1>{data.title}</h1>
<p>Raw view of json file</p>
<pre dangerouslySetInnerHTML={{ __html: JSON.stringify(data, null, 4) }} />
</div>
)
},
})
|
lib/ui/components/BottomBar/SearchInput.js | 500tech/mimic | import React from 'react';
import styled from 'styled-components';
import Icon from 'ui/components/common/Icon';
import ActionIcon from 'ui/components/common/ActionIcon';
import IconDropdown from 'ui/components/common/IconDropdown';
import { Div } from 'ui/components/common/base';
import InputControl from 'ui/components/common/InputControl';
const Container = styled(Div)`
width: 300px;
height: 23px;
display: flex;
align-items: center;
border-right: ${(props) => props.theme.lightBorder};
`;
const SearchStyle = {
border: 'none',
height: '19px',
flex: '1',
outline: 'none',
'padding-left': '5px',
'font-size': '13px'
};
class SearchInput extends React.Component {
focusOnField = () => {
if (this.searchInput) {
this.searchInput.select();
}
};
render() {
return (
<Container>
<Icon src="search" onClick={ this.focusOnField }/>
<InputControl
style={ SearchStyle }
value={ this.props.query}
onBlur={ this.props.onBlur }
onFocus={ this.props.onFocus }
onChange={ this.props.onChange }
placeholder="Find"
inputRef={ (node) => this.searchInput = node }/>
{ this.props.query && <ActionIcon action="clear" onClick={ this.props.onClearQuery }/> }
<IconDropdown icon="filter"
value={ this.props.filterValue }
position="right"
align="left"
anchorPoint="bottom"
onChange={ this.props.onFilterChange }
options={ this.props.filterOptions }/>
</Container>
)
}
}
export default SearchInput;
|
sample/components/text-area.js | LINKIWI/react-elemental | import React from 'react';
import { Label, Spacing, Text, TextArea } from 'react-elemental';
const SampleTextArea = () => (
<div>
<Spacing size="huge" bottom>
<Text size="gamma" color="primary" uppercase>
Text areas
</Text>
<Text>
Allow the user to enter an arbitrary-length text blob.
</Text>
</Spacing>
<Spacing size="huge" bottom>
<Spacing bottom>
<Text size="iota" color="gray70" uppercase bold>
Generic
</Text>
</Spacing>
<Label
label="Text area"
sublabel="Type some monospaced text in here."
/>
<TextArea
placeholder="Type away"
style={{
height: '100px',
width: '600px',
}}
/>
</Spacing>
<Spacing size="huge" bottom>
<Spacing bottom>
<Text size="iota" color="gray70" uppercase bold>
Error state
</Text>
</Spacing>
<Label label="Oh noes" />
<TextArea
error="Some error message here"
placeholder="Bad text"
style={{
height: '100px',
width: '600px',
}}
/>
</Spacing>
<Spacing size="huge" bottom>
<Spacing bottom>
<Text size="iota" color="gray70" uppercase bold>
Secondary style
</Text>
</Spacing>
<Label label="Secondary variant" />
<TextArea
placeholder="The secondary style uses an underline border, similar to a secondary TextField"
style={{ width: '600px' }}
secondary
/>
</Spacing>
</div>
);
export default SampleTextArea;
|
src/svg-icons/maps/beenhere.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsBeenhere = (props) => (
<SvgIcon {...props}>
<path d="M19 1H5c-1.1 0-1.99.9-1.99 2L3 15.93c0 .69.35 1.3.88 1.66L12 23l8.11-5.41c.53-.36.88-.97.88-1.66L21 3c0-1.1-.9-2-2-2zm-9 15l-5-5 1.41-1.41L10 13.17l7.59-7.59L19 7l-9 9z"/>
</SvgIcon>
);
MapsBeenhere = pure(MapsBeenhere);
MapsBeenhere.displayName = 'MapsBeenhere';
MapsBeenhere.muiName = 'SvgIcon';
export default MapsBeenhere;
|
src/routes/courses/index.js | fkn/ndo | import React from 'react';
import Layout from '../../components/Layout';
import Courses from './Courses';
import { fetchCourses } from '../../actions/courses';
const title = 'Courses';
async function action({ store }) {
const { user } = store.getState();
if (user) {
await store.dispatch(fetchCourses(user.id));
}
return {
chunks: ['courses'],
title,
component: (
<Layout>
<Courses title={title} />
</Layout>
),
};
}
export default action;
|
src/svg-icons/communication/stay-primary-landscape.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationStayPrimaryLandscape = (props) => (
<SvgIcon {...props}>
<path d="M1.01 7L1 17c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2H3c-1.1 0-1.99.9-1.99 2zM19 7v10H5V7h14z"/>
</SvgIcon>
);
CommunicationStayPrimaryLandscape = pure(CommunicationStayPrimaryLandscape);
CommunicationStayPrimaryLandscape.displayName = 'CommunicationStayPrimaryLandscape';
CommunicationStayPrimaryLandscape.muiName = 'SvgIcon';
export default CommunicationStayPrimaryLandscape;
|
WasteApp/js/components/picker/index.js | airien/workbits |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Platform } from 'react-native';
import { Container, Header, Title, Content, Button, Icon, Picker, Text } from 'native-base';
import { openDrawer } from '../../actions/drawer';
import styles from './styles';
const Item = Picker.Item;
class NHPicker extends Component {
static propTypes = {
openDrawer: React.PropTypes.func,
}
constructor(props) {
super(props);
this.state = {
selectedItem: undefined,
selected1: 'key1',
results: {
items: [],
},
};
}
onValueChange(value: string) {
this.setState({
selected1: value,
});
}
render() {
return (
<Container style={styles.container}>
<Header>
<Title>Picker</Title>
<Button transparent onPress={this.props.openDrawer}>
<Icon name="ios-menu" />
</Button>
</Header>
<Content padder>
<Text>Select your Payment Mode</Text>
<Picker
iosHeader="Select one"
mode="dropdown"
selectedValue={this.state.selected1}
onValueChange={this.onValueChange.bind(this)} // eslint-disable-line
style={{ marginLeft: (Platform.OS === 'android') ? 0 : -25 }}
>
<Item label="Wallet" value="key0" />
<Item label="ATM Card" value="key1" />
<Item label="Debit Card" value="key2" />
<Item label="Credit Card" value="key3" />
<Item label="Net Banking" value="key4" />
</Picker>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
});
export default connect(mapStateToProps, bindAction)(NHPicker);
|
src/svg-icons/av/album.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvAlbum = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 14.5c-2.49 0-4.5-2.01-4.5-4.5S9.51 7.5 12 7.5s4.5 2.01 4.5 4.5-2.01 4.5-4.5 4.5zm0-5.5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1z"/>
</SvgIcon>
);
AvAlbum = pure(AvAlbum);
AvAlbum.displayName = 'AvAlbum';
AvAlbum.muiName = 'SvgIcon';
export default AvAlbum;
|
src/svg-icons/places/hot-tub.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesHotTub = (props) => (
<SvgIcon {...props}>
<circle cx="7" cy="6" r="2"/><path d="M11.15 12c-.31-.22-.59-.46-.82-.72l-1.4-1.55c-.19-.21-.43-.38-.69-.5-.29-.14-.62-.23-.96-.23h-.03C6.01 9 5 10.01 5 11.25V12H2v8c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-8H11.15zM7 20H5v-6h2v6zm4 0H9v-6h2v6zm4 0h-2v-6h2v6zm4 0h-2v-6h2v6zm-.35-14.14l-.07-.07c-.57-.62-.82-1.41-.67-2.2L18 3h-1.89l-.06.43c-.2 1.36.27 2.71 1.3 3.72l.07.06c.57.62.82 1.41.67 2.2l-.11.59h1.91l.06-.43c.21-1.36-.27-2.71-1.3-3.71zm-4 0l-.07-.07c-.57-.62-.82-1.41-.67-2.2L14 3h-1.89l-.06.43c-.2 1.36.27 2.71 1.3 3.72l.07.06c.57.62.82 1.41.67 2.2l-.11.59h1.91l.06-.43c.21-1.36-.27-2.71-1.3-3.71z"/>
</SvgIcon>
);
PlacesHotTub = pure(PlacesHotTub);
PlacesHotTub.displayName = 'PlacesHotTub';
PlacesHotTub.muiName = 'SvgIcon';
export default PlacesHotTub;
|
app/screens/settings/theme/theme_tile.js | mattermost/mattermost-mobile | // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import PropTypes from 'prop-types';
import React from 'react';
import {
Dimensions,
TouchableOpacity,
View,
} from 'react-native';
import CompassIcon from '@components/compass_icon';
import {changeOpacity} from '@mm-redux/utils/theme_utils';
import {makeStyleSheetFromTheme} from '@utils/theme';
import ThemeThumbnail from './theme_thumbnail';
const tilePadding = 8;
const ThemeTile = (props) => {
const {
action,
actionValue,
isLandscape,
isTablet,
label,
selected,
activeTheme,
tileTheme,
} = props;
const style = getStyleSheet(activeTheme);
const labelComponent = React.cloneElement(
label,
{style: style.label},
);
const tilesPerLine = isLandscape || isTablet ? 4 : 2;
const {width: deviceWidth} = Dimensions.get('window');
const fullWidth = isLandscape ? deviceWidth - 40 : deviceWidth;
const layoutStyle = {
container: {
width: (fullWidth / tilesPerLine) - tilePadding,
},
thumbnail: {
width: (fullWidth / tilesPerLine) - (tilePadding + 16),
},
};
return (
<TouchableOpacity
style={[style.container, layoutStyle.container]}
onPress={() => action(actionValue)}
>
<View style={[style.imageWrapper, layoutStyle.thumbnail]}>
<ThemeThumbnail
width={layoutStyle.thumbnail.width}
borderColorBase={selected ? activeTheme.sidebarTextActiveBorder : activeTheme.centerChannelBg}
borderColorMix={selected ? activeTheme.sidebarTextActiveBorder : changeOpacity(activeTheme.centerChannelColor, 0.16)}
sidebarBg={tileTheme.sidebarBg}
sidebarText={changeOpacity(tileTheme.sidebarText, 0.48)}
sidebarUnreadText={tileTheme.sidebarUnreadText}
sidebarTextActiveBorder={activeTheme.sidebarTextActiveBorder}
onlineIndicator={tileTheme.onlineIndicator}
awayIndicator={tileTheme.awayIndicator}
dndIndicator={tileTheme.dndIndicator}
centerChannelColor={changeOpacity(tileTheme.centerChannelColor, 0.16)}
centerChannelBg={tileTheme.centerChannelBg}
newMessageSeparator={tileTheme.newMessageSeparator}
buttonBg={tileTheme.buttonBg}
/>
{selected && (
<CompassIcon
name='check-circle'
size={31.2}
style={style.check}
/>
)}
</View>
{labelComponent}
</TouchableOpacity>
);
};
ThemeTile.propTypes = {
action: PropTypes.func,
actionValue: PropTypes.string,
isLandscape: PropTypes.bool.isRequired,
isTablet: PropTypes.bool.isRequired,
label: PropTypes.node.isRequired,
selected: PropTypes.bool,
activeTheme: PropTypes.object.isRequired,
tileTheme: PropTypes.object.isRequired,
};
ThemeTile.defaultProps = {
action: () => true,
};
const getStyleSheet = makeStyleSheetFromTheme((theme) => {
return {
container: {
flexDirection: 'column',
padding: tilePadding,
marginTop: 8,
},
imageWrapper: {
position: 'relative',
alignItems: 'flex-start',
marginBottom: 12,
},
thumbnail: {
resizeMode: 'stretch',
},
check: {
position: 'absolute',
right: 5,
bottom: 5,
color: theme.sidebarTextActiveBorder,
},
label: {
color: theme.centerChannelColor,
fontSize: 15,
},
};
});
export default ThemeTile;
|
src/components/Portfolio/Portfolio.js | karim88/karim88.github.io | import React, { Component } from 'react';
import './Portfolio.css';
class Portfolio extends Component {
constructor (props) {
super(props);
this.portfolio = props.portfolio.map((project) => {
return <div key={project.id} className="col-md-3 col-lg-4">
<div className="card-img" style={{
backgroundImage: `url(${project.image})`,
backgroundPosition: 'center'
}}>
<div className="technologie-shape"/>
<div className="technologie wow zoomIn">{project.technologie}</div>
<div className="layer">
<a href={project.link} aria-label={`link to ${project.link}`} target="_blank" rel="noopener noreferrer">
<i className="fas fa-link fa-3x link-icon"></i>
</a>
</div>
</div>
</div>
});
}
render() {
return (
<div className="portfolio">
<h2>PORTFOLIO</h2>
<div className="row">
{this.portfolio}
</div>
</div>
);
}
}
export default Portfolio;
|
src/app.js | beaudavenport/regex-cafe | import React from 'react';
import ReactDOM from 'react-dom';
import lessons from './lessons';
import Lesson from './Lesson';
import Navbar from './Navbar';
import Introduction from './Introduction';
import Faq from './Faq';
class App extends React.Component {
render() {
let lessonsOutput = this.props.lessons.map((lesson) => {
return (<Lesson key={`lesson${lesson.number}`} lesson={lesson} />);
});
return (
<div>
<Navbar />
<div className="container">
<Introduction />
</div>
<div className="container lessons">
{lessonsOutput}
</div>
<div className="container">
<Faq />
</div>
</div>
);
}
}
ReactDOM.render(<App lessons={lessons} />, document.getElementById('content'));
|
src/svg-icons/device/battery-charging-60.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBatteryCharging60 = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V11h3.87L13 7v4h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9l1.87-3.5H7v9.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V11h-4v1.5z"/>
</SvgIcon>
);
DeviceBatteryCharging60 = pure(DeviceBatteryCharging60);
DeviceBatteryCharging60.displayName = 'DeviceBatteryCharging60';
DeviceBatteryCharging60.muiName = 'SvgIcon';
export default DeviceBatteryCharging60;
|
src/components/button/button.js | thinktopography/reframe | import React from 'react'
import PropTypes from 'prop-types'
class Button extends React.Component {
static contextTypes = {
confirm: PropTypes.object,
drawer: PropTypes.object,
flash: PropTypes.object,
modal: PropTypes.object,
router: PropTypes.object
}
static propTypes = {
basic: PropTypes.bool,
className: PropTypes.string,
color: PropTypes.string,
component: PropTypes.any,
confirm: PropTypes.any,
children: PropTypes.any,
disabled: PropTypes.bool,
drawer: PropTypes.any,
error: PropTypes.string,
location: PropTypes.string,
handler: PropTypes.func,
icon: PropTypes.string,
label: PropTypes.string,
link: PropTypes.string,
mobile: PropTypes.bool,
modal: PropTypes.oneOfType([
PropTypes.element,
PropTypes.func
]),
request: PropTypes.shape({
method: PropTypes.string,
endpoint: PropTypes.string,
onFailure: PropTypes.func,
onSuccess: PropTypes.func
}),
route: PropTypes.string,
status: PropTypes.string,
text: PropTypes.string,
onDone: PropTypes.func,
onRequest: PropTypes.func
}
static defaultProps = {
basic: false,
mobile: true,
disabled: false,
onDone: () => {}
}
render() {
const { children, component, icon, label, text } = this.props
return (
<div { ...this._getButton() }>
{ icon && <i className={`fa fa-fw fa-${icon}`} /> }
{ label || text || children }
{ component }
</div>
)
}
_getButton() {
const { disabled, link } = this.props
return {
href: link ? link : null,
className: this._getClass(),
disabled,
target: link ? '_blank' : null,
onClick: !link ? this._handleClick.bind(this) : null
}
}
_getClass() {
const { component, basic, className, color, disabled, mobile, status } = this.props
if(component) return ''
const classes = className ? className.split(' ') : ['ui', color, 'fluid', 'button']
classes.push('reframe-button')
if(mobile !== false) classes.push('mobile')
if(basic) classes.push('basic')
if(disabled) classes.push('disabled')
if(status === 'submitting') classes.push('loading')
return classes.join(' ')
}
componentDidUpdate(prevProps) {
const { flash } = this.context
const { error, status } = this.props
if(prevProps.status !== status && status === 'failure') {
flash.set('error', error)
}
}
_handleClick() {
const { confirm, disabled, drawer, handler, location, modal, request, route, onDone } = this.props
if(disabled) return
const yesHandler = () => {
if(route) this._handleRoute(route)
if(request) this._handleRequest(request)
if(modal) this._handleModal(modal)
if(drawer) this._handleDrawer(drawer, location)
if(handler) this._handleFunction(handler)
}
onDone()
if(confirm) return this.context.confirm.open(confirm, yesHandler)
yesHandler()
}
_handleRoute(route) {
this.context.router.push(route)
}
_handleModal(component) {
this.context.modal.open(component)
}
_handleDrawer(component, location) {
this.context.drawer.open(component, location)
}
_handleFunction(handler) {
handler(() => {})
}
_handleRequest(itemRequest) {
const { onRequest } = this.props
onRequest({
...itemRequest,
body: null,
params: null
})
}
}
export default Button
|
src/app/components/forms/inputs/UiSlider.js | backpackcoder/world-in-flames | import React from 'react'
import 'script-loader!bootstrap-slider/dist/bootstrap-slider.min.js'
export default class UiSlider extends React.Component {
componentDidMount() {
$(this.refs.slider).bootstrapSlider();
}
render() {
return <input type="text" ref="slider" {...this.props} />
}
} |
src/modules/components/WaveShapeSelector/index.js | ruebel/synth-react-redux | import React from 'react';
import PropTypes from 'prop-types';
import Select from '../Select';
import { waveShapes } from '../../../utils/audio';
const WaveShapeSelector = ({ value, change }) => {
const options = waveShapes.map(s => ({ id: s, name: s }));
return (
<div>
<Select
labelKey="name"
onChange={e => change(e.id)}
options={options}
searchable={false}
title="Shape"
value={value}
valueKey="id"
/>
</div>
);
};
WaveShapeSelector.propTypes = {
value: PropTypes.string,
change: PropTypes.func.isRequired
};
export default WaveShapeSelector;
|
docs/src/pages/StartPage.js | gocreating/react-tocas | import React from 'react';
import PageLayout from '../utils/PageLayout';
import CodeBlock from '../utils/CodeBlock';
import {
Segment,
Header,
} from '../../../lib';
import 'codemirror/mode/htmlmixed/htmlmixed';
import 'codemirror/mode/jsx/jsx';
import 'codemirror/theme/solarized.css';
let JSX_DEMO = `import Button from 'react-tocas/lib/Button';
// or this way:
// import { Button } from 'react-tocas';
let App = () => (
<div>
<Button info onClick={() => alert('World')}>
Hello
</Button>
</div>
);`;
let StartPage = () => (
<PageLayout>
<Segment borderless basic>
<Header level={1}>
Installation
</Header>
<Header huge>
Install react-tocas from npm.
</Header>
<CodeBlock
theme="solarized light"
readOnly
lineNumbers
>
{'npm install --save react-tocas'}
</CodeBlock>
</Segment>
<Segment borderless basic>
<Header level={1}>
Usage
</Header>
<Header huge>
Import css file from CDN.
</Header>
<CodeBlock
mode="htmlmixed"
theme="solarized light"
readOnly
lineNumbers
>
{'<link rel="stylesheet" href="//cdn.rawgit.com/TeaMeow/TocasUI/master/dist/tocas.min.css">'}
</CodeBlock>
<Header huge>
Start using great react components.
</Header>
<CodeBlock
mode="jsx"
theme="solarized light"
readOnly
lineNumbers
>
{JSX_DEMO}
</CodeBlock>
</Segment>
</PageLayout>
);
export default StartPage;
|
scr-app/src/redux/devtools/showDevTools.js | tlatoza/SeeCodeRun | import React from 'react';
import {render} from 'react-dom';
import DevTools from './DevTools';
/**
* Renders Redux Dev tools
* @param {Object} store - the Redux store to be debugged.
* @return {number} - The timeout id in case of cancellation.
*/
export default function showDevTools(store) {
return setTimeout(() => {
const devtoolsDiv = document.createElement('div');
devtoolsDiv.id = 'react-devtools-root';
document.body.appendChild(devtoolsDiv);
render(
<DevTools store={store}/>,
document.querySelector('#react-devtools-root')
);
}, 100);
}
|
src/components/containers/article-container.js | mberneti/ReactAdmin | import React from 'react';
import { connect } from 'react-redux';
import Article from '../views/article';
import store from '../../store';
import { loadDashboardCompleted } from '../../actions/dashboard-actions';
import { resetArticleModel } from '../../actions/article-actions';
import * as articleApi from '../../api/article-api';
class ArticleContainer extends React.Component {
componentDidMount() {
let _current = this;
this.type = this.props.route.title; //this is the name of the route
if (this.props.route.isEditRoute) {
let id = this.props.params.itemId;
//fetch tags list from api
articleApi.getTags().then(function () {
//fetch registered article data from api
articleApi.getArticle(id);
});
} else {
//fetch tags list
articleApi.getTags();
}
}
componentDidUpdate(prevProps) {
if(!this.props.isLoaded && !this.props.route.isEditRoute){
this.refs.child.clearFiles();
store.dispatch(resetArticleModel());
store.dispatch(loadDashboardCompleted());
}
}
submit() {
event.preventDefault();
let data = this.refs.child.getData();
console.log(data);
// articleApi.addOrUpdate(data);
}
render() {
return (
<Article submitHandler={this.submit} article={this.props.article} suggestions={this.props.suggestions} ref="child" />
);
}
};
const mapStateToProps = store => {
return {
isLoaded: store.dashboardLayoutState.isLoaded,
article: store.articleState.article,
suggestions: store.articleState.suggestions
};
};
export default connect(mapStateToProps)(ArticleContainer);
|
webapp/src/App.js | gcallah/Indra | import React from 'react';
import { HashRouter, Route, Switch } from 'react-router-dom';
import styled, { withTheme } from 'styled-components';
import Layout from './components/Layout';
import Home from './components/Home';
import WIP from './components/WIP';
import ModelDetail from './components/ModelDetail';
import ActionMenu from './components/ActionMenu';
import NotFoundPage from './components/NotFoundPage';
import ErrorCatching from './components/ErrorCatching';
const Wrapper = styled('div')`
background: ${(props) => props.theme.background};
width: 100vw;
min-height: 100vh;
font-family: -apple-stem, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen";
h1 {
color: ${(props) => props.theme.body};
}
`;
function App() {
return (
<Wrapper>
<HashRouter>
<Layout>
<IndraRoutes />
</Layout>
</HashRouter>
</Wrapper>
);
}
export function IndraRoutes() {
return (
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/wip" component={WIP} />
<Route exact path="/models/props/:id" component={ModelDetail} />
<Route exact path="/models/menu/:id" component={ActionMenu} />
<Route exact path="/errorCatching" component={ErrorCatching} />
<Route component={NotFoundPage} />
</Switch>
);
}
export default withTheme(App);
|
src/svg-icons/notification/wc.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationWc = (props) => (
<SvgIcon {...props}>
<path d="M5.5 22v-7.5H4V9c0-1.1.9-2 2-2h3c1.1 0 2 .9 2 2v5.5H9.5V22h-4zM18 22v-6h3l-2.54-7.63C18.18 7.55 17.42 7 16.56 7h-.12c-.86 0-1.63.55-1.9 1.37L12 16h3v6h3zM7.5 6c1.11 0 2-.89 2-2s-.89-2-2-2-2 .89-2 2 .89 2 2 2zm9 0c1.11 0 2-.89 2-2s-.89-2-2-2-2 .89-2 2 .89 2 2 2z"/>
</SvgIcon>
);
NotificationWc = pure(NotificationWc);
NotificationWc.displayName = 'NotificationWc';
NotificationWc.muiName = 'SvgIcon';
export default NotificationWc;
|
src/components/footer.js | jennywin/donate-for-good | import React, { Component } from 'react';
export default class Footer extends Component {
render() {
return (
<footer className="footer">
</footer>
);
}
}
|
app/components/TabContainer/index.js | JSSolutions/Perfi | import React from 'react';
import T from 'prop-types';
import { StyleSheet, View } from 'react-native';
const s = StyleSheet.create({
container: {
position: 'absolute',
top: 0,
bottom: 0,
},
show: {
left: 0,
right: 0,
},
hide: {
left: 90000, // over the screen,
right: -90000, // over the screen,
},
});
const TabContainer = ({
selectedTabIndex,
tabIndex,
children,
topOffset,
}) => (
<View
style={[
s.container,
topOffset && { top: topOffset },
selectedTabIndex === tabIndex
? s.show
: s.hide,
]}
>
{children}
</View>
);
TabContainer.propTypes = {
selectedTabIndex: T.number,
tabIndex: T.number,
topOffset: T.number,
children: T.element,
};
export default TabContainer;
|
app/main.js | wvicioso/dapr | import React, { Component } from 'react';
import {
Navigator,
StyleSheet,
Text,
TextInput,
ScrollView,
TouchableOpacity,
View,
Image,
ListView,
LayoutAnimation
} from 'react-native';
const Carousel = require('react-native-carousel');
const SideMenu = require('react-native-side-menu');
import Day from './day';
import Dress from './dress';
import OverlayInfo from './overlay_info';
import Forcast from './forcast';
import Details from './details';
export default class Application extends React.Component {
constructor() {
super();
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows([]),
temp: [],
cond: [],
city: '',
wind: '',
icon: '',
}
}
navigate(routeName) {
this.props.navigator.push({
name : routeName
})
}
componentWillMount() {
// Animate creation
LayoutAnimation.linear();
}
componentDidMount() {
fetch("http://api.wunderground.com/api/ae341c3c3cc0ff78/forecast10day/q/NY/New_York_City.json", {
method: 'get'
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
if (responseJson !== null) {
var temp_arr = []
for(i = 0; i < 8; i++ ) {
temp_arr.push(responseJson.forecast.simpleforecast.forecastday[i].high.fahrenheit)
}
var cond = responseJson.forecast.simpleforecast.forecastday[0].conditions
var icon = responseJson.forecast.simpleforecast.forecastday[0].icon_url
var city = responseJson.location.city
this.setWeather(temp_arr, cond, icon, city)
}
})
.catch((error) => {
throw new Error(error)
})
}
setWeather(temp, cond, icon, city){
this.setState({
temp: temp,
cond: cond,
icon: icon,
city: city,
})
}
render() {
return (
<View style={{ flex: 1 }} >
<View style={{ marginBottom: 20 }}>
</View>
<Dress />
<Forcast />
<View style={{position: 'absolute', top: 130, left: 20}}>
<Text style=
{{
color: "black",
fontSize: 40,
backgroundColor: 'transparent',
}}>
65°
</Text>
</View>
<Details />
<View style={{position: 'absolute', top: 300, left: 20}}>
<TouchableOpacity>
<Text style={{
color: 'white',
fontSize: 20,
backgroundColor: 'transparent',
textAlign: 'center',
}}>
-
</Text>
</TouchableOpacity>
</View>
<View style={{position: 'absolute', top: 300, right: 20}}>
<TouchableOpacity>
<Text style={{
color: 'white',
fontSize: 20,
backgroundColor: 'transparent',
textAlign: 'center',
}}>
-
</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
width: 100,
backgroundColor: 'transparent',
},
});
|
client/src/containers/CategoryPage/CategoryDetail/index.js | steThera/react-mobx-koa | import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import { SlideLeftTransition } from 'components/RouteTransition';
import { mode } from 'components/FormMobx/utils';
import { getCategory, updateCategory } from '../DetailForm/actions';
import DetailForm from '../DetailForm';
class CategoryDetail extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const { code } = this.props.params;
if (code) {
getCategory(code);
}
}
render() {
const { code } = this.props.params;
return (
<SlideLeftTransition
pathname="CategoryDetail"
>
<section className="content">
<DetailForm
mode={mode.EDIT}
onSubmit={(data) => updateCategory({...data, code})}
/>
</section>
</SlideLeftTransition>
)
}
}
export default CategoryDetail; |
src/icons/BlurOffIcon.js | kiloe/ui | import React from 'react';
import Icon from '../Icon';
export default class BlurOffIcon extends Icon {
getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M28 14c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-.4 8.96c.13.02.26.04.4.04 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .14.02.27.04.41.18 1.32 1.23 2.37 2.56 2.55zM28 7c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm-8 0c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm22 14c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm-22-7c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm16 16c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0-8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0-8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-8 27c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zM5 10.55l7.57 7.57c-.19-.06-.37-.12-.57-.12-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2c0-.2-.06-.38-.11-.57l5.62 5.62C18.08 25.29 17 26.51 17 28c0 1.66 1.34 3 3 3 1.49 0 2.71-1.08 2.95-2.5l5.62 5.62c-.18-.06-.37-.12-.57-.12-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2c0-.2-.06-.38-.11-.57L37.45 43 40 40.45 7.55 8 5 10.55zM20 34c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm22-7c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm-30-1c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6-7c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm14 22c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm-8-7c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6-7c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1z"/></svg>;}
}; |
src/svg-icons/image/crop-7-5.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCrop75 = (props) => (
<SvgIcon {...props}>
<path d="M19 7H5c-1.1 0-2 .9-2 2v6c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zm0 8H5V9h14v6z"/>
</SvgIcon>
);
ImageCrop75 = pure(ImageCrop75);
ImageCrop75.displayName = 'ImageCrop75';
ImageCrop75.muiName = 'SvgIcon';
export default ImageCrop75;
|
js/components/loaders/ProgressBar.android.js | phamngoclinh/PetOnline_vs2 | /* @flow */
import React from 'react';
import ProgressBarAndroid from 'react-native';
import NativeBaseComponent from 'native-base/Components/Base/NativeBaseComponent';
import computeProps from 'native-base/Utils/computeProps';
export default class SpinnerNB extends NativeBaseComponent {
prepareRootProps() {
const type = {
height: 40,
};
const defaultProps = {
style: type,
};
return computeProps(this.props, defaultProps);
}
render() {
const getColor = () => {
if (this.props.color) {
return this.props.color;
} else if (this.props.inverse) {
return this.getTheme().inverseProgressColor;
}
return this.getTheme().defaultProgressColor;
};
return (
<ProgressBarAndroid
{...this.prepareRootProps()}
styleAttr="Horizontal"
indeterminate={false}
progress={this.props.progress ? this.props.progress / 100 : 0.5}
color={getColor()}
/>
);
}
}
|
code/workspaces/web-app/src/components/common/ConfirmDialog.js | NERC-CEH/datalab | import React from 'react';
import PropTypes from 'prop-types';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContent from '@material-ui/core/DialogContent';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContentText from '@material-ui/core/DialogContentText';
import PrimaryActionButton from './buttons/PrimaryActionButton';
import SecondaryActionButton from './buttons/SecondaryActionButton';
import theme from '../../theme';
function ConfirmDialog({ state, onSubmit, title, body, onCancel }) {
if (!state.open) return null;
return (
<Dialog open={state.open} maxWidth="md">
<DialogTitle>{title}</DialogTitle>
<DialogContent>
<DialogContentText>{body}</DialogContentText>
</DialogContent>
<DialogActions>
<PrimaryActionButton
onClick={onSubmit}
>
Confirm
</PrimaryActionButton>
<SecondaryActionButton
style={{ marginLeft: theme.spacing(1) }}
onClick={onCancel}
>
Cancel
</SecondaryActionButton>
</DialogActions>
</Dialog>
);
}
ConfirmDialog.propTypes = {
onSubmit: PropTypes.func.isRequired,
onCancel: PropTypes.func.isRequired,
state: PropTypes.object.isRequired,
title: PropTypes.string.isRequired,
body: PropTypes.string.isRequired,
};
export default ConfirmDialog;
|
src/main.js | idealgardens/codeword | import React from 'react'
import ReactDOM from 'react-dom'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import { useRouterHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
import createStore from './store/createStore'
import AppContainer from './containers/AppContainer'
// ========================================================
// Browser History Setup
// ========================================================
const browserHistory = useRouterHistory(createBrowserHistory)({
basename: __BASENAME__
})
// ========================================================
// Store and History Instantiation
// ========================================================
// Create redux store and sync with react-router-redux. We have installed the
// react-router-redux reducer under the routerKey "router" in src/routes/index.js,
// so we need to provide a custom `selectLocationState` to inform
// react-router-redux of its location.
const initialState = window.___INITIAL_STATE__
const store = createStore(initialState, browserHistory)
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: (state) => state.router
})
// ========================================================
// Developer Tools Setup
// ========================================================
if (__DEBUG__) {
if (window.devToolsExtension) {
window.devToolsExtension.open()
}
}
// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('root')
let render = (routerKey = null) => {
const routes = require('./routes').default(store)
ReactDOM.render(
<AppContainer
store={store}
history={history}
routes={routes}
routerKey={routerKey}
/>,
MOUNT_NODE
)
}
// Enable HMR and catch runtime errors in RedBox
// This code is excluded from production bundle
// if (__DEV__ && module.hot) {
// const renderApp = render
// const renderError = (error) => {
// const RedBox = require('redbox-react')
//
// ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
// }
// render = () => {
// try {
// renderApp(Math.random())
// } catch (error) {
// renderError(error)
// }
// }
// module.hot.accept(['./routes'], () => render())
// }
// ========================================================
// Go!
// ========================================================
render()
|
src/data-table/DataTable.js | Synchro-TEC/apollo-11 | import React from 'react';
import PropTypes from 'prop-types';
import DataTableBody from './data-table-body/DataTableBody';
import DataTableHeader from './data-table-header/DataTableHeader';
class DataTable extends React.Component {
constructor(props) {
super(props);
this.keys = React.Children.map(props.children, child => {
return child.props.dataKey;
});
}
render() {
let { children, className, data, onSort } = this.props;
return (
<div className="sv-table-responsive-vertical">
<table className={className}>
<DataTableHeader onSort={onSort}>{children}</DataTableHeader>
<DataTableBody dataTableHeader={this.keys} dataTableRows={data} />
</table>
</div>
);
}
}
DataTable.defaultProps = {
className: 'sv-table with--hover with--borders',
};
DataTable.propTypes = {
className: PropTypes.string,
data: PropTypes.array.isRequired,
onSort: PropTypes.func,
};
DataTable.displayName = 'DataTable';
export default DataTable;
|
cuttlebelle/code/listPosts.js | staystatic/staystatic | import PropTypes from 'prop-types';
import React from 'react';
/**
* The listing posts component
*/
const ListPosts = ({ title, _pages, _relativeURL, _ID }) => (
<div>
<b>{ title }</b>
<ul className="news">
{
Object.keys( _pages )
.filter( page => _pages[ page ]._url.startsWith('/posts/') )
.sort( ( a, b ) => new Date( _pages[ b ].date ) - new Date( _pages[ a ].date ) )
.map( ( page, i ) =>
<li key={ i }>
<a href={ _relativeURL( _pages[ page ]._url, _ID ) }>{ _pages[ page ].pagetitle }</a>
</li>
)
}
</ul>
</div>
);
ListPosts.propTypes = {
/**
* title: "News 'n' Updates"
*/
title: PropTypes.string.isRequired,
};
ListPosts.defaultProps = {};
export default ListPosts;
|
resources/assets/javascript/components/plantsViewPage.js | colinjeanne/garden | import PlantList from './plantList';
import PlantListAddBox from './plantListAddBox';
import PlantView from './plantView';
import React from 'react';
const plantsViewPage = props => {
let plantView;
if (props.selectedPlant) {
plantView = (
<PlantView
plant={props.selectedPlant}
editing={props.editing}
onEdit={editing => props.onEdit(editing, props.selectedPlant)}
onUpdatePlant={props.onUpdatePlant} />
);
}
return (
<div id="content" className="plantsViewPage">
<div className="plantsViewSidebar">
<PlantListAddBox
onAdd={props.onAddPlant} />
<PlantList
onFilterPlants={props.onFilterPlants}
onSelectPlant={props.onSelectPlant}
onSortPlants={props.onSortPlants}
plants={props.plants}
visiblePlantNames={props.visiblePlantNames} />
</div>
{plantView}
</div>
);
};
plantsViewPage.propTypes = {
editing: React.PropTypes.bool.isRequired,
onAddPlant: React.PropTypes.func.isRequired,
onEdit: React.PropTypes.func.isRequired,
onFilterPlants: React.PropTypes.func.isRequired,
onSelectPlant: React.PropTypes.func.isRequired,
onSortPlants: React.PropTypes.func.isRequired,
onUpdatePlant: React.PropTypes.func.isRequired,
plants: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
selectedPlant: React.PropTypes.object,
visiblePlantNames: React.PropTypes.arrayOf(
React.PropTypes.string).isRequired
};
export default plantsViewPage; |
examples/with-jsxstyle/src/Home.js | jaredpalmer/razzle | import { Block, InlineBlock } from 'jsxstyle';
import React, { Component } from 'react';
class Home extends Component {
render() {
return (
<Block textAlign="center">
<Block backgroundColor="#222">
<Block fontSize="3rem" color="#fff" padding="6rem 0" fontWeight="800">
Razzle x JSXStyle
</Block>
</Block>
<Block margin="4rem auto">
<Block>
To get started, edit <code>src/App.js</code> or{' '}
<code>src/Home.js</code> and save to reload.
</Block>
<Block component="ul" margin="2rem auto">
<InlineBlock component="li" marginRight="1rem">
<a href="https://github.com/jaredpalmer/razzle">Docs</a>
</InlineBlock>
<InlineBlock component="li" marginRight="1rem">
<a href="https://github.com/jaredpalmer/razzle/issues">Issues</a>
</InlineBlock>
<InlineBlock component="li">
<a href="https://palmer.chat">Community Slack</a>
</InlineBlock>
</Block>
</Block>
</Block>
);
}
}
export default Home;
|
code/web/node_modules/react-bootstrap/es/FormControlStatic.js | zyxcambridge/RecordExistence | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import elementType from 'react-prop-types/lib/elementType';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
componentClass: elementType
};
var defaultProps = {
componentClass: 'p'
};
var FormControlStatic = function (_React$Component) {
_inherits(FormControlStatic, _React$Component);
function FormControlStatic() {
_classCallCheck(this, FormControlStatic);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
FormControlStatic.prototype.render = function render() {
var _props = this.props;
var Component = _props.componentClass;
var className = _props.className;
var props = _objectWithoutProperties(_props, ['componentClass', 'className']);
var _splitBsProps = splitBsProps(props);
var bsProps = _splitBsProps[0];
var elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement(Component, _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return FormControlStatic;
}(React.Component);
FormControlStatic.propTypes = propTypes;
FormControlStatic.defaultProps = defaultProps;
export default bsClass('form-control-static', FormControlStatic); |
src/index.js | koden-km/sc-react-redux | import SC from 'soundcloud';
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { Provider } from 'react-redux';
import configureStore from './stores/configureStore';
import App from './components/App';
import Callback from './components/Callback';
import Stream from './components/Stream';
import { CLIENT_ID, REDIRECT_URI } from './constants/auth';
SC.initialize({ client_id: CLIENT_ID, redirect_uri: REDIRECT_URI });
const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store);
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Stream} />
<Route path="/" component={Stream} />
<Route path="/callback" component={Callback} />
</Route>
</Router>
</Provider>,
document.getElementById('app')
);
|
src/ui/Item.js | touchstonejs/touchstonejs | import blacklist from 'blacklist';
import classnames from 'classnames';
import React from 'react';
module.exports = React.createClass({
displayName: 'Item',
propTypes: {
children: React.PropTypes.node.isRequired,
component: React.PropTypes.any,
className: React.PropTypes.string,
showDisclosureArrow: React.PropTypes.bool
},
getDefaultProps () {
return {
component: 'div'
};
},
render () {
var componentClass = classnames('Item', {
'Item--has-disclosure-arrow': this.props.showDisclosureArrow
}, this.props.className);
var props = blacklist(this.props, 'children', 'className', 'showDisclosureArrow');
props.className = componentClass;
return React.createElement(
this.props.component,
props,
this.props.children
);
}
});
|
node_modules/semantic-ui-react/dist/es/elements/Label/LabelDetail.js | mowbell/clickdelivery-fed-test | import _extends from 'babel-runtime/helpers/extends';
import _isNil from 'lodash/isNil';
import cx from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { customPropTypes, getElementType, getUnhandledProps, META } from '../../lib';
function LabelDetail(props) {
var children = props.children,
className = props.className,
content = props.content;
var classes = cx('detail', className);
var rest = getUnhandledProps(LabelDetail, props);
var ElementType = getElementType(LabelDetail, props);
return React.createElement(
ElementType,
_extends({}, rest, { className: classes }),
_isNil(children) ? content : children
);
}
LabelDetail.handledProps = ['as', 'children', 'className', 'content'];
LabelDetail._meta = {
name: 'LabelDetail',
parent: 'Label',
type: META.TYPES.ELEMENT
};
process.env.NODE_ENV !== "production" ? LabelDetail.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand
} : void 0;
export default LabelDetail; |
src/components/home/Home.js | uxlayouts/spidermonkey | import React from 'react'
const Home = () => (
<div className="container-fluid padding-top-3 padding-bottom-3">
<h2>Home</h2>
</div>
)
export default Home
|
dist/frontend/app.js | angeloocana/freecomclub | import React from 'react';
import ReactDOM from 'react-dom';
import Relay from 'react-relay';
import UserReport from './users/components/UserReport';
console.log('Hello app.tsx');
class HomeRoute extends Relay.Route {
}
HomeRoute.routeName = 'Home';
HomeRoute.queries = {
store: (Component) => Relay.QL `
query MainQuery{
store {
${Component.getFragment('store')}
}
}
`
};
ReactDOM.render(React.createElement(Relay.RootContainer, { Component: UserReport, route: new HomeRoute() }), document.getElementById('react'));
|
src/components/result.js | ShaneFairweather/React-iTunes | import React, { Component } from 'react';
const Result = (props) => {
function parseTime(milliseconds) {
var minutes = Math.floor(milliseconds / 60000);
var seconds = ((milliseconds % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}
return (
<div className="result" onClick={() => props.onItemSelect(props)}>
<div className="itunesButton">
<button>View on iTunes.com</button>
</div>
<div className="resultImg">
<img src={props.imageUrl} />
<div className="clearBox"></div>
</div>
<div className="resultInfo">
<h3>{props.trackName}</h3>
<h5>{props.artistName}</h5>
{/*<p className="price">${props.trackPrice}</p>*/}
<p className="runTime">{parseTime(props.trackTime)}</p>
<p>{props.releaseDate.slice(0, 4)}</p>
</div>
</div>
)
}
export default Result; |
src/parser/shared/modules/features/BaseHealerStatValues.js | FaideWW/WoWAnalyzer | import React from 'react';
import InformationIcon from 'interface/icons/Information';
import SPELLS from 'common/SPELLS/index';
import { formatNumber } from 'common/format';
import { calculatePrimaryStat, calculateSecondaryStatDefault } from 'common/stats';
import Analyzer from 'parser/core/Analyzer';
import HIT_TYPES from 'game/HIT_TYPES';
import HealingValue from 'parser/shared/modules/HealingValue';
import DamageValue from 'parser/shared/modules/DamageValue';
import CritEffectBonus from 'parser/shared/modules/helpers/CritEffectBonus';
import StatTracker from 'parser/shared/modules/StatTracker';
import { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import StatisticWrapper from 'interface/others/StatisticWrapper';
import CORE_SPELL_INFO from './SpellInfo';
import STAT, { getClassNameColor, getIcon, getName } from './STAT';
const DEBUG = false;
// 5% int bonus from wearing all of the highest armor rating (Leather, Mail, Plate) means each new point of int worth 1.05 vs character sheet int
export const ARMOR_INT_BONUS = .05;
/**
* This is currently completely focussed on Healer stat weights but it should be relatively easy to modify it to work for a DPS, it just requires some work. The only reason no effort was put towards this is that we currently have no DPS interested in implementing this so it would be wasted time. If you do want to implement stat weights for a DPS this should provide you with a very good basis.
* @property {CritEffectBonus} critEffectBonus
* @property {StatTracker} statTracker
*/
class BaseHealerStatValues extends Analyzer {
static dependencies = {
critEffectBonus: CritEffectBonus,
statTracker: StatTracker,
};
// region Spell info
// We assume unlisted spells scale with vers only (this will mostly be trinkets)
fallbackSpellInfo = {
int: false,
crit: true,
hasteHpm: false,
hasteHpct: false,
mastery: false,
vers: true,
};
// This will contain shared settings for things like trinkets and Leech
sharedSpellInfo = CORE_SPELL_INFO;
// This is for spec specific implementations to override. It gets priority over defaultSpellInfo.
spellInfo = {};
mentioned = [];
_getSpellInfo(event) {
const spellId = event.ability.guid;
const specSpecific = this.spellInfo[spellId];
if (specSpecific) {
return specSpecific;
}
const shared = this.sharedSpellInfo[spellId];
if (shared) {
return shared;
}
if (process.env.NODE_ENV === 'development') {
if (!this.mentioned.includes(spellId)) {
console.warn(`Missing spell definition: ${spellId}: ${event.ability.name}, using fallback:`, this.fallbackSpellInfo);
this.mentioned.push(spellId);
}
}
return this.fallbackSpellInfo;
}
// endregion
totalAdjustedHealing = 0; // total healing after excluding 'multiplier' spells like Leech / Velens
// These are the total healing that would be gained if their respective stats ratings were increased by one.
totalOneInt = 0;
totalOneCrit = 0;
totalOneHasteHpct = 0;
totalOneHasteHpm = 0;
totalOneMastery = 0;
totalOneVers = 0; // from healing increase only
totalOneVersDr = 0; // from damage reduced only
totalOneLeech = 0;
playerHealthMissing = 0;
scaleWeightsWithHealth = false;
on_heal(event) {
if (this.owner.byPlayer(event) || this.owner.byPlayerPet(event)) {
const healVal = new HealingValue(event.amount, event.absorbed, event.overheal);
this._handleHealEvent(event, healVal);
}
}
on_absorbed(event) {
if (this.owner.byPlayer(event) || this.owner.byPlayerPet(event)) {
const healVal = new HealingValue(event.amount, 0, 0);
this._handleHealEvent(event, healVal);
}
}
on_removebuff(event) {
if (this.owner.byPlayer(event) || this.owner.byPlayerPet(event)) {
if (event.absorb) {
const healVal = new HealingValue(0, 0, event.absorb);
this._handleHealEvent(event, healVal);
}
}
}
_handleHealEvent(event, healVal) {
const spellInfo = this._getSpellInfo(event);
const targetHealthPercentage = (event.hitPoints - healVal.effective) / event.maxHitPoints; // hitPoints contains HP *after* the heal
this._handleHeal(spellInfo, event, healVal, targetHealthPercentage);
}
/**
* This actually does that stat weights calculations.
* @param spellInfo An object containing information about how to treat the spell, like on what stats it scales.
* @param eventForWeights The event that uses the stats to scale its healing. If we're tracking a multiplier (like Beacons), this should be the source of the multiplier.
* @param {HealingValue} healVal The actual healing done, all child weight calculators should use this instead of the event data as that might be for another event.
* @param targetHealthPercentage The percentage of health the target has remaining BEFORE the heal.
* @private
*/
_handleHeal(spellInfo, eventForWeights, healVal, targetHealthPercentage) {
// Most spells are counted in healing total, but some spells scale not on their own but 'second hand' from other spells
// I adjust them out of total healing to preserve some accuracy in the "Rating per 1%" stat.
// Good examples of multiplier spells are Leech and Velens.
if (!spellInfo.multiplier) {
this.totalAdjustedHealing += this._adjustGain(healVal.effective, targetHealthPercentage);
}
if (spellInfo.ignored) {
return;
}
this.totalOneLeech += this._adjustGain(this._leech(eventForWeights, healVal, spellInfo), targetHealthPercentage);
if (spellInfo.multiplier) {
// Multiplier spells aren't counted for weights because they don't **directly** benefit from stat weights
return;
}
if (spellInfo.int) {
this.totalOneInt += this._adjustGain(this._intellect(eventForWeights, healVal), targetHealthPercentage);
}
if (spellInfo.crit) {
this.totalOneCrit += this._adjustGain(this._criticalStrike(eventForWeights, healVal), targetHealthPercentage);
}
if (spellInfo.hasteHpct) {
this.totalOneHasteHpct += this._adjustGain(this._hasteHpct(eventForWeights, healVal), targetHealthPercentage);
}
if (spellInfo.hasteHpm) {
this.totalOneHasteHpm += this._adjustGain(this._hasteHpm(eventForWeights, healVal), targetHealthPercentage);
}
if (spellInfo.mastery) {
this.totalOneMastery += this._adjustGain(this._mastery(eventForWeights, healVal), targetHealthPercentage);
}
if (spellInfo.vers) {
this.totalOneVers += this._adjustGain(this._versatility(eventForWeights, healVal), targetHealthPercentage);
}
}
_adjustGain(gain, targetHealthPercentage) {
if (gain === 0) {
return 0;
}
// We want 0-20% health to get value gain, and then linearly decay to 100% health
const maxValueHealthPercentage = 0.3;
const mult = 1 - Math.max(0, (targetHealthPercentage - maxValueHealthPercentage) / (1 - maxValueHealthPercentage));
return this.scaleWeightsWithHealth ? gain * mult : gain;
}
_leech(event, healVal, spellInfo) {
if (event.type !== 'heal') {
return 0; // leech doesn't proc from absorbs
}
// We have to calculate leech weight differently depending on if we already have any leech rating.
// Leech is marked as a 'multplier' heal, so we have to check it before we do the early return below
const hasLeech = this.statTracker.currentLeechPercentage > 0;
if (hasLeech) {
return this._leechHasLeech(event, healVal, spellInfo);
} else {
return this._leechPrediction(event, healVal, spellInfo);
}
}
_leechHasLeech(event, healVal/*, spellInfo*/) {
// When the user has Leech we can use the actual Leech healing to accuractely calculate its HPS value without having to do any kind of predicting
const spellId = event.ability.guid;
if (spellId !== SPELLS.LEECH.id) {
return 0;
}
if (!healVal.overheal) {
return healVal.effective / this.statTracker.currentLeechRating; // TODO: Make a generic method to account for base percentage
}
return 0;
}
_leechPrediction(event, healVal, spellInfo) {
// Without Leech we will have to make an estimation so we can still provide the user with a decent value
if (this.owner.toPlayer(event)) {
return 0; // Leech doesn't proc from self-healing
}
if (spellInfo.multiplier) {
return 0; // Leech doesn't proc from multipliers such as Velen's Future Sight
}
if (this.playerHealthMissing > 0) { // if the player is full HP this would have overhealed.
const healIncreaseFromOneLeech = 1 / this.statTracker.leechRatingPerPercent;
return healVal.raw * healIncreaseFromOneLeech;
}
return 0;
}
_intellect(event, healVal) {
if (healVal.overheal) {
// If a spell overheals, it could not have healed for more. Seeing as Int only adds HP on top of the existing heal we can skip it as increasing the power of this heal would only be more overhealing.
return 0;
}
const currInt = this.statTracker.currentIntellectRating;
// noinspection PointlessArithmeticExpressionJS
const healIncreaseFromOneInt = (1 + ARMOR_INT_BONUS) / currInt;
return healVal.effective * healIncreaseFromOneInt;
}
_getCritChance(event) {
const rating = this.statTracker.currentCritRating;
const baseCritChance = this.statTracker.baseCritPercentage;
const ratingCritChance = rating / this.statTracker.critRatingPerPercent;
return { baseCritChance, ratingCritChance };
}
_isCrit(event) {
return event.hitType === HIT_TYPES.CRIT;
}
_criticalStrike(event, healVal) {
if (this._isCrit(event)) {
// This collects the total effective healing contributed by the last 1 point of critical strike rating.
// We don't make any predictions on normal hits based on crit chance since this would be guess work and we are a log analysis system so we prefer to only work with facts. Actual crit heals are undeniable facts, unlike speculating the chance a normal hit might have crit (and accounting for the potential overhealing of that).
const { baseCritChance, ratingCritChance } = this._getCritChance(event);
const totalCritChance = baseCritChance + ratingCritChance;
if (totalCritChance > (1 + 1 / this.statTracker.critRatingPerPercent)) {
// If the crit chance was more than 100%+1 rating, then the last rating was over the cap and worth 0.
return 0;
}
const ratingCritChanceContribution = 1 - baseCritChance / totalCritChance;
const critMult = this.critEffectBonus.getBonus(event);
const rawBaseHealing = healVal.raw / critMult;
const effectiveCritHealing = Math.max(0, healVal.effective - rawBaseHealing);
const rating = this.statTracker.currentCritRating;
return effectiveCritHealing * ratingCritChanceContribution / rating;
}
return 0;
}
_hasteHpct(event, healVal) {
const currHastePerc = this.statTracker.currentHastePercentage;
const healIncreaseFromOneHaste = 1 / this.statTracker.hasteRatingPerPercent;
const baseHeal = healVal.effective / (1 + currHastePerc);
return baseHeal * healIncreaseFromOneHaste;
}
_hasteHpm(event, healVal) {
const healIncreaseFromOneHaste = 1 / this.statTracker.hasteRatingPerPercent;
const noHasteHealing = healVal.effective / (1 + this.statTracker.currentHastePercentage);
return noHasteHealing * healIncreaseFromOneHaste;
}
_mastery(event, healVal) {
throw new Error('Missing custom Mastery implementation. This is different per spec.');
}
_versatility(event, healVal) {
if (healVal.overheal) {
// If a spell overheals, it could not have healed for more. Seeing as Versatility only adds HP on top of the existing heal we can skip it as increasing the power of this heal would only be more overhealing.
return 0;
}
const currVersPerc = this.statTracker.currentVersatilityPercentage;
const healIncreaseFromOneVers = 1 / this.statTracker.versatilityRatingPerPercent;
const baseHeal = healVal.effective / (1 + currVersPerc);
return baseHeal * healIncreaseFromOneVers;
}
on_toPlayer_damage(event) {
this._updateMissingHealth(event);
const damageVal = new DamageValue(event.amount, event.absorbed, event.blocked, event.overkill);
// const targetHealthPercentage = event.hitPoints / event.maxHitPoints; // hitPoints contains HP *after* the damage taken, which in this case is desirable
// this.totalOneVersDr += this._adjustGain(this._versatilityDamageReduction(event, damageVal), targetHealthPercentage);
// TODO: Figure out how to make this account for target health since damage event don't appear to have hitPoints info
this.totalOneVersDr += this._versatilityDamageReduction(event, damageVal);
}
_versatilityDamageReduction(event, damageVal) {
const amount = damageVal.effective;
const currentVersDamageReductionPercentage = this.statTracker.currentVersatilityPercentage / 2;
const damageReductionIncreaseFromOneVers = 1 / this.statTracker.versatilityRatingPerPercent / 2; // the DR part is only 50% of the Versa percentage
const noVersDamage = amount / (1 - currentVersDamageReductionPercentage);
return noVersDamage * damageReductionIncreaseFromOneVers;
}
on_toPlayer_heal(event) {
this._updateMissingHealth(event);
}
_updateMissingHealth(event) {
if (event.hitPoints && event.maxHitPoints) { // fields not always populated, don't know why
// `maxHitPoints` is always the value *after* the effect applied
this.playerHealthMissing = event.maxHitPoints - event.hitPoints;
}
}
on_finished() {
if (DEBUG) {
console.log('total', formatNumber(this.totalAdjustedHealing));
console.log(`Int - ${formatNumber(this.totalOneInt)}`);
console.log(`Crit - ${formatNumber(this.totalOneCrit)}`);
console.log(`Haste HPCT - ${formatNumber(this.totalOneHasteHpct)}`);
console.log(`Haste HPM - ${formatNumber(this.totalOneHasteHpm)}`);
console.log(`Mastery - ${formatNumber(this.totalOneMastery)}`);
console.log(`Vers - ${formatNumber(this.totalOneVers)}`);
console.log(`Leech - ${formatNumber(this.totalOneLeech)}`);
}
}
get hpsPerIntellect() {
return this._getGain(STAT.INTELLECT) / this.owner.fightDuration * 1000;
}
get hpsPerCriticalStrike() {
return this._getGain(STAT.CRITICAL_STRIKE) / this.owner.fightDuration * 1000;
}
get hpsPerHasteHPCT() {
return this._getGain(STAT.HASTE_HPCT) / this.owner.fightDuration * 1000;
}
get hpsPerHasteHPM() {
return this._getGain(STAT.HASTE_HPM) / this.owner.fightDuration * 1000;
}
get hpsPerHaste() {
return this.hpsPerHasteHPCT + this.hpsPerHasteHPM;
}
get hpsPerMastery() {
return this._getGain(STAT.MASTERY) / this.owner.fightDuration * 1000;
}
get hpsPerVersatility() {
return this._getGain(STAT.VERSATILITY) / this.owner.fightDuration * 1000;
}
get hpsPerVersatilityDR() {
return this._getGain(STAT.VERSATILITY_DR) / this.owner.fightDuration * 1000;
}
get hpsPerLeech() {
return this._getGain(STAT.LEECH) / this.owner.fightDuration * 1000;
}
// region Item values
calculateItemStatsHps(baseStats, itemLevel) {
let hps = 0;
if (baseStats.primary) {
hps += calculatePrimaryStat(baseStats.itemLevel, baseStats.primary, itemLevel) * this.hpsPerIntellect;
}
if (baseStats.criticalStrike) {
hps += calculateSecondaryStatDefault(baseStats.itemLevel, baseStats.criticalStrike, itemLevel) * this.hpsPerCriticalStrike;
}
if (baseStats.haste) {
hps += calculateSecondaryStatDefault(baseStats.itemLevel, baseStats.haste, itemLevel) * this.hpsPerHaste;
}
if (baseStats.mastery) {
hps += calculateSecondaryStatDefault(baseStats.itemLevel, baseStats.mastery, itemLevel) * this.hpsPerMastery;
}
if (baseStats.versatility) {
hps += calculateSecondaryStatDefault(baseStats.itemLevel, baseStats.versatility, itemLevel) * this.hpsPerVersatility;
}
if (baseStats.leech) {
hps += calculateSecondaryStatDefault(baseStats.itemLevel, baseStats.leech, itemLevel) * this.hpsPerLeech;
}
return hps;
}
// endregion
// region statistic
_ratingPerOnePercent(oneRatingHealing) {
const onePercentHealing = this.totalAdjustedHealing / 100;
return onePercentHealing / oneRatingHealing;
}
_getGain(stat) {
switch (stat) {
case STAT.INTELLECT:
return this.totalOneInt;
case STAT.CRITICAL_STRIKE:
return this.totalOneCrit;
case STAT.HASTE_HPCT:
return this.totalOneHasteHpct;
case STAT.HASTE_HPM:
return this.totalOneHasteHpm;
case STAT.MASTERY:
return this.totalOneMastery;
case STAT.VERSATILITY:
return this.totalOneVers;
case STAT.VERSATILITY_DR:
return this.totalOneVers + this.totalOneVersDr;
case STAT.LEECH:
return this.totalOneLeech;
default:
return 0;
}
}
_getTooltip(stat) {
switch (stat) {
case STAT.HASTE_HPCT:
return 'HPCT stands for "Healing per Cast Time". This is the value that 1% Haste would be worth if you would cast everything you are already casting (and that can be casted quicker) 1% faster. Mana is not accounted for in any way and you should consider the Haste stat weight 0 if you run out of mana while doing everything else right.';
case STAT.HASTE_HPM:
return 'HPM stands for "Healing per Mana". In valuing Haste, it considers only the faster HoT ticking and not the reduced cast times. Effectively it models haste\'s bonus to mana efficiency. This is typically the better calculation to use for raid encounters where mana is an issue.';
case STAT.VERSATILITY:
return 'Weight includes only the boost to healing, and does not include the damage reduction.';
case STAT.VERSATILITY_DR:
return 'Weight includes both healing boost and damage reduction, counting damage reduction as additional throughput.';
default:
return null;
}
}
moreInformationLink = null;
statistic() {
const results = this._prepareResults();
return (
<StatisticWrapper position={STATISTIC_ORDER.CORE(11)}>
<div className="col-lg-3 col-md-6 col-sm-6 col-xs-12">
<div className="panel items">
<div className="panel-heading">
<h2>
<dfn data-tip="These stat values are calculated using the actual circumstances of this encounter. These values reveal the value of the last 1 rating of each stat, they may not necessarily be the best way to gear. The stat values are likely to differ based on fight, raid size, items used, talents chosen, etc.<br /><br />DPS gains are not included in any of the stat values.">Stat Values</dfn>
{this.moreInformationLink && (
<a href={this.moreInformationLink} className="pull-right">
More info
</a>
)}
</h2>
</div>
<div className="panel-body" style={{ padding: 0 }}>
<table className="data-table compact">
<thead>
<tr>
<th style={{ minWidth: 30 }}><b>Stat</b></th>
<th className="text-right" style={{ minWidth: 30 }} colSpan={2}>
<dfn data-tip="Normalized so Intellect is always 1.00."><b>Value</b></dfn>
</th>
</tr>
</thead>
<tbody>
{results.map(row => {
const stat = typeof row === 'object' ? row.stat : row;
const tooltip = typeof row === 'object' ? row.tooltip : this._getTooltip(stat);
const gain = this._getGain(stat);
const weight = gain / (this.totalOneInt || 1);
const ratingForOne = this._ratingPerOnePercent(gain);
const Icon = getIcon(stat);
return (
<tr key={stat}>
<td className={getClassNameColor(stat)}>
<Icon
style={{
height: '1.6em',
width: '1.6em',
marginRight: 10,
}}
/>{' '}
{tooltip ? <dfn data-tip={tooltip}>{getName(stat)}</dfn> : getName(stat)}
</td>
<td className="text-right">
{stat === STAT.HASTE_HPCT && '0.00 - '}{gain !== null ? weight.toFixed(2) : 'NYI'}
</td>
<td style={{ padding: 6 }}>
<InformationIcon data-tip={`${(gain / this.owner.fightDuration * 1000).toFixed(2)} HPS per 1 rating / ${gain !== null ? (
ratingForOne === Infinity ? '∞' : formatNumber(ratingForOne)
) : 'NYI'} rating per 1% throughput`} />
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
</div>
</StatisticWrapper>
);
}
// endregion
}
export default BaseHealerStatValues;
|
node_modules/react-router/es/RouterContext.js | NickingMeSpace/questionnaire | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
import invariant from 'invariant';
import React from 'react';
import createReactClass from 'create-react-class';
import { array, func, object } from 'prop-types';
import getRouteParams from './getRouteParams';
import { ContextProvider } from './ContextUtils';
import { isReactChildren } from './RouteUtils';
/**
* A <RouterContext> renders the component tree for a given router state
* and sets the history object and the current location in context.
*/
var RouterContext = createReactClass({
displayName: 'RouterContext',
mixins: [ContextProvider('router')],
propTypes: {
router: object.isRequired,
location: object.isRequired,
routes: array.isRequired,
params: object.isRequired,
components: array.isRequired,
createElement: func.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
createElement: React.createElement
};
},
childContextTypes: {
router: object.isRequired
},
getChildContext: function getChildContext() {
return {
router: this.props.router
};
},
createElement: function createElement(component, props) {
return component == null ? null : this.props.createElement(component, props);
},
render: function render() {
var _this = this;
var _props = this.props,
location = _props.location,
routes = _props.routes,
params = _props.params,
components = _props.components,
router = _props.router;
var element = null;
if (components) {
element = components.reduceRight(function (element, components, index) {
if (components == null) return element; // Don't create new children; use the grandchildren.
var route = routes[index];
var routeParams = getRouteParams(route, params);
var props = {
location: location,
params: params,
route: route,
router: router,
routeParams: routeParams,
routes: routes
};
if (isReactChildren(element)) {
props.children = element;
} else if (element) {
for (var prop in element) {
if (Object.prototype.hasOwnProperty.call(element, prop)) props[prop] = element[prop];
}
}
if ((typeof components === 'undefined' ? 'undefined' : _typeof(components)) === 'object') {
var elements = {};
for (var key in components) {
if (Object.prototype.hasOwnProperty.call(components, key)) {
// Pass through the key as a prop to createElement to allow
// custom createElement functions to know which named component
// they're rendering, for e.g. matching up to fetched data.
elements[key] = _this.createElement(components[key], _extends({
key: key }, props));
}
}
return elements;
}
return _this.createElement(components, props);
}, element);
}
!(element === null || element === false || React.isValidElement(element)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The root route must render a single element') : invariant(false) : void 0;
return element;
}
});
export default RouterContext; |
src/components/couchdb/plain/CouchdbPlain.js | fpoumian/react-devicon | import React from 'react'
import PropTypes from 'prop-types'
import SVGDeviconInline from '../../_base/SVGDeviconInline'
import iconSVG from './CouchdbPlain.svg'
/** CouchdbPlain */
function CouchdbPlain({ width, height, className }) {
return (
<SVGDeviconInline
className={'CouchdbPlain' + ' ' + className}
iconSVG={iconSVG}
width={width}
height={height}
/>
)
}
CouchdbPlain.propTypes = {
className: PropTypes.string,
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
}
export default CouchdbPlain
|
Libraries/Components/WebView/WebView.ios.js | Andreyco/react-native | /**
* 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 WebView
* @noflow
*/
'use strict';
var ActivityIndicator = require('ActivityIndicator');
var EdgeInsetsPropType = require('EdgeInsetsPropType');
var React = require('React');
var ReactNative = require('ReactNative');
var StyleSheet = require('StyleSheet');
var Text = require('Text');
var UIManager = require('UIManager');
var View = require('View');
var ScrollView = require('ScrollView');
var deprecatedPropType = require('deprecatedPropType');
var invariant = require('fbjs/lib/invariant');
var keyMirror = require('fbjs/lib/keyMirror');
var processDecelerationRate = require('processDecelerationRate');
var requireNativeComponent = require('requireNativeComponent');
var resolveAssetSource = require('resolveAssetSource');
var PropTypes = React.PropTypes;
var RCTWebViewManager = require('NativeModules').WebViewManager;
var BGWASH = 'rgba(255,255,255,0.8)';
var RCT_WEBVIEW_REF = 'webview';
var WebViewState = keyMirror({
IDLE: null,
LOADING: null,
ERROR: null,
});
const NavigationType = keyMirror({
click: true,
formsubmit: true,
backforward: true,
reload: true,
formresubmit: true,
other: true,
});
const JSNavigationScheme = 'react-js-navigation';
type ErrorEvent = {
domain: any,
code: any,
description: any,
}
type Event = Object;
const DataDetectorTypes = [
'phoneNumber',
'link',
'address',
'calendarEvent',
'none',
'all',
];
var defaultRenderLoading = () => (
<View style={styles.loadingView}>
<ActivityIndicator />
</View>
);
var defaultRenderError = (errorDomain, errorCode, errorDesc) => (
<View style={styles.errorContainer}>
<Text style={styles.errorTextTitle}>
Error loading page
</Text>
<Text style={styles.errorText}>
{'Domain: ' + errorDomain}
</Text>
<Text style={styles.errorText}>
{'Error Code: ' + errorCode}
</Text>
<Text style={styles.errorText}>
{'Description: ' + errorDesc}
</Text>
</View>
);
/**
* `WebView` renders web content in a native view.
*
*```
* import React, { Component } from 'react';
* import { WebView } from 'react-native';
*
* class MyWeb extends Component {
* render() {
* return (
* <WebView
* source={{uri: 'https://github.com/facebook/react-native'}}
* style={{marginTop: 20}}
* />
* );
* }
* }
*```
*
* You can use this component to navigate back and forth in the web view's
* history and configure various properties for the web content.
*/
class WebView extends React.Component {
static JSNavigationScheme = JSNavigationScheme;
static NavigationType = NavigationType;
static propTypes = {
...View.propTypes,
html: deprecatedPropType(
PropTypes.string,
'Use the `source` prop instead.'
),
url: deprecatedPropType(
PropTypes.string,
'Use the `source` prop instead.'
),
/**
* Loads static html or a uri (with optional headers) in the WebView.
*/
source: PropTypes.oneOfType([
PropTypes.shape({
/*
* The URI to load in the `WebView`. Can be a local or remote file.
*/
uri: PropTypes.string,
/*
* The HTTP Method to use. Defaults to GET if not specified.
* NOTE: On Android, only GET and POST are supported.
*/
method: PropTypes.string,
/*
* Additional HTTP headers to send with the request.
* NOTE: On Android, this can only be used with GET requests.
*/
headers: PropTypes.object,
/*
* The HTTP body to send with the request. This must be a valid
* UTF-8 string, and will be sent exactly as specified, with no
* additional encoding (e.g. URL-escaping or base64) applied.
* NOTE: On Android, this can only be used with POST requests.
*/
body: PropTypes.string,
}),
PropTypes.shape({
/*
* A static HTML page to display in the WebView.
*/
html: PropTypes.string,
/*
* The base URL to be used for any relative links in the HTML.
*/
baseUrl: PropTypes.string,
}),
/*
* Used internally by packager.
*/
PropTypes.number,
]),
/**
* Function that returns a view to show if there's an error.
*/
renderError: PropTypes.func, // view to show if there's an error
/**
* Function that returns a loading indicator.
*/
renderLoading: PropTypes.func,
/**
* Function that is invoked when the `WebView` has finished loading.
*/
onLoad: PropTypes.func,
/**
* Function that is invoked when the `WebView` load succeeds or fails.
*/
onLoadEnd: PropTypes.func,
/**
* Function that is invoked when the `WebView` starts loading.
*/
onLoadStart: PropTypes.func,
/**
* Function that is invoked when the `WebView` load fails.
*/
onError: PropTypes.func,
/**
* Boolean value that determines whether the web view bounces
* when it reaches the edge of the content. The default value is `true`.
* @platform ios
*/
bounces: PropTypes.bool,
/**
* A floating-point number that determines how quickly the scroll view
* decelerates after the user lifts their finger. You may also use the
* string shortcuts `"normal"` and `"fast"` which match the underlying iOS
* settings for `UIScrollViewDecelerationRateNormal` and
* `UIScrollViewDecelerationRateFast` respectively:
*
* - normal: 0.998
* - fast: 0.99 (the default for iOS web view)
* @platform ios
*/
decelerationRate: ScrollView.propTypes.decelerationRate,
/**
* Boolean value that determines whether scrolling is enabled in the
* `WebView`. The default value is `true`.
* @platform ios
*/
scrollEnabled: PropTypes.bool,
/**
* Controls whether to adjust the content inset for web views that are
* placed behind a navigation bar, tab bar, or toolbar. The default value
* is `true`.
*/
automaticallyAdjustContentInsets: PropTypes.bool,
/**
* The amount by which the web view content is inset from the edges of
* the scroll view. Defaults to {top: 0, left: 0, bottom: 0, right: 0}.
*/
contentInset: EdgeInsetsPropType,
/**
* Function that is invoked when the `WebView` loading starts or ends.
*/
onNavigationStateChange: PropTypes.func,
/**
* A function that is invoked when the webview calls `window.postMessage`.
* Setting this property will inject a `postMessage` global into your
* webview, but will still call pre-existing values of `postMessage`.
*
* `window.postMessage` accepts one argument, `data`, which will be
* available on the event object, `event.nativeEvent.data`. `data`
* must be a string.
*/
onMessage: PropTypes.func,
/**
* Boolean value that forces the `WebView` to show the loading view
* on the first load.
*/
startInLoadingState: PropTypes.bool,
/**
* The style to apply to the `WebView`.
*/
style: View.propTypes.style,
/**
* Determines the types of data converted to clickable URLs in the web view’s content.
* By default only phone numbers are detected.
*
* You can provide one type or an array of many types.
*
* Possible values for `dataDetectorTypes` are:
*
* - `'phoneNumber'`
* - `'link'`
* - `'address'`
* - `'calendarEvent'`
* - `'none'`
* - `'all'`
*
* @platform ios
*/
dataDetectorTypes: PropTypes.oneOfType([
PropTypes.oneOf(DataDetectorTypes),
PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)),
]),
/**
* Boolean value to enable JavaScript in the `WebView`. Used on Android only
* as JavaScript is enabled by default on iOS. The default value is `true`.
* @platform android
*/
javaScriptEnabled: PropTypes.bool,
/**
* Boolean value to control whether DOM Storage is enabled. Used only in
* Android.
* @platform android
*/
domStorageEnabled: PropTypes.bool,
/**
* Set this to provide JavaScript that will be injected into the web page
* when the view loads.
*/
injectedJavaScript: PropTypes.string,
/**
* Sets the user-agent for the `WebView`.
* @platform android
*/
userAgent: PropTypes.string,
/**
* Boolean that controls whether the web content is scaled to fit
* the view and enables the user to change the scale. The default value
* is `true`.
*/
scalesPageToFit: PropTypes.bool,
/**
* Function that allows custom handling of any web view requests. Return
* `true` from the function to continue loading the request and `false`
* to stop loading.
* @platform ios
*/
onShouldStartLoadWithRequest: PropTypes.func,
/**
* Boolean that determines whether HTML5 videos play inline or use the
* native full-screen controller. The default value is `false`.
*
* **NOTE** : In order for video to play inline, not only does this
* property need to be set to `true`, but the video element in the HTML
* document must also include the `webkit-playsinline` attribute.
* @platform ios
*/
allowsInlineMediaPlayback: PropTypes.bool,
/**
* Boolean that determines whether HTML5 audio and video requires the user
* to tap them before they start playing. The default value is `true`.
*/
mediaPlaybackRequiresUserAction: PropTypes.bool,
};
state = {
viewState: WebViewState.IDLE,
lastErrorEvent: (null: ?ErrorEvent),
startInLoadingState: true,
};
componentWillMount() {
if (this.props.startInLoadingState) {
this.setState({viewState: WebViewState.LOADING});
}
}
render() {
var otherView = null;
if (this.state.viewState === WebViewState.LOADING) {
otherView = (this.props.renderLoading || defaultRenderLoading)();
} else if (this.state.viewState === WebViewState.ERROR) {
var errorEvent = this.state.lastErrorEvent;
invariant(
errorEvent != null,
'lastErrorEvent expected to be non-null'
);
otherView = (this.props.renderError || defaultRenderError)(
errorEvent.domain,
errorEvent.code,
errorEvent.description
);
} else if (this.state.viewState !== WebViewState.IDLE) {
console.error(
'RCTWebView invalid state encountered: ' + this.state.loading
);
}
var webViewStyles = [styles.container, styles.webView, this.props.style];
if (this.state.viewState === WebViewState.LOADING ||
this.state.viewState === WebViewState.ERROR) {
// if we're in either LOADING or ERROR states, don't show the webView
webViewStyles.push(styles.hidden);
}
var onShouldStartLoadWithRequest = this.props.onShouldStartLoadWithRequest && ((event: Event) => {
var shouldStart = this.props.onShouldStartLoadWithRequest &&
this.props.onShouldStartLoadWithRequest(event.nativeEvent);
RCTWebViewManager.startLoadWithResult(!!shouldStart, event.nativeEvent.lockIdentifier);
});
var decelerationRate = processDecelerationRate(this.props.decelerationRate);
var source = this.props.source || {};
if (this.props.html) {
source.html = this.props.html;
} else if (this.props.url) {
source.uri = this.props.url;
}
const messagingEnabled = typeof this.props.onMessage === 'function';
var webView =
<RCTWebView
ref={RCT_WEBVIEW_REF}
key="webViewKey"
style={webViewStyles}
source={resolveAssetSource(source)}
injectedJavaScript={this.props.injectedJavaScript}
bounces={this.props.bounces}
scrollEnabled={this.props.scrollEnabled}
decelerationRate={decelerationRate}
contentInset={this.props.contentInset}
automaticallyAdjustContentInsets={this.props.automaticallyAdjustContentInsets}
onLoadingStart={this._onLoadingStart}
onLoadingFinish={this._onLoadingFinish}
onLoadingError={this._onLoadingError}
messagingEnabled={messagingEnabled}
onMessage={this._onMessage}
onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
scalesPageToFit={this.props.scalesPageToFit}
allowsInlineMediaPlayback={this.props.allowsInlineMediaPlayback}
mediaPlaybackRequiresUserAction={this.props.mediaPlaybackRequiresUserAction}
dataDetectorTypes={this.props.dataDetectorTypes}
/>;
return (
<View style={styles.container}>
{webView}
{otherView}
</View>
);
}
/**
* Go forward one page in the web view's history.
*/
goForward = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.goForward,
null
);
};
/**
* Go back one page in the web view's history.
*/
goBack = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.goBack,
null
);
};
/**
* Reloads the current page.
*/
reload = () => {
this.setState({viewState: WebViewState.LOADING});
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.reload,
null
);
};
/**
* Stop loading the current page.
*/
stopLoading = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.stopLoading,
null
);
};
/**
* Posts a message to the web view, which will emit a `message` event.
* Accepts one argument, `data`, which must be a string.
*
* In your webview, you'll need to something like the following.
*
* ```js
* document.addEventListener('message', e => { document.title = e.data; });
* ```
*/
postMessage = (data) => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.postMessage,
[String(data)]
);
};
/**
* We return an event with a bunch of fields including:
* url, title, loading, canGoBack, canGoForward
*/
_updateNavigationState = (event: Event) => {
if (this.props.onNavigationStateChange) {
this.props.onNavigationStateChange(event.nativeEvent);
}
};
/**
* Returns the native `WebView` node.
*/
getWebViewHandle = (): any => {
return ReactNative.findNodeHandle(this.refs[RCT_WEBVIEW_REF]);
};
_onLoadingStart = (event: Event) => {
var onLoadStart = this.props.onLoadStart;
onLoadStart && onLoadStart(event);
this._updateNavigationState(event);
};
_onLoadingError = (event: Event) => {
event.persist(); // persist this event because we need to store it
var {onError, onLoadEnd} = this.props;
onError && onError(event);
onLoadEnd && onLoadEnd(event);
console.warn('Encountered an error loading page', event.nativeEvent);
this.setState({
lastErrorEvent: event.nativeEvent,
viewState: WebViewState.ERROR
});
};
_onLoadingFinish = (event: Event) => {
var {onLoad, onLoadEnd} = this.props;
onLoad && onLoad(event);
onLoadEnd && onLoadEnd(event);
this.setState({
viewState: WebViewState.IDLE,
});
this._updateNavigationState(event);
};
_onMessage = (event: Event) => {
var {onMessage} = this.props;
onMessage && onMessage(event);
}
}
var RCTWebView = requireNativeComponent('RCTWebView', WebView, {
nativeOnly: {
onLoadingStart: true,
onLoadingError: true,
onLoadingFinish: true,
onMessage: true,
messagingEnabled: PropTypes.bool,
},
});
var styles = StyleSheet.create({
container: {
flex: 1,
},
errorContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: BGWASH,
},
errorText: {
fontSize: 14,
textAlign: 'center',
marginBottom: 2,
},
errorTextTitle: {
fontSize: 15,
fontWeight: '500',
marginBottom: 10,
},
hidden: {
height: 0,
flex: 0, // disable 'flex:1' when hiding a View
},
loadingView: {
backgroundColor: BGWASH,
flex: 1,
justifyContent: 'center',
alignItems: 'center',
height: 100,
},
webView: {
backgroundColor: '#ffffff',
}
});
module.exports = WebView;
|
node_modules/react-bootstrap/es/Jumbotron.js | okristian1/react-info | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import classNames from 'classnames';
import elementType from 'react-prop-types/lib/elementType';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
componentClass: elementType
};
var defaultProps = {
componentClass: 'div'
};
var Jumbotron = function (_React$Component) {
_inherits(Jumbotron, _React$Component);
function Jumbotron() {
_classCallCheck(this, Jumbotron);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Jumbotron.prototype.render = function render() {
var _props = this.props,
Component = _props.componentClass,
className = _props.className,
props = _objectWithoutProperties(_props, ['componentClass', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement(Component, _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return Jumbotron;
}(React.Component);
Jumbotron.propTypes = propTypes;
Jumbotron.defaultProps = defaultProps;
export default bsClass('jumbotron', Jumbotron); |
node/webpack/react/es6/es6.js | wushi27/nodejs201606 | 'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
class HelloWorld extends React.Component{
render(){
return (
<p>
hello,you aaa!
It is {this.props.date.toTimeString()}
</p>
);
}
}
var sampleNameSpace = {
myDirective:HelloWorld
};
setInterval(function(){
ReactDOM.render(
<sampleNameSpace.myDirective date={new Date()} />,
document.getElementById('test')
);
},1000); |
node_modules/react-bootstrap/es/SplitToggle.js | cmccandless/SolRFrontEnd | import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import DropdownToggle from './DropdownToggle';
var SplitToggle = function (_React$Component) {
_inherits(SplitToggle, _React$Component);
function SplitToggle() {
_classCallCheck(this, SplitToggle);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
SplitToggle.prototype.render = function render() {
return React.createElement(DropdownToggle, _extends({}, this.props, {
useAnchor: false,
noCaret: false
}));
};
return SplitToggle;
}(React.Component);
SplitToggle.defaultProps = DropdownToggle.defaultProps;
export default SplitToggle; |
app/components/TransferSelect/index.js | bruceli1986/react-qdp | /**
*
* TransferSelect
*
*/
import React from 'react';
import _ from 'lodash';
import { Modal, Button, Input, Transfer } from 'antd';
import classNames from 'classnames';
import { FormattedMessage } from 'react-intl';
import styles from './styles.css';
const InputGroup = Input.Group;
class TransferSelect extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props, context) {
super(props, context);
this.state = {
visible: false,
selectedRowKeys: [],
query: '',
};
}
componentWillReceiveProps(nextProps) {
if (!nextProps.value) {
this.setState({
selectedRowKeys: [],
query: '',
});
}
}
getClassName = (record, index) => {
const { selectedRowKeys } = this.state;
if (selectedRowKeys.indexOf(record[this.props.valueField]) >= 0) {
return 'qdp-row-selected';
}
return '';
}
showModal = () => {
if (this.props.disabled !== true) {
let show = true;
if (this.props.onClick) {
show = this.props.onClick(this.props.value);
}
this.setState({
visible: show,
});
}
}
getValue() {
const dataSource = this.filterDateSource();
const field = this.props.valueField;
if (!field) {
return '';
}
const result = this.state.selectedRowKeys.map((x) => {
const record = dataSource.find(function (y) {
return y[field] === x;
});
if (!record) {
return [];
}
return record[field];
});
// console.log('getValue', result.toString());
return result.toString();
}
getRecords() {
const dataSource = this.props.dataSource;
const field = this.props.valueField;
if (!field) {
return [];
}
const result = this.state.selectedRowKeys.map((x) => (dataSource.find(function (y) {
return y[field] === x;
})));
return result;
}
handleCancel = (e) => {
this.setState({
visible: false,
});
}
getText() {
const { textField, valueField, value, dataSource } = this.props;
const _value = value ? value.split(',') : [];
// console.log('_value:', _value);
const field = textField ? textField : valueField;
const records = dataSource ? dataSource.filter((x) => _value.indexOf(x[valueField]) >= 0) : [];
// console.log('records:', records);
const text = records ? records.map((x) => x[field]).toString() : '';
return text;
}
// setQuery = (fields) => {
// this.setState({
// query: Object.assign(this.state.query, fields),
// });
// }
_Submit = (form) => {
if (this.props.onSearch) {
this.props.onSearch(form);
} else {
this.setState({ filter: form });
}
}
filterDateSource() {
const { dataSource, searchField } = this.props;
const { query } = this.state;
let result = [];
// if (dataSource) {
// result = dataSource.filter(function (x) {
// let a = true;
// for (var key in filter) {
// let reg = new RegExp(`${filter[key]}`, 'i');
// if (filter[key] && x[key].search(reg) < 0) {
// return false;
// }
// }
// return a;
// });
// }
// console.log('dataSource:', dataSource);
if (dataSource) {
let reg = new RegExp(query, 'i');
result = dataSource.filter((x) => {
return searchField.some(y => reg.test(x[y]));
// let str = searchField.reduce((a, b) => x[a] + x[b] );
// return reg.test(x[textField]) || reg.test(x[valueField]);
});
if (result.length > 200) {
result = result.slice(0, 200);
}
}
return result;
}
render() {
const { style, placeholder, multiple } = this.props;
const { loading, selectedRowKeys } = this.state;
const btnCls = classNames({
'ant-search-btn': true,
'ant-search-btn-noempty': !!(this.props.value || '').trim(),
});
const searchCls = classNames({
'ant-search-input': true,
'ant-search-input-focus': true,
});
const dataSource = this.filterDateSource();
return (
<div>
<div className="ant-search-input-wrapper" style={style}>
<InputGroup className={searchCls}>
<Input placeholder={placeholder} onClick={this.showModal} value={this.getText()} disabled={this.props.disabled} />
<Input style={{ display: 'none' }} value={this.props.value} />
<div className="ant-input-group-wrap">
<Button icon="search" className={btnCls} size="small" onClick={this.handleSearch} style={{ height: '26px' }} />
</div>
</InputGroup>
</div>
<Modal
title={this.props.modalTitle}
visible={this.state.visible}
onCancel={this.handleCancel}
width={this.props.modalWidth}
footer={null}
>
<Transfer
className={styles.transfer}
listStyle={{ flex: '1', height: '300px' }}
showSearch
dataSource={dataSource}
titles={this.props.title}
targetKeys={this.props.targetKeys}
selectedKeys={this.props.selectedKeys}
rowKey={record => record.id}
onChange={this.props.onChange}
onSearchChange={(direction, event) => {
if (direction === 'left') {
this.setState({
query: event.target.value,
});
}
}}
render={this.props.render} />
</Modal>
</div>
);
}
}
export default TransferSelect;
|
src/components/book_display_component.js | allenyin55/reading_with_Annie | import React from 'react';
import { Link } from 'react-router';
import moment from 'moment-timezone';
const BookDisplay = ({book, isInList}) => {
if(isInList){
// for teh sake of the book that doesn't have bookinfo or volumeinfo
if(book.bookinfo === null || book.bookinfo.volumeInfo === undefined) return <Link to={"books/" + book.id}>
{book.title}
</Link>;
return(
<div>
<div>
<div>
<img src={
book.bookinfo.volumeInfo.imageLinks.thumbnail}
style={{width: 128+"px"}}/>
</div>
<Link to={"books/" + book.id}>
{book.title}
</Link>
</div>
{(book.bookinfo.volumeInfo.authors !== undefined)
? (<div>{book.bookinfo.volumeInfo.authors[0]}</div>)
: (<div>No author</div>)}
<div>{moment.tz(book.dateadded, "Zulu").tz("America/Los_Angeles").format().substring(0, 10)} added</div>
</div>
)
}
// for teh sake of the book that doesn't have bookinfo or volumeinfo
if(book.bookinfo === null || book.bookinfo.volumeInfo === undefined) return <div>The book doesn't have book info</div>
if (book.bookinfo.volumeInfo.description === undefined ){
book.bookinfo.volumeInfo.description = "No Description";
}
return(
<div>
{(book.bookinfo.volumeInfo.authors !== undefined)
? (<div>by {book.bookinfo.volumeInfo.authors[0]}</div>)
: (<div>No author</div>)}
<div>
<div>
<img src={
book.bookinfo.volumeInfo.imageLinks.thumbnail}
style={{width: 128+"px"}}/>
</div>
</div>
{(book.bookinfo.volumeInfo.description.length<400) ? (<p>{book.bookinfo.volumeInfo.description}</p>)
:(<p>{book.bookinfo.volumeInfo.description.slice(0,399)} ......</p>)}
</div>
)
};
export default BookDisplay; |
app/javascript/flavours/glitch/components/status_list.js | glitch-soc/mastodon | import { debounce } from 'lodash';
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import StatusContainer from 'flavours/glitch/containers/status_container';
import ImmutablePureComponent from 'react-immutable-pure-component';
import LoadGap from './load_gap';
import ScrollableList from './scrollable_list';
import RegenerationIndicator from 'flavours/glitch/components/regeneration_indicator';
export default class StatusList extends ImmutablePureComponent {
static propTypes = {
scrollKey: PropTypes.string.isRequired,
statusIds: ImmutablePropTypes.list.isRequired,
featuredStatusIds: ImmutablePropTypes.list,
onLoadMore: PropTypes.func,
onScrollToTop: PropTypes.func,
onScroll: PropTypes.func,
trackScroll: PropTypes.bool,
isLoading: PropTypes.bool,
isPartial: PropTypes.bool,
hasMore: PropTypes.bool,
prepend: PropTypes.node,
alwaysPrepend: PropTypes.bool,
emptyMessage: PropTypes.node,
timelineId: PropTypes.string.isRequired,
};
static defaultProps = {
trackScroll: true,
};
getFeaturedStatusCount = () => {
return this.props.featuredStatusIds ? this.props.featuredStatusIds.size : 0;
}
getCurrentStatusIndex = (id, featured) => {
if (featured) {
return this.props.featuredStatusIds.indexOf(id);
} else {
return this.props.statusIds.indexOf(id) + this.getFeaturedStatusCount();
}
}
handleMoveUp = (id, featured) => {
const elementIndex = this.getCurrentStatusIndex(id, featured) - 1;
this._selectChild(elementIndex, true);
}
handleMoveDown = (id, featured) => {
const elementIndex = this.getCurrentStatusIndex(id, featured) + 1;
this._selectChild(elementIndex, false);
}
handleLoadOlder = debounce(() => {
this.props.onLoadMore(this.props.statusIds.size > 0 ? this.props.statusIds.last() : undefined);
}, 300, { leading: true })
_selectChild (index, align_top) {
const container = this.node.node;
const element = container.querySelector(`article:nth-of-type(${index + 1}) .focusable`);
if (element) {
if (align_top && container.scrollTop > element.offsetTop) {
element.scrollIntoView(true);
} else if (!align_top && container.scrollTop + container.clientHeight < element.offsetTop + element.offsetHeight) {
element.scrollIntoView(false);
}
element.focus();
}
}
setRef = c => {
this.node = c;
}
render () {
const { statusIds, featuredStatusIds, onLoadMore, timelineId, ...other } = this.props;
const { isLoading, isPartial } = other;
if (isPartial) {
return <RegenerationIndicator />;
}
let scrollableContent = (isLoading || statusIds.size > 0) ? (
statusIds.map((statusId, index) => statusId === null ? (
<LoadGap
key={'gap:' + statusIds.get(index + 1)}
disabled={isLoading}
maxId={index > 0 ? statusIds.get(index - 1) : null}
onClick={onLoadMore}
/>
) : (
<StatusContainer
key={statusId}
id={statusId}
onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown}
contextType={timelineId}
scrollKey={this.props.scrollKey}
/>
))
) : null;
if (scrollableContent && featuredStatusIds) {
scrollableContent = featuredStatusIds.map(statusId => (
<StatusContainer
key={`f-${statusId}`}
id={statusId}
featured
onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown}
contextType={timelineId}
scrollKey={this.props.scrollKey}
/>
)).concat(scrollableContent);
}
return (
<ScrollableList {...other} showLoading={isLoading && statusIds.size === 0} onLoadMore={onLoadMore && this.handleLoadOlder} ref={this.setRef}>
{scrollableContent}
</ScrollableList>
);
}
}
|
examples/basic/components/Input.js | babotech/redux-uniform | import React from 'react'
const Input = (props) => {
const style = {
...defaultStyle,
borderColor: !props.dirty ? `none` : !props.valid ? `#ff0000` : `#363636`
}
return (
<input style={style} {...props} />
)
}
export default Input
const defaultStyle = {
display: `block`,
marginBottom: `10px`,
width: `100%`,
boxSizing: `border-box`,
border: `1ps solid`
} |
app/components/TimelineEvent/index.js | samtgarson/MyFirstReactNativeApp | /*
*
* TimelineEvent
*
*/
import ReactNative from 'react-native';
import React, { Component } from 'react';
import styles from './styles';
const { Animated, View, Text, ScrollView } = ReactNative;
const FINAL_HEIGHT = 120
const RELEASE_OFFSET = 80
class TimelineEvent extends Component {
constructor (props) {
super(props)
this.state = {
rowHeight: new Animated.Value(0),
scrollOffset: new Animated.Value(0),
releaseToHide: false
}
}
componentDidMount () {
Animated.timing(
this.state.rowHeight,
{toValue: FINAL_HEIGHT}
).start();
this.state.scrollOffset.addListener(({value}) => {
this.setState({
releaseToHide: value >= RELEASE_OFFSET
})
})
}
onRelease () {
if (this.state.releaseToHide) this.props.hideEvent()
}
render () {
const rowOpacity = this.state.rowHeight.interpolate({
inputRange: [0, FINAL_HEIGHT],
outputRange: [0, 1]
})
const onScroll = Animated.event(
[{nativeEvent: {contentOffset: {x: this.state.scrollOffset}}}]
)
const bgColor = this.state.scrollOffset.interpolate({
inputRange: [1, 2, RELEASE_OFFSET - 10, RELEASE_OFFSET],
outputRange: ['white', 'rgb(207,216,220)', 'rgb(207,216,220)', 'rgb(211,47,47)'],
extrapolate: 'clamp'
})
return (
<Animated.View style={[styles.container, {opacity: rowOpacity, backgroundColor: bgColor}]}>
<ScrollView
scrollEventThrottle={16}
horizontal={true}
contentContainerStyle={styles.scroll}
onScroll={onScroll}
onTouchEnd={this.onRelease.bind(this)}
>
<Animated.View style={[styles.event, {height: this.state.rowHeight}]}>
<Text>{this.props.text}</Text>
<Text>{this.props.createdAt.getSeconds()}</Text>
</Animated.View>
</ScrollView>
</Animated.View>
)
}
}
export default TimelineEvent;
|
packages/showcase/plot/labeled-stacked-vertical-bar-chart.js | uber-common/react-vis | // Copyright (c) 2016 - 2017 Uber Technologies, Inc.
//
// 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';
import ShowcaseButton from '../showcase-components/showcase-button';
import {
XYPlot,
XAxis,
YAxis,
VerticalGridLines,
HorizontalGridLines,
VerticalBarSeries,
VerticalBarSeriesCanvas,
LabelSeries
} from 'react-vis';
export default class Example extends React.Component {
state = {
useCanvas: false
};
render() {
const {useCanvas} = this.state;
const BarSeries = useCanvas ? VerticalBarSeriesCanvas : VerticalBarSeries;
const content = useCanvas ? 'TOGGLE TO SVG' : 'TOGGLE TO CANVAS';
const data = [
[
{x: 1, y: 8},
{x: 3, y: 5},
{x: 4, y: 15}
],
[
{x: 3, y: 9},
{x: 4, y: 2},
{x: 5, y: 7}
],
[
{x: 2, y: 11},
{x: 3, y: 7},
{x: 4, y: 9}
]
];
const labelsData = data.map(value =>
value.map(tuple => ({x: tuple.x, y: tuple.y, label: tuple.y.toString()}))
);
const bars = data.map((value, index) => (
<BarSeries data={value} key={index} />
));
const labels = labelsData.map((value, index) => (
<LabelSeries
data={value}
key={index}
labelAnchorY="hanging"
style={{fill: '#ff8c00'}}
/>
));
return (
<div>
<ShowcaseButton
onClick={() => this.setState({useCanvas: !useCanvas})}
buttonContent={content}
/>
<XYPlot width={300} height={300} stackBy="y">
<VerticalGridLines />
<HorizontalGridLines />
<XAxis />
<YAxis />
{bars}
{labels}
</XYPlot>
</div>
);
}
}
|
examples/src/components/StatesField.js | namuol/react-select-seamstress | import React from 'react';
import Select from 'react-select';
const STATES = require('../data/states');
var id = 0;
function logChange() {
console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments)));
}
var StatesField = React.createClass({
displayName: 'StatesField',
propTypes: {
label: React.PropTypes.string,
searchable: React.PropTypes.bool,
},
getDefaultProps () {
return {
label: 'States:',
searchable: true,
};
},
getInitialState () {
return {
country: 'AU',
disabled: false,
searchable: this.props.searchable,
id: ++id,
selectValue: 'new-south-wales'
};
},
switchCountry (e) {
var newCountry = e.target.value;
console.log('Country changed to ' + newCountry);
this.setState({
country: newCountry,
selectValue: null
});
},
updateValue (newValue) {
logChange('State changed to ' + newValue);
this.setState({
selectValue: newValue || null
});
},
focusStateSelect () {
this.refs.stateSelect.focus();
},
toggleCheckbox (e) {
let newState = {};
newState[e.target.name] = e.target.checked;
this.setState(newState);
},
render () {
var ops = STATES[this.state.country];
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select ref="stateSelect" options={ops} disabled={this.state.disabled} value={this.state.selectValue} onChange={this.updateValue} searchable={this.state.searchable} />
<div style={{ marginTop: 14 }}>
<button type="button" onClick={this.focusStateSelect}>Focus Select</button>
<label className="checkbox" style={{ marginLeft: 10 }}>
<input type="checkbox" className="checkbox-control" name="searchable" checked={this.state.searchable} onChange={this.toggleCheckbox}/>
<span className="checkbox-label">Searchable</span>
</label>
<label className="checkbox" style={{ marginLeft: 10 }}>
<input type="checkbox" className="checkbox-control" name="disabled" checked={this.state.disabled} onChange={this.toggleCheckbox}/>
<span className="checkbox-label">Disabled</span>
</label>
</div>
<div className="checkbox-list">
<label className="checkbox">
<input type="radio" className="checkbox-control" checked={this.state.country === 'AU'} value="AU" onChange={this.switchCountry}/>
<span className="checkbox-label">Australia</span>
</label>
<label className="checkbox">
<input type="radio" className="checkbox-control" checked={this.state.country === 'US'} value="US" onChange={this.switchCountry}/>
<span className="checkbox-label">United States</span>
</label>
</div>
</div>
);
}
});
module.exports = StatesField;
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.