path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/js/components/icons/base/VolumeLow.js | odedre/grommet-final | /**
* @description VolumeLow SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
* @example
* <svg width="24" height="24" ><path d="M1,8 L1,16 L6.09901951,16 L12,21 L12,3 L6,8 L1,8 Z M15,16 L15,16 C17.209139,16 19,14.209139 19,12 C19,9.790861 17.209139,8 15,8"/></svg>
*/
// (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}-volume-low`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'volume-low');
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="M1,8 L1,16 L6.09901951,16 L12,21 L12,3 L6,8 L1,8 Z M15,16 L15,16 C17.209139,16 19,14.209139 19,12 C19,9.790861 17.209139,8 15,8"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'VolumeLow';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
client/components/settings/emails/alert-form-modal.js | jankeromnes/kresus | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { translate as $t, AlertTypes } from '../../../helpers';
import { actions } from '../../../store';
import AccountSelector from './account-select';
import AmountInput from '../../ui/amount-input';
import Modal from '../../ui/modal';
class AlertCreationModal extends React.Component {
constructor(props) {
super(props);
this.state = { limit: null };
this.handleSubmit = this.handleSubmit.bind(this);
this.handleOnChangeAmountInput = this.handleOnChangeAmountInput.bind(this);
this.accountSelector = null;
this.orderSelector = null;
}
handleOnChangeAmountInput(limit) {
this.setState({ limit });
}
// TODO move handleSubmit logic in the above component for making this
// component a dumb one.
handleSubmit() {
let limit = this.state.limit;
// Actually submit the form
let newAlert = {
type: this.props.alertType,
limit,
order: this.orderSelector.value,
bankAccount: this.accountSelector.getWrappedInstance().value()
};
this.props.createAlert(newAlert);
// Clear form and errors
$(`#${this.props.modalId}`).modal('toggle');
this.setState({ limit: null });
}
render() {
let modalTitle = $t(this.props.titleTranslationKey);
let isBalanceAlert = this.props.alertType === 'balance';
let refAccountSelector = selector => {
this.accountSelector = selector;
};
let refOrderSelector = selector => {
this.orderSelector = selector;
};
let modalBody = (
<div>
<div className="form-group">
<label htmlFor="account">
{ $t('client.settings.emails.account') }
</label>
<AccountSelector
ref={ refAccountSelector }
id="account"
/>
</div>
<div className="form-group">
<span>{ this.props.sendIfText } </span>
<select
className="form-control"
ref={ refOrderSelector }>
<option value="gt">{ $t('client.settings.emails.greater_than') }</option>
<option value="lt">{ $t('client.settings.emails.less_than') }</option>
</select>
</div>
<div className="form-group">
<AmountInput
defaultValue={ this.state.limit !== null ? Math.abs(this.state.limit) : null }
initiallyNegative={ isBalanceAlert && this.state.limit < 0 }
togglable={ isBalanceAlert }
onChange={ this.handleOnChangeAmountInput }
signId={ `sign-${this.props.modalId}` }
/>
</div>
</div>
);
let modalFooter = (
<div>
<button
type="button"
className="btn btn-default"
data-dismiss="modal">
{ $t('client.general.cancel') }
</button>
<button
type="button"
className="btn btn-success"
onClick={ this.handleSubmit }
disabled={ Number.isNaN(this.state.limit) }>
{ $t('client.settings.emails.create') }
</button>
</div>
);
return (
<Modal
modalId={ this.props.modalId }
modalTitle={ modalTitle }
modalBody={ modalBody }
modalFooter={ modalFooter }
/>
);
}
}
AlertCreationModal.propTypes = {
// Type of alert
alertType: PropTypes.oneOf(AlertTypes).isRequired,
// Modal id
modalId: PropTypes.string.isRequired,
// Function which create the alert
createAlert: PropTypes.func.isRequired,
// Translation key of the title.
titleTranslationKey: PropTypes.string.isRequired,
// Description of the type of alert
sendIfText: PropTypes.string.isRequired
};
export default connect(() => {
return {};
}, dispatch => {
return {
createAlert(newAlert) {
actions.createAlert(dispatch, newAlert);
}
};
})(AlertCreationModal);
|
static/src/components/islands/IslandTree.js | andribja/airhornbot | // @flow
// jscs:disable maximumLineLength
import React from 'react';
import ResizableSVG from '../ResizableSVG';
export default React.createClass({
mixins: [ResizableSVG],
render(): React.Element {
let viewBox: string = this.getViewBox(259, 228);
let {paused} = this.props;
return (
<svg className={`island tree ${paused ? 'paused' : ''}`} xmlns="http://www.w3.org/2000/svg" width="259" height="252" viewBox={viewBox}>
<g fill="none" fill-rule="evenodd">
<path fill="#FFE6A7" d="M1.5012 124.2279v57.903l118.413 68.367 136.734-78.942v-57.903l-255.147 10.575z"/>
<path fill="#EDD194" d="M118.8135 119.3652v130.5l1.101.633 136.734-78.942v-57.903l-137.835 5.712z"/>
<path stroke="#5E4634" strokeWidth="3" d="M256.6494 113.6514v57.906l-136.734 78.942-118.416-68.367v-57.906" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#C7E082" d="M1.5012 124.2279v20.403l118.413 68.37 136.734-78.945v-20.403l-255.147 10.575z"/>
<path fill="#B0CC64" d="M119.8134 119.3235v93.618l.102.06 136.734-78.945v-20.406l-136.836 5.673z"/>
<path stroke="#5E4634" strokeWidth="3" d="M256.6494 116.6514v17.406l-136.734 78.942-118.416-68.367v-20.406" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#B7D86F" d="M1.5012 124.2279l118.413 68.367 136.734-78.942-118.413-68.367-136.734 78.942z"/>
<path stroke="#5E4634" strokeWidth="3" d="M119.9151 192.5949l-118.416-68.367 136.734-78.945 118.416 68.37-136.734 78.942zm0 0v57.906" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#EBEBEB" d="M128.5359 155.8383h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338"/>
<path stroke="#5E4634" strokeWidth="3" d="M128.5359 155.8383h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338z" strokeLinecap="round" strokeLinejoin="round"/>
<g className="leaves">
<path fill="#C3F270" d="M174.5202 103.4811l-.006-.003v-.003c-.738-6.15 5.319-10.884 11.106-8.685l.006.003v.003c.738 6.15-5.316 10.884-11.106 8.685"/>
<path stroke="#5E4634" strokeWidth="3" d="M174.5202 103.4811l-.006-.003v-.003c-.738-6.15 5.319-10.884 11.106-8.685l.006.003v.003c.738 6.15-5.316 10.884-11.106 8.685z" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#C3F270" d="M179.9169 25.9785v-.006h.006c5.667-2.493 11.958 1.923 11.535 8.103v.003l-.003.003c-5.67 2.493-11.961-1.926-11.538-8.103"/>
<path stroke="#5E4634" strokeWidth="3" d="M179.9169 25.9785v-.006h.006c5.667-2.493 11.958 1.923 11.535 8.103v.003l-.003.003c-5.67 2.493-11.961-1.926-11.538-8.103z" strokeLinecap="round" strokeLinejoin="round"/>
</g>
<path fill="#EDD194" d="M123.0954 116.8041l17.334-9.909c2.199-1.26 5.064-.936 6.714.984 1.233 1.434 1.998 3.441 1.998 5.664 0 2.973-1.371 5.562-3.396 6.903l-17.415 11.199"/>
<path stroke="#5E4634" strokeWidth="3" d="M123.0954 116.8041l17.334-9.909c2.199-1.26 5.064-.936 6.714.984 1.233 1.434 1.998 3.441 1.998 5.664 0 2.973-1.371 5.562-3.396 6.903l-17.415 11.199" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#FFE6A7" d="M132.3981 124.2567c0 4.434-2.991 8.028-6.681 8.028-3.693 0-6.684-3.594-6.684-8.028 0-4.434 2.991-8.028 6.684-8.028 3.69 0 6.681 3.594 6.681 8.028"/>
<path stroke="#5E4634" strokeWidth="3" d="M132.3981 124.2567c0 4.434-2.991 8.028-6.681 8.028-3.693 0-6.684-3.594-6.684-8.028 0-4.434 2.991-8.028 6.684-8.028 3.69 0 6.681 3.594 6.681 8.028zm24.9816-18.2232v3.249m63.7035-5.0343v3.249m-53.5137-23.8083v3.249m-10.1898-10.3017v3.249M50.4714 113.6514v3.249m137.2599 12.7443v3.249M37.8195 119.2956v3.249" strokeLinecap="round" strokeLinejoin="round"/>
<path fill="#FFE6A7" d="M87.6423 76.6362v52.428c0 2.268 4.458 4.107 9.957 4.107 5.499 0 9.957-1.839 9.957-4.107v-52.428h-19.914z"/>
<path fill="#EDD194" d="M98.0961 76.6362v56.517c5.262-.111 9.462-1.89 9.462-4.089v-52.428h-9.462z"/>
<path fill="#EDD194" d="M98.0961 76.6362v56.517c5.262-.111 9.462-1.89 9.462-4.089v-52.428h-9.462z"/>
<path stroke="#5E4634" strokeWidth="3" d="M87.6423 76.6362v52.428c0 2.268 4.458 4.107 9.957 4.107 5.499 0 9.957-1.839 9.957-4.107v-52.428h-19.914z" strokeLinecap="round" strokeLinejoin="round"/>
<g className="stretch">
<path fill="#C3F270" d="M103.7943 104.9043h-12.39c-19.443 0-35.349-15.906-35.349-35.349 0-19.443 15.906-35.349 35.349-35.349h12.39c19.443 0 35.349 15.906 35.349 35.349 0 19.443-15.906 35.349-35.349 35.349"/>
<path fill="#B7D86F" d="M113.811 35.6811c6.66 6.438 10.833 15.435 10.833 25.374 0 19.443-6.906 35.349-26.349 35.349h-21.39c-3.477 0-6.837-.528-10.017-1.476 6.369 6.159 15.012 9.975 24.516 9.975h12.39c19.443 0 35.349-15.906 35.349-35.349 0-15.963-10.731-29.526-25.332-33.873"/>
<path stroke="#5E4634" strokeWidth="3" d="M103.7943 104.9043h-12.39c-19.443 0-35.349-15.906-35.349-35.349 0-19.443 15.906-35.349 35.349-35.349h12.39c19.443 0 35.349 15.906 35.349 35.349 0 19.443-15.906 35.349-35.349 35.349z" strokeLinecap="round" strokeLinejoin="round"/>
</g>
<g className="lines">
<path stroke="#5E4634" strokeWidth="3" d="M168.4638 19.197c-22.68-11.94-48.399-18.042-74.025-17.568-14.496.267-29.208 2.697-42.066 9.396-12.855 6.696-23.709 18.054-27.633 32.01-3.924 13.956.06 30.384 11.388 39.432" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="6 12"/>
</g>
</g>
</svg>
);
}
});
|
renderer/components/Icon/Receive.js | LN-Zap/zap-desktop | import React from 'react'
const SvgReceive = props => (
<svg height="1em" viewBox="0 0 50 50" width="1em" {...props}>
<defs>
<linearGradient id="receive_svg__a" x1="0%" y1="0%" y2="100%">
<stop offset="0%" stopColor="#FFBD59" />
<stop offset="100%" stopColor="#FD9800" />
</linearGradient>
</defs>
<g fill="none" fillRule="evenodd">
<circle cx={25} cy={25} fill="url(#receive_svg__a)" r={25} />
<path d="M25.488 40L30 31l-9 .012z" stroke="currentColor" />
<path d="M25 31h1V10h-1z" fill="currentColor" />
</g>
</svg>
)
export default SvgReceive
|
src/TimePicker/Clock.js | rscnt/material-ui | import React from 'react';
import TimeDisplay from './TimeDisplay';
import ClockHours from './ClockHours';
import ClockMinutes from './ClockMinutes';
class Clock extends React.Component {
static propTypes = {
format: React.PropTypes.oneOf(['ampm', '24hr']),
initialTime: React.PropTypes.object,
isActive: React.PropTypes.bool,
mode: React.PropTypes.oneOf(['hour', 'minute']),
onChangeHours: React.PropTypes.func,
onChangeMinutes: React.PropTypes.func,
};
static defaultProps = {
initialTime: new Date(),
};
static contextTypes = {
muiTheme: React.PropTypes.object.isRequired,
};
state = {
selectedTime: this.props.initialTime || new Date(),
mode: 'hour',
};
componentWillReceiveProps(nextProps) {
this.setState({
selectedTime: nextProps.initialTime || new Date(),
});
}
setMode = (mode) => {
setTimeout(() => {
this.setState({
mode: mode,
});
}, 100);
};
handleSelectAffix = (affix) => {
if (affix === this.getAffix()) return;
const hours = this.state.selectedTime.getHours();
if (affix === 'am') {
this.handleChangeHours(hours - 12, affix);
return;
}
this.handleChangeHours(hours + 12, affix);
};
getAffix() {
if (this.props.format !== 'ampm') return '';
const hours = this.state.selectedTime.getHours();
if (hours < 12) {
return 'am';
}
return 'pm';
}
handleChangeHours = (hours, finished) => {
const time = new Date(this.state.selectedTime);
let affix;
if ( typeof finished === 'string' ) {
affix = finished;
finished = undefined;
}
if (!affix) {
affix = this.getAffix();
}
if (affix === 'pm' && hours < 12) {
hours += 12;
}
time.setHours(hours);
this.setState({
selectedTime: time,
});
const {onChangeHours} = this.props;
if (finished) {
setTimeout(() => {
this.setState({
mode: 'minute',
});
if (typeof (onChangeHours) === 'function') {
onChangeHours(time);
}
}, 100);
}
};
handleChangeMinutes = (minutes) => {
const time = new Date(this.state.selectedTime);
time.setMinutes(minutes);
this.setState({
selectedTime: time,
});
const {onChangeMinutes} = this.props;
if (typeof (onChangeMinutes) === 'function') {
setTimeout(() => {
onChangeMinutes(time);
}, 0);
}
};
getSelectedTime() {
return this.state.selectedTime;
}
render() {
let clock = null;
const {prepareStyles} = this.context.muiTheme;
const styles = {
root: {},
container: {
height: 280,
padding: 10,
position: 'relative',
},
circle: {
position: 'absolute',
top: 20,
width: 260,
height: 260,
borderRadius: '100%',
backgroundColor: this.context.muiTheme.timePicker.clockCircleColor,
},
};
if ( this.state.mode === 'hour') {
clock = (
<ClockHours key="hours"
format={this.props.format}
onChange={this.handleChangeHours}
initialHours={this.state.selectedTime.getHours()}
/>
);
} else {
clock = (
<ClockMinutes key="minutes"
onChange={this.handleChangeMinutes}
initialMinutes={this.state.selectedTime.getMinutes()}
/>
);
}
return (
<div style={prepareStyles(styles.root)}>
<TimeDisplay
selectedTime={this.state.selectedTime}
mode={this.state.mode}
format={this.props.format}
affix={this.getAffix()}
onSelectAffix={this.handleSelectAffix}
onSelectHour={this.setMode.bind(this, 'hour')}
onSelectMin={this.setMode.bind(this, 'minute')}
/>
<div style={prepareStyles(styles.container)} >
<div style={prepareStyles(styles.circle)} />
{clock}
</div>
</div>
);
}
}
export default Clock;
|
templates/rubix/rubix-bootstrap/src/L20n.js | jeffthemaximum/jeffline | import React from 'react';
import Dispatcher from './Dispatcher';
import isBrowser from './isBrowser';
var win = null;
if (!isBrowser()) {
win = {
L20n: {
getContext: function() {},
},
};
} else {
win = window;
if (!win.hasOwnProperty('L20n')) {
win.L20n = {
getContext: function() {},
};
}
}
var ctx = win.L20n.getContext();
var Entities = {
ready: false,
entities: {},
registerEntity: function(entity) {
if(Entities.hasOwnProperty(entity)) {
if(!Entities.ready) return;
Dispatcher.publish('ctx:'+entity);
return;
}
ctx.localize([entity], function(l) {
Dispatcher.publish('ctx:'+entity);
});
Entities[entity] = 1;
}
};
var initializeLocales = function(locales, rpath) {
rpath = rpath || '';
ctx.ready(function() {
Entities.ready = true;
for(var i in Entities.entities) {
Entities.registerEntity(Entities.entities[i]);
}
Dispatcher.publish('ctx:ready');
});
ctx.linkResource(function(locale) {
return rpath + '/locales/' + locale + '/strings.l20n';
});
ctx.registerLocales(locales.default, locales.locales);
ctx.requestLocales(locales.default);
};
var Entity = React.createClass({
propTypes: {
data: React.PropTypes.object,
entity: React.PropTypes.string,
dangerouslySetInnerHTML: React.PropTypes.bool,
},
getDefaultProps: function() {
return {
componentClass: 'span',
componentAttribute: ''
};
},
getInitialState: function() {
return {
entity: this.props.defaultValue || ''
};
},
handler: function() {
this.setState({
entity: ctx.getSync(this.props.entity, this.props.data)
});
},
componentDidMount: function() {
this.subscription = Dispatcher.subscribe('ctx:'+this.props.entity, this.handler);
Entities.registerEntity(this.props.entity);
if(Entities.ready) {
this.handler();
}
},
componentWillUnmount: function() {
Dispatcher.unsubscribe(this.subscription);
},
render: function() {
var ComponentClass = this.props.componentClass;
var componentAttribute = this.props.componentAttribute;
var props = {
...this.props,
data: null,
entity: null,
componentClass: null,
componentAttribute: null,
};
delete props.entity;
delete props.componentClass;
delete props.componentAttribute;
delete props.dangerouslySetInnerHTML;
if(ComponentClass && componentAttribute.length) {
props[componentAttribute] = this.state.entity;
return (
<ComponentClass {...props} />
);
}
if(ComponentClass === 'input') {
return (
<ComponentClass {...props} value={this.state.entity} />
);
}
if(this.props.dangerouslySetInnerHTML) {
return (
<ComponentClass {...props} dangerouslySetInnerHTML={{__html: this.state.entity}} />
);
}
return (
<ComponentClass {...props}>{this.state.entity}</ComponentClass>
);
}
});
module.exports = {
ctx: ctx,
initializeLocales: function(locales, rpath) {
initializeLocales(locales, rpath);
},
ready: function() {
if(Entities.ready) {
Dispatcher.publish('ctx:ready');
return;
}
},
changeLocale: function(locale) {
ctx.requestLocales(locale);
},
Entity: Entity
};
|
src/App.js | AzSiAz/LN-Reader | import React, { Component } from 'react';
import {
AppRegistry,
View,
AsyncStorage,
} from 'react-native';
import Info from 'react-native-device-info'
import codePush from 'react-native-code-push'
import Navigator from './screens'
import IntroComponent from './components/IntroComponent'
class LNReader extends Component {
state = {
showInfo: false,
isFetching: true
}
async componentWillMount() {
try {
const currentInfo = {
version: Info.getReadableVersion(),
deviceVersion: Info.getSystemVersion()
}
const storedInfo = await AsyncStorage.getItem('info')
const prevInfo = JSON.parse(storedInfo)
const showInfo = this.showInfo(prevInfo, currentInfo)
this.setState((prevState) => (
{...prevState, showInfo: showInfo, isFetching: false }
))
}
catch(e) {
this.setState((prevState) => (
{...prevState, showInfo: true, isFetching: false }
))
}
}
showInfo(prevInfo, currentInfo) {
return prevInfo.version === currentInfo.version ? false : true
}
hideIntro = async () => {
const currentInfo = {
version: Info.getReadableVersion(),
deviceVersion: Info.getSystemVersion()
}
await AsyncStorage.mergeItem('info', JSON.stringify(currentInfo))
this.setState((prevState) => (
{ ...prevState, showInfo: false }
))
}
render() {
const { showInfo, isFetching } = this.state
if (isFetching) return null
if (showInfo) return <IntroComponent hideIntro={this.hideIntro} />
return <Navigator />
}
}
const App = codePush(LNReader)
AppRegistry.registerComponent('LNReader', () => App)
|
frontend/components/Navbar.js | ParroApp/parro | import PropTypes from 'prop-types';
import React from 'react';
import Title from '../components/Title';
import { Redirect } from 'react-router-dom'
class Navbar extends React.Component {
constructor(props) {
super(props);
this.end = this.end.bind(this);
}
end() {
console.log('yoyoyoyoyoyo');
// <Redirect to="/end"/>
this.props.history.push('/end');
}
render() {
return(
<div>
<nav className="navbar">
<div className="navbar-brand">
<a className="navbar-item is-large">
<img src="/assets/img/parro.png" alt="Parro: speech practice program" href="https://github.com/coreymason/angelhack2017" width="150" height="28"/>
</a>
</div>
<div id="navMenuExample" className="navbar-menu">
<div className="navbar-end">
<div className="navbar-item">
<div className="field is-grouped">
<p className="control">
<a className="button is-danger"
onClick={this.end}
>
<span>End</span>
</a>
</p>
</div>
</div>
</div>
</div>
</nav>
</div>
)
}
};
export default Navbar;
|
app/containers/App/index.js | xavierouicar/react-boilerplate | /**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import injectTapEventPlugin from 'react-tap-event-plugin';
export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: React.PropTypes.node,
};
componentDidMount() {
injectTapEventPlugin();
}
render() {
return (
<MuiThemeProvider>
<div>
{React.Children.toArray(this.props.children)}
</div>
</MuiThemeProvider>
);
}
}
|
src/utils/Component.js | LnxPrgr3/Outlaw-CMS | import React from 'react';
import { OpenGraph } from './OpenGraph';
class Component extends React.Component {
static title() { return ''; };
static statusCode() { return 200; }
static loadData() {
return Promise.resolve(null);
}
withContext(callback) {
if(this.props.staticContext)
return callback(this.props.staticContext);
}
withOpenGraph(callback) {
return this.withContext(context => callback(new OpenGraph(context.og)));
}
constructor(props) {
super(props);
this.withContext = this.withContext.bind(this);
this.withContext((context) => context.title = this.constructor.title());
}
render() {
this.withContext((context) => context.statusCode = this.constructor.statusCode());
return null;
}
}
export default Component;
|
frontend/src/components/h5/Builder.js | sunlong/h5 | /**
* Created by sunlong on 2017/3/20.
*/
import React from 'react';
import moment from 'moment';
import Noty from 'noty';
import { connect } from 'react-redux';
import Panel from './panel/Panel';
import Header from './header/Header';
import store from '../../store';
import Template from './Template';
import PageContainer from './pageContainer/PageContainer';
import { addPage } from '../../actions/h5Actions';
import PageModal from './modal/PageModal';
import Sidebar from './sidebar/Sidebar';
import Fetch from '../../common/FetchIt';
import API_URL from '../../common/url';
import './builder.less';
class Builder extends React.Component {
componentDidMount = () => {
this.addPage();
};
addPage = () => {
store.dispatch(addPage(new PageModal()));
};
delPage = () => {
};
save = () => {
Fetch.post(API_URL.activity.save, { name: '', pages: JSON.stringify(this.props.pages), published: false }).then(() => {
new Noty({ text: '保存成功' }).show();
});
};
publish = () => {
Fetch.post(API_URL.activity.save, { name: '', pages: JSON.stringify(this.props.pages), published: true }).then(() => {
new Noty({ text: '发布成功' }).show();
});
};
render() {
return (
<div>
<Header onSave={this.save} onPublish={this.publish} />
<div className="builder">
<Template />
<PageContainer pages={this.props.pages} focusId={this.props.focus.id} />
<Panel focus={this.props.focus} />
<Sidebar pages={this.props.pages} />
</div>
</div>
);
}
}
const mapStateToProps = function (store) {
return {
pages: store.h5State.pages,
currentPage: store.h5State.currentPage,
focus: store.h5State.focus,
};
};
export default connect(mapStateToProps)(Builder);
|
src/example/Example.js | lsanwick/react-copy-to-clipboard | import React from 'react';
import CopyToClipboard from '..';
const App = React.createClass({
getInitialState() {
return {value: '', copied: false};
},
render() {
return (
<div>
<input value={this.state.value}
size={10}
onChange={({target: {value}}) => this.setState({value, copied: false})} />
<CopyToClipboard text={this.state.value}
onCopy={() => this.setState({copied: true})}>
<button>Copy to clipboard</button>
</CopyToClipboard>
{this.state.copied ? <span style={{color: 'red'}}>Copied.</span> : null}
<br />
<textarea style={{marginTop: '1em'}} cols="22" rows="3"></textarea>
</div>
);
}
});
React.render(<App />, document.body);
|
src/App.js | zhangmingkai4315/PPT-repo | import React, { Component } from 'react';
import SlidesManager from './components/SlidesManager'
export default class App extends Component {
render() {
return (
<SlidesManager/>
);
}
} |
src/js/components/icons/base/AccessAd.js | kylebyerly-hp/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}-access-ad`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'access-ad');
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 fillRule="evenodd" d="M12.3018676,10.102852 C13.6209278,10.102852 14.6837926,11.172641 14.6837926,12.484777 C14.6837926,13.8003751 13.6209278,14.8701641 12.3018676,14.8701641 L11.6786896,14.8701641 L11.6786896,10.102852 L12.3018676,10.102852 L12.3018676,10.102852 Z M12.5442146,16.9543484 C15.0126921,16.9543484 17.0207102,14.9497924 17.0207102,12.484777 C17.0207102,10.0093753 15.0334647,8.0082814 12.5649872,8.0082814 L12.5372904,8.0082814 L9.79876912,8.0082814 L9.79876912,16.9578105 L12.5442146,16.9578105 L12.5442146,16.9543484 Z M8.87336291,16.9595283 L6.91381417,16.9595283 L6.91381417,15.7754901 L3.63174315,15.7754901 L2.8770053,16.9595283 L0,16.9595283 L6.42565804,8.00653714 L8.87336291,8.00653714 L8.87336291,16.9595283 L8.87336291,16.9595283 Z M6.92591824,13.9098051 L4.8625065,13.9098051 L6.92591824,10.7039002 L6.92591824,13.9098051 L6.92591824,13.9098051 Z M22.2620257,8 L21.9781335,8 L21.44497,8 L21.1610778,8 C22.4039718,9.23596978 23.1206265,10.9289368 23.1206265,12.6876837 C23.1206265,14.2490909 22.5597663,15.7412561 21.5661435,16.9252944 L21.8500358,16.9252944 L22.3347298,16.9252944 L22.6220841,16.9252944 C23.5049197,15.7100972 24,14.2213941 24,12.6876837 C24,10.9600957 23.3698978,9.29828759 22.2620257,8 M20.0102192,8 L19.726327,8 L19.1931635,8 L18.9092713,8 C20.1521653,9.23596978 20.86882,10.9289368 20.86882,12.6876837 C20.86882,14.2490909 20.3079598,15.7412561 19.314337,16.9252944 L19.5982293,16.9252944 L20.0829233,16.9252944 L20.3633534,16.9252944 C21.2531132,15.7100972 21.7481935,14.2213941 21.7481935,12.6876837 C21.7481935,10.9600957 21.1180913,9.29828759 20.0102192,8 M17.7584421,8 L17.4745499,8 L16.9344623,8 L16.6574942,8 C17.9003882,9.23596978 18.6101188,10.9289368 18.6101188,12.6876837 C18.6101188,14.2490909 18.0492585,15.7412561 17.06256,16.9252944 L17.3464522,16.9252944 L17.8276841,16.9252944 L18.1115763,16.9252944 C19.0013361,15.7100972 19.4894922,14.2213941 19.4894922,12.6876837 C19.4894922,10.9600957 18.8663142,9.29828759 17.7584421,8"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'AccessAd';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
frontend/src/components/editor/attachments/uploader.js | 1905410/Misago | // jshint ignore:start
import React from 'react';
import moment from 'moment';
import misago from 'misago';
import ajax from 'misago/services/ajax';
import snackbar from 'misago/services/snackbar';
export default class extends React.Component {
onChange = (event) => {
const file = event.target.files[0];
if (!file) {
return;
}
let upload = {
id: null,
key: getRandomKey(),
progress: 0,
error: null,
filename: file.name
};
this.props.onAttachmentsChange([upload].concat(this.props.attachments));
const data = new FormData();
data.append('upload', file);
ajax.upload(misago.get('ATTACHMENTS_API'), data, (progress) => {
upload.progress = progress;
this.props.onAttachmentsChange(this.props.attachments.concat());
}).then((data) => {
data.uploaded_on = moment(data.uploaded_on);
Object.assign(upload, data);
this.props.onAttachmentsChange(this.props.attachments.concat());
}, (rejection) => {
if (rejection.status === 400) {
upload.error = rejection.detail;
this.props.onAttachmentsChange(this.props.attachments.concat());
} else {
snackbar.apiError(rejection);
}
});
};
render() {
return (
<input
id="editor-upload-field"
onChange={this.onChange}
type="file"
/>
);
}
};
export function getRandomKey() {
return 'upld-' + Math.round(new Date().getTime());
} |
app/jsx/grading/gradingStandardCollection.js | djbender/canvas-lms | /*
* Copyright (C) 2015 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import update from 'immutability-helper'
import GradingStandard from './gradingStandard'
import $ from 'jquery'
import I18n from 'i18n!external_toolsgradingStandardCollection'
import _ from 'underscore'
import 'jquery.instructure_misc_plugins'
class GradingStandardCollection extends React.Component {
state = {standards: null}
componentWillMount() {
$.getJSON(`${ENV.GRADING_STANDARDS_URL}.json`).done(this.gotStandards)
}
gotStandards = standards => {
let formattedStandards = $.extend(true, [], standards)
formattedStandards = _.map(formattedStandards, standard => {
standard.grading_standard.data = this.formatStandardData(standard.grading_standard.data)
return standard
})
this.setState({standards: formattedStandards})
}
formatStandardData = standardData =>
_.map(standardData, dataRow => [dataRow[0], this.roundToTwoDecimalPlaces(dataRow[1] * 100)])
addGradingStandard = () => {
const newStandard = {
editing: true,
justAdded: true,
grading_standard: {
permissions: {manage: true},
title: '',
data: this.formatStandardData(ENV.DEFAULT_GRADING_STANDARD_DATA),
id: -1
}
}
const newStandards = update(this.state.standards, {$unshift: [newStandard]})
this.setState({standards: newStandards})
}
getStandardById = id =>
_.find(this.state.standards, standard => standard.grading_standard.id === id)
standardNotCreated = gradingStandard => gradingStandard.id === -1
setEditingStatus = (id, setEditingStatusTo) => {
const newStandards = $.extend(true, [], this.state.standards)
const existingStandard = this.getStandardById(id)
const indexToEdit = this.state.standards.indexOf(existingStandard)
if (
setEditingStatusTo === false &&
this.standardNotCreated(existingStandard.grading_standard)
) {
newStandards.splice(indexToEdit, 1)
this.setState({standards: newStandards})
} else {
newStandards[indexToEdit].editing = setEditingStatusTo
this.setState({standards: newStandards})
}
}
anyStandardBeingEdited = () => !!_.find(this.state.standards, standard => standard.editing)
saveGradingStandard = standard => {
const newStandards = $.extend(true, [], this.state.standards)
const indexToUpdate = this.state.standards.indexOf(this.getStandardById(standard.id))
let type, url, data
standard.title = standard.title.trim()
if (this.standardNotCreated(standard)) {
if (standard.title === '') standard.title = 'New Grading Scheme'
type = 'POST'
url = ENV.GRADING_STANDARDS_URL
data = this.dataFormattedForCreate(standard)
} else {
type = 'PUT'
url = `${ENV.GRADING_STANDARDS_URL}/${standard.id}`
data = this.dataFormattedForUpdate(standard)
}
$.ajax({
type,
url,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
context: this
})
.success(function(updatedStandard) {
updatedStandard.grading_standard.data = this.formatStandardData(
updatedStandard.grading_standard.data
)
newStandards[indexToUpdate] = updatedStandard
this.setState({standards: newStandards}, () => {
$.flashMessage(I18n.t('Grading scheme saved'))
})
})
.error(function() {
newStandards[indexToUpdate].grading_standard.saving = false
this.setState({standards: newStandards}, () => {
$.flashError(I18n.t('There was a problem saving the grading scheme'))
})
})
}
dataFormattedForCreate = standard => {
const formattedData = {grading_standard: standard}
_.each(standard.data, (dataRow, i) => {
const name = dataRow[0]
const value = dataRow[1]
formattedData.grading_standard.data[i] = [
name.trim(),
this.roundToTwoDecimalPlaces(value) / 100
]
})
return formattedData
}
dataFormattedForUpdate = standard => {
const formattedData = {grading_standard: {title: standard.title, standard_data: {}}}
_.each(standard.data, (dataRow, i) => {
const name = dataRow[0]
const value = dataRow[1]
formattedData.grading_standard.standard_data[`scheme_${i}`] = {
name: name.trim(),
value: this.roundToTwoDecimalPlaces(value)
}
})
return formattedData
}
roundToTwoDecimalPlaces = number => Math.round(number * 100) / 100
deleteGradingStandard = (event, uniqueId) => {
const self = this,
$standard = $(event.target).parents('.grading_standard')
$standard.confirmDelete({
url: `${ENV.GRADING_STANDARDS_URL}/${uniqueId}`,
message: I18n.t('Are you sure you want to delete this grading scheme?'),
success() {
const indexToRemove = self.state.standards.indexOf(self.getStandardById(uniqueId))
const newStandards = update(self.state.standards, {$splice: [[indexToRemove, 1]]})
self.setState({standards: newStandards}, () => {
$.flashMessage(I18n.t('Grading scheme deleted'))
})
},
error() {
$.flashError(I18n.t('There was a problem deleting the grading scheme'))
}
})
}
hasAdminOrTeacherRole = () =>
_.intersection(ENV.current_user_roles, ['teacher', 'admin']).length > 0
getAddButtonCssClasses = () => {
let classes = 'Button pull-right add_standard_button'
if (!this.hasAdminOrTeacherRole() || this.anyStandardBeingEdited()) classes += ' disabled'
return classes
}
renderGradingStandards = () => {
if (!this.state.standards) {
return null
} else if (this.state.standards.length === 0) {
return <h3 ref="noSchemesMessage">{I18n.t('No grading schemes to display')}</h3>
}
return this.state.standards.map(function(s) {
return (
<GradingStandard
ref={`gradingStandard${s.grading_standard.id}`}
key={s.grading_standard.id}
uniqueId={s.grading_standard.id}
standard={s.grading_standard}
editing={!!s.editing}
permissions={s.grading_standard.permissions}
justAdded={!!s.justAdded}
onSetEditingStatus={this.setEditingStatus}
round={this.roundToTwoDecimalPlaces}
onDeleteGradingStandard={this.deleteGradingStandard}
othersEditing={!s.editing && this.anyStandardBeingEdited()}
onSaveGradingStandard={this.saveGradingStandard}
/>
)
}, this)
}
render() {
return (
<div>
<div className="pull-right">
<button
ref="addButton"
onClick={this.addGradingStandard}
className={this.getAddButtonCssClasses()}
>
<i className="icon-add" />
{I18n.t(' Add grading scheme')}
</button>
</div>
<div id="standards" className="content-box react_grading_standards">
{this.renderGradingStandards()}
</div>
</div>
)
}
}
export default GradingStandardCollection
|
src/components/orderInput/orderInput.js | beehive-spg/beehive-frontend | import React from 'react'
import { connect } from 'react-redux'
import { graphql } from 'react-apollo'
import Script from 'react-load-script'
import Geosuggest from 'react-geosuggest'
import { BounceLoader } from 'halogenium'
import LaddaButton, { S, EXPAND_RIGHT } from 'react-ladda'
import addOrder from 'graphql/mutations/addOrder.gql'
import ShopSelect from './shopSelect/shopSelect'
import addressLookup from 'utils/geocoding'
import 'react-geosuggest/module/geosuggest.css'
import 'ladda/dist/ladda.min.css'
import './orderInput.css'
@connect(store => {
return {
shops: store.shop.shops,
}
})
@graphql(addOrder)
export default class OrderInput extends React.Component {
constructor(props) {
super(props)
this.state = {
shop: { value: '', label: '' },
customer: {
address: '',
longitude: null,
latitude: null,
},
scriptLoaded: false,
typing: false,
orderLoading: false,
}
}
async componentDidMount() {
const location = await addressLookup(navigator.geolocation)
if (!this.state.typing) {
this.setState({
customer: {
address: location.address.formatted_address,
longitude: location.longitude,
latitude: location.latitude,
},
})
}
}
onSelect(e) {
let shop = e
if (shop === null) shop = { value: '', label: '' }
this.setState({ shop })
}
handleSubmit(e) {
e.preventDefault()
this.setState({
orderLoading: !this.state.orderLoading,
})
const order = {
shop: this.state.shop.value,
customer: this.state.customer,
}
this.props.mutate({ variables: { order } })
this.toggleOrderLoading()
}
toggleOrderLoading() {
setTimeout(() => {
this.setState({
orderLoading: !this.state.orderLoading,
})
}, 3000)
}
onFocus() {
if (!this.state.typing) {
this.setState({ typing: true })
}
}
onSuggestSelect(suggest) {
if (!suggest) {
this.setState({
customer: {
address: '',
longitude: null,
latitude: null,
},
})
return
}
this.setState({
customer: {
address: suggest.description,
longitude: suggest.location.lng,
latitude: suggest.location.lat,
},
})
}
handleScriptLoad() {
this.setState({ scriptLoaded: true })
}
getShopOptions() {
return this.props.shops
.map(shop => {
return shop.shops.map(buildingShop => {
return {
value: buildingShop.id,
label: `${buildingShop.name} - ${
shop.location.address
}`,
}
})
})
.flatten()
}
render() {
if (!this.state.scriptLoaded) {
const apiKey = process.env.REACT_APP_GOOGLE_API_KEY //eslint-disable-line
const apiUrl = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places`
return (
<Script
url={apiUrl}
onLoad={this.handleScriptLoad.bind(this)}
/>
)
}
const addressLoading = () => {
if (this.state.customer.address === '' && !this.state.typing) {
return (
<div className="loader">
<BounceLoader color="#26A65B" size="16px" />
</div>
)
}
return null
}
return (
<div className="orderInput">
<div className="heading">Order</div>
<hr />
<div className="container">
<form onSubmit={this.handleSubmit.bind(this)}>
<div className="fromInput">
From:
<ShopSelect
position="to"
shops={this.getShopOptions()}
selected={this.state.shop}
onSelect={this.onSelect.bind(this)}
/>
</div>
<div className="toInput">
To:
<div className="addressInput">
<Geosuggest
location={
new google.maps.LatLng( // eslint-disable-line
48.210033,
16.363449,
)
}
radius={20000}
placeholder="Enter address"
initialValue={this.state.customer.address}
onFocus={this.onFocus.bind(this)}
onSuggestSelect={this.onSuggestSelect.bind(
this,
)}
/>
{addressLoading()}
</div>
</div>
<div className="buttonInput">
<LaddaButton
data-size={S}
data-style={EXPAND_RIGHT}
loading={this.state.orderLoading}
onClick={this.handleSubmit.bind(this)}
data-spinner-size={30}
data-color="#eee"
data-spinner-color="#ddd"
data-spinner-lines={12}>
Order now
</LaddaButton>
</div>
</form>
</div>
</div>
)
}
}
|
examples/websdk-samples/LayerReactNativeSample/src/containers/ConversationListContainer.js | layerhq/layer-js-sampleapps | import React, { Component } from 'react';
import {
View,
Modal,
StyleSheet
} from 'react-native';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { QueryBuilder } from 'layer-websdk/index-react-native';
import { connectQuery } from 'layer-react';
import * as MessengerActions from '../actions/messenger';
import ConversationList from '../ui/ConversationList';
import ConversationListHeader from '../ui/ConversationListHeader';
import AnnouncementsList from '../ui/announcements/MessageList';
import UserListDialog from '../ui/UserListDialog'
/**
* Copy data from reducers into our properties
*/
function mapStateToProps({ app, announcementState, participantState, activeConversation }) {
return {
owner: app.owner,
ready: app.ready,
activeConversationId: activeConversation.activeConversationId,
showAnnouncements: announcementState.showAnnouncements,
participantState
};
}
/**
* Copy all actions into this.props.actions
*/
function mapDispatchToProps(dispatch) {
return { actions: bindActionCreators(MessengerActions, dispatch) };
}
/**
* Setup all of the Queries; will set the query results to be
* this.props.conversations, this.props.announcements, this.props.users.
* Message query is setup elsewhere.
*/
function getQueries() {
return {
conversations: QueryBuilder.conversations(),
announcements: QueryBuilder.announcements(),
users: QueryBuilder.identities(),
};
}
@connect(mapStateToProps, mapDispatchToProps)
@connectQuery({}, getQueries)
export default class ConversationListContainer extends Component {
componentWillReceiveProps(nextProps) {
if (nextProps.activeConversationId &&
nextProps.activeConversationId !== this.props.activeConversationId) {
this.props.navigator.push({
name: 'ActiveConversation'
});
}
}
/**
* Hide the Announcements Dialog
*/
hideAnnouncements = (event) => {
const { actions } = this.props;
const { hideAnnouncements } = actions;
hideAnnouncements();
}
/**
* Hide the Participants Dialog
*/
hideParticipants = (event) => {
const { actions } = this.props;
const { hideParticipants } = actions;
hideParticipants();
}
/**
* Render the Participants dialog.
*/
renderParticipantDialog() {
const { owner, users, participantState, actions } = this.props;
const selectedParticipants = participantState.participants;
return (
<div
onClick={this.hideParticipants}
className="participants-dialog dialog">
<div>
<UserListDialog
users={users.filter(user => user.id !== owner.id)}
selectedUsers={selectedParticipants}
onUserSelected={actions.addParticipant}
onUserUnselected={actions.removeParticipant}
onSave={actions.createConversation}/>
</div>
</div>
);
}
/**
* If we are ready, render the Messenger, else render a blank screen
*/
render() {
const {
owner,
users,
conversations,
announcements,
activeConversationId,
actions,
showAnnouncements,
participantState
} = this.props;
console.log('ConversationListContainer render', owner);
const { showParticipants, participants } = participantState;
if (this.props.ready) {
return (
<View style={styles.container}>
<ConversationListHeader
owner={owner}
unreadAnnouncements={Boolean(announcements.filter(item => item.isUnread).length)}
onShowAnnouncements={actions.showAnnouncements}
onShowParticipants={actions.showParticipants}
onTogglePresence={actions.togglePresence}/>
<ConversationList
conversations={conversations}
activeConversationId={activeConversationId}
onSelectConversation={actions.selectConversation}
onDeleteConversation={actions.deleteConversation}/>
<Modal
animationType={"slide"}
transparent={true}
visible={showAnnouncements}
>
<View style={styles.modalBackground}>
<AnnouncementsList
messages={announcements}
onMarkMessageRead={actions.markMessageRead}
onClose={this.hideAnnouncements}
/>
</View>
</Modal>
<Modal
animationType={"slide"}
transparent={true}
visible={showParticipants}
>
<View style={styles.modalBackground}>
<UserListDialog
users={users.filter(user => user.id !== owner.id)}
selectedUsers={participants}
onUserSelected={actions.addParticipant}
onUserUnselected={actions.removeParticipant}
onSave={actions.createConversation}
onClose={this.hideParticipants}
/>
</View>
</Modal>
</View>
)
} else {
return (
<View style={styles.container}>
</View>
)
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
modalBackground: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0.5)'
}
});
|
app/components/post_list/new_messages_divider.js | csduarte/mattermost-mobile | // Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import React from 'react';
import {StyleSheet, View} from 'react-native';
import FormattedText from 'app/components/formatted_text';
const style = StyleSheet.create({
container: {
alignItems: 'center',
flexDirection: 'row',
height: 28
},
textContainer: {
marginHorizontal: 15
},
line: {
flex: 1,
height: StyleSheet.hairlineWidth,
backgroundColor: '#f80'
},
text: {
fontSize: 14,
fontWeight: '600',
color: '#ffaf53'
}
});
function NewMessagesDivider(props) {
return (
<View style={[style.container, props.style]}>
<View style={style.line}/>
<View style={style.textContainer}>
<FormattedText
id='post_list.newMsg'
defaultMessage='New Messages'
style={style.text}
/>
</View>
<View style={style.line}/>
</View>
);
}
NewMessagesDivider.propTypes = {
style: View.propTypes.style
};
export default NewMessagesDivider;
|
www/src/components/Navbar.js | TaitoUnited/taito-cli | import React from 'react';
import styled from '@emotion/styled';
import { Link } from 'gatsby';
import { FaGithub } from 'react-icons/fa';
import { desktopOnly } from '../utils';
import theme from '../theme';
import Spacing from './Spacing';
import Search from './search';
const Navbar = () => {
const activeStyle = {
fontWeight: 500,
borderColor: theme.primary[500],
};
return (
<Nav>
<NavLinks>
<NavLink to="/">
<strong>Taito</strong> CLI
</NavLink>
<Spacing amount={64} />
<NavLink to="/docs" activeStyle={activeStyle} partiallyActive>
Docs
</NavLink>
<Spacing amount={32} />
<NavLink to="/tutorial" activeStyle={activeStyle} partiallyActive>
Tutorial
</NavLink>
<Spacing amount={32} />
<NavLink to="/plugins" activeStyle={activeStyle}>
Plugins
</NavLink>
<Spacing amount={32} />
<NavLink to="/templates" activeStyle={activeStyle}>
Templates
</NavLink>
<Spacing amount={32} />
<NavLink to="/extensions" activeStyle={activeStyle}>
Extensions
</NavLink>
<div style={{ flex: 1 }} />
<Search />
<Spacing />
<a
href="https://github.com/TaitoUnited/taito-cli"
target="__blank"
rel="noopener noreferrer"
>
<FaGithub color="#fff" size={24} />
</a>
</NavLinks>
</Nav>
);
};
const Nav = styled.nav`
position: fixed;
top: 0;
left: 0;
right: 0;
background-color: ${props => props.theme.primary[700]};
z-index: 1;
${desktopOnly}
`;
const NavLinks = styled.nav`
display: flex;
flex-direction: row;
align-items: center;
padding: 0px 16px;
`;
const NavLink = styled(Link)`
height: 50px;
display: flex;
justify-content: center;
align-items: center;
text-decoration: none;
color: #fff;
border-bottom: 4px solid ${props => props.theme.primary[700]};
position: relative;
&:hover {
border-bottom: 4px solid ${props => props.theme.primary[900]};
}
`;
export default Navbar;
|
app/jsx/external_apps/components/TextAreaInput.js | venturehive/canvas-lms | /*
* Copyright (C) 2014 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import I18n from 'i18n!external_tools'
import $ from 'jquery'
import React from 'react'
import PropTypes from 'prop-types'
import InputMixin from 'jsx/external_apps/mixins/InputMixin'
export default React.createClass({
displayName: 'TextAreaInput',
mixins: [InputMixin],
propTypes: {
defaultValue: PropTypes.string,
label: PropTypes.string,
id: PropTypes.string,
rows: PropTypes.number,
required: PropTypes.bool,
hintText: PropTypes.string,
errors: PropTypes.object
},
render() {
return (
<div className={this.getClassNames()}>
<label>
{this.props.label}
<textarea ref="input" rows={this.props.rows || 3} defaultValue={this.props.defaultValue}
className="form-control input-block-level"
placeholder={this.props.label} id={this.props.id}
required={this.props.required ? "required" : null}
onChange={this.handleChange}
aria-invalid={!!this.getErrorMessage()} />
{this.renderHint()}
</label>
</div>
)
}
});
|
node_modules/styled-components/src/models/StyleSheet.js | vinhtran19950804/procure_react | // @flow
import React from 'react'
import BrowserStyleSheet from './BrowserStyleSheet'
import ServerStyleSheet from './ServerStyleSheet'
export const SC_ATTR = 'data-styled-components'
export const LOCAL_ATTR = 'data-styled-components-is-local'
export const CONTEXT_KEY = '__styled-components-stylesheet__'
export interface Tag {
isLocal: boolean,
components: { [string]: Object },
isFull(): boolean,
addComponent(componentId: string): void,
inject(componentId: string, css: string, name: ?string): void,
toHTML(): string,
toReactElement(key: string): React.Element<*>,
clone(): Tag,
}
let instance = null
// eslint-disable-next-line no-use-before-define
export const clones: Array<StyleSheet> = []
export default class StyleSheet {
tagConstructor: (boolean) => Tag
tags: Array<Tag>
names: { [string]: boolean }
hashes: { [string]: string } = {}
deferredInjections: { [string]: string } = {}
componentTags: { [string]: Tag }
constructor(tagConstructor: (boolean) => Tag,
tags: Array<Tag> = [],
names: { [string]: boolean } = {},
) {
this.tagConstructor = tagConstructor
this.tags = tags
this.names = names
this.constructComponentTagMap()
}
constructComponentTagMap() {
this.componentTags = {}
this.tags.forEach(tag => {
Object.keys(tag.components).forEach(componentId => {
this.componentTags[componentId] = tag
})
})
}
/* Best level of caching—get the name from the hash straight away. */
getName(hash: any) {
return this.hashes[hash.toString()]
}
/* Second level of caching—if the name is already in the dom, don't
* inject anything and record the hash for getName next time. */
alreadyInjected(hash: any, name: string) {
if (!this.names[name]) return false
this.hashes[hash.toString()] = name
return true
}
/* Third type of caching—don't inject components' componentId twice. */
hasInjectedComponent(componentId: string) {
return !!this.componentTags[componentId]
}
deferredInject(componentId: string, isLocal: boolean, css: string) {
if (this === instance) {
clones.forEach(clone => {
clone.deferredInject(componentId, isLocal, css)
})
}
this.getOrCreateTag(componentId, isLocal)
this.deferredInjections[componentId] = css
}
inject(componentId: string, isLocal: boolean, css: string, hash: ?any, name: ?string) {
if (this === instance) {
clones.forEach(clone => {
clone.inject(componentId, isLocal, css)
})
}
const tag = this.getOrCreateTag(componentId, isLocal)
const deferredInjection = this.deferredInjections[componentId]
if (deferredInjection) {
tag.inject(componentId, deferredInjection)
delete this.deferredInjections[componentId]
}
tag.inject(componentId, css, name)
if (hash && name) {
this.hashes[hash.toString()] = name
}
}
toHTML() {
return this.tags.map(tag => tag.toHTML()).join('')
}
toReactElements() {
return this.tags.map((tag, i) => tag.toReactElement(`sc-${i}`))
}
getOrCreateTag(componentId: string, isLocal: boolean) {
const existingTag = this.componentTags[componentId]
if (existingTag) {
return existingTag
}
const lastTag = this.tags[this.tags.length - 1]
const componentTag = (!lastTag || lastTag.isFull() || lastTag.isLocal !== isLocal)
? this.createNewTag(isLocal)
: lastTag
this.componentTags[componentId] = componentTag
componentTag.addComponent(componentId)
return componentTag
}
createNewTag(isLocal: boolean) {
const newTag = this.tagConstructor(isLocal)
this.tags.push(newTag)
return newTag
}
static get instance() {
return instance || (instance = StyleSheet.create())
}
static reset(isServer: ?boolean) {
instance = StyleSheet.create(isServer)
}
/* We can make isServer totally implicit once Jest 20 drops and we
* can change environment on a per-test basis. */
static create(isServer: ?boolean = typeof document === 'undefined') {
return (isServer ? ServerStyleSheet : BrowserStyleSheet).create()
}
static clone(oldSheet: StyleSheet) {
const newSheet = new StyleSheet(
oldSheet.tagConstructor,
oldSheet.tags.map(tag => tag.clone()),
{ ...oldSheet.names },
)
newSheet.hashes = { ...oldSheet.hashes }
newSheet.deferredInjections = { ...oldSheet.deferredInjections }
clones.push(newSheet)
return newSheet
}
}
|
src/mobile/src/components/EmployeeCreate.js | douglascbarbosa/plankit | import React, { Component } from 'react';
import { Picker, Text } from 'react-native';
import { connect } from 'react-redux';
import { employeeUpdate, employeeCreate } from '../actions';
import {Card, CardSection, Input, Button } from './common';
class EmployeeCreat extends Component {
onButtonPress(){
const { name, phone, shift } = this.props;
this.props.employeeCreate({name, phone, shift: shift || 'Monday'});
}
render(){
return(
<Card>
<CardSection>
<Input
label="Name"
placeholder="Jane"
value={this.props.name}
onChangeText={ value => this.props.employeeUpdate({prop: 'name', value})}
/>
</CardSection>
<CardSection>
<Input
label="Phone"
placeholder="(55) 5555-5555"
value={this.props.phone}
onChangeText={ value => this.props.employeeUpdate({prop: 'phone', value})}
/>
</CardSection>
<CardSection>
<Text style={styles.pickerTextStyle}>Shift</Text>
<Picker
style={{flex:1}}
selectedValue={this.props.shift}
onValueChange={value => this.props.employeeUpdate({prop:'shift', value})}
>
<Picker.Item label="Monday" value="Monday" />
<Picker.Item label="Tuesday" value="Tuesday" />
<Picker.Item label="Wednesday" value="Wednesday" />
<Picker.Item label="Thursday" value="Thursday" />
<Picker.Item label="Friday" value="Friday" />
<Picker.Item label="Saturday" value="Saturday" />
<Picker.Item label="Sunday" value="Sunday" />
</Picker>
</CardSection>
<CardSection>
<Button onPress={this.onButtonPress.bind(this)}>
Create
</Button>
</CardSection>
</Card>
);
}
}
const styles ={
pickerTextStyle: {
fontSize: 18,
paddingLeft: 20
}
};
const mapStateToProps = (state) =>{
const { name, phone, shift } = state.employeeForm;
return { name, phone, shift };
}
export default connect(mapStateToProps, { employeeUpdate, employeeCreate })(EmployeeCreat);
|
App.js | munyrasirio/mss-chat | import React, { Component } from 'react';
import { StackNavigator } from 'react-navigation';
import { View, StatusBar } from 'react-native';
import Contacts from './src/page/Contacts';
import Chat from './src/page/Chat';
import Config from './src/page/Config';
const ROUTES = StackNavigator({
contacts: {
screen: Contacts
},
chat: {
screen: Chat
},
config: {
screen: Config
}
}, {
headerMode: 'none'
})
export default class App extends Component {
render() {
return (
<View style={{flex: 1}}>
<View style={{height: StatusBar.currentHeight, backgroundColor: 'black'}}/>
<ROUTES/>
</View>
)
}
}
/*this.props.navigation.state.params.contact*/ |
clients/packages/admin-client/src/mobilizations/widgets/__plugins__/form/components/__form__.js | nossas/bonde-client | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import CountUp from 'react-countup';
import { intlShape } from 'react-intl';
import classnames from 'classnames';
import { Error } from '../../../../../components/form-util';
import { isValidEmail } from '../../../../../utils/validation-helper';
import { FinishMessageCustom } from '../../../../../mobilizations/widgets/components';
import AnalyticsEvents from '../../../../../mobilizations/widgets/utils/analytics-events';
import { Button, Input, FormTellAFriend } from '../components';
class Form extends Component {
constructor(props, context) {
super(props, context);
this.state = {
hasMouseOver: false,
loading: false,
success: false,
errors: [],
};
}
componentWillReceiveProps() {
if (this.state.loading) {
this.setState({ loading: false, success: true });
}
}
fields() {
const { settings } = this.props.widget;
return settings && settings.fields ? settings.fields : [];
}
submit() {
if (!this.props.editable) {
const { asyncFormEntryCreate, mobilization, widget } = this.props;
const fieldsWithValue = widget.settings.fields.map((field) => ({
...field,
value: document.querySelector(`#input-${field.uid}`).value,
}));
const errors = this.validate(fieldsWithValue);
this.setState({ errors });
if (errors.length === 0) {
this.setState({ loading: true });
const formEntry = {
widget_id: widget.id,
fields: JSON.stringify(fieldsWithValue),
};
asyncFormEntryCreate({ mobilization, formEntry }).then(() => {
this.setState({ loading: false, success: true });
});
}
}
}
validate(fieldsWithValue) {
const errors = [];
fieldsWithValue.forEach((field) => {
if (field.required === 'true' && field.value === '') {
errors.push(`${field.label} não pode ficar em branco`);
} else if (
field.value !== '' &&
field.kind === 'email' &&
!isValidEmail(field.value)
) {
errors.push(`${field.label} inválido`);
}
});
return errors;
}
renderCallToAction() {
const {
configurable,
widget,
mobilization: { header_font: headerFont },
intl,
} = this.props;
const callToAction = (
widget.settings && widget.settings.call_to_action
? widget.settings.call_to_action
: intl.formatMessage({
id: 'form-widget.components--form.default.title-text',
defaultMessage: 'Clique para configurar seu formulário...',
})
).replace('\n', '<br/><br/>');
return configurable ? null : (
<h2
className="mt0 mb3 center white"
dangerouslySetInnerHTML={{ __html: callToAction }}
style={{ fontFamily: headerFont }}
/>
);
}
renderFields() {
const fields = this.fields();
return fields.map((field, index) => {
return (
<Input
{...this.props}
key={field.uid}
uid={field.uid}
onBlur={
Number(index) === 0
? AnalyticsEvents.formIsFilled.bind(AnalyticsEvents)
: () => {}
}
canMoveUp={index !== 0}
canMoveDown={index !== fields.length - 1}
initializeEditing={
this.props.hasNewField && index === fields.length - 1
}
field={field}
/>
);
});
}
renderButton() {
const { configurable, widget, intl } = this.props;
const { loading, success } = this.state;
if (!configurable) {
return (
<Button
{...this.props}
buttonText={
(widget.settings && widget.settings.button_text) ||
intl.formatMessage({
id: 'form-widget.components--form.default.button-text',
defaultMessage: 'Enviar',
})
}
handleClick={this.submit.bind(this)}
loading={loading}
success={success}
/>
);
}
}
renderCount() {
const {
widget: { settings },
} = this.props;
if (!this.props.configurable && settings && settings.count_text) {
const {
block: { scrollTopReached: startCounting },
widget: { form_entries_count: count },
mobilization: { body_font: bodyFont },
} = this.props;
return (
<div className="mt2 h3 center white" style={{ fontFamily: bodyFont }}>
<CountUp
start={0}
end={!isNaN(count) && startCounting ? Number(count) : 0}
duration={5}
/>
{settings.count_text}
</div>
);
}
}
renderErrors() {
const { errors } = this.state;
return (
errors.length > 0 && (
<div>
{errors.map((error) => (
<Error message={error} />
))}
</div>
)
);
}
renderShareButtons() {
const fields = this.fields();
let message = '';
fields.map((field) => {
if (field.kind === 'greetings') {
message = field.placeholder;
}
return message;
});
if (message === '') {
const { mobilization, widget } = this.props;
const {
settings: { finish_message_type: finishMessageType },
} = widget;
return finishMessageType === 'custom' ? (
<FinishMessageCustom widget={widget} />
) : (
<FormTellAFriend mobilization={mobilization} widget={widget} />
);
} else {
return <p className="center p2 bg-darken-3">{message}</p>;
}
}
renderForm() {
const {
editable,
configurable,
widget: { settings },
} = this.props;
const backgroundColor =
settings && settings.main_color
? settings.main_color
: 'rgba(0,0,0,0.25)';
return (
<div>
<div
className={classnames('rounded', {
'p3 relative': editable || !configurable,
})}
style={{ backgroundColor: !configurable ? backgroundColor : null }}
>
{this.renderCallToAction()}
{this.renderFields()}
{this.renderErrors()}
{this.renderButton()}
</div>
</div>
);
}
render() {
const {
mobilization: { header_font: headerFont },
} = this.props;
const { success } = this.state;
return (
<div className={`widget ${headerFont}-header`}>
{success ? this.renderShareButtons() : this.renderForm()}
{this.renderCount()}
</div>
);
}
}
Form.propTypes = {
mobilization: PropTypes.object.isRequired,
widget: PropTypes.shape({
settings: PropTypes.shape({
finish_message_type: PropTypes.string,
}).isRequired,
}).isRequired,
editable: PropTypes.bool,
configurable: PropTypes.bool,
hasNewField: PropTypes.bool,
intl: intlShape,
};
export default Form;
|
client/src/components/billing/checkout-form.js | WebTalentTop/newsfere-mern | import React, { Component } from 'react';
import CheckoutFields from './checkout-fields';
import { connect } from 'react-redux';
import * as actions from '../../actions/billing';
/* TODO:
* - Pass more information down with redux state (i.e., billing address initial val)
*/
class CheckoutForm extends Component {
constructor(props) {
super(props);
this.state = {
stripePublicKey: 'pk_test_XXXXXXXXXXXXXXXXXXXXXXXX',
cardNumber: '',
expMonth: '',
expYear: '',
cvc: '',
error: '',
};
}
componentWillMount() {
// Import Stripe.js
this.loadStripe();
}
loadStripe() {
// Check if Stripe is already loaded first
if (!document.getElementById('stripe-import')) {
const stripeJs = document.createElement('script');
stripeJs.id = 'stripe-import';
stripeJs.src = 'https://js.stripe.com/v2/';
stripeJs.type = 'text/javascript';
stripeJs.async = true;
document.body.appendChild(stripeJs);
}
}
handleFormChange(e) {
e.preventDefault();
switch (e.target.id) {
case 'cardNumber': return (this.setState({ cardNumber: e.target.value }));
case 'cvc': return (this.setState({ cvc: e.target.value }));
case 'expMonth': return (this.setState({ expMonth: e.target.value }));
case 'expYear': return (this.setState({ expYear: e.target.value }));
}
}
handleSubmit(e) {
e.preventDefault();
const that = this;
that.setState({ error: '' });
Stripe.setPublishableKey(this.state.stripePublicKey);
Stripe.card.createToken({
number: this.state.cardNumber,
cvc: this.state.cvc,
exp_month: this.state.expMonth,
exp_year: this.state.expYear,
}, (status, response) => {
if (response.error) {
that.setState({ error: response.error });
return;
}
// Action to save customer token and create charge
const plan = that.props.plan;
const stripeToken = response.id;
const lastFour = response.card.last4;
if (!plan) {
that.props.updateBilling(stripeToken);
} else {
that.props.createCustomer(stripeToken, plan, lastFour);
}
});
}
render() {
return (
<div className="checkout-form">
{this.state.error.message}
<CheckoutFields
handleChange={this.handleFormChange.bind(this)}
onSubmit={this.handleSubmit.bind(this)}
formState={this.state}
/>
</div>
);
}
}
export default connect(null, actions)(CheckoutForm);
|
src/components/project/project_slide.js | LeeLa-Jet/nick | import React, { Component } from 'react';
import classNames from 'classnames'
class ProjectSlide extends Component {
renderContent(){
let data = this.props.data;
let backgroundImage = `url(${data.bg})`;
if(data.id == 'main'){
return (
<div className={classNames(
"project_slide-wrapper main",
{ '-overlay': data.overlay ? data.overlay : '' }
)} style={{backgroundImage}}>
<div className="project_slide-content">
<h1 className="project_slide-title">{data.title}</h1>
</div>
</div>
);
}
if(data.id == 'text'){
return (
<div className={classNames(
"project_slide-wrapper text",
{ '-overlay': data.overlay ? data.overlay : '' }
)} style={{backgroundImage}}>
<div className="project_slide-content">
<p className="project_slide-text">{data.text}</p>
</div>
</div>
);
}
if(data.id == 'bg'){
return (
<div className="project_slide-wrapper bg" style={{backgroundImage}}>
</div>
);
}
if(data.id == 'imgs'){
let backgroundImage1 = `url(${data.img1})`;
let backgroundImage2 = `url(${data.img2})`;
return (
<div className={classNames("project_slide-images",
{ '-overlay': data.overlay ? data.overlay : '' }
)} >
<div className="project_slide-content">
<h1 className="project_slide-title">{data.title}</h1>
</div>
<img className="project_slide-img" style={{backgroundImage : backgroundImage1}} />
<img className="project_slide-img" style={{backgroundImage : backgroundImage2}}/>
</div>
);
}
if(data.id == 'finish'){
return (
<div className="project_slide-finish" style={{backgroundImage}}>
<div className="project_slide-finish-content">
<a href={`/projects/${data.link}`} className="project_slide-finish-next">{data.title}</a>
<div className="project_slide-finish-note">
<p className="project_slide-finish-scroll">следующая работа</p>
</div>
</div>
</div>
);
}
}
render(){
return (
<div className="project_slide">
{this.renderContent()}
{/* <div className="project_slide-content">
<h1 className="project_slide-title">Transmedia HSE</h1>
<p className="project_slide-text">Полная разработка логотипа + фирменный стиль.</p>
<p className="project_slide-text">Совершенно новая программа магистратуры факультета коммуникаций,медиа и дизайна крупнейшего университета России — Высшей Школы Экономики (НИУ ВШЭ). «Трансмедийное производство в цифровых индустриях» — первое в России digital-образование с дипломом государтсвенного образца. Программа разработана для студентов и молодых специалистов, желающих развивать навыки в области дизайна, технологий, программирования, управления цифровыми проектами.</p>
</div>
<div className="project_slide-images">
<img className="project_slide-img" style={{ backgroundImage: 'url(/static/img/1.jpg)' }} />
<img className="project_slide-img" style={{ backgroundImage: 'url(/static/img/bg.jpg)' }}/>
</div>
<div className="project_slide-finish">
<div className="project_slide-finish-content">
<a href="" className="project_slide-finish-next">Novaja</a>
<div className="project_slide-finish-note">
<p className="project_slide-finish-scroll">следующая работа</p>
</div>
</div>
</div> */}
</div>
);
}
}
export default ProjectSlide;
|
src/components/ManageUsers/ManageUsers.js | RegOpz/RegOpzWebApp | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { dispatch } from 'redux';
import Breadcrumbs from 'react-breadcrumbs';
import {
actionFetchUsers
} from '../../actions/UsersAction';
require('./ManageUsers.css');
class ManageUsersComponent extends Component {
constructor(props) {
super(props);
this.state = {
filterText: null
}
this.dataSource = null;
this.fetchFlag = true;
this.iconClass = {
"Contact Number": "fa fa-phone",
"Email": "fa fa-paper-plane",
"Role": "fa fa-user",
"Status": "fa fa-power-off",
"Active": "green",
"Unspecified":" red"
};
this.renderUsers = this.renderUsers.bind(this);
this.handleFilter = this.handleFilter.bind(this);
}
componentWillMount() {
this.props.fetchUsers();
}
componentWillUpdate() {
if (this.fetchFlag) {
this.dataSource = null;
this.props.fetchUsers();
}
}
componentDidUpdate(){
this.fetchFlag = ! this.fetchFlag;
}
componentDidMount() {
document.title = "RegOpz Dashboard | Manage Users";
}
handleFilter(){
if(typeof this.props.userDetails != 'undefined' && this.props.userDetails ){
let userData = this.props.userDetails;
const { filterText } = this.state;
if (filterText != null) {
let matchText = RegExp(`(${filterText.toString().toLowerCase().replace(/[,+&\:\ ]$/,'').replace(/[,+&\:\ ]/g,'|')})`,'i');
console.log("matchText",matchText);
userData = userData.filter(element =>
element.name.match(matchText) ||
element.username.match(matchText)||
element.info.some(info => info.value.match(matchText))
);
}
this.dataSource = userData;
}
}
render() {
return(
<div>
{ this.renderDisplay() }
</div>
);
}
renderDisplay() {
// this.dataSource = this.props.userDetails;
this.handleFilter();
// console.log("renderDisplay",this.dataSource,this.props.userDetails)
if(this.dataSource == null) {
return(
<h4>Loading...</h4>
);
}
return(
<div className="row ">
<div className="col-md-12">
<div className="x_panel">
<div className="x_title">
<h2>User Management <small>Manage users</small></h2>
<div className="clearfix"></div>
</div>
<div className="x_content">
<div className="input-group">
<input
id="filter"
className="form-control col-md-9 col-sm-9 col-xs-12"
placeholder="Enter Filter Text"
value={this.state.filterText}
onChange={(event) => {
this.setState({ filterText: event.target.value });
}}
/>
<span className="input-group-addon">
<i className="fa fa-filter"></i>
</span>
</div>
<div className="row">
<div className="col-md-12 col-sm-12 col-xs-12"></div>
<div classNam="clearfix"></div>
{ this.renderUsers(this.dataSource) }
</div>
</div>
</div>
</div>
</div>
);
}
renderUsers(dataSource) {
let user_list = [];
dataSource.map((item, index) => {
console.log(index, "From ManageUsers", item);
user_list.push(
<div key={index} className="col-md-4 col-sm-4 col-xs-12 profile_details">
<div className="well profile_view">
<div className="col-sm-12">
<h4 className="brief">
<i>User Details</i>
</h4>
<div className="left col-xs-7">
<h2>
<span className="small dark"><strong>{ item.name }</strong></span>
</h2>
<ul className="list-unstyled">
{
item.info.map((obj, index) => (
<li key={index}>
<i className={this.iconClass[obj.title] + " " + this.iconClass[obj.value]}></i>
<strong> {obj.title}:</strong> { obj.value }
</li>
))
}
</ul>
</div>
<div className="right col-xs-5 text-center">
<img src="images/user.png" alt="" className="img-circle img-responsive" />
</div>
</div>
<div className="col-xs-12 bottom text-center">
<div className="col-xs-12 col-sm-6 emphasis"></div>
<div className="col-xs-12 col-sm-6 emphasis">
<Link className="btn btn-primary btn-xs" to={`/dashboard/manage-users/edit-user?userId=${item.username}`}>
<i className="fa fa-user"></i> View Profile
</Link>
</div>
</div>
</div>
</div>
);
});
return(user_list);
}
}
function mapStateToProps(state) {
console.log("On map state of Manage Users:", state);
return {
userDetails: state.user_details.data
};
}
const mapDispatchToProps = (dispatch) => {
return {
fetchUsers: () => {
dispatch(actionFetchUsers());
}
};
};
const VisibleManageUsers = connect(
mapStateToProps,
mapDispatchToProps
)(ManageUsersComponent);
export default VisibleManageUsers;
|
src/components/label/index.js | KleeGroup/focus-components | // Dependencies
import PropTypes from 'prop-types';
import React from 'react';
import { translate } from 'focus-core/translation';
function Label({ name, text, isRequired }) {
const content = text || name;
return (
<label data-focus='label' htmlFor={name}>
{translate(content) + (isRequired ? '\u202f*' : '')}
</label>
);
}
Label.propTypes = {
name: PropTypes.string.isRequired,
text: PropTypes.string,
isRequired: PropTypes.bool
};
Label.defaultProps = {
isRequired: false,
text: ''
};
export default Label; |
src/react/index.js | threepointone/redux-devtools | import React from 'react';
import createDevTools from '../createDevTools';
export const DevTools = createDevTools(React);
export { default as LogMonitor } from './LogMonitor';
export { default as DebugPanel } from './DebugPanel';
|
src/components/Home/Home.js | lucaslencinas/react-node-socketio-template | import React from 'react';
import PropTypes from 'prop-types';
import styles from './Home.css';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = { name: '' };
this.handleEnter = this.handleEnter.bind(this);
this.handleNameChange = this.handleNameChange.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
}
handleEnter() {
this.props.onEnter({
user: { name: this.state.name.trim() }
});
}
handleNameChange(e) {
this.setState({ name: e.target.value });
}
handleKeyPress(e) {
if (e.key === 'Enter' && this.state.name.trim()) {
this.handleEnter();
}
}
render() {
const { name } = this.state;
const { homeTitle } = this.props;
return (
<div className={styles.home}>
<div className={styles.title}>
<h3>{homeTitle}</h3>
</div>
<div className={styles.form}>
<input
placeholder="Name"
className={styles.inputName}
value={name}
onChange={this.handleNameChange}
onKeyPress={this.handleKeyPress}
autoFocus
/>
<button
type="button"
className={styles.button}
onClick={this.handleEnter}
>
Enter
</button>
</div>
</div>
);
}
}
Home.propTypes = {
homeTitle: PropTypes.string,
onEnter: PropTypes.func
};
export default Home;
|
app/jsx/shared/hooks/useLocalStorage.js | djbender/canvas-lms | /*
* Copyright (C) 2020 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
function useLocalStorage(key, initialValue) {
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = React.useState(() => {
const item = window.localStorage.getItem(key)
try {
// Get from local storage by key
// Parse stored json or if none return initialValue
return item ? JSON.parse(item) : initialValue
} catch (error) {
return item
}
})
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
const setValue = value => {
try {
// Allow value to be a function so we have same API as useState
const valueToStore = value instanceof Function ? value(storedValue) : value
// Save state
setStoredValue(valueToStore)
// Save to local storage
window.localStorage.setItem(key, JSON.stringify(valueToStore))
} catch (error) {
// A more advanced implementation would handle the error case
// We'll just swallow it.
}
}
return [storedValue, setValue]
}
export default useLocalStorage
|
app/javascript/mastodon/components/domain.js | sylph-sin-tyaku/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import IconButton from './icon_button';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unhide {domain}' },
});
export default @injectIntl
class Account extends ImmutablePureComponent {
static propTypes = {
domain: PropTypes.string,
onUnblockDomain: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleDomainUnblock = () => {
this.props.onUnblockDomain(this.props.domain);
}
render () {
const { domain, intl } = this.props;
return (
<div className='domain'>
<div className='domain__wrapper'>
<span className='domain__domain-name'>
<strong>{domain}</strong>
</span>
<div className='domain__buttons'>
<IconButton active icon='unlock' title={intl.formatMessage(messages.unblockDomain, { domain })} onClick={this.handleDomainUnblock} />
</div>
</div>
</div>
);
}
}
|
src/components/InputSection.js | Ibrasau/socketChatExample | import React, { Component } from 'react';
import { Row, Form, Input, Button } from 'antd';
import { compose, pure, withState, withHandlers } from 'recompose';
import PropTypes from 'prop-types';
import moment from 'moment';
const InputSection = ({
messageInput,
setMessageInput,
submitHandler,
username,
}) => (
<Row className="input-section" type="flex" align="bottom">
<Form className="message-form" onSubmit={submitHandler}>
<Form.Item className="message-input" required>
<Input
type="text"
addonBefore="Your message:"
placeholder="Muffins"
value={messageInput}
onChange={e => setMessageInput(e.target.value)}
/>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
Send
</Button>
</Form.Item>
</Form>
</Row>
);
InputSection.propTypes = {
username: PropTypes.string,
setMessageInput: PropTypes.func.isRequired,
};
InputSection.defaultProps = {
username: 'Anonymous',
};
export default compose(
pure,
withState('messageInput', 'setMessageInput', ''),
withState('error', 'setError', ''),
withHandlers({
submitHandler: ({
socket,
username,
messageInput,
setMessageInput,
setError,
}) => e => {
e.preventDefault();
if (messageInput.trim()) {
socket.emit('send:message', {
value: messageInput,
date: moment(),
username,
});
setMessageInput('');
} else setError('Error! Your message is empty!');
},
})
)(InputSection);
|
src/svg-icons/image/hdr-strong.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageHdrStrong = (props) => (
<SvgIcon {...props}>
<path d="M17 6c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zM5 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>
</SvgIcon>
);
ImageHdrStrong = pure(ImageHdrStrong);
ImageHdrStrong.displayName = 'ImageHdrStrong';
ImageHdrStrong.muiName = 'SvgIcon';
export default ImageHdrStrong;
|
src/utils/CustomPropTypes.js | mengmenglv/react-bootstrap | import React from 'react';
import warning from 'react/lib/warning';
import childrenToArray from './childrenToArray';
const ANONYMOUS = '<<anonymous>>';
/**
* Create chain-able isRequired validator
*
* Largely copied directly from:
* https://github.com/facebook/react/blob/0.11-stable/src/core/ReactPropTypes.js#L94
*/
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName) {
componentName = componentName || ANONYMOUS;
if (props[propName] == null) {
if (isRequired) {
return new Error(
`Required prop '${propName}' was not specified in '${componentName}'.`
);
}
} else {
return validate(props, propName, componentName);
}
}
let chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function errMsg(props, propName, componentName, msgContinuation) {
return `Invalid prop '${propName}' of value '${props[propName]}'` +
` supplied to '${componentName}'${msgContinuation}`;
}
function createMountableChecker() {
function validate(props, propName, componentName) {
if (typeof props[propName] !== 'object' ||
typeof props[propName].render !== 'function' && props[propName].nodeType !== 1) {
return new Error(
errMsg(props, propName, componentName,
', expected a DOM element or an object that has a `render` method')
);
}
}
return createChainableTypeChecker(validate);
}
function createKeyOfChecker(obj) {
function validate(props, propName, componentName) {
let propValue = props[propName];
if (!obj.hasOwnProperty(propValue)) {
let valuesString = JSON.stringify(Object.keys(obj));
return new Error(
errMsg(props, propName, componentName, `, expected one of ${valuesString}.`)
);
}
}
return createChainableTypeChecker(validate);
}
function createSinglePropFromChecker(arrOfProps) {
function validate(props, propName) {
const usedPropCount = arrOfProps
.map(listedProp => props[listedProp])
.reduce((acc, curr) => acc + (curr !== undefined ? 1 : 0), 0);
if (usedPropCount > 1) {
const [first, ...others] = arrOfProps;
const message = `${others.join(', ')} and ${first}`;
return new Error(
`Invalid prop '${propName}', only one of the following ` +
`may be provided: ${message}`
);
}
}
return validate;
}
function all(propTypes) {
if (propTypes === undefined) {
throw new Error('No validations provided');
}
if (!(propTypes instanceof Array)) {
throw new Error('Invalid argument must be an array');
}
if (propTypes.length === 0) {
throw new Error('No validations provided');
}
return function(props, propName, componentName) {
for (let i = 0; i < propTypes.length; i++) {
let result = propTypes[i](props, propName, componentName);
if (result !== undefined && result !== null) {
return result;
}
}
};
}
function createElementTypeChecker() {
function validate(props, propName, componentName) {
let errBeginning = errMsg(props, propName, componentName,
'. Expected an Element `type`');
if (typeof props[propName] !== 'function') {
if (React.isValidElement(props[propName])) {
return new Error(errBeginning + ', not an actual Element');
}
if (typeof props[propName] !== 'string') {
return new Error(errBeginning +
' such as a tag name or return value of React.createClass(...)');
}
}
}
return createChainableTypeChecker(validate);
}
export default {
deprecated(propType, explanation) {
return function(props, propName, componentName) {
if (props[propName] != null) {
warning(false, `"${propName}" property of "${componentName}" has been deprecated.\n${explanation}`);
}
return propType(props, propName, componentName);
};
},
isRequiredForA11y(propType) {
return function(props, propName, componentName) {
if (props[propName] == null) {
return new Error(
'The prop `' + propName + '` is required to make ' + componentName + ' accessible ' +
'for users using assistive technologies such as screen readers `'
);
}
return propType(props, propName, componentName);
};
},
requiredRoles(...roles) {
return createChainableTypeChecker(
function requiredRolesValidator(props, propName, component) {
let missing;
let children = childrenToArray(props.children);
let inRole = (role, child) => role === child.props.bsRole;
roles.every(role => {
if (!children.some(child => inRole(role, child))) {
missing = role;
return false;
}
return true;
});
if (missing) {
return new Error(`(children) ${component} - Missing a required child with bsRole: ${missing}. ` +
`${component} must have at least one child of each of the following bsRoles: ${roles.join(', ')}`);
}
});
},
exclusiveRoles(...roles) {
return createChainableTypeChecker(
function exclusiveRolesValidator(props, propName, component) {
let children = childrenToArray(props.children);
let duplicate;
roles.every(role => {
let childrenWithRole = children.filter(child => child.props.bsRole === role);
if (childrenWithRole.length > 1) {
duplicate = role;
return false;
}
return true;
});
if (duplicate) {
return new Error(
`(children) ${component} - Duplicate children detected of bsRole: ${duplicate}. ` +
`Only one child each allowed with the following bsRoles: ${roles.join(', ')}`);
}
});
},
/**
* Checks whether a prop provides a DOM element
*
* The element can be provided in two forms:
* - Directly passed
* - Or passed an object that has a `render` method
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
mountable: createMountableChecker(),
/**
* Checks whether a prop provides a type of element.
*
* The type of element can be provided in two forms:
* - tag name (string)
* - a return value of React.createClass(...)
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
elementType: createElementTypeChecker(),
/**
* Checks whether a prop matches a key of an associated object
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
keyOf: createKeyOfChecker,
/**
* Checks if only one of the listed properties is in use. An error is given
* if multiple have a value
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
singlePropFrom: createSinglePropFromChecker,
all
};
|
ui/src/index.js | jliddev/pgBrowse | import React from 'react';
import ReactDOM from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import App from './App';
import './index.css';
injectTapEventPlugin();
window.ReactDOM = ReactDOM;
window.React = React;
ReactDOM.render(
<MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>
<App />
</MuiThemeProvider>,
document.getElementById('root')
);
|
src/modules/Auth/RequireLoggedIn.js | hdngr/mantenuto | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { populateUser } from 'modules/user/redux';
export class RequireLoggedInComponent extends Component {
static propTypes = {
tryingAuth: PropTypes.bool.isRequired,
authenticated: PropTypes.bool.isRequired,
triedAuth: PropTypes.bool.isRequired,
children: PropTypes.node.isRequired,
push: PropTypes.func.isRequired
}
componentWillReceiveProps(nextProps) {
if (nextProps.tryingAuth || nextProps.authenticated) {
return;
}
if (nextProps.triedAuth) {
return this.props.push('/login');
}
}
render() {
if (this.props.authenticated) {
return <div>{ this.props.children }</div>
}
if (this.props.tryingAuth) {
// change to spinner
return <h1>Loading...</h1>;
}
if (this.props.triedAuth) {
return null;
}
}
}
const mapStateToProps = (state) => {
const { tryingAuth, triedAuth } = state.auth;
const authenticated = !!state.auth.user;
return {
tryingAuth,
triedAuth,
authenticated
}
}
export default connect(mapStateToProps, { push, populateUser })(RequireLoggedInComponent);
|
src/components/LoadingCirclePop/LoadingCirclePop.js | k2data/k2-react-components | import React from 'react'
import logo from './logo.png'
const LoadingCirclePop = () => (
<div className='loading--ripple-container'>
<div className='img'>
<img src={logo} />
</div>
<svg width='182px' height='182px' xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 100 100' preserveAspectRatio='xMidYMid'
className='loading--ripple'>
<rect x='0' y='0' width='100' height='100' fill='none' className='bk' />
<g>
<circle cx='50' cy='50' r='40' stroke='#dddddd' fill='none'
strokeWidth='2' strokeLinecap='round' className='circle-1' />
</g>
<g>
<circle cx='50' cy='50' r='40' stroke='#dddddd' fill='none'
strokeWidth='2' strokeLinecap='round' className='circle-2' />
</g>
</svg>
<div className='loading' />
</div>
)
export default LoadingCirclePop
|
src/components/Accounts/ChargeFeeFine/ItemLookup.js | folio-org/ui-users | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import {
Button,
Row,
Col,
Modal,
MultiColumnList,
} from '@folio/stripes/components';
class ItemLookup extends React.Component {
static propTypes = {
open: PropTypes.bool,
items: PropTypes.arrayOf(PropTypes.object),
onClose: PropTypes.func.isRequired,
onChangeItem: PropTypes.func.isRequired,
}
constructor(props) {
super(props);
this.onRowClick = this.onRowClick.bind(this);
this.state = {
selectedRow: {},
};
}
onRowClick(e, row) {
this.setState({
selectedRow: row,
});
}
onConfirm = () => {
const {
onChangeItem,
onClose,
} = this.props;
const { selectedRow } = this.state;
onChangeItem(selectedRow);
onClose();
}
render() {
const {
onClose,
items = [],
} = this.props;
return (
<Modal
open={this.props.open}
label={<FormattedMessage id="ui-users.charge.itemLookup.modalLabel" />}
onClose={this.props.onClose}
size="medium"
dismissible
>
<Row>
<Col xs>
<MultiColumnList
contentData={items}
onRowClick={this.onRowClick}
visibleColumns={['barcode', 'title']}
/>
</Col>
</Row>
<Row>
<Col xs>
<Button
onClick={this.onConfirm}
disabled={!this.state.selectedRow.id}
>
<FormattedMessage id="ui-users.charge.itemLookup.confirm" />
</Button>
<Button
onClick={onClose}
>
<FormattedMessage id="ui-users.charge.itemLookup.cancel" />
</Button>
</Col>
</Row>
</Modal>
);
}
}
export default ItemLookup;
|
src/svg-icons/device/graphic-eq.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceGraphicEq = (props) => (
<SvgIcon {...props}>
<path d="M7 18h2V6H7v12zm4 4h2V2h-2v20zm-8-8h2v-4H3v4zm12 4h2V6h-2v12zm4-8v4h2v-4h-2z"/>
</SvgIcon>
);
DeviceGraphicEq = pure(DeviceGraphicEq);
DeviceGraphicEq.displayName = 'DeviceGraphicEq';
DeviceGraphicEq.muiName = 'SvgIcon';
export default DeviceGraphicEq;
|
example4/js/components/7ListView.js | hbarve1/react-native-examples | import React, { Component } from 'react';
import { View, Text, ListView, Image } from 'react-native';
export default class ListViewExample extends Component {
// Initialize the hardcoded data
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows([
'John', 'Joel', 'James', 'Jimmy', 'Jackson', 'Jillian', 'Julie', 'Devin'
])
};
}
render() {
return (
<View style={{flex: 1, paddingTop: 22}}>
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) => <Text style={{fontSize: 50}}>{rowData}</Text>}
/>
</View>
);
}
}
|
src/components/footer.js | itzsaga/slack-list | import React from 'react'
const Footer = () => (
<footer className="footer">
<div className="container">
<div className="content has-text-centered">
<p>
<strong>Slack List</strong>
<br /> The source code is available as open source under the terms of
the{' '}
<a href="https://github.com/itzsaga/slack-list/blob/master/LICENSE">
MIT License
</a>
.<br /> The website content is licensed{' '}
<a href="http://creativecommons.org/licenses/by-nc-sa/4.0/">
CC BY-NC-SA 4.0
</a>
.
</p>
</div>
</div>
</footer>
)
export default Footer
|
src/interface/icons/Mastery.js | anom0ly/WoWAnalyzer | import React from 'react';
const icon = (props) => (
<svg
xmlns="http://www.w3.org/2000/svg"
version="1.1"
viewBox="16 16 32 32"
className="icon"
{...props}
>
<path d="M46.934,26.287c-1.107,0-2.004,0.885-2.004,1.976c0,0.31,0.079,0.599,0.208,0.861l-6.74,4.691 l-0.387-8.422c1.064-0.048,1.914-0.906,1.914-1.967c0-1.091-0.898-1.976-2.005-1.976c-1.107,0-2.004,0.885-2.004,1.976 c0,0.732,0.408,1.364,1.008,1.705l-4.812,8.237l-4.812-8.237c0.6-0.341,1.008-0.973,1.008-1.705c0-1.091-0.897-1.976-2.004-1.976 c-1.107,0-2.004,0.885-2.004,1.976c0,1.061,0.85,1.919,1.914,1.967l-0.387,8.422l-6.74-4.691c0.129-0.261,0.208-0.551,0.208-0.861 c0-1.092-0.897-1.976-2.005-1.976c-1.107,0-2.004,0.885-2.004,1.976c0,1.091,0.897,1.976,2.004,1.976 c0.298,0,0.578-0.068,0.832-0.183l5.048,13.236c2.178-0.849,5.377-1.385,8.943-1.385c3.566,0,6.764,0.536,8.942,1.385l5.048-13.236 c0.254,0.115,0.534,0.183,0.832,0.183c1.107,0,2.005-0.885,2.005-1.976C48.939,27.172,48.041,26.287,46.934,26.287z" />
</svg>
);
export default icon;
|
web/components/pages/NewGame.fixture.js | skidding/flatris | // @flow
import React from 'react';
import { FlatrisReduxMock } from '../../mocks/ReduxMock';
import { SocketProviderMock } from '../../mocks/SocketProviderMock';
import NewGame from './NewGame';
// NOTE: An authenticated fixture for NewGame does not exist because it would
// automatically redirect to /join page
export default {
ready: (
<FlatrisReduxMock initialState={{ jsReady: true }}>
<SocketProviderMock>
<NewGame />
</SocketProviderMock>
</FlatrisReduxMock>
),
'loading js': (
<FlatrisReduxMock initialState={{ jsReady: false }}>
<SocketProviderMock>
<NewGame />
</SocketProviderMock>
</FlatrisReduxMock>
),
};
|
teletobit/src/containers/routes/ErrorRoute.js | edenpark/teletobit | import React, { Component } from 'react';
import UhOh, {
LeftColumn,
CenterColumn,
RightColumn,
} from 'components/UhOh';
import { Header, Icon } from 'semantic-ui-react'
class ErrorRoute extends Component {
render() {
return(
<UhOh>
<LeftColumn/>
<CenterColumn>
<div className="error-wrapper">
<Header as='h1' icon textAlign='center'>
<Icon name='warning' circular />
<Header.Content>
404
</Header.Content>
<Header.Subheader>
존재하지 않는 페이지입니다
</Header.Subheader>
</Header>
</div>
</CenterColumn>
<RightColumn/>
</UhOh>
);
}
}
export default ErrorRoute;
|
packages/icons/src/md/image/PhotoLibrary.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdPhotoLibrary(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M44 32c0 2.21-1.79 4-4 4H16c-2.21 0-4-1.79-4-4V8c0-2.21 1.79-4 4-4h24c2.21 0 4 1.79 4 4v24zm-22-8l-6 8h24l-8-10-5.94 7.42L22 24zM4 12v28c0 2.21 1.79 4 4 4h28v-4H8V12H4z" />
</IconBase>
);
}
export default MdPhotoLibrary;
|
src/parser/paladin/protection/modules/spells/azeritetraits/InspiringVanguard.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import Analyzer from 'parser/core/Analyzer';
import TraitStatisticBox from 'interface/others/TraitStatisticBox';
import { calculateAzeriteEffects } from 'common/stats';
import { formatNumber, formatPercentage } from 'common/format';
import GrandCrusader from '../../core/GrandCrusader';
import SpellUsable from '../../features/SpellUsable';
function inspiringVanguardStrength(combatant) {
if(!combatant.hasTrait(SPELLS.INSPIRING_VANGUARD.id)) {
return 0;
}
const traits = combatant.traitsBySpellId[SPELLS.INSPIRING_VANGUARD.id];
return traits.reduce((sum, ilvl) => sum + calculateAzeriteEffects(SPELLS.INSPIRING_VANGUARD.id, ilvl)[0], 0);
}
// TODO: figure out how to get the stats to the stat tracker without
// crashing the whole thing.
//
// something is causing a dependency look via SpellUsable
export const INSPIRING_VANGUARD_STATS = {
strength: inspiringVanguardStrength,
};
class InspiringVanguard extends Analyzer {
static dependencies = {
spellUsable: SpellUsable,
gc: GrandCrusader,
};
_strength = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTrait(SPELLS.INSPIRING_VANGUARD.id);
if(!this.active) {
return;
}
this._strength = inspiringVanguardStrength(this.selectedCombatant);
}
get avgStrength() {
return this._strength * this.buffUptimePct;
}
get buffUptimePct() {
return this.selectedCombatant.getBuffUptime(SPELLS.INSPIRING_VANGUARD_BUFF.id) / this.owner.fightDuration;
}
on_toPlayer_applybuff(event) {
this._handleBuff(event);
}
on_toPlayer_refreshbuff(event) {
this._handleBuff(event);
}
_handleBuff(event) {
if(event.ability.guid !== SPELLS.INSPIRING_VANGUARD_BUFF.id) {
return;
}
this.gc.triggerExactReset(this.spellUsable, event);
}
statistic() {
return (
<TraitStatisticBox
trait={SPELLS.INSPIRING_VANGUARD.id}
value={`${formatNumber(this.avgStrength)} Avg. Strength`}
tooltip={<>Inspiring Vanguard was up for <strong>{formatPercentage(this.buffUptimePct)}%</strong> of the fight.</>}
/>
);
}
}
export default InspiringVanguard;
|
client/src/index.js | Jeff-Tian/jeey | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './semantic-ui/dist/semantic.min.css';
import './index.css';
import {Router, Route, browserHistory} from 'react-router';
import JeeyReader from './modules/jeey/jeey-reader.js';
ReactDOM.render((
<Router history={browserHistory}>
<Route path="/" component={App}/>
<Route path="/:id" component={JeeyReader}/>
</Router>
), document.getElementById('root')); |
src/components/ChatApp/ChatApp.react.js | isuruAb/chat.susi.ai | import MessageSection from './MessageSection/MessageSection.react';
import React, { Component } from 'react';
import './ChatApp.css';
import history from '../../history';
export default class ChatApp extends Component {
componentDidMount() {
document.title = 'SUSI.AI Chat - Open Source Artificial Intelligence';
// force an update if the URL changes
history.listen(() => this.forceUpdate());
}
render() {
return (
<div className='chatapp'>
<MessageSection {...this.props}/>
</div>
);
}
};
|
src/components/about-page/AboutPage.js | CodeDraken/IdeaZone | import React from 'react';
import {Link} from 'react-router';
import ideaBulb from './../../../public/img/ideaBulb.jpg';
// static about / info page
const AboutPage = () => {
return (
<div className="container">
<Link to='/'>
<i className="fa fa-arrow-circle-left fa-3x" aria-hidden="true" title="home page"></i>
</Link>
<h1 className="text-center">About IdeaZone</h1>
<div className="row">
<div className="col-xs-12 col-sm-10 col-sm-offset-1">
<img className="img--center img-thumbnail img__idea" src={ideaBulb} alt="ideaBulb" />
<h3 className="text-center">All great projects start with an idea! So we're here to help you find an idea.</h3>
<h4 className="text-center">Take a look through some of the ideas or add an idea of your own to help others.</h4>
<br/>
<p className="text-center">IdeaZone was created by <em>Evan</em> and <em>Anisa</em> using a React framework with Sass and Bootstrap, while collaborating through Cloud9 and GitHub</p>
</div>
</div>
</div>
);
}
export default AboutPage; |
dist/es/index.js | mberneti/react-datepicker2 | import momentJalaali from 'moment-jalaali';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import TetherComponent from 'react-tether';
import classnames from 'classnames';
import onClickOutside from 'react-onclickoutside';
import range from 'lodash.range';
import Trigger from 'rc-trigger';
import ReactDom from 'react-dom';
function styleInject(css, ref) {
if ( ref === void 0 ) ref = {};
var insertAt = ref.insertAt;
if (!css || typeof document === 'undefined') { return; }
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
if (insertAt === 'top') {
if (head.firstChild) {
head.insertBefore(style, head.firstChild);
} else {
head.appendChild(style);
}
} else {
head.appendChild(style);
}
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
}
var css_248z = ".calendarContainer{position:relative;border-radius:4px;-webkit-box-shadow:0 3px 15px rgba(0,0,0,.2);box-shadow:0 3px 15px rgba(0,0,0,.2);width:320px;margin:auto;text-align:center;padding:15px;background-color:#fff}.calendarContainer *{-webkit-box-sizing:border-box;box-sizing:border-box}.calendarContainer .dayPickerContainer:after,.calendarContainer .daysOfWeek:after,.calendarContainer .monthsList:after{content:'';display:block;clear:both}.datepicker-input{-webkit-box-sizing:border-box;box-sizing:border-box}.calendarContainer .heading{height:auto;font-weight:700;margin-bottom:10px}.calendarContainer .heading>button{background:0 0;margin:5px 0;border:none;text-align:center;line-height:30px;width:36px;height:32px;cursor:pointer}.calendarContainer .heading>button:hover{background-color:#f2f2f2}.calendarContainer .heading svg{width:10px;fill:#777}.calendarContainer .heading .next,.calendarContainer .heading .prev{width:42px;height:42px;border-radius:50%;margin:0}.calendarContainer .heading .prev{float:right}.calendarContainer .heading .next{float:left}.calendarContainer .heading .title{height:auto;border-radius:4px;width:auto;margin:0 5px;border:1px solid #f7f7f7;text-align:center;display:inline-block;font-weight:400;padding:4px 15px 5px 15px;line-height:1.5;font-size:1.2em;max-height:none}.jalaali.calendarContainer .heading .title{padding:4px 15px 7px 15px}.calendarContainer .dayWrapper{float:left;width:14.28571429%;margin-top:5px;position:relative}.calendarContainer .dayWrapper button{border:none;background:0 0;outline:0;width:100%;cursor:pointer;width:40px;height:40px;border-radius:50%;font-size:1.1em;padding:0;line-height:1.5;padding:0 0 1px 0}.jalaali.calendarContainer .dayWrapper button{padding:0 0 1px 0}.calendarContainer .dayWrapper:not(.selected) button:hover{background-color:#d6f1ff}.calendarContainer .dayWrapper button[disabled]{color:#aaa;cursor:not-allowed;background-color:#ebebeb}.calendarContainer .dayWrapper button.selected{background-color:#337ab7;color:#fff}.calendarContainer .dayWrapper:not(.currentMonth) button{opacity:.5}.calendarContainer .daysOfWeek{margin-bottom:5px;padding-bottom:5px;display:-webkit-box;display:-ms-flexbox;display:flex;width:100%;color:#919191}.calendarContainer .daysOfWeek>div{-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1;-webkit-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between;width:42px}.calendarContainer .monthsList{clear:both;width:100%}.calendarContainer .monthsList button{width:33.33333332%;height:25%;float:right;border:1px solid #f9f9f9;outline:0;font-size:1em;background:#fff;padding:10px 0;cursor:pointer}.calendarContainer .monthsList button:hover{background:#eee;cursor:pointer}.calendarContainer .yearsList{clear:both;width:100%;max-height:200px;overflow-y:scroll}.calendarContainer .yearsList button{width:20%;height:25%;float:right;border:1px solid #f9f9f9;outline:0;font-size:1em;background:#fff;padding:10px 0;cursor:pointer}.calendarContainer .yearsList button:hover{background:#eee;cursor:pointer}.calendarContainer .selected button,.calendarContainer .selected button:active,.calendarContainer .selected button:focus,.calendarContainer .selected button:hover :not([disabled]){background-color:#4285f4;color:#fff}.calendarContainer.jalaali{direction:rtl}.calendarContainer.jalaali .dayWrapper{float:right}.time-picker-container{margin-bottom:10}.time-picker-container>.time-label{float:left;line-height:30px;width:50%;text-align:center}.time-picker-container>.time-picker-panel{float:right;width:50%}.time-picker-container.jalaali>.time-label{float:right}.time-picker-container.jalaali>.time-picker-panel{float:left}.rc-time-picker{border-radius:4px;display:inline-block;-webkit-box-sizing:border-box;box-sizing:border-box;width:110px;border:1px solid #f7f7f7;font-size:1.2em}.rc-time-picker *{-webkit-box-sizing:border-box;box-sizing:border-box}.rc-time-picker-input{margin:4px 0;padding:0 15px 1px 15px;direction:ltr;text-align:center;width:100%;position:relative;display:inline-block;cursor:pointer;font-size:1em;line-height:1.5;border:none;background-image:none;background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.jalaali.calendarContainer .rc-time-picker-input{padding:0 15px 3px 15px}.rc-time-picker-input:focus{-webkit-box-shadow:none;box-shadow:none;border:none;background-color:#f2f2f2}.rc-time-picker:hover{background-color:#f2f2f2}.rc-time-picker-panel{z-index:2001;width:170px;position:absolute;-webkit-box-sizing:border-box;box-sizing:border-box}.rc-time-picker-panel *{-webkit-box-sizing:border-box;box-sizing:border-box}.rc-time-picker-panel-inner{display:inline-block;position:relative;outline:0;list-style:none;font-size:12px;text-align:left;background-color:#fff;border-radius:3px;-webkit-box-shadow:0 1px 5px #ccc;box-shadow:0 1px 5px #ccc;background-clip:padding-box;border:1px solid #ccc;line-height:1.5}.rc-time-picker-panel-input{margin:0;padding:0;width:100%;cursor:default;line-height:1.5;outline:0;border:1px solid transparent;padding:4px 0;font-size:1.4em;text-align:center;font-family:inherit}.rc-time-picker-panel-input,.rc-time-picker-panel-input:hover{-webkit-box-shadow:none;box-shadow:none;border:none}.rc-time-picker-panel-input-wrap{-webkit-box-sizing:border-box;box-sizing:border-box;position:relative;padding:6px;border-bottom:1px solid #e9e9e9}.rc-time-picker-panel-input-invalid{border-color:red}.rc-time-picker-panel-clear-btn{position:absolute;right:6px;cursor:pointer;overflow:hidden;width:20px;height:20px;text-align:center;line-height:20px;top:6px;margin:0}.rc-time-picker-panel-clear-btn:after{content:'x';font-size:12px;color:#aaa;display:inline-block;line-height:1;width:20px;-webkit-transition:color .3s ease;transition:color .3s ease}.rc-time-picker-panel-clear-btn:hover:after{color:#666}.rc-time-picker-panel-select{float:left;font-size:12px;border:1px solid #e9e9e9;border-width:0 1px;margin-left:-1px;-webkit-box-sizing:border-box;box-sizing:border-box;width:56px;overflow:hidden;position:relative}.rc-time-picker-panel-select-active{overflow-y:auto}.rc-time-picker-panel-select:first-child{border-left:0;margin-left:0}.rc-time-picker-panel-select:last-child{border-right:0}.rc-time-picker-panel-select ul{list-style:none;-webkit-box-sizing:border-box;box-sizing:border-box;margin:0;padding:0;width:100%;max-height:144px;overflow-x:hidden;overflow-y:scroll}.rc-time-picker-panel-select li{list-style:none;-webkit-box-sizing:content-box;box-sizing:content-box;margin:0;padding:0 0 0 16px;width:100%;height:24px;line-height:24px;text-align:left;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.rc-time-picker-panel-select li:hover{background:#edfaff}li.rc-time-picker-panel-select-option-selected{background:#edfaff;color:#2db7f5}li.rc-time-picker-panel-select-option-disabled{color:#bfbfbf}li.rc-time-picker-panel-select-option-disabled:hover{background:0 0;cursor:not-allowed}.tether-element.tether-element-attached-top.tether-element-attached-center.tether-target-attached-bottom.tether-target-attached-center.tether-enabled{z-index:2000}.calendarContainer *,.datepicker-input{font-family:inherit}.today button{border:3px solid #4285f4!important}.jalaali.calendarContainer .selectToday{padding:4px 0 6px 0}.calendarButton{display:block;width:100%;background:#4285f4;color:#fff;outline:0;border-radius:5px;border:0;cursor:pointer;padding:5px 0 7px 0;-webkit-transition:.2s all ease-in-out;transition:.2s all ease-in-out;-webkit-transition-property:background;transition-property:background}.calendarButton:hover{background:#1266f1}.toggleButton{margin-bottom:1rem}.selectToday{margin-top:1rem}.highLightDot-container{text-align:center;bottom:0;width:100%;position:absolute;cursor:pointer;direction:ltr}.highLightDot-container .highLightDot{border:1px solid #fff;display:inline-block;width:7px;height:7px;border-radius:50%}.highLightDot-container .highLightDot:not(:first-child){margin-left:2px}.disabled{cursor:not-allowed}button[disabled],button[disabled]:hover{color:#aaa;cursor:not-allowed;background-color:#ebebeb}";
styleInject(css_248z);
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var classCallCheck = _classCallCheck;
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
var createClass = _createClass;
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var assertThisInitialized = _assertThisInitialized;
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var setPrototypeOf = createCommonjsModule(function (module) {
function _setPrototypeOf(o, p) {
module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
module.exports = _setPrototypeOf;
});
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) setPrototypeOf(subClass, superClass);
}
var inherits = _inherits;
var _typeof_1 = createCommonjsModule(function (module) {
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
module.exports = _typeof = function _typeof(obj) {
return typeof obj;
};
} else {
module.exports = _typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
module.exports = _typeof;
});
function _possibleConstructorReturn(self, call) {
if (call && (_typeof_1(call) === "object" || typeof call === "function")) {
return call;
}
return assertThisInitialized(self);
}
var possibleConstructorReturn = _possibleConstructorReturn;
var getPrototypeOf = createCommonjsModule(function (module) {
function _getPrototypeOf(o) {
module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
module.exports = _getPrototypeOf;
});
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var defineProperty = _defineProperty;
var latinToPersianMap = ['۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹', '۰'];
var latinNumbers = [/1/g, /2/g, /3/g, /4/g, /5/g, /6/g, /7/g, /8/g, /9/g, /0/g];
function prepareNumber(input) {
var string;
if (typeof input === 'number') {
string = input.toString();
} else if (typeof input === 'undefined') {
string = '';
} else {
string = input;
}
return string;
}
function latinToPersian(string) {
var result = string;
for (var index = 0; index < 10; index++) {
result = result.replace(latinNumbers[index], latinToPersianMap[index]);
}
return result;
}
function persianNumber(input) {
return latinToPersian(prepareNumber(input));
}
var leftArrow = {
__html: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 314.5 314.5" style="enable-background:new 0 0 314.5 314.5;" xml:space="preserve"><g><path class="arrow-icon" d="M125,157.5l116-116c10-10,10-24,0-34s-25-10-35,0l-133,133c-5,5-7,10-7,17s2,12,7,17l133,133c5,5,11,7,17,7s13-2,18-7c10-10,10-24,0-34L125,157.5z"/></g></svg>'
};
var rightArrow = {
__html: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 315.5 315.5" style="enable-background:new 0 0 315.5 315.5;" xml:space="preserve"><g><path class="arrow-icon" d="M242,141L109,8c-5-5-12-8-18-8S79,3,74,8c-10,10-10,24,0,34l116,116L74,274c-10,10-10,24,0,34s25,10,35,0l133-133c5-5,7-11,7-17C249,151,247,146,242,141z"/></g></svg>'
};
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
var Heading = /*#__PURE__*/function (_Component) {
inherits(Heading, _Component);
var _super = _createSuper(Heading);
function Heading() {
classCallCheck(this, Heading);
return _super.apply(this, arguments);
}
createClass(Heading, [{
key: "handleMonthClick",
value: function handleMonthClick(event) {
var setCalendarMode = this.context.setCalendarMode;
event.preventDefault();
setCalendarMode('monthSelector');
}
}, {
key: "render",
value: function render() {
var _this$context = this.context,
nextMonth = _this$context.nextMonth,
prevMonth = _this$context.prevMonth;
var _this$props = this.props,
month = _this$props.month,
styles = _this$props.styles;
return /*#__PURE__*/React.createElement("div", {
className: styles.heading
}, /*#__PURE__*/React.createElement("button", {
className: styles.title,
onClick: this.handleMonthClick.bind(this)
}, this.props.isGregorian ? month.locale('en').format('MMMM YYYY') : persianNumber(month.locale('fa').format('jMMMM jYYYY'))), this.props.timePicker, !this.props.isGregorian && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("button", {
type: "button",
title: "\u0645\u0627\u0647 \u0642\u0628\u0644",
className: styles.prev,
onClick: prevMonth,
dangerouslySetInnerHTML: rightArrow
}), /*#__PURE__*/React.createElement("button", {
type: "button",
title: "\u0645\u0627\u0647 \u0628\u0639\u062F",
className: styles.next,
onClick: nextMonth,
dangerouslySetInnerHTML: leftArrow
})), this.props.isGregorian && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("button", {
type: "button",
title: "previous month",
className: styles.next,
onClick: prevMonth,
dangerouslySetInnerHTML: leftArrow
}), /*#__PURE__*/React.createElement("button", {
type: "button",
title: "next month",
className: styles.prev,
onClick: nextMonth,
dangerouslySetInnerHTML: rightArrow
})));
}
}]);
return Heading;
}(Component);
defineProperty(Heading, "propTypes", {
month: PropTypes.object.isRequired,
isGregorian: PropTypes.bool
});
defineProperty(Heading, "contextTypes", {
styles: PropTypes.object,
nextMonth: PropTypes.func.isRequired,
prevMonth: PropTypes.func.isRequired,
setCalendarMode: PropTypes.func.isRequired
});
function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function () { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
var dayOfWeekNamesJalaali = ['ش', 'ی', 'د', 'س', 'چ', 'پ', 'ج'];
var dayOfWeekNamesGregorian = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
var DaysOfWeek = /*#__PURE__*/function (_Component) {
inherits(DaysOfWeek, _Component);
var _super = _createSuper$1(DaysOfWeek);
function DaysOfWeek() {
classCallCheck(this, DaysOfWeek);
return _super.apply(this, arguments);
}
createClass(DaysOfWeek, [{
key: "render",
value: function render() {
var _this$props = this.props,
styles = _this$props.styles,
isGregorian = _this$props.isGregorian;
var dayOfWeekNames = isGregorian ? dayOfWeekNamesGregorian : dayOfWeekNamesJalaali;
return /*#__PURE__*/React.createElement("div", {
className: styles.daysOfWeek
}, dayOfWeekNames.map(function (name, key) {
return /*#__PURE__*/React.createElement("div", {
key: key
}, name);
}));
}
}]);
return DaysOfWeek;
}(Component);
defineProperty(DaysOfWeek, "propTypes", {
styles: PropTypes.object,
isGregorian: PropTypes.bool
});
function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function () { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
var MonthsViewHeading = /*#__PURE__*/function (_Component) {
inherits(MonthsViewHeading, _Component);
var _super = _createSuper$2(MonthsViewHeading);
function MonthsViewHeading() {
classCallCheck(this, MonthsViewHeading);
return _super.apply(this, arguments);
}
createClass(MonthsViewHeading, [{
key: "handleYearClick",
value: function handleYearClick(event) {
var setCalendarMode = this.context.setCalendarMode;
event.preventDefault();
setCalendarMode('yearSelector');
}
}, {
key: "render",
value: function render() {
var _this$props = this.props,
year = _this$props.year,
styles = _this$props.styles,
type = _this$props.type,
isGregorian = _this$props.isGregorian,
disableYearSelector = _this$props.disableYearSelector;
var yearFormat = isGregorian ? 'YYYY' : 'jYYYY';
return /*#__PURE__*/React.createElement("div", {
className: styles.heading
}, /*#__PURE__*/React.createElement("button", {
disabled: disableYearSelector,
className: styles.title,
onClick: this.handleYearClick.bind(this)
}, isGregorian ? year.format(yearFormat) : persianNumber(year.format(yearFormat))), /*#__PURE__*/React.createElement("button", {
type: "button",
title: isGregorian ? 'next year' : 'سال قبل',
style: styles.navButton,
className: styles.prev,
onClick: isGregorian ? this.props.onNextYear : this.props.onPrevYear,
dangerouslySetInnerHTML: rightArrow
}), /*#__PURE__*/React.createElement("button", {
type: "button",
title: isGregorian ? 'previous year' : 'سال بعد',
style: styles.navButton,
className: styles.next,
onClick: isGregorian ? this.props.onPrevYear : this.props.onNextYear,
dangerouslySetInnerHTML: leftArrow
}));
}
}]);
return MonthsViewHeading;
}(Component);
defineProperty(MonthsViewHeading, "propTypes", {
year: PropTypes.object.isRequired,
onNextYear: PropTypes.func.isRequired,
onPrevYear: PropTypes.func.isRequired,
isGregorian: PropTypes.bool,
disableYearSelector: PropTypes.bool
});
defineProperty(MonthsViewHeading, "contextTypes", {
styles: PropTypes.object,
type: PropTypes.number,
setCalendarMode: PropTypes.func.isRequired
});
function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function () { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
var monthsJalaali = ['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'];
var monthsGregorian = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var MonthSelector = /*#__PURE__*/function (_Component) {
inherits(MonthSelector, _Component);
var _super = _createSuper$3(MonthSelector);
function MonthSelector() {
var _this;
classCallCheck(this, MonthSelector);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty(assertThisInitialized(_this), "state", {
year: _this.props.selectedMonth
});
return _this;
}
createClass(MonthSelector, [{
key: "nextYear",
value: function nextYear() {
this.setState({
year: this.state.year.clone().add(1, 'year')
});
}
}, {
key: "prevYear",
value: function prevYear() {
this.setState({
year: this.state.year.clone().subtract(1, 'year')
});
}
}, {
key: "handleClick",
value: function handleClick(key) {
var _this$context = this.context,
setMonth = _this$context.setMonth,
setCalendarMode = _this$context.setCalendarMode;
var isGregorian = this.props.isGregorian;
var monthYearFormat = isGregorian ? 'M-YYYY' : 'jM-jYYYY';
setMonth(momentJalaali(key, monthYearFormat));
setCalendarMode('days');
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var year = this.state.year;
var _this$props = this.props,
selectedMonth = _this$props.selectedMonth,
styles = _this$props.styles,
isGregorian = _this$props.isGregorian,
disableYearSelector = _this$props.disableYearSelector;
var yearFormat = isGregorian ? 'YYYY' : 'jYYYY';
var monthYearFormat = isGregorian ? 'M-YYYY' : 'jM-jYYYY';
var months = isGregorian ? monthsGregorian : monthsJalaali;
return /*#__PURE__*/React.createElement("div", {
className: "month-selector"
}, /*#__PURE__*/React.createElement(MonthsViewHeading, {
isGregorian: isGregorian,
styles: styles,
year: year,
onNextYear: this.nextYear.bind(this),
onPrevYear: this.prevYear.bind(this),
disableYearSelector: disableYearSelector
}), /*#__PURE__*/React.createElement("div", {
className: styles.monthsList
}, months.map(function (name, key) {
var buttonFingerprint = "".concat(key + 1, "-").concat(year.format(yearFormat));
var selectedMonthFingerprint = selectedMonth.format(monthYearFormat);
var isCurrent = selectedMonthFingerprint === buttonFingerprint;
var className = classnames(styles.monthWrapper, defineProperty({}, styles.selected, isCurrent));
return /*#__PURE__*/React.createElement("div", {
key: key,
className: className
}, /*#__PURE__*/React.createElement("button", {
onClick: _this2.handleClick.bind(_this2, buttonFingerprint)
}, name));
})));
}
}]);
return MonthSelector;
}(Component);
defineProperty(MonthSelector, "propTypes", {
styles: PropTypes.object,
selectedMonth: PropTypes.object.isRequired,
isGregorian: PropTypes.bool,
disableYearSelector: PropTypes.bool
});
defineProperty(MonthSelector, "contextTypes", {
setCalendarMode: PropTypes.func.isRequired,
setMonth: PropTypes.func.isRequired
});
function _createSuper$4(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$4(); return function () { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$4() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
var yearsJalaali = range(momentJalaali(new Date()).jYear() + 100, 1300);
var yearsGregorian = range(momentJalaali(new Date()).year() + 100, 1920);
var YearSelector = /*#__PURE__*/function (_Component) {
inherits(YearSelector, _Component);
var _super = _createSuper$4(YearSelector);
function YearSelector(props) {
var _this;
classCallCheck(this, YearSelector);
_this = _super.call(this, props);
defineProperty(assertThisInitialized(_this), "state", {
year: _this.props.selectedYear,
month: _this.props.selectedMonth
});
defineProperty(assertThisInitialized(_this), "getOffsetTop", function (element) {
var offsetTop = 0;
while (element) {
console.log(element.scrollTop);
offsetTop += element.offsetTop;
element = element.offsetParent;
}
return offsetTop;
});
defineProperty(assertThisInitialized(_this), "scrollToCurrentYearPositionRef", function () {
var marginTop = 160;
_this.yearsContainerRef.current.scrollTo({
top: _this.getOffsetTop(_this.currentYearPositionRef.current) - marginTop,
behavior: 'smooth' // optional
});
});
_this.currentYearPositionRef = React.createRef();
_this.yearsContainerRef = React.createRef();
return _this;
}
createClass(YearSelector, [{
key: "componentDidMount",
value: function componentDidMount() {
this.scrollToCurrentYearPositionRef();
}
}, {
key: "nextYear",
value: function nextYear() {
this.setState({
year: this.state.year.clone().add(1, 'year')
});
}
}, {
key: "prevYear",
value: function prevYear() {
this.setState({
year: this.state.year.clone().subtract(1, 'year')
});
}
}, {
key: "handleClick",
value: function handleClick(key) {
var _this$context = this.context,
setMonth = _this$context.setMonth,
setCalendarMode = _this$context.setCalendarMode;
var isGregorian = this.props.isGregorian;
var monthYearFormat = isGregorian ? 'M-YYYY' : 'jM-jYYYY';
setMonth(momentJalaali(key, monthYearFormat));
setCalendarMode('days');
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var _this$state = this.state,
year = _this$state.year,
month = _this$state.month;
var _this$props = this.props,
styles = _this$props.styles,
isGregorian = _this$props.isGregorian;
var yearFormat = isGregorian ? 'YYYY' : 'jYYYY';
var monthFormat = isGregorian ? 'M' : 'jM';
var years = isGregorian ? yearsGregorian : yearsJalaali;
return /*#__PURE__*/React.createElement("div", {
className: "month-selector"
}, /*#__PURE__*/React.createElement(MonthsViewHeading, {
isGregorian: isGregorian,
styles: styles,
year: year,
onNextYear: this.nextYear.bind(this),
onPrevYear: this.prevYear.bind(this)
}), /*#__PURE__*/React.createElement("div", {
ref: this.yearsContainerRef,
className: styles.yearsList
}, years.map(function (yearItem, key) {
var buttonFingerprint = "".concat(month.format(monthFormat), "-").concat(years[key]);
var isCurrent = Number(year.format(yearFormat)) === years[key];
var isCurrentYearPosition = Number(year.format(yearFormat)) === years[key];
var currentYearClass = classnames(styles.yearWrapper, defineProperty({}, styles.selected, isCurrent));
return /*#__PURE__*/React.createElement("div", {
key: key,
className: currentYearClass
}, /*#__PURE__*/React.createElement("button", {
ref: isCurrentYearPosition && _this2.currentYearPositionRef,
onClick: _this2.handleClick.bind(_this2, buttonFingerprint)
}, yearItem));
})));
}
}]);
return YearSelector;
}(Component);
defineProperty(YearSelector, "propTypes", {
styles: PropTypes.object,
selectedYear: PropTypes.object.isRequired,
selectedMonth: PropTypes.object.isRequired,
isGregorian: PropTypes.bool
});
defineProperty(YearSelector, "contextTypes", {
setCalendarMode: PropTypes.func.isRequired,
setMonth: PropTypes.func.isRequired
});
var _extends_1 = createCommonjsModule(function (module) {
function _extends() {
module.exports = _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
module.exports = _extends;
});
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var objectWithoutPropertiesLoose = _objectWithoutPropertiesLoose;
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
var objectWithoutProperties = _objectWithoutProperties;
function _createSuper$5(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$5(); return function () { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$5() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
var Day = /*#__PURE__*/function (_Component) {
inherits(Day, _Component);
var _super = _createSuper$5(Day);
function Day() {
classCallCheck(this, Day);
return _super.apply(this, arguments);
}
createClass(Day, [{
key: "shouldComponentUpdate",
value: function shouldComponentUpdate(nextProps) {
return nextProps.selected !== this.props.selected || nextProps.disabled !== this.props.disabled || nextProps.isCurrentMonth !== this.props.isCurrentMonth;
}
}, {
key: "handleClick",
value: function handleClick(event) {
event.preventDefault();
event.stopPropagation();
event.nativeEvent.stopImmediatePropagation();
var _this$props = this.props,
disabled = _this$props.disabled,
onClick = _this$props.onClick,
day = _this$props.day;
if (disabled) return;
if (onClick) {
onClick(day);
}
}
}, {
key: "render",
value: function render() {
var _classnames;
var _this$props2 = this.props,
day = _this$props2.day,
disabled = _this$props2.disabled,
selected = _this$props2.selected,
isCurrentMonth = _this$props2.isCurrentMonth,
onClick = _this$props2.onClick,
styles = _this$props2.styles,
isGregorian = _this$props2.isGregorian,
isToday = _this$props2.isToday,
colors = _this$props2.colors,
rest = objectWithoutProperties(_this$props2, ["day", "disabled", "selected", "isCurrentMonth", "onClick", "styles", "isGregorian", "isToday", "colors"]);
var className = classnames(styles.dayWrapper, (_classnames = {}, defineProperty(_classnames, styles.selected, selected), defineProperty(_classnames, styles.currentMonth, isCurrentMonth), defineProperty(_classnames, styles.today, isToday), defineProperty(_classnames, styles.disabled, disabled), _classnames));
var highlightDotContainer = classnames("highLightDot-container", defineProperty({}, styles.disabled, disabled));
return /*#__PURE__*/React.createElement("div", {
className: className
}, /*#__PURE__*/React.createElement("button", _extends_1({
type: "button",
onClick: this.handleClick.bind(this),
disabled: disabled
}, rest), isGregorian ? day.format('D') : persianNumber(day.format('jD'))), /*#__PURE__*/React.createElement("div", {
className: highlightDotContainer,
onClick: this.handleClick.bind(this)
}, colors.map(function (x, i) {
return /*#__PURE__*/React.createElement("span", {
key: i,
className: "highLightDot",
style: {
backgroundColor: x
}
});
})));
}
}]);
return Day;
}(Component);
defineProperty(Day, "propTypes", {
day: PropTypes.object.isRequired,
isCurrentMonth: PropTypes.bool,
disabled: PropTypes.bool,
selected: PropTypes.bool,
onClick: PropTypes.func,
isGregorian: PropTypes.bool
});
/**
* Get days of a month that should be shown on a month page
*
* @param month A moment object
* @returns {Array}
*/
function getDaysOfMonth(month, isGregorian) {
var days = [];
var monthFormat = isGregorian ? 'Month' : 'jMonth';
var dayOffset = isGregorian ? 0 : 1;
var current = month.clone().startOf(monthFormat);
var end = month.clone().endOf(monthFormat); // Set start to the first day of week in the last month
current.subtract((current.day() + dayOffset) % 7, 'days'); // Set end to the last day of week in the next month
end.add(6 - (end.day() + dayOffset) % 7, 'days');
while (current.isBefore(end)) {
days.push(current.clone());
current.add(1, 'days');
}
return days;
}
function addZero(val) {
val = Number(val);
if (val < 10) return "0".concat(val);
return val;
}
function checkToday(compare) {
var today = new Date();
var todayString = String(today.getFullYear()) + addZero(String(today.getMonth() + 1)) + addZero(String(today.getDate()));
return compare === todayString;
}
var defaultStyles = {
calendarContainer: 'calendarContainer',
heading: 'heading',
prev: 'prev',
next: 'next',
title: 'title',
dayWrapper: 'dayWrapper',
currentMonth: 'currentMonth',
daysOfWeek: 'daysOfWeek',
yearsList: 'yearsList',
monthsList: 'monthsList',
selected: 'selected',
today: 'today',
dayPickerContainer: 'dayPickerContainer',
disabled: 'disabled'
};
var MomentRange = require('moment-range');
var extendedMoment = MomentRange.extendMoment(momentJalaali);
var RangesList = /*#__PURE__*/function () {
function RangesList(ranges) {
var _this = this;
classCallCheck(this, RangesList);
this.ranges = [];
if (ranges) {
ranges.forEach(function (item) {
_this.validateRangeObject(item);
var range = extendedMoment.range(item.start, item.end); // include start
var start = range.start.add(-1, 'days');
_this.ranges.push({
color: item.color,
range: range,
disabled: !!item.disabled
});
});
}
}
createClass(RangesList, [{
key: "getDayState",
value: function getDayState(day) {
var disabled = this.ranges.some(function (x) {
return x.disabled && x.range.contains(day);
});
var colors = this.ranges.filter(function (x) {
return x.color && x.range.contains(day);
}).map(function (x) {
return x.color;
});
return {
disabled: disabled,
colors: colors
};
}
}, {
key: "validateRangeObject",
value: function validateRangeObject(range) {
if (!('start' in range)) throw "'start' property is a required property of 'range' object.\n range object: ".concat(JSON.stringify(range));
if (!('end' in range)) throw "'end' property is a required property of 'range' object.\n range object: ".concat(JSON.stringify(range));
}
}]);
return RangesList;
}();
function _createSuper$6(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$6(); return function () { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$6() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
var Calendar = /*#__PURE__*/function (_Component) {
inherits(Calendar, _Component);
var _super = _createSuper$6(Calendar);
function Calendar() {
var _this;
classCallCheck(this, Calendar);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty(assertThisInitialized(_this), "state", {
year: _this.props.defaultYear || _this.props.selectedDay || momentJalaali(_this.props.min),
month: _this.props.defaultMonth || _this.props.selectedDay || momentJalaali(_this.props.min),
selectedDay: _this.props.selectedDay || _this.props.value || momentJalaali(),
mode: 'days',
isGregorian: _this.props.isGregorian,
ranges: new RangesList(_this.props.ranges)
});
defineProperty(assertThisInitialized(_this), "setMode", function (mode) {
_this.setState({
mode: mode
});
});
defineProperty(assertThisInitialized(_this), "setYear", function (year) {
var onYearChange = _this.props.onYearChange;
_this.setState({
year: year
});
if (onYearChange) {
onYearChange(year);
}
});
defineProperty(assertThisInitialized(_this), "setMonth", function (month) {
var onMonthChange = _this.props.onMonthChange;
_this.setState({
month: month
});
if (onMonthChange) {
onMonthChange(month);
}
});
defineProperty(assertThisInitialized(_this), "setType", function (type) {
_this.setState({
type: type
});
});
defineProperty(assertThisInitialized(_this), "nextMonth", function () {
var isGregorian = _this.state.isGregorian;
var monthFormat = isGregorian ? 'Month' : 'jMonth';
_this.setState({
month: _this.state.month.clone().add(1, monthFormat)
}, function () {
return _this.props.onMonthChange && _this.props.onMonthChange(_this.state.month);
});
});
defineProperty(assertThisInitialized(_this), "prevMonth", function () {
var isGregorian = _this.state.isGregorian;
var monthFormat = isGregorian ? 'Month' : 'jMonth';
_this.setState({
month: _this.state.month.clone().subtract(1, monthFormat)
}, function () {
return _this.props.onMonthChange && _this.props.onMonthChange(_this.state.month);
});
});
defineProperty(assertThisInitialized(_this), "selectDay", function (selectedDay) {
var _this$state = _this.state,
month = _this$state.month,
isGregorian = _this$state.isGregorian;
var yearMonthFormat = isGregorian ? 'YYYYMM' : 'jYYYYjMM'; // Because there's no `m1.isSame(m2, 'jMonth')`
if (selectedDay.format(yearMonthFormat) !== month.format(yearMonthFormat)) {
_this.setState({
month: selectedDay
});
}
_this.setState({
selectedDay: selectedDay
});
});
defineProperty(assertThisInitialized(_this), "handleClickOnDay", function (selectedDay) {
var _this$props = _this.props,
onSelect = _this$props.onSelect,
onChange = _this$props.onChange;
_this.selectDay(selectedDay);
if (onSelect) {
onSelect(selectedDay);
}
if (onChange) onChange(selectedDay);
});
defineProperty(assertThisInitialized(_this), "handleClickOutside", function (event) {
if (_this.props.onClickOutside) {
_this.props.onClickOutside(event);
}
});
defineProperty(assertThisInitialized(_this), "days", null);
defineProperty(assertThisInitialized(_this), "lastRenderedMonth", null);
defineProperty(assertThisInitialized(_this), "renderMonthSelector", function () {
var _this$state2 = _this.state,
month = _this$state2.month,
isGregorian = _this$state2.isGregorian;
var _this$props2 = _this.props,
styles = _this$props2.styles,
disableYearSelector = _this$props2.disableYearSelector;
return /*#__PURE__*/React.createElement(MonthSelector, {
disableYearSelector: disableYearSelector,
styles: styles,
isGregorian: isGregorian,
selectedMonth: month
});
});
defineProperty(assertThisInitialized(_this), "renderYearSelector", function () {
var _this$state3 = _this.state,
year = _this$state3.year,
month = _this$state3.month,
isGregorian = _this$state3.isGregorian;
var styles = _this.props.styles;
return /*#__PURE__*/React.createElement(YearSelector, {
styles: styles,
isGregorian: isGregorian,
selectedYear: year,
selectedMonth: month
});
});
defineProperty(assertThisInitialized(_this), "renderDays", function () {
var _this$state4 = _this.state,
month = _this$state4.month,
selectedDay = _this$state4.selectedDay,
isGregorian = _this$state4.isGregorian;
var _this$props3 = _this.props,
children = _this$props3.children,
min = _this$props3.min,
max = _this$props3.max,
styles = _this$props3.styles,
outsideClickIgnoreClass = _this$props3.outsideClickIgnoreClass;
var days;
if (_this.lastRenderedMonth === month) {
days = _this.days;
} else {
days = getDaysOfMonth(month, isGregorian);
_this.days = days;
_this.lastRenderedMonth = month;
}
var monthFormat = isGregorian ? 'MM' : 'jMM';
var dateFormat = isGregorian ? 'YYYYMMDD' : 'jYYYYjMMjDD';
return /*#__PURE__*/React.createElement("div", {
className: _this.props.calendarClass
}, children, /*#__PURE__*/React.createElement(Heading, {
timePicker: _this.props.timePicker,
isGregorian: isGregorian,
styles: styles,
month: month
}), /*#__PURE__*/React.createElement(DaysOfWeek, {
styles: styles,
isGregorian: isGregorian
}), /*#__PURE__*/React.createElement("div", {
className: styles.dayPickerContainer
}, days.map(function (day) {
var isCurrentMonth = day.format(monthFormat) === month.format(monthFormat);
var selected = selectedDay ? selectedDay.isSame(day, 'day') : false;
var key = day.format(dateFormat);
var isToday = checkToday(day.format('YYYYMMDD')); // disabling by old min-max props
var disabled = (min ? day.isBefore(min) : false) || (max ? day.isAfter(max) : false); // new method for disabling and highlighting the ranges of days
var dayState = _this.state.ranges.getDayState(day);
return /*#__PURE__*/React.createElement(Day, {
isGregorian: isGregorian,
key: key,
onClick: _this.handleClickOnDay,
day: day,
isToday: isToday,
colors: dayState.colors,
disabled: disabled || dayState.disabled // disabled by old method or new range method
,
selected: selected,
isCurrentMonth: isCurrentMonth,
styles: styles
});
})));
});
return _this;
}
createClass(Calendar, [{
key: "getChildContext",
value: function getChildContext() {
return {
nextMonth: this.nextMonth.bind(this),
prevMonth: this.prevMonth.bind(this),
setCalendarMode: this.setMode.bind(this),
setYear: this.setYear.bind(this),
setMonth: this.setMonth.bind(this),
setType: this.setMonth.bind(this)
};
}
}, {
key: "UNSAFE_componentWillReceiveProps",
value: function UNSAFE_componentWillReceiveProps(_ref) {
var selectedDay = _ref.selectedDay,
defaultYear = _ref.defaultYear,
defaultMonth = _ref.defaultMonth,
min = _ref.min,
isGregorian = _ref.isGregorian,
ranges = _ref.ranges;
if (typeof isGregorian !== 'undefined' && isGregorian !== this.state.isGregorian) {
this.setState({
isGregorian: isGregorian
});
}
if (this.props.selectedDay !== selectedDay) {
this.selectDay(selectedDay || momentJalaali());
} else if (defaultYear && this.props.defaultYear !== defaultYear && this.state.year === this.props.defaultYear) {
this.setYear(defaultYear);
} else if (defaultMonth && this.props.defaultMonth !== defaultMonth && this.state.month === this.props.defaultMonth) {
this.setMonth(defaultMonth);
} else if (min && this.props.min !== min && this.state.month.isSame(this.props.min)) {
this.setMonth(min.clone());
}
if (JSON.stringify(this.props.ranges) !== JSON.stringify(ranges)) {
this.setState({
ranges: new RangesList(ranges)
});
}
}
}, {
key: "changeCalendarMode",
value: function changeCalendarMode() {
this.props.toggleMode();
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var _this$props4 = this.props,
selectedDay = _this$props4.selectedDay,
min = _this$props4.min,
max = _this$props4.max,
onClickOutside = _this$props4.onClickOutside,
outsideClickIgnoreClass = _this$props4.outsideClickIgnoreClass,
styles = _this$props4.styles,
className = _this$props4.className,
showTodayButton = _this$props4.showTodayButton;
var _this$state5 = this.state,
mode = _this$state5.mode,
isGregorian = _this$state5.isGregorian;
var jalaaliClassName = isGregorian ? '' : 'jalaali ';
var today = momentJalaali();
today.set({
hour: 0,
minute: 0,
second: 0,
millisecond: 0
}); // check today state -----------
// disabling by old min-max props
var disabled = (min ? today.isBefore(min) : false) || (max ? today.isAfter(max) : false); // new method for disabling and highlighting the ranges of days
var dayState = this.state.ranges.getDayState(today);
var isTodayDisabled = disabled || dayState.disabled; // ------------------------------
return /*#__PURE__*/React.createElement("div", {
className: "".concat(styles.calendarContainer, " ").concat(jalaaliClassName).concat(className)
}, this.props.showToggleButton && /*#__PURE__*/React.createElement("button", {
className: "calendarButton toggleButton",
type: "button",
onClick: this.changeCalendarMode.bind(this)
}, isGregorian ? this.props.toggleButtonText[0] : this.props.toggleButtonText[1]), mode === 'days' && this.renderDays(), mode === 'monthSelector' && this.renderMonthSelector(), mode === 'yearSelector' && this.renderYearSelector(), showTodayButton && /*#__PURE__*/React.createElement("button", {
type: "button",
className: "calendarButton selectToday",
onClick: function onClick() {
return _this2.handleClickOnDay(today);
},
disabled: isTodayDisabled
}, isGregorian ? 'today' : 'امروز'));
}
}]);
return Calendar;
}(Component);
defineProperty(Calendar, "propTypes", {
min: PropTypes.object,
max: PropTypes.object,
styles: PropTypes.object,
selectedDay: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
defaultYear: PropTypes.object,
defaultMonth: PropTypes.object,
onSelect: PropTypes.func,
onYearChange: PropTypes.func,
onMonthChange: PropTypes.func,
onClickOutside: PropTypes.func,
containerProps: PropTypes.object,
isGregorian: PropTypes.bool,
calendarClass: PropTypes.string,
showToggleButton: PropTypes.bool,
toggleButtonText: PropTypes.any,
showTodayButton: PropTypes.bool,
disableYearSelector: PropTypes.bool
});
defineProperty(Calendar, "childContextTypes", {
nextMonth: PropTypes.func.isRequired,
prevMonth: PropTypes.func.isRequired,
setCalendarMode: PropTypes.func.isRequired,
setYear: PropTypes.func.isRequired,
setMonth: PropTypes.func.isRequired,
setType: PropTypes.func.isRequired
});
defineProperty(Calendar, "defaultProps", {
styles: defaultStyles,
containerProps: {},
isGregorian: true,
showToggleButton: false,
showTodayButton: true,
toggleButtonText: ['تاریخ شمسی', 'تاریخ میلادی']
});
var Calendar$1 = onClickOutside(Calendar);
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
var arrayLikeToArray = _arrayLikeToArray;
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return arrayLikeToArray(arr);
}
var arrayWithoutHoles = _arrayWithoutHoles;
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
}
var iterableToArray = _iterableToArray;
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
}
var unsupportedIterableToArray = _unsupportedIterableToArray;
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var nonIterableSpread = _nonIterableSpread;
function _toConsumableArray(arr) {
return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
}
var toConsumableArray = _toConsumableArray;
function _createSuper$7(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$7(); return function () { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$7() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
var Header = /*#__PURE__*/function (_React$Component) {
inherits(Header, _React$Component);
var _super = _createSuper$7(Header);
function Header(props) {
var _this;
classCallCheck(this, Header);
_this = _super.call(this, props);
var _this$props = _this.props,
value = _this$props.value,
format = _this$props.format;
_this.state = {
str: value && value.format(format) || '',
invalid: false
};
_this.onClear = _this.onClear.bind(assertThisInitialized(_this));
_this.onInputChange = _this.onInputChange.bind(assertThisInitialized(_this));
_this.onKeyDown = _this.onKeyDown.bind(assertThisInitialized(_this));
return _this;
}
createClass(Header, [{
key: "UNSAFE_componentWillReceiveProps",
value: function UNSAFE_componentWillReceiveProps(nextProps) {
var value = nextProps.value,
format = nextProps.format;
this.setState({
str: value && value.format(format) || '',
invalid: false
});
}
}, {
key: "onInputChange",
value: function onInputChange(event) {
var str = event.target.value;
this.setState({
str: str
});
var _this$props2 = this.props,
format = _this$props2.format,
hourOptions = _this$props2.hourOptions,
minuteOptions = _this$props2.minuteOptions,
secondOptions = _this$props2.secondOptions,
disabledHours = _this$props2.disabledHours,
disabledMinutes = _this$props2.disabledMinutes,
disabledSeconds = _this$props2.disabledSeconds,
onChange = _this$props2.onChange,
allowEmpty = _this$props2.allowEmpty;
if (str) {
var originalValue = this.props.value;
var value = this.getProtoValue().clone();
var parsed = momentJalaali(str, format, true);
if (!parsed.isValid()) {
this.setState({
invalid: true
});
return;
}
value.hour(parsed.hour()).minute(parsed.minute()).second(parsed.second()); // if time value not allowed, response warning.
if (hourOptions.indexOf(value.hour()) < 0 || minuteOptions.indexOf(value.minute()) < 0 || secondOptions.indexOf(value.second()) < 0) {
this.setState({
invalid: true
});
return;
} // if time value is disabled, response warning.
var disabledHourOptions = disabledHours();
var disabledMinuteOptions = disabledMinutes(value.hour());
var disabledSecondOptions = disabledSeconds(value.hour(), value.minute());
if (disabledHourOptions && disabledHourOptions.indexOf(value.hour()) >= 0 || disabledMinuteOptions && disabledMinuteOptions.indexOf(value.minute()) >= 0 || disabledSecondOptions && disabledSecondOptions.indexOf(value.second()) >= 0) {
this.setState({
invalid: true
});
return;
}
if (originalValue) {
if (originalValue.hour() !== value.hour() || originalValue.minute() !== value.minute() || originalValue.second() !== value.second()) {
// keep other fields for rc-calendar
var changedValue = originalValue.clone();
changedValue.hour(value.hour());
changedValue.minute(value.minute());
changedValue.second(value.second());
onChange(changedValue);
}
} else if (originalValue !== value) {
onChange(value);
}
} else if (allowEmpty) {
onChange(null);
} else {
this.setState({
invalid: true
});
return;
}
this.setState({
invalid: false
});
}
}, {
key: "onKeyDown",
value: function onKeyDown(e) {
if (e.keyCode === 27) {
this.props.onEsc();
}
}
}, {
key: "onClear",
value: function onClear() {
this.setState({
str: ''
});
this.props.onClear();
}
}, {
key: "getClearButton",
value: function getClearButton() {
var _this$props3 = this.props,
prefixCls = _this$props3.prefixCls,
allowEmpty = _this$props3.allowEmpty;
if (!allowEmpty) {
return null;
}
return /*#__PURE__*/React.createElement("a", {
className: "".concat(prefixCls, "-clear-btn"),
role: "button",
title: this.props.clearText,
onMouseDown: this.onClear
});
}
}, {
key: "getProtoValue",
value: function getProtoValue() {
return this.props.value || this.props.defaultOpenValue;
}
}, {
key: "getInput",
value: function getInput() {
var _this2 = this;
var _this$props4 = this.props,
prefixCls = _this$props4.prefixCls,
placeholder = _this$props4.placeholder,
name = _this$props4.name;
var _this$state = this.state,
invalid = _this$state.invalid,
str = _this$state.str;
var invalidClass = invalid ? "".concat(prefixCls, "-input-invalid") : '';
return /*#__PURE__*/React.createElement("input", {
className: "".concat(prefixCls, "-input ").concat(invalidClass),
ref: function ref(inst) {
_this2.input = inst;
},
onKeyDown: this.onKeyDown,
value: str,
placeholder: placeholder,
name: name,
onChange: this.onInputChange
});
}
}, {
key: "render",
value: function render() {
var prefixCls = this.props.prefixCls;
return /*#__PURE__*/React.createElement("div", {
className: "".concat(prefixCls, "-input-wrap")
}, this.getInput(), this.getClearButton());
}
}]);
return Header;
}(React.Component);
defineProperty(Header, "propTypes", {
format: PropTypes.string,
prefixCls: PropTypes.string,
disabledDate: PropTypes.func,
placeholder: PropTypes.string,
name: PropTypes.string,
clearText: PropTypes.string,
value: PropTypes.object,
hourOptions: PropTypes.array,
minuteOptions: PropTypes.array,
secondOptions: PropTypes.array,
disabledHours: PropTypes.func,
disabledMinutes: PropTypes.func,
disabledSeconds: PropTypes.func,
onChange: PropTypes.func,
onClear: PropTypes.func,
onEsc: PropTypes.func,
allowEmpty: PropTypes.bool,
defaultOpenValue: PropTypes.object,
currentSelectPanel: PropTypes.string
});
function _createSuper$8(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$8(); return function () { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$8() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
var scrollTo = function scrollTo(element, to, duration) {
var requestAnimationFrame = window.requestAnimationFrame || function requestAnimationFrameTimeout() {
return setTimeout(arguments[0], 10);
}; // jump to target if duration zero
if (duration <= 0) {
element.scrollTop = to;
return;
}
var difference = to - element.scrollTop;
var perTick = difference / duration * 10;
requestAnimationFrame(function () {
element.scrollTop += perTick;
if (element.scrollTop === to) return;
scrollTo(element, to, duration - 10);
});
};
var Select = /*#__PURE__*/function (_React$Component) {
inherits(Select, _React$Component);
var _super = _createSuper$8(Select);
function Select() {
var _this;
classCallCheck(this, Select);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty(assertThisInitialized(_this), "onSelect", function (value) {
var _this$props = _this.props,
onSelect = _this$props.onSelect,
type = _this$props.type;
_this.props.onSelect(type, value);
});
defineProperty(assertThisInitialized(_this), "getOptions", function () {
var _this$props2 = _this.props,
options = _this$props2.options,
selectedIndex = _this$props2.selectedIndex,
prefixCls = _this$props2.prefixCls;
return options.map(function (item, index) {
var _classnames;
var cls = classnames((_classnames = {}, defineProperty(_classnames, "".concat(prefixCls, "-select-option-selected"), selectedIndex === index), defineProperty(_classnames, "".concat(prefixCls, "-select-option-disabled"), item.disabled), _classnames));
var onclick = null;
if (!item.disabled) {
var value = +item.value;
if (Number.isNaN(value)) {
value = item.value;
}
onclick = _this.onSelect.bind(assertThisInitialized(_this), value);
}
return /*#__PURE__*/React.createElement("li", {
className: cls,
key: index,
onClick: onclick,
disabled: item.disabled
}, typeof item.label !== 'undefined' ? item.label : item.value);
});
});
defineProperty(assertThisInitialized(_this), "scrollToSelected", function (duration) {
// move to selected item
var select = ReactDom.findDOMNode(assertThisInitialized(_this));
var list = ReactDom.findDOMNode(_this.list);
var index = _this.props.selectedIndex;
if (index < 0) {
index = 0;
}
var topOption = list.children[index];
var to = topOption.offsetTop;
scrollTo(select, to, duration);
});
return _this;
}
createClass(Select, [{
key: "componentDidMount",
value: function componentDidMount() {
// jump to selected option
this.scrollToSelected(0);
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
// smooth scroll to selected option
if (prevProps.selectedIndex !== this.props.selectedIndex) {
this.scrollToSelected(120);
}
}
}, {
key: "render",
value: function render() {
var _this2 = this;
if (this.props.options.length === 0) {
return null;
}
var prefixCls = this.props.prefixCls;
return /*#__PURE__*/React.createElement("div", {
className: "".concat(prefixCls, "-select"),
onMouseEnter: this.props.onMouseEnter
}, /*#__PURE__*/React.createElement("ul", {
ref: function ref(inst) {
_this2.list = inst;
}
}, this.getOptions()));
}
}]);
return Select;
}(React.Component);
defineProperty(Select, "propTypes", {
prefixCls: PropTypes.string,
options: PropTypes.array,
selectedIndex: PropTypes.number,
type: PropTypes.string,
onSelect: PropTypes.func,
onMouseEnter: PropTypes.func
});
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper$9(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$9(); return function () { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$9() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
var pad = function pad(value) {
return value < 10 ? "0".concat(value) : "".concat(value);
};
var formatOption = function formatOption(option, disabledOptions) {
var value = pad(option);
var disabled = false;
if (disabledOptions && disabledOptions.indexOf(option) >= 0) {
disabled = true;
}
return {
value: value,
disabled: disabled
};
};
var Combobox = /*#__PURE__*/function (_React$Component) {
inherits(Combobox, _React$Component);
var _super = _createSuper$9(Combobox);
function Combobox() {
var _this;
classCallCheck(this, Combobox);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty(assertThisInitialized(_this), "onItemChange", function (type, itemValue) {
var _this$props = _this.props,
onChange = _this$props.onChange,
defaultOpenValue = _this$props.defaultOpenValue;
var value = (_this.props.value || defaultOpenValue).clone();
if (type === 'hour') {
value.hour(itemValue);
} else if (type === 'minute') {
value.minute(itemValue);
} else if (type === 'second') {
value.second(itemValue);
} else {
var actualPeriod = value.format('A');
if (actualPeriod !== itemValue) {
var hour24style = value.hour();
var hour12style = hour24style < 12 ? hour24style : hour24style - 12;
if (itemValue === 'PM') {
value.hour(hour12style + 12);
} else {
value.hour(hour12style);
}
}
}
onChange(value);
});
defineProperty(assertThisInitialized(_this), "onEnterSelectPanel", function (range) {
_this.props.onCurrentSelectPanelChange(range);
});
defineProperty(assertThisInitialized(_this), "getHourSelect", function (hour) {
var _this$props2 = _this.props,
prefixCls = _this$props2.prefixCls,
showAMPM = _this$props2.showAMPM,
disabledHours = _this$props2.disabledHours,
showHour = _this$props2.showHour;
if (!showHour) {
return null;
}
var disabledOptions = disabledHours();
var hourOptions = _this.props.hourOptions;
var formattedOptions = hourOptions.map(function (option) {
return formatOption(option, disabledOptions);
});
if (showAMPM) {
hourOptions = hourOptions.filter(function (value) {
return hour < 12 ? value < 12 : value >= 12;
});
formattedOptions = formattedOptions.map(function (option) {
return _objectSpread(_objectSpread({}, option), {}, {
label: option.value <= 12 ? option.value : pad(option.value - 12)
});
}).filter(function (_ref) {
var value = _ref.value;
return hour < 12 ? Number(value) < 12 : Number(value) >= 12;
});
}
return /*#__PURE__*/React.createElement(Select, {
prefixCls: prefixCls,
options: formattedOptions,
selectedIndex: hourOptions.indexOf(hour),
type: "hour",
onSelect: _this.onItemChange,
onMouseEnter: _this.onEnterSelectPanel.bind(assertThisInitialized(_this), 'hour')
});
});
defineProperty(assertThisInitialized(_this), "getMinuteSelect", function (minute) {
var _this$props3 = _this.props,
prefixCls = _this$props3.prefixCls,
minuteOptions = _this$props3.minuteOptions,
disabledMinutes = _this$props3.disabledMinutes,
defaultOpenValue = _this$props3.defaultOpenValue;
var value = _this.props.value || defaultOpenValue;
var disabledOptions = disabledMinutes(value.hour());
return /*#__PURE__*/React.createElement(Select, {
prefixCls: prefixCls,
options: minuteOptions.map(function (option) {
return formatOption(option, disabledOptions);
}),
selectedIndex: minuteOptions.indexOf(minute),
type: "minute",
onSelect: _this.onItemChange,
onMouseEnter: _this.onEnterSelectPanel.bind(assertThisInitialized(_this), 'minute')
});
});
defineProperty(assertThisInitialized(_this), "getSecondSelect", function (second) {
var _this$props4 = _this.props,
prefixCls = _this$props4.prefixCls,
secondOptions = _this$props4.secondOptions,
disabledSeconds = _this$props4.disabledSeconds,
showSecond = _this$props4.showSecond,
defaultOpenValue = _this$props4.defaultOpenValue;
if (!showSecond) {
return null;
}
var value = _this.props.value || defaultOpenValue;
var disabledOptions = disabledSeconds(value.hour(), value.minute());
return /*#__PURE__*/React.createElement(Select, {
prefixCls: prefixCls,
options: secondOptions.map(function (option) {
return formatOption(option, disabledOptions);
}),
selectedIndex: secondOptions.indexOf(second),
type: "second",
onSelect: _this.onItemChange,
onMouseEnter: _this.onEnterSelectPanel.bind(assertThisInitialized(_this), 'second')
});
});
defineProperty(assertThisInitialized(_this), "getAMPMSelect", function (period) {
var _this$props5 = _this.props,
prefixCls = _this$props5.prefixCls,
showAMPM = _this$props5.showAMPM,
defaultOpenValue = _this$props5.defaultOpenValue,
isGregorian = _this$props5.isGregorian;
if (!showAMPM) {
return null;
}
var options = [{
value: 'AM',
label: isGregorian ? 'AM' : 'ق.ظ'
}, {
value: 'PM',
label: isGregorian ? 'PM' : 'ب.ظ'
}];
return /*#__PURE__*/React.createElement(Select, {
prefixCls: prefixCls,
options: options,
selectedIndex: period === 'AM' ? 0 : 1,
type: "period",
onSelect: _this.onItemChange,
onMouseEnter: _this.onEnterSelectPanel.bind(assertThisInitialized(_this), 'period')
});
});
return _this;
}
createClass(Combobox, [{
key: "render",
value: function render() {
var _this$props6 = this.props,
prefixCls = _this$props6.prefixCls,
defaultOpenValue = _this$props6.defaultOpenValue;
var value = this.props.value || defaultOpenValue;
return /*#__PURE__*/React.createElement("div", {
className: "".concat(prefixCls, "-combobox")
}, this.getHourSelect(value.hour()), this.getMinuteSelect(value.minute()), this.getSecondSelect(value.second()), this.getAMPMSelect(value.hour() < 12 ? 'AM' : 'PM'));
}
}]);
return Combobox;
}(React.Component);
defineProperty(Combobox, "propTypes", {
format: PropTypes.string,
defaultOpenValue: PropTypes.object,
prefixCls: PropTypes.string,
value: PropTypes.object,
onChange: PropTypes.func,
showHour: PropTypes.bool,
showSecond: PropTypes.bool,
hourOptions: PropTypes.array,
minuteOptions: PropTypes.array,
secondOptions: PropTypes.array,
disabledHours: PropTypes.func,
disabledMinutes: PropTypes.func,
disabledSeconds: PropTypes.func,
onCurrentSelectPanelChange: PropTypes.func,
isGregorian: PropTypes.bool
});
function _createSuper$a(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$a(); return function () { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$a() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function noop() {}
function generateOptions(length, disabledOptions, hideDisabledOptions) {
var arr = [];
for (var value = 0; value < length; value++) {
if (!disabledOptions || disabledOptions.indexOf(value) < 0 || !hideDisabledOptions) {
arr.push(value);
}
}
return arr;
}
var Panel = /*#__PURE__*/function (_React$Component) {
inherits(Panel, _React$Component);
var _super = _createSuper$a(Panel);
function Panel(props) {
var _this;
classCallCheck(this, Panel);
_this = _super.call(this, props);
defineProperty(assertThisInitialized(_this), "onChange", function (newValue) {
_this.setState({
value: newValue
});
_this.props.onChange(newValue);
});
defineProperty(assertThisInitialized(_this), "onClear", function () {
_this.props.onClear();
});
defineProperty(assertThisInitialized(_this), "onCurrentSelectPanelChange", function (currentSelectPanel) {
_this.setState({
currentSelectPanel: currentSelectPanel
});
});
_this.state = {
value: _this.props.value,
selectionRange: []
};
return _this;
}
createClass(Panel, [{
key: "UNSAFE_componentWillReceiveProps",
value: function UNSAFE_componentWillReceiveProps(nextProps) {
var value = nextProps.value;
if (value) {
this.setState({
value: value
});
}
}
}, {
key: "render",
value: function render() {
var _this$props = this.props,
isGregorian = _this$props.isGregorian,
formatter = _this$props.formatter,
prefixCls = _this$props.prefixCls,
className = _this$props.className,
placeholder = _this$props.placeholder,
name = _this$props.name,
disabledHours = _this$props.disabledHours,
disabledMinutes = _this$props.disabledMinutes,
disabledSeconds = _this$props.disabledSeconds,
hideDisabledOptions = _this$props.hideDisabledOptions,
allowEmpty = _this$props.allowEmpty,
showHour = _this$props.showHour,
showSecond = _this$props.showSecond,
showAMPM = _this$props.showAMPM,
format = _this$props.format,
defaultOpenValue = _this$props.defaultOpenValue,
clearText = _this$props.clearText,
onEsc = _this$props.onEsc;
var _this$state = this.state,
value = _this$state.value,
currentSelectPanel = _this$state.currentSelectPanel;
var disabledHourOptions = disabledHours();
var disabledMinuteOptions = disabledMinutes(value ? value.hour() : null);
var disabledSecondOptions = disabledSeconds(value ? value.hour() : null, value ? value.minute() : null);
var hourOptions = generateOptions(24, disabledHourOptions, hideDisabledOptions);
var minuteOptions = generateOptions(60, disabledMinuteOptions, hideDisabledOptions);
var secondOptions = generateOptions(60, disabledSecondOptions, hideDisabledOptions);
return /*#__PURE__*/React.createElement("div", {
className: "".concat(prefixCls, "-inner ").concat(className)
}, /*#__PURE__*/React.createElement(Header, {
clearText: clearText,
prefixCls: prefixCls,
defaultOpenValue: defaultOpenValue,
value: value,
currentSelectPanel: currentSelectPanel,
onEsc: onEsc,
format: format,
placeholder: placeholder,
name: name,
hourOptions: hourOptions,
minuteOptions: minuteOptions,
secondOptions: secondOptions,
disabledHours: disabledHours,
disabledMinutes: disabledMinutes,
disabledSeconds: disabledSeconds,
onChange: this.onChange,
onClear: this.onClear,
allowEmpty: allowEmpty
}), /*#__PURE__*/React.createElement(Combobox, {
isGregorian: isGregorian,
formatter: formatter,
prefixCls: prefixCls,
value: value,
defaultOpenValue: defaultOpenValue,
format: format,
onChange: this.onChange,
showAMPM: showAMPM,
showHour: showHour,
showSecond: showSecond,
hourOptions: hourOptions,
minuteOptions: minuteOptions,
secondOptions: secondOptions,
disabledHours: disabledHours,
disabledMinutes: disabledMinutes,
disabledSeconds: disabledSeconds,
onCurrentSelectPanelChange: this.onCurrentSelectPanelChange
}));
}
}]);
return Panel;
}(React.Component);
defineProperty(Panel, "propTypes", {
clearText: PropTypes.string,
prefixCls: PropTypes.string,
defaultOpenValue: PropTypes.object,
value: PropTypes.object,
placeholder: PropTypes.string,
name: PropTypes.string,
format: PropTypes.string,
disabledHours: PropTypes.func,
disabledMinutes: PropTypes.func,
disabledSeconds: PropTypes.func,
hideDisabledOptions: PropTypes.bool,
onChange: PropTypes.func,
onEsc: PropTypes.func,
allowEmpty: PropTypes.bool,
showHour: PropTypes.bool,
showSecond: PropTypes.bool,
onClear: PropTypes.func,
showAMPM: PropTypes.bool,
isGregorian: PropTypes.bool
});
defineProperty(Panel, "defaultProps", {
prefixCls: 'rc-time-picker-panel',
onChange: noop,
onClear: noop,
defaultOpenValue: momentJalaali()
});
var autoAdjustOverflow = {
adjustX: 1,
adjustY: 1
};
var targetOffset = [0, 0];
var placements = {
bottomLeft: {
points: ['tl', 'tl'],
overflow: autoAdjustOverflow,
offset: [0, -3],
targetOffset: targetOffset
},
bottomRight: {
points: ['tr', 'tr'],
overflow: autoAdjustOverflow,
offset: [0, -3],
targetOffset: targetOffset
},
topRight: {
points: ['br', 'br'],
overflow: autoAdjustOverflow,
offset: [0, 3],
targetOffset: targetOffset
},
topLeft: {
points: ['bl', 'bl'],
overflow: autoAdjustOverflow,
offset: [0, 3],
targetOffset: targetOffset
}
};
function _createSuper$b(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$b(); return function () { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$b() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function noop$1() {}
function refFn(field, component) {
this[field] = component;
}
var Picker = /*#__PURE__*/function (_React$Component) {
inherits(Picker, _React$Component);
var _super = _createSuper$b(Picker);
function Picker(props) {
var _this;
classCallCheck(this, Picker);
_this = _super.call(this, props);
defineProperty(assertThisInitialized(_this), "setOpen", function (open, callback) {
var _this$props = _this.props,
onOpen = _this$props.onOpen,
onClose = _this$props.onClose;
if (_this.state.open !== open) {
_this.setState({
open: open
}, callback);
var event = {
open: open
};
if (open) {
onOpen(event);
} else {
onClose(event);
}
}
});
defineProperty(assertThisInitialized(_this), "onPanelChange", function (value) {
_this.setValue(value);
});
defineProperty(assertThisInitialized(_this), "onPanelClear", function () {
_this.setValue(null);
_this.setOpen(false);
});
defineProperty(assertThisInitialized(_this), "onVisibleChange", function (open) {
_this.setOpen(open);
});
defineProperty(assertThisInitialized(_this), "onEsc", function () {
_this.setOpen(false);
_this.picker.focus();
});
defineProperty(assertThisInitialized(_this), "onKeyDown", function (e) {
if (e.keyCode === 40) {
_this.setOpen(true);
}
});
defineProperty(assertThisInitialized(_this), "setValue", function (value) {
if (!('value' in _this.props)) {
_this.setState({
value: value
});
}
_this.props.onChange(value);
});
defineProperty(assertThisInitialized(_this), "getFormat", function () {
var format = _this.props.format;
if (_this.props.format) {
format = _this.props.format;
} else if (!_this.props.showSecond) {
format = 'HH:mm';
} else if (!_this.props.showHour) {
format = 'mm:ss';
} else {
format = 'HH:mm:ss';
}
if (_this.props.showAMPM) {
format = "".concat(format.replace('HH', 'hh'), " A");
}
return format;
});
defineProperty(assertThisInitialized(_this), "getPanelElement", function () {
var _this$props2 = _this.props,
prefixCls = _this$props2.prefixCls,
placeholder = _this$props2.placeholder,
name = _this$props2.name,
disabledHours = _this$props2.disabledHours,
disabledMinutes = _this$props2.disabledMinutes,
disabledSeconds = _this$props2.disabledSeconds,
hideDisabledOptions = _this$props2.hideDisabledOptions,
allowEmpty = _this$props2.allowEmpty,
showHour = _this$props2.showHour,
showSecond = _this$props2.showSecond,
showAMPM = _this$props2.showAMPM,
defaultOpenValue = _this$props2.defaultOpenValue,
clearText = _this$props2.clearText,
isGregorian = _this$props2.isGregorian;
return /*#__PURE__*/React.createElement(Panel, {
isGregorian: isGregorian,
clearText: clearText,
prefixCls: "".concat(prefixCls, "-panel"),
ref: function ref(refs) {
_this.savePanelRef = refs;
},
value: _this.state.value,
onChange: _this.onPanelChange,
onClear: _this.onPanelClear,
defaultOpenValue: defaultOpenValue,
showHour: showHour,
onEsc: _this.onEsc,
showSecond: showSecond,
showAMPM: showAMPM,
allowEmpty: true,
format: _this.getFormat(),
placeholder: placeholder,
name: name,
disabledHours: disabledHours,
disabledMinutes: disabledMinutes,
disabledSeconds: disabledSeconds,
hideDisabledOptions: hideDisabledOptions
});
});
_this.savePanelRef = refFn.bind(assertThisInitialized(_this), 'panelInstance');
var _this$props3 = _this.props,
defaultOpen = _this$props3.defaultOpen,
defaultValue = _this$props3.defaultValue,
_this$props3$open = _this$props3.open,
_open = _this$props3$open === void 0 ? defaultOpen : _this$props3$open,
_this$props3$value = _this$props3.value,
_value = _this$props3$value === void 0 ? defaultValue : _this$props3$value;
_this.state = {
open: _open,
value: _value
};
return _this;
}
createClass(Picker, [{
key: "UNSAFE_componentWillReceiveProps",
value: function UNSAFE_componentWillReceiveProps(nextProps) {
var value = nextProps.value,
open = nextProps.open;
if ('value' in nextProps) {
this.setState({
value: value
});
}
if (open !== undefined) {
this.setState({
open: open
});
}
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var _this$props4 = this.props,
panelClassName = _this$props4.panelClassName,
prefixCls = _this$props4.prefixCls,
placeholder = _this$props4.placeholder,
name = _this$props4.name,
placement = _this$props4.placement,
align = _this$props4.align,
disabled = _this$props4.disabled,
transitionName = _this$props4.transitionName,
style = _this$props4.style,
className = _this$props4.className,
showHour = _this$props4.showHour,
showSecond = _this$props4.showSecond,
getPopupContainer = _this$props4.getPopupContainer;
var _this$state = this.state,
open = _this$state.open,
value = _this$state.value;
var popupClassName;
if (!showHour || !showSecond) {
popupClassName = "".concat(prefixCls, "-panel-narrow");
}
return /*#__PURE__*/React.createElement(Trigger, {
prefixCls: "".concat(prefixCls, "-panel ").concat(panelClassName),
popupClassName: popupClassName,
popup: this.getPanelElement(),
popupAlign: align,
builtinPlacements: placements,
popupPlacement: placement,
action: disabled ? [] : ['click'],
destroyPopupOnHide: true,
getPopupContainer: getPopupContainer,
popupTransitionName: transitionName,
popupVisible: open,
onPopupVisibleChange: this.onVisibleChange
}, /*#__PURE__*/React.createElement("span", {
className: "".concat(prefixCls, " ").concat(className),
style: style
}, /*#__PURE__*/React.createElement("input", {
className: "".concat(prefixCls, "-input"),
ref: function ref(refs) {
_this2.picker = refs;
},
type: "text",
placeholder: placeholder,
name: name,
readOnly: true,
onKeyDown: this.onKeyDown,
disabled: disabled,
value: value && value.format(this.getFormat()) || ''
}), /*#__PURE__*/React.createElement("span", {
className: "".concat(prefixCls, "-icon")
})));
}
}]);
return Picker;
}(React.Component);
defineProperty(Picker, "propTypes", {
prefixCls: PropTypes.string,
clearText: PropTypes.string,
value: PropTypes.object,
defaultOpenValue: PropTypes.object,
disabled: PropTypes.bool,
allowEmpty: PropTypes.bool,
defaultValue: PropTypes.object,
open: PropTypes.bool,
defaultOpen: PropTypes.bool,
align: PropTypes.object,
placement: PropTypes.any,
transitionName: PropTypes.string,
getPopupContainer: PropTypes.func,
placeholder: PropTypes.string,
name: PropTypes.string,
format: PropTypes.string,
showHour: PropTypes.bool,
style: PropTypes.object,
className: PropTypes.string,
showSecond: PropTypes.bool,
disabledHours: PropTypes.func,
disabledMinutes: PropTypes.func,
disabledSeconds: PropTypes.func,
hideDisabledOptions: PropTypes.bool,
onChange: PropTypes.func,
onOpen: PropTypes.func,
onClose: PropTypes.func,
showAMPM: PropTypes.bool,
panelClassName: PropTypes.string,
isGregorian: PropTypes.bool
});
defineProperty(Picker, "defaultProps", {
clearText: 'clear',
prefixCls: 'rc-time-picker',
defaultOpen: false,
style: {},
className: '',
align: {},
defaultOpenValue: momentJalaali(),
allowEmpty: true,
showHour: true,
showSecond: true,
disabledHours: noop$1,
disabledMinutes: noop$1,
disabledSeconds: noop$1,
hideDisabledOptions: false,
placement: 'bottomLeft',
onChange: noop$1,
onOpen: noop$1,
onClose: noop$1
});
function _createSuper$c(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$c(); return function () { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$c() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
var disabledMinutes = function disabledMinutes() {
return toConsumableArray(Array(60)).map(function (v, i) {
return i;
}).filter(function (v) {
return v % 5 !== 0;
});
};
var MyTimePicker = /*#__PURE__*/function (_Component) {
inherits(MyTimePicker, _Component);
var _super = _createSuper$c(MyTimePicker);
function MyTimePicker() {
classCallCheck(this, MyTimePicker);
return _super.apply(this, arguments);
}
createClass(MyTimePicker, [{
key: "handleChange",
value: function handleChange(value) {
var _this$props = this.props,
momentValue = _this$props.momentValue,
min = _this$props.min;
var newValue;
if (momentValue) {
newValue = momentValue.clone();
} else if (min && min.isAfter(momentJalaali())) {
newValue = min.clone();
} else {
newValue = momentJalaali(value);
}
newValue.hour(value ? value.hour() : null);
newValue.minute(value ? value.minute() : null);
this.props.setMomentValue(newValue);
}
}, {
key: "render",
value: function render() {
var _this$props2 = this.props,
momentValue = _this$props2.momentValue,
isGregorian = _this$props2.isGregorian,
outsideClickIgnoreClass = _this$props2.outsideClickIgnoreClass;
return /*#__PURE__*/React.createElement(Picker, {
showAMPM: true,
isGregorian: isGregorian,
showSecond: false,
allowEmpty: false,
value: momentValue,
className: outsideClickIgnoreClass,
popupClassName: outsideClickIgnoreClass,
panelClassName: "".concat(outsideClickIgnoreClass, " time-picker-panel"),
onChange: this.handleChange.bind(this),
disabledMinutes: disabledMinutes,
formatter: function formatter(value) {
return persianNumber(value);
},
hideDisabledOptions: true
});
}
}]);
return MyTimePicker;
}(Component);
defineProperty(MyTimePicker, "propTypes", {
momentValue: PropTypes.object,
setMomentValue: PropTypes.func,
isGregorian: PropTypes.bool
});
defineProperty(MyTimePicker, "defaultProps", {
momentValue: momentJalaali()
});
function _createSuper$d(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$d(); return function () { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$d() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
var outsideClickIgnoreClass = 'ignore--click--outside';
var DatePicker = /*#__PURE__*/function (_Component) {
inherits(DatePicker, _Component);
var _super = _createSuper$d(DatePicker);
function DatePicker(props) {
var _this;
classCallCheck(this, DatePicker);
_this = _super.call(this, props); // create a ref to store the textInput DOM element
defineProperty(assertThisInitialized(_this), "setOpen", function (isOpen) {
_this.setState({
isOpen: isOpen
});
if (_this.props.onOpen) {
_this.props.onOpen(isOpen);
}
});
defineProperty(assertThisInitialized(_this), "toggleMode", function () {
var isGregorian = !_this.state.isGregorian;
var nextPropsInputFormat = _this.props.inputFormat;
var nextPropsInputJalaaliFormat = _this.props.inputJalaaliFormat;
_this.setState({
isGregorian: isGregorian,
inputValue: _this.getValue(_this.props.value, isGregorian, _this.props.timePicker)
});
});
defineProperty(assertThisInitialized(_this), "handleFocus", function () {
_this.setOpen(true);
});
defineProperty(assertThisInitialized(_this), "renderInput", function (ref) {
var _this$state = _this.state,
isOpen = _this$state.isOpen,
inputValue = _this$state.inputValue,
isGregorian = _this$state.isGregorian;
var className = classnames(_this.props.className, defineProperty({}, outsideClickIgnoreClass, isOpen));
return /*#__PURE__*/React.createElement("div", {
ref: ref
}, /*#__PURE__*/React.createElement("input", {
placeholder: _this.props.placeholder,
name: _this.props.name,
className: "datepicker-input ".concat(className),
type: "text",
ref: function ref(inst) {
_this.input = inst;
},
onFocus: _this.handleFocus.bind(assertThisInitialized(_this)),
onBlur: _this.hanldeBlur.bind(assertThisInitialized(_this)),
onChange: _this.handleInputChange.bind(assertThisInitialized(_this)),
onClick: _this.handleInputClick.bind(assertThisInitialized(_this)),
value: isGregorian || !_this.props.persianDigits ? inputValue : _this.toPersianDigits(inputValue),
readOnly: _this.props.inputReadOnly === true,
disabled: _this.props.disabled
}));
});
defineProperty(assertThisInitialized(_this), "renderCalendar", function (ref) {
var _this$state2 = _this.state,
momentValue = _this$state2.momentValue,
isGregorian = _this$state2.isGregorian,
TimePicker = _this$state2.timePickerComponent;
var _this$props = _this.props,
onChange = _this$props.onChange,
min = _this$props.min,
max = _this$props.max,
defaultYear = _this$props.defaultYear,
defaultMonth = _this$props.defaultMonth,
styles = _this$props.styles,
calendarContainerProps = _this$props.calendarContainerProps,
ranges = _this$props.ranges,
disableYearSelector = _this$props.disableYearSelector;
return /*#__PURE__*/React.createElement("div", {
ref: ref
}, /*#__PURE__*/React.createElement(Calendar$1, {
toggleMode: _this.toggleMode,
ranges: ranges,
min: min,
max: max,
selectedDay: momentValue,
defaultYear: defaultYear,
defaultMonth: defaultMonth,
onSelect: _this.handleSelectDay.bind(assertThisInitialized(_this)),
onClickOutside: _this.handleClickOutsideCalendar.bind(assertThisInitialized(_this)),
outsideClickIgnoreClass: outsideClickIgnoreClass,
styles: styles,
containerProps: calendarContainerProps,
isGregorian: isGregorian,
calendarClass: _this.props.calendarClass ? _this.props.calendarClass : '',
showToggleButton: _this.props.showToggleButton,
toggleButtonText: _this.props.toggleButtonText,
showTodayButton: _this.props.showTodayButton,
disableYearSelector: disableYearSelector,
timePicker: TimePicker ? /*#__PURE__*/React.createElement(TimePicker, {
outsideClickIgnoreClass: outsideClickIgnoreClass,
isGregorian: isGregorian,
min: min,
max: max,
momentValue: momentValue,
setMomentValue: _this.setMomentValue.bind(assertThisInitialized(_this))
}) : null
}));
});
_this.textInput = React.createRef();
_this.state = {
isOpen: false,
momentValue: _this.props.defaultValue || null,
inputValue: _this.getValue(_this.props.defaultValue, _this.props.isGregorian, _this.props.timePicker),
inputJalaaliFormat: _this.props.inputJalaaliFormat || _this.getInputFormat(false, _this.props.timePicker),
inputFormat: _this.props.inputFormat || _this.getInputFormat(true, _this.props.timePicker),
isGregorian: _this.props.isGregorian,
timePicker: _this.props.timePicker,
timePickerComponent: _this.props.timePicker ? MyTimePicker : undefined
};
return _this;
}
createClass(DatePicker, [{
key: "getInputFormat",
value: function getInputFormat(isGregorian, timePicker) {
if (timePicker) return isGregorian ? 'YYYY/M/D hh:mm A' : 'jYYYY/jM/jD hh:mm A';
return isGregorian ? 'YYYY/M/D' : 'jYYYY/jM/jD';
}
}, {
key: "getValue",
value: function getValue(inputValue, isGregorian, timePicker) {
if (!inputValue) return '';
var inputFormat = this.state.inputFormat;
var inputJalaaliFormat = this.state.inputJalaaliFormat;
if (!inputFormat) inputFormat = this.getInputFormat(isGregorian, timePicker);
if (!inputJalaaliFormat) inputJalaaliFormat = this.getInputFormat(isGregorian, timePicker);
return isGregorian ? inputValue.locale('es').format(inputFormat) : inputValue.locale('fa').format(inputJalaaliFormat);
}
}, {
key: "UNSAFE_componentWillMount",
value: function UNSAFE_componentWillMount() {
if (this.props.value) {
this.setMomentValue(this.props.value);
}
}
}, {
key: "UNSAFE_componentWillReceiveProps",
value: function UNSAFE_componentWillReceiveProps(nextProps) {
if ('value' in nextProps) {
if (nextProps.value === null) {
this.setState({
input: '',
inputValue: ''
});
} else if (typeof nextProps.value === 'undefined' && typeof this.props.value !== 'undefined' || typeof nextProps.value !== 'undefined' && !nextProps.value.isSame(this.props.value)) {
this.setMomentValue(nextProps.value);
}
}
if ('isGregorian' in nextProps && nextProps.isGregorian !== this.props.isGregorian) {
var nextPropsInputFormat = nextProps.inputFormat;
var nextPropsInputJalaaliFormat = nextProps.inputJalaaliFormat;
this.setState({
isGregorian: nextProps.isGregorian,
inputValue: this.getValue(nextProps.value, nextProps.isGregorian, nextProps.timePicker),
inputFormat: nextPropsInputFormat || this.state.inputFormat,
inputJalaaliFormat: nextPropsInputJalaaliFormat || this.state.inputJalaaliFormat
});
}
if ('timePicker' in nextProps && nextProps.timePicker !== this.props.timePicker) {
this.setState({
timePicker: nextProps.timePicker,
timePickerComponent: this.props.timePicker ? MyTimePicker : undefined
});
}
}
}, {
key: "setMomentValue",
value: function setMomentValue(momentValue) {
var _this$state3 = this.state,
inputFormat = _this$state3.inputFormat,
isGregorian = _this$state3.isGregorian,
timePicker = _this$state3.timePicker;
if (this.props.onChange) {
this.props.onChange(momentValue);
}
var inputValue = this.getValue(momentValue, isGregorian, timePicker);
this.setState({
momentValue: momentValue,
inputValue: inputValue
});
}
}, {
key: "handleClickOutsideCalendar",
value: function handleClickOutsideCalendar() {
this.setOpen(false);
}
}, {
key: "toEnglishDigits",
value: function toEnglishDigits(str) {
if (!str) return str;
var regex1 = /[\u0660-\u0669]/g;
var regex2 = /[\u06f0-\u06f9]/g;
return str.replace(regex1, function (c) {
return c.charCodeAt(0) - 0x0660;
}).replace(regex2, function (c) {
return c.charCodeAt(0) - 0x06f0;
});
}
}, {
key: "toPersianDigits",
value: function toPersianDigits(str) {
if (!str) return str;
var regex = /[0-9]/g;
var id = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
return str.replace(regex, function (w) {
return id[+w];
});
}
}, {
key: "handleSelectDay",
value: function handleSelectDay(selectedDay) {
var oldValue = this.state.momentValue;
var momentValue = selectedDay.clone();
if (oldValue) {
momentValue = momentValue.set({
hour: oldValue.hours(),
minute: oldValue.minutes(),
second: oldValue.seconds()
});
}
this.setOpen(false);
this.setMomentValue(momentValue);
}
}, {
key: "handleInputChange",
value: function handleInputChange(event) {
var _this2 = this;
var _this$state4 = this.state,
inputFormat = _this$state4.inputFormat,
inputJalaaliFormat = _this$state4.inputJalaaliFormat,
isGregorian = _this$state4.isGregorian;
var inputValue = this.toEnglishDigits(event.target.value);
var currentInputFormat = isGregorian ? inputFormat : inputJalaaliFormat;
var momentValue = momentJalaali(inputValue, currentInputFormat);
var cursor = event.target.selectionStart;
if (momentValue.isValid()) {
this.setState({
momentValue: momentValue
});
}
this.setState({
inputValue: inputValue
}, function () {
// It cause lose current cursor positon if persian digits is active
// for example it convert 4 to ۴, so the react set cursor position to end of string
if (_this2.props.persianDigits) _this2.input.setSelectionRange(cursor, cursor);
});
if (this.props.onInputChange) {
this.props.onInputChange(event);
}
}
}, {
key: "hanldeBlur",
value: function hanldeBlur(event) {
if (this.props.onChange) {
var _this$state5 = this.state,
inputFormat = _this$state5.inputFormat,
inputJalaaliFormat = _this$state5.inputJalaaliFormat,
isGregorian = _this$state5.isGregorian;
var inputValue = this.toEnglishDigits(event.target.value);
var currentInputFormat = isGregorian ? inputFormat : inputJalaaliFormat;
var momentValue = momentJalaali(inputValue, currentInputFormat);
if (momentValue.isValid()) {
this.props.onChange(this.state.momentValue);
} else if (this.props.setTodayOnBlur) {
this.props.onChange(momentJalaali());
}
}
}
}, {
key: "handleInputClick",
value: function handleInputClick() {
if (!this.props.disabled) {
this.setOpen(true);
}
}
}, {
key: "removeDate",
value: function removeDate() {
var onChange = this.props.onChange;
if (onChange) {
onChange(null);
}
this.setState({
input: '',
inputValue: ''
});
}
}, {
key: "render",
value: function render() {
var _this3 = this;
var isOpen = this.state.isOpen;
return /*#__PURE__*/React.createElement(TetherComponent, {
ref: function ref(tether) {
return _this3.tether = tether;
},
attachment: this.props.tetherAttachment ? this.props.tetherAttachment : 'top center',
constraints: [{
to: 'window',
attachment: 'together'
}],
offset: "-10px -10px",
onResize: function onResize() {
return _this3.tether && _this3.tether.position();
}
/* renderTarget: This is what the item will be tethered to, make sure to attach the ref */
,
renderTarget: function renderTarget(ref) {
return _this3.renderInput(ref);
}
/* renderElement: If present, this item will be tethered to the the component returned by renderTarget */
,
renderElement: function renderElement(ref) {
return isOpen && _this3.renderCalendar(ref);
}
});
}
}]);
return DatePicker;
}(Component);
defineProperty(DatePicker, "propTypes", {
value: PropTypes.object,
defaultValue: PropTypes.object,
onChange: PropTypes.func,
onInputChange: PropTypes.func,
onFocus: PropTypes.func,
onBlur: PropTypes.func,
children: PropTypes.node,
min: PropTypes.object,
max: PropTypes.object,
defaultYear: PropTypes.object,
defaultMonth: PropTypes.object,
inputFormat: PropTypes.string,
inputJalaaliFormat: PropTypes.string,
removable: PropTypes.bool,
styles: PropTypes.object,
calendarStyles: PropTypes.object,
calendarContainerProps: PropTypes.object,
isGregorian: PropTypes.bool,
// jalaali or gregorian
timePicker: PropTypes.bool,
calendarClass: PropTypes.string,
datePickerClass: PropTypes.string,
tetherAttachment: PropTypes.string,
inputReadOnly: PropTypes.bool,
ranges: PropTypes.array,
showToggleButton: PropTypes.bool,
toggleButtonText: PropTypes.any,
showTodayButton: PropTypes.bool,
placeholder: PropTypes.string,
name: PropTypes.string,
persianDigits: PropTypes.bool,
setTodayOnBlur: PropTypes.bool,
disableYearSelector: PropTypes.bool
});
defineProperty(DatePicker, "defaultProps", {
styles: undefined,
calendarContainerProps: {},
isGregorian: true,
timePicker: true,
showTodayButton: true,
placeholder: '',
name: '',
persianDigits: true,
setTodayOnBlur: true,
disableYearSelector: false
});
momentJalaali.loadPersian({
dialect: 'persian-modern'
});
export default DatePicker;
export { Calendar };
|
app/containers/UserContainer/index.js | vinhtran19950804/procure_react | /**
*
* UserContainer
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { compose } from 'redux';
import injectSaga from 'utils/injectSaga';
import injectReducer from 'utils/injectReducer';
import makeSelectUserContainer from './selectors';
import reducer from './reducer';
import saga from './saga';
import User from '../../components/User';
export class UserContainer extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<User {...this.props} />
);
}
}
UserContainer.propTypes = {
dispatch: PropTypes.func.isRequired,
};
const mapStateToProps = createStructuredSelector({
usercontainer: makeSelectUserContainer(),
});
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
const withConnect = connect(mapStateToProps, mapDispatchToProps);
const withReducer = injectReducer({ key: 'userContainer', reducer });
const withSaga = injectSaga({ key: 'userContainer', saga });
export default compose(
withReducer,
withSaga,
withConnect,
)(UserContainer);
|
frontend/src/AddMovie/AddNewMovie/AddNewMovieModalContentConnector.js | geogolem/Radarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { addMovie, setAddMovieDefault } from 'Store/Actions/addMovieActions';
import createDimensionsSelector from 'Store/Selectors/createDimensionsSelector';
import createSystemStatusSelector from 'Store/Selectors/createSystemStatusSelector';
import selectSettings from 'Store/Selectors/selectSettings';
import AddNewMovieModalContent from './AddNewMovieModalContent';
function createMapStateToProps() {
return createSelector(
(state) => state.addMovie,
createDimensionsSelector(),
createSystemStatusSelector(),
(addMovieState, dimensions, systemStatus) => {
const {
isAdding,
addError,
defaults
} = addMovieState;
const {
settings,
validationErrors,
validationWarnings
} = selectSettings(defaults, {}, addError);
return {
isAdding,
addError,
isSmallScreen: dimensions.isSmallScreen,
validationErrors,
validationWarnings,
isWindows: systemStatus.isWindows,
...settings
};
}
);
}
const mapDispatchToProps = {
setAddMovieDefault,
addMovie
};
class AddNewMovieModalContentConnector extends Component {
//
// Listeners
onInputChange = ({ name, value }) => {
this.props.setAddMovieDefault({ [name]: value });
}
onAddMoviePress = () => {
const {
tmdbId,
rootFolderPath,
monitor,
qualityProfileId,
minimumAvailability,
searchForMovie,
tags
} = this.props;
this.props.addMovie({
tmdbId,
rootFolderPath: rootFolderPath.value,
monitor: monitor.value,
qualityProfileId: qualityProfileId.value,
minimumAvailability: minimumAvailability.value,
searchForMovie: searchForMovie.value,
tags: tags.value
});
}
//
// Render
render() {
return (
<AddNewMovieModalContent
{...this.props}
onInputChange={this.onInputChange}
onAddMoviePress={this.onAddMoviePress}
/>
);
}
}
AddNewMovieModalContentConnector.propTypes = {
tmdbId: PropTypes.number.isRequired,
rootFolderPath: PropTypes.object,
monitor: PropTypes.object.isRequired,
qualityProfileId: PropTypes.object,
minimumAvailability: PropTypes.object.isRequired,
searchForMovie: PropTypes.object.isRequired,
tags: PropTypes.object.isRequired,
onModalClose: PropTypes.func.isRequired,
setAddMovieDefault: PropTypes.func.isRequired,
addMovie: PropTypes.func.isRequired
};
export default connect(createMapStateToProps, mapDispatchToProps)(AddNewMovieModalContentConnector);
|
src/routes/dashboard/components/comments.js | yunqiangwu/kmadmin | import React from 'react'
import PropTypes from 'prop-types'
import { Table, Tag } from 'antd'
import { color } from 'utils'
import styles from './comments.less'
const status = {
1: {
color: color.green,
text: 'APPROVED',
},
2: {
color: color.yellow,
text: 'PENDING',
},
3: {
color: color.red,
text: 'REJECTED',
},
}
function Comments ({ data }) {
const columns = [
{
title: 'avatar',
dataIndex: 'avatar',
width: 48,
className: styles.avatarcolumn,
render: text => <span style={{ backgroundImage: `url(${text})` }} className={styles.avatar} />,
}, {
title: 'content',
dataIndex: 'content',
render: (text, it) => (<div>
<h5 className={styles.name}>{it.name}</h5>
<p className={styles.content}>{it.content}</p>
<div className={styles.daterow}>
<Tag color={status[it.status].color}>{status[it.status].text}</Tag>
<span className={styles.date}>{it.date}</span>
</div>
</div>),
},
]
return (
<div className={styles.comments}>
<Table pagination={false} showHeader={false} columns={columns} rowKey={(record, key) => key} dataSource={data.filter((item, key) => key < 3)} />
</div>
)
}
Comments.propTypes = {
data: PropTypes.array,
}
export default Comments
|
src/components/Signin/Signin.js | ihenvyr/react-app | import React from 'react';
import { Link } from 'react-router';
import styles from './Signin.scss';
class Signin extends React.Component {
static propTypes = {
// React.PropTypes.array
// React.PropTypes.bool
// React.PropTypes.func
// React.PropTypes.number
// React.PropTypes.object
// React.PropTypes.string
// React.PropTypes.node // anything that can be rendered
// React.PropTypes.element
// React.PropTypes.instanceOf(MyClass)
// React.PropTypes.oneOf(['Thing 1', 'Thing 2'])
// React.PropTypes.oneOfType([
// React.PropTypes.bool,
// React.PropTypes.string
// ])
// React.PropTypes.arrayOf(React.PropTypes.string)
// React.PropTypes.objectOf(React.PropTypes.string)
// React.PropTypes.shape({
// age: React.PropTypes.number,
// name: React.PropTypes.string
// })
// React.PropTypes.any
};
static defaultProps = {};
state = {};
// componentWillMount() {}
// componentWillUnmount() {}
// componentDidMount() {}
// componentWillReceiveProps(nextProps) {}
// shouldComponentUpdate(nextProps, nextState) {}
// componentWillUpdate(nextProps, nextState) {}
// componentDidUpdate(prevProps, prevState) {}
onSubmit = (event) => {
event.preventDefault();
const { email, password } = event.target;
this.props.userSignin({ email: email.value, password: password.value });
};
render() {
return (
<form action="/signin" method="post" onSubmit={this.onSubmit} className={`ui form ${styles.container}`}>
<div className="field">
<label>Email</label>
<input type="text" name="email" placeholder="" required />
</div>
<div className="field">
<label>Password</label>
<input type="password" name="password" placeholder="" required />
</div>
<button className="ui blue button" type="submit">Sign in</button>
{' '}
|
{' '}
No account yet?
{' '}
<Link to="/signup">Sign up</Link>
</form>
);
}
}
export default Signin;
|
src/svg-icons/hardware/desktop-mac.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareDesktopMac = (props) => (
<SvgIcon {...props}>
<path d="M21 2H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h7l-2 3v1h8v-1l-2-3h7c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 12H3V4h18v10z"/>
</SvgIcon>
);
HardwareDesktopMac = pure(HardwareDesktopMac);
HardwareDesktopMac.displayName = 'HardwareDesktopMac';
HardwareDesktopMac.muiName = 'SvgIcon';
export default HardwareDesktopMac;
|
app/containers/EffectsPage/index.js | Statfine/reactDemo | /**
* Created by easub on 2017/2/16.
*/
import React from 'react';
import { merge } from 'lodash';
import styled from 'styled-components';
const Content = styled.div`
padding-right: 15px;
padding-left: 15px;
margin: 0 auto;
padding-top: 94px;
width: 852px;
`;
const DrawContent = styled.div`
width: 852px;
height: 480px;
background-color: #000;
position: relative;
`;
const ResizeContainer = styled.div`
position: absolute;
display: inline-block;
cursor: move;
border: 1px dashed red;
box-sizing: border-box;
padding: 0;
margin: 0;
top: ${(props) => `${props.top}px`};
left: ${(props) => `${props.left}px`};
height: ${(props) => `${props.height}px`};
width: ${(props) => `${props.width}px`};
`;
const Resize = styled.div`
position: relative;
height: 100%;
width: 100%;
`;
const ResizeCenterP = styled.p`
background-color: rgba(0,0,0,0);
color: : ${(props) => `#${props.color}`};
outline: none;
resize: none;
border: none;
font-size: 14px;
width: 100%;
height: 100%;
padding: 4px;
`;
const TopLeft = styled.span`
position: absolute;
display: block;
width: 24px;
height: 24px;
z-index: 999;
border: 4px solid #fff;
top: -1px;
left: -1px;
cursor: nw-resize;
border-bottom: none;
border-right: none;
`;
const TopRight = styled.span`
position: absolute;
display: block;
width: 24px;
height: 24px;
z-index: 999;
border: 4px solid #fff;
right: -1px;
top: -1px;
cursor: ne-resize;
border-bottom: none;
border-left: none;
`;
const BottomLeft = styled.span`
position: absolute;
display: block;
width: 24px;
height: 24px;
z-index: 999;
border: 4px solid #fff;
left: -1px;
bottom: -1px;
cursor: sw-resize;
border-top: none;
border-right: none;
`;
const BottomRight = styled.span`
position: absolute;
display: block;
width: 24px;
height: 24px;
z-index: 999;
border: 4px solid #fff;
right: -1px;
bottom: -1px;
cursor: se-resize;
border-top: none;
border-left: none;
`;
export default class EffectsPage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
state = {
topLeft: { x: 0, y: 0 },
topRight: { x: 200, y: 0 },
bottomLeft: { x: 0, y: 100 },
bottomRight: { x: 200, y: 100 },
textValue: '',
color: '#fff',
};
componentDidMount() {
this.minLeft = this.drawContent.offsetLeft;
this.minTop = this.drawContent.offsetTop;
window.addEventListener('resize', this.handleResize);
window.addEventListener('mousemove', this.handleMouseMove);
window.addEventListener('mouseup', this.handleMouseUp);
}
maxLength = 30;
minLeft= 0;
minTop = 0;
moveFlag = ''; // topLeft; topRight; bottomLeft; bottomRight; center
centerPostiosX = 0;
centerPostiosY = 0;
centerTopLeft = {};
centerTopRight = {};
centerBottomLeft = {};
centerBottomRight = {};
handleResize = () => {
this.minLeft = this.drawContent.offsetLeft;
this.minTop = this.drawContent.offsetTop;
};
handleMouseMove = (event) => {
if (this.moveFlag === 'center') {
const { topLeft, topRight, bottomLeft, bottomRight } = this.state;
const moveX = event.pageX - this.centerPostiosX;
const moveY = event.pageY - this.centerPostiosY;
if (this.centerTopLeft.x + moveX >= 0 && this.centerTopRight.x + moveX <= this.drawContent.offsetWidth &&
this.centerBottomLeft.x + moveX >= 0 && this.centerBottomRight.x + moveX <= this.drawContent.offsetWidth) {
topLeft.x = this.centerTopLeft.x + moveX;
topRight.x = this.centerTopRight.x + moveX;
bottomLeft.x = this.centerBottomLeft.x + moveX;
bottomRight.x = this.centerBottomRight.x + moveX;
}
if (this.centerTopLeft.y + moveY >= 0 && this.centerTopRight.y + moveY >= 0 &&
this.centerBottomLeft.y + moveY <= this.drawContent.offsetHeight && this.centerBottomRight.y + moveY <= this.drawContent.offsetHeight) {
topLeft.y = this.centerTopLeft.y + moveY;
topRight.y = this.centerTopRight.y + moveY;
bottomLeft.y = this.centerBottomLeft.y + moveY;
bottomRight.y = this.centerBottomRight.y + moveY;
}
this.setState({
topLeft: merge({}, topLeft),
topRight: merge({}, topRight),
bottomLeft: merge({}, bottomLeft),
bottomRight: merge({}, bottomRight),
});
}
if (this.moveFlag === 'topLeft') {
const { topLeft, topRight, bottomLeft } = this.state;
const moveX = event.pageX - this.minLeft;
const moveY = event.pageY - this.minTop;
if (event.pageX >= this.minLeft && event.pageX <= ((topRight.x + this.minLeft) - this.maxLength)) {
topLeft.x = moveX;
bottomLeft.x = moveX;
}
if (event.pageY >= this.minTop && event.pageY <= ((bottomLeft.y + this.minTop) - this.maxLength)) {
topLeft.y = moveY;
topRight.y = moveY;
}
this.setState({
topLeft: merge({}, topLeft),
topRight: merge({}, topRight),
bottomLeft: merge({}, bottomLeft),
});
}
if (this.moveFlag === 'topRight') {
const { topLeft, topRight, bottomRight } = this.state;
const moveX = event.pageX - this.minLeft;
const moveY = event.pageY - this.minTop;
if (event.pageX >= topLeft.x + this.minLeft + this.maxLength && event.pageX <= this.minLeft + this.drawContent.offsetWidth) {
topRight.x = moveX;
bottomRight.x = moveX;
}
if (event.pageY >= this.minTop && event.pageY <= ((bottomRight.y + this.minTop) - this.maxLength)) {
topRight.y = moveY;
topLeft.y = moveY;
}
this.setState({
topLeft: merge({}, topLeft),
topRight: merge({}, topRight),
bottomRight: merge({}, bottomRight),
});
}
if (this.moveFlag === 'bottomLeft') {
const { topLeft, bottomLeft, bottomRight } = this.state;
const moveX = event.pageX - this.minLeft;
const moveY = event.pageY - this.minTop;
if (event.pageX >= this.minLeft && event.pageX <= ((bottomRight.x + this.minLeft) - this.maxLength)) {
bottomLeft.x = moveX;
topLeft.x = moveX;
}
if (event.pageY >= topLeft.y + this.minTop + this.maxLength && event.pageY <= this.minTop + this.drawContent.offsetHeight) {
bottomLeft.y = moveY;
bottomRight.y = moveY;
}
this.setState({
bottomRight: merge({}, bottomRight),
bottomLeft: merge({}, bottomLeft),
topLeft: merge({}, topLeft),
});
}
if (this.moveFlag === 'bottomRight') {
const { bottomRight, bottomLeft, topRight } = this.state;
const moveX = event.pageX - this.minLeft;
const moveY = event.pageY - this.minTop;
if (event.pageX >= bottomLeft.x + this.minLeft + this.maxLength && event.pageX <= this.minLeft + this.drawContent.offsetWidth) {
bottomRight.x = moveX;
topRight.x = moveX;
}
if (event.pageY >= topRight.y + this.minTop + this.maxLength && event.pageY <= this.minTop + this.drawContent.offsetHeight) {
bottomRight.y = moveY;
bottomLeft.y = moveY;
}
this.setState({
bottomRight: merge({}, bottomRight),
bottomLeft: merge({}, bottomLeft),
topRight: merge({}, topRight),
});
}
};
// event 整体对象,获取原始位置
handleMouseDown = (position, event) => {
this.moveFlag = position;
if (event) {
const { topLeft, topRight, bottomLeft, bottomRight } = this.state;
this.centerPostiosX = event.pageX;
this.centerPostiosY = event.pageY;
this.centerTopLeft = topLeft;
this.centerTopRight = topRight;
this.centerBottomLeft = bottomLeft;
this.centerBottomRight = bottomRight;
}
};
handleMouseUp = () => {
this.moveFlag = '';
};
/* global someFunction prismplayer:true */
/* eslint no-undef: "error" */
handleSetupLiveVideo = () => {
const liveUrl = this.inputSearch.value;
this.playLive = new prismplayer({
id: 'video', // 容器id
source: liveUrl, // 视频url 支持互联网可直接访问的视频地址
autoplay: true, // 自动播放
width: '100%', // 播放器宽度
height: '100%', // 播放器高度
});
}
// 边框 -2 -4 +1 (内边距2px 宽度4 虚线边框1)
render() {
const { topLeft, topRight, bottomLeft, bottomRight, textValue, color } = this.state;
return (
<Content>
<div>
{`x:${topLeft.x}`}<br />
{`y:${topLeft.y}`}<br />
{`width:${Math.max(topRight.x - topLeft.x, bottomRight.x - bottomLeft.x)}`}<br />
{`height:${Math.max(bottomLeft.y - topLeft.y, bottomRight.y - topRight.y)}`}
</div>
<DrawContent innerRef={(c) => { this.drawContent = c; }}>
<div style={{ width: '852px', height: '480px', display: 'block' }}>
<div ref={(c) => { this.video = c; }} id="video"></div>
</div>
<ResizeContainer
top={topLeft.y}
left={topLeft.x}
height={Math.max(bottomLeft.y - topLeft.y, bottomRight.y - topRight.y)}
width={Math.max(topRight.x - topLeft.x, bottomRight.x - bottomLeft.x)}
>
<Resize>
<ResizeCenterP color={color} onMouseDown={(e) => this.handleMouseDown('center', e)}>{textValue}</ResizeCenterP>
<TopLeft onMouseDown={() => this.handleMouseDown('topLeft')} />
<TopRight onMouseDown={() => this.handleMouseDown('topRight')} />
<BottomLeft onMouseDown={() => this.handleMouseDown('bottomLeft')} />
<BottomRight onMouseDown={() => this.handleMouseDown('bottomRight')} />
</Resize>
</ResizeContainer>
</DrawContent>
</Content>
);
}
}
|
app/javascript/mastodon/features/account_timeline/index.js | mstdn-jp/mastodon | import React from 'react';
import { connect } from 'react-redux';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { fetchAccount } from '../../actions/accounts';
import { expandAccountFeaturedTimeline, expandAccountTimeline } from '../../actions/timelines';
import StatusList from '../../components/status_list';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import HeaderContainer from './containers/header_container';
import ColumnBackButton from '../../components/column_back_button';
import { List as ImmutableList } from 'immutable';
import ImmutablePureComponent from 'react-immutable-pure-component';
const mapStateToProps = (state, { params: { accountId }, withReplies = false }) => {
const path = withReplies ? `${accountId}:with_replies` : accountId;
return {
statusIds: state.getIn(['timelines', `account:${path}`, 'items'], ImmutableList()),
featuredStatusIds: withReplies ? ImmutableList() : state.getIn(['timelines', `account:${accountId}:pinned`, 'items'], ImmutableList()),
isLoading: state.getIn(['timelines', `account:${path}`, 'isLoading']),
hasMore: state.getIn(['timelines', `account:${path}`, 'hasMore']),
};
};
@connect(mapStateToProps)
export default class AccountTimeline extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
statusIds: ImmutablePropTypes.list,
featuredStatusIds: ImmutablePropTypes.list,
isLoading: PropTypes.bool,
hasMore: PropTypes.bool,
withReplies: PropTypes.bool,
};
componentWillMount () {
const { params: { accountId }, withReplies } = this.props;
this.props.dispatch(fetchAccount(accountId));
if (!withReplies) {
this.props.dispatch(expandAccountFeaturedTimeline(accountId));
}
this.props.dispatch(expandAccountTimeline(accountId, { withReplies }));
}
componentWillReceiveProps (nextProps) {
if ((nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) || nextProps.withReplies !== this.props.withReplies) {
this.props.dispatch(fetchAccount(nextProps.params.accountId));
if (!nextProps.withReplies) {
this.props.dispatch(expandAccountFeaturedTimeline(nextProps.params.accountId));
}
this.props.dispatch(expandAccountTimeline(nextProps.params.accountId, { withReplies: nextProps.params.withReplies }));
}
}
handleLoadMore = maxId => {
this.props.dispatch(expandAccountTimeline(this.props.params.accountId, { maxId, withReplies: this.props.withReplies }));
}
render () {
const { statusIds, featuredStatusIds, isLoading, hasMore } = this.props;
if (!statusIds && isLoading) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
return (
<Column>
<ColumnBackButton />
<StatusList
prepend={<HeaderContainer accountId={this.props.params.accountId} />}
scrollKey='account_timeline'
statusIds={statusIds}
featuredStatusIds={featuredStatusIds}
isLoading={isLoading}
hasMore={hasMore}
onLoadMore={this.handleLoadMore}
/>
</Column>
);
}
}
|
src/js/index.js | ClubExpressions/poc-expression.club | import { AppContainer } from 'react-hot-loader';
import React from 'react';
import ReactDOM from 'react-dom';
import Main from './main';
const rootEl = document.getElementById('app');
ReactDOM.render(
<AppContainer>
<Main />
</AppContainer>,
rootEl
);
if (module.hot) {
module.hot.accept('./main', () => {
const NextMain = require('./main').default;
ReactDOM.render(
<AppContainer>
<NextMain />
</AppContainer>,
rootEl
);
});
}
|
src/components/form.js | frig-js/frig | import React from 'react'
import AbstractForm from './abstract_form.js'
/*
* A JSX-compatible React DOM Component.
* Form should be used as the top level component above any other frig
* components.
*/
export default class Form extends AbstractForm {
displayName = 'Form'
componentWillMount() {
if (!this.props.data) {
throw new Error(`<Form data={} /> must always be defined, got: ${this.props.data}`)
}
if (!this.props.onChange) {
throw new Error(`<Form onChange={} /> must always be defined, got: ${this.props.onChange}`)
}
}
static propTypes = {
data: React.PropTypes.object.isRequired,
onChange: React.PropTypes.func.isRequired,
errors: React.PropTypes.object.isRequired,
saved: React.PropTypes.object.isRequired,
theme: React.PropTypes.object.isRequired,
typeMapping: React.PropTypes.objectOf(React.PropTypes.string),
layout: React.PropTypes.string.isRequired,
align: React.PropTypes.string.isRequired,
// Callbacks
onSubmit: React.PropTypes.func,
}
static defaultProps = {
errors: {},
saved: {},
theme: undefined,
typeMapping: {},
layout: 'vertical',
align: 'left',
onSubmit() {},
}
static childContextTypes = AbstractForm.childContextTypes
render() {
const ThemedForm = this.props.theme.Form
return (
<ThemedForm
{...this._themedFormProps()}
ref="form"
>
{this.props.children}
</ThemedForm>
)
}
}
|
client/aframe/components/WarScene.js | shanemcgraw/PoopVR | import React from 'react';
class WarScene extends React.Component {
constructor(props) {
super(props);
}
render () {
return (
<a-scene>
<a-assets>
<a-asset-item id='fighterDae' src='/assets/fighterPlane/model.dae' />
<a-asset-item id='stall' src='/assets/Toilet_Stall.dae' />
<a-asset-item id='tallGrass' src='/assets/tallGrass.dae' />
<audio id='siren' src='assets/siren.mp3' />
<audio id='planeSound' src='assets/planeSound.mp3' />
<audio id='battle' src='assets/battle.mp3' />
<img id='sky' src='/assets/gloomySky.jpg' />
<img id='ground' src='/assets/redDirt.jpg' />
</a-assets>
<a-sky src='#sky' rotation='60 0 0' />
<a-plane id='ground' src='#ground' material='side:double'
position='0 0 -3' rotation='-90 0 0' width='10' height='10' />
<a-entity position='0 1.5 0'>
<a-camera id='camera' wasd-controls-enabled='true'/>
</a-entity>
<a-entity position='-47 25 0' rotation='0 180 0'>
<a-collada-model sound='src:assets/planeSound.mp3; autoplay:true; loop:true; volume:10;'
src='#fighterDae' position='65 2 0' rotation='10 0 26'/>
<a-collada-model src='#fighterDae' position='45 0 0' rotation='10 0 20'/>
<a-animation
begin='5000'
attribute='rotation'
dur='8000'
from='0 180 0'
to='0 -180 0'
repeat='indefinite'
easing='linear'
/>
</a-entity>
<a-entity id='siren' position='30 3 -25' sound='src:assets/siren.mp3; autoplay:true; loop:true;' />
<a-entity id='battle' position='-10 2 -5' sound='src:assets/battle.mp3; autoplay:true; loop:true;' />
<a-collada-model scale='2.3 1.5 2' src='#tallGrass' position='-1.5 -0.8 -1.5' />
<a-collada-model scale='2.3 1.5 2' src='#stall' position='1.2 0 1' rotation='0 180 0'/>
<a-light type='ambient' color='#f6da80'></a-light>
<a-light type='point' color='#fff' intensity='0' position='-3 0.1 -15'>
<a-animation
begin='15000'
attribute='intensity'
dur='500'
from='100'
to='0'
repeat='indefinite'
easing='ease-out'
/>
</a-light>
<a-light type='point' color='#fff' intensity='0' position='1 5 5'>
<a-animation
begin='12000'
attribute='intensity'
dur='500'
from='100'
to='0'
repeat='indefinite'
easing='ease-out'
/>
</a-light>
</a-scene>
);
}
};
module.exports = WarScene;
|
src/shared/components/modal/modal.js | miaket/operationcode_frontend | import React from 'react';
import PropTypes from 'prop-types';
import ReactModal from 'react-modal';
import Section from 'shared/components/section/section';
import styles from './modal.css';
const Modal = ({
isOpen, title, onRequestClose, children
}) => (
<ReactModal
isOpen={isOpen}
contentLabel={title}
shouldCloseOnOverlayClick
onRequestClose={onRequestClose}
>
<Section title={title} theme="white" className={styles.modal}>
<div className={styles.scrollable}>
{children}
</div>
</Section>
<button className={styles.close} onClick={() => onRequestClose()} />
</ReactModal>
);
Modal.propTypes = {
children: PropTypes.element,
isOpen: PropTypes.bool,
onRequestClose: PropTypes.func,
title: PropTypes.string
};
Modal.defaultProps = {
children: <span />,
isOpen: false,
onRequestClose: () => {},
title: ''
};
export default Modal;
|
src/utils/ValidComponentChildren.js | aabenoja/react-bootstrap | import React from 'react';
/**
* Maps children that are typically specified as `props.children`,
* but only iterates over children that are "valid components".
*
* The mapFunction provided index will be normalised to the components mapped,
* so an invalid component would not increase the index.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} mapFunction.
* @param {*} mapContext Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapValidComponents(children, func, context) {
let index = 0;
return React.Children.map(children, function (child) {
if (React.isValidElement(child)) {
let lastIndex = index;
index++;
return func.call(context, child, lastIndex);
}
return child;
});
}
/**
* Iterates through children that are typically specified as `props.children`,
* but only iterates over children that are "valid components".
*
* The provided forEachFunc(child, index) will be called for each
* leaf child with the index reflecting the position relative to "valid components".
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc.
* @param {*} forEachContext Context for forEachContext.
*/
function forEachValidComponents(children, func, context) {
let index = 0;
return React.Children.forEach(children, function (child) {
if (React.isValidElement(child)) {
func.call(context, child, index);
index++;
}
});
}
/**
* Count the number of "valid components" in the Children container.
*
* @param {?*} children Children tree container.
* @returns {number}
*/
function numberOfValidComponents(children) {
let count = 0;
React.Children.forEach(children, function (child) {
if (React.isValidElement(child)) { count++; }
});
return count;
}
/**
* Determine if the Child container has one or more "valid components".
*
* @param {?*} children Children tree container.
* @returns {boolean}
*/
function hasValidComponent(children) {
let hasValid = false;
React.Children.forEach(children, function (child) {
if (!hasValid && React.isValidElement(child)) {
hasValid = true;
}
});
return hasValid;
}
export default {
map: mapValidComponents,
forEach: forEachValidComponents,
numberOf: numberOfValidComponents,
hasValidComponent: hasValidComponent
};
|
src/App.js | Minishlink/DailyScrum | // @flow
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import codePush from 'react-native-code-push';
import Scenes from './navigation/Scenes';
import createStore from './modules/store';
class App extends Component<void, State> {
state = {
store: null,
};
componentDidMount() {
createStore().then(({ store }) => this.setState({ store }));
}
render() {
return this.state.store ? (
<Provider store={this.state.store}>
<Scenes />
</Provider>
) : null;
}
}
type State = {
store: any,
};
export default (!__DEV__ ? codePush()(App) : App);
|
js/app/categories/components.js | monetario/web |
'use strict';
import React from 'react';
import {Router, Route, Link, History} from 'react-router'
import Reflux from 'reflux';
import classNames from 'classnames';
import Moment from 'moment';
import Store from './store';
import Actions from './actions';
import CategoryIcon from '../../components/category_icon';
var Category = React.createClass({
mixins: [History],
handleCategoryClick(e) {
e.preventDefault();
this.history.pushState(null, `/p/category/${this.props.category.id}/`, {});
},
render() {
let category = this.props.category;
return (
<tr onClick={this.handleCategoryClick}>
<td><CategoryIcon category={category} /> {category.name}</td>
<td>
{category.category_type.title}
</td>
</tr>
);
}
});
var Categories = React.createClass({
mixins: [History],
handleNextPage(e) {
e.preventDefault();
if (this.props.meta.next_url) {
//this.history.pushState(null, `/p/categories/`, {page: 2});
Actions.loadUrl(this.props.meta.next_url);
}
},
handlePrevPage(e) {
e.preventDefault();
if (this.props.meta.prev_url) {
//this.history.pushState(null, `/p/categories/`, {page: 2});
Actions.loadUrl(this.props.meta.prev_url);
}
},
renderPageCounters() {
let total = this.props.meta.total;
let per_page = this.props.meta.per_page;
let page = this.props.meta.page;
if (total === 0) {
return <span></span>;
}
let first_item = page * per_page - per_page + 1;
let last_item = (page * per_page <= total) ? page * per_page : total;
return (
<span> {first_item} - {last_item} / {total} </span>
);
},
render() {
let nextPageClassName = classNames({
'btn btn-default btn-flat': true,
'disabled': this.props.meta.next_url === null
});
let prevPageClassName = classNames({
'btn btn-default btn-flat': true,
'disabled': this.props.meta.prev_url === null
});
return (
<div className="row">
<div className="col-md-12">
<div className="box box-primary">
<div className="box-header with-border">
<h3 className="box-title">Categories</h3>
<div className="box-tools">
<div className="input-group" style={{width: "75px"}}>
<div className="input-group-btn">
<Link to="/p/category/" className="btn btn-success btn-flat">
<i className="fa fa-plus"></i> New Category
</Link>
</div>
</div>
</div>
</div>
<div className="box-body no-padding">
<div className="mailbox-controls">
<div className="btn-group"></div>
<div className="pull-right">
{this.renderPageCounters()}
<div className="btn-group">
<button className={prevPageClassName} onClick={this.handlePrevPage}>
<i className="fa fa-chevron-left"></i>
</button>
<button className={nextPageClassName} onClick={this.handleNextPage}>
<i className="fa fa-chevron-right"></i>
</button>
</div>
</div>
</div>
<div className="table-responsive mailbox-messages">
<table className="table table-hover table-striped">
<thead>
<tr>
<th className="mailbox-star">Name</th>
<th className="mailbox-name">Category type</th>
</tr>
</thead>
<tbody>
{this.props.categories.map((category) => {
return <Category key={`category_${category.id}`} category={category}/>;
})}
</tbody>
</table>
</div>
</div>
<div className="box-footer no-padding">
<div className="mailbox-controls">
<div className="btn-group"></div>
<div className="pull-right">
{this.renderPageCounters()}
<div className="btn-group">
<button className={prevPageClassName} onClick={this.handlePrevPage}>
<i className="fa fa-chevron-left"></i>
</button>
<button className={nextPageClassName} onClick={this.handleNextPage}>
<i className="fa fa-chevron-right"></i>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
});
export default Categories;
|
client/src/components/helpers/SkeletonSprite.js | HKuz/FreeCodeCamp | import React from 'react';
import styles from './skeletonStyles';
function SkeletonSprite() {
return (
<div className='sprite-container'>
<style dangerouslySetInnerHTML={{ __html: styles }} />
<svg className='sprite-svg'>
<rect
className='sprite'
fill='#ccc'
height='100%'
stroke='#ccc'
width='2px'
x='0'
y='0'
/>
</svg>
</div>
);
}
SkeletonSprite.displayName = 'SkeletonSprite';
export default SkeletonSprite;
|
client/admin/viewLogs/ViewLogsRoute.js | Sing-Li/Rocket.Chat | import React from 'react';
import NotAuthorizedPage from '../../components/NotAuthorizedPage';
import { usePermission } from '../../contexts/AuthorizationContext';
import ViewLogs from './ViewLogs';
export default function ViewLogsRoute() {
const canViewLogs = usePermission('view-logs');
if (!canViewLogs) {
return <NotAuthorizedPage />;
}
return <ViewLogs />;
}
|
packages/wix-style-react/test/utils/visual/utils.js | wix/wix-style-react | import allComponents from '../../../autodocs-registry/autodocs-registry.json';
import { storiesOf } from '@storybook/react';
import React from 'react';
import { Layout, Cell } from '../../../src/Layout';
import Tooltip from '../../../src/Tooltip';
function getTestValues(
{ type, required, defaultValue },
{ skipUndefinedValue },
) {
const testValues = [];
if (!skipUndefinedValue && !required && !defaultValue) {
testValues.push(undefined);
}
switch (type.name) {
case 'bool':
testValues.push(false, true);
break;
case 'string':
testValues.push('Hello World');
break;
case 'number':
testValues.push(5);
break;
case 'enum':
type.value.forEach(value => {
if (value.computed) {
testValues.push(value.value);
} else {
// eslint-disable-next-line no-eval
testValues.push(eval(value.value));
}
});
break;
default:
}
return testValues;
}
function getPropsPermutations(componentName, options) {
const { props } = options;
let permutations = [];
const component = allComponents[componentName];
const propsMap = {};
props.forEach(propName => {
if (typeof propName === 'string') {
if (!component.props[propName])
throw new Error(
`prop ${propName} does not exist in component ${componentName}`,
);
propsMap[propName] = getTestValues(component.props[propName], options);
} else if (typeof propName === 'object') {
if (!component.props[propName.name])
throw new Error(
`prop ${propName} does not exist in component ${componentName}`,
);
propsMap[propName.name] = propName.values;
}
});
Object.keys(propsMap).forEach(key => {
if (permutations.length === 0) {
propsMap[key].forEach(value => permutations.push({ [key]: value }));
} else {
const arr = [];
propsMap[key].forEach(value =>
permutations.forEach(group => arr.push({ ...group, [key]: value })),
);
permutations = arr;
}
});
return permutations;
}
/**
* Create a story of props permutations
* @param Story - A renderable node
* @param Component - The component class
* @param options - {
* props - string[] - Names of the props to test
* skipUndefinedValue - boolean - If true, will not test undefined values
* }
*/
export const storyOfAllPermutations = (Story, Component, options = {}) => {
const permutations = getPropsPermutations(Component.displayName, options);
const {
storyName = 'Props Permutations',
testWithTheme = i => i,
themeName,
} = options;
storiesOf(
`${themeName ? `${themeName}|` : ''}${Component.displayName}`,
module,
).add(storyName, () =>
testWithTheme(
<Layout>
{permutations.map((props, key) => (
<Cell key={key}>
<Layout>
<Cell span={1}>
<Tooltip content={JSON.stringify(props)}>
<span>{key}</span>
</Tooltip>
</Cell>
<Cell span={11}>
<Story {...props} />
</Cell>
</Layout>
</Cell>
))}
</Layout>,
),
);
};
/** A simple wait function to test components with animations */
export const wait = timeToDelay =>
new Promise(resolve => setTimeout(resolve, timeToDelay));
|
actor-apps/app-web/src/app/components/sidebar/RecentSectionItem.react.js | Jeremy-Meng/actor-platform | import React from 'react';
import classNames from 'classnames';
import DialogActionCreators from 'actions/DialogActionCreators';
import DialogStore from 'stores/DialogStore';
import AvatarItem from 'components/common/AvatarItem.react';
class RecentSectionItem extends React.Component {
static propTypes = {
dialog: React.PropTypes.object.isRequired
};
constructor(props) {
super(props);
}
onClick = () => {
DialogActionCreators.selectDialogPeer(this.props.dialog.peer.peer);
}
render() {
const dialog = this.props.dialog,
selectedDialogPeer = DialogStore.getSelectedDialogPeer();
let isActive = false,
title;
if (selectedDialogPeer) {
isActive = (dialog.peer.peer.id === selectedDialogPeer.id);
}
if (dialog.counter > 0) {
const counter = <span className="counter">{dialog.counter}</span>;
const name = <span className="col-xs title">{dialog.peer.title}</span>;
title = [name, counter];
} else {
title = <span className="col-xs title">{dialog.peer.title}</span>;
}
let recentClassName = classNames('sidebar__list__item', 'row', {
'sidebar__list__item--active': isActive,
'sidebar__list__item--unread': dialog.counter > 0
});
return (
<li className={recentClassName} onClick={this.onClick}>
<AvatarItem image={dialog.peer.avatar}
placeholder={dialog.peer.placeholder}
size="tiny"
title={dialog.peer.title}/>
{title}
</li>
);
}
}
export default RecentSectionItem;
|
src/components/Lobby/Admin/index.js | socialgorithm/ultimate-ttt-web | import React from 'react';
import { withRouter } from 'react-router-dom';
import {
Icon,
Container,
Message,
Loader,
Button,
Segment,
Grid,
List,
Label,
Form,
Dropdown, Popup
} from 'semantic-ui-react';
import classNames from 'classnames';
import Tournament from '../Tournament'
class LobbyAdmin extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
admin: false,
availableGames: [],
lobby: {
token: null,
players: [],
tournament: null,
},
tournamentOptions: {
gameAddress: null,
timeout: 100,
numberOfGames: 50,
type: 'DoubleElimination',
autoPlay: false
},
update: 0, // since we are not using immutable data structures (yet), bump this when making a deep change
activePlayers: [],
activePlayersDrop: false,
connectedPlayersDrop: false,
showTournament: true,
};
}
componentDidMount() {
this.props.socket.socket.on('connected', data => {
const lobby = data.lobby;
if (lobby.token !== this.state.lobby.token) {
return;
}
let activePlayers = this.state.activePlayers;
if (this.state.lobby.players.length === this.state.activePlayers.length) {
activePlayers = lobby.players.slice();
}
console.log('connected', lobby);
this.setState({
lobby, activePlayers
});
});
this.props.socket.socket.on('lobby disconnected', data => {
const lobby = data.payload.lobby;
if (lobby.token !== this.state.lobby.token) {
return;
}
console.log('lobby disconnected', lobby);
this.setState({
lobby,
});
});
this.props.socket.emit('lobby join', {
token: this.token(),
spectating: true,
});
this.props.socket.socket.on('lobby joined', data => {
const {lobby, isAdmin} = data;
this.setState({
admin: isAdmin,
lobby,
showTournament: true,
});
});
this.props.socket.socket.on("GameList", data => {
this.setState({availableGames: data});
});
this.props.socket.socket.on('lobby tournament started', data => {
if (!data.tournament) {
return;
}
let newLobby = Object.assign({}, this.state.lobby);
newLobby.tournament = data.tournament;
console.log('lobby tournament started', newLobby);
this.setState({lobby: newLobby});
});
this.props.socket.socket.on('lobby tournament continued', data => {
if (!data.tournament) {
return;
}
let newLobby = Object.assign({}, this.state.lobby);
newLobby.tournament = data.tournament;
console.log('lobby tournament continued', newLobby);
this.setState({lobby: newLobby});
});
this.props.socket.socket.on('lobby player disconnected', data => {
if (!data.lobby) {
return;
}
console.log('lobby player disconnected', data.lobby);
this.setState({
lobby: data.lobby,
});
this.ensureActivePlayersConnected();
});
this.props.socket.socket.on('lobby player kicked', data => {
if (!data.lobby) {
return;
}
console.log('lobby player kicked', data.lobby);
this.setState({
lobby: data.lobby,
});
this.ensureActivePlayersConnected();
});
this.props.socket.socket.on('lobby player banned', data => {
if (!data.lobby) {
return;
}
console.log('lobby player banned', data.lobby);
this.setState({
lobby: data.lobby,
});
this.ensureActivePlayersConnected();
});
this.props.socket.socket.on('tournament stats', data => {
const lobby = this.state.lobby;
if (lobby.tournament && data) {
lobby.tournament = data;
console.log('tournament stats', lobby);
this.setState({
lobby,
update: this.state.update + 1,
});
}
});
}
startTournament = () => {
this.props.socket.socket.emit('lobby tournament start', {
token: this.state.lobby.token,
options: this.state.tournamentOptions,
players: this.state.activePlayers.map(p => p.token)
});
this.setState({showTournament: true});
};
token = () => this.props.match.params.name;
updateOption = (field) => (event, data) => {
const updatedOptions = this.state.tournamentOptions;
updatedOptions[field] = data.value;
this.setState({
tournamentOptions: updatedOptions,
update: this.state.update + 1,
});
};
updateTypeOption = (event, data) => {
const updatedOptions = this.state.tournamentOptions;
updatedOptions.type = data.value;
updatedOptions.autoPlay = data.value === 'FreeForAll';
this.setState({
tournamentOptions: updatedOptions,
update: this.state.update + 1,
});
};
updateCheckedOption = (field) => (event, data) => {
const updatedOptions = this.state.tournamentOptions;
updatedOptions[field] = data.checked;
this.setState({
tournamentOptions: updatedOptions,
update: this.state.update + 1,
});
};
kickPlayer = (token) => {
this.props.socket.socket.emit('lobby player kick', {
lobbyToken: this.state.lobby.token,
playerToken: token
});
this.removeActivePlayer(token);
};
banPlayer = (token) => {
this.props.socket.socket.emit('lobby player ban', {
lobbyToken: this.state.lobby.token,
playerToken: token
});
this.removeActivePlayer(token);
};
ensureActivePlayersConnected = () => {
const activePlayers = [...this.state.activePlayers];
this.setState({
activePlayers: activePlayers.filter(activePlayer => this.state.lobby.players.indexOf(activePlayer) !== -1 ),
});
}
addActivePlayer = (token) => {
const activePlayers = [...this.state.activePlayers];
if (!activePlayers.find(player => player === token)) {
const player = this.state.lobby.players.find(player => player === token);
if (player) {
activePlayers.push(player);
this.setState({
activePlayers,
});
}
}
}
removeActivePlayer = (token) => {
const index = this.state.activePlayers.indexOf(token);
if (index > -1) {
const activePlayers = [...this.state.activePlayers];
activePlayers.splice(index, 1);
this.setState({
activePlayers,
});
}
};
onDragPlayerStart = (token, e) => {
e.dataTransfer.setData("text/plain", token);
e.dataTransfer.effectAllowed = 'move';
};
onDragPlayerDrop = (e, type) => {
e.preventDefault();
const token = e.dataTransfer.getData("text");
if (type === 'active') {
this.addActivePlayer(token);
} else {
this.removeActivePlayer(token);
}
this.setState({
activePlayersDrop: false,
connectedPlayersDrop: false,
});
};
onDragPlayerMouseMove = (e, type, playersDrop) => {
e.preventDefault();
const key = type + 'PlayersDrop';
this.setState({
[key]: playersDrop,
});
};
onDragPlayerOver = (e, type) => {
e.preventDefault();
};
backToLobby = () => {
this.setState({showTournament: false});
};
continueMatches = () => {
this.props.socket.socket.emit('lobby tournament continue', {
token: this.state.lobby.token
});
};
renderLoader = () => {
if (this.state.admin) {
return null;
}
return (
<div style={ { textAlign: 'center', color: '#999' } }>
<Loader
inline
active
content='Waiting for game to start...'
/>
</div>
);
};
renderAdmin = () => {
if (!this.state.admin) {
return null;
}
const availableGames = this.state.availableGames.map(game => {
return {
text: `${!game.healthy ? '[UNHEALTHY] ' : '' }${game.info.name}`,
value: game.address,
title: `${game.address}`,
icon: game.healthy ? 'green circle' : 'yellow warning sign',
disabled: !game.healthy,
}
});
const tournamentModes = [
{
text: 'Free For All',
value: 'FreeForAll',
title: 'Everyone plays everyone else',
},
{
text: 'Double Elimination',
value: 'DoubleElimination',
title: 'League Mode, a player gets kicked out when losing two games',
},
];
const title = (this.state.lobby.players.length < 2 || this.invalidGameServerSelected()) ? 'Atleast two players + healthy game server connection required' : 'Start the match';
return (
<Grid columns={ 1 }>
<Grid.Row>
<Grid.Column>
<h3>Tournament Settings:</h3>
<Form size='small'>
<Form.Select
label='Game'
options={ availableGames }
className={ this.invalidGameServerSelected() ? 'error' : '' }
value={ this.state.tournamentOptions.gameAddress }
onChange={ this.updateOption('gameAddress') }
/>
<Form.Group widths='equal'>
<Form.Input
label='Timeout (Per Move, in ms)'
type='number'
placeholder='100'
value={ this.state.tournamentOptions.timeout }
onChange={ this.updateOption('timeout') }
/>
<Form.Input
label='Number of Games per Match'
type='number'
placeholder='10'
value={ this.state.tournamentOptions.numberOfGames }
onChange={ this.updateOption('numberOfGames') }
/>
</Form.Group>
<Form.Select
label='Tournament Type'
options={ tournamentModes }
value={ this.state.tournamentOptions.type }
onChange={ this.updateTypeOption }
/>
<Form.Checkbox
label='Automatically play next set of games'
checked={ this.state.tournamentOptions.autoPlay }
onChange={ this.updateCheckedOption('autoPlay') }
/>
<Button
primary
icon='play'
title={ title }
disabled={ this.state.activePlayers.length < 2 || this.invalidGameServerSelected() }
content='Start Game'
onClick={ this.startTournament }
/>
</Form>
</Grid.Column>
</Grid.Row>
</Grid>
);
};
renderJoinCommand = () => {
const connectStyle = {
margin: '1em -1em 0',
borderTop: '1px solid #efefef',
padding: '1em 1em 0',
fontSize: '0.9em',
};
const host = this.props.socket.socket.io.uri;
return (
<div style={ connectStyle }>
<p>Connect your player:</p>
<pre className='code'>$ uabc --host "{host}" --lobby "{this.token()}" --token "your team name" -f "path/to/executable"</pre>
</div>
);
};
addAllConnectedPlayers = () => {
this.setState({
activePlayers: this.state.lobby.players,
});
};
invalidGameServerSelected = () => {
const currentGameAddress = this.state.tournamentOptions.gameAddress
const currentGame = this.state.availableGames.find(game => game.address === currentGameAddress )
return currentGameAddress === undefined || currentGameAddress === null || currentGameAddress.length === 0
|| currentGame === undefined || currentGame.healthy === false;
};
renderPlayers = ({titleText, type, dropText, infoText, displayAddAll}) => {
const footerStyle = {
position: 'absolute',
bottom: 0,
left: 0,
padding: '0.3em',
width: '100%',
textAlign: 'center',
background: '#efefef',
fontSize: '0.7em',
};
const players = type === 'connected' ? this.state.lobby.players : this.state.activePlayers;
players.sort();
const playerDropKey = type + 'PlayersDrop';
let addAll = (
<div style={ footerStyle }>
<a href={ window.location }><Icon name='copy outline' /> { this.token() }</a>
</div>
);
if (displayAddAll) {
addAll = (
<div style={ footerStyle }>
<button className="link" onClick={ this.addAllConnectedPlayers }>
<Icon name='plus' /> Add All
</button>
</div>
);
}
return (
<div style={ { paddingBottom: '2em', height: 'calc(100% - 2em)' } }>
<Popup trigger={<p>{titleText} <Label size='mini' style={ { float: 'right' } }>{ players.length }</Label></p>} content={infoText} />
<div onDrop={(e) => this.onDragPlayerDrop(e, type)} onDragOver={this.onDragPlayerOver} onDragEnter={(e) => this.onDragPlayerMouseMove(e, type, true)} onDragLeave={(e) => this.onDragPlayerMouseMove(e, type, false)}
style={{height: '100%', position: 'relative', background: this.state[playerDropKey] && '#efefef', borderRadius: this.state[playerDropKey] && '0.28571429rem'}}>
{
!this.state[playerDropKey] &&
<List className='draggable relaxed divided'>
{ players.map(player => {
const isActive = this.state.activePlayers.indexOf(player) > -1;
return (
<List.Item key={ player } draggable className={ classNames({ inactive: !isActive }) } onDragStart={(e) => this.onDragPlayerStart(player, e)}>
<Icon name='circle' className={ classNames({ outline: !isActive }) } color='green' style={{display: 'inline-block', marginRight: '1rem'}}/>
{ player }
<Dropdown style={{float: 'right'}}>
<Dropdown.Menu>
<Dropdown.Item text="Kick player" onClick={() => this.kickPlayer(player)}/>
<Dropdown.Item text="Ban player" onClick={() => this.banPlayer(player)}/>
{ !isActive && (<Dropdown.Item text="Add player" onClick={() => this.addActivePlayer(player)}/>) }
{ isActive && (<Dropdown.Item text="Remove player" onClick={() => this.removeActivePlayer(player)}/>) }
</Dropdown.Menu>
</Dropdown>
</List.Item>
);
}) }
</List>
}
{
this.state[playerDropKey] &&
<p style={{position: 'absolute', top: '50%', transform: 'translateY(-50%)', width: '100%', textAlign: 'center'}}>{dropText}</p>
}
</div>
{ addAll }
</div>
);
};
render() {
if (!this.props.socket) {
return (
<Message>
Please connect to the server first.
</Message>
);
}
if (this.state.lobby.tournament && this.state.showTournament) {
return (
<Tournament
tournamentOptions={ this.state.tournamentOptions }
tournament={ this.state.lobby.tournament }
backToLobby={this.backToLobby}
continueMatches={this.continueMatches}
/>
);
}
return (
<Container textAlign='center' fluid style={{width: '80%'}}>
<Segment attached='top' className='socialgorithm-hue-bg animated-hue'>
<h1><Icon name='game' /> Welcome to { this.state.lobby.token }!</h1>
</Segment>
<Segment attached='bottom' textAlign='left'>
<Grid columns={ 3 } divided>
<Grid.Column width={ 3 }>
{ this.renderPlayers({titleText: 'Connected Players', type: 'connected', dropText: 'Exclude player from game', infoText: 'Players connected to the lobby', displayAddAll: true}) }
</Grid.Column>
<Grid.Column width={ 3 }>
{ this.renderPlayers({titleText: 'Players', type: 'active', dropText: 'Include player in game', infoText: 'Players to be included in the tournament'}) }
</Grid.Column>
<Grid.Column width={ 10 }>
{ this.renderLoader() }
{ this.renderAdmin() }
{ this.renderJoinCommand() }
</Grid.Column>
</Grid>
</Segment>
</Container>
);
}
};
export default withRouter(LobbyAdmin); |
src/parser/shaman/restoration/modules/features/CastBehavior.js | fyruna/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import Analyzer from 'parser/core/Analyzer';
import AbilityTracker from 'parser/shared/modules/AbilityTracker';
import { STATISTIC_ORDER } from 'interface/others/StatisticsListBox';
import StatisticGroup from 'interface/statistics/StatisticGroup';
import Statistic from 'interface/statistics/Statistic';
import DonutChart from 'interface/statistics/components/DonutChart';
class CastBehavior extends Analyzer {
static dependencies = {
abilityTracker: AbilityTracker,
};
get twUsageRatioChart() {
const riptide = this.abilityTracker.getAbility(SPELLS.RIPTIDE.id);
const healingWave = this.abilityTracker.getAbility(SPELLS.HEALING_WAVE.id);
const healingSurge = this.abilityTracker.getAbility(SPELLS.HEALING_SURGE_RESTORATION.id);
const chainHeal = this.abilityTracker.getAbility(SPELLS.CHAIN_HEAL.id);
const chainHealCasts = chainHeal.casts || 0;
const riptideCasts = riptide.casts || 0;
const totalTwGenerated = riptideCasts + chainHealCasts;
const twHealingWaves = healingWave.healingTwHits || 0;
const twHealingSurges = healingSurge.healingTwHits || 0;
const totalTwUsed = twHealingWaves + twHealingSurges;
const unusedTw = totalTwGenerated - totalTwUsed;
const items = [
{
color: SPELLS.HEALING_WAVE.color,
label: 'Healing Wave',
spellId: SPELLS.HEALING_WAVE.id,
value: twHealingWaves,
},
{
color: SPELLS.HEALING_SURGE_RESTORATION.color,
label: 'Healing Surge',
spellId: SPELLS.HEALING_SURGE_RESTORATION.id,
value: twHealingSurges,
},
{
color: '#CC3D20',
label: 'Unused Tidal Waves',
tooltip: `The amount of Tidal Waves you did not use out of the total available. You cast ${riptideCasts} Riptides and ${chainHealCasts} Chain Heals which gave you ${totalTwGenerated} Tidal Waves charges, of which you used ${totalTwUsed}.`,
value: unusedTw,
},
];
return (
<DonutChart
items={items}
/>
);
}
get fillerCastRatioChart() {
const healingWave = this.abilityTracker.getAbility(SPELLS.HEALING_WAVE.id);
const healingSurge = this.abilityTracker.getAbility(SPELLS.HEALING_SURGE_RESTORATION.id);
const twHealingWaves = healingWave.healingTwHits || 0;
const twHealingSurges = healingSurge.healingTwHits || 0;
const healingWaveHeals = healingWave.casts || 0;
const healingSurgeHeals = healingSurge.casts || 0;
const fillerHealingWaves = healingWaveHeals - twHealingWaves;
const fillerHealingSurges = healingSurgeHeals - twHealingSurges;
const items = [
{
color: SPELLS.HEALING_WAVE.color,
label: 'Healing Wave',
spellId: SPELLS.HEALING_WAVE.id,
value: fillerHealingWaves,
},
{
color: SPELLS.HEALING_SURGE_RESTORATION.color,
label: 'Healing Surge',
spellId: SPELLS.HEALING_SURGE_RESTORATION.id,
value: fillerHealingSurges,
},
];
return (
<DonutChart
items={items}
/>
);
}
statistic() {
return (
<StatisticGroup position={STATISTIC_ORDER.CORE(40)}>
<Statistic ultrawide>
<div className="pad">
<label><SpellLink id={SPELLS.TIDAL_WAVES_BUFF.id} /> usage</label>
{this.twUsageRatioChart}
</div>
</Statistic>
<Statistic ultrawide>
<div className="pad">
<label>Fillers</label>
{this.fillerCastRatioChart}
</div>
</Statistic>
</StatisticGroup>
);
}
}
export default CastBehavior;
|
android/source/view/home.js | cloudfavorites/favorites | import React, { Component } from 'react';
import {
View,
Dimensions,
RefreshControl,
DrawerLayoutAndroid
} from 'react-native';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import DrawerPanel from '../component/drawerPanel';
import HomeRender from '../component/homeRender';
import PostList from '../component/postList';
import MenuButton from '../component/menuButton';
import * as PostAction from '../action/post';
import { postCategory } from '../config';
import refreshControlConfig from '../config/refreshControlConfig';
const { width } = Dimensions.get('window');
class HomePage extends Component {
constructor (props) {
super(props);
this.state = {
category: postCategory.home
};
this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
}
componentDidMount(){
this.fetchPostData(this.state.category);
}
fetchPostData(category){
const { posts, ui } = this.props;
if ((!posts[category] || posts[category].length === 0) && ui[category].refreshPending === false) {
this.props.postAction.getPostByCategory(category).then(()=>{
this.setState({ category:category });
});
}else{
this.setState({ category: category });
}
}
renderNavigationView(){
return (
<DrawerPanel
router={this.props.router}
onDrawerPress={(e)=>this.onDrawerPress(e)}
onDrawerHide={(e)=> this.onDrawerHide(e)}/>
);
}
onDrawerPress(drawerItem){
if (drawerItem) {
if (drawerItem.action === "refresh" && drawerItem.flag !== this.state.category) {
this.fetchPostData(drawerItem.flag);
}else{
this.props.router[drawerItem.action] && this.props.router[drawerItem.action]();
}
}
}
onDrawerHide(){
this.drawer &&
this.drawer.closeDrawer();
}
onMenuPress(){
this.drawer &&
this.drawer.openDrawer();
}
onSearchPress(){
this.props.router.toSearch();
}
onListEndReached(){
const { postAction, posts, ui } = this.props;
if (posts && posts[this.state.category].length && ui[this.state.category].pageEnabled) {
postAction.getPostByCategoryWithPage(this.state.category, {
pageIndex: ui[this.state.category].pageIndex + 1
});
}
}
renderListRefreshControl(){
let { ui, postAction } = this.props;
return (
<RefreshControl { ...refreshControlConfig }
refreshing={ ui[this.state.category].refreshPending }
onRefresh={ ()=>{ postAction.getPostByCategory(this.state.category) } } />
);
}
render() {
return (
<DrawerLayoutAndroid
ref={(view)=>{ this.drawer = view }}
drawerWidth={width-80}
keyboardDismissMode="on-drag"
drawerPosition={DrawerLayoutAndroid.positions.Left}
renderNavigationView={()=> this.renderNavigationView()}>
<HomeRender
category={ this.state.category }
refreshControl={ this.renderListRefreshControl() }
onMenuPress={ ()=>this.onMenuPress() }
onSearchPress={ ()=>this.onSearchPress() }
onListEndReached = { ()=>this.onListEndReached() }>
<PostList router={ this.props.router } category={ this.state.category }/>
</HomeRender>
<MenuButton
onPress={()=> this.onMenuPress()}
router = { this.props.router }/>
</DrawerLayoutAndroid>
);
}
}
export default connect((state, props) => ({
posts : state.post,
ui: state.postListUI
}), dispatch => ({
postAction : bindActionCreators(PostAction, dispatch)
}), null, {
withRef: true
})(HomePage); |
frontend/src/admin/common/tables/SortedTable.js | rabblerouser/core | import React, { Component } from 'react';
import styled from 'styled-components';
import Table from './Table';
import sortColumn from './sortColumn';
const TableAside = styled.aside`
padding: 15px;
font-size: 14px;
background-color: ${props => props.theme.lightGrey};
font-style: italic;
`;
class SortedTable extends Component {
constructor(props) {
super(props);
this.onSort = this.onSort.bind(this);
this.state = sortColumn(props.sortOn, props.columns, props.data);
}
componentWillReceiveProps(props) {
this.setState(sortColumn(props.sortOn, props.columns, props.data));
}
onSort(field) {
this.setState(sortColumn(field, this.state.columns, this.state.data));
}
render() {
return (
this.state.data.length === 0 ?
<TableAside>No entries found</TableAside>
:
<Table
columns={this.state.columns}
data={this.state.data}
onClickHeader={this.onSort}
/>
);
}
}
export default SortedTable;
|
src/index.js | elisherer/react-storybook-addon-info | import React from 'react';
import _Story from './components/Story';
import { H1, H2, H3, H4, H5, H6, Code, P, UL, A, LI } from './components/markdown';
export const Story = _Story;
const defaultOptions = {
inline: false,
header: true,
source: true,
propTables: [],
};
const defaultMtrcConf = {
h1: H1,
h2: H2,
h3: H3,
h4: H4,
h5: H5,
h6: H6,
code: Code,
p: P,
a: A,
li: LI,
ul: UL,
};
export default {
addWithInfo(storyName, info, storyFn, _options) {
if (typeof storyFn !== 'function') {
if (typeof info === 'function') {
_options = storyFn;
storyFn = info;
info = '';
} else {
throw new Error('No story defining function has been specified');
}
}
const options = {
...defaultOptions,
..._options
};
// props.propTables can only be either an array of components or null
// propTables option is allowed to be set to 'false' (a boolean)
// if the option is false, replace it with null to avoid react warnings
if (!options.propTables) {
options.propTables = null;
}
const mtrcConf = { ...defaultMtrcConf };
if (options && options.mtrcConf) {
Object.assign(mtrcConf, options.mtrcConf);
}
return this.add(storyName, (context) => {
const props = {
info,
context,
showInline: Boolean(options.inline),
showHeader: Boolean(options.header),
showSource: Boolean(options.source),
propTables: options.propTables,
mtrcConf
};
return (
<Story {...props}>
{storyFn(context)}
</Story>
);
});
}
};
export function setDefaults(newDefaults) {
return Object.assign(defaultOptions, newDefaults);
};
|
src/cell/carto.js | HVF/franchise | import React from 'react'
import classNames from 'classnames'
import { updateCell } from './index'
import './carto.less'
String.prototype.replaceAll = function(search, replacement) {
var target = this
return target.replace(new RegExp(search, 'g'), replacement)
}
function addCSS(url) {
var link = document.createElement('link')
link.type = 'text/css'
link.rel = 'stylesheet'
link.href = url
document.head.appendChild(link)
}
function addJS(url, resolve, reject) {
var script = document.createElement('script')
script.src = url
script.addEventListener('load', function() {
resolve()
})
script.addEventListener('error', function(e) {
reject(e)
})
document.head.appendChild(script)
}
export class CartoVisualizer extends React.Component {
static key = 'carto'
static desc = 'CARTO View'
static icon = (
<svg width="16px" height="16px" viewBox="762 -58 32 32" version="1.1">
<g
className="imago"
stroke="none"
strokeWidth="1"
fill="none"
fillRule="evenodd"
transform="translate(762.000000, -58.000000)"
>
<circle className="Halo" fill="#ccc" opacity="0.6" cx="16" cy="16" r="16" />
<circle className="point" fill="#ccc" cx="16" cy="16" r="5.5" />
</g>
</svg>
)
static test(result) {
return result.columns.some((k) => ['the_geom_webmercator'].includes(k.toLowerCase()))
}
state = {
loaded: false,
layer: undefined,
mapConfig: {
maxZoom: 18,
minZoom: 0,
center: [0, 0],
zoom: 0,
},
fitBoundsMaxZoom: 12,
tooltip: [
'<script type="infowindow/html" id="infowindow_template">',
'<div class="cartodb-popup">',
'<a href="#close" class="cartodb-popup-close-button close">x</a>',
'<div class="cartodb-popup-content-wrapper">',
'<div class="cartodb-popup-content">',
'{{cartodb_id}}',
'</div>',
'</div>',
'<div class="cartodb-popup-tip-container"></div>',
'</div>',
'</script>',
].join('\n'),
defaultCSS: [
"#layer['mapnik::geometry_type'=1] {",
' marker-width: 7;',
' marker-fill: #EE4D5A;',
' marker-fill-opacity: 0.9;',
' marker-line-color: #FFFFFF;',
' marker-line-width: 1;',
' marker-line-opacity: 1;',
' marker-type: ellipse;',
' marker-allow-overlap: true;',
'}',
"#layer['mapnik::geometry_type'=2] {",
' line-color: #4CC8A3;',
' line-width: 1.5;',
' line-opacity: 1;',
'}',
"#layer['mapnik::geometry_type'=3] {",
' polygon-fill: #826DBA;',
' polygon-opacity: 0.9;',
' ::outline {',
' line-color: #FFFFFF;',
' line-width: 1;',
' line-opacity: 0.5;',
' }',
'}',
].join('\n'),
}
shouldComponentUpdate(nextProps) {
return (
nextProps.result.expandedQuery !== this.props.result.expandedQuery ||
nextProps.view.query !== this.props.view.query
)
}
componentWillUpdate(props, state) {
let newQuery = props.result.expandedQuery || props.view.query
if (state.layer && state.layer.getQuery() != newQuery) {
state.layer.getSubLayer(0).setSQL(newQuery)
this.zoomToLayer(state.layer, this.props.config)
}
}
componentDidMount() {
let { result, view, config } = this.props
var self = this
var query = result.expandedQuery || view.query
if (!this.state.css) {
this.setState({ css: this.state.defaultCSS })
}
this.loadLibrary()
.then(() => {
if (cartodb) {
var map = new cartodb.L.Map('mapContainer_' + view.id, self.state.mapConfig)
var baseLayer = cartodb.L.tileLayer(
'https://cartodb-basemaps-{s}.global.ssl.fastly.net/rastertiles/voyager/{z}/{x}/{y}.png',
{
subdomains: 'abcd',
maxZoom: self.state.mapConfig.maxZoom,
minZoom: self.state.mapConfig.minZoom,
label: 'Voyager',
}
).addTo(map)
var layer = cartodb.createLayer(
map,
{
user_name: config.credentials.user,
type: 'cartodb',
sublayers: [
{
sql: query,
cartocss: self.state.defaultCSS,
},
],
infowindow: true,
tooltip: true,
legends: true,
extra_params: {
map_key: config.credentials.apiKey,
},
},
{ https: true }
)
layer
.addTo(map)
.on('done', function(layer) {
layer.on('error', function(error) {
updateCell(view.id, { loading: false, result: null, error: error })
})
layer.leafletMap.zoomControl.setPosition('topright')
self.addInfoWindow(map, layer.getSubLayer(0), view.result.columns)
self.setState({ layer: layer })
self.cssCell.updateLayer(layer)
self.zoomToLayer(layer, config)
setTimeout(() => {
layer.leafletMap.invalidateSize()
}, 1000)
})
.on('error', function(error) {
updateCell(view.id, { loading: false, result: null, error: error })
})
}
})
.catch((e) => {
console.log(e)
})
}
addInfoWindow(map, layer, columns) {
cartodb.vis.Vis.addInfowindow(map, layer, this.filterColumns(columns))
}
filterColumns(columns) {
return columns.filter((column) => column.indexOf('the_geom') == -1)
}
zoomToLayer(layer, config) {
var self = this
let sql = new cartodb.SQL({
user: config.credentials.user,
api_key: config.credentials.apiKey,
})
sql.getBounds(
layer
.getQuery()
.replaceAll('{{', '')
.replaceAll('}}', '')
).done(function(bounds) {
layer.leafletMap.fitBounds(bounds, { maxZoom: self.state.fitBoundsMaxZoom })
})
}
loadLibrary(resolve, reject) {
return new Promise((resolve, reject) => {
addCSS(
'https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/themes/css/cartodb.css'
)
addJS(
'https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/cartodb.js',
resolve,
reject
)
})
}
render() {
let { result, view } = this.props
let mapContainerId = 'mapContainer_' + view.id
return (
<div className="carto-container">
<div className="map-container" id={mapContainerId}>
<CartoCSSCell
css={!this.state.css ? this.state.defaultCSS : this.state.css}
layer={this.state.layer}
ref={(cssCell) => {
this.cssCell = cssCell
}}
/>
</div>
</div>
)
}
}
import CodeMirror from 'codemirror'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/mode/markdown/markdown'
import 'codemirror/keymap/sublime'
import 'codemirror/mode/css/css'
import 'codemirror/theme/monokai.css'
import ReactCodeMirror from '@skidding/react-codemirror'
import { Tooltip as BlueprintTooltip, Position } from '@blueprintjs/core'
function Tooltip(props) {
return (
<BlueprintTooltip
position={Position.RIGHT}
tetherOptions={{ constraints: [{ attachment: 'together', to: 'scrollParent' }] }}
{...props}
/>
)
}
export class CartoCSSCell extends React.PureComponent {
key = 'cartocss'
desc = 'Cmd+Enter to apply changes'
state = {
css: undefined,
layer: undefined,
shown: true,
}
componentWillReceiveProps(newProps) {
this.setState({ layer: newProps.layer })
}
updateLayer(layer) {
this.setState({ layer: layer })
}
toggle(e) {
this.setState({ shown: !this.state.shown })
}
render() {
const css_options = {
theme: 'monokai',
lineNumbers: false,
lineWrapping: true,
mode: 'text/x-scss',
extraKeys: {
'Cmd-Enter': (cm) => this.updateCartoCSS(),
'Ctrl-Enter': (cm) => this.updateCartoCSS(),
'Ctrl-Space': 'autocomplete',
},
autoCloseBrackets: true,
matchBrackets: true,
placeholder: 'Type CartoCSS here...',
showPredictions: false,
}
let { shown } = this.state
return (
<div
className={classNames({
'carto-css': true,
hide: !shown,
})}
>
<div className="input-wrap">
<Tooltip key={this.key} content={this.desc}>
<ReactCodeMirror
value={!this.props.css ? '' : this.props.css}
key="a"
ref={(e) => (this.cmr = e)}
onChange={(css) => {
this.setState({ css: css })
}}
options={css_options}
/>
</Tooltip>
<button type="button" onClick={(e) => this.toggle(e)}>
<i
className={
shown ? 'fa fa-angle-double-left' : 'fa fa-angle-double-right'
}
aria-hidden="true"
/>
</button>
</div>
</div>
)
}
updateCartoCSS() {
let layer = this.state.layer || this.props.layer
if (layer && this.state.css) {
layer.setCartoCSS(this.state.css)
}
}
}
|
app/resources.js | gusreiber/jenkins-plugin-site | import { createSelector } from 'reselect';
import { createSearchAction, getSearchSelectors } from 'redux-search';
import Immutable from 'immutable';
import keymirror from 'keymirror';
import { api, logger } from './commons';
import _ from 'lodash';
import React from 'react';
api.init({
latency: 100
});
export const SearchOptions = Immutable.Record({
limit: 100,
page: 1,
pages: 0,
total: 0
});
export const State = Immutable.Record({
plugins: Immutable.OrderedMap(),
isFetching: false,
searchOptions: SearchOptions,
labelFilter: Immutable.Record({//fixme: that should become label: search, sort: field
field: 'title',
searchField: null,
asc: false,
search: []
})
});
/*
buildDate: "Mar 03, 2011"
dependencies: Array[0]
developers: Array[1]
excerpt: "This (experimental) plug-in exposes the jenkins build extension
points (SCM, Build, Publish) to a groovy scripting environment that has
some DSL-style extensions for ease of development."
gav: "jenkins:AdaptivePlugin:0.1"
labels: Array[2]
name: "AdaptivePlugin"
releaseTimestamp: "2011-03-03T16:49:24.00Z"
requiredCore: "1.398"
scm: "github.com"
sha1: "il8z91iDnqVMu78Ghj8q2swCpdk="
title: "Jenkins Adaptive DSL Plugin"
url: "http://updates.jenkins-ci.org/download/plugins/AdaptivePlugin/0.1/AdaptivePlugin.hpi"
version: "0.1"
wiki: "https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+Adaptive+Plugin"
*/
// Immutable Data attributes must be accessible as getters
const Record = Immutable.Record({
id: null,
name: null,
title: '',
buildDate: null,
releaseTimestamp: null,
version: null,
wiki: '',
excerpt: '',
iconDom: null,
requiredCore: null,
developers: [],
labels: [],
dependencies: []
});
export const ACTION_TYPES = keymirror({
CLEAR_PLUGIN_DATA: null,
FETCH_PLUGIN_DATA: null,
SET_PLUGIN_DATA: null,
SET_LABEL_FILTER: null,
SET_QUERY_INFO: null
});
export const actionHandlers = {
[ACTION_TYPES.CLEAR_PLUGIN_DATA](state) {
return state.set('plugins', Immutable.Map());
},
[ACTION_TYPES.FETCH_PLUGIN_DATA](state, {}): State {
return state.set('isFetching', !state.isFetching);
},
[ACTION_TYPES.SET_PLUGIN_DATA](state, { payload }): State {
return state.set('plugins', payload);
},
[ACTION_TYPES.SET_LABEL_FILTER](state, { payload }): State {
return state.set('labelFilter', payload);
},
[ACTION_TYPES.SET_QUERY_INFO](state, { payload }): State {
return state.set('searchOptions', payload);
}
};
export const actions = {
//FIXME: This should not inject React DOM here, but.... hack...
makeIcon(title, type){
title = title
.replace('Jenkins ','')
.replace('jenkins ','')
.replace(' Plugin','')
.replace(' Plug-in','')
.replace(' lugin','');
type = type || '';
const colors = ['#6D6B6D','#DCD9D8','#D33833','#335061','#81B0C4','#709aaa','#000'];
const color = colors[(title.length % 7)]; //pick color based on chars in the name to make semi-random, but fixed color per-plugin
const iconClass=`i ${type};
color = ${color}`;
const firstLetter = title.substring(0,1).toUpperCase();
const firstSpace = title.indexOf(' ') + 1;
const nextIndx = (firstSpace === 0)?
1: firstSpace;
const nextLetter = title.substring(nextIndx,nextIndx + 1);
return (
<i className={iconClass} style={{background: color}}>
<span className="first">{firstLetter}</span>
<span className="next">{nextLetter}</span>
</i>
);
},
clearPluginData: () => ({ type: ACTION_TYPES.CLEAR_PLUGIN_DATA }),
fetchPluginData: () => ({ type: ACTION_TYPES.FETCH_PLUGIN_DATA }),
setFilter(filter) {
return (dispatch) => {
dispatch({
type: ACTION_TYPES.SET_LABEL_FILTER,
payload: filter
});
};
},
generatePluginData(query={}) {
return (dispatch) => {
logger.log(query);
let url;
if (query.category) {
const CATEGORY_URL = '/getCategories';
url = `${CATEGORY_URL}?id=${query.category}`;
}else if(query.latest){
url = '/latest';
}else {
const PLUGINS_URL = '/plugins';
url = `${PLUGINS_URL}?page=${query.page || 1}&limit=${query.limit || 10}&q=${query.q || ''}`;
}
logger.log(query, url);
dispatch(actions.clearPluginData());
dispatch(actions.fetchPluginData());
const plugins = {};
return api.getJSON(url,(error, data) => {
if (data) {
const searchOptions = new SearchOptions({
limit: data.limit,
page: data.page,
pages: data.pages,
total: data.total
});
const items = data.docs;
_.forEach(items, (item) => {
_.set(item, 'id', item.sha1);
_.set(item, 'iconDom', actions.makeIcon(item.title));
plugins[item.id] = new Record(item);
});
const recordsMap = Immutable.Map(plugins);
dispatch({
type: ACTION_TYPES.SET_PLUGIN_DATA,
payload: recordsMap
});
dispatch({
type: ACTION_TYPES.SET_QUERY_INFO,
payload: searchOptions
});
dispatch(actions.fetchPluginData());
}
});
};
},
searchPluginData: createSearchAction('plugins')
};
export function groupAndCountLabels(recordsMap) {
const labelMap = _.map(
_.groupBy(
_.flatten(recordsMap.toArray().map((a) => a.labels)
)
), (array, item) => {
return {
value: array.length,
key: item
};
}
);
return Immutable.List(labelMap);
}
export const resources = state => state.resources;
export const resourceSelector = (resourceName, state) => state.resources.get(resourceName);
export const plugins = createSelector([resources], resources => resources.plugins);
export const searchOptions = createSelector([resources], resources => resources.searchOptions);
export const isFetching = createSelector([resources], resources => resources.isFetching);
export const labelFilter = createSelector([resources], resources => resources.labelFilter);
const pluginSelectors = getSearchSelectors({ resourceName: 'plugins', resourceSelector });
export const searchText = pluginSelectors.text;
export const filteredList = createSelector([pluginSelectors.result], result => Immutable.List(result));
export const getVisiblePlugins = createSelector(
[ filteredList, plugins ],
(filteredList, plugins) => {
return filteredList.map(
(id) => {
return plugins.get(id);
});
}
);
export const totalSize = createSelector(
[ searchOptions ],
( searchOptions ) => {
return searchOptions.total || 0;
}
);
export const filterVisibleList = createSelector (
[getVisiblePlugins, labelFilter],
(plugins, labelFilter) => {
if (labelFilter instanceof Function) {
labelFilter = labelFilter();
}
const list = plugins
.filter(
item => {
if ( !labelFilter.searchField || !labelFilter.search || !labelFilter.search.length > 0) {
return true;
}
const matchIndex = _.findIndex(item[labelFilter.searchField], (i) => {
let match = false;
labelFilter.search.some(searchFilter => {
match = (i === searchFilter);
return match;
});
return match;
});
return ( matchIndex >= 0);
}
)
.sortBy(plugin => {
return plugin[labelFilter.field];}, (plugin, nextPlugin) => {
if (labelFilter.asc) {
return nextPlugin.localeCompare(plugin);
} else {
return plugin.localeCompare(nextPlugin);
}
});
logger.warn(`xxx ${list}`);
return list;
}
);
export const getVisiblePluginsLabels = createSelector(
[ filterVisibleList ],
( plugins ) => {
return groupAndCountLabels(plugins);
}
);
export function reducer(state = new State(), action: Object): State {
const { type } = action;
if (type in actionHandlers) {
return actionHandlers[type](state, action);
} else {
return state;
}
}
|
powerauth-webflow/src/main/js/components/operationTimeout.js | lime-company/lime-security-powerauth-webauth | /*
* Copyright 2019 Wultra s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react'
import {FormattedMessage} from "react-intl";
import {verifyOperationTimeout} from "../actions/timeoutActions";
import {connect} from "react-redux";
/**
* Component for handling operation timeouts.
*
* @author Roman Strobl, roman.strobl@wultra.com
*/
@connect((store) => {
return {
timeout: store.timeout
}
})
export default class OperationTimeout extends React.Component {
constructor() {
super();
this.state = {timeoutCheckEnabled: false, warningEnabled: false, timeoutCheckScheduled: false}
}
componentWillMount() {
// Check timeout only in case the check is active to avoid concurrent requests
if (this.props.timeoutCheckActive) {
this.props.dispatch(verifyOperationTimeout());
}
}
componentWillReceiveProps(props) {
if (!this.props.timeoutCheckActive && props.timeoutCheckActive) {
// Timeout check has just been activated e.g. by switching the active organization
if (this.state.timeoutCheckScheduled) {
// Timeout check is already scheduled, just enable it
this.setState({timeoutCheckEnabled: true});
} else {
// Trigger new timeout check
this.props.dispatch(verifyOperationTimeout());
}
return;
}
if (this.props.timeoutCheckActive && !props.timeoutCheckActive) {
// Timeout check has just been deactivated e.g. by switching the active organization
this.setState({timeoutCheckEnabled: false});
return;
}
if (props.timeoutCheckActive && props.timeout) {
if (!this.state.timeoutCheckScheduled && props.timeout.timeoutCheckEnabled && props.timeout.timeoutDelayMs > 0) {
this.setState({timeoutCheckEnabled: true, timeoutCheckScheduled: true});
let nextVerificationMs = props.timeout.timeoutDelayMs;
if (props.timeout.timeoutWarningDelayMs > 0 && props.timeout.timeoutWarningDelayMs < props.timeout.timeoutDelayMs) {
nextVerificationMs = props.timeout.timeoutWarningDelayMs;
}
setTimeout(function() {
// Only send timeout related requests when timeout checking is enabled, other components can disable
// timeout checking using timeout reducer when operation has been completed.
if (this.state.timeoutCheckEnabled) {
this.props.dispatch(verifyOperationTimeout());
this.setState({timeoutCheckScheduled: false});
}
}.bind(this), nextVerificationMs);
} else if (props.timeout.timeoutDelayMs === 0) {
// This state is already handled on server, however if it occurs, it is clearly an error
props.dispatch({
type: "SHOW_SCREEN_ERROR",
payload: {
message: "error.sessionExpired"
}
})
}
if (props.timeout.timeoutWarningDelayMs === 0) {
// Exact match on zero is required to enable the warning message
this.setState({warningEnabled: true})
} else {
this.setState({warningEnabled: false})
}
}
}
render() {
if (this.state.warningEnabled) {
return (
<div className="alert alert-warning font-small">
<FormattedMessage id="operation.timeoutWarning"/>
</div>
)
}
return null;
}
}
|
vertex_ui/src/components/Badge/Badge.js | zapcoop/vertex | import React from 'react';
import { PropTypes } from 'prop-types';
import classNames from 'classnames';
import _ from 'underscore';
import { Badge as ReactBootstrapBadge } from 'react-bootstrap';
/*
Extended Badge from ReactBootstrap. Adds outline option, color changing by
bsStyle and withIcon which adjusts the badge position next to an icon element
*/
const Badge = props => {
const {
className,
outline,
bsStyle,
withIcon,
children,
...otherProps
} = props;
const badgeClass = classNames(className, {
'badge-outline': outline,
'badge-primary': bsStyle === 'primary',
'badge-success': bsStyle === 'success',
'badge-info': bsStyle === 'info',
'badge-warning': bsStyle === 'warning',
'badge-danger': bsStyle === 'danger',
'badge-with-icon': props.withIcon,
});
return (
<ReactBootstrapBadge {...otherProps} className={badgeClass}>
{props.children}
</ReactBootstrapBadge>
);
};
Badge.propTypes = {
outline: PropTypes.bool,
bsStyle: PropTypes.string,
children: PropTypes.node.isRequired,
withIcon: PropTypes.bool,
};
Badge.defaultProps = {
outline: false,
bsStyle: '',
withIcon: false,
};
export default Badge;
|
js/ui/Root.js | rabaut/oneroom | import React, { Component } from 'react';
import Welcome from './welcome/welcome';
import Game from './game/game';
export default class Root extends Component {
render() {
if(true) { return (<Game {...this.props} />); }
return (<Welcome />);
}
}
|
src/core/display/App/Navigation/Horizontal/ChildrenLinks.js | JulienPradet/pigment-store | import React from 'react'
import {Link} from 'react-router'
const ChildrenLinks = ({children}) => (
<ul>
{children.map(({pattern, name}) => (
<li key={pattern}>
<Link to={pattern}>{name}</Link>
</li>
))}
</ul>
)
export default ChildrenLinks
|
src/index.js | physiii/home-gateway | import 'normalize.css';
import './views/styles/base.css';
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider as ReduxProvider} from 'react-redux';
import {ConnectedRouter} from 'connected-react-router';
import createHistory from 'history/createBrowserHistory';
import moment from 'moment';
import momentDurationFormatSetup from 'moment-duration-format';
import configureStore from './state/store';
import {initialize as initializeConfig} from './state/ducks/config/operations.js';
import {initialize as initializeSession} from './state/ducks/session/operations.js';
import {listenForDeviceChanges} from './state/ducks/devices-list/operations.js';
import {listenForRoomChanges} from './state/ducks/rooms-list/operations.js';
import {listenForAutomationChanges} from './state/ducks/automations-list/operations.js';
import AppContext from './views/AppContext.js';
import App from './views/layouts/App';
const history = createHistory(), // History object to share between router and store.
reduxStore = configureStore(history), // Create store.
THREE_SECONDS = 3,
ONE_MINUTE_IN_SECONDS = 60,
ONE_HOUR_IN_MINUTES = 60;
// Configure moment.
moment.relativeTimeThreshold('s', ONE_MINUTE_IN_SECONDS);
moment.relativeTimeThreshold('ss', THREE_SECONDS);
moment.relativeTimeThreshold('m', ONE_HOUR_IN_MINUTES);
momentDurationFormatSetup(moment);
// Save configuration to store.
reduxStore.dispatch(initializeConfig(window.OpenAutomation.config));
// Set up user if already logged in.
reduxStore.dispatch(initializeSession());
// Listen for changes pushed from server.
reduxStore.dispatch(listenForDeviceChanges());
reduxStore.dispatch(listenForRoomChanges());
reduxStore.dispatch(listenForAutomationChanges());
ReactDOM.render(
<ReduxProvider store={reduxStore}>
<ConnectedRouter history={history}>
<AppContext>
<App />
</AppContext>
</ConnectedRouter>
</ReduxProvider>,
document.getElementById('open-automation')
);
|
app/src/Frontend/modules/crm/containers/me/setting.js | ptphp/ptphp | /**
* Created by jf on 15/12/10.
*/
//"use strict";
import React from 'react';
var Sentry = require('react-sentry');
import {
Panel,
PanelBody,
Toast,
Cells,
Cell,
CellHeader,
CellBody,
CellFooter,
ActionSheet,
Ico
} from '../../../../index';
import Page from '../../components/page/index';
import './index.less';
export default React.createClass( {
mixins: [Sentry],
contextTypes: {
dataStore: React.PropTypes.object.isRequired,
router: React.PropTypes.object.isRequired,
},
getInitialState(){
return {
showLogoutTips:false,
logoutTipsMenus:[{
label: '确认退出',
onClick: ()=> {
alert("logout");
this.setState({showLogoutTips:false})
}
}],
logoutTipsActions:[
{
label: '返回',
onClick: ()=>{this.setState({showLogoutTips:false})}
}
],
showUnbndTips:false,
UnbndTipsMenus:[{
label: '确认解绑',
onClick: ()=> {
alert("UnbndTips")
this.setState({showUnbndTips:false})
}
}],
UnbndTipsActions:[
{
label: '返回',
onClick: ()=>{this.setState({showUnbndTips:false})}
}
]
}
},
showAboutUs(){
this.context.router.push("/me/aboutus");
},
unBindWechat(){
alert("unBindWechat");
},
componentDidMount(){
},
render () {
return (
<Page title="设置" goBack={()=>{history.go(-1)}} className="me-view">
<Cells access>
<Cell onTap={this.showAboutUs}>
<CellHeader>
<Ico value="aboutus"/>
</CellHeader>
<CellBody>
关于我们
</CellBody>
<CellFooter>
</CellFooter>
</Cell>
</Cells>
<Cells access>
<Cell onTap={()=>{this.setState({showUnbndTips:true})}}>
<CellHeader>
<Ico value="arrow_right"/>
</CellHeader>
<CellBody>
解除微信绑定
</CellBody>
<CellFooter>
</CellFooter>
</Cell>
<Cell onTap={()=>{this.setState({showLogoutTips:true})}}>
<CellHeader>
<Ico value="logout"/>
</CellHeader>
<CellBody>
退出登录
</CellBody>
<CellFooter>
</CellFooter>
</Cell>
</Cells>
<ActionSheet
menus={this.state.logoutTipsMenus}
actions={this.state.logoutTipsActions}
show={this.state.showLogoutTips}
onRequestClose={()=>{this.setState({showLogoutTips:false})}} />
<ActionSheet
menus={this.state.UnbndTipsMenus}
actions={this.state.UnbndTipsActions}
show={this.state.showUnbndTips}
onRequestClose={()=>{this.setState({showUnbndTips:false})}} />
</Page>
);
}
});
|
src/components/shared/modal/ModalComponent.js | refinedjs/refinedjs-blog | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ModalBodyComponent from './ModalBodyComponent';
import './ModalComponent.scss';
export default class ModalComponent extends Component {
constructor(props) {
super(props);
this.state = {
styles: {}
};
this.closeModal = this.closeModal.bind(this);
this.renderModalBody = this.renderModalBody.bind(this);
}
closeModal() {
this.props.closeModal();
}
renderModalBody() {
if(this.props.children) {
return (
<div className="modal-body-container" style={this.props.modalBodyStyles}>
{this.props.children}
</div>
);
}
return (
<ModalBodyComponent styles={{ position: 'absolute' }} content={this.props.content} closeModal={this.closeModal} />
);
}
render() {
return (
<div className="modal" style={this.state.styles}>
{/*<div className="modal-back" />*/}
{this.renderModalBody()}
</div>
);
}
}
ModalComponent.propTypes = {
children: PropTypes.node,
content: PropTypes.string,
closeModal: PropTypes.func.isRequired,
modalBodyStyles: PropTypes.shape({})
};
ModalComponent.defaultProps = {
children: null,
content: '',
modalBodyStyles: {}
}; |
src/templates/blog-post.js | lucasflores/lucasflores.github.io | import React from 'react'
import { graphql } from 'gatsby'
import TimeAgo from 'react-timeago'
import { Flex, Box } from 'grid-styled'
import { media } from '../utils/style'
import styled, { createGlobalStyle } from 'styled-components'
import Breadcrumb from '../components/breadcrumb'
import Bar from '../components/bar'
import "katex/dist/katex.min.css"
import { DiscussionEmbed } from "disqus-react"
import Footer from '../components/footer'
const GlobalStyle = createGlobalStyle`
@import "//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css";
html {
max-width: 100vw;
overflow-x: hidden;
}
`
const Body = styled.div`
display: flex;
min-height: 100vh;
flex-direction: column;
width: 100vw;
img {
margin-bottom: 0;
}
`
const imgRight = styled.div`
& > div {
float: right;
width: 54%;
padding-left:25px;
}
`
const Header = styled.div`
height: fit-contents;
padding: 0;
background: #292929;
position: relative;
overflow: hidden;
& > div {
padding-top: 60px;
margin: auto;
max-width: 1000px;
}
`
const Tags = styled.ol`
float: right;
list-style: none;
margin: 0;
& li a,
& li {
font-weight: 600;
text-transform: uppercase;
text-decoration: none;
display: inline-block;
color: #222;
}
& > li + li:before {
padding: 0 8px;
font-weight: 400;
color: #444;
content: '|';
}
`
const Content = styled.div`
margin: 0 auto;
max-width: 960px;
padding: 0px 1.0875rem 1.45rem;
padding-top: 5vh;
hr {
margin: 0 0 40px;
}
`
const Title = styled.h1`
margin-top: 0;
text-transform: capitalize;
color: #fff;
`
const Timestamp = styled.i`
float: right;
`
const TimeToRead = styled.h5`
text-transform: uppercase;
margin-top: 0.5em;
display: inline-block;
`
export const disqusConfig = ({ slug, title }) => ({
shortname: process.env.GATSBY_DISQUS_NAME,
config: { identifier: title },
})
export default ({ data, location }) => {
const post = data.markdownRemark
const crumbs = [
{ name: 'home', link: '/' },
{ name: 'blogfolio', link: '/#blogfolio' },
{ name: post.frontmatter.title, link: location.pathname },
]
const tags = post.frontmatter.tags.map(function(tag) {
return <li key={tag}>{tag}</li>
})
const { frontmatter, excerpt, body, timeToRead } = post
const { title, slug, cover, showToc } = frontmatter
return (
<div>
<Body>
<GlobalStyle />
<Header>
<Flex flexWrap="wrap">
<Box px={2} width={[1, 2 / 3, 1 / 3]}>
<Title>{post.frontmatter.title}</Title>
</Box>
<Box px={2} width={[1, 2 / 3]}>
<Breadcrumb crumbs={crumbs} />
</Box>
<Box px={2} width={[1]}>
<Bar />
</Box>
</Flex>
</Header>
<Content>
<TimeToRead>{post.timeToRead} min read</TimeToRead>
<Tags>{tags}</Tags>
<Bar />
<div dangerouslySetInnerHTML={{ __html: post.html }} />
<DiscussionEmbed {...disqusConfig({ slug, title })} />
<Timestamp>
Posted: <TimeAgo date={post.frontmatter.date} />
</Timestamp>
</Content>
<Footer/>
</Body>
</div>
)
}
export const query = graphql`
query BlogPostQuery($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
timeToRead
frontmatter {
title
date
tags
}
}
}
`
|
es/components/sidebar/panel-element-editor/attributes-editor/line-attributes-editor.js | cvdlab/react-planner | export { LineAttributesEditor as default };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormNumberInput, FormTextInput } from '../../../style/export';
import { PropertyLengthMeasure } from '../../../../catalog/properties/export';
var tableStyle = { width: '100%' };
var firstTdStyle = { width: '6em' };
var inputStyle = { textAlign: 'left' };
function LineAttributesEditor(_ref, _ref2) {
var element = _ref.element,
_onUpdate = _ref.onUpdate,
attributeFormData = _ref.attributeFormData,
state = _ref.state,
rest = _objectWithoutProperties(_ref, ['element', 'onUpdate', 'attributeFormData', 'state']);
var translator = _ref2.translator;
var name = attributeFormData.has('name') ? attributeFormData.get('name') : element.name;
var vertexOne = attributeFormData.has('vertexOne') ? attributeFormData.get('vertexOne') : null;
var vertexTwo = attributeFormData.has('vertexTwo') ? attributeFormData.get('vertexTwo') : null;
var lineLength = attributeFormData.has('lineLength') ? attributeFormData.get('lineLength') : null;
return React.createElement(
'div',
null,
React.createElement(
'table',
{ style: tableStyle },
React.createElement(
'tbody',
null,
React.createElement(
'tr',
null,
React.createElement(
'td',
{ style: firstTdStyle },
translator.t('Name')
),
React.createElement(
'td',
null,
React.createElement(FormTextInput, {
value: name,
onChange: function onChange(event) {
return _onUpdate('name', event.target.value);
},
style: inputStyle
})
)
),
React.createElement(
'tr',
null,
React.createElement(
'td',
{ style: firstTdStyle },
'X1'
),
React.createElement(
'td',
null,
React.createElement(FormNumberInput, _extends({
value: vertexOne.get('x'),
onChange: function onChange(event) {
return _onUpdate('vertexOne', { 'x': event.target.value });
},
style: inputStyle,
state: state,
precision: 2
}, rest))
)
),
React.createElement(
'tr',
null,
React.createElement(
'td',
{ style: firstTdStyle },
'Y1'
),
React.createElement(
'td',
null,
React.createElement(FormNumberInput, _extends({
value: vertexOne.get('y'),
onChange: function onChange(event) {
return _onUpdate('vertexOne', { 'y': event.target.value });
},
style: inputStyle,
state: state,
precision: 2
}, rest))
)
),
React.createElement(
'tr',
null,
React.createElement(
'td',
{ style: firstTdStyle },
'X2'
),
React.createElement(
'td',
null,
React.createElement(FormNumberInput, _extends({
value: vertexTwo.get('x'),
onChange: function onChange(event) {
return _onUpdate('vertexTwo', { 'x': event.target.value });
},
style: inputStyle,
state: state,
precision: 2
}, rest))
)
),
React.createElement(
'tr',
null,
React.createElement(
'td',
{ style: firstTdStyle },
'Y2'
),
React.createElement(
'td',
null,
React.createElement(FormNumberInput, _extends({
value: vertexTwo.get('y'),
onChange: function onChange(event) {
return _onUpdate('vertexTwo', { 'y': event.target.value });
},
style: inputStyle,
state: state,
precision: 2
}, rest))
)
)
)
),
React.createElement(PropertyLengthMeasure, {
value: lineLength,
onUpdate: function onUpdate(mapped) {
return _onUpdate('lineLength', mapped);
},
configs: { label: translator.t('Length'), min: 0, max: Infinity, precision: 2 },
state: state
})
);
}
LineAttributesEditor.propTypes = {
element: PropTypes.object.isRequired,
onUpdate: PropTypes.func.isRequired,
onValid: PropTypes.func,
attributeFormData: PropTypes.object.isRequired,
state: PropTypes.object.isRequired
};
LineAttributesEditor.contextTypes = {
translator: PropTypes.object.isRequired
}; |
src/Containers/TagListContainer.js | sashasushko/moira-front | // @flow
import React from 'react';
import type { ContextRouter } from 'react-router-dom';
import type { IMoiraApi } from '../Api/MoiraAPI';
import type { TagStat } from '../Domain/Tag';
import { withMoiraApi } from '../Api/MoiraApiInjection';
import Layout from '../Components/Layout/Layout';
type Props = ContextRouter & { moiraApi: IMoiraApi };
type State = {|
loading: boolean;
error: boolean;
list: ?Array<TagStat>;
|};
class TagListContainer extends React.Component {
props: Props;
state: State = {
loading: true,
error: true,
list: null,
};
componentDidMount() {
this.getData();
}
async getData(): Promise<void> {
const { moiraApi } = this.props;
try {
const stats = await moiraApi.getTagStats();
this.setState({ loading: false, ...stats });
}
catch (error) {
this.setState({ error: true });
}
}
render(): React.Element<*> {
const { loading, error, list } = this.state;
return (
<Layout loading={loading} loadingError={error}>
<Layout.Content>
<pre>{JSON.stringify(list, null, 2)}</pre>
</Layout.Content>
</Layout>
);
}
}
export default withMoiraApi(TagListContainer);
|
src/SparklinesReferenceLine.js | codevlabs/react-sparklines | import React from 'react';
import DataProcessor from './DataProcessor';
export default class SparklinesReferenceLine extends React.Component {
static propTypes = {
type: React.PropTypes.oneOf(['max', 'min', 'mean', 'avg', 'median']),
style: React.PropTypes.object
};
static defaultProps = {
type: 'mean',
style: { stroke: 'red', strokeOpacity: .75, strokeDasharray: '2, 2' }
};
render() {
const { points, margin, type, style } = this.props;
const ypoints = points.map(p => p.y);
const y = DataProcessor.calculateFromData(ypoints, type);
return (
<line
x1={points[0].x} y1={y + margin}
x2={points[points.length - 1].x} y2={y + margin}
style={style} />
)
}
}
|
frontend/src/containers/PlayerNav/index.js | webrecorder/webrecorder | import React from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import PlayerNavUI from 'components/player/PlayerNavUI';
const mapStateToProps = ({ app }) => {
return {
collectionLoaded: app.getIn(['collection', 'loaded']),
source: app.getIn(['appSettings', 'source'])
};
};
export default withRouter(connect(mapStateToProps)(PlayerNavUI));
|
src/components/EditProfile.js | partneran/partneran | import React, { Component } from 'react';
import Footer from './Footer/Footer'
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import draftToHtml from 'draftjs-to-html';
import Loading from './Lib/Loading';
import { assign } from 'lodash'
// import { isLoggedIn } from '../../helpers/verification';
import Auth from '../helpers/token';
import { editProfile } from '../actions/user'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
// const jwt = require('jsonwebtoken')
// const imgur = require('imgur');
// const ImgUpload = (file) => {
// imgur.uploadFile(file)
// .then(function (json) {
// console.log(json.data.link);
// return json.data.link;
// })
// .catch(function (err) {
// console.error(err.message);
// });
// }
// import {
// convertFromHTML,
// convertToRaw,
// ContentState,
// } from 'draft-js';
class EditProfile extends Component {
constructor(props) {
super(props)
this.state = {
name: "" || Auth.getUser().name,
email: "" || Auth.getUser().email,
bio: "",
photo_URL: "" || Auth.getUser().photo_URL,
imagePreviewUrl: "",
loading: false
}
this.onChange = this.onChange.bind(this)
this.onSubmit = this.onSubmit.bind(this)
this.onEditorChange = this.onEditorChange.bind(this)
}
_handleImageChange(e) {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = () => {
this.setState({
photo_URL: file,
imagePreviewUrl: reader.result
});
}
reader.readAsDataURL(file)
}
// ImgUpload(e) {
// imgur.uploadFile({this.state})
// .then(function (json) {
// this.setState({
// image: json.data.link
// })
// })
// .catch(function (err) {
// console.error(err.message);
// });
// }
// ImgUpload(e) {
// imgur.uploadFile(file)
// .then(function (json) {
// console.log(json.data.link);
// return json.data.link;
// })
// .catch(function (err) {
// console.error(err.message);
// });
// }
onChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
onSubmit(e) {
e.preventDefault()
// call dispatch to state
this.props.editProfile(assign(this.state, {UserId: Auth.getUser().sub}))
}
onEditorChange(bio) {
this.setState({
bio: draftToHtml(bio)
})
}
render() {
const { name, email, bio, loading, photo_URL, imagePreviewUrl} = this.state;
let $imagePreview = null;
if (imagePreviewUrl) {
$imagePreview = (<img src={imagePreviewUrl} alt={name} className="img-responsive"/>);
} else if(photo_URL) {
$imagePreview = (<img src={photo_URL} alt={name} className="img-responsive"/>);
} else {
$imagePreview = (<p>No image selected, plese select an image for a preview</p>)
}
// isLoggedIn()
return (
<div>
{(loading) ? <Loading /> :
<div className="components-page">
<div className="wrapper">
<div id="new-idea-intro" className="header header-filter">
<div className="container">
<div className="row text-center">
<h1 className="title">Edit Profile</h1>
<h5>Change something about your profile</h5>
</div>
</div>
</div>
<div className="main">
<div className="container">
<div className="row">
<div className="card form-card">
<div className="card-header" data-background-color="blue">
<h4 className="title">Your Profile</h4>
<p className="category">Tell us about you</p>
</div>
<div className="card-signup">
<div className="container">
<form encType="multipart/form-data" onSubmit={this.onSubmit}>
<div className="form-group label-floating">
<label className="control-label">Name</label>
<input
type="text"
className="form-control"
name="name"
value={name}
onChange={this.onChange}
required
/>
</div>
<div className="form-group label-floating">
<label className="control-label">Email</label>
<input
type="email"
className="form-control"
name="email"
value={email}
onChange={this.onChange}
required
/>
</div>
<div className="form-group label-floating">
<div className="row">
<div className="col-md-offset-3 col-md-6 text-center">
{$imagePreview}
</div>
</div>
<label className="btn btn-info btn-sm">Upload Image</label>
<input
className="fileInput"
type="file"
onChange={(e)=>this._handleImageChange(e)}
name="photo_URL"
id="exampleInputFile"
/>
</div>
<br/>
<br/>
<div className="form-group">
<br/>
<label>Tell us more about you</label>
<Editor
bio={bio}
onChange={this.onEditorChange}
/>
</div>
<div className="form-group">
<button type="submit" className="btn btn-info">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<Footer />
</div>
}
</div>
)
}
}
// export default EditProfile;
function mapDispatchToProps(dispatch) {
return {
editProfile: bindActionCreators(editProfile, dispatch)
}
}
export default connect(null, mapDispatchToProps)(EditProfile)
|
ui/src/components/FocusGroup/FocusGroup.js | LearningLocker/learninglocker | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import onClickOutside from 'react-onclickoutside';
class FocusGroup extends Component {
static propTypes = {
className: PropTypes.string,
onFocus: PropTypes.func,
onBlur: PropTypes.func,
hasFocus: PropTypes.bool,
children: PropTypes.node,
}
handleClickOutside = () => {
if (this.props.hasFocus) {
this.props.onBlur();
}
}
handleClick = () => {
if (!this.props.hasFocus) {
this.props.onFocus();
}
}
render = () => (
<div
ref={(wrapper) => { this.wrapper = wrapper; }}
className={this.props.className}
onClick={this.handleClick}>
{this.props.children}
</div>
)
}
export default onClickOutside(FocusGroup);
|
src/components/auth/UnauthenticatedRoute.js | mg4tv/mg4tv-web | import React from 'react'
import {Redirect, Route} from 'react-router'
import auth from '../../auth'
const UnauthenticatedRoute = ({component: Component, ...rest}) => (
<Route {...rest} render={(props) => (
(!auth.isAuthenticated) ?
<Component {...props} /> :
<Redirect
to={{
pathname: '/',
state: {from: props.location}
}}
/>
)}
/>
)
export default UnauthenticatedRoute
|
src/index.js | reactjs-andru1989/blog | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
// Switch searches the first Route component path match with current browser route
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import promise from 'redux-promise';
import reducers from './reducers';
import PostsIndex from './components/posts_index';
import PostsNew from './components/posts_new';
import PostsShow from './components/posts_show';
const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<div>
<Switch>
<Route path="/posts/new" component={PostsNew} />
<Route path="/posts/:id" component={PostsShow} />
<Route path="/" component={PostsIndex} />
</Switch>
</div>
</BrowserRouter>
</Provider>
, document.querySelector('.container'));
|
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js | quentinbernet/quentinbernet.github.io | import React from 'react';
import { render } from 'react-dom';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
render(<HelloWorld />, document.getElementById('react-root'));
|
app/javascript/mastodon/features/compose/containers/sensitive_button_container.js | abcang/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { changeComposeSensitivity } from 'mastodon/actions/compose';
import { injectIntl, defineMessages, FormattedMessage } from 'react-intl';
const messages = defineMessages({
marked: {
id: 'compose_form.sensitive.marked',
defaultMessage: '{count, plural, one {Media is marked as sensitive} other {Media is marked as sensitive}}',
},
unmarked: {
id: 'compose_form.sensitive.unmarked',
defaultMessage: '{count, plural, one {Media is not marked as sensitive} other {Media is not marked as sensitive}}',
},
});
const mapStateToProps = state => ({
active: state.getIn(['compose', 'sensitive']),
disabled: state.getIn(['compose', 'spoiler']),
mediaCount: state.getIn(['compose', 'media_attachments']).size,
});
const mapDispatchToProps = dispatch => ({
onClick () {
dispatch(changeComposeSensitivity());
},
});
class SensitiveButton extends React.PureComponent {
static propTypes = {
active: PropTypes.bool,
disabled: PropTypes.bool,
mediaCount: PropTypes.number,
onClick: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
render () {
const { active, disabled, mediaCount, onClick, intl } = this.props;
return (
<div className='compose-form__sensitive-button'>
<label className={classNames('icon-button', { active })} title={intl.formatMessage(active ? messages.marked : messages.unmarked, { count: mediaCount })}>
<input
name='mark-sensitive'
type='checkbox'
checked={active}
onChange={onClick}
disabled={disabled}
/>
<span className={classNames('checkbox', { active })} />
<FormattedMessage
id='compose_form.sensitive.hide'
defaultMessage='{count, plural, one {Mark media as sensitive} other {Mark media as sensitive}}'
values={{ count: mediaCount }}
/>
</label>
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(SensitiveButton));
|
js/App/Components/Device/Common/ZWaveIncludeExcludeUI.js | telldus/telldus-live-mobile-v3 | /**
* Copyright 2016-present Telldus Technologies AB.
*
* This file is part of the Telldus Live! app.
*
* Telldus Live! app is free : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Telldus Live! app is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>.
*
*/
// @flow
'use strict';
import React from 'react';
import {
Platform,
TouchableOpacity,
} from 'react-native';
const isEqual = require('react-fast-compare');
import {
View,
Text,
Image,
InfoBlock,
ProgressBarLinear,
Throbber,
Icon,
} from '../../../../BaseComponents';
import {
withTheme,
PropsThemedComponent,
} from '../../HOC/withTheme';
import Theme from '../../../Theme';
import shouldUpdate from '../../../Lib/shouldUpdate';
import i18n from '../../../Translations/common';
type Props = PropsThemedComponent & {
appLayout: Object,
timer: number | null | string,
status: string | null,
percent: number,
progress: number,
showThrobber?: boolean,
infoText?: string,
deviceImage: string,
actionsDescription?: string,
action: 'include' | 'exclude',
intl: Object,
onPressCancel?: Function,
};
type State = {
width: number,
};
type DefaultProps = {
action: 'include' | 'exclude',
showThrobber: boolean,
deviceImage: string,
};
class ZWaveIncludeExcludeUI extends View<Props, State> {
props: Props;
state: State;
onLayout: (Object) => void;
static defaultProps: DefaultProps = {
action: 'include',
showThrobber: false,
deviceImage: 'img_zwave_include',
};
constructor(props: Props) {
super(props);
this.state = {
width: 0,
};
this.onLayout = this.onLayout.bind(this);
const { action, intl } = this.props;
const { formatMessage } = intl;
this.isInclude = action === 'include';
this.isExclude = action === 'exclude';
this.messageOne = this.isInclude ? formatMessage(i18n.messageOne) : formatMessage(i18n.messageOneExclude);
this.messageTwo = this.isInclude ? formatMessage(i18n.messageTwo) : formatMessage(i18n.messageTwoExclude);
}
shouldComponentUpdate(nextProps: Object, nextState: Object): boolean {
if (shouldUpdate(nextProps, this.props, [
'showThrobber',
'progress',
'percent',
'status',
'timer',
'appLayout',
'deviceImage',
'infoText',
'themeInApp',
'colorScheme',
'selectedThemeSet',
'actionsDescription',
])) {
return true;
}
if (!isEqual(this.state, nextState)) {
return true;
}
return false;
}
onLayout(ev: Object) {
let { width } = ev.nativeEvent.layout;
if (this.state.width !== width) {
this.setState({
width,
});
}
}
render(): Object {
const {
intl,
timer,
status,
progress,
showThrobber,
infoText,
deviceImage,
onPressCancel,
appLayout,
actionsDescription,
} = this.props;
const { width } = this.state;
const {
container,
progressContainer,
infoContainer,
imageType,
textStyle,
infoIconStyle,
markerTextCover,
markerText,
timerStyle,
statusStyle,
blockLeft,
infoOneContainer,
headerTextStyle,
throbberContainerStyle,
iconCancelStyle,
iconCancelSize,
iconCancelColor,
} = this.getStyles();
const { formatMessage } = intl;
const showInfo = this.isInclude && !!infoText;
const showIconCancel = !!onPressCancel;
return (
<View style={container}>
<View
level={2}
style={progressContainer}>
<View style={[blockLeft, {
flexDirection: 'column',
alignItems: 'flex-start',
}]}>
{this.isInclude && (
[
<View style={markerTextCover} key={'0'}/>,
<Text style={markerText} key={'1'}>
1.
</Text>,
]
)}
<Image source={{uri: deviceImage}} resizeMode={'cover'} style={imageType}/>
</View>
<View style={infoOneContainer} onLayout={this.onLayout}>
{this.isExclude && (
[<Text style={headerTextStyle} key={'0'}>
{formatMessage(i18n.headerExclude)}
</Text>,
<Text key={'1'}/>]
)}
{actionsDescription ?
<>
<Text>
<Text
level={4}
style={textStyle}>
{'Information from the manufacturer: '}
</Text>
<Text
level={25}
style={textStyle}>
{actionsDescription}
</Text>
</Text>
<Text/>
</>
:
<>
<Text
level={25}
style={textStyle}>
{this.messageOne}
</Text>
<Text/>
<Text
level={25}
style={textStyle}>
{this.messageTwo}
</Text>
<Text/>
</>
}
{showThrobber ?
<Throbber throbberContainerStyle={throbberContainerStyle} throbberStyle={timerStyle}/>
:
<>
<View style={{
flexDirection: 'row',
alignItems: 'center',
}}>
<Text style={timerStyle} key={'0'}>
{timer}
</Text>
{showIconCancel && <TouchableOpacity
onPress={onPressCancel}>
<Icon
style={iconCancelStyle}
name={'times-circle'}
size={iconCancelSize}
color={iconCancelColor}/>
</TouchableOpacity>
}
</View>
<Text
level={25}
style={statusStyle} key={'1'}>
{status}
</Text>
</>
}
<ProgressBarLinear
progress={progress}
height={4}
width={width}
borderWidth={0}
borderColor="transparent"
unfilledColor={Theme.Core.inactiveSwitchBackground} />
</View>
</View>
{showInfo && (
<InfoBlock
text={infoText}
appLayout={appLayout}
infoContainer={infoContainer}
textStyle={textStyle}
infoIconStyle={infoIconStyle}/>
)}
</View>
);
}
getStyles(): Object {
const { appLayout, colors } = this.props;
const { height, width } = appLayout;
const isPortrait = height > width;
const deviceWidth = isPortrait ? width : height;
const {
inAppBrandSecondary,
inAppBrandPrimary,
} = colors;
const {
paddingFactor,
shadow,
inactiveSwitchBackground,
fontSizeFactorFive,
fontSizeFactorEight,
fontSizeFactorTen,
} = Theme.Core;
const padding = deviceWidth * paddingFactor;
const fontSizeText = deviceWidth * fontSizeFactorTen;
const fontSizeStatus = deviceWidth * 0.03;
const blockIconContainerSize = deviceWidth * 0.26;
const contPadding = 5 + (fontSizeText * 0.5);
const markerHeight = deviceWidth * 0.075;
const contOneTop = markerHeight - contPadding;
const iconCancelSize = fontSizeText * 1.3;
const iconCancelColor = inactiveSwitchBackground;
return {
innerPadding: contPadding,
container: {
paddingTop: padding,
paddingBottom: padding / 2,
marginHorizontal: padding,
},
progressContainer: {
flex: 1,
flexDirection: 'row',
marginBottom: padding / 2,
borderRadius: 2,
padding: contPadding,
...shadow,
},
infoContainer: {
flex: 1,
flexDirection: 'row',
marginBottom: padding / 2,
borderRadius: 2,
padding: contPadding,
...shadow,
},
markerTextCover: {
position: 'absolute',
left: -(contPadding),
top: -(contPadding),
width: deviceWidth * 0.2,
height: Platform.OS === 'ios' ? deviceWidth * fontSizeFactorFive : 0,
backgroundColor: 'transparent',
borderStyle: 'solid',
borderRightWidth: deviceWidth * fontSizeFactorFive,
borderTopWidth: Platform.OS === 'ios' ? deviceWidth * 0.17 : deviceWidth * 0.1,
borderRightColor: 'transparent',
borderTopColor: inAppBrandPrimary,
borderTopLeftRadius: 2,
},
markerText: {
position: 'absolute',
fontSize: deviceWidth * fontSizeFactorFive,
color: '#fff',
top: -(contPadding) + (deviceWidth * 0.025),
left: deviceWidth * 0.025,
},
infoOneContainer: {
flex: 1,
flexDirection: 'column',
paddingTop: contOneTop,
},
headerTextStyle: {
fontSize: fontSizeText * 1.2,
color: inAppBrandSecondary,
},
imageType: {
marginTop: markerHeight,
height: deviceWidth * 0.20,
width: deviceWidth * 0.17,
},
textStyle: {
fontSize: fontSizeText,
flexWrap: 'wrap',
},
infoIconStyle: {
fontSize: blockIconContainerSize / 2,
},
blockIcontainerStyle: {
width: blockIconContainerSize,
height: undefined,
borderRadius: 0,
backgroundColor: 'transparent',
},
timerStyle: {
fontSize: deviceWidth * fontSizeFactorEight,
color: inAppBrandSecondary,
textAlignVertical: 'center',
marginRight: 5,
},
throbberContainerStyle: {
position: 'relative',
alignSelf: 'flex-start',
marginBottom: 4,
},
statusStyle: {
fontSize: fontSizeStatus,
marginBottom: 4,
},
blockLeft: {
width: deviceWidth * 0.21,
justifyContent: 'center',
alignItems: 'center',
},
iconCancelStyle: {
paddingHorizontal: 4,
justifyContent: 'center',
alignItems: 'center',
},
iconCancelSize,
iconCancelColor,
};
}
}
export default (withTheme(ZWaveIncludeExcludeUI): Object);
|
src/components/count-icon.js | josebigio/PodCast | import React from 'react';
const CountIcon = ({ style, count, color="#fafafa", radius="30px" }) => {
const styles = {
...style,
borderRadius: "50%",
width: radius,
height: radius,
lineHeight: radius,
backgroundColor: color ,
textAlign: "center",
fontSize: "small",
margin:"5px"
}
return <div style={styles}>{count}</div>
}
export default CountIcon; |
js/redux/learn-redux/node_modules/react-router/es6/RoutingContext.js | austinjalexander/sandbox | import React from 'react';
import RouterContext from './RouterContext';
import warning from './routerWarning';
var RoutingContext = React.createClass({
displayName: 'RoutingContext',
componentWillMount: function componentWillMount() {
process.env.NODE_ENV !== 'production' ? warning(false, '`RoutingContext` has been renamed to `RouterContext`. Please use `import { RouterContext } from \'react-router\'`. http://tiny.cc/router-routercontext') : void 0;
},
render: function render() {
return React.createElement(RouterContext, this.props);
}
});
export default RoutingContext; |
spec/components/chip.js | showings/react-toolbox | import React from 'react';
import Avatar from '../../components/avatar';
import Chip from '../../components/chip';
import style from '../style';
class ChipTest extends React.Component {
state = {
deleted: false,
};
handleDeleteClick = () => {
this.setState({
deleted: true,
});
};
render() {
return (
<section>
<h5>Chips</h5>
<p>Chips can be deletable and have an avatar.</p>
<Chip>Example chip</Chip>
<Chip>
<span style={{ textDecoration: 'line-through' }}>Standard</span>
<strong>Custom</strong> chip <small>(custom markup)</small>
</Chip>
{
this.state.deleted ? null : (
<Chip
deletable
onDeleteClick={this.handleDeleteClick}
>
Deletable Chip
</Chip>
)
}
<Chip>
<Avatar style={{ backgroundColor: 'deepskyblue' }} icon="folder" />
<span>Avatar Chip</span>
</Chip>
<Chip>
<Avatar title="A" /><span>Initial chip</span>
</Chip>
<Chip>
<Avatar><img src="https://placeimg.com/80/80/animals" /></Avatar>
<span>Image contact chip</span>
</Chip>
<div className={style.chipTruncateWrapper}>
<Chip deletable>
Truncated chip with long label. Lorem ipsum Amet quis mollit Excepteur id dolore.
</Chip>
</div>
</section>
);
}
}
export default ChipTest;
|
pkg/interface/chat/src/js/components/lib/group-item.js | ngzax/urbit | import React, { Component } from 'react';
import { ChannelItem } from './channel-item';
export class GroupItem extends Component {
render() {
const { props, state } = this;
let association = !!props.association ? props.association : {};
let title = association["app-path"] ? association["app-path"] : "Direct Messages";
if (association.metadata && association.metadata.title) {
title = association.metadata.title !== ""
? association.metadata.title
: title;
}
let channels = !!props.channels ? props.channels : [];
let first = (props.index === 0) ? "pt1" : "pt4"
let channelItems = channels.sort((a, b) => {
if (props.index === "/~/") {
let aPreview = props.messagePreviews[a];
let bPreview = props.messagePreviews[b];
let aWhen = !!aPreview ? aPreview.when : 0;
let bWhen = !!bPreview ? bPreview.when : 0;
return bWhen - aWhen;
} else {
let aAssociation = a in props.chatMetadata ? props.chatMetadata[a] : {};
let bAssociation = b in props.chatMetadata ? props.chatMetadata[b] : {};
let aTitle = a;
let bTitle = b;
if (aAssociation.metadata && aAssociation.metadata.title) {
aTitle = (aAssociation.metadata.title !== "")
? aAssociation.metadata.title : a;
}
if (bAssociation.metadata && bAssociation.metadata.title) {
bTitle =
bAssociation.metadata.title !== "" ? bAssociation.metadata.title : b;
}
return aTitle.toLowerCase().localeCompare(bTitle.toLowerCase());
}
}).map((each, i) => {
let unread = props.unreads[each];
let title = each.substr(1);
if (
each in props.chatMetadata &&
props.chatMetadata[each].metadata
) {
title = props.chatMetadata[each].metadata.title
? props.chatMetadata[each].metadata.title
: each.substr(1);
}
let selected = props.station === each;
return (
<ChannelItem
key={i}
unread={unread}
title={title}
selected={selected}
box={each}
{...props}
/>
)
})
return (
<div className={first}>
<p className="f9 ph4 fw6 pb2 gray3">{title}</p>
{channelItems}
</div>
)
}
}
export default GroupItem
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.