path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
src/components/RevealAuction/RevealAuctionJsonDialog.js | PhyrexTsai/ens-bid-dapp | import React from 'react';
import Dialog from 'material-ui/Dialog';
import Slide from 'material-ui/transitions/Slide';
import IconButton from 'material-ui/IconButton';
import CloseIcon from 'material-ui-icons/Close';
import Button from 'material-ui/Button';
import Card from 'material-ui/Card';
import TextField from 'material-ui/TextField';
import './RevealAuctionJsonDialog.css';
export const RevealAuctionJsonDialog = (props) => {
const disabled = (props.revealJson !== '') ? false : true;
const contextText = `{"name": "yourbid", "secret": "your secret", "value": "0.01", "address": "0x0000000000000000000000000000000000000000"}`;
return (
<Dialog
className="RevealAuctionJsonDialog"
open={props.importDialogOpen}
transition={Slide}>
<IconButton
color="primary"
onClick={props.handleImportDialogClose}
aria-label="Close">
<CloseIcon/>
</IconButton>
<div className="RevealAuctionJsonDialog-wrapper">
<Card className='RevealAuctionJsonDialog-card'>
<h2>Import Reveal Auction JSON</h2>
<p>Example:</p>
<p>{contextText}</p>
<TextField
className="RevealAuctionJsonDialog-formcontrol"
error={props.revealJsonErr}
id="revealJson"
name="revealJson"
label="Reveal Auction JSON"
value={props.revealJson}
onChange={props.handleInputChange}
margin="normal"
helperText={props.revealJsonErr ? props.revealJsonErrMsg : ''}
/>
<div className="RevealAuctionJsonDialog-button-container">
<Button
raised
disabled={disabled}
onClick={props.handleParseImportJson}>
Import
</Button>
</div>
</Card>
</div>
</Dialog>
);
} |
src/svg-icons/action/lock-open.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionLockOpen = (props) => (
<SvgIcon {...props}>
<path d="M12 17c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm6-9h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6h1.9c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm0 12H6V10h12v10z"/>
</SvgIcon>
);
ActionLockOpen = pure(ActionLockOpen);
ActionLockOpen.displayName = 'ActionLockOpen';
export default ActionLockOpen;
|
modules/react-docs/src/components/MarkdownTitle.js | conorhastings/react-color | /* jshint node: true, esnext: true */
"use strict";
import React from 'react';
import ReactCSS from 'reactcss';
class MarkdownTitle extends ReactCSS.Component {
constructor() {
super();
this.state = {
hover: false,
};
this.handleHover = this.handleHover.bind(this);
}
classes() {
return {
'default': {
link: {
opacity: '0',
textDecoration: 'none',
fill: this.props.primaryColor,
transition: 'opacity 200ms linear',
},
},
'hovered': {
link: {
opacity: '1',
},
},
};
}
styles() {
return this.css({
'hovered': this.state.hover,
});
}
handleHover(e) {
if (e.type === 'mouseenter') {
this.setState({ hover: true });
} else if (e.type === 'mouseleave') {
this.setState({ hover: false });
}
}
render() {
var linkSvg = {
__html: `
<svg style="width:24px;height:24px" viewBox="0 0 24 24">
<path d="M10.59,13.41C11,13.8 11,14.44 10.59,14.83C10.2,15.22 9.56,15.22 9.17,14.83C7.22,12.88 7.22,9.71 9.17,7.76V7.76L12.71,4.22C14.66,2.27 17.83,2.27 19.78,4.22C21.73,6.17 21.73,9.34 19.78,11.29L18.29,12.78C18.3,11.96 18.17,11.14 17.89,10.36L18.36,9.88C19.54,8.71 19.54,6.81 18.36,5.64C17.19,4.46 15.29,4.46 14.12,5.64L10.59,9.17C9.41,10.34 9.41,12.24 10.59,13.41M13.41,9.17C13.8,8.78 14.44,8.78 14.83,9.17C16.78,11.12 16.78,14.29 14.83,16.24V16.24L11.29,19.78C9.34,21.73 6.17,21.73 4.22,19.78C2.27,17.83 2.27,14.66 4.22,12.71L5.71,11.22C5.7,12.04 5.83,12.86 6.11,13.65L5.64,14.12C4.46,15.29 4.46,17.19 5.64,18.36C6.81,19.54 8.71,19.54 9.88,18.36L13.41,14.83C14.59,13.66 14.59,11.76 13.41,10.59C13,10.2 13,9.56 13.41,9.17Z" />
</svg>
`,
};
var title;
if (this.props.isHeadline) {
title = <h1>{ this.props.title } <a is="link" href={ '#' + this.props.link } dangerouslySetInnerHTML={ linkSvg } /></h1>;
} else {
title = <h2>{ this.props.title } <a is="link" href={ '#' + this.props.link } dangerouslySetInnerHTML={ linkSvg } /></h2>;
}
return (
<div onMouseEnter={ this.handleHover } onMouseLeave={ this.handleHover }>
{ title }
</div>
);
}
};
export default MarkdownTitle;
|
src/routes.js | jseminck/jseminck-be-main | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/App';
import LinksPage from "./components/Links";
import Game from "./components/Translation/Game";
import LoginPage from './components/Login';
import NotFoundPage from './components/NotFoundPage.js';
import ServerOverview from './components/Servers'; // eslint-disable-line import/no-named-as-default
export default (
<Route path="/" component={App}>
<IndexRoute component={LinksPage} />
<Route path="servers" component={ServerOverview} />
<Route path="translations" component={Game} />
<Route path="login" component={LoginPage} />
<Route path="*" component={NotFoundPage} />
</Route>
);
|
docs/src/app/components/pages/components/Snackbar/ExampleTwice.js | frnk94/material-ui | import React from 'react';
import Snackbar from 'material-ui/Snackbar';
import RaisedButton from 'material-ui/RaisedButton';
export default class SnackbarExampleTwice extends React.Component {
constructor(props) {
super(props);
this.state = {
message: 'Event 1 added to your calendar',
open: false,
};
this.timer = undefined;
}
componentWillUnMount() {
clearTimeout(this.timer);
}
handleTouchTap = () => {
this.setState({
open: true,
});
this.timer = setTimeout(() => {
this.setState({
message: `Event ${Math.round(Math.random() * 100)} added to your calendar`,
});
}, 1500);
};
handleRequestClose = () => {
this.setState({
open: false,
});
};
render() {
return (
<div>
<RaisedButton
onTouchTap={this.handleTouchTap}
label="Add to my calendar two times"
/>
<Snackbar
open={this.state.open}
message={this.state.message}
action="undo"
autoHideDuration={3000}
onRequestClose={this.handleRequestClose}
/>
</div>
);
}
}
|
server/sonar-web/src/main/js/apps/overview/main/components.js | vamsirajendra/sonarqube | import moment from 'moment';
import React from 'react';
import { Timeline } from './timeline';
export const Domain = React.createClass({
render () {
return <div className="overview-card">{this.props.children}</div>;
}
});
export const DomainTitle = React.createClass({
render () {
if (this.props.linkTo) {
let url = window.baseUrl + '/overview' + this.props.linkTo +
'?id=' + encodeURIComponent(this.props.component.key);
return <div>
<div className="overview-title">
{this.props.children}
<a className="small big-spacer-left link-no-underline" href={url}>
{window.t('more')}
<i className="icon-chevron-right" style={{ position: 'relative', top: -1 }}/>
</a>
</div>
</div>;
} else {
return <div className="overview-title">{this.props.children}</div>;
}
}
});
export const DomainLeakTitle = React.createClass({
renderInline (tooltip, fromNow) {
return <span className="overview-domain-leak-title" title={tooltip} data-toggle="tooltip">
<span>{window.tp('overview.leak_period_x', this.props.label)}</span>
<span className="note spacer-left">{window.tp('overview.started_x', fromNow)}</span>
</span>;
},
render() {
if (!this.props.label || !this.props.date) {
return null;
}
let momentDate = moment(this.props.date);
let fromNow = momentDate.fromNow();
let tooltip = 'Started on ' + momentDate.format('LL');
if (this.props.inline) {
return this.renderInline(tooltip, fromNow);
}
return <span className="overview-domain-leak-title" title={tooltip} data-toggle="tooltip">
<span>{window.tp('overview.leak_period_x', this.props.label)}</span>
<br/>
<span className="note">{window.tp('overview.started_x', fromNow)}</span>
</span>;
}
});
export const DomainHeader = React.createClass({
render () {
return <div className="overview-card-header">
<DomainTitle {...this.props}>{this.props.title}</DomainTitle>
</div>;
}
});
export const DomainPanel = React.createClass({
propTypes: {
domain: React.PropTypes.string
},
render () {
return <div className="overview-domain-panel">
{this.props.children}
</div>;
}
});
export const DomainNutshell = React.createClass({
render () {
return <div className="overview-domain-nutshell">{this.props.children}</div>;
}
});
export const DomainLeak = React.createClass({
render () {
return <div className="overview-domain-leak">{this.props.children}</div>;
}
});
export const MeasuresList = React.createClass({
render () {
return <div className="overview-domain-measures">{this.props.children}</div>;
}
});
export const Measure = React.createClass({
propTypes: {
label: React.PropTypes.string,
composite: React.PropTypes.bool
},
getDefaultProps() {
return { composite: false };
},
renderValue () {
if (this.props.composite) {
return this.props.children;
} else {
return <div className="overview-domain-measure-value">
{this.props.children}
</div>;
}
},
renderLabel() {
return this.props.label ?
<div className="overview-domain-measure-label">{this.props.label}</div> : null;
},
render () {
return <div className="overview-domain-measure">
{this.renderValue()}
{this.renderLabel()}
</div>;
}
});
export const DomainMixin = {
renderTimelineStartDate() {
let momentDate = moment(this.props.historyStartDate);
let fromNow = momentDate.fromNow();
return <span className="overview-domain-timeline-date">{window.tp('overview.started_x', fromNow)}</span>;
},
renderTimeline(range, displayDate) {
if (!this.props.history) {
return null;
}
let props = { history: this.props.history };
props[range] = this.props.leakPeriodDate;
return <div className="overview-domain-timeline">
<Timeline {...props}/>
{displayDate ? this.renderTimelineStartDate(range) : null}
</div>;
},
hasLeakPeriod () {
return this.props.leakPeriodDate != null;
}
};
|
src/svg-icons/image/photo-camera.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImagePhotoCamera = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="12" r="3.2"/><path d="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/>
</SvgIcon>
);
ImagePhotoCamera = pure(ImagePhotoCamera);
ImagePhotoCamera.displayName = 'ImagePhotoCamera';
ImagePhotoCamera.muiName = 'SvgIcon';
export default ImagePhotoCamera;
|
fixtures/ssr/src/index.js | ArunTesco/react | import React from 'react';
import {createRoot} from 'react-dom';
import App from './components/App';
let root = createRoot(document, {hydrate: true});
root.render(<App assets={window.assetManifest} />);
|
src/components/VmActions/WindowsRdpButton.js | mareklibra/userportal | import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { getRDP } from '_/actions'
import { isWindows } from '_/helpers'
import { canConsole } from '_/vm-status'
/**
* Button to send a RDP connection file to the user for a Windows VM.
*/
const WindowsRdpButton = ({ vm, className, config, onRDP, id }) => {
const isWindowsVM = isWindows(vm.getIn(['os', 'type']))
let component = null
if (isWindowsVM && canConsole(vm.get('status'))) {
const domain = config.get('domain')
const username = config.getIn([ 'user', 'name' ])
component = (
<a
id={id}
href='#'
key={vm.get('id')}
className={className}
onClick={(e) => { e.preventDefault(); onRDP(domain, username) }}
>
RDP
</a>
)
}
return component
}
WindowsRdpButton.propTypes = {
id: PropTypes.string.isRequired,
vm: PropTypes.object.isRequired,
className: PropTypes.string.isRequired,
config: PropTypes.object.isRequired,
onRDP: PropTypes.func.isRequired,
}
export default connect(
(state) => ({
config: state.config,
}),
(dispatch, { vm }) => ({
onRDP: (domain, username) => dispatch(getRDP({ name: vm.get('name'), fqdn: vm.get('fqdn'), domain, username })),
})
)(WindowsRdpButton)
|
src/components/Spinner.js | merrettr/school-ui | import React from 'react';
const Spinner = ({ scale = 1, visible = true }) =>
visible
? <div style={{ display: 'flex', justifyContent: 'center' }}>
<i className="fa fa-circle-o-notch fa-spin fa-3x fa-fw" style={{ fontSize: `${scale * 3}em` }}/>
<span className="sr-only">Loading...</span>
</div>
: <div></div>;
export default Spinner; |
src/svg-icons/image/photo-album.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImagePhotoAlbum = (props) => (
<SvgIcon {...props}>
<path d="M18 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM6 4h5v8l-2.5-1.5L6 12V4zm0 15l3-3.86 2.14 2.58 3-3.86L18 19H6z"/>
</SvgIcon>
);
ImagePhotoAlbum = pure(ImagePhotoAlbum);
ImagePhotoAlbum.displayName = 'ImagePhotoAlbum';
ImagePhotoAlbum.muiName = 'SvgIcon';
export default ImagePhotoAlbum;
|
app/javascript/mastodon/features/ui/components/actions_modal.js | imas/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import StatusContent from '../../../components/status_content';
import Avatar from '../../../components/avatar';
import RelativeTimestamp from '../../../components/relative_timestamp';
import DisplayName from '../../../components/display_name';
import IconButton from '../../../components/icon_button';
import classNames from 'classnames';
export default class ActionsModal extends ImmutablePureComponent {
static propTypes = {
status: ImmutablePropTypes.map,
actions: PropTypes.array,
onClick: PropTypes.func,
};
renderAction = (action, i) => {
if (action === null) {
return <li key={`sep-${i}`} className='dropdown-menu__separator' />;
}
const { icon = null, text, meta = null, active = false, href = '#' } = action;
return (
<li key={`${text}-${i}`}>
<a href={href} target='_blank' rel='noopener noreferrer' onClick={this.props.onClick} data-index={i} className={classNames({ active })}>
{icon && <IconButton title={text} icon={icon} role='presentation' tabIndex='-1' inverted />}
<div>
<div className={classNames({ 'actions-modal__item-label': !!meta })}>{text}</div>
<div>{meta}</div>
</div>
</a>
</li>
);
}
render () {
const status = this.props.status && (
<div className='status light'>
<div className='boost-modal__status-header'>
<div className='boost-modal__status-time'>
<a href={this.props.status.get('url')} className='status__relative-time' target='_blank' rel='noopener noreferrer'>
<RelativeTimestamp timestamp={this.props.status.get('created_at')} />
</a>
</div>
<a href={this.props.status.getIn(['account', 'url'])} className='status__display-name'>
<div className='status__avatar'>
<Avatar account={this.props.status.get('account')} size={48} />
</div>
<DisplayName account={this.props.status.get('account')} />
</a>
</div>
<StatusContent status={this.props.status} />
</div>
);
return (
<div className='modal-root__modal actions-modal'>
{status}
<ul className={classNames({ 'with-status': !!status })}>
{this.props.actions.map(this.renderAction)}
</ul>
</div>
);
}
}
|
examples/js/shopping-list-redux-hoc/client/containers/App.js | reimagined/resolve | import React from 'react'
import { renderRoutes } from 'react-router-config'
import Header from './Header'
const App = ({ route }) => (
<div>
<Header
title="ReSolve Shopping List Example"
name="Shopping Lists Example"
favicon="/favicon.png"
css={['/bootstrap.min.css', '/fontawesome.min.css', '/style.css']}
/>
{renderRoutes(route.routes)}
</div>
)
export default App
|
client/node_modules/uu5g03/dist-node/forms-v3/select.js | UnicornCollege/ucl.itkpd.configurator | import React from 'react';
import {BaseMixin, ElementaryMixin, ContentMixin, LsiMixin, Tools} from './../common/common.js';
import Backdrop from './../bricks/backdrop.js';
import Span from './../bricks/span.js';
import Link from './../bricks/link.js';
import ItemList from './internal/item-list.js';
import Label from './internal/label.js';
import InputWrapper from './internal/input-wrapper.js';
import ItemsInput from './internal/items-input.js';
import ChoiceMixin from './mixins/choice-mixin.js';
import InputMixin from './mixins/input-mixin.js';
import SelectOption from './select-option.js';
import './select.less';
export const Select = React.createClass({
//@@viewOn:mixins
mixins: [
BaseMixin,
ElementaryMixin,
ContentMixin,
InputMixin,
ChoiceMixin,
LsiMixin
],
//@@viewOff:mixins
//@@viewOn:statics
statics: {
tagName: 'UU5.Forms.Select',
classNames: {
main: 'uu5-forms-select',
link: 'uu5-forms-select-link',
open: 'uu5-forms-select-open'
},
defaults: {
childTagName: 'UU5.Forms.Select.option'
},
lsi: {
selectAll: {
cs: 'Vybrat vše',
en: 'Select all'
},
unselectAll: {
cs: 'Odebrat vše',
en: 'Deselect all'
}
}
},
//@@viewOff:statics
//@@viewOn:propTypes
propTypes: {
value: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.arrayOf(React.PropTypes.string)
]),
multiple: React.PropTypes.bool,
selectAllEnabled: React.PropTypes.bool,
allowTags: React.PropTypes.array
},
//@@viewOff:propTypes
//@@viewOn:getDefaultProps
getDefaultProps () {
return {
value: null,
multiple: false,
allowTags: [],
selectAllEnabled: false
};
},
//@@viewOff:getDefaultProps
//@@viewOn:standardComponentLifeCycle
getInitialState () {
return {
opened: false
};
},
componentWillMount(){
let value = [];
if (this.props.value) {
value = this._valuesToValuesArray(this.props.value);
}
if (this.props.onValidate && typeof this.props.onValidate === 'function') {
this._validateOnChange({value: value, event: null, component: this})
} else {
this.setInitial(null, value)
}
return this;
},
componentWillReceiveProps(nextProps) {
let value = this._valuesToValuesArray(nextProps.value, nextProps.children);
if (nextProps.controlled) {
this.setFeedback(nextProps.feedback, nextProps.message, value)
}
return this;
},
//@@viewOff:standardComponentLifeCycle
//@@viewOn:interface
isOpened () {
return this.state.opened;
},
open (setStateCallback) {
this.setState({opened: true}, setStateCallback);
return this;
},
close (setStateCallback) {
this.setState({opened: false}, setStateCallback);
return this;
},
toggle (setStateCallback) {
this.setState((state) => ({opened: !state.opened}), setStateCallback);
return this;
},
addValue: function (index, setStateCallback) {
if (this.props.multiple) {
var indexes = this.getValue() || [];
var indexPosition = indexes.indexOf(index);
if (indexPosition === -1) {
indexes.push(index);
this.setValue(indexes, setStateCallback);
} else if (typeof setStateCallback === 'function') {
setStateCallback();
}
} else {
this.showWarning('notMultiple', 'addValue');
}
return this;
},
removeValue(opt, setStateCallback){
if (typeof this.props.onChange === 'function') {
opt.component = this;
//opt.value = this._itemList.getRenderedChildren()[opt.index].props.value;
this._itemList.getRenderedChildren().forEach((child)=> {
let value = child ? child.props.selectedContent || child.props.content || child.props.children || child.props.value : null;
if (value === opt.value) {
opt.value = child.props.value;
}
});
this.props.multiple ? this.props.onChange(opt) : this.toggle(() => this.props.onChange(opt));
} else {
var values = this.getValue() || [];
if (opt.index > -1) {
values.splice(opt.index, 1);
!values.length && (values = null);
if (!this.isOpened() && this.props.required) {
if (values !== null) {
this.setValue(values, setStateCallback);
} else {
this.setError(this.props.requiredMessage, null, setStateCallback);
}
} else {
this.setValue(values, setStateCallback);
}
} else if (typeof setStateCallback === 'function') {
setStateCallback();
}
}
},
//@@viewOff:interface
//@@viewOn:overridingMethods
_valuesToValuesArray(newValue, newChildren){
let value = [];
let children = newChildren || this.getChildren();
for (let i = 0; i < children.length; i++) {
let childValue = children[i].props.value;
if (typeof newValue === 'string') {
if (newValue === childValue) {
value.push(i);
}
} else if (newValue && newValue.length > 0) {
if (newValue.indexOf(childValue) > -1) {
value.push(i);
}
}
}
return value;
},
setValue_(value, setStateCallback){
let result = [];
let children = this.getChildren();
for (let i = 0; i < children.length; i++) {
let childValue = children[i].props.value;
if (typeof value === 'string') {
if (value === childValue) {
result.push(i);
}
} else if (value && value.length > 0) {
if (value.indexOf(childValue) > -1) {
result.push(i);
}
}
}
this.setState({value: result || []}, setStateCallback);
},
setFeedback_(feedback, message, value, setStateCallback){
if (typeof value === 'string') {
value = this._valuesToValuesArray(value);
}
this.setState({
feedback: feedback,
message: message,
value: value || []
}, setStateCallback);
return this;
},
getValue_(){
let result = [];
if (this.state.value) {
for (let i = 0; i < this.state.value.length; i++) {
result.push(this._itemList.getRenderedChildren()[this.state.value[i]].props.value)
}
}
return this.props.multiple ? result : result[0];
},
shouldChildRender_(child) {
let childTagName = Tools.getChildTagName(child);
let childTagNames = this.props.allowTags.concat(this.getDefault().childTagName);
return childTagNames.indexOf(childTagName) > -1;
},
//@@viewOff:overridingMethods
//@@viewOn:componentSpecificHelpers
_validateOnChange(opt){
let result = typeof this.props.onValidate === 'function' ? this.props.onValidate(opt) : null;
if (result) {
if (typeof result === 'object') {
if (result.feedback) {
this.setFeedback(result.feedback, result.message, result.value);
} else {
this.setState({value: opt.value});
}
} else {
this.showError('validateError', null, {context: {event: e, func: this.props.onValidate, result: result}});
}
} else if (this.props.required && opt.value.length > 0) {
this.setSuccess(null, opt.value)
} else {
this.setInitial(null, opt.value)
}
return this;
},
_getFeedbackIcon(){
let icon = this.props.required ? this.props.successGlyphicon : null;
switch (this.getFeedback()) {
case 'success':
icon = this.props.successGlyphicon;
break;
case 'warning':
icon = this.props.warningGlyphicon;
break;
case 'error':
icon = this.props.errorGlyphicon;
break;
}
return icon;
},
_getBackdropProps () {
var backdropId = this.getId() + "-backdrop";
return {
hidden: !this.isOpened(),
id: backdropId,
onClick: () => this._onChange({opened: !this.isOpened()})
};
},
_getTextInputAttrs () {
var props = {};
if (!this.state.isReadOnly && !this.isDisabled()) {
var input = this;
props.onClick = function () {
input.open();
};
}
return props;
},
_getItemListProps(){
let props = {};
let multiple = this.props.multiple;
props.hidden = !this.isOpened();
props.ref = (itemList) => this._itemList = itemList;
props.onChange = (opt) => this._onChange(opt);
props.value = this.state.value;
props.multiple = this.props.multiple;
return props;
},
_onChange(opt){
let multiple = this.props.multiple;
let requiredResult = this._checkRequired((opt && opt.value > -1) ? opt.value : this.state.value);
if (this.isOpened() && opt && opt.value > -1) {
let value = [];
if (opt.value !== null) {
if (multiple) {
if (this.state.value && this.state.value.length > 0) {
// && (value = Tools.merge([], this.state.value));
for (let i = 0; i < this.state.value.length; i++) {
value.push(this.state.value[i]);
}
}
if (opt.value != this.state.value || this.state.value.length === 0) {
let itemPosition = value.indexOf(opt.value);
if (itemPosition < 0) {
value.push(opt.value);
} else {
value.splice(itemPosition, 1);
}
} else {
value = [];
}
} else {
value = [opt.value];
}
}
let result = value;
if (typeof this.props.onChange === 'function') {
opt.component = this;
opt.value = this._itemList.getRenderedChildren()[opt.value].props.value;
multiple ? this.props.onChange(opt) : this.toggle(() => this.props.onChange(opt));
} else {
if (requiredResult) {
multiple ? this.setInitial(null, result) : this.setInitial(null, result, () => this.toggle());
} else {
this.setError(this.props.requiredMessage, null, () => this.toggle());
}
}
} else if (opt && !opt.opened && this.props.required) {
if (requiredResult) {
this.toggle(() => this.setSuccess(null, this.state.value));
} else {
this.setError(this.props.requiredMessage, null, () => this.toggle());
}
} else {
if (requiredResult) {
this.toggle(() => this.setInitial(null, this.state.value));
} else {
this.setError(this.props.requiredMessage, null, () => this.toggle());
}
}
return this;
},
_checkRequired(value){
let result = true;
if (((!value && value != 0) || value.length < 1) && this.props.required && this.isOpened()) {
result = false;
}
return result;
},
_getMainAttrs(){
let attrs = this._getInputAttrs();
if (this.isOpened()) {
attrs.className += ' ' + this.getClassName().open;
}
return attrs;
},
_getFeedbackIcon(){
let icon = this.props.required ? this.props.successGlyphicon : null;
switch (this.getFeedback()) {
case 'success':
icon = this.props.successGlyphicon;
break;
case 'warning':
icon = this.props.warningGlyphicon;
break;
case 'error':
icon = this.props.errorGlyphicon;
break;
}
return icon;
},
_getItemValues(children){
let result = [];
if (this.props.placeholder && children === null) {
result.push(<Span className={this.getClassName().placeholder} content={this.props.placeholder}/>);
}
if (children && this.state.value) {
for (let i = 0; i < this.state.value.length; i++) {
let child = children[this.state.value[i]];
let childContent = child ? child.props.selectedContent || child.props.content || child.props.children || child.props.value : null;
result.push(childContent);
}
}
return result;
},
_getHeader(){
let result;
if (this.props.selectAllEnabled && this.props.multiple) {
let label = this._isSelectedAll() ? this.getLSIValue('unselectAll') : this.getLSIValue('selectAll');
result = <Link content={label} onClick={this._select} className={this.getClassName().link} colorSchema='primary'/>
}
return result;
},
_isSelectedAll() {
let result = false;
if (this.props.children && this.state.value && this.props.children.length === this.state.value.length) {
result = true;
}
return result;
},
_select(){
let result = [];
if (this._isSelectedAll()) {
} else {
this.props.children && this.props.children.forEach((item, i) => {
result.push(i);
});
}
this.setState({value: result});
return this;
},
_getChildren(){
let children = [];
if (this.props.children) {
let childTagNames = this.props.allowTags.concat(this.getDefault().childTagName);
React.Children.toArray(this.props.children).forEach((child) => {
let childTagName = Tools.getChildTagName(child);
if (childTagNames.indexOf(childTagName) > -1) {
children.push(child);
}
})
}
return children;
},
//@@viewOff:componentSpecificHelpers
//@@viewOn:render
render () {
let inputId = this.getId() + '-input';
let buttons = !this.isReadOnly() && !this.props.buttonHidden ? [{
glyphicon: this.isOpened() ? this.props.glyphiconOpened : this.props.glyphiconClosed,
disabled: this.isDisabled(),
onClick: () => this._onChange(),
pressed: this.isOpened(),
colorSchema: 'default'
}] : null;
let children = this._getChildren();
return (
<div {...this._getMainAttrs()}>
<Label
for={inputId}
content={this.props.label}
colWidth={this._buildColWidthClassName(this.props.labelColWidth)}/>
{this.getInputWrapper([
<ItemsInput
id={inputId}
name={this.props.name || inputId}
value={this._getItemValues(children)}
placeholder={this.props.placeholder}
multiple={this.props.multiple}
disabled={this.isDisabled() || this.isLoading()}
readonly={this.isReadOnly()}
loading={this.isLoading()}
onItemClick={(opt) => {
this.removeValue(opt)
}}
onClick={(!this.isReadOnly() && !this.isDisabled()) ? () => this._onChange() : null}
glyphicon={this._getFeedbackIcon()}
/>,
<ItemList {...this._getItemListProps()} header={this._getHeader()}>
{children}
</ItemList>,
<Backdrop {...this._getBackdropProps()} />],
buttons)}
</div>
);
}
//@@viewOn:render
});
Select.Option = SelectOption;
export default Select;
|
react-native/nativebase/js/components/semana/DayListItem.js | lemol/diario-escola-sabatina |
import React, { Component } from 'react';
import { TouchableOpacity, View } from 'react-native';
import { Text, Button, Icon, H3, H2, H1, List, ListItem } from 'native-base';
import { Grid, Row, Col } from 'react-native-easy-grid';
import styles from './styles';
export default function({ dia: { tema, data }, openDay, key}) {
return (
<ListItem key={key}>
<Grid>
<Row>
<Col size={1}>
<Row><Text>AA</Text></Row>
<Row><Text>{data}</Text></Row>
<Row><Text>BB</Text></Row>
</Col>
<Col size={4} style={{ justifyContent: 'center'}}>
<Text style={styles.itemTema}>{tema.toUpperCase()}</Text>
</Col>
</Row>
</Grid>
</ListItem>
);
}
|
assets/js/components/score.js | CandN/eliscore | import React from 'react'
class Score extends React.Component {
render () {
const { score, opponentScore } = this.props
let scoreClass
if (score === opponentScore) {
scoreClass = 'draw'
} else if (score < opponentScore) {
scoreClass = 'lost'
} else {
scoreClass = 'win'
}
return (
<div className={'player__score_' + scoreClass + ' col-xs-1 player__score'}>
{score}
</div>
)
}
}
export default Score
|
src/components/About/Bio/Bio.js | jumpalottahigh/jumpalottahigh.github.io | import React from 'react'
import styled from 'styled-components'
import { Link } from 'gatsby'
import Button from '../../elements/Button/Button.js'
import H2 from '../../elements/H2/H2.js'
import CenteredDiv from '../../elements/CenteredDiv/CenteredDiv.js'
const StyledBio = styled.section`
background: #dedede;
`
const Bio = () => (
<StyledBio>
<H2>{ If you want to learn even more about me... }</H2>
<CenteredDiv>
<Link to="/bio/">
<Button>Full Bio</Button>
</Link>
</CenteredDiv>
</StyledBio>
)
export default Bio
|
node_modules/babel-plugin-react-transform/test/fixtures/code-ignore/expected.js | MaleSharker/Qingyan | import React from 'react';
const First = React.createNotClass({
displayName: 'First'
});
class Second extends React.NotComponent {}
|
src/components/product/item.js | RamEduard/admin-lte-express | /**
* Created by Ramon Serrano <[email protected]>
* Date: 5/24/16
* Time: 2:03 PM
*/
import React from 'react';
import { Link } from 'react-router';
import AppStore from '../../stores/app-store';
import StoreWatchMixin from '../../mixins/StoreWatchMixin';
import AppActions from '../../actions/app-actions'
import CartButton from '../cart/button';
function getCatalogItem( props ){
let item = AppStore.getCatalog().find( ({ id }) => id === props.params.item )
return {item}
}
const CatalogDetail = (props) => {
return (
<div>
<h4>{ props.item.title }</h4>
<img src="http://placehold.it/250x250" />
<p>{ props.item.description }</p>
<p>${ props.item.cost } <span
className="text-success">
{ props.item.qty && `(${props.item.qty} in cart)`}
</span>
</p>
<div className="btn-group">
<Link to="/" className="btn btn-default btn-sm">Continue Shopping</Link>
<CartButton
handler={
AppActions.addItem.bind(null, props.item)
}
txt="Add To Cart"
/>
</div>
</div>
)
}
export default StoreWatchMixin( CatalogDetail, getCatalogItem )
|
react-flux/demo01/js/components/UXKit/Icon.js | majunbao/xue | import React from 'react';
class Icon extends React.Component {
render() {
return (
<i></i>
)
}
}
// ×
// ✓ |
StateProps/main.js | tareque20/react | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app')); |
server/sonar-web/src/main/js/apps/projects/header.js | vamsirajendra/sonarqube | import React from 'react';
import CreateView from './create-view';
export default React.createClass({
propTypes: {
hasProvisionPermission: React.PropTypes.bool.isRequired
},
createProject() {
new CreateView({
refresh: this.props.refresh
}).render();
},
renderCreateButton() {
if (!this.props.hasProvisionPermission) {
return null;
}
return <button onClick={this.createProject}>Create Project</button>;
},
render() {
return (
<header className="page-header">
<h1 className="page-title">Projects Management</h1>
<div className="page-actions">{this.renderCreateButton()}</div>
<p className="page-description">Use this page to delete multiple projects at once, or to provision projects
if you would like to configure them before the first analysis. Note that once a project is provisioned, you
have access to perform all project configurations on it.</p>
</header>
);
}
});
|
src/client/pages/search-page.react.js | lassecapel/este-isomorphic-app | import React from 'react';
import DocumentTitle from 'react-document-title';
import SearchBox from '../search/search-box.react';
import ProductList from '../products/product-list.react';
import SearchMessage from '../search/search-message.react';
import Pagination from '../products/pagination.react';
import {getProducts, getTotal} from '../products/store';
import {getSearchQuery} from '../search/store';
export default class SearchPage extends React.Component {
render() {
return (
<DocumentTitle title='Webshop Search'>
<div>
<div className='row'>
<h1>Search page</h1>
<SearchBox query={getSearchQuery()}/>
</div>
<div>
<Pagination/>
<SearchMessage total={getTotal()} query={getSearchQuery()}/>
<ProductList products={getProducts()}/>
</div>
</div>
</DocumentTitle>
);
}
}
|
src/ReactBoilerplate/Scripts/components/TwoFactor/VerifyCodeForm.js | theonlylawislove/react-dot-net | import React from 'react';
import Form from 'components/Form';
import { reduxForm } from 'redux-form';
import { Input } from 'components';
import { verifyCode } from 'redux/modules/account';
class VerifyCodeForm extends Form {
modifyValues(values) {
return {
...values,
provider: this.props.sentCodeWithProvider
};
}
render() {
const {
fields: { code, rememberMe, rememberBrowser }
} = this.props;
return (
<form onSubmit={this.handleApiSubmit(verifyCode)} className="form-horizontal">
{this.renderGlobalErrorList()}
<Input field={code} label="Code" />
<Input field={rememberMe} type="checkbox" label="Remember me" />
<Input field={rememberBrowser} type="checkbox" label="Remember browser" />
<div className="form-group">
<div className="col-md-offset-2 col-md-10">
<button type="submit" className="btn btn-default">Verify</button>
</div>
</div>
</form>
);
}
}
VerifyCodeForm = reduxForm({
form: 'verifyCode',
fields: ['code', 'rememberMe', 'rememberBrowser']
},
(state) => ({
sentCodeWithProvider: state.account.sentCodeWithProvider,
initialValues: {
rememberMe: true,
rememberBrowser: true
}
}),
{ }
)(VerifyCodeForm);
export default VerifyCodeForm;
|
src/components/Footer.js | vitorbarbosa19/ziro-online | import React from 'react'
import Link from 'gatsby-link'
import { buttonStyleBright } from '../styles/styles'
export default (props) => (
<div>
{props.page !== '/acesso'
? <div
style={{
position: 'fixed',
bottom: '0',
width: '100%',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
fontSize: '13px',
fontFamily: 'hind vadodara',
color: '#fff',
backgroundColor: 'rgba(48, 62, 77, 0.95)',
padding: '12px 0',
boxShadow: '0px -2px 6px 1px rgba(0,0,0,0.1), 0px -2px 6px 1px rgba(0,0,0,0.1)'
}}>
<p
style={{
margin: '0 10px 0 0'
}}>
Quer ver preços? Acesse com seu CNPJ
</p>
<Link style={buttonStyleBright} to='/acesso'>Ver preços</Link>
</div>
: null
}
</div>
)
|
react-dev/pages/post.js | 575617819/yanghang | import React, { Component } from 'react';
import Paper from 'material-ui/Paper';
import { blueGrey800, grey50, teal900, green900, green500, teal500, cyan500 } from 'material-ui/styles/colors';
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
//it's safe to use dangerouslySetInnerHTML because all components under /pages
//are going to be statically generated and placed in a position for Jekyll to use
const muiTheme = getMuiTheme(darkBaseTheme, {
palette: {
primary1Color: blueGrey800,
primary2Color: green900,
primary3Color: teal900,
accent1Color: green500,
accent2Color: teal500,
accent3Color: cyan500,
textColor: grey50,
alternateTextColor: grey50, //color on header
//pickerHeaderColor: grey900
},
appBar: {
height: 100
},
});
class Post extends Component {
createMarkup(markup) {
return { __html: markup };
}
render() {
return (
<MuiThemeProvider muiTheme={muiTheme}>
<div className="single-post-content" id="single-post-content">
<Paper zDepth={4} className="paper-wrapper" id="post-static-content">
<article className="post" itemScope itemType="http://schema.org/BlogPosting">
<header className="post-header">
<h1 className="post-title" itemProp="name headline">{'{{ page.title }}'}</h1>
<p className="post-meta">
<time
dateTime="{`{{ page.date | date_to_xmlschema }}`}" itemProp="datePublished"
dangerouslySetInnerHTML={this.createMarkup("{{ page.date | date: '%b %-d, %Y'}}")}
/>
{'{% if page.author %}'} • <span itemProp="author" itemScope itemType="http://schema.org/Person"><span itemProp="name">{'{{ page.author }}'}</span></span>{'{% endif %}'}</p>
</header>
<div className="post-content" itemProp="articleBody">
{'{{ content }}'}
</div>
</article>
</Paper>
</div>
</MuiThemeProvider>
);
}
}
export default Post;
|
packages/strapi-plugin-content-manager/admin/src/containers/Edit/index.js | lucusteen/strap | /*
*
* Edit
*
*/
import React from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import _ from 'lodash';
import { router } from 'app';
import { define } from 'i18n';
import Container from 'components/Container';
import EditForm from 'components/EditForm';
import { makeSelectSchema } from 'containers/App/selectors';
import EditFormRelations from 'components/EditFormRelations';
import {
setInitialState,
setCurrentModelName,
setIsCreating,
loadRecord,
setRecordAttribute,
editRecord,
deleteRecord,
} from './actions';
import {
makeSelectRecord,
makeSelectLoading,
makeSelectCurrentModelName,
makeSelectEditing,
makeSelectDeleting,
makeSelectIsCreating,
} from './selectors';
import messages from './messages.json';
define(messages);
export class Edit extends React.Component {
componentWillMount() {
this.props.setInitialState();
this.props.setCurrentModelName(this.props.routeParams.slug.toLowerCase());
// Detect that the current route is the `create` route or not
if (this.props.routeParams.id === 'create') {
this.props.setIsCreating();
} else {
this.props.loadRecord(this.props.routeParams.id);
}
}
render() {
const PluginHeader = this.props.exposedComponents.PluginHeader;
let content = <p>Loading...</p>;
let relations;
if (!this.props.loading && this.props.schema && this.props.currentModelName) {
content = (
<EditForm
record={this.props.record}
currentModelName={this.props.currentModelName}
schema={this.props.schema}
setRecordAttribute={this.props.setRecordAttribute}
editRecord={this.props.editRecord}
editing={this.props.editing}
/>
);
relations = (
<EditFormRelations
currentModelName={this.props.currentModelName}
record={this.props.record}
schema={this.props.schema}
setRecordAttribute={this.props.setRecordAttribute}
/>
);
}
// Define plugin header actions
const pluginHeaderActions = [
{
label: messages.cancel,
class: 'btn-default',
onClick: () => {
router.push(`/plugins/content-manager/${this.props.currentModelName}`);
},
},
{
label: this.props.editing ? messages.editing : messages.submit,
class: 'btn-primary',
onClick: this.props.editRecord,
disabled: this.props.editing,
},
];
// Add the `Delete` button only in edit mode
if (!this.props.isCreating) {
pluginHeaderActions.push({
label: messages.delete,
class: 'btn-danger',
onClick: this.props.deleteRecord,
disabled: this.props.deleting,
});
}
// Plugin header config
const pluginHeaderTitle = _.get(this.props.schema, [this.props.currentModelName, 'label']) || 'Content Manager';
const pluginHeaderDescription = this.props.isCreating
? 'New entry'
: `#${this.props.record && this.props.record.get('id')}`;
return (
<div className="col-md-12">
<div className="container-fluid">
<PluginHeader
title={{
id: 'plugin-content-manager-title',
defaultMessage: `${pluginHeaderTitle}`,
}}
description={{
id: 'plugin-content-manager-description',
defaultMessage: `${pluginHeaderDescription}`,
}}
actions={pluginHeaderActions}
/>
<Container>
<div className="row">
<div className="col-md-8">
{content}
{relations}
</div>
</div>
</Container>
</div>
</div>
);
}
}
Edit.propTypes = {
currentModelName: React.PropTypes.oneOfType([
React.PropTypes.bool,
React.PropTypes.string,
]),
deleteRecord: React.PropTypes.func.isRequired,
deleting: React.PropTypes.bool.isRequired,
editing: React.PropTypes.bool.isRequired,
editRecord: React.PropTypes.func.isRequired,
exposedComponents: React.PropTypes.object.isRequired,
isCreating: React.PropTypes.bool.isRequired,
loading: React.PropTypes.bool.isRequired,
loadRecord: React.PropTypes.func.isRequired,
record: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.bool,
]),
routeParams: React.PropTypes.object.isRequired,
schema: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.bool,
]),
setCurrentModelName: React.PropTypes.func.isRequired,
setInitialState: React.PropTypes.func.isRequired,
setIsCreating: React.PropTypes.func.isRequired,
setRecordAttribute: React.PropTypes.func.isRequired,
};
const mapStateToProps = createStructuredSelector({
record: makeSelectRecord(),
loading: makeSelectLoading(),
currentModelName: makeSelectCurrentModelName(),
editing: makeSelectEditing(),
deleting: makeSelectDeleting(),
isCreating: makeSelectIsCreating(),
schema: makeSelectSchema(),
});
function mapDispatchToProps(dispatch) {
return {
setInitialState: () => dispatch(setInitialState()),
setCurrentModelName: currentModelName =>
dispatch(setCurrentModelName(currentModelName)),
setIsCreating: () => dispatch(setIsCreating()),
loadRecord: id => dispatch(loadRecord(id)),
setRecordAttribute: (key, value) =>
dispatch(setRecordAttribute(key, value)),
editRecord: () => dispatch(editRecord()),
deleteRecord: () => {
// TODO: improve confirmation UX.
if (window.confirm('Are you sure ?')) {
// eslint-disable-line no-alert
dispatch(deleteRecord());
}
},
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Edit);
|
src/components/Day.js | mohebifar/react-persian-datepicker | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { persianNumber } from '../utils/persian';
const styles = {
wrapper: {},
button: {
outline: 'none',
cursor: 'pointer'
}
};
export default class Day extends Component {
static propTypes = {
day: PropTypes.object.isRequired,
isCurrentMonth: PropTypes.bool,
disabled: PropTypes.bool,
selected: PropTypes.bool,
onClick: PropTypes.func
};
shouldComponentUpdate(nextProps) {
return nextProps.selected !== this.props.selected ||
nextProps.disabled !== this.props.disabled ||
nextProps.isCurrentMonth !== this.props.isCurrentMonth;
}
handleClick(event) {
event.preventDefault();
event.stopPropagation();
event.nativeEvent.stopImmediatePropagation();
const { onClick, day } = this.props;
if (onClick) {
onClick(day);
}
}
render() {
const { day, disabled, selected, isCurrentMonth, onClick, styles, ...rest } = this.props;
const className = classnames(styles.dayWrapper, {
[styles.selected]: selected,
[styles.currentMonth]: isCurrentMonth
});
return (
<div className={className}>
<button
type="button"
onClick={this.handleClick.bind(this) }
disabled={disabled}
{...rest}
>
{ persianNumber(day.format('jD')) }
</button>
</div>
);
}
}
|
entry_types/scrolled/package/spec/support/pageObjects.js | tf/pageflow | import React from 'react';
import {renderInEntry} from './rendering';
import {Entry} from 'frontend/Entry';
import foregroundStyles from 'frontend/Foreground.module.css';
import {loadInlineEditingComponents} from 'frontend/inlineEditing';
import {api} from 'frontend/api';
import {act, fireEvent, queryHelpers, queries, within} from '@testing-library/react'
import {useFakeTranslations} from 'pageflow/testHelpers';
import {simulateScrollingIntoView} from './fakeIntersectionObserver';
export function renderEntry({seed, consent} = {}) {
return renderInEntry(<Entry />, {
seed,
consent,
queries: {...queries, ...pageObjectQueries}
});
}
export function useInlineEditingPageObjects() {
beforeAll(async () => {
await loadInlineEditingComponents();
});
useFakeTranslations({
'pageflow_scrolled.inline_editing.select_section': 'Select section',
'pageflow_scrolled.inline_editing.select_content_element': 'Select content element',
'pageflow_scrolled.inline_editing.add_content_element': 'Add content element',
'pageflow_scrolled.inline_editing.insert_content_element.after': 'Insert content element after',
'pageflow_scrolled.inline_editing.drag_content_element': 'Drag to move',
'pageflow_scrolled.inline_editing.edit_section_transition_before': 'Edit section transition before',
'pageflow_scrolled.inline_editing.edit_section_transition_after': 'Edit section transition after'
});
usePageObjects();
}
export function usePageObjects() {
beforeEach(() => {
jest.restoreAllMocks();
api.contentElementTypes.register('withTestId', {
component: function WithTestId({configuration}) {
return (
<div data-testid={`contentElement-${configuration.testId}`} />
);
}
});
});
}
const pageObjectQueries = {
getSectionByPermaId(container, permaId) {
const el = queryHelpers.queryByAttribute('id',
container,
`section-${permaId}`);
if (!el) {
throw queryHelpers.getElementError(
`Unable to find section with perma id ${permaId}.`,
container
);
}
return createSectionPageObject(el);
},
getContentElementByTestId(container, testId) {
const el = queryHelpers.queryByAttribute('data-testid',
container,
`contentElement-${testId}`);
if (!el) {
throw queryHelpers.getElementError(
`Unable to find content element with testId id ${testId}.`,
container
);
}
return createContentElementPageObject(el);
},
fakeContentElementBoundingClientRectsByTestId(container, rectsByTestId) {
jest.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function() {
const testIdAttribute = this.querySelector('[data-testid]')?.getAttribute('data-testid');
const testId = testIdAttribute?.split('-')[1];
return {
top: 0,
left: 0,
width: 0,
height: 0,
bottom: 0,
right: 0,
...(testId ? rectsByTestId[testId] : {})
};
});
}
}
function createSectionPageObject(el) {
const selectionRect = el.closest('[aria-label="Select section"]');
const foreground = el.querySelector(`.${foregroundStyles.Foreground}`);
return {
el,
simulateScrollingIntoView() {
act(() => simulateScrollingIntoView(el));
},
select() {
fireEvent.mouseDown(selectionRect);
},
clickAddContentElement() {
const {getByTitle} = within(selectionRect);
fireEvent.click(getByTitle('Add content element'));
},
clickEditTransitionBefore() {
const {getByTitle} = within(selectionRect);
fireEvent.mouseDown(getByTitle('Edit section transition before'));
},
clickEditTransitionAfter() {
const {getByTitle} = within(selectionRect);
fireEvent.mouseDown(getByTitle('Edit section transition after'));
},
hasBottomPadding() {
return foreground.classList.contains(foregroundStyles.paddingBottom);
}
}
}
function createContentElementPageObject(el) {
const selectionRect = el.closest('[aria-label="Select content element"]');
return {
select() {
fireEvent.click(selectionRect);
},
clickInsertAfterButton() {
const {getByTitle} = within(selectionRect);
fireEvent.click(getByTitle('Insert content element after'));
},
drag(at, otherContentElement) {
const {getByTitle} = within(selectionRect);
fireEvent.dragStart(getByTitle('Drag to move'));
otherContentElement._drop(at);
},
_drop(at) {
const {getByTestId} = within(selectionRect);
const target = getByTestId(`drop-${at}`);
fireEvent.drop(target);
}
}
}
|
app/containers/Record/index.js | Omnicrola/panoptes-react | /*
*
* Record
*
*/
import React from 'react';
import {connect} from 'react-redux';
import Helmet from 'react-helmet';
import selectRecord from './selectors';
import {FormattedMessage} from 'react-intl';
import messages from './messages';
import TimeForm from 'components/TimeForm';
import TimeEntryList from 'components/TimeEntryList';
export class Record extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
this.state = {
timeEntries: []
}
}
onEntryCreated(newEntry) {
let entries = this.state.timeEntries.slice()
entries.push(newEntry);
this.setState({
timeEntries: entries
});
}
render() {
return (
<div className={'row record-new-entry'}>
<Helmet
title="Record"
meta={[
{name: 'description', content: 'Description of Record'},
]}
/>
<h1><FormattedMessage {...messages.header} /></h1>
<TimeForm
onCreateEntry={(entry) => {
this.onEntryCreated(entry);
}}
/>
<h2><FormattedMessage {...messages.listHeader}/></h2>
<TimeEntryList items={this.state.timeEntries}/>
</div>
);
}
}
const mapStateToProps = selectRecord();
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Record);
|
node_modules/@expo/vector-icons/vendor/react-native-vector-icons/lib/tab-bar-item-ios.js | jasonlarue/react-native-flashcards | import { isEqual, pick } from 'lodash';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { TabBarIOS } from './react-native';
export default function createTabBarItemIOSComponent(
IconNamePropType,
getImageSource
) {
return class TabBarItemIOS extends Component {
static propTypes = {
iconName: IconNamePropType.isRequired,
selectedIconName: IconNamePropType,
iconSize: PropTypes.number,
iconColor: PropTypes.string,
selectedIconColor: PropTypes.string,
};
static defaultProps = {
iconSize: 30,
};
updateIconSources(props) {
if (props.iconName) {
getImageSource(
props.iconName,
props.iconSize,
props.iconColor
).then(icon => this.setState({ icon }));
}
if (props.selectedIconName || props.selectedIconColor) {
const selectedIconName = props.selectedIconName || props.iconName;
const selectedIconColor = props.selectedIconColor || props.iconColor;
getImageSource(
selectedIconName,
props.iconSize,
selectedIconColor
).then(selectedIcon => this.setState({ selectedIcon }));
}
}
componentWillMount() {
this.updateIconSources(this.props);
}
componentWillReceiveProps(nextProps) {
const keys = Object.keys(TabBarItemIOS.propTypes);
if (!isEqual(pick(nextProps, keys), pick(this.props, keys))) {
this.updateIconSources(nextProps);
}
}
render() {
return <TabBarIOS.Item {...this.props} {...this.state} />;
}
};
}
|
src/containers/Create_New_Group.js | giladgreen/pokerStats | import React, { Component } from 'react';
import { addGroup,deleteGroup } from '../actions/index';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import pokerIcons from '../components/pokerIcons';
import { browserHistory } from 'react-router';
import {cloneDeep} from 'lodash';
import xxx from '../dateHelper';
let siRef;
class CreateNewGroup extends Component {
constructor(props){
super(props);
const selectedGroup = this.props.pokerStats.selectedGroup;
this.state = this.getNewState(selectedGroup);
this.onFormSubmit = this.onFormSubmit.bind(this);
this.cancel = this.cancel.bind(this);
this.OnNameChange = this.OnNameChange.bind(this);
this.OnIdChange = this.OnIdChange.bind(this);
this.OnPasswordChange = this.OnPasswordChange.bind(this);
this.OnAdminPasswordChange = this.OnAdminPasswordChange.bind(this);
this.OnAdminPhoneChange = this.OnAdminPhoneChange.bind(this);
this.OnAdminMailChange = this.OnAdminMailChange.bind(this);
this.DeleteGroup = this.DeleteGroup.bind(this);
this.getUpdateEnable = this.getUpdateEnable.bind(this);
this.OnAdminFullNameChange = this.OnAdminFullNameChange.bind(this);
this.OnCurrencySignChange = this.OnCurrencySignChange.bind(this);
this.deleteGroupIntervalMethod = this.deleteGroupIntervalMethod.bind(this);
}
DeleteGroup(event){
event.preventDefault();
// console.log("DeleteGroup was pressed.");
const {deleteButtonState} = this.state;
if (!deleteButtonState.enabled) return;
if (deleteButtonState.buttonPressed){
//console.log("DeleteGroup was pressed twice - deleting..");
this.props.deleteGroup();
if (siRef){
clearInterval(siRef);
siRef=null;
}
return;
}
// console.log("DeleteGroup setting interval..");
this.deleteGroupIntervalMethod();
siRef = setInterval(this.deleteGroupIntervalMethod,1000);
}
deleteGroupIntervalMethod(){
const newState = cloneDeep(this.state);
let secondsTillDelete = newState.deleteButtonState.secondsTillDelete - 1;
// console.log("deleteGroupIntervalMethod, secondsTillDelete:"+secondsTillDelete);
if (secondsTillDelete == 0){
// console.log("deleteGroupIntervalMethod, clearInterval");
if (siRef){
clearInterval(siRef);
siRef=null;
}
newState.deleteButtonState ={
enabled:true,
buttonText:"Delete Group",
buttonPressed:false,
secondsTillDelete:6
}
}else{
// console.log("deleteGroupIntervalMethod, setting text to be:",`Confirm Delete (${secondsTillDelete})`);
newState.deleteButtonState ={
enabled:true,
buttonText:`Confirm Delete (${secondsTillDelete})`,
buttonPressed:true,
secondsTillDelete:secondsTillDelete
}
}
this.setState(newState);
}
getUpdateEnable(newGroupData){
return newGroupData.groupName &&
newGroupData.groupName.length > 0 &&
newGroupData.groupId &&
newGroupData.groupId.length > 0 &&
newGroupData.password &&
newGroupData.password.length > 0 &&
newGroupData.adminFullName &&
newGroupData.adminFullName.length>2 &&
newGroupData.adminPassword &&
newGroupData.adminPassword.length > 0 &&
newGroupData.groupCurrencySign &&
newGroupData.groupCurrencySign.length>0 &&
newGroupData.adminPhone &&
newGroupData.adminPhone.length > 0 &&
newGroupData.adminPhone.indexOf('05')==0 &&
newGroupData.adminMail &&
newGroupData.adminMail.length > 4 &&
newGroupData.adminMail.indexOf('@'>1) &&
newGroupData.password!=newGroupData.adminPassword ;
}
getNewState(existingGroup){
// console.log('getNewState state:',existingGroup);
const newState= {
deleteButtonState:{
enabled:false
},
updateEnabled:false,
groupData:{
adminFullName:"",
groupName:"",
groupId:"",
groupCurrencySign:"₪",
password:"",
adminPassword:"",
adminPhone:"",
adminMail:""
}
};
if (existingGroup){
newState.deleteButtonState={
enabled:true,
buttonText:"Delete Group",
buttonPressed:false,
secondsTillDelete:6
},
newState.groupData.groupName=existingGroup.groupName;
newState.groupData.adminFullName=existingGroup.adminFullName;
newState.groupData.groupId=existingGroup.groupId;
newState.groupData.id=existingGroup.id;
newState.groupData.password=existingGroup.password;
newState.groupData.adminPassword=existingGroup.adminPassword;
newState.groupData.adminPhone=existingGroup.adminPhone;
newState.groupData.adminMail=existingGroup.adminMail;
newState.groupData.groupCurrencySign=existingGroup.groupCurrencySign;
}
return newState;
}
OnNameChange(groupName){
const newState =cloneDeep(this.state);
newState.groupData.groupName = groupName;
newState.updateEnabled=this.getUpdateEnable(newState.groupData);
this.setState(newState);
}
OnCurrencySignChange(groupCurrencySign){
const newState =cloneDeep(this.state);
newState.groupData.groupCurrencySign = groupCurrencySign;
newState.updateEnabled=this.getUpdateEnable(newState.groupData);
this.setState(newState);
}
OnIdChange(groupId){
const newState =cloneDeep(this.state);
newState.groupData.groupId = groupId;
newState.updateEnabled=this.getUpdateEnable(newState.groupData);
this.setState(newState);
}
OnPasswordChange(password){
const newState =cloneDeep(this.state);
newState.groupData.password = password;
newState.updateEnabled=this.getUpdateEnable(newState.groupData);
this.setState(newState);
}
OnAdminFullNameChange(adminFullName){
const newState =cloneDeep(this.state);
newState.groupData.adminFullName = adminFullName;
newState.updateEnabled=this.getUpdateEnable(newState.groupData);
this.setState(newState);
}
OnAdminPasswordChange(adminPassword){
const newState =cloneDeep(this.state);
newState.groupData.adminPassword = adminPassword;
newState.updateEnabled=this.getUpdateEnable(newState.groupData);
this.setState(newState);
}
OnAdminPhoneChange(adminPhone){
const newState =cloneDeep(this.state);
newState.groupData.adminPhone = adminPhone;
newState.updateEnabled=this.getUpdateEnable(newState.groupData);
this.setState(newState);
}
OnAdminMailChange(adminMail){
const newState =cloneDeep(this.state);
newState.groupData.adminMail = adminMail;
newState.updateEnabled=this.getUpdateEnable(newState.groupData);
this.setState(newState);
}
onFormSubmit(event){
event.preventDefault();
const newState =cloneDeep(this.state);
const group = newState.groupData;
this.props.addGroup(group);
browserHistory.push('/');
}
cancel(){
this.props.addGroup(null);
browserHistory.push('/login');
}
render(){
const state = this.props.pokerStats;
const {deleteButtonState} = this.state;
const {buttonText} = deleteButtonState;
const newGroup = !state.selectedGroup;
const SubmitText = newGroup ? "Add" : "Update";
const header = newGroup ? "Create New Group" : "Update Group";
const deleteButton = newGroup ?
<div/> :
(<button className="btn btn-danger text-xs-right marginTop" onClick={this.DeleteGroup}>
<span className="glyphicon glyphicon-trash" aria-hidden="true" > </span>
{buttonText}
</button>);
const decoration = newGroup? pokerIcons : <div/>;
return (<div/>);
}
}
function mapStateToProps(state){
return {pokerStats:state.pokerStats};
}
function mapDispatchToProps(dispatch){
return bindActionCreators({addGroup,deleteGroup},dispatch);
}
export default connect(mapStateToProps,mapDispatchToProps)(CreateNewGroup);
|
src/shipit/frontend/src/views/NewRelease/index.js | La0/mozilla-relengapi | import React from 'react';
import {
ButtonToolbar, Button, FormGroup, FormControl, ControlLabel, InputGroup, DropdownButton,
MenuItem, Collapse, Modal, Tooltip, OverlayTrigger,
} from 'react-bootstrap';
import { object } from 'prop-types';
import { NavLink } from 'react-router-dom';
import * as moment from 'moment';
import config, { SHIPIT_API_URL } from '../../config';
import { getBuildNumbers, getShippedReleases } from '../../components/api';
import { getPushes, getVersion, getLocales } from '../../components/mercurial';
import maybeShorten from '../../components/text';
export default class NewRelease extends React.Component {
static contextTypes = {
authController: object.isRequired,
};
constructor(...args) {
super(...args);
this.state = Object.assign(this.defaultState());
}
set version(version) {
this.setState({
version,
});
}
defaultState = () => ({
selectedProduct: {},
selectedBranch: {},
suggestedRevisions: [],
revision: '',
version: '',
buildNumber: 0,
partialVersions: [],
showModal: false,
errorMsg: null,
submitted: false,
inProgress: false,
releaseDate: '',
releaseTime: '',
});
readyToSubmit = () => (
this.state.version !== '' &&
this.state.buildNumber > 0 &&
(this.state.selectedProduct.enablePartials ?
this.state.partialVersions.length > 0 : true)
);
open = () => {
this.setState({ showModal: true });
};
close = () => {
this.setState(Object.assign(this.defaultState()));
};
handleBranch = async (branch) => {
this.setState({
selectedBranch: branch,
revision: '',
version: '',
buildNumber: 0,
partialVersions: [],
});
const pushes = await getPushes(branch.repo);
const suggestedRevisions = Object.values(pushes.pushes).map(push =>
({ ...push.changesets[0], date: new Date(push.date * 1000) })).reverse().filter(push =>
push.desc.indexOf('DONTBUILD') === -1);
this.setState({ suggestedRevisions });
};
guessBuildId = async () => {
const buildNumbers = await getBuildNumbers(
this.state.selectedProduct.product,
this.state.selectedBranch.branch,
this.state.version,
);
const nextBuildNumber = buildNumbers.length !== 0 ? Math.max(...buildNumbers) + 1 : 1;
this.setState({
buildNumber: nextBuildNumber,
});
};
// Poor man's RC detection. xx.0 is the only pattern that matches RC
isRc = (version) => {
const parts = version.split('.');
if (parts.length !== 2) {
return false;
}
if (parts[1] !== '0') {
return false;
}
return true;
};
guessPartialVersions = async () => {
const { product } = this.state.selectedProduct;
const {
branch, rcBranch, numberOfPartials, alternativeBranch,
} = this.state.selectedBranch;
const numberOfPartialsOrDefault = numberOfPartials || 3;
const shippedReleases = await getShippedReleases(product, branch);
const shippedBuilds = shippedReleases.map(r => `${r.version}build${r.build_number}`);
// take first N releases
const suggestedBuilds = shippedBuilds.slice(0, numberOfPartialsOrDefault);
// alternativeBranch is used for find partials from a different branch, and
// usually used for ESR releases
let suggestedAlternativeBuilds = [];
if (suggestedBuilds.length < numberOfPartialsOrDefault && alternativeBranch) {
const alternativeReleases = await getShippedReleases(product, alternativeBranch);
const shippedAlternativeBuilds = alternativeReleases.map(r => `${r.version}build${r.build_number}`);
suggestedAlternativeBuilds = shippedAlternativeBuilds.slice(
0,
numberOfPartialsOrDefault - suggestedBuilds.length,
);
}
// if RC, also add last shipped beta
let suggestedRcBuilds = [];
if (rcBranch && this.isRc(this.state.version)) {
const rcShippedReleases = await getShippedReleases(product, rcBranch);
const rcLastBuild = `${rcShippedReleases[0].version}build${rcShippedReleases[0].build_number}`;
suggestedRcBuilds = [rcLastBuild];
}
this.setState({
partialVersions: suggestedBuilds.concat(suggestedRcBuilds, suggestedAlternativeBuilds),
});
};
handleSuggestedRev = async (rev) => {
this.setState({
revision: rev.node,
});
this.version = await getVersion(
this.state.selectedBranch.repo, rev.node,
this.state.selectedProduct.appName,
this.state.selectedBranch.versionFile,
);
await this.guessBuildId();
if (this.state.selectedProduct.enablePartials) {
await this.guessPartialVersions();
}
};
handleProduct = (product) => {
this.setState({
selectedProduct: product,
selectedBranch: {},
suggestedRevisions: [],
revision: '',
version: '',
buildNumber: 0,
partialVersions: [],
});
};
handleRevisionChange = async (event) => {
this.setState({
revision: event.target.value,
});
this.version = await getVersion(
this.state.selectedBranch.repo, event.target.value,
this.state.selectedProduct.appName,
this.state.selectedBranch.versionFile,
);
await this.guessBuildId();
if (this.state.selectedProduct.enablePartials) {
await this.guessPartialVersions();
}
};
handlePartialsChange = async (event) => {
this.setState({
partialVersions: event.target.value.split(',').map(v => v.trim()),
});
};
handleReleaseDateChange = (event) => {
this.setState({
releaseDate: event.target.value,
});
};
handleReleaseTimeChange = (event) => {
this.setState({
releaseTime: event.target.value,
});
};
generateReleaseEta = (date, time) => {
if (date !== '' && time !== '') {
return moment(`${date}T${time}Z`).toISOString();
}
return '';
};
submitRelease = async () => {
this.setState({ inProgress: true });
const { product } = this.state.selectedProduct;
const {
branch, repo, rcBranch, rcBranchVersionPattern, rcRepo, productKey,
alternativeBranch, alternativeRepo,
} = this.state.selectedBranch;
const releaseObj = {
product,
branch,
revision: this.state.revision,
version: this.state.version,
build_number: this.state.buildNumber,
release_eta: this.generateReleaseEta(this.state.releaseDate, this.state.releaseTime),
};
if (this.state.selectedProduct.enablePartials) {
const partialUpdates = await Promise.all(this.state.partialVersions.map(async (ver) => {
const [version, buildNumber] = ver.split('build');
let partialBranch = branch;
let partialRepo = repo;
// override the branch in case this is an RC and the version matches the (beta) pattern
if (this.isRc(releaseObj.version) && rcBranch && rcBranchVersionPattern.test(version)) {
partialBranch = rcBranch;
partialRepo = rcRepo;
}
let shippedReleases = await getShippedReleases(
product, partialBranch, version,
buildNumber,
);
if (shippedReleases.length === 0 && alternativeBranch) {
partialBranch = alternativeBranch;
partialRepo = alternativeRepo;
shippedReleases = await getShippedReleases(product, partialBranch, version, buildNumber);
}
if (shippedReleases.length !== 1) {
this.setState({
inProgress: false,
errorMsg: `Cannot obtain proper information for ${product} ${partialBranch} ${version} build ${buildNumber}`,
});
return null;
}
const { revision } = shippedReleases[0];
const locales = await getLocales(
partialRepo, revision,
this.state.selectedProduct.appName,
);
return [
version, { buildNumber, locales },
];
}));
const partialUpdatesFlattened = {};
partialUpdates.forEach(([v, e]) => {
partialUpdatesFlattened[v] = e;
});
releaseObj.partial_updates = partialUpdatesFlattened;
}
if (productKey) {
releaseObj.product_key = productKey;
}
await this.doEet(releaseObj);
this.setState({ inProgress: false });
};
doEet = async (releaseObj) => {
if (!this.context.authController.userSession) {
this.setState({ errorMsg: 'Login required!' });
return;
}
const url = `${SHIPIT_API_URL}/releases`;
const { accessToken } = this.context.authController.getUserSession();
const headers = {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
};
try {
const body = JSON.stringify(releaseObj);
const response = await fetch(url, { method: 'POST', headers, body });
if (!response.ok) {
this.setState({ errorMsg: 'Auth failure!' });
return;
}
this.setState({ submitted: true });
} catch (e) {
this.setState({ errorMsg: 'Server issues!' });
throw e;
}
};
releaseEtaValidationState = () => {
const { releaseDate, releaseTime } = this.state;
if (releaseDate === '' && releaseTime === '') {
return null;
} else if (releaseDate !== '' && releaseTime !== '') {
return 'success';
}
return 'error';
};
renderBody = () => {
const { inProgress, submitted, errorMsg } = this.state;
if (errorMsg) {
return (
<div>
<p>{errorMsg}</p>
</div>
);
}
if (inProgress) {
return (
<div>
<h4>Working....</h4>
</div>
);
}
if (!submitted) {
const url = `${config.TREEHERDER_URL}/#/jobs?repo=${this.state.selectedBranch.project}&revision=${this.state.revision}`;
const buildName =
`${this.state.selectedProduct.product}-${this.state.version}-build${this.state.buildNumber}`;
return (
<div>
<h4>The following release will be submitted:</h4>
<div>
<a href={url}>{buildName}</a>
</div>
</div>
);
}
return (
<div>
Done. Start the release from <NavLink to="/">the list of releases</NavLink>
</div>
);
};
renderPartials = () => {
const { selectedProduct, partialVersions } = this.state;
if (selectedProduct && selectedProduct.enablePartials) {
return (
<FormGroup>
<InputGroup>
<InputGroup.Addon>Partial versions</InputGroup.Addon>
<FormControl
type="text"
value={partialVersions.join(',')}
onChange={this.handlePartialsChange}
/>
</InputGroup>
<small>
Coma-separated list of versions with build number, e.g. 59.0b8build7.
UX will be improved!
</small>
</FormGroup>
);
}
return '';
};
renderReleaseEta = () => {
if (this.state.selectedBranch.enableReleaseEta) {
const tooltip = (
<Tooltip id="releaseEtaHelp">
Date and time at which the release is planned to be public. This date
is used by Balrog to automatically activate the new rule. One extra
condition: The new rule should be signed off by a set of human before
going live. In the case the date expires, the rule will go live
immediately after every signoff is made.
</Tooltip>
);
return (
<FormGroup validationState={this.releaseEtaValidationState()}>
<InputGroup>
<OverlayTrigger placement="right" overlay={tooltip}>
<InputGroup.Addon>Release ETA (UTC)</InputGroup.Addon>
</OverlayTrigger>
<FormControl
type="date"
value={this.state.releaseDate}
onChange={this.handleReleaseDateChange}
style={{ width: '200px' }}
min={moment().format('YYYY-MM-DD')}
/>
<FormControl
type="time"
value={this.state.releaseTime}
onChange={this.handleReleaseTimeChange}
style={{ width: '150px' }}
/>
<FormControl.Feedback />
</InputGroup>
</FormGroup>
);
}
return '';
};
render() {
return (
<div className="container">
<h3>Start a new release</h3>
<div>
<ButtonToolbar>
{config.PRODUCTS.map(product => (
<Button
key={product.product}
bsStyle={this.state.selectedProduct === product ? 'primary' : 'default'}
bsSize="large"
onClick={() => this.handleProduct(product)}
>
{product.prettyName}
</Button>
))}
</ButtonToolbar>
</div>
<Collapse in={this.state.selectedProduct.branches
&& this.state.selectedProduct.branches.length > 0}
>
<div style={{ paddingTop: '10px', paddingBottom: '10px' }}>
<ButtonToolbar>
{this.state.selectedProduct.branches &&
this.state.selectedProduct.branches.map(branch => (
<Button
key={branch.project}
bsStyle={this.state.selectedBranch === branch ? 'primary' : 'default'}
bsSize="large"
onClick={() => this.handleBranch(branch)}
>
{branch.prettyName}
</Button>
))}
</ButtonToolbar>
</div>
</Collapse>
<Collapse in={this.state.selectedBranch.repo && this.state.selectedBranch.repo.length > 0}>
<div>
<FormGroup>
<ControlLabel>Revision</ControlLabel>
<InputGroup>
<DropdownButton
componentClass={InputGroup.Button}
id="input-dropdown-addon"
title="Suggested revisions"
>
{this.state.suggestedRevisions && this.state.suggestedRevisions.map(rev => (
<MenuItem
onClick={() => this.handleSuggestedRev(rev)}
key={rev.node}
title={
`${rev.date.toString()} - ${rev.node} - ${rev.desc}`
}
>
{rev.date.toDateString()}
{' '} - {' '}
{rev.node.substring(0, 8)}
{' '} - {' '}
{maybeShorten(rev.desc)}
</MenuItem>
))}
</DropdownButton>
<FormControl type="text" value={this.state.revision} onChange={this.handleRevisionChange} />
</InputGroup>
</FormGroup>
{this.renderReleaseEta()}
{this.renderPartials()}
<div className="text-muted">Version: {this.state.version || ''}</div>
<div className="text-muted">Build number: {this.state.buildNumber || ''}</div>
<div style={{ paddingTop: '10px', paddingBottom: '10px' }}>
<Button type="submit" bsStyle="primary" onClick={this.open} disabled={!this.readyToSubmit()}>Start tracking it!</Button>
<Modal show={this.state.showModal} onHide={this.close}>
<Modal.Header closeButton>
<Modal.Title>Start release</Modal.Title>
</Modal.Header>
<Modal.Body>
{this.renderBody()}
</Modal.Body>
<Modal.Footer>
<Collapse in={!this.state.submitted}>
<div>
<Button
onClick={this.submitRelease}
bsStyle="danger"
disabled={!this.context.authController.userSession || this.state.inProgress}
>
Do eet!
</Button>
<Button onClick={this.close} bsStyle="primary">Close</Button>
</div>
</Collapse>
</Modal.Footer>
</Modal>
</div>
</div>
</Collapse>
</div>
);
}
}
|
server/sonar-web/src/main/js/app/utils/startReactApp.js | Builders-SonarSource/sonarqube-bis | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, IndexRoute, Redirect } from 'react-router';
import { Provider } from 'react-redux';
import LocalizationContainer from '../components/LocalizationContainer';
import MigrationContainer from '../components/MigrationContainer';
import App from '../components/App';
import GlobalContainer from '../components/GlobalContainer';
import SimpleContainer from '../components/SimpleContainer';
import Landing from '../components/Landing';
import ProjectContainer from '../components/ProjectContainer';
import ProjectAdminContainer from '../components/ProjectAdminContainer';
import ProjectPageExtension from '../components/extensions/ProjectPageExtension';
import ProjectAdminPageExtension from '../components/extensions/ProjectAdminPageExtension';
import ViewDashboard from '../components/extensions/ViewDashboard';
import AdminContainer from '../components/AdminContainer';
import GlobalPageExtension from '../components/extensions/GlobalPageExtension';
import GlobalAdminPageExtension from '../components/extensions/GlobalAdminPageExtension';
import MarkdownHelp from '../components/MarkdownHelp';
import NotFound from '../components/NotFound';
import aboutRoutes from '../../apps/about/routes';
import accountRoutes from '../../apps/account/routes';
import backgroundTasksRoutes from '../../apps/background-tasks/routes';
import codeRoutes from '../../apps/code/routes';
import codingRulesRoutes from '../../apps/coding-rules/routes';
import componentRoutes from '../../apps/component/routes';
import componentIssuesRoutes from '../../apps/component-issues/routes';
import componentMeasuresRoutes from '../../apps/component-measures/routes';
import customMeasuresRoutes from '../../apps/custom-measures/routes';
import groupsRoutes from '../../apps/groups/routes';
import issuesRoutes from '../../apps/issues/routes';
import metricsRoutes from '../../apps/metrics/routes';
import overviewRoutes from '../../apps/overview/routes';
import organizationsRouters from '../../apps/organizations/routes';
import permissionTemplatesRoutes from '../../apps/permission-templates/routes';
import projectActivityRoutes from '../../apps/projectActivity/routes';
import projectAdminRoutes from '../../apps/project-admin/routes';
import projectsRoutes from '../../apps/projects/routes';
import projectsAdminRoutes from '../../apps/projects-admin/routes';
import qualityGatesRoutes from '../../apps/quality-gates/routes';
import qualityProfilesRoutes from '../../apps/quality-profiles/routes';
import sessionsRoutes from '../../apps/sessions/routes';
import settingsRoutes from '../../apps/settings/routes';
import systemRoutes from '../../apps/system/routes';
import updateCenterRoutes from '../../apps/update-center/routes';
import usersRoutes from '../../apps/users/routes';
import webAPIRoutes from '../../apps/web-api/routes';
import { maintenanceRoutes, setupRoutes } from '../../apps/maintenance/routes';
import { globalPermissionsRoutes, projectPermissionsRoutes } from '../../apps/permissions/routes';
import getStore from './getStore';
import getHistory from './getHistory';
function handleUpdate () {
const { action } = this.state.location;
if (action === 'PUSH') {
window.scrollTo(0, 0);
}
}
const startReactApp = () => {
const el = document.getElementById('content');
const history = getHistory();
const store = getStore();
render((
<Provider store={store}>
<Router history={history} onUpdate={handleUpdate}>
<Route path="/dashboard/index/:key" onEnter={(nextState, replace) => {
replace({ pathname: '/dashboard', query: { id: nextState.params.key } });
}}/>
<Route path="markdown/help" component={MarkdownHelp}/>
<Route component={LocalizationContainer}>
<Route component={SimpleContainer}>
<Route path="maintenance">{maintenanceRoutes}</Route>
<Route path="setup">{setupRoutes}</Route>
</Route>
<Route component={MigrationContainer}>
<Route component={SimpleContainer}>
<Route path="/sessions">{sessionsRoutes}</Route>
</Route>
<Route path="/" component={App}>
<IndexRoute component={Landing}/>
<Route component={GlobalContainer}>
<Route path="about">{aboutRoutes}</Route>
<Route path="account">{accountRoutes}</Route>
<Route path="codingrules" onEnter={(nextState, replace) => {
replace('/coding_rules' + window.location.hash);
}}/>
<Route path="coding_rules">{codingRulesRoutes}</Route>
<Route path="component">{componentRoutes}</Route>
<Route path="extension/:pluginKey/:extensionKey" component={GlobalPageExtension}/>
<Route path="issues">{issuesRoutes}</Route>
<Route path="organizations">{organizationsRouters}</Route>
<Route path="projects">{projectsRoutes}</Route>
<Route path="quality_gates">{qualityGatesRoutes}</Route>
<Route path="profiles">{qualityProfilesRoutes}</Route>
<Route path="web_api">{webAPIRoutes}</Route>
<Route component={ProjectContainer}>
<Route path="code">{codeRoutes}</Route>
<Route path="component_issues">{componentIssuesRoutes}</Route>
<Route path="component_measures">{componentMeasuresRoutes}</Route>
<Route path="custom_measures">{customMeasuresRoutes}</Route>
<Route path="dashboard">{overviewRoutes}</Route>
<Redirect from="governance" to="/view"/>
<Route path="project">
<Route path="activity">{projectActivityRoutes}</Route>
<Route path="admin" component={ProjectAdminContainer}>
<Route path="extension/:pluginKey/:extensionKey" component={ProjectAdminPageExtension}/>
</Route>
<Redirect from="extension/governance/governance" to="/view"/>
<Route path="extension/:pluginKey/:extensionKey" component={ProjectPageExtension}/>
<Route path="background_tasks">{backgroundTasksRoutes}</Route>
<Route path="settings">{settingsRoutes}</Route>
{projectAdminRoutes}
</Route>
<Route path="project_roles">{projectPermissionsRoutes}</Route>
<Route path="view" component={ViewDashboard}/>
</Route>
<Route component={AdminContainer}>
<Route path="admin/extension/:pluginKey/:extensionKey" component={GlobalAdminPageExtension}/>
<Route path="background_tasks">{backgroundTasksRoutes}</Route>
<Route path="groups">{groupsRoutes}</Route>
<Route path="metrics">{metricsRoutes}</Route>
<Route path="permission_templates">{permissionTemplatesRoutes}</Route>
<Route path="projects_admin">{projectsAdminRoutes}</Route>
<Route path="roles/global">{globalPermissionsRoutes}</Route>
<Route path="settings">{settingsRoutes}</Route>
<Route path="system">{systemRoutes}</Route>
<Route path="updatecenter">{updateCenterRoutes}</Route>
<Route path="users">{usersRoutes}</Route>
</Route>
</Route>
<Route path="*" component={NotFound}/>
</Route>
</Route>
</Route>
</Router>
</Provider>
), el);
};
export default startReactApp;
|
react-flux-mui/js/material-ui/src/svg-icons/maps/local-movies.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalMovies = (props) => (
<SvgIcon {...props}>
<path d="M18 3v2h-2V3H8v2H6V3H4v18h2v-2h2v2h8v-2h2v2h2V3h-2zM8 17H6v-2h2v2zm0-4H6v-2h2v2zm0-4H6V7h2v2zm10 8h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V7h2v2z"/>
</SvgIcon>
);
MapsLocalMovies = pure(MapsLocalMovies);
MapsLocalMovies.displayName = 'MapsLocalMovies';
MapsLocalMovies.muiName = 'SvgIcon';
export default MapsLocalMovies;
|
app/components/FilterFields/DateField.js | barbalex/kapla3 | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
FormGroup,
InputGroup,
FormControl,
ControlLabel,
Glyphicon
} from 'react-bootstrap';
import moment from 'moment';
import DatePicker from 'react-datepicker';
import { observer } from 'mobx-react';
import compose from 'recompose/compose';
import styled from 'styled-components';
import ComparatorSelector from './ComparatorSelector';
import SortSelector from './SortSelector';
import getDateValidationStateDate from '../../src/getDateValidationStateDate';
moment.locale('de');
const StyledDatePicker = styled(DatePicker)`
cursor: pointer;
`;
const StyledFormGroup = styled(FormGroup)`
grid-area: ${props =>
props['data-name'] === 'rechtsmittelEntscheidDatum'
? 'fieldEntscheidDatum'
: 'unset'};
grid-column: ${props =>
props['data-name'] === 'rechtsmittelEntscheidDatum' ? 'unset' : 1};
.react-datepicker-popper {
z-index: 10;
}
.react-datepicker {
font-size: 1em;
}
.react-datepicker__header {
padding-top: 0.8em;
}
.react-datepicker__month {
margin: 0.4em 1em;
}
.react-datepicker__day-name,
.react-datepicker__day {
width: 1.9em;
line-height: 1.9em;
margin: 0.166em;
}
.react-datepicker__current-month {
font-size: 1em;
}
.react-datepicker__navigation {
top: 1em;
line-height: 1.7em;
border: 0.45em solid transparent;
}
.react-datepicker__navigation--previous {
border-right-color: #ccc;
left: 1em;
}
.react-datepicker__navigation--next {
border-left-color: #ccc;
right: 1em;
}
`;
const enhance = compose(observer);
class DateField extends Component {
static propTypes = {
name: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
tabIndex: PropTypes.number.isRequired,
values: PropTypes.object.isRequired,
change: PropTypes.func.isRequired,
changeComparator: PropTypes.func.isRequired
};
constructor(props) {
super(props);
const { values, name } = this.props;
let value = values[name];
if (value) value = moment(value, 'YYYY-MM-DD').format('DD.MM.YYYY');
this.state = { value };
}
componentDidUpdate(prevProps) {
const { values, name } = this.props;
let value = values[name];
const prevValue = prevProps.values[name];
if (value !== prevValue) {
if (value) value = moment(value, 'YYYY-MM-DD').format('DD.MM.YYYY');
this.setState({ value }); // eslint-disable-line react/no-did-update-set-state
}
}
onChange = e => {
this.setState({ value: e.target.value });
};
onBlur = () => {
const { values, name, change } = this.props;
let { value } = this.state;
// only filter if value has changed
if (value !== values[name]) {
if (!value || moment(value, 'DD.MM.YYYY').isValid()) {
if (value) {
// convert value for local state
value = moment(value, 'DD.MM.YYYY').format('DD.MM.YYYY');
this.setState({ value });
}
const e = {
target: {
type: 'text',
name,
value
}
};
change(e);
} else {
// TODO: tell user this is invalid
console.log('DateField.js: invalid date'); // eslint-disable-line no-console
}
}
};
onChangeDatePicker = date => {
const { name } = this.props;
const rValForBlur = {
target: {
type: 'text',
name,
value: date
}
};
const rValForChange = {
target: {
type: 'text',
name,
value: moment(date, 'DD.MM.YYYY').format('DD.MM.YYYY')
}
};
this.onChange(rValForChange);
this.onBlur(rValForBlur);
};
render() {
const { name, label, tabIndex, changeComparator } = this.props;
const { value } = this.state;
/**
* need to give addon no padding
* and the originally addon's padding to the glyphicon
* to make entire addon clickable
* for opening calendar
*/
const datePickerAddonStyle = {
padding: 0
};
const datePickerCalendarStyle = {
paddingTop: 6,
paddingBottom: 6,
paddingLeft: 12,
paddingRight: 12
};
return (
<StyledFormGroup
data-name={name}
// className={name === 'rechtsmittelEntscheidDatum' ? styles.fieldEntscheidDatum : styles.field}
validationState={getDateValidationStateDate(value)}
>
<ControlLabel>{label}</ControlLabel>
<InputGroup>
<SortSelector name={name} />
<ComparatorSelector name={name} changeComparator={changeComparator} />
<FormControl
type="text"
value={value || ''}
name={name}
onChange={this.onChange}
onBlur={this.onBlur}
tabIndex={tabIndex}
/>
<InputGroup.Addon style={datePickerAddonStyle}>
<StyledDatePicker
onChange={this.onChangeDatePicker}
dateFormat="DD.MM.YYYY"
//locale="de"
customInput={
<Glyphicon glyph="calendar" style={datePickerCalendarStyle} />
}
popperPlacement="top-end"
/>
</InputGroup.Addon>
</InputGroup>
</StyledFormGroup>
);
}
}
export default enhance(DateField);
|
src/components/containers/RegisterContainer.js | teamNOne/showdown | import React from 'react';
import UserActions from '../../actions/UserActions';
import FormActions from '../../actions/FormActions';
import FormStore from '../../stores/FormStore';
import Register from '../user/Register';
import Validator from '../../utilities/FormValidator';
export default class RegisterContainer extends React.Component {
_fieldLabels = ['Username', 'Password', 'Confirmation password', 'First name', 'Last name', 'Age', 'Gender'];
_fieldNames = ['username', 'password', 'confirmedPassword', 'firstName', 'lastName', 'age', 'gender'];
constructor(props) {
super(props);
this.state = { Register: {} };
this.onChange = this.onChange.bind(this);
this.handleRegister = this.handleRegister.bind(this);
}
onChange(state) {
console.log('[RegisterContainer] changing state', state);
this.setState({ Register: state.Register });
}
componentDidMount() {
FormStore.init('Register');
FormStore.listen(this.onChange);
}
componentWillUnmount() {
FormStore.unlisten(this.onChange);
}
handleRegister(e) {
e.preventDefault();
if (Validator.validate(this._fieldNames, this._fieldLabels, this.state.Register)) {
UserActions.register(this.state.Register, this.props.history);
}
}
render() {
return (
<Register handleRegister={this.handleRegister}
Register={this.state.Register}
FormActions={FormActions} />
)
}
} |
js/index.js | sambev/fe-boot | 'use strict';
import React from 'react';
require('css/base.css');
var TestComponent = React.createClass({
render () {
return (<div>
<h1>It works!</h1>
<p> This is some text</p>
</div>);
}
});
React.render(<TestComponent />, document.querySelector('#content'));
|
Console/app/node_modules/rc-tooltip/es/Tooltip.js | RisenEsports/RisenEsports.github.io | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Trigger from 'rc-trigger';
import { placements } from './placements';
var Tooltip = function (_Component) {
_inherits(Tooltip, _Component);
function Tooltip() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Tooltip);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Tooltip.__proto__ || Object.getPrototypeOf(Tooltip)).call.apply(_ref, [this].concat(args))), _this), _this.getPopupElement = function () {
var _this$props = _this.props,
arrowContent = _this$props.arrowContent,
overlay = _this$props.overlay,
prefixCls = _this$props.prefixCls;
return [React.createElement(
'div',
{ className: prefixCls + '-arrow', key: 'arrow' },
arrowContent
), React.createElement(
'div',
{ className: prefixCls + '-inner', key: 'content' },
typeof overlay === 'function' ? overlay() : overlay
)];
}, _this.saveTrigger = function (node) {
_this.trigger = node;
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Tooltip, [{
key: 'getPopupDomNode',
value: function getPopupDomNode() {
return this.trigger.getPopupDomNode();
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
overlayClassName = _props.overlayClassName,
trigger = _props.trigger,
mouseEnterDelay = _props.mouseEnterDelay,
mouseLeaveDelay = _props.mouseLeaveDelay,
overlayStyle = _props.overlayStyle,
prefixCls = _props.prefixCls,
children = _props.children,
onVisibleChange = _props.onVisibleChange,
afterVisibleChange = _props.afterVisibleChange,
transitionName = _props.transitionName,
animation = _props.animation,
placement = _props.placement,
align = _props.align,
destroyTooltipOnHide = _props.destroyTooltipOnHide,
defaultVisible = _props.defaultVisible,
getTooltipContainer = _props.getTooltipContainer,
restProps = _objectWithoutProperties(_props, ['overlayClassName', 'trigger', 'mouseEnterDelay', 'mouseLeaveDelay', 'overlayStyle', 'prefixCls', 'children', 'onVisibleChange', 'afterVisibleChange', 'transitionName', 'animation', 'placement', 'align', 'destroyTooltipOnHide', 'defaultVisible', 'getTooltipContainer']);
var extraProps = _extends({}, restProps);
if ('visible' in this.props) {
extraProps.popupVisible = this.props.visible;
}
return React.createElement(
Trigger,
_extends({
popupClassName: overlayClassName,
ref: this.saveTrigger,
prefixCls: prefixCls,
popup: this.getPopupElement,
action: trigger,
builtinPlacements: placements,
popupPlacement: placement,
popupAlign: align,
getPopupContainer: getTooltipContainer,
onPopupVisibleChange: onVisibleChange,
afterPopupVisibleChange: afterVisibleChange,
popupTransitionName: transitionName,
popupAnimation: animation,
defaultPopupVisible: defaultVisible,
destroyPopupOnHide: destroyTooltipOnHide,
mouseLeaveDelay: mouseLeaveDelay,
popupStyle: overlayStyle,
mouseEnterDelay: mouseEnterDelay
}, extraProps),
children
);
}
}]);
return Tooltip;
}(Component);
Tooltip.propTypes = {
trigger: PropTypes.any,
children: PropTypes.any,
defaultVisible: PropTypes.bool,
visible: PropTypes.bool,
placement: PropTypes.string,
transitionName: PropTypes.string,
animation: PropTypes.any,
onVisibleChange: PropTypes.func,
afterVisibleChange: PropTypes.func,
overlay: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired,
overlayStyle: PropTypes.object,
overlayClassName: PropTypes.string,
prefixCls: PropTypes.string,
mouseEnterDelay: PropTypes.number,
mouseLeaveDelay: PropTypes.number,
getTooltipContainer: PropTypes.func,
destroyTooltipOnHide: PropTypes.bool,
align: PropTypes.object,
arrowContent: PropTypes.any
};
Tooltip.defaultProps = {
prefixCls: 'rc-tooltip',
mouseEnterDelay: 0,
destroyTooltipOnHide: false,
mouseLeaveDelay: 0.1,
align: {},
placement: 'right',
trigger: ['hover'],
arrowContent: null
};
export default Tooltip; |
stories/sync.js | wcastand/okami | import React from 'react'
import {storiesOf} from '@storybook/react'
import frLocale from 'date-fns/locale/fr'
import parse from 'date-fns/parse'
import isSameDay from 'date-fns/isSameDay'
import {Div} from 'glamorous'
import Calendar from '../src/'
import DailyCalendar from '../src/components/daily'
import Weekly from './components/weekly'
import Daily from './components/daily'
import Monthly from './components/monthly'
import MonthlySync from './components/syncMonth'
import DailySync from './components/syncDaily'
import NoRef from './components/noRef'
import data from './data'
import data2 from './data2'
import datagoogle from './googledata'
const css = document.createElement('style')
css.innerHTML = `
* { box-sizing: border-box; }
`
document.body.appendChild(css)
storiesOf('Sync', module)
.add('Daily', () => (
<Calendar
data={data}
startingDay="monday"
dateFormat="ddd DD/MM"
hourFormat="HH"
startHour="PT3H"
endHour="PT22H"
locale={frLocale}
>
<Daily />
</Calendar>
))
.add('Weekly', () => (
<Calendar
data={datagoogle.filter(e => e.status !== 'cancelled').map(e => ({
...e,
...(e.start.dateTime && {
start: parse(e.start.dateTime, 'YYYY-MM-DDTHH:mm:ss', new Date()),
end: parse(e.end.dateTime, 'YYYY-MM-DDTHH:mm:ss', new Date()),
allDay: !isSameDay(e.start.dateTime, e.end.dateTime),
}),
...(e.start.date && {
allDay: parse(e.start.date, 'YYYY-MM-DD', new Date()),
}),
title: e.summary,
}))}
startingDay="monday"
dateFormat="ddd DD/MM"
hourFormat="HH"
locale={frLocale}
>
<Weekly />
</Calendar>
))
.add('Monthly', () => (
<Calendar
data={data2}
startingDay="monday"
dateFormat="dddd"
hourFormat="HH"
locale={frLocale}
rowHeight={30}
>
<Monthly />
</Calendar>
))
.add('Multiple Sync', () => {
class Sync extends React.Component {
state = {s: new Date()}
_setDate = date => this.setState(() => ({s: date}))
render() {
return (
<Calendar
data={data2}
startingDay="monday"
dateFormat="dddd"
hourFormat="HH"
locale={frLocale}
>
<Div display="flex" alignItems="stretch">
<MonthlySync style={{flex: 2}} onClick={this._setDate} rowHeight={20} />
<DailySync start={this.state.s} style={{flex: 1}} />
</Div>
</Calendar>
)
}
}
return <Sync />
})
.add('No Column prop', () => (
<Calendar
data={data}
startingDay="monday"
dateFormat="ddd DD/MM"
hourFormat="HH"
startHour="PT3H"
endHour="PT22H"
locale={frLocale}
>
<NoRef />
</Calendar>
))
|
src/svg-icons/places/all-inclusive.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesAllInclusive = (props) => (
<SvgIcon {...props}>
<path d="M18.6 6.62c-1.44 0-2.8.56-3.77 1.53L12 10.66 10.48 12h.01L7.8 14.39c-.64.64-1.49.99-2.4.99-1.87 0-3.39-1.51-3.39-3.38S3.53 8.62 5.4 8.62c.91 0 1.76.35 2.44 1.03l1.13 1 1.51-1.34L9.22 8.2C8.2 7.18 6.84 6.62 5.4 6.62 2.42 6.62 0 9.04 0 12s2.42 5.38 5.4 5.38c1.44 0 2.8-.56 3.77-1.53l2.83-2.5.01.01L13.52 12h-.01l2.69-2.39c.64-.64 1.49-.99 2.4-.99 1.87 0 3.39 1.51 3.39 3.38s-1.52 3.38-3.39 3.38c-.9 0-1.76-.35-2.44-1.03l-1.14-1.01-1.51 1.34 1.27 1.12c1.02 1.01 2.37 1.57 3.82 1.57 2.98 0 5.4-2.41 5.4-5.38s-2.42-5.37-5.4-5.37z"/>
</SvgIcon>
);
PlacesAllInclusive = pure(PlacesAllInclusive);
PlacesAllInclusive.displayName = 'PlacesAllInclusive';
PlacesAllInclusive.muiName = 'SvgIcon';
export default PlacesAllInclusive;
|
src/main.js | thanhiro/techmatrix | 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 makeRoutes from './routes';
import Root from './containers/Root';
import configureStore from './redux/configureStore';
// Configure history for react-router
const browserHistory = useRouterHistory(createBrowserHistory)({
basename: __BASENAME__
});
// Create redux store and sync with react-router-redux. We have installed the
// react-router-redux reducer under the key "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 = configureStore(initialState, browserHistory);
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: state => state.router
});
// Now that we have the Redux store, we can create our routes. We provide
// the store to the route definitions so that routes have access to it for
// hooks such as `onEnter`.
const routes = makeRoutes(store);
// Now that redux and react-router have been configured, we can render the
// React application to the DOM!
ReactDOM.render(
<Root history={history} routes={routes} store={store} />,
document.getElementById('root')
);
|
client/index.js | BattleSneks/BattleSneks | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './containers/App.jsx';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'),
);
|
src/containers/ContactForm.js | jp7internet/react-apz | import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { reduxForm, Field } from 'redux-form';
import TextInput from '../components/TextInput';
class ContactForm extends Component {
required(value) {
return value && value.length > 0 ? undefined : 'This field is required.';
}
maxLength(max) {
return value => value && value.length <= max ? undefined : `Must have ${max} characters or less.`;
}
phoneFormat(value) {
return value && /^\+1 \([0-9]{3}\) [0-9]{3}-[0-9]{4}$/.test(value) ? undefined : 'Must be in US format, e.g. +1 (111) 111-1111';
}
render() {
const { handleSubmit, pristine, submitting, reset } = this.props;
return (
<form className="form-horizontal" onSubmit={handleSubmit}>
<Field name="id" type="hidden" component="input" />
<Field
name="name"
component={TextInput}
type="text"
label="Name"
placeholder="e.g. John Doe"
validate={[
this.required,
(() => this.maxLength(25))()
]}
/>
<Field
name="phone"
component={TextInput}
type="text"
label="Phone"
placeholder="(111) 111-1111"
validate={[
this.required,
this.phoneFormat
]}
/>
<Field
name="email"
component={TextInput}
type="email"
label="Email"
placeholder="[email protected]"
validate={this.required}
/>
<fieldset className="form-group">
<button type="submit" disabled={pristine || submitting} className="btn btn-primary">Submit</button>
<button type="button" disabled={pristine || submitting} className="btn btn-default" onClick={reset}>Reset</button>
<Link to="/"><i className="glyphicon glyphicon-chevron-left"></i> Back to Home Page</Link>
</fieldset>
</form>
)
}
}
const phoneUnique = values => {
const { phone, id } = values;
return fetch(`/contacts?phone=${btoa(phone)}&id=${id}`)
.then(response => response.json())
.then(json => {
if (json.length > 0) {
// eslint-disable-next-line
throw { phone: 'This phone number already exists.' };
}
});
}
export default reduxForm({
form: 'contact', // This is the form's name and must be unique across the app
asyncValidate: phoneUnique,
asyncBlurFields: ['phone'],
enableReinitialize: true
})(ContactForm);
|
docs/src/_bilprospekt_radio_component.js | Bilprospekt/bilprospekt-ui | import React from 'react';
import _ from 'underscore';
import {Radio} from 'bilprospekt-ui';
const {RadioButton, RadioButtonGroup} = Radio;
const RadioDoc = React.createClass({
render() {
return (
<div id='RadioDoc'>
<p className="table-header-label">Radio</p>
<RadioButtonGroup name="radio-test">
<RadioButton value='first' label="First radio" />
<RadioButton value='second' label="Second radio" />
<RadioButton value='disabled' disabled label="Disabled radio" />
<RadioButton value='third' label="Third radio" />
</RadioButtonGroup>
<pre>
<code>
{
[
"<RadioButtonGroup name='radio-test'>",
<br key={1} />,
"\t<RadioButton value='first' label='First radio' />",
<br key={3} />,
"\t<RadioButton value='second' label='Second radio' />",
<br key={5} />,
"\t<RadioButton value='disabled' disabled label='Disabled radio' />",
<br key={7} />,
"\t<RadioButton value='third' label='Third radio' />",
<br key={9} />,
"</RadioButtonGroup>",
]
}
</code>
</pre>
</div>
);
},
});
export default RadioDoc;
|
pages/error/index.js | sunilbandla/caniuse-inmyapp | /**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import history from '../../core/history';
import s from './styles.css';
class ErrorPage extends React.Component {
static propTypes = {
error: React.PropTypes.object,
};
componentDidMount() {
document.title = this.props.error && this.props.error.status === 404 ?
'Page Not Found' : 'Error';
}
goBack = event => {
event.preventDefault();
history.goBack();
};
render() {
if (this.props.error) console.error(this.props.error); // eslint-disable-line no-console
const [code, title] = this.props.error && this.props.error.status === 404 ?
['404', 'Page not found'] :
['Error', 'Oups, something went wrong'];
return (
<div className={s.container}>
<main className={s.content}>
<h1 className={s.code}>{code}</h1>
<p className={s.title}>{title}</p>
{code === '404' &&
<p className={s.text}>
The page you're looking for does not exist or an another error occurred.
</p>
}
<p className={s.text}>
<a href="/" onClick={this.goBack}>Home</a>
</p>
</main>
</div>
);
}
}
export default ErrorPage;
|
packages/benchmarks/reshadow/client/Table.js | A-gambit/CSS-IN-JS-Benchmarks | import React from 'react';
import styled from 'reshadow';
const Table = ({table, toPercent}) => styled`
table {
display: table;
margin: 10px 10px 10px 0;
}
row {
display: table-row;
}
`(
<table as="div">
{table.map((row, i) => (
<row>
{row.map((x, j) => styled`
cell {
display: table-cell;
padding: 10px;
background: rgba(74, 174, 53, ${x});
}
`(<cell>{toPercent(x)}</cell>))}
</row>
))}
</table>,
);
export default Table;
|
src/stateAndProps.js | Zyj163/React_learning | /**
* Created by ddn on 16/11/7.
*/
import React from 'react';
import ReactDOM from 'react-dom';
//自定义控件
//方式一:函数
//function Welcome(props){
// return <h1>Hello, {props.name}</h1>
//}
//方式二:类(ES6 class)
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
const element = <Welcome name="Sara" />;
//props are read-only 设置不变的内容
//state(状态机) 设置会改变的内容setState
class Clock extends React.Component {
// 构造
constructor(props) {
super(props);
// 初始状态
this.state = {date: new Date()};
}
//生命周期
//will rendered
componentWillMount() {
}
//did rendered
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
)
}
//will removed
componentWillUnMount() {
clearInterval(this.timerID);
}
//did removed
componentDidUnMount() {
}
//渲染内容
render() {
return (
<div>
<h1>hello world</h1>
<h2>it is {this.state.date.toLocaleTimeString()}</h2>
</div>
)
}
//更新状态机,刷新页面
tick() {
this.setState({
date: new Date()
})
}
/*
* 注意点:
* 1.不要直接修改state,应该用setState
* 2.React may batch multiple setState() calls into a single update for performance.
Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.
For example, this code may fail to update the counter:
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
We used an arrow function above, but it also works with regular functions:
// Correct
this.setState(function(prevState, props) {
return {
counter: prevState.counter + props.increment
};
});
3.State Updates are Merged
* */
}
const clock = <Clock />;
ReactDOM.render(
//element,
//clock,
<div>
<Welcome name="Sara" />
<Clock />
</div>,
document.getElementById('root')
); |
src/components/ThankYou/ThankYou.js | dorono/resistance-calendar-frontend | import React from 'react';
import { Link } from 'react-router-dom';
import styles from './ThankYou.sass';
const ThankYou = () => {
return (
<div className={styles.thankYouWrapper}>
<div className={styles.textWrapper}>
<h1>Thank you! Your event has been submitted for review.</h1>
<Link to="/"> View our event listings</Link>
</div>
</div>
);
};
export default ThankYou;
|
docs/src/app/components/pages/customization/StylesOverridingInlineExample.js | mtsandeep/material-ui | import React from 'react';
import Checkbox from 'material-ui/Checkbox';
const StylesOverridingInlineExample = () => (
<Checkbox
name="StylesOverridingInlineExample"
label="Checked the mail"
style={{
width: '50%',
margin: '0 auto',
border: '2px solid #FF9800',
backgroundColor: '#ffd699',
}}
/>
);
export default StylesOverridingInlineExample;
|
components/reports/ConsumptionCategoryPieChart.js | hutsi/bookkeeping | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import withWidth from '@material-ui/core/withWidth';
import Chart from 'react-google-charts';
class ConsumptionCategoryPieChart extends Component {
static propTypes = {
data: PropTypes.instanceOf(Array),
width: PropTypes.oneOf(['xs', 'sm',' md', 'lg', 'xl'])
};
static defaultProps = {
data: [],
};
render() {
const { data, width, className } = this.props;
const extraChartOptions = width === 'xs' ? {
chartArea: { left: 10, top: 10, right: 10, bottom: 10, width: '100%' },
legend: {
position: 'left',
textStyle: { fontSize: 8 },
},
} : {
chartArea: { left: 20, top: 20, right: 20, bottom: 20, width: '100%' },
};
return (
<div className={className}>
<h2 style={{ textAlign: 'center' }}>Consumptions on Categories Pie</h2>
<Chart
width={width === 'xs' ? 'calc(100vw - 16px)' : '50vw'}
height={width === 'xs' ? 200 : 400}
chartType="PieChart"
loader={<div>Loading Chart</div>}
data={[
['Category', 'Money spent'],
...data.map(item => ([ `${item.name} (${item.sum})`, item.sum])),
]}
options={{
is3D: true,
pieHole: 0.5,
tooltip: {
text: 'percentage'
},
...extraChartOptions,
}}
/>
</div>
);
}
}
export default withWidth()(ConsumptionCategoryPieChart);
|
lib/components/DownloadPage.js | gramakri/filepizza | import ChromeNotice from './ChromeNotice'
import DownloadActions from '../actions/DownloadActions'
import DownloadButton from './DownloadButton'
import DownloadStore from '../stores/DownloadStore'
import ErrorPage from './ErrorPage'
import ProgressBar from './ProgressBar'
import React from 'react'
import Spinner from './Spinner'
import { formatSize } from '../util'
export default class DownloadPage extends React.Component {
constructor() {
super()
this.state = DownloadStore.getState()
this._onChange = () => {
this.setState(DownloadStore.getState())
}
}
componentDidMount() {
DownloadStore.listen(this._onChange)
}
componentDidUnmount() {
DownloadStore.unlisten(this._onChange)
}
downloadFile() {
DownloadActions.requestDownload()
}
render() {
switch (this.state.status) {
case 'ready':
return <div className="page">
<h1>FilePizza</h1>
<Spinner dir="down"
name={this.state.fileName}
size={this.state.fileSize} />
<ChromeNotice />
<p className="notice">Peers: {this.state.peers} · Up: {formatSize(this.state.speedUp)} · Down: {formatSize(this.state.speedDown)}</p>
<DownloadButton onClick={this.downloadFile.bind(this)} />
</div>
case 'requesting':
case 'downloading':
return <div className="page">
<h1>FilePizza</h1>
<Spinner dir="down" animated
name={this.state.fileName}
size={this.state.fileSize} />
<ChromeNotice />
<p className="notice">Peers: {this.state.peers} · Up: {formatSize(this.state.speedUp)} · Down: {formatSize(this.state.speedDown)}</p>
<ProgressBar value={this.state.progress} />
</div>
case 'done':
return <div className="page">
<h1>FilePizza</h1>
<Spinner dir="down"
name={this.state.fileName}
size={this.state.fileSize} />
<ChromeNotice />
<p className="notice">Peers: {this.state.peers} · Up: {formatSize(this.state.speedUp)} · Down: {formatSize(this.state.speedDown)}</p>
<ProgressBar value={1} />
</div>
default:
return <ErrorPage />
}
}
}
|
src/app/index.js | shawnmclean/redux-react-es6-tutorial | import React from 'react'
import App from './containers/App'
React.render(
<App />,
document.getElementById('app')
)
|
packages/react-scripts/fixtures/kitchensink/src/features/env/NodePath.js | christiantinauer/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import load from 'absoluteLoad';
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = load();
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-node-path">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
src/components/Layout/Header/index.js | Apozhidaev/terminal.mobi | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import cx from 'classnames';
import './styles.css';
import Archive from './Archive';
class Header extends Component {
constructor(props) {
super(props);
this.state = {
collapsed: true,
};
this.toggleNavigation = this.toggleNavigation.bind(this);
this.collapseNavigation = this.collapseNavigation.bind(this);
}
toggleNavigation() {
this.setState({ collapsed: !this.state.collapsed });
}
collapseNavigation() {
this.setState({ collapsed: true });
}
render() {
return (
<div>
<nav className="navbar navbar-expand-md navbar-light bg-faded">
<Link className="navbar-brand" to="/" onClick={this.collapseNavigation}>TERMINAL</Link>
<button
type="button"
className={cx('navbar-toggler', this.state.collapsed && 'collapsed')}
onClick={this.toggleNavigation}
>
<span className="navbar-toggler-icon" />
</button>
<div className={cx('navbar-collapse', 'collapse', !this.state.collapsed && 'show')}>
<ul className="navbar-nav mr-auto" />
<div className="navbar-nav">
<Archive />
<Link className="nav-item nav-link" to="/settings" onClick={this.collapseNavigation}>
SETTINGS
</Link>
</div>
</div>
</nav>
</div>
);
}
}
const mapStateToProps = state => ({
profile: state.app.context.profile,
});
export default connect(mapStateToProps)(Header);
|
react/features/video-menu/components/native/ConnectionStatusComponent.js | gpolitis/jitsi-meet | // @flow
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { withTheme } from 'react-native-paper';
import { Avatar } from '../../../base/avatar';
import { ColorSchemeRegistry } from '../../../base/color-scheme';
import { BottomSheet, isDialogOpen, hideDialog } from '../../../base/dialog';
import { translate } from '../../../base/i18n';
import { IconArrowDownLarge, IconArrowUpLarge } from '../../../base/icons';
import { getParticipantDisplayName } from '../../../base/participants';
import { BaseIndicator } from '../../../base/react';
import { connect } from '../../../base/redux';
import { StyleType } from '../../../base/styles';
import statsEmitter from '../../../connection-indicator/statsEmitter';
import styles from './styles';
/**
* Size of the rendered avatar in the menu.
*/
const AVATAR_SIZE = 25;
const CONNECTION_QUALITY = [
'Low',
'Medium',
'Good'
];
export type Props = {
/**
* The Redux dispatch function.
*/
dispatch: Function,
/**
* The ID of the participant that this button is supposed to pin.
*/
participantID: string,
/**
* The color-schemed stylesheet of the BottomSheet.
*/
_bottomSheetStyles: StyleType,
/**
* True if the menu is currently open, false otherwise.
*/
_isOpen: boolean,
/**
* Display name of the participant retrieved from Redux.
*/
_participantDisplayName: string,
/**
* The function to be used to translate i18n labels.
*/
t: Function,
/**
* Theme used for styles.
*/
theme: Object
}
/**
* The type of the React {@code Component} state of {@link ConnectionStatusComponent}.
*/
type State = {
resolutionString: string,
downloadString: string,
uploadString: string,
packetLostDownloadString: string,
packetLostUploadString: string,
serverRegionString: string,
codecString: string,
connectionString: string
};
// eslint-disable-next-line prefer-const
let ConnectionStatusComponent_;
/**
* Class to implement a popup menu that show the connection statistics.
*/
class ConnectionStatusComponent extends Component<Props, State> {
/**
* Constructor of the component.
*
* @param {P} props - The read-only properties with which the new
* instance is to be initialized.
*
* @inheritdoc
*/
constructor(props: Props) {
super(props);
this._onStatsUpdated = this._onStatsUpdated.bind(this);
this._onCancel = this._onCancel.bind(this);
this._renderMenuHeader = this._renderMenuHeader.bind(this);
this.state = {
resolutionString: 'N/A',
downloadString: 'N/A',
uploadString: 'N/A',
packetLostDownloadString: 'N/A',
packetLostUploadString: 'N/A',
serverRegionString: 'N/A',
codecString: 'N/A',
connectionString: 'N/A'
};
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {React$Node}
*/
render(): React$Node {
const { t, theme } = this.props;
const { palette } = theme;
return (
<BottomSheet
onCancel = { this._onCancel }
renderHeader = { this._renderMenuHeader }>
<View style = { styles.statsWrapper }>
<View style = { styles.statsInfoCell }>
<Text style = { styles.statsTitleText }>
{ `${t('connectionindicator.status')} ` }
</Text>
<Text style = { styles.statsInfoText }>
{ this.state.connectionString }
</Text>
</View>
<View style = { styles.statsInfoCell }>
<Text style = { styles.statsTitleText }>
{ `${t('connectionindicator.bitrate')}` }
</Text>
<BaseIndicator
icon = { IconArrowDownLarge }
iconStyle = {{
color: palette.icon03
}} />
<Text style = { styles.statsInfoText }>
{ this.state.downloadString }
</Text>
<BaseIndicator
icon = { IconArrowUpLarge }
iconStyle = {{
color: palette.icon03
}} />
<Text style = { styles.statsInfoText }>
{ `${this.state.uploadString} Kbps` }
</Text>
</View>
<View style = { styles.statsInfoCell }>
<Text style = { styles.statsTitleText }>
{ `${t('connectionindicator.packetloss')}` }
</Text>
<BaseIndicator
icon = { IconArrowDownLarge }
iconStyle = {{
color: palette.icon03
}} />
<Text style = { styles.statsInfoText }>
{ this.state.packetLostDownloadString }
</Text>
<BaseIndicator
icon = { IconArrowUpLarge }
iconStyle = {{
color: palette.icon03
}} />
<Text style = { styles.statsInfoText }>
{ this.state.packetLostUploadString }
</Text>
</View>
<View style = { styles.statsInfoCell }>
<Text style = { styles.statsTitleText }>
{ `${t('connectionindicator.resolution')} ` }
</Text>
<Text style = { styles.statsInfoText }>
{ this.state.resolutionString }
</Text>
</View>
<View style = { styles.statsInfoCell }>
<Text style = { styles.statsTitleText }>
{ `${t('connectionindicator.codecs')}` }
</Text>
<Text style = { styles.statsInfoText }>
{ this.state.codecString }
</Text>
</View>
</View>
</BottomSheet>
);
}
/**
* Starts listening for stat updates.
*
* @inheritdoc
* returns {void}
*/
componentDidMount() {
statsEmitter.subscribeToClientStats(
this.props.participantID, this._onStatsUpdated);
}
/**
* Updates which user's stats are being listened to.
*
* @inheritdoc
* returns {void}
*/
componentDidUpdate(prevProps: Props) {
if (prevProps.participantID !== this.props.participantID) {
statsEmitter.unsubscribeToClientStats(
prevProps.participantID, this._onStatsUpdated);
statsEmitter.subscribeToClientStats(
this.props.participantID, this._onStatsUpdated);
}
}
_onStatsUpdated: Object => void;
/**
* Callback invoked when new connection stats associated with the passed in
* user ID are available. Will update the component's display of current
* statistics.
*
* @param {Object} stats - Connection stats from the library.
* @private
* @returns {void}
*/
_onStatsUpdated(stats = {}) {
const newState = this._buildState(stats);
this.setState(newState);
}
/**
* Extracts statistics and builds the state object.
*
* @param {Object} stats - Connection stats from the library.
* @private
* @returns {State}
*/
_buildState(stats) {
const { download: downloadBitrate, upload: uploadBitrate } = this._extractBitrate(stats) ?? {};
const { download: downloadPacketLost, upload: uploadPacketLost } = this._extractPacketLost(stats) ?? {};
return {
resolutionString: this._extractResolutionString(stats) ?? this.state.resolutionString,
downloadString: downloadBitrate ?? this.state.downloadString,
uploadString: uploadBitrate ?? this.state.uploadString,
packetLostDownloadString: downloadPacketLost === undefined
? this.state.packetLostDownloadString : `${downloadPacketLost}%`,
packetLostUploadString: uploadPacketLost === undefined
? this.state.packetLostUploadString : `${uploadPacketLost}%`,
serverRegionString: this._extractServer(stats) ?? this.state.serverRegionString,
codecString: this._extractCodecs(stats) ?? this.state.codecString,
connectionString: this._extractConnection(stats) ?? this.state.connectionString
};
}
/**
* Extracts the resolution and framerate.
*
* @param {Object} stats - Connection stats from the library.
* @private
* @returns {string}
*/
_extractResolutionString(stats) {
const { framerate, resolution } = stats;
const resolutionString = Object.keys(resolution || {})
.map(ssrc => {
const { width, height } = resolution[ssrc];
return `${width}x${height}`;
})
.join(', ') || null;
const frameRateString = Object.keys(framerate || {})
.map(ssrc => framerate[ssrc])
.join(', ') || null;
return resolutionString && frameRateString ? `${resolutionString}@${frameRateString}fps` : undefined;
}
/**
* Extracts the download and upload bitrates.
*
* @param {Object} stats - Connection stats from the library.
* @private
* @returns {{ download, upload }}
*/
_extractBitrate(stats) {
return stats.bitrate;
}
/**
* Extracts the download and upload packet lost.
*
* @param {Object} stats - Connection stats from the library.
* @private
* @returns {{ download, upload }}
*/
_extractPacketLost(stats) {
return stats.packetLoss;
}
/**
* Extracts the server name.
*
* @param {Object} stats - Connection stats from the library.
* @private
* @returns {string}
*/
_extractServer(stats) {
return stats.serverRegion;
}
/**
* Extracts the audio and video codecs names.
*
* @param {Object} stats - Connection stats from the library.
* @private
* @returns {string}
*/
_extractCodecs(stats) {
const { codec } = stats;
let codecString;
// Only report one codec, in case there are multiple for a user.
Object.keys(codec || {})
.forEach(ssrc => {
const { audio, video } = codec[ssrc];
codecString = `${audio}, ${video}`;
});
return codecString;
}
/**
* Extracts the connection percentage and sets connection quality.
*
* @param {Object} stats - Connection stats from the library.
* @private
* @returns {string}
*/
_extractConnection(stats) {
const { connectionQuality } = stats;
if (connectionQuality) {
const signalLevel = Math.floor(connectionQuality / 33.4);
return CONNECTION_QUALITY[signalLevel];
}
}
_onCancel: () => boolean;
/**
* Callback to hide the {@code ConnectionStatusComponent}.
*
* @private
* @returns {boolean}
*/
_onCancel() {
statsEmitter.unsubscribeToClientStats(
this.props.participantID, this._onStatsUpdated);
if (this.props._isOpen) {
this.props.dispatch(hideDialog(ConnectionStatusComponent_));
return true;
}
return false;
}
_renderMenuHeader: () => React$Element<any>;
/**
* Function to render the menu's header.
*
* @returns {React$Element}
*/
_renderMenuHeader() {
const { _bottomSheetStyles, participantID } = this.props;
return (
<View
style = { [
_bottomSheetStyles.sheet,
styles.participantNameContainer ] }>
<Avatar
participantId = { participantID }
size = { AVATAR_SIZE } />
<Text style = { styles.participantNameLabel }>
{ this.props._participantDisplayName }
</Text>
</View>
);
}
}
/**
* Function that maps parts of Redux state tree into component props.
*
* @param {Object} state - Redux state.
* @param {Object} ownProps - Properties of component.
* @private
* @returns {Props}
*/
function _mapStateToProps(state, ownProps) {
const { participantID } = ownProps;
return {
_bottomSheetStyles: ColorSchemeRegistry.get(state, 'BottomSheet'),
_isOpen: isDialogOpen(state, ConnectionStatusComponent_),
_participantDisplayName: getParticipantDisplayName(state, participantID)
};
}
ConnectionStatusComponent_ = translate(connect(_mapStateToProps)(withTheme(ConnectionStatusComponent)));
export default ConnectionStatusComponent_;
|
src/layouts/CoreLayout/CoreLayout.js | TheModevShop/craft-app | import React from 'react';
import {connect} from 'react-redux';
import Header from '../../components/Header';
import {teardownSession} from '../../store/authentication';
import _ from 'lodash';
import './core-layout.less';
import '../../styles/core.less';
export const CoreLayout = (props) => {
const path = _.get(props, 'location.pathname', '');
const locationPath = path.split('/').join(' ');
const latestRoute = (path.split('/') || []).pop();
return (
<div className={`app-container container text-center admin-page ${locationPath}-page`}>
<Header loc={latestRoute || ''} teardownSession={props.teardownSession} auth={props.auth} slug={_.get(props, 'membership.slug')} membership={_.get(props, 'membership')} name={_.get(props, 'membership.resource_name')} />
<div className="core-layout__viewport">
{props.children}
</div>
</div>
);
};
CoreLayout.propTypes = {
children: React.PropTypes.element.isRequired
};
const mapStateToProps = (state) => {
return {
auth: state.authentication,
membership: state.memberships[0]
}
}
const mapDispatchToProps = {
teardownSession
};
export default connect(mapStateToProps, mapDispatchToProps)(CoreLayout); |
src/svg-icons/image/crop-16-9.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCrop169 = (props) => (
<SvgIcon {...props}>
<path d="M19 6H5c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 10H5V8h14v8z"/>
</SvgIcon>
);
ImageCrop169 = pure(ImageCrop169);
ImageCrop169.displayName = 'ImageCrop169';
ImageCrop169.muiName = 'SvgIcon';
export default ImageCrop169;
|
packages/reactor-kitchensink/src/examples/Layouts/vbox/vbox.js | dbuhrman/extjs-reactor | import React, { Component } from 'react';
import { Container, Panel, Spacer } from '@extjs/ext-react';
import colors from '../../colors';
export default class VBoxLayoutExample extends Component {
render() {
const panelProps = {
height: 175,
margin: '0 0 40 0',
defaults: {
layout: 'center'
}
};
return (
<Container padding={Ext.os.is.Phone ? 20 : 30}>
<Panel shadow ui="instructions" margin="0 0 40 0">
<div>A <b>vbox</b> layout positions items vertically with optional 'pack', and 'align' configs.</div>
</Panel>
<div style={styles.heading}>align: 'stretch'</div>
<Panel shadow layout="vbox" {...panelProps}>
<Container style={colors.card.red} flex={1}>Item 1</Container>
<Container style={colors.card.blue} flex={1}>Item 2</Container>
<Container style={colors.card.green} flex={1}>Item 3</Container>
</Panel>
<div style={styles.heading}>align: 'left'</div>
<Panel shadow layout={{ type: 'vbox', align: 'left' }} {...panelProps}>
<Container style={colors.card.red} flex={1}>Item 1</Container>
<Container style={colors.card.blue} flex={1}>Item 2</Container>
<Container style={colors.card.green} flex={1}>Item 3</Container>
</Panel>
<div style={styles.heading}>align: 'right'</div>
<Panel shadow layout={{ type: 'vbox', align: 'right' }} {...panelProps}>
<Container style={colors.card.red} flex={1}>Item 1</Container>
<Container style={colors.card.blue} flex={1}>Item 2</Container>
<Container style={colors.card.green} flex={1}>Item 3</Container>
</Panel>
<div style={styles.heading}>pack: 'start'</div>
<Panel shadow layout={{ type: 'vbox', pack: 'start' }} {...panelProps}>
<Container style={colors.card.red}>Item 1</Container>
<Container style={colors.card.blue}>Item 2</Container>
<Container style={colors.card.green}>Item 3</Container>
</Panel>
<div style={styles.heading}>pack: 'center'</div>
<Panel shadow layout={{ type: 'vbox', pack: 'center' }} {...panelProps}>
<Container style={colors.card.red}>Item 1</Container>
<Container style={colors.card.blue}>Item 2</Container>
<Container style={colors.card.green}>Item 3</Container>
</Panel>
<div style={styles.heading}>pack: 'end'</div>
<Panel shadow layout={{ type: 'vbox', pack: 'end' }} {...panelProps}>
<Container style={colors.card.red}>Item 1</Container>
<Container style={colors.card.blue}>Item 2</Container>
<Container style={colors.card.green}>Item 3</Container>
</Panel>
<div style={styles.heading}>pack: 'space-between'</div>
<Panel shadow layout={{ type: 'vbox', pack: 'space-between' }} {...panelProps}>
<Container style={colors.card.red}>Item 1</Container>
<Container style={colors.card.blue}>Item 2</Container>
<Container style={colors.card.green}>Item 3</Container>
</Panel>
<div style={styles.heading}>pack: 'space-around'</div>
<Panel shadow layout={{ type: 'vbox', pack: 'space-around' }} {...panelProps}>
<Container style={colors.card.red}>Item 1</Container>
<Container style={colors.card.blue}>Item 2</Container>
<Container style={colors.card.green}>Item 3</Container>
</Panel>
</Container>
)
}
}
const styles = {
heading: {
fontSize: '13px',
fontFamily: 'Menlo, Courier',
margin: '0 0 8px 0'
}
}
|
src/js/components/icons/base/Install.js | linde12/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-install`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'install');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M19,13.5 L19,17.5 L12,22 L5,17.5 L5,13.5 M12,22 L12,13.5 M18.5,8.5 L12,4.5 L15.5,2 L22,6 L18.5,8.5 L18.5,8.5 L18.5,8.5 Z M5.5,8.5 L12,4.5 L8.5,2 L2,6 L5.5,8.5 L5.5,8.5 L5.5,8.5 Z M18.5,9 L12,13 L15.5,15.5 L22,11.5 L18.5,9 L18.5,9 L18.5,9 Z M5.5,9 L12,13 L8.5,15.5 L2,11.5 L5.5,9 L5.5,9 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Install';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
src/components/layout.js | akabekobeko/akabeko.me | import React from 'react'
import PropTypes from 'prop-types'
import { Helmet } from 'react-helmet'
import { StaticQuery, graphql } from 'gatsby'
const Layout = ({ children }) => (
<StaticQuery
query={graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
blogTitle
subtitle
description
copyright
repositoryName
repositoryLink
}
}
}
`}
render={(data) => (
<>
<Helmet
title={data.site.siteMetadata.title}
meta={[
{
name: 'description',
content: data.site.siteMetadata.description,
},
]}
/>
{children}
</>
)}
/>
)
Layout.propTypes = {
children: PropTypes.func,
}
export default Layout
|
admin/client/App/components/Navigation/Mobile/ListItem.js | brianjd/keystone | /**
* A list item of the mobile navigation
*/
import React from 'react';
import { Link } from 'react-router';
const MobileListItem = React.createClass({
displayName: 'MobileListItem',
propTypes: {
children: React.PropTypes.node.isRequired,
className: React.PropTypes.string,
href: React.PropTypes.string.isRequired,
onClick: React.PropTypes.func,
},
render () {
return (
<Link
className={this.props.className}
to={this.props.href}
onClick={this.props.onClick}
tabIndex="-1"
>
{this.props.children}
</Link>
);
},
});
module.exports = MobileListItem;
|
src/components/withAxios.js | sheaivey/react-axios | import React from 'react'
import PropTypes from 'prop-types'
import Request from './Request'
import { AxiosContext } from './AxiosProvider'
export const withAxios = (mixed = {}) => {
if(typeof mixed === 'function') {
// basic axios provider HoC
const WrappedComponent = mixed
return (props) => {
const axiosInstance = React.useContext(AxiosContext)
return <WrappedComponent axios={ axiosInstance } { ...props }/>
}
}
// advanced Request provider HoC
const options = { ...Request.defaultProps, ...mixed }
return (WrappedComponent) => {
// validate the options passed in are valid request propTypes.
PropTypes.checkPropTypes({
...Request.propTypes,
method: PropTypes.string, // not required if the user just wants access to the axios instance
}, options, 'option', `withAxios()(${WrappedComponent.name})`)
const ReactAxiosExtracter = (props) => {
// allow overriding the config initial options
const newOptions = { ...options, ...props.options }
return (
<Request {...newOptions}>
{(error, response, isLoading, makeRequest, axios) => (
<WrappedComponent
{...props}
error={error}
response={response}
isLoading={isLoading}
makeRequest={makeRequest}
axios={axios}
options={newOptions}
/>
)}
</Request>
)
}
ReactAxiosExtracter.propTypes = {
options: PropTypes.object,
}
return ReactAxiosExtracter
}
}
export default withAxios
|
tests/lib/rules/vars-on-top.js | jamestalmage/eslint | /**
* @fileoverview Tests for vars-on-top rule.
* @author Danny Fritz
* @author Gyandeep Singh
* @copyright 2014 Danny Fritz. All rights reserved.
* @copyright 2014 Gyandeep Singh. All rights reserved.
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var rule = require("../../../lib/rules/vars-on-top"),
EslintTester = require("../../../lib/testers/rule-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
var ruleTester = new EslintTester();
ruleTester.run("vars-on-top", rule, {
valid: [
[
"var first = 0;",
"function foo() {",
" first = 2;",
"}"
].join("\n"),
[
"function foo() {",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" if (true) {",
" first = true;",
" } else {",
" first = 1;",
" }",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" var third;",
" var fourth = 1, fifth, sixth = third;",
" var seventh;",
" if (true) {",
" third = true;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var i;",
" for (i = 0; i < 10; i++) {",
" alert(i);",
" }",
"}"
].join("\n"),
[
"function foo() {",
" var outer;",
" function inner() {",
" var inner = 1;",
" var outer = inner;",
" }",
" outer = 1;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" //Hello",
" var second = 1;",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" /*",
" Hello Clarice",
" */",
" var second = 1;",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" function bar(){",
" var first;",
" first = 5;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" function bar(){",
" var third;",
" third = 5;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var bar = function(){",
" var third;",
" third = 5;",
" }",
" first = 5;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" first.onclick(function(){",
" var third;",
" third = 5;",
" });",
" first = 5;",
"}"
].join("\n"),
{
code: [
"function foo() {",
" var i = 0;",
" for (let j = 0; j < 10; j++) {",
" alert(j);",
" }",
" i = i + 1;",
"}"
].join("\n"),
ecmaFeatures: {
blockBindings: true
}
},
"'use strict'; var x; f();",
"'use strict'; 'directive'; var x; var y; f();",
"function f() { 'use strict'; var x; f(); }",
"function f() { 'use strict'; 'directive'; var x; var y; f(); }",
{code: "import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}
],
invalid: [
{
code: [
"var first = 0;",
"function foo() {",
" first = 2;",
" second = 2;",
"}",
"var second = 0;"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first;",
" first = 1;",
" first = 2;",
" first = 3;",
" first = 4;",
" var second = 1;",
" second = 2;",
" first = second;",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first;",
" if (true) {",
" var second = true;",
" }",
" first = second;",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" for (var i = 0; i < 10; i++) {",
" alert(i);",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" for (i = 0; i < first; i ++) {",
" var second = i;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" switch (first) {",
" case 10:",
" var hello = 1;",
" break;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" try {",
" var hello = 1;",
" } catch (e) {",
" alert('error');",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" try {",
" asdf;",
" } catch (e) {",
" var hello = 1;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" while (first) {",
" var hello = 1;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" do {",
" var hello = 1;",
" } while (first == 10);",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = [1,2,3];",
" for (var item in first) {",
" item++;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = [1,2,3];",
" var item;",
" for (item in first) {",
" var hello = item;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"var foo = () => {",
" var first = [1,2,3];",
" var item;",
" for (item in first) {",
" var hello = item;",
" }",
"}"
].join("\n"),
ecmaFeatures: { arrowFunctions: true },
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: "'use strict'; 0; var x; f();",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "'use strict'; var x; 'directive'; var y; f();",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "function f() { 'use strict'; 0; var x; f(); }",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "function f() { 'use strict'; var x; 'directive'; var y; f(); }",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
}
]
});
|
src/svg-icons/notification/network-check.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationNetworkCheck = (props) => (
<SvgIcon {...props}>
<path d="M15.9 5c-.17 0-.32.09-.41.23l-.07.15-5.18 11.65c-.16.29-.26.61-.26.96 0 1.11.9 2.01 2.01 2.01.96 0 1.77-.68 1.96-1.59l.01-.03L16.4 5.5c0-.28-.22-.5-.5-.5zM1 9l2 2c2.88-2.88 6.79-4.08 10.53-3.62l1.19-2.68C9.89 3.84 4.74 5.27 1 9zm20 2l2-2c-1.64-1.64-3.55-2.82-5.59-3.57l-.53 2.82c1.5.62 2.9 1.53 4.12 2.75zm-4 4l2-2c-.8-.8-1.7-1.42-2.66-1.89l-.55 2.92c.42.27.83.59 1.21.97zM5 13l2 2c1.13-1.13 2.56-1.79 4.03-2l1.28-2.88c-2.63-.08-5.3.87-7.31 2.88z"/>
</SvgIcon>
);
NotificationNetworkCheck = pure(NotificationNetworkCheck);
NotificationNetworkCheck.displayName = 'NotificationNetworkCheck';
NotificationNetworkCheck.muiName = 'SvgIcon';
export default NotificationNetworkCheck;
|
client/components/AppLoading.js | kuip/oro-devi | import React from 'react';
AppLoading = React.createClass({
render: function render() {
return React.createElement("p");
}
});
|
src/components/appStructure/additionalInfo/newBlogs.js | Jguardado/HiRproject | import React from 'react';
const NewBlogs = () => {
return (
<div className='newcomp two'>
<div className="box-heading">New Blog Posts</div>
<h4>
<ul className="list-items"><a href='https://medium.com/@juanguardado/redux-single-source-of-truth-e1fe1fb6ffec#.k7bgyf2uu'>Redux: Art of the State</a></ul>
<ul className="list-items"><a href='https://medium.com/@juanguardado/stateful-vs-stateless-components-444b5aa21865#.5netw27vq'>Stateful vs Stateless</a></ul>
<ul className="list-items"><a href='https://medium.com/@juanguardado/how-to-structure-your-app-in-react-dd706639bc93#.ms4djdqhj'>How to start a react app</a></ul>
</h4>
</div>
);
}
export default NewBlogs
|
src/routes.js | Capgemini/react-scaffold | import React from 'react';
import { Route, DefaultRoute, NotFoundRoute } from 'react-router';
import NotFound from './components/NotFoundPage';
import Home from './components/Home';
import About from './components/About';
import App from './components/App';
export default (
<Route name="app" path="/" handler={ App }>
<Route name="about" path="/about" handler={ About }/>
<DefaultRoute handler={ Home } />
<NotFoundRoute handler={ NotFound } />
</Route>
);
|
src/renderApp.js | ender74/yart | import React from 'react'
import ReactDOM from 'react-dom'
import AppView from './views/app/AppView'
ReactDOM.render(<AppView />, document.getElementById("container"))
|
features/apimgt/org.wso2.carbon.apimgt.admin.feature/src/main/resources/admin/source/src/app/components/Base/Header/Header.js | thusithak/carbon-apimgt | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 {Link, withRouter} from "react-router-dom";
import AuthManager from '../../../data/AuthManager.js';
import qs from 'qs'
const Header = (props) => {
let params = qs.stringify({referrer: props.location.pathname});
return (
<header className="header header-default">
<div className="container-fluid">
<div id="nav-icon1" className="menu-trigger navbar-left " data-toggle="sidebar"
data-target="#left-sidebar" data-container=".page-content-wrapper" data-container-divide="true"
aria-expanded="false" rel="sub-nav">
</div>
<div className="pull-left brand">
<Link to="/">
<span>APIM Admin Portal</span>
</Link>
</div>
<ul className="nav navbar-right">
<li className="visible-inline-block">
<a className="dropdown" data-toggle="dropdown" aria-expanded="false">
<span className="icon fw-stack">
<i className="fw fw-circle fw-stack-2x"/>
<i className="fw fw-user fw-stack-1x fw-inverse"/>
</span>
<span className="hidden-xs add-margin-left-1x" id="logged-in-username">
{ AuthManager.getUser() ? AuthManager.getUser().name : ""}
<span className="caret"/></span>
</a>
<ul className="dropdown-menu dropdown-menu-right slideInDown" role="menu">
<li><a href="#">Profile Settings</a></li>
<li>
<Link to={{pathname: '/logout', search: params}}>Logout</Link>
</li>
</ul>
</li>
</ul>
</div>
</header >
);
};
// Using `withRouter` helper from React-Router-Dom to get the current user location to be used with logout action,
// We pass the current path in referrer parameter to redirect back the user to where he/she was after login.
// DOC: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md
export default withRouter(Header) |
webpack/components/Content/Details/ContentDetailInfo.js | mccun934/katello | import React from 'react';
import PropTypes from 'prop-types';
import { Table } from 'react-bootstrap';
// using Map to preserve order
const createRows = (details, mapping) => {
const rows = [];
/* eslint-disable no-restricted-syntax, react/jsx-closing-tag-location */
for (const key of mapping.keys()) {
rows.push(<tr key={key}>
<td><b>{mapping.get(key)}</b></td>
<td>{Array.isArray(details[key]) ? details[key].join(', ') : details[key]}</td>
</tr>);
}
/* eslint-enable no-restricted-syntax, react/jsx-closing-tag-location */
return rows;
};
const ContentDetailInfo = ({ contentDetails, displayMap }) => (
<Table>
<tbody>
{createRows(contentDetails, displayMap)}
</tbody>
</Table>
);
ContentDetailInfo.propTypes = {
contentDetails: PropTypes.shape({}).isRequired,
displayMap: PropTypes.instanceOf(Map).isRequired,
};
export default ContentDetailInfo;
|
src/views/forms/layout/Layout.js | mrholek/CoreUI-React | import React from 'react'
import {
CButton,
CCard,
CCardBody,
CCardHeader,
CCol,
CForm,
CFormCheck,
CFormInput,
CFormLabel,
CFormSelect,
CInputGroup,
CInputGroupText,
CRow,
} from '@coreui/react'
import { DocsExample } from 'src/components'
const Layout = () => {
return (
<CRow>
<CCol xs={12}>
<CCard className="mb-4">
<CCardHeader>
<strong>Layout</strong> <small>Form grid</small>
</CCardHeader>
<CCardBody>
<p className="text-medium-emphasis small">
More complex forms can be built using our grid classes. Use these for form layouts
that require multiple columns, varied widths, and additional alignment options.
</p>
<DocsExample href="forms/layout#form-grid">
<CRow>
<CCol xs>
<CFormInput placeholder="First name" aria-label="First name" />
</CCol>
<CCol xs>
<CFormInput placeholder="Last name" aria-label="Last name" />
</CCol>
</CRow>
</DocsExample>
</CCardBody>
</CCard>
</CCol>
<CCol xs={12}>
<CCard className="mb-4">
<CCardHeader>
<strong>Layout</strong> <small>Gutters</small>
</CCardHeader>
<CCardBody>
<p className="text-medium-emphasis small">
By adding <a href="https://coreui.io/docs/layout/gutters/">gutter modifier classes</a>
, you can have control over the gutter width in as well the inline as block direction.
</p>
<DocsExample href="forms/layout#gutters">
<CRow className="g-3">
<CCol xs>
<CFormInput placeholder="First name" aria-label="First name" />
</CCol>
<CCol xs>
<CFormInput placeholder="Last name" aria-label="Last name" />
</CCol>
</CRow>
</DocsExample>
<p className="text-medium-emphasis small">
More complex layouts can also be created with the grid system.
</p>
<DocsExample href="forms/layout#gutters">
<CForm className="row g-3">
<CCol md={6}>
<CFormLabel htmlFor="inputEmail4">Email</CFormLabel>
<CFormInput type="email" id="inputEmail4" />
</CCol>
<CCol md={6}>
<CFormLabel htmlFor="inputPassword4">Password</CFormLabel>
<CFormInput type="password" id="inputPassword4" />
</CCol>
<CCol xs={12}>
<CFormLabel htmlFor="inputAddress">Address</CFormLabel>
<CFormInput id="inputAddress" placeholder="1234 Main St" />
</CCol>
<CCol xs={12}>
<CFormLabel htmlFor="inputAddress2">Address 2</CFormLabel>
<CFormInput id="inputAddress2" placeholder="Apartment, studio, or floor" />
</CCol>
<CCol md={6}>
<CFormLabel htmlFor="inputCity">City</CFormLabel>
<CFormInput id="inputCity" />
</CCol>
<CCol md={4}>
<CFormLabel htmlFor="inputState">State</CFormLabel>
<CFormSelect id="inputState">
<option>Choose...</option>
<option>...</option>
</CFormSelect>
</CCol>
<CCol md={2}>
<CFormLabel htmlFor="inputZip">Zip</CFormLabel>
<CFormInput id="inputZip" />
</CCol>
<CCol xs={12}>
<CFormCheck type="checkbox" id="gridCheck" label="Check me out" />
</CCol>
<CCol xs={12}>
<CButton type="submit">Sign in</CButton>
</CCol>
</CForm>
</DocsExample>
</CCardBody>
</CCard>
</CCol>
<CCol xs={12}>
<CCard className="mb-4">
<CCardHeader>
<strong>Layout</strong> <small>Horizontal form</small>
</CCardHeader>
<CCardBody>
<p className="text-medium-emphasis small">
Create horizontal forms with the grid by adding the <code>.row</code> class to form
groups and using the <code>.col-*-*</code> classes to specify the width of your labels
and controls. Be sure to add <code>.col-form-label</code> to your{' '}
<code><CFormLabel></code>s as well so they're vertically centered with their
associated form controls.
</p>
<p className="text-medium-emphasis small">
At times, you maybe need to use margin or padding utilities to create that perfect
alignment you need. For example, we've removed the <code>padding-top</code> on our
stacked radio inputs label to better align the text baseline.
</p>
<DocsExample href="forms/layout#horizontal-form">
<CForm>
<CRow className="mb-3">
<CFormLabel htmlFor="inputEmail3" className="col-sm-2 col-form-label">
Email
</CFormLabel>
<CCol sm={10}>
<CFormInput type="email" id="inputEmail3" />
</CCol>
</CRow>
<CRow className="mb-3">
<CFormLabel htmlFor="inputPassword3" className="col-sm-2 col-form-label">
Password
</CFormLabel>
<CCol sm={10}>
<CFormInput type="password" id="inputPassword3" />
</CCol>
</CRow>
<fieldset className="row mb-3">
<legend className="col-form-label col-sm-2 pt-0">Radios</legend>
<CCol sm={10}>
<CFormCheck
type="radio"
name="gridRadios"
id="gridRadios1"
value="option1"
label="First radio"
defaultChecked
/>
<CFormCheck
type="radio"
name="gridRadios"
id="gridRadios2"
value="option2"
label="Second radio"
/>
<CFormCheck
type="radio"
name="gridRadios"
id="gridRadios3"
value="option3"
label="Third disabled radio"
disabled
/>
</CCol>
</fieldset>
<CRow className="mb-3">
<div className="col-sm-10 offset-sm-2">
<CFormCheck type="checkbox" id="gridCheck1" label="Example checkbox" />
</div>
</CRow>
<CButton type="submit">Sign in</CButton>
</CForm>
</DocsExample>
</CCardBody>
</CCard>
</CCol>
<CCol xs={12}>
<CCard className="mb-4">
<CCardHeader>
<strong>Layout</strong> <small>Horizontal form label sizing</small>
</CCardHeader>
<CCardBody>
<p className="text-medium-emphasis small">
Be sure to use <code>.col-form-label-sm</code> or <code>.col-form-label-lg</code> to
your <code><CFormLabel></code>s or <code><legend></code>s to correctly
follow the size of <code>.form-control-lg</code> and <code>.form-control-sm</code>.
</p>
<DocsExample href="forms/layout#horizontal-form-label-sizing">
<CRow className="mb-3">
<CFormLabel
htmlFor="colFormLabelSm"
className="col-sm-2 col-form-label col-form-label-sm"
>
Email
</CFormLabel>
<CCol sm={10}>
<CFormInput
type="email"
className="form-control form-control-sm"
id="colFormLabelSm"
placeholder="col-form-label-sm"
/>
</CCol>
</CRow>
<CRow className="mb-3">
<CFormLabel htmlFor="colFormLabel" className="col-sm-2 col-form-label">
Email
</CFormLabel>
<CCol sm={10}>
<CFormInput type="email" id="colFormLabel" placeholder="col-form-label" />
</CCol>
</CRow>
<CRow>
<CFormLabel
htmlFor="colFormLabelLg"
className="col-sm-2 col-form-label col-form-label-lg"
>
Email
</CFormLabel>
<CCol sm={10}>
<CFormInput
type="email"
className="form-control form-control-lg"
id="colFormLabelLg"
placeholder="col-form-label-lg"
/>
</CCol>
</CRow>
</DocsExample>
</CCardBody>
</CCard>
</CCol>
<CCol xs={12}>
<CCard className="mb-4">
<CCardHeader>
<strong>Layout</strong> <small>Column sizing</small>
</CCardHeader>
<CCardBody>
<p className="text-medium-emphasis small">
As shown in the previous examples, our grid system allows you to place any number of{' '}
<code><CCol></code>s within a <code><CRow></code>. They'll split the
available width equally between them. You may also pick a subset of your columns to
take up more or less space, while the remaining <code><CCol></code>s equally
split the rest, with specific column classes like{' '}
<code><CCol sm="7"></code>.
</p>
<DocsExample href="forms/layout#column-sizing">
<CRow className="g-3">
<CCol sm={7}>
<CFormInput placeholder="City" aria-label="City" />
</CCol>
<CCol sm>
<CFormInput placeholder="State" aria-label="State" />
</CCol>
<CCol sm>
<CFormInput placeholder="Zip" aria-label="Zip" />
</CCol>
</CRow>
</DocsExample>
</CCardBody>
</CCard>
</CCol>
<CCol xs={12}>
<CCard className="mb-4">
<CCardHeader>
<strong>Layout</strong> <small>Auto-sizing</small>
</CCardHeader>
<CCardBody>
<p className="text-medium-emphasis small">
The example below uses a flexbox utility to vertically center the contents and changes{' '}
<code><CCol></code> to <code><CCol xs="auto"></code> so that your
columns only take up as much space as needed. Put another way, the column sizes itself
based on the contents.
</p>
<DocsExample href="forms/layout#auto-sizing">
<CForm className="row gy-2 gx-3 align-items-center">
<CCol xs="auto">
<CFormLabel className="visually-hidden" htmlFor="autoSizingInput">
Name
</CFormLabel>
<CFormInput id="autoSizingInput" placeholder="Jane Doe" />
</CCol>
<CCol xs="auto">
<CFormLabel className="visually-hidden" htmlFor="autoSizingInputGroup">
Username
</CFormLabel>
<CInputGroup>
<CInputGroupText>@</CInputGroupText>
<CFormInput id="autoSizingInputGroup" placeholder="Username" />
</CInputGroup>
</CCol>
<CCol xs="auto">
<CFormLabel className="visually-hidden" htmlFor="autoSizingSelect">
Preference
</CFormLabel>
<CFormSelect id="autoSizingSelect">
<option>Choose...</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</CFormSelect>
</CCol>
<CCol xs="auto">
<CFormCheck type="checkbox" id="autoSizingCheck" label="Remember me" />
</CCol>
<CCol xs="auto">
<CButton type="submit">Submit</CButton>
</CCol>
</CForm>
</DocsExample>
<p className="text-medium-emphasis small">
You can then remix that once again with size-specific column classes.
</p>
<DocsExample href="forms/layout#auto-sizing">
<CForm className="row gx-3 gy-2 align-items-center">
<CCol sm={3}>
<CFormLabel className="visually-hidden" htmlFor="specificSizeInputName">
Name
</CFormLabel>
<CFormInput id="specificSizeInputName" placeholder="Jane Doe" />
</CCol>
<CCol sm={3}>
<CFormLabel className="visually-hidden" htmlFor="specificSizeInputGroupUsername">
Username
</CFormLabel>
<CInputGroup>
<CInputGroupText>@</CInputGroupText>
<CFormInput id="specificSizeInputGroupUsername" placeholder="Username" />
</CInputGroup>
</CCol>
<CCol sm={3}>
<CFormLabel className="visually-hidden" htmlFor="specificSizeSelect">
Preference
</CFormLabel>
<CFormSelect id="specificSizeSelect">
<option>Choose...</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</CFormSelect>
</CCol>
<CCol xs="auto">
<CFormCheck type="checkbox" id="autoSizingCheck2" label="Remember me" />
</CCol>
<CCol xs="auto">
<CButton type="submit">Submit</CButton>
</CCol>
</CForm>
</DocsExample>
</CCardBody>
</CCard>
</CCol>
<CCol xs={12}>
<CCard className="mb-4">
<CCardHeader>
<strong>Layout</strong> <small>Inline forms</small>
</CCardHeader>
<CCardBody>
<p className="text-medium-emphasis small">
Use the <code><CCol xs="auto"></code> class to create horizontal
layouts. By adding{' '}
<a href="https://coreui.io/docs/layout/gutters/">gutter modifier classes</a>, we will
have gutters in horizontal and vertical directions. The{' '}
<code>.align-items-center</code> aligns the form elements to the middle, making the{' '}
<code><CFormCheck></code> align properly.
</p>
<DocsExample href="forms/layout#inline-forms">
<CForm className="row row-cols-lg-auto g-3 align-items-center">
<CCol xs={12}>
<CFormLabel className="visually-hidden" htmlFor="inlineFormInputGroupUsername">
Username
</CFormLabel>
<CInputGroup>
<CInputGroupText>@</CInputGroupText>
<CFormInput id="inlineFormInputGroupUsername" placeholder="Username" />
</CInputGroup>
</CCol>
<CCol xs={12}>
<CFormLabel className="visually-hidden" htmlFor="inlineFormSelectPref">
Preference
</CFormLabel>
<CFormSelect id="inlineFormSelectPref">
<option>Choose...</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</CFormSelect>
</CCol>
<CCol xs={12}>
<CFormCheck type="checkbox" id="inlineFormCheck" label="Remember me" />
</CCol>
<CCol xs={12}>
<CButton type="submit">Submit</CButton>
</CCol>
</CForm>
</DocsExample>
</CCardBody>
</CCard>
</CCol>
</CRow>
)
}
export default Layout
|
examples/js/keyboard-nav/pagination-nav-table.js | prajapati-parth/react-bootstrap-table | /* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(75);
export default class PaginationNavTable extends React.Component {
render() {
return (
<BootstrapTable data={ products } pagination keyBoardNav>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
src/client.js | hakonrossebo/ciq-layout-composer | /**
* THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER.
*/
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import createStore from './redux/create';
import ApiClient from './helpers/ApiClient';
import {Provider} from 'react-redux';
import { Router, browserHistory } from 'react-router';
import { ReduxAsyncConnect } from 'redux-async-connect';
import useScroll from 'scroll-behavior/lib/useStandardScroll';
import getRoutes from './routes';
const client = new ApiClient();
const history = useScroll(() => browserHistory)();
const dest = document.getElementById('content');
const store = createStore(history, client, window.__data);
const component = (
<Router render={(props) =>
<ReduxAsyncConnect {...props} helpers={{client}} filter={item => !item.deferred} />
} history={history}>
{getRoutes(store)}
</Router>
);
ReactDOM.render(
<Provider store={store} key="provider">
{component}
</Provider>,
dest
);
if (process.env.NODE_ENV !== 'production') {
window.React = React; // enable debugger
if (!dest || !dest.firstChild || !dest.firstChild.attributes || !dest.firstChild.attributes['data-react-checksum']) {
console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.');
}
}
if (__DEVTOOLS__ && !window.devToolsExtension) {
const DevTools = require('./containers/DevTools/DevTools');
ReactDOM.render(
<Provider store={store} key="provider">
<div>
{component}
<DevTools />
</div>
</Provider>,
dest
);
}
|
examples/server-rendering/routes.js | acdlite/redux-router | import React from 'react';
import {Route} from 'react-router';
import {App, Parent, Child} from './components';
export default (
<Route path="/" component={App}>
<Route path="parent" component={Parent}>
<Route path="child" component={Child} />
<Route path="child/:id" component={Child} />
</Route>
</Route>
);
|
fields/types/code/CodeField.js | joerter/keystone | import _ from 'lodash';
import CodeMirror from 'codemirror';
import Field from '../Field';
import React from 'react';
import ReactDOM from 'react-dom';
import { FormInput } from 'elemental';
import classnames from 'classnames';
/**
* TODO:
* - Remove dependency on underscore
*/
// See CodeMirror docs for API:
// http://codemirror.net/doc/manual.html
module.exports = Field.create({
displayName: 'CodeField',
getInitialState () {
return {
isFocused: false,
};
},
componentDidMount () {
if (!this.refs.codemirror) {
return;
}
var options = _.defaults({}, this.props.editor, {
lineNumbers: true,
readOnly: this.shouldRenderField() ? false : true,
});
this.codeMirror = CodeMirror.fromTextArea(ReactDOM.findDOMNode(this.refs.codemirror), options);
this.codeMirror.setSize(null, this.props.height);
this.codeMirror.on('change', this.codemirrorValueChanged);
this.codeMirror.on('focus', this.focusChanged.bind(this, true));
this.codeMirror.on('blur', this.focusChanged.bind(this, false));
this._currentCodemirrorValue = this.props.value;
},
componentWillUnmount () {
// todo: is there a lighter-weight way to remove the cm instance?
if (this.codeMirror) {
this.codeMirror.toTextArea();
}
},
componentWillReceiveProps (nextProps) {
if (this.codeMirror && this._currentCodemirrorValue !== nextProps.value) {
this.codeMirror.setValue(nextProps.value);
}
},
focus () {
if (this.codeMirror) {
this.codeMirror.focus();
}
},
focusChanged (focused) {
this.setState({
isFocused: focused,
});
},
codemirrorValueChanged (doc, change) { // eslint-disable-line no-unused-vars
var newValue = doc.getValue();
this._currentCodemirrorValue = newValue;
this.props.onChange({
path: this.props.path,
value: newValue,
});
},
renderCodemirror () {
const className = classnames('CodeMirror-container', {
'is-focused': this.state.isFocused && this.shouldRenderField(),
});
return (
<div className={className}>
<FormInput multiline ref="codemirror" name={this.props.path} value={this.props.value} onChange={this.valueChanged} autoComplete="off" />
</div>
);
},
renderValue () {
return this.renderCodemirror();
},
renderField () {
return this.renderCodemirror();
},
});
|
app/javascript/mastodon/features/standalone/compose/index.js | summoners-riftodon/mastodon | import React from 'react';
import ComposeFormContainer from '../../compose/containers/compose_form_container';
import NotificationsContainer from '../../ui/containers/notifications_container';
import LoadingBarContainer from '../../ui/containers/loading_bar_container';
import ModalContainer from '../../ui/containers/modal_container';
export default class Compose extends React.PureComponent {
render () {
return (
<div>
<ComposeFormContainer />
<NotificationsContainer />
<ModalContainer />
<LoadingBarContainer className='loading-bar' />
</div>
);
}
}
|
src/svg-icons/action/settings-input-composite.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsInputComposite = (props) => (
<SvgIcon {...props}>
<path d="M5 2c0-.55-.45-1-1-1s-1 .45-1 1v4H1v6h6V6H5V2zm4 14c0 1.3.84 2.4 2 2.82V23h2v-4.18c1.16-.41 2-1.51 2-2.82v-2H9v2zm-8 0c0 1.3.84 2.4 2 2.82V23h2v-4.18C6.16 18.4 7 17.3 7 16v-2H1v2zM21 6V2c0-.55-.45-1-1-1s-1 .45-1 1v4h-2v6h6V6h-2zm-8-4c0-.55-.45-1-1-1s-1 .45-1 1v4H9v6h6V6h-2V2zm4 14c0 1.3.84 2.4 2 2.82V23h2v-4.18c1.16-.41 2-1.51 2-2.82v-2h-6v2z"/>
</SvgIcon>
);
ActionSettingsInputComposite = pure(ActionSettingsInputComposite);
ActionSettingsInputComposite.displayName = 'ActionSettingsInputComposite';
ActionSettingsInputComposite.muiName = 'SvgIcon';
export default ActionSettingsInputComposite;
|
docs/src/app/components/pages/components/IconMenu/ExampleSimple.js | manchesergit/material-ui | import React from 'react';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import IconButton from 'material-ui/IconButton';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
/**
* Simple Icon Menus demonstrating some of the layouts possible using the `anchorOrigin` and
* `targetOrigin` properties.
*/
const IconMenuExampleSimple = () => (
<div>
<IconMenu
iconButtonElement={<IconButton><MoreVertIcon /></IconButton>}
anchorOrigin={{horizontal: 'left', vertical: 'top'}}
targetOrigin={{horizontal: 'left', vertical: 'top'}}
>
<MenuItem primaryText="Refresh" />
<MenuItem primaryText="Send feedback" />
<MenuItem primaryText="Settings" />
<MenuItem primaryText="Help" />
<MenuItem primaryText="Sign out" />
</IconMenu>
<IconMenu
iconButtonElement={<IconButton><MoreVertIcon /></IconButton>}
anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
targetOrigin={{horizontal: 'left', vertical: 'bottom'}}
>
<MenuItem primaryText="Refresh" />
<MenuItem primaryText="Send feedback" />
<MenuItem primaryText="Settings" />
<MenuItem primaryText="Help" />
<MenuItem primaryText="Sign out" />
</IconMenu>
<IconMenu
iconButtonElement={<IconButton><MoreVertIcon /></IconButton>}
anchorOrigin={{horizontal: 'right', vertical: 'bottom'}}
targetOrigin={{horizontal: 'right', vertical: 'bottom'}}
>
<MenuItem primaryText="Refresh" />
<MenuItem primaryText="Send feedback" />
<MenuItem primaryText="Settings" />
<MenuItem primaryText="Help" />
<MenuItem primaryText="Sign out" />
</IconMenu>
<IconMenu
iconButtonElement={<IconButton><MoreVertIcon /></IconButton>}
anchorOrigin={{horizontal: 'right', vertical: 'top'}}
targetOrigin={{horizontal: 'right', vertical: 'top'}}
>
<MenuItem primaryText="Refresh" />
<MenuItem primaryText="Send feedback" />
<MenuItem primaryText="Settings" />
<MenuItem primaryText="Help" />
<MenuItem primaryText="Sign out" />
</IconMenu>
</div>
);
export default IconMenuExampleSimple;
|
src/parser/hunter/marksmanship/modules/talents/HuntersMark.js | fyruna/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import ItemDamageDone from 'interface/others/ItemDamageDone';
import Enemies from 'parser/shared/modules/Enemies';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import TalentStatisticBox from 'interface/others/TalentStatisticBox';
import { formatPercentage } from 'common/format';
import { encodeTargetString } from 'parser/shared/modules/EnemyInstances';
import StatisticListBoxItem from 'interface/others/StatisticListBoxItem';
/**
* Apply Hunter's Mark to the target, increasing all damage you deal to the marked target by 5%.
* If the target dies while affected by Hunter's Mark, you instantly gain 20 Focus.
* The target can always be seen and tracked by the Hunter.
*
* Only one Hunter's Mark can be applied at a time.
*
* Example log: https://www.warcraftlogs.com/reports/v6nrtTxNKGDmYJXy#fight=16&type=auras&hostility=1&spells=debuffs&target=6
*/
const HUNTERS_MARK_MODIFIER = 0.05;
const FOCUS_PER_REFUND = 20;
const MS_BUFFER = 100;
class HuntersMark extends Analyzer {
static dependencies = {
enemies: Enemies,
};
casts = 0;
damage = 0;
recasts = 0;
refunds = 0;
debuffRemoved = false;
timeOfCast = 0;
precastConfirmed = false;
markWindow = [];
damageToTarget = [];
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.HUNTERS_MARK_TALENT.id);
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.HUNTERS_MARK_TALENT.id) {
return;
}
this.casts++;
this.timeOfCast = event.timestamp;
}
on_byPlayer_removedebuff(event) {
const spellID = event.ability.guid;
if (spellID !== SPELLS.HUNTERS_MARK_TALENT.id) {
return;
}
if (event.timestamp > this.timeOfCast + MS_BUFFER) {
this.debuffRemoved = true;
}
const enemyID = encodeTargetString(event.targetID, event.targetInstance);
if (this.precastConfirmed === false) {
this.precastConfirmed = true;
this.damage = this.damageToTarget[enemyID];
return;
}
if (!this.markWindow[enemyID]) {
return;
}
this.markWindow[enemyID].forEach(window => {
if (window.status === "active") {
window.status = "inactive";
}
});
}
on_byPlayer_applydebuff(event) {
const spellID = event.ability.guid;
if (spellID !== SPELLS.HUNTERS_MARK_TALENT.id) {
return;
}
if (!this.precastConfirmed) {
this.precastConfirmed = true;
}
if (!this.debuffRemoved) {
this.recasts++;
}
this.debuffRemoved = false;
const enemyID = encodeTargetString(event.targetID, event.targetInstance);
if (!this.markWindow[enemyID]) {
this.markWindow[enemyID] = [];
}
this.markWindow[enemyID].push({ status: "active", start: event.timestamp });
}
calculateMarkDamage(event) {
const enemyID = encodeTargetString(event.targetID, event.targetInstance);
if (!this.precastConfirmed) {
if (!this.damageToTarget[enemyID]) {
this.damageToTarget[enemyID] = 0;
}
this.damageToTarget[enemyID] += calculateEffectiveDamage(event, HUNTERS_MARK_MODIFIER);
}
if (!this.markWindow[enemyID]) {
return;
}
this.markWindow[enemyID].forEach(window => {
if (window.start < event.timestamp && window.status === "active") {
this.damage += calculateEffectiveDamage(event, HUNTERS_MARK_MODIFIER);
}
});
}
on_byPlayer_refreshdebuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.HUNTERS_MARK_TALENT.id) {
return;
}
this.recasts++;
}
on_byPlayer_energize(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.HUNTERS_MARK_FOCUS.id) {
return;
}
this.refunds++;
}
on_byPlayer_damage(event) {
const enemy = this.enemies.getEntity(event);
if (!enemy) {
return;
}
this.calculateMarkDamage(event);
}
get uptimePercentage() {
return this.enemies.getBuffUptime(SPELLS.HUNTERS_MARK_TALENT.id) / this.owner.fightDuration;
}
get potentialPrecastConfirmation() {
return (this.refunds + this.recasts) > this.casts ? <li>We've detected a possible precast, and there might be a discrepancy in amount of total casts versus amount of refunds and casts whilst debuff was active on another target.</li> : '';
}
statistic() {
return (
<TalentStatisticBox
talent={SPELLS.HUNTERS_MARK_TALENT.id}
value={`${formatPercentage(this.uptimePercentage)}% uptime`}
tooltip={(
<ul>
<li>You had a total of {this.casts} casts of Hunter's Mark.</li>
<li>You cast Hunter's Mark {this.recasts} times, whilst it was active on the target or another target.</li>
<li>You received up to {this.refunds * FOCUS_PER_REFUND} Focus from a total of {this.refunds} refunds from targets with Hunter's Mark active dying.</li>
{this.potentialPrecastConfirmation}
</ul>
)}
/>
);
}
subStatistic() {
return (
<StatisticListBoxItem
title={<SpellLink id={SPELLS.HUNTERS_MARK_TALENT.id} />}
value={<ItemDamageDone amount={this.damage} />}
/>
);
}
}
export default HuntersMark;
|
app/javascript/mastodon/features/ui/index.js | rekif/mastodon | import classNames from 'classnames';
import React from 'react';
import { HotKeys } from 'react-hotkeys';
import { defineMessages, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { Redirect, withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';
import NotificationsContainer from './containers/notifications_container';
import LoadingBarContainer from './containers/loading_bar_container';
import TabsBar from './components/tabs_bar';
import ModalContainer from './containers/modal_container';
import { isMobile } from '../../is_mobile';
import { debounce } from 'lodash';
import { uploadCompose, resetCompose, insertNhooCompose, submitCompose } from '../../actions/compose';
import { expandHomeTimeline } from '../../actions/timelines';
import { expandNotifications } from '../../actions/notifications';
import { fetchFilters } from '../../actions/filters';
import { clearHeight } from '../../actions/height_cache';
import { WrappedSwitch, WrappedRoute } from './util/react_router_helpers';
import UploadArea from './components/upload_area';
import ColumnsAreaContainer from './containers/columns_area_container';
import {
Compose,
Status,
GettingStarted,
KeyboardShortcuts,
PublicTimeline,
CommunityTimeline,
AccountTimeline,
AccountGallery,
HomeTimeline,
Followers,
Following,
Reblogs,
Favourites,
DirectTimeline,
HashtagTimeline,
Notifications,
FollowRequests,
GenericNotFound,
FavouritedStatuses,
ListTimeline,
Blocks,
DomainBlocks,
Mutes,
PinnedStatuses,
Lists,
} from './util/async-components';
import { me } from '../../initial_state';
import { previewState } from './components/media_modal';
// Dummy import, to make sure that <Status /> ends up in the application bundle.
// Without this it ends up in ~8 very commonly used bundles.
import '../../components/status';
const messages = defineMessages({
beforeUnload: { id: 'ui.beforeunload', defaultMessage: 'Your draft will be lost if you leave Mastodon.' },
});
const mapStateToProps = state => ({
isComposing: state.getIn(['compose', 'is_composing']),
hasComposingText: state.getIn(['compose', 'text']).trim().length !== 0,
hasMediaAttachments: state.getIn(['compose', 'media_attachments']).size > 0,
dropdownMenuIsOpen: state.getIn(['dropdown_menu', 'openId']) !== null,
});
const keyMap = {
help: '?',
new: 'n',
nhoo: 'option+i',
search: 's',
forceNew: 'option+n',
focusColumn: ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
reply: 'r',
favourite: 'f',
boost: 'b',
mention: 'm',
open: ['enter', 'o'],
openProfile: 'p',
moveDown: ['down', 'j'],
moveUp: ['up', 'k'],
back: 'backspace',
goToHome: 'g h',
goToNotifications: 'g n',
goToLocal: 'g l',
goToFederated: 'g t',
goToDirect: 'g d',
goToStart: 'g s',
goToFavourites: 'g f',
goToPinned: 'g p',
goToProfile: 'g u',
goToBlocked: 'g b',
goToMuted: 'g m',
goToRequests: 'g r',
toggleHidden: 'x',
};
class SwitchingColumnsArea extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
location: PropTypes.object,
onLayoutChange: PropTypes.func.isRequired,
};
state = {
mobile: isMobile(window.innerWidth),
};
componentWillMount () {
window.addEventListener('resize', this.handleResize, { passive: true });
}
componentDidUpdate (prevProps) {
if (![this.props.location.pathname, '/'].includes(prevProps.location.pathname)) {
this.node.handleChildrenContentChange();
}
}
componentWillUnmount () {
window.removeEventListener('resize', this.handleResize);
}
shouldUpdateScroll (_, { location }) {
return location.state !== previewState;
}
handleResize = debounce(() => {
// The cached heights are no longer accurate, invalidate
this.props.onLayoutChange();
this.setState({ mobile: isMobile(window.innerWidth) });
}, 500, {
trailing: true,
});
setRef = c => {
this.node = c.getWrappedInstance().getWrappedInstance();
}
render () {
const { children } = this.props;
const { mobile } = this.state;
const redirect = mobile ? <Redirect from='/' to='/timelines/home' exact /> : <Redirect from='/' to='/getting-started' exact />;
return (
<ColumnsAreaContainer ref={this.setRef} singleColumn={mobile}>
<WrappedSwitch>
{redirect}
<WrappedRoute path='/getting-started' component={GettingStarted} content={children} />
<WrappedRoute path='/keyboard-shortcuts' component={KeyboardShortcuts} content={children} />
<WrappedRoute path='/timelines/home' component={HomeTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/timelines/public' exact component={PublicTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/timelines/public/media' component={PublicTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, onlyMedia: true }} />
<WrappedRoute path='/timelines/public/local' exact component={CommunityTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/timelines/public/local/media' component={CommunityTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, onlyMedia: true }} />
<WrappedRoute path='/timelines/direct' component={DirectTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/timelines/tag/:id' component={HashtagTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/timelines/list/:id' component={ListTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/notifications' component={Notifications} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/favourites' component={FavouritedStatuses} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/pinned' component={PinnedStatuses} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/search' component={Compose} content={children} componentParams={{ isSearchPage: true }} />
<WrappedRoute path='/statuses/new' component={Compose} content={children} />
<WrappedRoute path='/statuses/:statusId' exact component={Status} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/statuses/:statusId/reblogs' component={Reblogs} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/statuses/:statusId/favourites' component={Favourites} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/accounts/:accountId' exact component={AccountTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/accounts/:accountId/with_replies' component={AccountTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, withReplies: true }} />
<WrappedRoute path='/accounts/:accountId/followers' component={Followers} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/accounts/:accountId/following' component={Following} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/accounts/:accountId/media' component={AccountGallery} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/follow_requests' component={FollowRequests} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/blocks' component={Blocks} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/domain_blocks' component={DomainBlocks} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/mutes' component={Mutes} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/lists' component={Lists} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute component={GenericNotFound} content={children} />
</WrappedSwitch>
</ColumnsAreaContainer>
);
}
}
export default @connect(mapStateToProps)
@injectIntl
@withRouter
class UI extends React.PureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
dispatch: PropTypes.func.isRequired,
children: PropTypes.node,
isComposing: PropTypes.bool,
hasComposingText: PropTypes.bool,
hasMediaAttachments: PropTypes.bool,
location: PropTypes.object,
intl: PropTypes.object.isRequired,
dropdownMenuIsOpen: PropTypes.bool,
};
state = {
draggingOver: false,
};
handleBeforeUnload = (e) => {
const { intl, isComposing, hasComposingText, hasMediaAttachments } = this.props;
if (isComposing && (hasComposingText || hasMediaAttachments)) {
// Setting returnValue to any string causes confirmation dialog.
// Many browsers no longer display this text to users,
// but we set user-friendly message for other browsers, e.g. Edge.
e.returnValue = intl.formatMessage(messages.beforeUnload);
}
}
handleLayoutChange = () => {
// The cached heights are no longer accurate, invalidate
this.props.dispatch(clearHeight());
}
handleDragEnter = (e) => {
e.preventDefault();
if (!this.dragTargets) {
this.dragTargets = [];
}
if (this.dragTargets.indexOf(e.target) === -1) {
this.dragTargets.push(e.target);
}
if (e.dataTransfer && Array.from(e.dataTransfer.types).includes('Files')) {
this.setState({ draggingOver: true });
}
}
handleDragOver = (e) => {
e.preventDefault();
e.stopPropagation();
try {
e.dataTransfer.dropEffect = 'copy';
} catch (err) {
}
return false;
}
handleDrop = (e) => {
e.preventDefault();
this.setState({ draggingOver: false });
if (e.dataTransfer && e.dataTransfer.files.length === 1) {
this.props.dispatch(uploadCompose(e.dataTransfer.files));
}
}
handleDragLeave = (e) => {
e.preventDefault();
e.stopPropagation();
this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el));
if (this.dragTargets.length > 0) {
return;
}
this.setState({ draggingOver: false });
}
closeUploadModal = () => {
this.setState({ draggingOver: false });
}
handleServiceWorkerPostMessage = ({ data }) => {
if (data.type === 'navigate') {
this.context.router.history.push(data.path);
} else {
console.warn('Unknown message type:', data.type);
}
}
componentWillMount () {
window.addEventListener('beforeunload', this.handleBeforeUnload, false);
document.addEventListener('dragenter', this.handleDragEnter, false);
document.addEventListener('dragover', this.handleDragOver, false);
document.addEventListener('drop', this.handleDrop, false);
document.addEventListener('dragleave', this.handleDragLeave, false);
document.addEventListener('dragend', this.handleDragEnd, false);
if ('serviceWorker' in navigator) {
navigator.serviceWorker.addEventListener('message', this.handleServiceWorkerPostMessage);
}
this.props.dispatch(expandHomeTimeline());
this.props.dispatch(expandNotifications());
setTimeout(() => this.props.dispatch(fetchFilters()), 500);
}
componentDidMount () {
this.hotkeys.__mousetrap__.stopCallback = (e, element) => {
return ['TEXTAREA', 'SELECT', 'INPUT'].includes(element.tagName);
};
}
componentWillUnmount () {
window.removeEventListener('beforeunload', this.handleBeforeUnload);
document.removeEventListener('dragenter', this.handleDragEnter);
document.removeEventListener('dragover', this.handleDragOver);
document.removeEventListener('drop', this.handleDrop);
document.removeEventListener('dragleave', this.handleDragLeave);
document.removeEventListener('dragend', this.handleDragEnd);
}
setRef = c => {
this.node = c;
}
handleHotkeyNew = e => {
e.preventDefault();
const element = this.node.querySelector('.compose-form__autosuggest-wrapper textarea');
if (element) {
element.focus();
}
}
handleHotkeyNhoo = e => {
this.handleHotkeyNew(e);
this.props.dispatch(resetCompose());
this.props.dispatch(insertNhooCompose());
this.props.dispatch(submitCompose());
}
handleHotkeySearch = e => {
e.preventDefault();
const element = this.node.querySelector('.search__input');
if (element) {
element.focus();
}
}
handleHotkeyForceNew = e => {
this.handleHotkeyNew(e);
this.props.dispatch(resetCompose());
}
handleHotkeyFocusColumn = e => {
const index = (e.key * 1) + 1; // First child is drawer, skip that
const column = this.node.querySelector(`.column:nth-child(${index})`);
if (column) {
const status = column.querySelector('.focusable');
if (status) {
status.focus();
}
}
}
handleHotkeyBack = () => {
if (window.history && window.history.length === 1) {
this.context.router.history.push('/');
} else {
this.context.router.history.goBack();
}
}
setHotkeysRef = c => {
this.hotkeys = c;
}
handleHotkeyToggleHelp = () => {
if (this.props.location.pathname === '/keyboard-shortcuts') {
this.context.router.history.goBack();
} else {
this.context.router.history.push('/keyboard-shortcuts');
}
}
handleHotkeyGoToHome = () => {
this.context.router.history.push('/timelines/home');
}
handleHotkeyGoToNotifications = () => {
this.context.router.history.push('/notifications');
}
handleHotkeyGoToLocal = () => {
this.context.router.history.push('/timelines/public/local');
}
handleHotkeyGoToFederated = () => {
this.context.router.history.push('/timelines/public');
}
handleHotkeyGoToDirect = () => {
this.context.router.history.push('/timelines/direct');
}
handleHotkeyGoToStart = () => {
this.context.router.history.push('/getting-started');
}
handleHotkeyGoToFavourites = () => {
this.context.router.history.push('/favourites');
}
handleHotkeyGoToPinned = () => {
this.context.router.history.push('/pinned');
}
handleHotkeyGoToProfile = () => {
this.context.router.history.push(`/accounts/${me}`);
}
handleHotkeyGoToBlocked = () => {
this.context.router.history.push('/blocks');
}
handleHotkeyGoToMuted = () => {
this.context.router.history.push('/mutes');
}
handleHotkeyGoToRequests = () => {
this.context.router.history.push('/follow_requests');
}
render () {
const { draggingOver } = this.state;
const { children, isComposing, location, dropdownMenuIsOpen } = this.props;
const handlers = {
help: this.handleHotkeyToggleHelp,
new: this.handleHotkeyNew,
nhoo: this.handleHotkeyNhoo,
search: this.handleHotkeySearch,
forceNew: this.handleHotkeyForceNew,
focusColumn: this.handleHotkeyFocusColumn,
back: this.handleHotkeyBack,
goToHome: this.handleHotkeyGoToHome,
goToNotifications: this.handleHotkeyGoToNotifications,
goToLocal: this.handleHotkeyGoToLocal,
goToFederated: this.handleHotkeyGoToFederated,
goToDirect: this.handleHotkeyGoToDirect,
goToStart: this.handleHotkeyGoToStart,
goToFavourites: this.handleHotkeyGoToFavourites,
goToPinned: this.handleHotkeyGoToPinned,
goToProfile: this.handleHotkeyGoToProfile,
goToBlocked: this.handleHotkeyGoToBlocked,
goToMuted: this.handleHotkeyGoToMuted,
goToRequests: this.handleHotkeyGoToRequests,
};
return (
<HotKeys keyMap={keyMap} handlers={handlers} ref={this.setHotkeysRef} attach={window} focused>
<div className={classNames('ui', { 'is-composing': isComposing })} ref={this.setRef} style={{ pointerEvents: dropdownMenuIsOpen ? 'none' : null }}>
<TabsBar />
<SwitchingColumnsArea location={location} onLayoutChange={this.handleLayoutChange}>
{children}
</SwitchingColumnsArea>
<NotificationsContainer />
<LoadingBarContainer className='loading-bar' />
<ModalContainer />
<UploadArea active={draggingOver} onClose={this.closeUploadModal} />
</div>
</HotKeys>
);
}
}
|
src/components/MediaList/LoadingRow.js | u-wave/web | import cx from 'clsx';
import React from 'react';
import PropTypes from 'prop-types';
import MediaLoadingIndicator from './MediaLoadingIndicator';
function LoadingRow({ className, ...attrs }) {
return (
<div className={cx('MediaListRow', 'is-loading', className)} {...attrs}>
<MediaLoadingIndicator className="MediaListRow-loader" />
<div className="MediaListRow-data">
<div className="MediaListRow-artist">
{' … '}
</div>
<div className="MediaListRow-title">
{' … '}
</div>
</div>
<div className="MediaListRow-duration">
{' … '}
</div>
<div className="MediaListRow-icon" />
</div>
);
}
LoadingRow.propTypes = {
className: PropTypes.string,
selected: PropTypes.bool,
};
export default LoadingRow;
|
jenkins-design-language/src/js/components/material-ui/svg-icons/communication/import-export.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const CommunicationImportExport = (props) => (
<SvgIcon {...props}>
<path d="M9 3L5 6.99h3V14h2V6.99h3L9 3zm7 14.01V10h-2v7.01h-3L15 21l4-3.99h-3z"/>
</SvgIcon>
);
CommunicationImportExport.displayName = 'CommunicationImportExport';
CommunicationImportExport.muiName = 'SvgIcon';
export default CommunicationImportExport;
|
src/frontend/components/AdminEventUploadRsvps.js | Bernie-2016/ground-control | import React from 'react'
import Dropzone from 'react-dropzone';
import {BernieText, BernieColors} from './styles/bernie-css'
import {RaisedButton} from 'material-ui'
import Papa from 'papaparse'
import superagent from 'superagent'
import downloadCSV from '../helpers/downloadCSV'
export default class AdminEventUploadRsvps extends React.Component {
styles = {
dropzoneStyle: {
font: BernieText.default,
fontSize: '1.5em',
color: BernieColors.green,
margin: '0 auto',
width: 500,
height: 500,
borderWidth: 2,
borderColor: BernieColors.green,
borderStyle: 'dashed',
borderRadius: 5,
position: 'relative',
textAlign: 'center',
overflow: 'scroll'
},
dropzoneActiveStyle: {
borderStyle: 'solid',
backgroundColor: '#eee'
},
dropzoneRejectStyle: {
borderStyle: 'solid',
backgroundColor: '#ffdddd'
},
fileStatus: {
...BernieText.secondaryTitle,
fontSize: '0.75em',
textAlign: 'left',
paddingLeft: 20
}
}
state = {
filesProcessed: {},
}
allowedKeys = new Set([
'event_id',
'event_id_obfuscated',
'will_attend',
'guid',
'email',
'zip',
'country',
'shift_ids',
'phone',
'employer',
'occupation',
'addr1',
'addr2',
'addr3',
'city',
'comment',
// 'firstname', // not sure why first and last name don't work, but they're also not immediately necessary
'guests',
'is_potential_volunteer',
'is_reminder_sent',
// 'lastname',
'pledge_amt',
'pledge_method',
'state_cd',
'zip_4'
])
createRSVPs(row, fileName, [...eventIdKeys]) {
const obfuscatedIds = eventIdKeys
.filter((key) => row[key])
.map((key) => row[key])
const event_id_obfuscated = [row.event_id_obfuscated, ...obfuscatedIds].join(',')
if (event_id_obfuscated)
row.event_id_obfuscated = event_id_obfuscated
Object.keys(row).forEach((key) => {
if (!this.allowedKeys.has(key))
delete row[key]
})
superagent.post('/events/add-rsvp')
.set('Accept', 'application/json')
.send(row)
.end((err, res) => {
let filesProcessed = this.state.filesProcessed
let processObj = filesProcessed[fileName]
processObj.processedRows += 1
console.log(res.body)
if (err) {
processObj.errors.push(res.body)
}
filesProcessed[fileName] = processObj
this.setState(filesProcessed)
})
}
onDrop = (files) => {
let eventIdKeys
const transformFields = (chunk) => {
eventIdKeys = new Set(chunk.match(/(Event\s\d+\sID)/g))
return chunk
.replace(/Email Address/i, 'email')
.replace(/First Name/i, 'firstname')
.replace(/Last Name/i, 'lastname')
.replace(/Phone Number/i, 'phone')
.replace(/Zip/i, 'zip')
.replace(/DWID/i, 'guid')
}
files.forEach((file) => {
let reader = new FileReader();
reader.onload = (e) => {
let text = reader.result;
let data = Papa.parse(text, {header: true, beforeFirstChunk: transformFields}).data
let processObj = {
totalRows: data.length,
processedRows: 0,
errors: []
}
let currentFiles = this.state.filesProcessed
currentFiles[file.name] = processObj
this.setState({filesProcessed: currentFiles})
if (confirm(`You are about to upload ${data.length} RSVPs. Continue?`)) {
for (let i=0; i<data.length; i++){
this.createRSVPs(data[i], file.name, eventIdKeys)
}
}
}
reader.readAsText(file, 'utf8');
})
}
renderFileProgress() {
let count = 0
let renderErrors = (fileObj) => {
if (fileObj.errors.length === 0)
return <div></div>
return (
<div style={{
...BernieText.default,
borderTop: '1px solid ' + BernieColors.red,
fontSize: '0.5em',
paddingLeft: 10,
width: 470,
}}>
{fileObj.errors.map((error) => {
return (
<div>
{`${error.email}, Zip: ${error.zip}, Phone: ${error.phone}`}
<br />
<span style={{color: BernieColors.red}}>{error.error}</span>
<hr />
</div>
)
})}
</div>
)
}
let renderDownloadErrors = (fileObj, fileName) => {
if (fileObj.errors.length === 0)
return <div></div>
return (
<RaisedButton
label="Download & Fix Errors"
primary={true}
style={{marginTop: '1em', marginBottom: '1em'}}
onTouchTap={() => {
const csv = Papa.unparse(fileObj.errors)
// modify file name to include 'errors'
fileName = fileName.split('.')
const fileExtension = fileName[fileName.length - 1]
fileName[fileName.length - 1] = 'errors'
fileName.push(fileExtension)
// download the file
downloadCSV(csv, fileName.join('.'))
}}
/>
)
}
let fileNodes = Object.keys(this.state.filesProcessed).map((fileName) => {
count = count + 1
let fileObj = this.state.filesProcessed[fileName]
let color = (fileObj.errors.length === 0 ? (fileObj.totalRows === fileObj.processedRows ? BernieColors.green : BernieColors.gray) : BernieColors.red)
return (
<div>
<div style={{
...this.styles.fileStatus,
color: color,
backgroundColor: count % 2 ? BernieColors.lightGray : BernieColors.white
}}>
{fileName}: {fileObj.processedRows}/{fileObj.totalRows}
{renderErrors(fileObj)}
</div>
{renderDownloadErrors(fileObj, fileName)}
</div>
)
})
return (
<div>
{fileNodes}
</div>
)
}
render() {
return (
<div style={{paddingTop: 40}}>
<Dropzone
onDrop={this.onDrop}
style={this.styles.dropzoneStyle}
activeStyle={this.styles.dropzoneActiveStyle}
rejectStyle={this.styles.dropzoneRejectStyle}
disableClick={true}
>
<div style={{
paddingTop: 20,
paddingBottom: 20,
borderBottom: '1px dashed ' + BernieColors.green
}}>
<div style={{...BernieText.title, fontSize: '1.2em', color: BernieColors.green}}>
Drop your CSVs of RSVPs here!
</div>
<div style={{...BernieText.default, fontSize: '0.65em'}}>
<a href="https://docs.google.com/a/berniesanders.com/spreadsheets/d/1eUrirsw6fM0WF5IHZl3PAUgiC1LJB6-KSiCDTwj3JI4/edit?usp=sharing" target="_blank">Click here for a valid .csv sample</a>
<br />
You can add more columns specified under "Query Parameters" <a href="https://www.bluestatedigital.com/page/api/doc#----------------------graph-addrsvp-----------------" target="_blank">here</a>.
</div>
</div>
{this.renderFileProgress()}
</Dropzone>
</div>
);
}
} |
client/router.js | jmptrader/AspNet-Server-Template | /**
* ASP.NET Core Starter Kit (https://dotnetreact.com)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
function decodeParam(val) {
if (!(typeof val === 'string' || val.length === 0)) {
return val;
}
try {
return decodeURIComponent(val);
} catch (err) {
if (err instanceof URIError) {
err.message = `Failed to decode param '${val}'`;
err.status = 400;
}
throw err;
}
}
// Match the provided URL path pattern to an actual URI string. For example:
// matchURI({ path: '/posts/:id' }, '/dummy') => null
// matchURI({ path: '/posts/:id' }, '/posts/123') => { id: 123 }
function matchURI(route, path) {
const match = route.pattern.exec(path);
if (!match) {
return null;
}
const params = Object.create(null);
for (let i = 1; i < match.length; i++) {
params[route.keys[i - 1].name] = match[i] !== undefined ? decodeParam(match[i]) : undefined;
}
return params;
}
// Find the route matching the specified location (context), fetch the required data,
// instantiate and return a React component
function resolve(routes, context) {
for (const route of routes) {
const params = matchURI(route, context.error ? '/error' : context.pathname);
if (params) {
// Check if the route has any data requirements, for example:
// { path: '/tasks/:id', data: { task: 'GET /api/tasks/$id' }, page: './pages/task' }
if (route.data) {
// Load page component and all required data in parallel
const keys = Object.keys(route.data);
return Promise.all([
route.load(),
...keys.map(key => {
const query = route.data[key];
const method = query.substring(0, query.indexOf(' ')); // GET
const url = query.substr(query.indexOf(' ') + 1); // /api/tasks/$id
// TODO: Replace query parameters with actual values coming from `params`
return fetch(url, { method }).then(resp => resp.json());
}),
]).then(([Page, ...data]) => {
const props = keys.reduce((result, key, i) => ({ ...result, [key]: data[i] }), {});
return <Page route={{ ...route, params }} error={context.error} {...props} />;
});
}
return route.load().then(Page => <Page route={{ ...route, params }} error={context.error} />);
}
}
const error = new Error('Page not found');
error.status = 404;
return Promise.reject(error);
}
export default { resolve };
|
js/jqwidgets/demos/react/app/scheduler/bindingtojson/app.js | luissancheza/sice | import React from 'react';
import ReactDOM from 'react-dom';
import JqxScheduler from '../../../jqwidgets-react/react_jqxscheduler.js';
class App extends React.Component {
render() {
// prepare the data
let source = {
dataType: 'json',
dataFields: [
{ name: 'id', type: 'string' },
{ name: 'status', type: 'string' },
{ name: 'about', type: 'string' },
{ name: 'address', type: 'string' },
{ name: 'company', type: 'string' },
{ name: 'name', type: 'string' },
{ name: 'style', type: 'string' },
{ name: 'calendar', type: 'string' },
{ name: 'start', type: 'date', format: 'yyyy-MM-dd HH:mm' },
{ name: 'end', type: 'date', format: 'yyyy-MM-dd HH:mm' }
],
id: 'id',
url: '../sampledata/appointments.txt'
};
let adapter = new $.jqx.dataAdapter(source);
let appointmentDataFields = {
from: 'start',
to: 'end',
id: 'id',
description: 'about',
location: 'address',
subject: 'name',
style: 'style',
status: 'status'
};
let views = [
'dayView',
'weekView',
'monthView'
];
return (
<JqxScheduler ref='myScheduler'
date={new $.jqx.date(2016, 11, 23)}
width={850}
height={600}
source={adapter}
showLegend={true}
appointmentDataFields={appointmentDataFields}
view={'weekView'}
views={views}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/Button.js | lzcmaro/react-ratchet | import React from 'react';
import classNames from 'classnames';
import Icon from './Icon';
import Badge from './Badge';
import {classesDecorator, stylesDecorator} from './utils/componentDecorators';
import ratchetUtils from './utils/ratchetUtils';
import {BUTTON_STYLES} from './utils/styleMaps';
let Button = React.createClass ({
propTypes: {
block:React.PropTypes.bool,
href: React.PropTypes.string,
target: React.PropTypes.string,
type: React.PropTypes.oneOf(['button', 'reset', 'submit'])
},
getDefaultProps() {
return{
block:false,
outlined:false
};
},
render() {
let classes = ratchetUtils.getClassSet(this.props);
let blockClass = ratchetUtils.prefix(this.props,'block');
let outlinedClass = ratchetUtils.prefix(this.props,'outlined');
let renderFuncName;
classes = {
...classes,
[blockClass]:this.props.block,
[outlinedClass]:this.props.outlined
};
renderFuncName = this.props.ratStyle === BUTTON_STYLES.LINK || this.props.href === '' || this.props.href || this.props.target ? 'renderAnchor' : 'renderButton';
return this[renderFuncName](classes);
},
renderAnchor(classes){
let Component = this.props.eleType || 'a';
let href = this.props.href || 'javascript:;';
return (
<Component
{...this.props}
href= {href}
className = {classNames(classes,this.props.className)}>
{this.props.children}
</Component>
)
},
renderButton(classes){
let Component = this.props.eleType || 'button';
return (
<Component
{...this.props}
type={this.props.type || 'button'}
className = {classNames(classes,this.props.className)}>
{this.props.children}
</Component>
)
}
});
export default stylesDecorator(BUTTON_STYLES.values(), classesDecorator('btn',Button)); |
src/index.js | Pochwar/ReduxSimpleStarter | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import GooderList from './components/gooder_list';
import GooderDetail from "./components/gooder_detail";
import OptionBar from './components/option_bar';
const MG_API_URL = 'https://api.mygooder.com/api/v1/gooders';
const LOCATIONS = {
'Partout' : '',
'Nantes' : '47.218371%2C-1.553621000000021',
'Rennes' : '48.117266%2C-1.6777925999999752',
'Brest' : '48.390394%2C-4.4860760000000255',
'Bordeaux' : '44.837789%2C-0.5791799999999512',
'Angers' : '47.478419%2C-0.5631660000000238',
'La Rochelle' : '46.160329%2C-1.1511390000000574'
};
const GOODER_PER_PAGE = [3, 5, 10];
class App extends Component{
constructor(props) {
super(props);
this.state = {
nbGooders: null,
nbPages: null,
currentPage: null,
gooders: [],
selectedGooder: null,
options: {
limit:3,
page: 1,
location: ''
}
}
this.callMyGooderApi(MG_API_URL, this.state.options);
}
callMyGooderApi(url, options){
let optStr = '?';
let c = 0;
let o = '';
for(const option in options) {
if (c != 0) o = "&";
if (options[option]) {
optStr += `${o}${option}=${options[option]}`;
}
c++;
}
fetch(url + optStr)
.then(result => {
// Get the result, If we want text, call result.text()
return result.json();
}).then(jsonResult => {
this.setState({
nbGooders: jsonResult.gooders.total,
nbPages: jsonResult.gooders.last_page,
currentPage: jsonResult.gooders.current_page,
gooders: jsonResult.gooders.data,
selectedGooder: jsonResult.gooders.data[0]
});
})
}
render() {
const tmpOptions = this.state.options;
const nbGooderPerPageChange = (nb) => {
tmpOptions.limit = nb;
this.setState({tmpOptions}, () => {
this.callMyGooderApi(MG_API_URL, this.state.options);
});
}
const nbPageChange = (nb) => {
tmpOptions.page = nb;
this.setState({tmpOptions}, () => {
this.callMyGooderApi(MG_API_URL, this.state.options);
});
}
const locationChange = (location) => {
tmpOptions.location = location;
this.setState({tmpOptions}, () => {
this.callMyGooderApi(MG_API_URL, this.state.options);
});
}
return (
<div>
<OptionBar
// option bar
nbGooders={this.state.nbGooders}
// option bar nb items
actualNbGooderPerPage={this.state.options.limit}
nbGooderPerPageTab={GOODER_PER_PAGE}
nbGooderPerPageChange={nb => nbGooderPerPageChange(nb)}
// option bar nb pages
actualNbPage={this.state.options.page}
nbPages={this.state.nbPages}
nbPageChange={nb => nbPageChange(nb)}
// option bar location
actualLocation={this.state.options.location}
locationsTab={LOCATIONS}
locationChange={location => locationChange(location)}
/>
<GooderDetail gooder={this.state.selectedGooder} />
<GooderList
actualGooder={this.state.selectedGooder}
onGooderSelect={selectedGooder => this.setState({selectedGooder})}
gooders={this.state.gooders}
/>
</div>
);
}
}
ReactDOM.render(
<App />,
document.querySelector('.container')
); |
packages/react-scripts/fixtures/kitchensink/src/features/env/ShellEnvVariables.js | g3r4n/create-esri-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
export default () => (
<span id="feature-shell-env-variables">
{process.env.REACT_APP_SHELL_ENV_MESSAGE}.
</span>
);
|
app/components/Toggle/index.js | ninjaref/ninjaref | /**
*
* LocaleToggle
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import Select from './Select';
import ToggleOption from '../ToggleOption';
function Toggle(props) {
let content = (<option>--</option>);
// If we have items, render them
if (props.values) {
content = props.values.map((value) => (
<ToggleOption key={value} value={value} message={props.messages[value]} />
));
}
return (
<Select value={props.value} onChange={props.onToggle}>
{content}
</Select>
);
}
Toggle.propTypes = {
onToggle: PropTypes.func,
values: PropTypes.array,
value: PropTypes.string,
messages: PropTypes.object,
};
export default Toggle;
|
lib/codemod/src/transforms/__testfixtures__/storiesof-to-csf/default.input.js | storybooks/storybook | /* eslint-disable */
import React from 'react';
import Button from './Button';
import { storiesOf } from '@storybook/react';
storiesOf('Button', module).add('default', () => <Button label="Story 1" />);
|
app/components/CategoriesForm/index.js | vlastoun/picture-uploader-crud |
import { Field, reduxForm } from 'redux-form/immutable'; // <--- immutable import
import React from 'react';
import PropTypes from 'prop-types';
import InputField from 'components/InputField';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import { Card, CardActions, CardTitle, CardText } from 'material-ui/Card';
import validate from './validate';
import asyncValidate from './asyncValidate';
/* eslint-disable jsx-a11y/label-has-for */
const cardStyle = {
marginTop: '1em',
marginBotom: '1em',
};
const buttonStyle = {
margin: '0.5em',
};
class CategoriesForm extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
const { sendData, handleSubmit, submitting, categoriesError, item } = this.props; //eslint-disable-line
const name = (
<Field
name="name"
type="text"
component={InputField}
label="Name"
/>);
const description = (
<Field
name="description"
type="text"
component={InputField}
label="Description"
multiLine
rows={2}
/>);
const Form = (
<form onSubmit={handleSubmit(sendData)}>
<Card style={cardStyle} zDepth={3} >
<CardTitle
title={name}
/>
<CardText>
{description}
</CardText>
<CardActions >
<RaisedButton type="submit" disabled={submitting} style={buttonStyle}>
Submit
</RaisedButton>
<RaisedButton type="button" disabled={submitting} onClick={this.props.close} secondary style={buttonStyle}>
Close
</RaisedButton>
</CardActions>
</Card>
</form>
);
return (
<div>
{
this.props.visibilityState
? Form
: <FlatButton onTouchTap={this.props.newCategory} primary>New category</FlatButton>
}
</div>
);
}
}
CategoriesForm.propTypes = {
close: PropTypes.func.isRequired,
visibilityState: PropTypes.bool.isRequired,
submitting: PropTypes.bool,
handleSubmit: PropTypes.func.isRequired,
sendData: PropTypes.func.isRequired,
categoriesError: PropTypes.object,
newCategory: PropTypes.func.isRequired,
};
export default reduxForm({
form: 'CategoriesForm', // a unique identifier for this form
validate,
asyncValidate,
asyncBlurFields: ['name'],
})(CategoriesForm);
|
admin/client/App/shared/FlashMessages.js | linhanyang/keystone | /**
* Render a few flash messages, e.g. errors, success messages, warnings,...
*
* Use like this:
* <FlashMessages
* messages={{
* error: [{
* title: 'There is a network problem',
* detail: 'Please try again later...',
* }],
* }}
* />
*
* Instead of error, it can also be hilight, info, success or warning
*/
import React from 'react';
import _ from 'lodash';
import FlashMessage from './FlashMessage';
var FlashMessages = React.createClass({
displayName: 'FlashMessages',
propTypes: {
messages: React.PropTypes.oneOfType([
React.PropTypes.bool,
React.PropTypes.shape({
error: React.PropTypes.array,
hilight: React.PropTypes.array,
info: React.PropTypes.array,
success: React.PropTypes.array,
warning: React.PropTypes.array,
}),
]),
},
// Render messages by their type
renderMessages (messages, type) {
if (!messages || !messages.length) return null;
return messages.map((message, i) => {
return <FlashMessage message={message} type={type} key={`i${i}`} />;
});
},
// Render the individual messages based on their type
renderTypes (types) {
return Object.keys(types).map(type => this.renderMessages(types[type], type));
},
render () {
if (!this.props.messages) return null;
return (
<div className="flash-messages">
{_.isPlainObject(this.props.messages) && this.renderTypes(this.props.messages)}
</div>
);
},
});
module.exports = FlashMessages;
|
src/app/index.js | skratchdot/ble-midi | /* eslint-env browser */
import './styles/app.less';
import App from './containers/app';
import { AppContainer } from 'react-hot-loader';
import { Provider } from 'react-redux';
import React from 'react';
import ReactDOM from 'react-dom';
import configureStore from './store/configure-store';
import injectTapEventPlugin from 'react-tap-event-plugin';
const store = configureStore();
const render = Component => {
ReactDOM.render(
<Provider store={store}>
<AppContainer>
<Component />
</AppContainer>
</Provider>,
document.body
);
};
if (module.hot) {
module.hot.accept('./containers/app', () => {
render(App);
});
}
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();
render(App);
|
techCurriculum/ui/solutions/4.7/src/components/TextInput.js | tadas412/EngineeringEssentials | /**
* Copyright 2017 Goldman Sachs.
* 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';
class TextInput extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
const value = event.target.value;
this.props.onChange(value);
}
render() {
return (
<div className='form-group'>
<label className='control-label'>{this.props.label}</label>
<input type='text' className='form-control' name={this.props.name} value={this.props.value} onChange={this.handleChange} />
</div>
)
}
}
export default TextInput;
|
src/caret.js | georgest/react-native-select-list | import React, { Component } from 'react';
import { StyleSheet, View } from 'react-native';
class Caret extends Component {
render() {
const { element, size, color } = this.props;
if (!element) {
return null;
}
if (typeof(element) !== "string") {
return element;
} else {
return <View style={[
styles.caret,
styles[element],
{
borderLeftWidth: size/2,
borderRightWidth: size/2,
borderTopWidth: size - 5,
borderTopColor: color,
}
]} />;
}
}
}
const styles = StyleSheet.create({
caret: {
width: 0,
height: 0,
backgroundColor: 'transparent',
borderStyle: 'solid',
borderLeftColor: 'transparent',
borderRightColor: 'transparent',
},
up: {
transform: [
{rotate: '180deg'}
]
}
});
Caret.propTypes = {
size: React.PropTypes.number,
color: React.PropTypes.string,
};
Caret.defaultProps = {
size: 15,
color: '#333333',
};
module.exports = Caret;
|
src/svg-icons/action/alarm-off.js | jacklam718/react-svg-iconx | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAlarmOff = (props) => (
<SvgIcon {...props}>
<path d="M12 6c3.87 0 7 3.13 7 7 0 .84-.16 1.65-.43 2.4l1.52 1.52c.58-1.19.91-2.51.91-3.92 0-4.97-4.03-9-9-9-1.41 0-2.73.33-3.92.91L9.6 6.43C10.35 6.16 11.16 6 12 6zm10-.28l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM2.92 2.29L1.65 3.57 2.98 4.9l-1.11.93 1.42 1.42 1.11-.94.8.8C3.83 8.69 3 10.75 3 13c0 4.97 4.02 9 9 9 2.25 0 4.31-.83 5.89-2.2l2.2 2.2 1.27-1.27L3.89 3.27l-.97-.98zm13.55 16.1C15.26 19.39 13.7 20 12 20c-3.87 0-7-3.13-7-7 0-1.7.61-3.26 1.61-4.47l9.86 9.86zM8.02 3.28L6.6 1.86l-.86.71 1.42 1.42.86-.71z"/>
</SvgIcon>
);
ActionAlarmOff = pure(ActionAlarmOff);
ActionAlarmOff.displayName = 'ActionAlarmOff';
ActionAlarmOff.muiName = 'SvgIcon';
export default ActionAlarmOff;
|
src/components/Layout/Footer/index.js | ndlib/usurper | import React from 'react'
import FooterLinks from './FooterLinks'
import FooterInfo from './FooterInfo'
const Footer = () => {
return (
<footer>
<FooterLinks />
<FooterInfo />
</footer>
)
}
export default Footer
|
l4/index.ios.js | huang6349/rn | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import App from './src/app';
AppRegistry.registerComponent('l4', () => App);
|
examples/sidebar/app.js | buddhike/react-router | import React from 'react';
import { Router, Route, Link } from 'react-router';
import data from './data';
var Category = React.createClass({
render() {
var category = data.lookupCategory(this.props.params.category);
return (
<div>
<h1>{category.name}</h1>
{this.props.children || (
<p>{category.description}</p>
)}
</div>
);
}
});
var CategorySidebar = React.createClass({
render() {
var category = data.lookupCategory(this.props.params.category);
return (
<div>
<Link to="/">◀︎ Back</Link>
<h2>{category.name} Items</h2>
<ul>
{category.items.map((item, index) => (
<li key={index}>
<Link to={`/category/${category.name}/${item.name}`}>{item.name}</Link>
</li>
))}
</ul>
</div>
);
}
});
var Item = React.createClass({
render() {
var { category, item } = this.props.params;
var menuItem = data.lookupItem(category, item);
return (
<div>
<h1>{menuItem.name}</h1>
<p>${menuItem.price}</p>
</div>
);
}
});
var Index = React.createClass({
render() {
return (
<div>
<h1>Sidebar</h1>
<p>
Routes can have multiple components, so that all portions of your UI
can participate in the routing.
</p>
</div>
);
}
});
var IndexSidebar = React.createClass({
render() {
return (
<div>
<h2>Categories</h2>
<ul>
{data.getAll().map((category, index) => (
<li key={index}>
<Link to={`/category/${category.name}`}>{category.name}</Link>
</li>
))}
</ul>
</div>
);
}
});
var App = React.createClass({
render() {
var { children } = this.props;
return (
<div>
<div className="Sidebar">
{children ? children.sidebar : <IndexSidebar />}
</div>
<div className="Content">
{children ? children.content : <Index />}
</div>
</div>
);
}
});
React.render((
<Router>
<Route path="/" component={App}>
<Route path="category/:category" components={{content: Category, sidebar: CategorySidebar}}>
<Route path=":item" component={Item} />
</Route>
</Route>
</Router>
), document.getElementById('example'));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.