path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
src/example/app/pages/MemberForm.js | lighter-cd/ezui_react_one | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';
import {Container,FixedBox,EnlargeBox} from '../../../lib/flexBoxLayout';
import {Row,Col} from '../../../lib/flexBoxGrid';
import {Button} from '../../../lib/components/form';
import {Popup} from '../../../lib/components/popup';
import dropDown from '../../assets/icons/dropdown.png';
import showList from '../../assets/icons/show_list.png';
import profession from './profession';
import position from './position';
import PopupSelector from './PopupSelector';
const styles = {
lable : {
display: 'block',
width: '100%',
height: '0.60rem',
lineHeight: '0.60rem',
fontSize: '.30rem',
color: '#6d6d6d',
},
input : {
width: '100%',
height: '0.60rem',
lineHeight: '0.60rem',
padding: '0 0.2rem', /* The 6px vertically centers text on FF, ignored by Webkit */
backgroundColor: '#fff',
border: '0.02rem solid #D1D1D1',
borderRadius: '0.08rem',
boxShadow: 'none',
boxSizing: 'border-box',
fontSize: '.30rem',
'&:focus' : {
border: '0.02rem solid #33C3F0',
outline: 0,
}
},
select : {
/*很关键:将默认的select选择框样式清除*/
appearance:'none',
MozAppearance:'none',
WebkitAppearance:'none',
backgroundColor: 'transparent',
//backgroundImage: 'url("paper.gif")',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'right center',
backgroundAttachment: 'scroll',
backgroundSize: '0.53rem 0.33rem',
/*在选择框的最右侧中间显示小箭头图片*/
//background: 'url("http://ourjs.github.io/static/2015/arrow.png") no-repeat scroll right center transparent',
/*为下拉小箭头留出一点位置,避免被文字覆盖*/
paddingRight: '.36rem',
}
}
const sexOptions = [
{key: 'm', text: '男', value: 1},
{key: 'f', text: '女', value: 0},
];
const hourOptions = [
{value: 0, text: '0:00~1:00:子时'},
{value: 1, text: '1:00~3:00:丑时'},
{value: 3, text: '3:00~5:00:寅时'},
{value: 5, text: '5:00~7:00:卯时'},
{value: 7, text: '7:00~9:00:辰时'},
{value: 9, text: '9:00~11:00:巳时'},
{value: 11, text: '11:00~13:00:午时'},
{value: 13, text: '13:00~15:00:未时'},
{value: 15, text: '15:00~17:00:申时'},
{value: 17, text: '17:00~19:00:酉时'},
{value: 19, text: '19:00~21:00:戌时'},
{value: 21, text: '21:00~23:00:亥时'},
{value: 23, text: '23:00~0:00:子时'},
{value: 255, text: '不详'},
];
class MemberForm extends Component {
static propTypes = {
/*userData: PropTypes.object.isRequired,
submitButtonCaption: PropTypes.string.isRequired,
handleSubmit: PropTypes.func.isRequired,
submitType: PropTypes.oneOf(['register', 'modify']).isRequired,*/
};
state = {
account: '',
password: '',
password2: '',
name: '',
sex: -1,
birthday: '',
hour: -1,
phone: '',
profession: -1,
position: -1,
home_province: -1,
home_city: -1,
location_province: -1,
location_city: -1,
plate_no: '',
house_no: '',
formError: false,
formErrorMessage: '',
listPage: null,
professionText:'请选择所从事的职业',
positionText:'请选择担任的职位',
provinceOptions:[],
homeCityOptions:[],
lifeCityOptions:[],
};
render() {
const row_between = '.36rem';
let backgroundImage = `url("${dropDown}")`;
return (
<form style={{padding:'0 .40rem'}}>
{this.listPage()}
<Row marginTop={row_between}>
<Col xs={3}>
<span style={styles.lable}>手机号码:</span>
</Col>
<Col xs={9}>
<input type='number' placeholder="+86手机号码" style={styles.input}/>
</Col>
</Row>
<Row marginTop={row_between}>
<Col xs={3}>
<span style={styles.lable}>登录密码:</span>
</Col>
<Col xs={9}>
<input type='password' placeholder="请输入登录密码" style={styles.input}/>
</Col>
</Row>
<Row marginTop={row_between}>
<Col xs={3}>
<span style={styles.lable}>重复密码:</span>
</Col>
<Col xs={9}>
<input type='password' placeholder="请重复输入登录密码" style={styles.input}/>
</Col>
</Row>
<Row marginTop={row_between}>
<Col xs={3}>
<span style={styles.lable}>姓名:</span>
</Col>
<Col xs={9}>
<input type='text' placeholder="请填写真实姓名" style={styles.input}/>
</Col>
</Row>
<Row marginTop={row_between}>
<Col xs={3}>
<span style={styles.lable}>性别:</span>
</Col>
<Col xs={9}>
<select name="hour" style={{...styles.input,...styles.select,backgroundImage:backgroundImage}}
onChange={this.handleSelectChange.bind(this)}
value = {this.state.hour}>
<option value={-1} key={-1} disabled="disabled" style={{display:'none'}}>请选择性别</option>
{
sexOptions.map((item,index)=>{
return <option value={item.value} key={index}>{item.text}</option>
})
}
</select>
</Col>
</Row>
<Row marginTop={row_between}>
<Col xs={3}>
<span style={styles.lable}>生日(公历):</span>
</Col>
<Col xs={9}>
<input type='date' placeholder="请选择出生日期" style={{...styles.input,...styles.select,backgroundImage:backgroundImage}}/>
</Col>
</Row>
<Row marginTop={row_between}>
<Col xs={3}>
<span style={styles.lable}>出生时间:</span>
</Col>
<Col xs={9}>
<select name="hour" style={{...styles.input,...styles.select,backgroundImage:backgroundImage}}
onChange={this.handleSelectChange.bind(this)}
value = {this.state.hour}>
<option value={-1} key={-1} disabled="disabled" style={{display:'none'}}>请选择出生时间</option>
{
hourOptions.map((item,index)=>{
return <option value={item.value} key={index}>{item.text}</option>
})
}
</select>
</Col>
</Row>
<Row marginTop={row_between}>
<Col xs={3}>
<span style={styles.lable}>职业:</span>
</Col>
<Col xs={9}>
<input type='button' value="选择所从事的职业" style={{...styles.input,...styles.select,textAlign: 'left',backgroundImage:`url("${showList}")`}}
onClick={this.handleProfessionClick.bind(this)}/>
</Col>
</Row>
<Row marginTop={row_between}>
<Col xs={3}>
<span style={styles.lable}>职位:</span>
</Col>
<Col xs={9}>
<input type='button' value="选择所担任的职位" style={{...styles.input,...styles.select,textAlign: 'left', backgroundImage:`url("${showList}")`}}/>
</Col>
</Row>
<Row marginTop={row_between}>
<Col xs={3}>
<span style={styles.lable}>出生地:</span>
</Col>
<Col xs={9}>
<Row>
<Col xs={6}>
<select name="hour" style={{...styles.input,...styles.select,backgroundImage:backgroundImage}}
onChange={this.handleSelectChange.bind(this)}
value = {this.state.hour}>
<option value={-1} key={-1} disabled="disabled" style={{display:'none'}}>请选择省份</option>
{
sexOptions.map((item,index)=>{
return <option value={item.value} key={index}>{item.text}</option>
})
}
</select>
</Col>
<Col xs={6}>
<select name="hour" style={{...styles.input,...styles.select,backgroundImage:backgroundImage}}
onChange={this.handleSelectChange.bind(this)}
value = {this.state.hour}>
<option value={-1} key={-1} disabled="disabled" style={{display:'none'}}>请选择城市</option>
{
sexOptions.map((item,index)=>{
return <option value={item.value} key={index}>{item.text}</option>
})
}
</select>
</Col>
</Row>
</Col>
</Row>
<Row marginTop={row_between}>
<Col xs={3}>
<span style={styles.lable}>居住地:</span>
</Col>
<Col xs={9}>
<Row>
<Col xs={6}>
<select name="hour" style={{...styles.input,...styles.select,backgroundImage:backgroundImage}}
onChange={this.handleSelectChange.bind(this)}
value = {this.state.hour}>
<option value={-1} key={-1} disabled="disabled" style={{display:'none'}}>请选择省份</option>
{
sexOptions.map((item,index)=>{
return <option value={item.value} key={index}>{item.text}</option>
})
}
</select>
</Col>
<Col xs={6}>
<select name="hour" style={{...styles.input,...styles.select,backgroundImage:backgroundImage}}
onChange={this.handleSelectChange.bind(this)}
value = {this.state.hour}>
<option value={-1} key={-1} disabled="disabled" style={{display:'none'}}>请选择城市</option>
{
sexOptions.map((item,index)=>{
return <option value={item.value} key={index}>{item.text}</option>
})
}
</select>
</Col>
</Row>
</Col>
</Row>
<Row marginTop={row_between}>
<Col xs={3}>
<span style={styles.lable}>详细地址:</span>
</Col>
<Col xs={9}>
<input type='text' placeholder="请填写详细地址" style={styles.input}/>
</Col>
</Row>
<Row marginTop={row_between} marginBottom={row_between}>
<Col xs={3}>
<span style={styles.lable}>车牌号码:</span>
</Col>
<Col xs={9}>
<input type='text' placeholder="请填写车牌号码" style={styles.input}/>
</Col>
</Row>
</form>
)
}
listPage() {
return (
<Popup
show={this.state.listPage!==null}
onRequestClose={e=>this.setState({listPage: null})}
>
<PopupSelector listPage={this.state.listPage} handleClose={e=>this.setState({listPage: null})} handleSelect={this.handleListSelected.bind(this)}/>
</Popup>
);
}
submit(){
alert('submit');
}
handleSelectChange(e){
let data = {
name : e.target.name,
value : parseInt(e.target.value,10),
};
this.handleTextChange(e,data)
}
handleTextChange(e, data) {
let otherState = {};
if(data.name === 'home_province'){
otherState['homeCityOptions'] = this.buildCity(data.value);
otherState['home_city']=-1;
}else if(data.name === 'location_province'){
otherState['lifeCityOptions'] = this.buildCity(data.value);
otherState['location_city']=-1;
}
otherState[data.name] = data.value;
this.setState(otherState);
}
handleProfessionClick(){
this.setState({listPage: {list:profession,field:'profession',title:'请选择所从事的行业' }});
}
handleListSelected(id,value,list){
alert(id + value);
this.setState({listPage: null});
}
}
export default MemberForm; |
src/components/input.js | frig-js/frig | import React from 'react'
import UnboundInput from './unbound_input.js'
export default class Input extends React.Component {
static propTypes = {
name: React.PropTypes.string.isRequired,
errors: React.PropTypes.arrayOf(React.PropTypes.string),
layout: React.PropTypes.string,
align: React.PropTypes.string,
className: React.PropTypes.string,
disabled: React.PropTypes.bool,
multiple: React.PropTypes.bool,
type: React.PropTypes.string,
options: React.PropTypes.array,
validate: React.PropTypes.bool,
// Callbacks (Public API)
onChange: React.PropTypes.func.isRequired,
onValidChange: React.PropTypes.func.isRequired,
}
static contextTypes = {
frigForm: React.PropTypes.shape({
data: React.PropTypes.object.isRequired,
theme: React.PropTypes.object.isRequired,
errors: React.PropTypes.object.isRequired,
layout: React.PropTypes.string.isRequired,
align: React.PropTypes.string.isRequired,
saved: React.PropTypes.object.isRequired,
// Callbacks (Private API - reserved for frig form use only)
requestChildComponentChange: React.PropTypes.func.isRequired,
childComponentWillMount: React.PropTypes.func.isRequired,
childComponentWillUnmount: React.PropTypes.func.isRequired,
}).isRequired,
}
static defaultProps = {
validate: true,
disabled: false,
errors: [],
onChange: () => {},
onValidChange: () => {},
}
displayName = 'Frig.Input'
/*
* =========================================================================
* React Lifecycle
* =========================================================================
*/
componentWillMount() {
this.context.frigForm.childComponentWillMount(this.props.name, this)
}
componentWillUnmount() {
this.context.frigForm.childComponentWillUnmount(this.props.name, this)
}
/*
* =========================================================================
* Public Functions
* =========================================================================
*/
validate() {
/* istanbul ignore next */
return this.refs.unboundInput.validate()
}
isValid() {
/* istanbul ignore next */
return this.refs.unboundInput.isValid()
}
isModified() {
/* istanbul ignore next */
return this.refs.unboundInput.isModified()
}
resetModified() {
/* istanbul ignore next */
return this.refs.unboundInput.resetModified()
}
reset() {
/* istanbul ignore next */
return this.refs.unboundInput.reset()
}
/*
* =========================================================================
* Private functions
* =========================================================================
*/
_onChange = (val, valid) => {
// Update the value link (used by Frig form components)
this.context.frigForm.requestChildComponentChange(this.props.name, val)
// Run the external callbacks (external API, not used by Frig internally)
this.props.onChange(val, valid)
if (valid) this.props.onValidChange(val, valid)
}
render() {
const value = this.context.frigForm.data[this.props.name]
return (
<UnboundInput
{...this.props}
ref="unboundInput"
errors={(this.props.errors || []).slice().concat(
this.context.frigForm.errors[this.props.name] || []
)}
saved={this.context.frigForm.saved[this.props.name]}
value={value == null ? '' : value}
onChange={this._onChange}
/>
)
}
}
|
app/javascript/mastodon/features/explore/suggestions.js | im-in-space/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import AccountCard from 'mastodon/features/directory/components/account_card';
import LoadingIndicator from 'mastodon/components/loading_indicator';
import { connect } from 'react-redux';
import { fetchSuggestions } from 'mastodon/actions/suggestions';
const mapStateToProps = state => ({
suggestions: state.getIn(['suggestions', 'items']),
isLoading: state.getIn(['suggestions', 'isLoading']),
});
export default @connect(mapStateToProps)
class Suggestions extends React.PureComponent {
static propTypes = {
isLoading: PropTypes.bool,
suggestions: ImmutablePropTypes.list,
dispatch: PropTypes.func.isRequired,
};
componentDidMount () {
const { dispatch } = this.props;
dispatch(fetchSuggestions(true));
}
render () {
const { isLoading, suggestions } = this.props;
return (
<div className='explore__suggestions'>
{isLoading ? <LoadingIndicator /> : suggestions.map(suggestion => (
<AccountCard key={suggestion.get('account')} id={suggestion.get('account')} />
))}
</div>
);
}
}
|
node_modules/react-native/Libraries/Modal/Modal.js | odapplications/WebView-with-Lower-Tab-Menu | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Modal
* @flow
*/
'use strict';
const AppContainer = require('AppContainer');
const I18nManager = require('I18nManager');
const Platform = require('Platform');
const React = require('React');
const StyleSheet = require('StyleSheet');
const View = require('View');
const deprecatedPropType = require('deprecatedPropType');
const requireNativeComponent = require('requireNativeComponent');
const RCTModalHostView = requireNativeComponent('RCTModalHostView', null);
const PropTypes = React.PropTypes;
/**
* The Modal component is a simple way to present content above an enclosing view.
*
* _Note: If you need more control over how to present modals over the rest of your app,
* then consider using a top-level Navigator._
*
* ```javascript
* import React, { Component } from 'react';
* import { Modal, Text, TouchableHighlight, View } from 'react-native';
*
* class ModalExample extends Component {
*
* state = {
* modalVisible: false,
* }
*
* setModalVisible(visible) {
* this.setState({modalVisible: visible});
* }
*
* render() {
* return (
* <View style={{marginTop: 22}}>
* <Modal
* animationType={"slide"}
* transparent={false}
* visible={this.state.modalVisible}
* onRequestClose={() => {alert("Modal has been closed.")}}
* >
* <View style={{marginTop: 22}}>
* <View>
* <Text>Hello World!</Text>
*
* <TouchableHighlight onPress={() => {
* this.setModalVisible(!this.state.modalVisible)
* }}>
* <Text>Hide Modal</Text>
* </TouchableHighlight>
*
* </View>
* </View>
* </Modal>
*
* <TouchableHighlight onPress={() => {
* this.setModalVisible(true)
* }}>
* <Text>Show Modal</Text>
* </TouchableHighlight>
*
* </View>
* );
* }
* }
* ```
*/
class Modal extends React.Component {
static propTypes = {
/**
* The `animationType` prop controls how the modal animates.
*
* - `slide` slides in from the bottom
* - `fade` fades into view
* - `none` appears without an animation
*/
animationType: PropTypes.oneOf(['none', 'slide', 'fade']),
/**
* The `transparent` prop determines whether your modal will fill the entire view. Setting this to `true` will render the modal over a transparent background.
*/
transparent: PropTypes.bool,
/**
* The `hardwareAccelerated` prop controls whether to force hardware acceleration for the underlying window.
* @platform android
*/
hardwareAccelerated: PropTypes.bool,
/**
* The `visible` prop determines whether your modal is visible.
*/
visible: PropTypes.bool,
/**
* The `onRequestClose` callback is called when the user taps the hardware back button.
* @platform android
*/
onRequestClose: Platform.OS === 'android' ? PropTypes.func.isRequired : PropTypes.func,
/**
* The `onShow` prop allows passing a function that will be called once the modal has been shown.
*/
onShow: PropTypes.func,
animated: deprecatedPropType(
PropTypes.bool,
'Use the `animationType` prop instead.'
),
/**
* The `supportedOrientations` prop allows the modal to be rotated to any of the specified orientations.
* On iOS, the modal is still restricted by what's specified in your app's Info.plist's UISupportedInterfaceOrientations field.
* @platform ios
*/
supportedOrientations: PropTypes.arrayOf(PropTypes.oneOf(['portrait', 'portrait-upside-down', 'landscape', 'landscape-left', 'landscape-right'])),
/**
* The `onOrientationChange` callback is called when the orientation changes while the modal is being displayed.
* The orientation provided is only 'portrait' or 'landscape'. This callback is also called on initial render, regardless of the current orientation.
* @platform ios
*/
onOrientationChange: PropTypes.func,
};
static defaultProps = {
visible: true,
hardwareAccelerated: false,
};
static contextTypes = {
rootTag: React.PropTypes.number,
};
render(): ?React.Element<any> {
if (this.props.visible === false) {
return null;
}
const containerStyles = {
backgroundColor: this.props.transparent ? 'transparent' : 'white',
};
let animationType = this.props.animationType;
if (!animationType) {
// manually setting default prop here to keep support for the deprecated 'animated' prop
animationType = 'none';
if (this.props.animated) {
animationType = 'slide';
}
}
const innerChildren = __DEV__ ?
( <AppContainer rootTag={this.context.rootTag}>
{this.props.children}
</AppContainer>) :
this.props.children;
return (
<RCTModalHostView
animationType={animationType}
transparent={this.props.transparent}
hardwareAccelerated={this.props.hardwareAccelerated}
onRequestClose={this.props.onRequestClose}
onShow={this.props.onShow}
style={styles.modal}
onStartShouldSetResponder={this._shouldSetResponder}
supportedOrientations={this.props.supportedOrientations}
onOrientationChange={this.props.onOrientationChange}
>
<View style={[styles.container, containerStyles]}>
{innerChildren}
</View>
</RCTModalHostView>
);
}
// We don't want any responder events bubbling out of the modal.
_shouldSetResponder(): boolean {
return true;
}
}
const side = I18nManager.isRTL ? 'right' : 'left';
const styles = StyleSheet.create({
modal: {
position: 'absolute',
},
container: {
position: 'absolute',
[side] : 0,
top: 0,
}
});
module.exports = Modal;
|
cm19/ReactJS/your-first-react-app-exercises-master/exercise-13/shared/Page.js | Brandon-J-Campbell/codemash | import React from 'react';
import styles from './Page.css';
export default function Page({ children }) {
return (
<div className={styles.page}>
<div className={styles.content}>{children}</div>
</div>
);
}
|
src/components/details/SetDetails.js | cpsubrian/redis-explorer | import React from 'react'
import pureRender from 'pure-render-decorator'
import ImmutablePropTypes from 'react-immutable-proptypes'
import clipboard from 'clipboard'
import Details from '../../components/details/Details'
import Highlight from '../../components/Highlight'
import Icon from '../../components/Icon'
@pureRender
class SetDetails extends React.Component {
static propTypes = {
item: ImmutablePropTypes.map
}
state = {
types: ['JSON', 'Raw'],
show: 'JSON',
hasJSON: false
}
renderValue () {
let values = this.props.item.get('value')
return values.map((value, i) => {
let result
try {
if (this.state.show === 'Raw') {
result = <pre><code>{value}</code></pre>
} else {
result = (
<Highlight className='json'>
{JSON.stringify(JSON.parse(value), null, 2)}
</Highlight>
)
}
this.state.hasJSON = true
} catch (e) {
result = <pre><code>{value}</code></pre>
}
return (
<div key={i} className='value-item'>
{result}
<div className='actions'>
<a href='#' onClick={(e) => clipboard.writeText(value)}>
<Icon type='content_paste'/>
</a>
</div>
</div>
)
})
}
renderButtons () {
let buttons = {}
// Create types buttons.
if (this.state.hasJSON) {
buttons.show = (
<div className='pill'>
{this.state.types.map((type) => {
return (
<a
key={type}
href='#'
className={(this.state.show === type) ? 'active' : null}
onClick={(e) => {
e.preventDefault()
this.setState({show: type})
}}
>
{type}
</a>
)
})}
</div>
)
}
return React.addons.createFragment(buttons)
}
render () {
let {_key, type} = this.props.item.toJS()
return (
<Details _key={_key} type={type} value={this.renderValue()} buttons={this.renderButtons()}/>
)
}
}
export default SetDetails
|
app/components/HashLink/index.js | transparantnederland/browser | import React from 'react';
import { Link } from 'react-router';
const HashLink = ({ hash, children }) =>
<Link
to={window.location.pathname}
hash={'#' + hash}
state={{ hash }}
>
{children}
</Link>;
HashLink.propTypes = {
hash: React.PropTypes.string.isRequired,
children: React.PropTypes.node.isRequired,
};
export default HashLink;
|
stories/Dropdown/ExampleControlled.js | nirhart/wix-style-react | import React from 'react';
import Dropdown from 'wix-style-react/Dropdown';
const style = {
display: 'inline-block',
padding: '0 5px 0',
width: '200px',
lineHeight: '22px',
marginBottom: '160px'
};
const options = [
{id: 1, value: 'Option 1'},
{id: 2, value: 'Option 2'},
{id: 3, value: 'Option 3'},
{id: 4, value: 'Option 4', disabled: true},
{id: 5, value: 'Option 5'},
];
class ControlledDropdown extends React.Component {
constructor(props) {
super(props);
this.onSelect = this.onSelect.bind(this);
}
onSelect(option) {
console.log(`Option ${JSON.stringify(option)} selected`);
}
render() {
return (
<Dropdown
options={options}
onSelect={this.onSelect}
placeholder={'Choose an option'}
/>
);
}
}
export default () =>
<div className="ltr" style={style}>
<ControlledDropdown/>
</div>;
|
src/Parser/Priest/Discipline/Modules/Items/CordOfMaiev.js | hasseboulen/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import Wrapper from 'common/Wrapper';
import Combatants from 'Parser/Core/Modules/Combatants';
import Analyzer from 'Parser/Core/Analyzer';
const debug = true;
const PENANCE_COOLDOWN = 9000; // unaffected by Haste
/** The amount of time during which it's impossible a second Penance could have started */
const PENANCE_CHANNEL_TIME_BUFFER = 2500;
class CordOfMaiev extends Analyzer {
static dependencies = {
combatants: Combatants,
};
procs = 0;
procTime = 0;
on_initialized() {
this.active = this.combatants.selected.hasWaist(ITEMS.CORD_OF_MAIEV_PRIESTESS_OF_THE_MOON.id);
}
lastPenanceStartTimestamp = null;
canHaveProcced = false;
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.PENANCE.id) {
// TODO: T20 4 set: Power Word: Shield has a 25% chance to cause your next Penance to be free and have 50% reduced cooldown.
if (this.canHaveProcced && (event.timestamp - this.lastPenanceStartTimestamp) < PENANCE_COOLDOWN) {
debug && console.log('%cCord of Maiev proc', 'color:green', event.timestamp, this.lastPenanceStartTimestamp, event.timestamp - this.lastPenanceStartTimestamp);
this.procs += 1;
this.procTime += PENANCE_COOLDOWN - (event.timestamp - this.lastPenanceStartTimestamp);
}
this.canHaveProcced = false;
if (!this.lastPenanceStartTimestamp || (event.timestamp - this.lastPenanceStartTimestamp) > PENANCE_CHANNEL_TIME_BUFFER) {
this.lastPenanceStartTimestamp = event.timestamp;
}
} else if (spellId === SPELLS.SMITE.id) {
this.canHaveProcced = true;
}
}
item() {
const procTimeSaved = (this.procTime / 1000).toFixed(1) || 0;
const numProcs = this.procs || 0;
return {
item: ITEMS.CORD_OF_MAIEV_PRIESTESS_OF_THE_MOON,
result: (
<Wrapper>
{procTimeSaved} seconds off the cooldown, {numProcs} Penances cast earlier
</Wrapper>
),
};
}
}
export default CordOfMaiev;
|
front/app/index.js | nudoru/React-Starter-3 | import 'babel-polyfill';
import 'isomorphic-fetch';
import React from 'react';
import ReactDOM from 'react-dom';
import Bootstrap from './js/Bootstrap';
// Bootstrap 4 styles with some variables tweaked
require('./sass/index.sass');
// Additional global CSS styles
require('./js/theme/GlobalStyles');
// Application container optionally loads config.json and sets up routing
ReactDOM.render(<Bootstrap />, document.querySelector('#app')); |
client/component/table/row-action.js | johngodley/redirection | /**
* External dependencies
*/
import React from 'react';
import { has_capability } from 'lib/capabilities';
/**
* @param {object} props - Component props
* @param {RowAction[]} props.actions - Array of actions
* @param {boolean} props.disabled
*/
export function RowActions( props ) {
const { actions, disabled = false } = props;
return (
<div className="row-actions">
{ disabled ? (
<span> </span>
) : (
actions.length > 0 && actions.filter( ( item ) => item ).reduce( ( prev, curr ) => [ prev, ' | ', curr ] )
) }
</div>
);
}
/**
*
* @param {object} props - Component props
* @param {} [props.onClick]
* @param {} props.children
* @param {string} [props.href='']
* @param {string} [props.capability='']
*/
export function RowAction( props ) {
const { onClick, children, href = '', capability = '' } = props;
function click( ev ) {
if ( onClick ) {
ev.preventDefault();
onClick();
}
}
if ( capability && ! has_capability( capability ) ) {
return null;
}
return (
<a href={ href ? href : '#' } onClick={ click }>
{ children }
</a>
);
}
|
example/pages/toptips/index.js | woshisbb43/coinMessageWechat | import React from 'react';
import {Button, Toast, Toptips} from '../../../build/packages';
import Page from '../../component/page';
class ToptipsDemo extends React.Component {
state = {
showWarn: false,
showSuccess: false,
showInfo: false,
warnTimer: null,
successTimer: null,
infoTimer: null,
};
componentWillUnmount() {
this.state.warnTimer && clearTimeout(this.state.warnTimer);
this.state.successTimer && clearTimeout(this.state.successTimer);
this.state.infoTimer && clearTimeout(this.state.infoTimer);
}
render() {
return (
<Page className="toptips" title="Toptips" subTitle="弹出式提示" spacing>
<Button onClick={this.showWarn.bind(this)} type="default">Warn Toptip</Button>
<Button onClick={this.showSuccess.bind(this)} type="default">Primary Toptip</Button>
<Button onClick={this.showInfo.bind(this)} type="default">Info Toptip</Button>
<Toptips type="warn" show={this.state.showWarn}> Oops, something is wrong! </Toptips>
<Toptips type="primary" show={this.state.showSuccess}> Success submited! </Toptips>
<Toptips type="info" show={this.state.showInfo}> Thanks for coming! </Toptips>
</Page>
);
}
showWarn() {
this.setState({showWarn: true});
this.state.warnTimer = setTimeout(()=> {
this.setState({showWarn: false});
}, 2000);
}
showSuccess() {
this.setState({showSuccess: true});
this.state.successTimer = setTimeout(()=> {
this.setState({showSuccess: false});
}, 2000);
}
showInfo() {
this.setState({showInfo: true});
this.state.infoTimer = setTimeout(()=> {
this.setState({showInfo: false});
}, 2000);
}
};
export default ToptipsDemo |
app/containers/contact/AddBySuggest.js | karthik-ir/TotallyNotArbore | // @flow
import React from 'react'
import { connect } from 'react-redux'
import type { Store } from 'utils/types'
import AddBySuggest from 'components/contact/AddBySuggest'
import * as contactList from 'actions/contactList'
import Contact from 'models/Contact'
const mapStateToProps = (state: Store) => ({
suggestion: state.contactList.suggestForAdd(6)
})
const mapDispatchToProps = dispatch => ({
onSuggestAcceptGenerator: (contact: Contact) => () => {
dispatch(contactList.addContactInDirectory(contact.pubkey))
},
onSuggestRefuseGenerator: (contact: Contact) => () => {
dispatch(contactList.rejectSuggestion(contact))
},
})
export default connect(mapStateToProps, mapDispatchToProps)(AddBySuggest)
|
src/script/pages/Home.js | neikvon/fbi-template-react | 'use strict';
import React from 'react';
import Nav from '../components/Nav';
import '!style!css!sass!autoprefixer!../../style/style.scss';
let Home = React.createClass({
render: function() {
document.title = '首页';
return (
<div className="home">
<div className="logo"></div>
<Nav />
</div>
);
}
});
module.exports = Home;
|
chapter-06/hoc/src/inheritance/OnlyForLoggedinHOC.js | mocheng/react-and-redux | import React from 'react';
const onlyForLoggedinHOC = (WrappedComponent) => {
return class NewComponent extends WrappedComponent {
render() {
if (this.props.loggedIn) {
return super.render();
} else {
return null;
}
}
}
}
export default onlyForLoggedinHOC;
|
react/features/google-api/components/GoogleSignInButton.native.js | bgrozev/jitsi-meet | // @flow
import React from 'react';
import { Image, Text, TouchableOpacity } from 'react-native';
import { translate } from '../../base/i18n';
import AbstractGoogleSignInButton from './AbstractGoogleSignInButton';
import styles from './styles';
/**
* The Google Brand image for Sign In.
*
* NOTE: iOS doesn't handle the react-native-google-signin button component
* well due to our CocoaPods build process (the lib is not intended to be used
* this way), hence the custom button implementation.
*/
const GOOGLE_BRAND_IMAGE
= require('../../../../images/btn_google_signin_dark_normal.png');
/**
* A React Component showing a button to sign in with Google.
*
* @extends Component
*/
class GoogleSignInButton extends AbstractGoogleSignInButton {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const { onClick, signedIn, t } = this.props;
if (signedIn) {
return (
<TouchableOpacity
onPress = { onClick }
style = { styles.signOutButton } >
<Text style = { styles.signOutButtonText }>
{ t('liveStreaming.signOut') }
</Text>
</TouchableOpacity>
);
}
return (
<TouchableOpacity
onPress = { onClick }
style = { styles.signInButton } >
<Image
resizeMode = { 'contain' }
source = { GOOGLE_BRAND_IMAGE }
style = { styles.signInImage } />
</TouchableOpacity>
);
}
}
export default translate(GoogleSignInButton);
|
src/svg-icons/image/tag-faces.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageTagFaces = (props) => (
<SvgIcon {...props}>
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/>
</SvgIcon>
);
ImageTagFaces = pure(ImageTagFaces);
ImageTagFaces.displayName = 'ImageTagFaces';
ImageTagFaces.muiName = 'SvgIcon';
export default ImageTagFaces;
|
src/components/containers/author-user-list-container.js | HuangXingBin/goldenEast | import React from 'react';
import { Button, AutoComplete, DatePicker, message } from 'antd';
import './user-list-container.css';
import UserListTable from '../views/author-user-list-view.js';
import SearchUserInput from '../views/SearchUserInput.js';
import store from '../../store';
import { connect } from 'react-redux';
import { updateAuthorUserListDataSearch } from '../../actions/app-interaction-actions';
import { getAuthorUserListData, deleteSomeUserAuthor } from '../../api/app-interaction-api';
import { Link } from 'react-router';
const RangePicker = DatePicker.RangePicker;
var UserListContainer = React.createClass({
onChange(value){
store.dispatch(updateAuthorUserListDataSearch({
'search[find]' : value,
'page' : 1
}));
},
/* onDateChange(dates, dateStrings){
store.dispatch(updateAuthorUserListDataSearch({
'search[d_begin]' : dateStrings[0],
'search[d_end]' : dateStrings[1],
'page' : 1
}));
this.submitSearch();
},*/
submitSearch() {
getAuthorUserListData(this.props.searchState);
},
onPageChange(page){
store.dispatch(updateAuthorUserListDataSearch({
page:page
}));
this.submitSearch();
},
componentDidMount(){
getAuthorUserListData();
},
componentWillUnmount(){
//清理搜索条件
store.dispatch(updateAuthorUserListDataSearch({
'search[find]' : '',
'search[d_begin]' : '',
'search[d_end]' : '',
'page' : 1
}));
},
deleteUserAuthor(user_sn) {
return function () {
deleteSomeUserAuthor({ sn : user_sn }, function (info) {
message.info('删除成功');
}.bind(this), function (info) {
message.info('删除失败 ' + info.info);
}.bind(this))
}.bind(this);
},
render(){
const data = this.props.dataState.data;
return this.props.children || (
<div>
<div className="userListHeader">
<SearchUserInput placeholder="输入姓名或手机号" search={this.submitSearch} onChange={this.onChange}/>
</div>
{/* <div className="data-picker-bar">
<label>注册时间:</label>
<RangePicker style={{ width: 200 }} onChange={this.onDateChange} />
</div>*/}
<UserListTable deleteUserAuthor={this.deleteUserAuthor} data={data.list} total={data.total} currentPage={data.this_page} onPageChange={this.onPageChange}/>
<div>
{this.props.children}
</div>
</div>
)
}
});
const mapStateToProps = function (store) {
return {
dataState : store.authorUserListState.dataState,
searchState : store.authorUserListState.searchState
}
};
export default connect(mapStateToProps)(UserListContainer);
|
packages/bonde-admin-canary/src/components/PageLogged/Header/Tabs.js | ourcities/rebu-client | import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router-dom'
import { Tab as Tabs, TabItem } from 'bonde-styleguide'
export const Tab = ({ children, to }) => (
<Link to={to}>
<TabItem>
{children}
</TabItem>
</Link>
)
Tab.propTypes = {
to: PropTypes.string.isRequired
}
export default Tabs
|
src/components/Pagination/index.js | cantonjs/re-admin | import React, { Component } from 'react';
import { Pagination as AntdPagination } from 'antd';
import PropTypes from 'utils/PropTypes';
import CursorIndicator from './CursorIndicator';
export default class Pagination extends Component {
static propTypes = {
store: PropTypes.object.isRequired,
};
render() {
const { props: { store, ...other } } = this;
if (store.useCursor) {
return <CursorIndicator {...other} store={store} />;
}
return <AntdPagination {...other} />;
}
}
|
examples/chatbot/index.js | despairblue/microcosm | import Chat from './components/chat'
import Messages from './stores/messages'
import Microcosm from 'Microcosm'
import React from 'react'
import "./style"
let app = new Microcosm()
app.addStore('messages', Messages)
app.listen(function () {
React.render(<Chat app={ app } { ...app.state } />, document.getElementById('app'))
})
app.start()
|
src/shared/pages/Menu/index.js | AlekseyWW/shop-react-ssr | import React from 'react';
import style from './styles.styl';
const Menu = () => <div className={style.Menu}>Menu</div>;
export default Menu;
|
src/svg-icons/image/looks.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageLooks = (props) => (
<SvgIcon {...props}>
<path d="M12 10c-3.86 0-7 3.14-7 7h2c0-2.76 2.24-5 5-5s5 2.24 5 5h2c0-3.86-3.14-7-7-7zm0-4C5.93 6 1 10.93 1 17h2c0-4.96 4.04-9 9-9s9 4.04 9 9h2c0-6.07-4.93-11-11-11z"/>
</SvgIcon>
);
ImageLooks = pure(ImageLooks);
ImageLooks.displayName = 'ImageLooks';
export default ImageLooks;
|
packages/ui-toolkit/src/form/meta.js | yldio/joyent-portal | import { Subscriber } from 'joy-react-broadcast';
import is from 'styled-is';
import PropTypes from 'prop-types';
import React from 'react';
import remcalc from 'remcalc';
import styled from 'styled-components';
import Label from '../label';
const StyledLabel = styled(Label)`
${is('right')`
float: right;
`};
${is('error')`
color: ${props => props.theme.red};
-webkit-text-fill-color: currentcolor;
`};
${is('warning')`
color: ${props => props.theme.orange};
-webkit-text-fill-color: currentcolor;
`};
${is('success')`
color: ${props => props.theme.green};
-webkit-text-fill-color: currentcolor;
`};
font-size: ${remcalc(13)};
float: none;
width: ${remcalc(300)};
${is('small')`
width: ${remcalc(120)};
`};
${is('absolute')`
position: absolute;
`};
`;
const Meta = props => {
const render = (value = {}) => {
const { meta = {} } = value;
const msg =
props.children ||
props.error ||
props.warning ||
props.success ||
meta.error ||
meta.warning ||
meta.success ||
value.error ||
value.warning ||
value.success;
const hasError = Boolean(props.error || meta.error || value.error);
const hasWarning = Boolean(props.warning || meta.warning || value.warning);
const hasSuccess = Boolean(props.success || meta.success || value.success);
const isRight = !props.left;
return msg ? (
<StyledLabel
{...meta}
{...props}
error={hasError}
warning={hasWarning}
success={hasSuccess}
right={isRight}
>
{msg}
</StyledLabel>
) : null;
};
return <Subscriber channel="input-group">{render}</Subscriber>;
};
Meta.propTypes = {
children: PropTypes.node,
error: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
left: PropTypes.bool,
success: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
warning: PropTypes.oneOfType([PropTypes.string, PropTypes.bool])
};
export default Meta;
|
react-router-tutorial/modules/About.js | guilsa/javascript-stuff | import React from 'react'
export default React.createClass({
render() {
return <div>About</div>
}
})
|
src/components/markdown/htags.js | mnmtanish/react-storybook-story | import React from 'react';
export class H1 extends React.Component {
render() {
const styles = {
fontFamily: 'Arimo, Helvetica, sans-serif',
color: '#777',
borderBottom: '2px solid #fafafa',
marginBottom: '1.15rem',
paddingBottom: '.5rem',
margin: '1.414rem 0 .5rem',
fontWeight: 'inherit',
lineHeight: 1.42,
textAlign: 'center',
marginTop: 0,
fontSize: '3.998rem',
};
return <h1 id={this.props.id} style={styles}>{this.props.children}</h1>;
}
}
export class H2 extends React.Component {
render() {
const styles = {
fontFamily: 'Arimo, Helvetica, sans-serif',
borderBottom: '2px solid #fafafa',
marginBottom: '1.15rem',
paddingBottom: '.5rem',
margin: '1.414rem 0 .5rem',
fontWeight: 'inherit',
lineHeight: 1.42,
fontSize: '2.827rem',
};
return <h2 id={this.props.id} style={styles}>{this.props.children}</h2>;
}
}
export class H3 extends React.Component {
render() {
const styles = {
fontFamily: 'Arimo, Helvetica, sans-serif',
borderBottom: '2px solid #fafafa',
marginBottom: '1.15rem',
paddingBottom: '.5rem',
margin: '1.414rem 0 .5rem',
fontWeight: 'inherit',
lineHeight: 1.42,
fontSize: '1.999rem',
};
return <h3 id={this.props.id} style={styles}>{this.props.children}</h3>;
}
}
export class H4 extends React.Component {
render() {
const styles = {
fontFamily: 'Arimo, Helvetica, sans-serif',
color: '#444',
margin: '1.414rem 0 .5rem',
fontWeight: 'inherit',
lineHeight: 1.42,
fontSize: '1.414rem',
};
return <h4 id={this.props.id} style={styles}>{this.props.children}</h4>;
}
}
export class H5 extends React.Component {
render() {
const styles = {
fontFamily: 'Arimo, Helvetica, sans-serif',
fontSize: '1.121rem',
};
return <h5 id={this.props.id} style={styles}>{this.props.children}</h5>;
}
}
export class H6 extends React.Component {
render() {
const styles = {
fontFamily: 'Arimo, Helvetica, sans-serif',
fontSize: '.88rem',
};
return <h6 id={this.props.id} style={styles}>{this.props.children}</h6>;
}
}
|
test/client/app/components/pages/login/test-login.js | LINKIWI/apache-auth | /* global window */
import {browserHistory} from 'react-router';
import Fingerprint from 'fingerprintjs2';
import jsdom from 'jsdom';
import {mount} from 'enzyme';
import React from 'react';
import request from 'browser-request';
import sinon from 'sinon';
import test from 'tape';
import {Login} from '../../../../../../src/client/app/components/pages/login';
import browser from '../../../../../../src/client/app/util/browser';
const loading = (func) => func(() => {});
test('Login component rendering', (t) => {
const fingerprintStub = sinon.stub(Fingerprint.prototype, 'get', (cb) => cb('fingerprint'));
const browserStub = sinon.stub(browser, 'push');
const requestGetStub = sinon.stub(request, 'get', (opts, cb) => {
t.equal(opts.url, '/auth-check', 'Endpoint for initial auth check');
return cb(null, {statusCode: 200});
});
const requestPostStub = sinon.stub(request, 'post', (opts, cb) => {
t.equal(opts.url, '/api/login/is-fingerprint-valid', 'Endpoint for checking fingerprint');
t.deepEqual(opts.json, {fingerprint: 'fingerprint'}, 'Fingerprint is passed as a parameter');
return cb(null, {});
});
jsdom.changeURL(window, 'https://auth.kevinlin.info/login');
const login = mount(
<Login loading={loading} />
);
t.ok(fingerprintStub.called, 'Attempt to grab browser fingerprint on mount');
t.ok(requestGetStub.called, 'Auth check on initial component mount');
t.ok(requestPostStub.called, 'Fingerprint check on initial component mount');
t.ok(browserStub.called, 'Redirect to status on successful auth check');
t.ok(login.instance().usernameInput, 'Username text field input is present');
t.ok(login.instance().passwordInput, 'Password text field input is present');
t.deepEqual(login.state(), {loginStatus: {}}, 'Initial state is empty');
t.notOk(login.find('.login-success-alert').length, 'No success alert is initially shown');
t.notOk(login.find('.login-error-alert').length, 'No error alert is initially shown');
request.get.restore();
request.post.restore();
browser.push.restore();
Fingerprint.prototype.get.restore();
t.end();
});
test('Redirect to redirect URL on successful auth', (t) => {
const fingerprintStub = sinon.stub(Fingerprint.prototype, 'get', (cb) => cb('fingerprint'));
const browserStub = sinon.stub(browser, 'go');
const requestGetStub = sinon.stub(request, 'get', (opts, cb) => {
t.equal(opts.url, '/auth-check', 'Endpoint for initial auth check');
return cb(null, {statusCode: 200});
});
const requestPostStub = sinon.stub(request, 'post', (opts, cb) => {
t.equal(opts.url, '/api/login/is-fingerprint-valid', 'Endpoint for checking fingerprint');
t.deepEqual(opts.json, {fingerprint: 'fingerprint'}, 'Fingerprint is passed as a parameter');
return cb(null, {});
});
jsdom.changeURL(window, 'https://auth.kevinlin.info/login?redirect=https://google.com');
const login = mount(
<Login loading={loading} />
);
t.ok(fingerprintStub.called, 'Attempt to grab browser fingerprint on mount');
t.ok(requestGetStub.called, 'Auth check on initial component mount');
t.ok(requestPostStub.called, 'Fingerprint check on initial component mount');
t.ok(browserStub.calledWith('https://google.com'), 'Redirect to URL on successful auth check');
t.ok(login.instance().usernameInput, 'Username text field input is present');
t.ok(login.instance().passwordInput, 'Password text field input is present');
t.deepEqual(login.state(), {loginStatus: {}}, 'Initial state is empty');
t.notOk(login.find('.login-success-alert').length, 'No success alert is initially shown');
t.notOk(login.find('.login-error-alert').length, 'No error alert is initially shown');
request.get.restore();
request.post.restore();
browser.go.restore();
Fingerprint.prototype.get.restore();
t.end();
});
test('Redirect to OTP for authenticated browser', (t) => {
const fingerprintStub = sinon.stub(Fingerprint.prototype, 'get', (cb) => cb('fingerprint'));
const browserStub = sinon.stub(browserHistory, 'push');
const requestGetStub = sinon.stub(request, 'get', (opts, cb) => {
t.equal(opts.url, '/auth-check', 'Endpoint for initial auth check');
return cb(null, {statusCode: 200});
});
const requestPostStub = sinon.stub(request, 'post', (opts, cb) => {
t.equal(opts.url, '/api/login/is-fingerprint-valid', 'Endpoint for checking fingerprint');
t.deepEqual(opts.json, {fingerprint: 'fingerprint'}, 'Fingerprint is passed as a parameter');
return cb(null, {statusCode: 200});
});
jsdom.changeURL(window, 'https://auth.kevinlin.info/login?redirect=https://google.com');
const login = mount(
<Login loading={loading} />
);
t.ok(fingerprintStub.called, 'Attempt to grab browser fingerprint on mount');
t.ok(requestGetStub.called, 'Auth check on initial component mount');
t.ok(requestPostStub.called, 'Fingerprint check on initial component mount');
t.ok(browserStub.calledWith({
pathname: '/u2f',
query: {
redirect: 'https://google.com'
}
}), 'Redirect to status on successful auth check');
t.ok(login.instance().usernameInput, 'Username text field input is present');
t.ok(login.instance().passwordInput, 'Password text field input is present');
t.deepEqual(login.state(), {loginStatus: {}}, 'Initial state is empty');
t.notOk(login.find('.login-success-alert').length, 'No success alert is initially shown');
t.notOk(login.find('.login-error-alert').length, 'No error alert is initially shown');
request.get.restore();
request.post.restore();
browserHistory.push.restore();
Fingerprint.prototype.get.restore();
t.end();
});
test('Initialization of Duo 2FA', (t) => {
const fingerprintStub = sinon.stub(Fingerprint.prototype, 'get', (cb) => cb('fingerprint'));
sinon.stub(request, 'get');
const requestStub = sinon.stub(request, 'post', (opts, cb) => {
if (opts.url === '/api/login/duo') {
t.deepEqual(opts.json, {
username: 'username',
password: 'password'
}, 'Username and password are passed to Duo authentication');
return cb(null, null, {sigRequest: 'sig:request', duoHost: 'api.duosecurity.com'});
}
return null;
});
const login = mount(
<Login loading={loading} />
);
login.instance().usernameInput.setValue('username');
login.instance().passwordInput.setValue('password');
login.find('.login-submit-btn').simulate('click');
t.ok(requestStub.called, 'Request is made');
t.ok(fingerprintStub.called, 'Fingerprint is requested');
request.get.restore();
request.post.restore();
Fingerprint.prototype.get.restore();
t.end();
});
test('Duo 2FA successful response', (t) => {
const fingerprintStub = sinon.stub(Fingerprint.prototype, 'get', (cb) => cb('fingerprint'));
sinon.stub(request, 'get');
const browserStub = sinon.stub(browser, 'push');
const requestStub = sinon.stub(request, 'post', (opts, cb) => {
if (opts.url === '/api/login/duo') {
t.deepEqual(opts.json, {
username: 'username',
password: 'password'
}, 'Username and password are passed to Duo authentication');
return cb(null, null, {sigRequest: 'sig:request', duoHost: 'api.duosecurity.com'});
}
if (opts.url === '/api/login/apache') {
t.deepEqual(opts.json, {
username: 'username',
password: 'password',
sigResponse: 'sig response'
}, 'Credentials and sig response are passed to Apache');
return cb(null, {statusCode: 200}, {});
}
return null;
});
jsdom.changeURL(window, 'https://auth.kevinlin.info/login');
const login = mount(
<Login loading={loading} />
);
login.instance().usernameInput.setValue('username');
login.instance().passwordInput.setValue('password');
login.find('.login-submit-btn').simulate('click');
t.ok(requestStub.called, 'Request is made');
t.ok(fingerprintStub.called, 'Fingerprint is requested');
login.find('Duo').props().sigResponseCallback('sig response');
t.ok(browserStub.calledWith('/status'), 'Successful redirect to status');
request.get.restore();
request.post.restore();
Fingerprint.prototype.get.restore();
browser.push.restore();
t.end();
});
test('Duo 2FA successful response with redirect', (t) => {
const fingerprintStub = sinon.stub(Fingerprint.prototype, 'get', (cb) => cb('fingerprint'));
sinon.stub(request, 'get');
const browserStub = sinon.stub(browser, 'go');
const requestStub = sinon.stub(request, 'post', (opts, cb) => {
if (opts.url === '/api/login/duo') {
t.deepEqual(opts.json, {
username: 'username',
password: 'password'
}, 'Username and password are passed to Duo authentication');
return cb(null, null, {sigRequest: 'sig:request', duoHost: 'api.duosecurity.com'});
}
if (opts.url === '/api/login/apache') {
t.deepEqual(opts.json, {
username: 'username',
password: 'password',
sigResponse: 'sig response'
}, 'Credentials and sig response are passed to Apache');
return cb(null, {statusCode: 200}, {});
}
return null;
});
jsdom.changeURL(window, 'https://auth.kevinlin.info/login?redirect=https://google.com');
const login = mount(
<Login loading={loading} />
);
login.instance().usernameInput.setValue('username');
login.instance().passwordInput.setValue('password');
login.find('.login-submit-btn').simulate('click');
t.ok(requestStub.called, 'Request is made');
t.ok(fingerprintStub.called, 'Fingerprint is requested');
login.find('Duo').props().sigResponseCallback('sig response');
t.ok(browserStub.calledWith('https://google.com'), 'Successful redirect to status');
request.get.restore();
request.post.restore();
Fingerprint.prototype.get.restore();
browser.go.restore();
t.end();
});
test('Redirect to authorization request', (t) => {
sinon.stub(Fingerprint.prototype, 'get', (cb) => cb('fingerprint'));
sinon.stub(browser, 'push');
sinon.stub(request, 'get', (opts, cb) => {
t.equal(opts.url, '/auth-check', 'Endpoint for initial auth check');
return cb(null, {statusCode: 200});
});
sinon.stub(request, 'post', (opts, cb) => {
t.equal(opts.url, '/api/login/is-fingerprint-valid', 'Endpoint for checking fingerprint');
t.deepEqual(opts.json, {fingerprint: 'fingerprint'}, 'Fingerprint is passed as a parameter');
return cb(null, {});
});
const browserHistoryStub = sinon.stub(browserHistory, 'push');
jsdom.changeURL(window, 'https://auth.kevinlin.info/login?redirect=https://google.com');
const login = mount(
<Login loading={loading} />
);
login.find('.auth-request').simulate('click');
t.ok(browserHistoryStub.calledWith({
pathname: '/authorize',
query: {redirect: 'https://google.com'}
}), 'Redirect to authorization page with redirect URL');
request.get.restore();
request.post.restore();
browser.push.restore();
Fingerprint.prototype.get.restore();
browserHistory.push.restore();
t.end();
});
|
list/views/ListWrapperView.js | ExtPoint/yii2-frontend | import React from 'react';
import PropTypes from 'prop-types';
export default class ListWrapperView extends React.Component {
static propTypes = {
className: PropTypes.string,
itemsOrder: PropTypes.oneOf(['asc', 'desc']),
search: PropTypes.element,
items: PropTypes.array,
pagination: PropTypes.element,
paginationSize: PropTypes.element,
empty: PropTypes.element,
};
render() {
if (this.props.itemsOrder.toLowerCase() === 'desc') {
return (
<div className={this.props.className}>
{this.props.search}
{this.props.paginationSize}
{this.props.items}
{this.props.pagination}
{this.props.empty}
</div>
);
} else {
return (
<div className={this.props.className}>
{this.props.search}
{this.props.paginationSize}
{this.props.pagination}
{this.props.items}
{this.props.empty}
</div>
);
}
}
} |
src/svg-icons/communication/email.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationEmail = (props) => (
<SvgIcon {...props}>
<path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z"/>
</SvgIcon>
);
CommunicationEmail = pure(CommunicationEmail);
CommunicationEmail.displayName = 'CommunicationEmail';
CommunicationEmail.muiName = 'SvgIcon';
export default CommunicationEmail;
|
app/src/About/pages/AboutPage5.js | wekilledit/portfolio-frontend | import React from 'react';
const AboutPage5 = () => {
return (
<div className='subpage-about'>
<h3>hobbies</h3>
<div className='about-hobbies'>
<img className='img-skateboard' src={require('../images/k-grind-nollie-shuvit.jpg')} />
<ul>
<li>
Skateboarding
</li>
<li>Live music</li>
<li>Coding</li>
<li>Futsal</li>
<li>Nature walks</li>
<li>Keyboard shortcuts</li>
</ul>
</div>
</div>
);
}
export default AboutPage5;
|
src/app/components/ribbon/SmallBreadcrumbs.js | backpackcoder/world-in-flames | import React from 'react'
import {connect} from 'react-redux'
class SmallBreadcrumbs extends React.Component {
render() {
return (
<ol className="breadcrumb">
{
this.props.items.map((it, idx)=> (
<li key={it + idx}>{it}</li>
))
}
</ol>
)
}
}
const mapStateToProps = (state, ownProps) => {
const {navigation, routing}= state;
const route = routing.locationBeforeTransitions.pathname;
const titleReducer = (chain, it)=> {
if (it.route == route) {
chain.push(it.title)
} else if (it.items) {
it.items.reduce(titleReducer, chain);
}
return chain
};
const items = navigation.items.reduce(titleReducer, ['Home']);
return {items}
};
export default connect(mapStateToProps)(SmallBreadcrumbs) |
packages/react/components/nav-title-large.js | iamxiaoma/Framework7 | import React from 'react';
import Utils from '../utils/utils';
import Mixins from '../utils/mixins';
import __reactComponentSlots from '../runtime-helpers/react-component-slots.js';
import __reactComponentSetProps from '../runtime-helpers/react-component-set-props.js';
class F7NavTitle extends React.Component {
constructor(props, context) {
super(props, context);
}
render() {
const self = this;
const props = self.props;
const {
id,
style,
className
} = props;
const classes = Utils.classNames(className, 'title-large', Mixins.colorClasses(props));
const children = [];
const slots = self.slots;
if (slots && Object.keys(slots).length) {
Object.keys(slots).forEach(key => {
children.push(...slots[key]);
});
}
return React.createElement('div', {
id: id,
style: style,
className: classes
}, React.createElement('div', {
className: 'title-large-text'
}, children));
}
get slots() {
return __reactComponentSlots(this.props);
}
}
__reactComponentSetProps(F7NavTitle, Object.assign({
id: [String, Number],
className: String,
style: Object
}, Mixins.colorProps));
F7NavTitle.displayName = 'f7-nav-title';
export default F7NavTitle; |
src/containers/recipes/Listing/ListingView.js | BrownEPTech/brown-ep-startup-ideas-app | /**
* Recipe Listing Screen
* - Shows a list of receipes
*
* React Native Starter App
* https://github.com/mcnamee/react-native-starter-app
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
View,
ListView,
RefreshControl,
} from 'react-native';
// Consts and Libs
import { AppColors, AppStyles } from '@theme/';
import { ErrorMessages } from '@constants/';
// Containers
import RecipeCard from '@containers/recipes/Card/CardContainer';
// Components
import Error from '@components/general/Error';
/* Component ==================================================================== */
class RecipeListing extends Component {
static componentName = 'RecipeListing';
static propTypes = {
recipes: PropTypes.arrayOf(PropTypes.object).isRequired,
reFetch: PropTypes.func,
}
static defaultProps = {
reFetch: null,
}
constructor() {
super();
this.state = {
isRefreshing: true,
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
};
}
componentWillReceiveProps(props) {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(props.recipes),
isRefreshing: false,
});
}
/**
* Refetch Data (Pull to Refresh)
*/
reFetch = () => {
if (this.props.reFetch) {
this.setState({ isRefreshing: true });
this.props.reFetch()
.then(() => {
this.setState({ isRefreshing: false });
});
}
}
render = () => {
const { recipes } = this.props;
const { isRefreshing, dataSource } = this.state;
if (!isRefreshing && (!recipes || recipes.length < 1)) {
return <Error text={ErrorMessages.recipe404} />;
}
return (
<View style={[AppStyles.container]}>
<ListView
initialListSize={5}
renderRow={recipe => <RecipeCard recipe={recipe} />}
dataSource={dataSource}
automaticallyAdjustContentInsets={false}
refreshControl={
this.props.reFetch ?
<RefreshControl
refreshing={isRefreshing}
onRefresh={this.reFetch}
tintColor={AppColors.brand.primary}
/>
: null
}
/>
</View>
);
}
}
/* Export Component ==================================================================== */
export default RecipeListing;
|
app/javascript/mastodon/features/list_editor/index.js | unarist/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { connect } from 'react-redux';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { injectIntl } from 'react-intl';
import { setupListEditor, clearListSuggestions, resetListEditor } from '../../actions/lists';
import Account from './components/account';
import Search from './components/search';
import Motion from '../ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
const mapStateToProps = state => ({
title: state.getIn(['listEditor', 'title']),
accountIds: state.getIn(['listEditor', 'accounts', 'items']),
searchAccountIds: state.getIn(['listEditor', 'suggestions', 'items']),
});
const mapDispatchToProps = dispatch => ({
onInitialize: listId => dispatch(setupListEditor(listId)),
onClear: () => dispatch(clearListSuggestions()),
onReset: () => dispatch(resetListEditor()),
});
@connect(mapStateToProps, mapDispatchToProps)
@injectIntl
export default class ListEditor extends ImmutablePureComponent {
static propTypes = {
listId: PropTypes.string.isRequired,
onClose: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
onInitialize: PropTypes.func.isRequired,
onClear: PropTypes.func.isRequired,
onReset: PropTypes.func.isRequired,
title: PropTypes.string.isRequired,
accountIds: ImmutablePropTypes.list.isRequired,
searchAccountIds: ImmutablePropTypes.list.isRequired,
};
componentDidMount () {
const { onInitialize, listId } = this.props;
onInitialize(listId);
}
componentWillUnmount () {
const { onReset } = this.props;
onReset();
}
render () {
const { title, accountIds, searchAccountIds, onClear } = this.props;
const showSearch = searchAccountIds.size > 0;
return (
<div className='modal-root__modal list-editor'>
<h4>{title}</h4>
<Search />
<div className='drawer__pager'>
<div className='drawer__inner list-editor__accounts'>
{accountIds.map(accountId => <Account key={accountId} accountId={accountId} added />)}
</div>
{showSearch && <div role='button' tabIndex='-1' className='drawer__backdrop' onClick={onClear} />}
<Motion defaultStyle={{ x: -100 }} style={{ x: spring(showSearch ? 0 : -100, { stiffness: 210, damping: 20 }) }}>
{({ x }) => (
<div className='drawer__inner backdrop' style={{ transform: x === 0 ? null : `translateX(${x}%)`, visibility: x === -100 ? 'hidden' : 'visible' }}>
{searchAccountIds.map(accountId => <Account key={accountId} accountId={accountId} />)}
</div>
)}
</Motion>
</div>
</div>
);
}
}
|
app/scenes/About.js | alexindigo/ndash | import React, { Component } from 'react';
import { Alert, ScrollView, Text, TouchableOpacity, View } from 'react-native';
import LinkText from '../components/LinkText';
import styles from '../styles';
export default class AboutScene extends Component {
resetApp() {
Alert.alert(
'reset',
'press [ok] to reset all the data',
[
{text: 'cancel'},
{
text: 'ok',
onPress: this.props.onResetApp
},
]
);
}
render() {
const profiles = Object.keys(this.props.profiles || {}).filter((id) => id !== '$');
const packages = Object.keys(this.props.packages || {}).filter((id) => id !== '$');
return (
<ScrollView
style={styles.about}
contentContainerStyle={styles.aboutContainer}
>
<Text style={styles.aboutHeader}>
about
</Text>
<Text style={styles.aboutParagraph}>
This application allows you to see what your public node modules are up to,
and take a peek at other developers, you collaborate with.
</Text>
<Text style={styles.aboutHeader}>
thanks
</Text>
<Text style={styles.aboutParagraph}>
Awesome APIs are provided by <LinkText
style={styles.aboutParagraphLink}
url="https://www.npmjs.com/"
>npmjs.com</LinkText> and <LinkText
style={styles.aboutParagraphLink}
url="https://www.npms.io/"
>npms.io</LinkText>,
without them this project wouldn't exist. Thanks a lot folks.
</Text>
<Text style={styles.aboutHeader}>
disclaimer
</Text>
<Text style={styles.aboutParagraph}>
This is not an official <LinkText
style={styles.aboutParagraphLink}
url="https://www.npmjs.com/"
>npmjs.com</LinkText> or <LinkText
style={styles.aboutParagraphLink}
url="https://www.npms.io/"
>npms.io</LinkText> app,
it just utilizes their publicly accessible APIs
for the benefit of the <LinkText
style={styles.aboutParagraphLink}
url="https://nodejs.org/"
>nodejs</LinkText> community.
</Text>
<Text style={styles.aboutHeader}>
nuts & bolts
</Text>
<Text style={styles.aboutParagraph}>
This application is released under the <LinkText
style={styles.aboutParagraphLink}
url="https://github.com/alexindigo/ndash/blob/master/LICENSE"
>MIT</LinkText> license.
Source code available at <LinkText
style={styles.aboutParagraphLink}
url="https://github.com/alexindigo/ndash"
>github.com/alexindigo/ndash</LinkText>.
</Text>
<Text style={styles.aboutHeader}>
stats
</Text>
<Text style={styles.aboutParagraph}>
You have collected {packages.length} packages from {profiles.length} author{profiles.length === 1 ? '' : 's'}.
</Text>
<TouchableOpacity
style={styles.aboutButton}
onPress={this.resetApp.bind(this)}
>
<Text
style={styles.aboutButtonText}
>
reset all data
</Text>
</TouchableOpacity>
</ScrollView>
);
}
}
|
pages/api/circular-progress.js | AndriusBil/material-ui | // @flow
import React from 'react';
import withRoot from 'docs/src/modules/components/withRoot';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import markdown from './circular-progress.md';
function Page() {
return <MarkdownDocs markdown={markdown} />;
}
export default withRoot(Page);
|
src/components/protected/ProtectedPage.js | RanjithNair/FeatureTracker | import React from 'react';
import {Link} from 'react-router';
import checkAuth from '../requireAuth';
const ProtectedPage = () => {
return (
<div>
<h1>You will only see this page if you are logged in</h1>
<Link to="/" activeClassName="active">Home</Link>
</div>
);
};
export default checkAuth(ProtectedPage);
|
src/containers/App.js | danbovey/Dekt | import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import classNames from 'classnames';
import * as configActions from 'actions/config';
import * as lightActions from 'actions/lights';
import Navbar from 'components/Navbar';
import Spinner from 'components/Spinner';
import 'app.scss';
@connect(
state => ({
config: state.config,
lights: state.lights.on
}),
dispatch => ({
configActions: bindActionCreators(configActions, dispatch),
lightActions: bindActionCreators(lightActions, dispatch)
})
)
export default class App extends Component {
componentWillMount() {
const config = this.props.config;
if(!config.loaded || config.failed) {
this.props.configActions.load();
}
}
lightsOff() {
this.props.lightActions.off();
}
render() {
const {
children,
config,
lights
} = this.props;
if(!config.loaded) {
return (
<div className="container container--app-load">
<Spinner size="large" />
</div>
);
}
if(config.failed) {
return (
<div className="container container--app-load">
<p className="error">Failed to load <code>config.json</code></p>
</div>
);
}
return (
<div
className={classNames({
'cinematic-lighting': lights
})}
>
<Navbar />
<div
className="cinematic-lighting-bg"
onClick={this.lightsOff.bind(this)}
/>
{children}
</div>
);
}
}
|
client/src/views/HomePage/index.js | dmitrij-borchuk/lms | /*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*
* 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 { FormattedMessage } from 'react-intl';
import messages from './messages';
import AppHeader from '../../components/AppHeader'
export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<div>
<AppHeader />
<h1>
<FormattedMessage {...messages.header} />
</h1>
</div>
);
}
}
|
src/svg-icons/hardware/desktop-mac.js | skarnecki/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';
export default HardwareDesktopMac;
|
tests/fixtures/apps/fluxible-router/components/Page.js | mridgway/react-server | /**
* Copyright 2014, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
import React from 'react';
import PageStore from '../stores/PageStore';
class Page extends React.Component {
constructor(props, context) {
super(props, context);
this.state = context.getStore(PageStore).getState();
this._changeListener = this._onStoreChange.bind(this);
}
componentDidMount() {
this.context.getStore(PageStore).addChangeListener(this._changeListener);
}
componentWillUnmount() {
this.context.getStore(PageStore).removeChangeListener(this._changeListener);
}
_onStoreChange() {
this.setState(this.context.getStore(PageStore).getState());
}
render() {
return (
<p>{this.state.content}</p>
);
}
}
Page.contextTypes = {
getStore: React.PropTypes.func,
executeAction: React.PropTypes.func
};
export default Page; |
src/svg-icons/communication/email.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationEmail = (props) => (
<SvgIcon {...props}>
<path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z"/>
</SvgIcon>
);
CommunicationEmail = pure(CommunicationEmail);
CommunicationEmail.displayName = 'CommunicationEmail';
CommunicationEmail.muiName = 'SvgIcon';
export default CommunicationEmail;
|
frontend/app/components/Form/Common/Text.js | First-Peoples-Cultural-Council/fv-web-ui | import React from 'react'
import PropTypes from 'prop-types'
import './Text.css'
const { bool, string, func, object } = PropTypes
export default class Text extends React.Component {
static propTypes = {
ariaDescribedby: string,
className: string,
disabled: bool,
error: object,
handleChange: func,
id: string.isRequired,
isRequired: bool,
labelText: string.isRequired,
name: string.isRequired,
setRef: func,
value: string,
wysiwyg: bool,
}
static defaultProps = {
className: 'Text',
disabled: false,
error: {},
handleChange: () => {},
isRequired: false,
setRef: () => {},
value: '',
wysiwyg: false,
}
state = {
value: this.props.value,
TextElement: null,
}
async componentDidMount() {
const { ariaDescribedby, disabled, id, name, setRef } = this.props
const textComponent = this.props.wysiwyg ? (
await import(/* webpackChunkName: "Editor" */ 'components/Editor').then((_module) => {
const Editor = _module.default
return (
<Editor
aria-describedby={ariaDescribedby}
className="Text__text"
disabled={disabled}
id={id}
initialValue={this.state.value}
name={name}
onChange={(content /*, delta, source, editor*/) => {
this._handleChange(content /*, delta, source, editor*/)
}}
setRef={setRef}
/>
)
})
) : (
<input
aria-describedby={ariaDescribedby}
className="Text__text"
disabled={disabled}
id={id}
name={name}
defaultValue={this.state.value}
onChange={(event) => {
this._handleChange(event.target.value)
}}
type="text"
ref={setRef}
/>
)
this.setState({
TextElement: textComponent,
})
}
render() {
const { message } = this.props.error
const { className, id, labelText, wysiwyg } = this.props
const { TextElement } = this.state
const labelClickHandler = wysiwyg
? () => {
if (this.state.wysiwygRef) {
this.state.wysiwygRef.focus()
}
}
: () => {}
return (
<div className={`${className} Text ${message ? 'Form__error Text--error' : ''}`}>
<label onClick={labelClickHandler} className="Text__label" htmlFor={id}>
{labelText} {this.props.isRequired ? '*' : ''}
</label>
{TextElement}
{message && (
<label onClick={labelClickHandler} className="Form__errorMessage" htmlFor={id}>
{message}
</label>
)}
</div>
)
}
_handleChange = (value) => {
this.setState({ value })
this.props.handleChange(value)
}
}
|
react-flux-mui/js/material-ui/src/svg-icons/action/line-style.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionLineStyle = (props) => (
<SvgIcon {...props}>
<path d="M3 16h5v-2H3v2zm6.5 0h5v-2h-5v2zm6.5 0h5v-2h-5v2zM3 20h2v-2H3v2zm4 0h2v-2H7v2zm4 0h2v-2h-2v2zm4 0h2v-2h-2v2zm4 0h2v-2h-2v2zM3 12h8v-2H3v2zm10 0h8v-2h-8v2zM3 4v4h18V4H3z"/>
</SvgIcon>
);
ActionLineStyle = pure(ActionLineStyle);
ActionLineStyle.displayName = 'ActionLineStyle';
ActionLineStyle.muiName = 'SvgIcon';
export default ActionLineStyle;
|
components/mailSharing.js | Yutenko/stories360 | import React from 'react'
import {Container,Row,Col} from 'react-grid-system'
import {deepPurple500,orange500} from 'material-ui/styles/colors'
import {translate} from '../client/lang/translation'
import Paper from 'material-ui/Paper'
import TextField from 'material-ui/TextField'
import RaisedButton from 'material-ui/RaisedButton'
import FontIcon from 'material-ui/FontIcon'
import mailsharingstore from '../stores/mailsharingstore'
import messenger from '../stores/messenger.js'
@observer
class ShareMail extends React.Component {
render () {
const store = mailsharingstore
return (
<Dialog
title={translate("socialShare").title}
modal={false}
open={store.open}
onRequestClose={store.handleClose}
autoScrollBodyContent={true}
>
<DialogContent store={store} />
</Dialog>
)
}
}
@observer
class DialogContent extends React.Component {
render () {
const store = this.props.store
return (
<div>
<TextField
floatingLabelText={translate("socialShare").toWhom}
fullWidth={true}
value={store.toWhom}
onChange={this.onToWhomChange}
/>
<TextField
floatingLabelText={translate("socialShare").fromWho}
fullWidth={true}
value={store.fromWho}
onChange={this.onFromWhoChange}
/>
<RaisedButton
label={translate("mail").send}
primary={true}
icon={<FontIcon className="material-icons">send</FontIcon>}
fullWidth={true}
onTouchTap={this.sendMail}
/>
</dv>
)
}
sendMail () {
mailsharingstore.sendMail( () => {
messenger.mailSent(messenger.MESSAGES.mailSent)
})
}
onToWhomChange (e,value) {
mailsharingstore.setToWhom(value)
}
onFromWhoChange (e,value) {
mailsharingstore.setFromWho(value)
}
}
export default
|
packages/icon-builder/tpl/SvgIcon.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '{{{ muiRequireStmt }}}';
let {{className}} = (props) => (
<SvgIcon {...props}>
{{{paths}}}
</SvgIcon>
);
{{className}} = pure({{className}});
{{className}}.displayName = '{{className}}';
{{className}}.muiName = 'SvgIcon';
export default {{className}};
|
packages/slate-react/src/components/leaf.js | 6174/slate |
import Debug from 'debug'
import React from 'react'
import Types from 'prop-types'
import SlateTypes from 'slate-prop-types'
import OffsetKey from '../utils/offset-key'
import { IS_FIREFOX } from '../constants/environment'
/**
* Debugger.
*
* @type {Function}
*/
const debug = Debug('slate:leaves')
/**
* Leaf.
*
* @type {Component}
*/
class Leaf extends React.Component {
/**
* Property types.
*
* @type {Object}
*/
static propTypes = {
block: SlateTypes.block.isRequired,
editor: Types.object.isRequired,
index: Types.number.isRequired,
leaves: SlateTypes.leaves.isRequired,
marks: SlateTypes.marks.isRequired,
node: SlateTypes.node.isRequired,
offset: Types.number.isRequired,
parent: SlateTypes.node.isRequired,
schema: SlateTypes.schema.isRequired,
state: SlateTypes.state.isRequired,
text: Types.string.isRequired,
}
/**
* Debug.
*
* @param {String} message
* @param {Mixed} ...args
*/
debug = (message, ...args) => {
debug(message, `${this.props.node.key}-${this.props.index}`, ...args)
}
/**
* Should component update?
*
* @param {Object} props
* @return {Boolean}
*/
shouldComponentUpdate(props) {
// If any of the regular properties have changed, re-render.
if (
props.index != this.props.index ||
props.marks != this.props.marks ||
props.schema != this.props.schema ||
props.text != this.props.text ||
props.parent != this.props.parent
) {
return true
}
// Otherwise, don't update.
return false
}
/**
* Render the leaf.
*
* @return {Element}
*/
render() {
const { props } = this
const { node, index } = props
const offsetKey = OffsetKey.stringify({
key: node.key,
index
})
this.debug('render', { props })
return (
<span data-offset-key={offsetKey}>
{this.renderMarks(props)}
</span>
)
}
/**
* Render all of the leaf's mark components.
*
* @param {Object} props
* @return {Element}
*/
renderMarks(props) {
const { marks, schema, node, offset, text, state, editor } = props
const children = this.renderText(props)
return marks.reduce((memo, mark) => {
const Component = mark.getComponent(schema)
if (!Component) return memo
return (
<Component
editor={editor}
mark={mark}
marks={marks}
node={node}
offset={offset}
schema={schema}
state={state}
text={text}
>
{memo}
</Component>
)
}, children)
}
/**
* Render the text content of the leaf, accounting for browsers.
*
* @param {Object} props
* @return {Element}
*/
renderText(props) {
const { block, node, parent, text, index, leaves } = props
// COMPAT: If the text is empty and it's the only child, we need to render a
// <br/> to get the block to have the proper height.
if (text == '' && parent.kind == 'block' && parent.text == '') return <br />
// COMPAT: If the text is empty otherwise, it's because it's on the edge of
// an inline void node, so we render a zero-width space so that the
// selection can be inserted next to it still.
if (text == '') {
// COMPAT: In Chrome, zero-width space produces graphics glitches, so use
// hair space in place of it. (2017/02/12)
const space = IS_FIREFOX ? '\u200B' : '\u200A'
return <span data-slate-zero-width>{space}</span>
}
// COMPAT: Browsers will collapse trailing new lines at the end of blocks,
// so we need to add an extra trailing new lines to prevent that.
const lastText = block.getLastText()
const lastChar = text.charAt(text.length - 1)
const isLastText = node == lastText
const isLastLeaf = index == leaves.size - 1
if (isLastText && isLastLeaf && lastChar == '\n') return `${text}\n`
// Otherwise, just return the text.
return text
}
}
/**
* Export.
*
* @type {Component}
*/
export default Leaf
|
src/components/footer/footer-heading.js | adrienlozano/stephaniewebsite | import React from 'react';
import { defaultProps, compose, setDisplayName } from 'recompose';
import Typography from '~/components/typography';
const enhance = compose(
setDisplayName("FooterHeading"),
defaultProps({ size: 0.3, component:"h2", color:"#FFF"})
);
export default enhance(Typography); |
src/ButtonInput.js | RichardLitt/react-bootstrap | import React from 'react';
import Button from './Button';
import FormGroup from './FormGroup';
import InputBase from './InputBase';
import childrenValueValidation from './utils/childrenValueInputValidation';
class ButtonInput extends InputBase {
renderFormGroup(children) {
let {bsStyle, value, ...other} = this.props; // eslint-disable-line object-shorthand, no-unused-vars
return <FormGroup {...other}>{children}</FormGroup>;
}
renderInput() {
let {children, value, ...other} = this.props; // eslint-disable-line object-shorthand
let val = children ? children : value;
return <Button {...other} componentClass="input" ref="input" key="input" value={val} />;
}
}
ButtonInput.types = ['button', 'reset', 'submit'];
ButtonInput.defaultProps = {
type: 'button'
};
ButtonInput.propTypes = {
type: React.PropTypes.oneOf(ButtonInput.types),
bsStyle(props) {
//defer to Button propTypes of bsStyle
return null;
},
children: childrenValueValidation,
value: childrenValueValidation
};
export default ButtonInput;
|
examples/star-wars/js/components/StarWarsRegion.js | SBUtltmedia/relay | /**
* This file provided by Facebook is for non-commercial testing and evaluation
* purposes only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import React from 'react';
import Relay from 'react-relay';
class StarWarsRegion extends React.Component {
render() {
var {region} = this.props;
return <div>{region.points}</div>;
}
}
export default Relay.createContainer(StarWarsRegion, {
fragments: {
region: () => Relay.QL`
fragment on Region {
id
points
}
`,
},
});
|
docs/app/Examples/elements/Button/Variations/ButtonExampleCircularSocial.js | koenvg/Semantic-UI-React | import React from 'react'
import { Button } from 'semantic-ui-react'
const ButtonExampleCircularSocial = () => (
<div>
<Button circular color='facebook' icon='facebook' />
<Button circular color='twitter' icon='twitter' />
<Button circular color='linkedin' icon='linkedin' />
<Button circular color='google plus' icon='google plus' />
</div>
)
export default ButtonExampleCircularSocial
|
common/components/ide/panels/OptionsPanel.js | ebertmi/webbox | import React from 'react';
import set from 'lodash/set';
import {Button, Input} from '../../bootstrap';
import optionManager from '../../../models/options';
const themeList = {themes: ['vs', 'vs-dark', 'hc-black']};
export default class OptionsPanel extends React.Component {
constructor(props) {
super(props);
this.onChangeOption = this.onChangeOption.bind(this);
this.onReset = this.onReset.bind(this);
this.onChange = this.onChange.bind(this);
this.state = {
options: optionManager.getOptions()
};
}
componentDidMount() {
optionManager.on('change', this.onChangeOption);
this.onChangeOption();
}
componentWillUnmount() {
optionManager.removeListener('change', this.onChangeOption);
}
onChangeOption() {
this.setState({
options: optionManager.getOptions()
});
}
onChange(e) {
e.stopPropagation();
const target = e.target;
let value;
switch (target.type) {
case 'checkbox':
value = target.checked;
break;
case 'number':
value = +target.value;
break;
default:
value = target.value;
}
const path = target.name.split('.');
const options = set({}, path, value);
optionManager.setOptions(options);
}
onReset(e) {
e.preventDefault();
e.stopPropagation();
// ToDo: maybe ask for confirmation
optionManager.reset();
}
renderEditorOptions() {
const options = this.state.options.editor;
const themes = themeList.themes.map((theme) => {
return <option key={theme} value={theme}>{theme}</option>;
});
const wrapOptions = [
<option key="wordWrap-on" value="on">An</option>,
<option key="wordWrap-off" value="off">Aus</option>
];
const whitespaceOptions = [
<option key="wordWrap-none" value="none">Keine</option>,
<option key="wordWrap-boundary" value="boundary">Zeilenanfang und -ende</option>,
<option key="wordWrap-all" value="all">Alle</option>
];
const lineHighlightOptions = [
<option key="wordWrap-none" value="none">Keine</option>,
<option key="wordWrap-gutter" value="gutter">In der linken Leiste (Gutter)</option>,
<option key="wordWrap-line" value="line">Zeile</option>,
<option key="wordWrap-all" value="all">Leiste + Zeile</option>
];
return (
<div onChange={this.onChange}>
<legend>Editor</legend>
<Input type="select" label="Farbschema" name="editor.theme" defaultValue={options.theme}>
{themes}
</Input>
<Input type="select" label="Aktive Zeile hervorheben" name="editor.renderLineHighlight" defaultValue={options.renderLineHighlight}>
{lineHighlightOptions}
</Input>
<Input label="Ausgewähltes Wort hervorheben" type="checkbox" name="editor.selectionHighlight" defaultChecked={options.selectionHighlight}/>
<Input type="select" label="Unsichtbare Zeichen anzeigen" name="editor.renderWhitespace" defaultValue={options.renderWhitespace}>
{whitespaceOptions}
</Input>
<Input label="Einrückung anzeigen" type="checkbox" name="editor.renderIndentGuides" defaultChecked={options.renderIndentGuides}/>
<Input type="select" label="Zeilen umbrechen" name="editor.wordWrap" defaultValue={options.wordWrap}>
{wrapOptions}
</Input>
<Input label="Autovervollständigung bei Klammern" type="checkbox" name="editor.autoClosingBrackets" defaultChecked={options.autoClosingBrackets}/>
<Input label="Minimap anzeigen" type="checkbox" name="editor.minimap.enabled" defaultChecked={options.minimap.enabled}/>
</div>
);
}
renderTerminalOptions() {
const options = this.state.options.terminal;
return (
<div onChange={this.onChange}>
<legend>Terminal</legend>
<Input label="Akustisches Signal" type="checkbox" name="terminal.audibleBell" defaultChecked={options.audibleBell}/>
</div>
);
}
render() {
const options = this.state.options;
return (
<form className="options-panel" onChange={this.onChange} onSubmit={e => e.preventDefault()}>
<legend>Allgemeine Einstellungen</legend>
<Input label="Schriftart" type="text" name="font" defaultValue={options.font}/>
<Input label="Schriftgröße" type="number" min="1" max="50" step="1" name="fontSize" defaultValue={options.fontSize}/>
{this.renderEditorOptions()}
{this.renderTerminalOptions()}
<hr/>
<Button bsStyle="danger" className="form-group" onClick={this.onReset}>Alle Einstellungen zurücksetzen</Button>
</form>
);
}
}
|
docs/app/Examples/elements/Label/Types/LabelExamplePointing.js | koenvg/Semantic-UI-React | import React from 'react'
import { Divider, Form, Label } from 'semantic-ui-react'
const LabelExamplePointing = () => (
<Form>
<Form.Field>
<input type='text' placeholder='First name' />
<Label pointing>Please enter a value</Label>
</Form.Field>
<Divider />
<Form.Field>
<Label pointing='below'>Please enter a value</Label>
<input type='text' placeholder='Last Name' />
</Form.Field>
<Divider />
<Form.Field inline>
<input type='text' placeholder='Username' />
<Label pointing='left'>That name is taken!</Label>
</Form.Field>
<Divider />
<Form.Field inline>
<Label pointing='right'>Your password must be 6 characters or more</Label>
<input type='password' placeholder='Password' />
</Form.Field>
</Form>
)
export default LabelExamplePointing
|
client/components/MakeRequest.js | lendr2/lendr2 | import React, { Component } from 'react';
import { Router, Route, Link, browserHistory } from 'react-router';
const cookieParser = require('cookie-parser');
class MakeRequest extends Component {
constructor(props) {
super(props)
this.makeRequest = this.makeRequest.bind(this);
}
makeRequest(event) {
event.preventDefault();
console.log('this runs');
const title = event.target.elements[0].value;
const note = event.target.elements[1].value;
const lendeename = document.cookie.split('=').pop();
// Post request to be saved to the database
$.post('/makeRequest', { lendeename: lendeename, itemname: title, note: note })
.done(data => {
console.log(data);
browserHistory.push('/userInfo')
})
.fail(() => console.error('error with makeRequest'));
}
render() {
return (
<div className="makeRequest-form">
<form onSubmit={this.makeRequest}>
<div className="form-group">
<label for="title">Title:</label>
<input type="text" className="form-control" name="title" placeholder="title" />
</div>
<div className="form-group">
<label for="description">Description:</label>
<textarea className="form-control" name="description" placeholder="place a note here..." />
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
);
}
}
export default MakeRequest;
|
packages/material-ui-icons/src/ModeComment.js | AndriusBil/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let ModeComment = props =>
<SvgIcon {...props}>
<path d="M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18z" />
</SvgIcon>;
ModeComment = pure(ModeComment);
ModeComment.muiName = 'SvgIcon';
export default ModeComment;
|
docs/app/Examples/elements/Icon/Variations/IconExampleInvertedColored.js | vageeshb/Semantic-UI-React | import React from 'react'
import { Segment, Icon } from 'semantic-ui-react'
const IconExampleInvertedColored = () => (
<Segment inverted>
<Icon inverted color='red' name='users' />
<Icon inverted color='orange' name='users' />
<Icon inverted color='yellow' name='users' />
<Icon inverted color='olive' name='users' />
<Icon inverted color='green' name='users' />
<Icon inverted color='teal' name='users' />
<Icon inverted color='blue' name='users' />
<Icon inverted color='violet' name='users' />
<Icon inverted color='purple' name='users' />
<Icon inverted color='pink' name='users' />
<Icon inverted color='brown' name='users' />
<Icon inverted color='grey' name='users' />
<Icon inverted color='black' name='users' />
</Segment>
)
export default IconExampleInvertedColored
|
actor-apps/app-web/src/app/components/modals/create-group/Form.react.js | voidException/actor-platform | import _ from 'lodash';
import Immutable from 'immutable';
import keymirror from 'keymirror';
import React from 'react';
import { Styles, TextField, FlatButton } from 'material-ui';
import CreateGroupActionCreators from 'actions/CreateGroupActionCreators';
import ContactStore from 'stores/ContactStore';
import ContactItem from './ContactItem.react';
import ActorTheme from 'constants/ActorTheme';
const ThemeManager = new Styles.ThemeManager();
const STEPS = keymirror({
NAME_INPUT: null,
CONTACTS_SELECTION: null
});
class CreateGroupForm extends React.Component {
static displayName = 'CreateGroupForm'
static childContextTypes = {
muiTheme: React.PropTypes.object
};
state = {
step: STEPS.NAME_INPUT,
selectedUserIds: new Immutable.Set()
}
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
textField: {
textColor: 'rgba(0,0,0,.87)',
focusColor: '#68a3e7',
backgroundColor: 'transparent',
borderColor: '#68a3e7'
}
});
}
render() {
let stepForm;
switch (this.state.step) {
case STEPS.NAME_INPUT:
stepForm = (
<form className="group-name" onSubmit={this.onNameSubmit}>
<div className="modal-new__body">
<TextField className="login__form__input"
floatingLabelText="Group name"
fullWidth
onChange={this.onNameChange}
value={this.state.name}/>
</div>
<footer className="modal-new__footer text-right">
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Add members"
secondary={true}
type="submit"/>
</footer>
</form>
);
break;
case STEPS.CONTACTS_SELECTION:
let contactList = _.map(ContactStore.getContacts(), (contact, i) => {
return (
<ContactItem contact={contact} key={i} onToggle={this.onContactToggle}/>
);
});
stepForm = (
<form className="group-members" onSubmit={this.onMembersSubmit}>
<div className="count">{this.state.selectedUserIds.size} Members</div>
<div className="modal-new__body">
<ul className="contacts__list">
{contactList}
</ul>
</div>
<footer className="modal-new__footer text-right">
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Create group"
secondary={true}
type="submit"/>
</footer>
</form>
);
break;
}
return stepForm;
}
onContactToggle = (contact, isSelected) => {
if (isSelected) {
this.setState({selectedUserIds: this.state.selectedUserIds.add(contact.uid)});
} else {
this.setState({selectedUserIds: this.state.selectedUserIds.remove(contact.uid)});
}
}
onNameChange = event => {
event.preventDefault();
this.setState({name: event.target.value});
}
onNameSubmit = event => {
event.preventDefault();
if (this.state.name) {
let name = this.state.name.trim();
if (name.length > 0) {
this.setState({step: STEPS.CONTACTS_SELECTION});
}
}
}
onMembersSubmit =event => {
event.preventDefault();
CreateGroupActionCreators.createGroup(this.state.name, null, this.state.selectedUserIds.toJS());
}
}
export default CreateGroupForm;
|
src/js/modules/DiagramTitle.js | fredyagomez/reactjs-D3-V4-grommet |
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import * as d3 from 'd3';
export default class DiagramV2 extends Component {
constructor (props) {
super(props);
this.state = {color: 'white', x: props.letterx, y: props.lettery, flag_tooltip: false};
}
componentWillAppear(callback) {
let node = d3.select(ReactDOM.findDOMNode(this));
this.setState({x: this.props.letterx});
this.setState({y: this.props.lettery});
this.setState({color: 'black'});
node.transition(this.props.transition)
.attr('x', this.state.x)
.attr('y', this.state.y)
.style('color', this.state.color)
.on('end', () => {
this.setState({color: this.state.color, x: this.state.x, y: this.state.y});
callback();
});
}
render() {
let x = 0;
let y = 0;
let color = 'white';
let entity = this.props.entity;
return (
<text x={x+5} y={y} key={x+y} color={color}>{entity} </text>
);
}
};
|
js/components/App.js | iamchenxin/relay-starter-kit | import React from 'react';
import Relay from 'react-relay';
class App extends React.Component {
render() {
return (
<div>
<h1>Widget list</h1>
<ul>
{this.props.viewer.widgets.edges.map(edge =>
<li key={edge.node.id}>{edge.node.name} (ID: {edge.node.id})</li>
)}
</ul>
</div>
);
}
}
export default Relay.createContainer(App, {
fragments: {
viewer: () => Relay.QL`
fragment on User {
widgets(first: 10) {
edges {
node {
id,
name,
},
},
},
}
`,
},
});
|
src/components/notfound.js | martezconner/react_vidhub | import React from 'react';
const NotFound = () => (
<div>
<p className="not-found">Sorry, but the page you were trying to view does not exist.</p>
<div className="big">
<h1 className="big-title">404</h1>
</div>
</div>
);
export default NotFound;
|
examples/auth-flow/app.js | stshort/react-router | import React from 'react'
import { render } from 'react-dom'
import { browserHistory, Router, Route, Link, withRouter } from 'react-router'
import withExampleBasename from '../withExampleBasename'
import auth from './auth'
const App = React.createClass({
getInitialState() {
return {
loggedIn: auth.loggedIn()
}
},
updateAuth(loggedIn) {
this.setState({
loggedIn
})
},
componentWillMount() {
auth.onChange = this.updateAuth
auth.login()
},
render() {
return (
<div>
<ul>
<li>
{this.state.loggedIn ? (
<Link to="/logout">Log out</Link>
) : (
<Link to="/login">Sign in</Link>
)}
</li>
<li><Link to="/about">About</Link></li>
<li><Link to="/dashboard">Dashboard</Link> (authenticated)</li>
</ul>
{this.props.children || <p>You are {!this.state.loggedIn && 'not'} logged in.</p>}
</div>
)
}
})
const Dashboard = React.createClass({
render() {
const token = auth.getToken()
return (
<div>
<h1>Dashboard</h1>
<p>You made it!</p>
<p>{token}</p>
</div>
)
}
})
const Login = withRouter(
React.createClass({
getInitialState() {
return {
error: false
}
},
handleSubmit(event) {
event.preventDefault()
const email = this.refs.email.value
const pass = this.refs.pass.value
auth.login(email, pass, (loggedIn) => {
if (!loggedIn)
return this.setState({ error: true })
const { location } = this.props
if (location.state && location.state.nextPathname) {
this.props.router.replace(location.state.nextPathname)
} else {
this.props.router.replace('/')
}
})
},
render() {
return (
<form onSubmit={this.handleSubmit}>
<label><input ref="email" placeholder="email" defaultValue="[email protected]" /></label>
<label><input ref="pass" placeholder="password" /></label> (hint: password1)<br />
<button type="submit">login</button>
{this.state.error && (
<p>Bad login information</p>
)}
</form>
)
}
})
)
const About = React.createClass({
render() {
return <h1>About</h1>
}
})
const Logout = React.createClass({
componentDidMount() {
auth.logout()
},
render() {
return <p>You are now logged out</p>
}
})
function requireAuth(nextState, replace) {
if (!auth.loggedIn()) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
})
}
}
render((
<Router history={withExampleBasename(browserHistory, __dirname)}>
<Route path="/" component={App}>
<Route path="login" component={Login} />
<Route path="logout" component={Logout} />
<Route path="about" component={About} />
<Route path="dashboard" component={Dashboard} onEnter={requireAuth} />
</Route>
</Router>
), document.getElementById('example'))
|
node_modules/react-bootstrap/es/DropdownMenu.js | ProjectSunday/rooibus | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _Array$from from 'babel-runtime/core-js/array/from';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import keycode from 'keycode';
import React from 'react';
import ReactDOM from 'react-dom';
import RootCloseWrapper from 'react-overlays/lib/RootCloseWrapper';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
import createChainedFunction from './utils/createChainedFunction';
import ValidComponentChildren from './utils/ValidComponentChildren';
var propTypes = {
open: React.PropTypes.bool,
pullRight: React.PropTypes.bool,
onClose: React.PropTypes.func,
labelledBy: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]),
onSelect: React.PropTypes.func,
rootCloseEvent: React.PropTypes.oneOf(['click', 'mousedown'])
};
var defaultProps = {
bsRole: 'menu',
pullRight: false
};
var DropdownMenu = function (_React$Component) {
_inherits(DropdownMenu, _React$Component);
function DropdownMenu(props) {
_classCallCheck(this, DropdownMenu);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_this.handleKeyDown = _this.handleKeyDown.bind(_this);
return _this;
}
DropdownMenu.prototype.handleKeyDown = function handleKeyDown(event) {
switch (event.keyCode) {
case keycode.codes.down:
this.focusNext();
event.preventDefault();
break;
case keycode.codes.up:
this.focusPrevious();
event.preventDefault();
break;
case keycode.codes.esc:
case keycode.codes.tab:
this.props.onClose(event);
break;
default:
}
};
DropdownMenu.prototype.getItemsAndActiveIndex = function getItemsAndActiveIndex() {
var items = this.getFocusableMenuItems();
var activeIndex = items.indexOf(document.activeElement);
return { items: items, activeIndex: activeIndex };
};
DropdownMenu.prototype.getFocusableMenuItems = function getFocusableMenuItems() {
var node = ReactDOM.findDOMNode(this);
if (!node) {
return [];
}
return _Array$from(node.querySelectorAll('[tabIndex="-1"]'));
};
DropdownMenu.prototype.focusNext = function focusNext() {
var _getItemsAndActiveInd = this.getItemsAndActiveIndex(),
items = _getItemsAndActiveInd.items,
activeIndex = _getItemsAndActiveInd.activeIndex;
if (items.length === 0) {
return;
}
var nextIndex = activeIndex === items.length - 1 ? 0 : activeIndex + 1;
items[nextIndex].focus();
};
DropdownMenu.prototype.focusPrevious = function focusPrevious() {
var _getItemsAndActiveInd2 = this.getItemsAndActiveIndex(),
items = _getItemsAndActiveInd2.items,
activeIndex = _getItemsAndActiveInd2.activeIndex;
if (items.length === 0) {
return;
}
var prevIndex = activeIndex === 0 ? items.length - 1 : activeIndex - 1;
items[prevIndex].focus();
};
DropdownMenu.prototype.render = function render() {
var _extends2,
_this2 = this;
var _props = this.props,
open = _props.open,
pullRight = _props.pullRight,
onClose = _props.onClose,
labelledBy = _props.labelledBy,
onSelect = _props.onSelect,
className = _props.className,
rootCloseEvent = _props.rootCloseEvent,
children = _props.children,
props = _objectWithoutProperties(_props, ['open', 'pullRight', 'onClose', 'labelledBy', 'onSelect', 'className', 'rootCloseEvent', 'children']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, 'right')] = pullRight, _extends2));
return React.createElement(
RootCloseWrapper,
{
disabled: !open,
onRootClose: onClose,
event: rootCloseEvent
},
React.createElement(
'ul',
_extends({}, elementProps, {
role: 'menu',
className: classNames(className, classes),
'aria-labelledby': labelledBy
}),
ValidComponentChildren.map(children, function (child) {
return React.cloneElement(child, {
onKeyDown: createChainedFunction(child.props.onKeyDown, _this2.handleKeyDown),
onSelect: createChainedFunction(child.props.onSelect, onSelect)
});
})
)
);
};
return DropdownMenu;
}(React.Component);
DropdownMenu.propTypes = propTypes;
DropdownMenu.defaultProps = defaultProps;
export default bsClass('dropdown-menu', DropdownMenu); |
web/static/js/utils.js | ryo33/Yayaka19 | import React from 'react'
import { Segment, Icon } from 'semantic-ui-react'
import { postPage } from './pages.js'
import { hashtag } from './global.js'
export const compareInsertedAtDesc = (a, b) => {
if (a.inserted_at > b.inserted_at) {
return -1
} else if (a.inserted_at < b.inserted_at) {
return 1
} else {
return 0
}
}
export const compareNotices = compareInsertedAtDesc
export const getTweetURL = post => {
const url = encodeURIComponent(`https://${post.host || location.host}${postPage.path({id: post.id})}`)
const text = encodeURIComponent(`“${post.text}” - ${post.user.display} (${post.user.name})`)
const hashtags = encodeURIComponent(hashtag)
return `https://twitter.com/intent/tweet?url=${url}&text=${text}&hashtags=${hashtags}`
}
export const DEFAULT_CHANNEL = `@@/${title}/DEFAULT_CHANNEL`
export function isDefaultChannel(channel) {
return channel == null || channel === DEFAULT_CHANNEL
}
export function createRemotePath(host, path) {
if (path) {
return `https://${host}${path}`
} else {
return null
}
}
export function isRemoteHost(host) {
return host != null && host != location.host
}
export function getLocalID(post) {
return post.remote_id || post.id
}
export function getPostKey(post) {
if (isRemoteHost(post.host)) {
return `${post.host}/${post.id}`
} else {
return post.remote_id || post.id
}
}
export function getPostsFooters(posts, localFooter = null) {
const endOfHosts = {}
let endOfLocal = null
posts.forEach(post => {
const { host } = post
if (isRemoteHost(host)) {
endOfHosts[host] = post
} else {
endOfLocal = post
}
})
const footers = {}
Object.keys(endOfHosts).forEach(host => {
footers[getPostKey(endOfHosts[host])] = (
<Segment basic secondary>
<Icon size='large' name='anchor' />
The end of posts from <Icon name='external' /> <a href={`https://${host}`}>{host}</a>
</Segment>
)
})
if (endOfLocal != null) {
footers[getPostKey(endOfLocal)] = localFooter
}
return footers
}
export function isSameUser(user1, user2) {
if (user1 == null || user2 == null) return false
const { host: host1, name: name1 } = user1
const { host: host2, name: name2 } = user2
const isSameRemoteUser = isRemoteHost(host1)
&& isRemoteHost(host2)
&& host1 == host2
&& name1 == name2
const isSameLocalUser = !isRemoteHost(host1)
&& !isRemoteHost(host2)
&& name1 == name2
return isSameRemoteUser || isSameLocalUser
}
|
src/components/Site/App.js | zjuasmn/sketch-react | import React from 'react'
import Document from '../Document/Document'
import "./index.css";
import fetch from 'isomorphic-fetch'
import Loading from './Loading'
import qs from 'querystring'
// https://github.com/github/fetch/issues/89#issuecomment-256610849
function futch(url, opts = {}, onProgress) {
return new Promise((res, rej) => {
let xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.open(opts.method || 'get', url);
for (let k in opts.headers || {})
xhr.setRequestHeader(k, opts.headers[k]);
xhr.onload = e => res(e.target);
xhr.onerror = rej;
// event.loaded / event.total * 100 ; //event.lengthComputable
if (onProgress) {
xhr.upload && xhr.upload.addEventListener('progress', onProgress);
xhr.addEventListener('progress', onProgress);
}
xhr.send(opts.body);
});
}
class Header extends React.PureComponent {
onClickTitle = () => {
this.fileInput && this.fileInput.click();
};
gao = (input) => {
this.fileInput = input;
};
render() {
let {file, filename = '', onSelectFile} = this.props;
return <div className="header">
<a className="title" href=".">Sketch React</a>
{
file && <a className="filename" onClick={this.onClickTitle}>
{filename.replace(/\.sketch$/, '')}
<input type="file" onChange={onSelectFile} accept=".sketch" hidden ref={this.gao}/>
</a>
}
{!file && <div className="flex"/>}
<div className="actions">
<a href="https://github.com/zjuasmn/sketch-react" className="icon-link">
<svg className="icon" width="16px" height="16px" viewBox="0 0 16 16">
<path
d="M8,0 C3.58,0 0,3.58 0,8 C0,11.54 2.29,14.53 5.47,15.59 C5.87,15.66 6.02,15.42 6.02,15.21 C6.02,15.02 6.01,14.39 6.01,13.72 C4,14.09 3.48,13.23 3.32,12.78 C3.23,12.55 2.84,11.84 2.5,11.65 C2.22,11.5 1.82,11.13 2.49,11.12 C3.12,11.11 3.57,11.7 3.72,11.94 C4.44,13.15 5.59,12.81 6.05,12.6 C6.12,12.08 6.33,11.73 6.56,11.53 C4.78,11.33 2.92,10.64 2.92,7.58 C2.92,6.71 3.23,5.99 3.74,5.43 C3.66,5.23 3.38,4.41 3.82,3.31 C3.82,3.31 4.49,3.1 6.02,4.13 C6.66,3.95 7.34,3.86 8.02,3.86 C8.7,3.86 9.38,3.95 10.02,4.13 C11.55,3.09 12.22,3.31 12.22,3.31 C12.66,4.41 12.38,5.23 12.3,5.43 C12.81,5.99 13.12,6.7 13.12,7.58 C13.12,10.65 11.25,11.33 9.47,11.53 C9.76,11.78 10.01,12.26 10.01,13.01 C10.01,14.08 10,14.94 10,15.21 C10,15.42 10.15,15.67 10.55,15.59 C13.71,14.53 16,11.53 16,8 C16,3.58 12.42,0 8,0 L8,0 Z"/>
</svg>
</a>
</div>
</div>
}
}
const simpleFiles = [
'https://zjuasmn.github.io/sketch-react/images/ui-video-simple-john-hansen.sketch',
'https://zjuasmn.github.io/sketch-react/images/Fitness%20App.sketch',
];
function getName(url) {
return decodeURIComponent(url.substring(url.lastIndexOf('/') + 1));
}
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
onSelectFile = (e) => {
if (!e) {
return this.setState({file: null, filename: ''});
}
e.preventDefault();
let file;
if (e.dataTransfer) {
file = e.dataTransfer.files[0];
} else if (e.target.files.length) {
file = e.target.files[0];
}
if (file) {
this.setState({file, filename: file.name});
}
};
onClickButton = () => {
this.fileInput && this.fileInput.click();
};
gao = (input) => {
this.fileInput = input;
};
selectFileFromURL = (url) => {
this.setState({file: fetch(url).then(r => r.blob()), filename: getName(url)})
};
componentWillMount() {
console.log('mount', this.state);
let url;
if (this.props.__url) {// for test
url = this.props.__url
} else {
let queryObj = qs.parse(location.search.substr(1));
if ('url' in queryObj) {
url = queryObj['url'];
}
}
if (url) {
this.setState({loading: true, filename: getName(url)});
futch(url, {}, (progress) => {
this.setState({progress})
})
.then(e => {
if (200 <= e.status && e.status < 300) {
this.setState({loading: false, file: e.response});
} else {
throw new Error('fail to fetch file from this url!');
}
})
.catch(e => {
this.setState({loading: false});
if(e.message) {
alert(e.message);
}else{
alert(`Fail to load from this url. Does it allow cross domain access?`);
}
location.search = '';
});
}
}
render() {
let {file, filename, loading, progress} = this.state;
return <div style={{height: '100%'}}>
<Header onSelectFile={this.onSelectFile} file={file} filename={filename}/>
{ loading &&
<Loading
style={{
margin: '120px auto 0'
}}
progress={progress}
filename={filename}
onCancel={() => location.search = ''}/>}
{!loading && !file && <div className="home">
<h2 className="sample-header" style={{textAlign: 'center', marginBottom: -36}}>From Local File</h2>
<div className="upload-area"
onDragEnter={(e) => {
e.preventDefault();
}}
onDragLeave={(e) => {
e.preventDefault();
}}
onDragOver={(e) => {
e.preventDefault();
}}
onDrop={this.onSelectFile}
// onDropCapture={(e) => {
// e.preventDefault();
// console.log(e);
// debugger
// }}
>
<div className="desc">Drop .sketch(v43+) file here</div>
<a className="upload-button" onClick={this.onClickButton}>Or select from computer<input
type="file" onChange={this.onSelectFile} accept=".sketch" hidden ref={this.gao}/></a>
</div>
<div className="sample">
<h2 className="sample-header">From URL</h2>
<input style={{
width: 320, lineHeight: '32px', boxSizing: 'border-box',
fontSize:16,
color: '#666',
padding: '0 8px',
outline: 'none',
}} id="url" defaultValue="https://zjuasmn.github.io/sketch-react/images/Fitness App.sketch"/>
<a className="upload-button" style={{boxSizing: 'border-box', width: 320, margin: '16px auto'}}
onClick={() => location.search = `?url=${encodeURIComponent(document.getElementById('url').value)}`}>Go</a>
</div>
{/*<div>*/}
{/*<a className="upload-button" onClick={() => {*/}
{/*let url = prompt(`Enter the file's URL`);*/}
{/*if (url) {*/}
{/*this.selectFileFromURL(url);*/}
{/*}*/}
{/*}}>parse .sketch file on web</a>*/}
{/*</div>*/}
<div className="sample">
<h2 className="sample-header">Sample Files</h2>
<div>
{simpleFiles.map(url =>
<div key={url} className="sample-link">
<a onClick={() => location.search = `?url=${encodeURIComponent(url)}`}>{getName(url)}</a>
{' ('}<a href={url}>raw</a>)
</div>
)}
</div>
</div>
</div>}
{!loading && file && <Document blob={file} style={{height: `calc(100% - 32px)`}}/>}
</div>
}
} |
src/components/Header/Header.js | churel/pricechecker | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react';
import styles from './Header.css';
import withStyles from '../../decorators/withStyles';
import Link from '../Link';
import Navigation from '../Navigation';
@withStyles(styles)
class Header extends Component {
render() {
return (
<div className="Header">
<div className="Header-container">
<a className="Header-brand" href="/" onClick={Link.handleClick}>
<img className="Header-brandImg" src={require('./logo-small.png')} width="38" height="38" alt="React" />
<span className="Header-brandTxt">Price Checker</span>
</a>
<Navigation className="Header-nav" />
<div className="Header-banner">
<h1 className="Header-bannerTitle">Price Checker</h1>
<p className="Header-bannerDesc">Check Price over different canadian price checkers.</p>
</div>
</div>
</div>
);
}
}
export default Header;
|
index.js | rastapasta/react-native-gl-model-view | import React, { Component } from 'react';
import { requireNativeComponent, View } from 'react-native';
import PropTypes from 'prop-types';
class GLModelView extends Component {
render() {
return <RNGLModelView {...this.props} />;
}
}
GLModelView.propTypes = {
...View.propTypes,
animate: PropTypes.bool,
flipTexture: PropTypes.bool,
model: PropTypes.object,
texture: PropTypes.object,
tint: PropTypes.object,
rotateX: PropTypes.number,
rotateY: PropTypes.number,
rotateZ: PropTypes.number,
scale: PropTypes.number,
scaleX: PropTypes.number,
scaleY: PropTypes.number,
scaleZ: PropTypes.number,
translateX: PropTypes.number,
translateY: PropTypes.number,
translateZ: PropTypes.number
};
var RNGLModelView = requireNativeComponent('RNGLModelView', GLModelView);
export default GLModelView;
|
client/components/SortableTree.js | XuHaoJun/tiamat | import React from 'react';
import Loadable from 'react-loadable';
function Loading() {
return <div>Loading...</div>;
}
const SortableTree = Loadable({
loader: async () => {
if (process.browser) {
const modules = await Promise.all([
import(/* webpackChunkName: "react-dnd-touch-backend" */ 'react-dnd-touch-backend'),
import(/* webpackChunkName: "react-dnd-html5-backend" */ 'react-dnd-html5-backend'),
import(/* webpackChunkName: "react-dnd-multi-backend" */ 'react-dnd-multi-backend'),
import(/* webpackChunkName: "react-dnd" */ 'react-dnd'),
import(/* webpackChunkName: "react-sortable-tree" */ 'react-sortable-tree'),
import(/* webpackChunkName: "react-sortable-tree/style.css" */ '../../node_modules/react-sortable-tree/style.css'),
]);
const [TouchBackend, HTML5Backend, MultiBackend, reactDnd, reactSortableTree] = modules;
const { TouchTransition } = MultiBackend;
const { DragDropContext } = reactDnd;
const HTML5toTouch = {
backends: [
{
backend: HTML5Backend.default,
},
{
backend: TouchBackend.default({
delayTouchStart: 10,
}), // Note that you can call your backends with options
preview: true,
transition: TouchTransition,
},
],
};
const { SortableTreeWithoutDndContext } = reactSortableTree;
const SortableTreeComponent = DragDropContext(MultiBackend.default(HTML5toTouch))(
SortableTreeWithoutDndContext
);
return SortableTreeComponent;
} else {
return Loading;
}
},
loading: Loading,
});
export default SortableTree;
|
examples/universal/client/index.js | splendido/redux | import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import configureStore from '../common/store/configureStore'
import App from '../common/containers/App'
const preloadedState = window.__PRELOADED_STATE__
const store = configureStore(preloadedState)
const rootElement = document.getElementById('app')
render(
<Provider store={store}>
<App/>
</Provider>,
rootElement
)
|
site/components/Cover.js | Reggino/react-dnd | import React from 'react';
import './Cover.less';
export default class Cover {
render() {
return (
<div className="Cover">
<div className="Cover-header">
<p className="Cover-description">
Drag and Drop for React
</p>
</div>
</div>
);
}
} |
src/server.js | louisukiri/react-starter-kit | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import path from 'path';
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import expressJwt, { UnauthorizedError as Jwt401Error } from 'express-jwt';
import expressGraphQL from 'express-graphql';
import jwt from 'jsonwebtoken';
import nodeFetch from 'node-fetch';
import React from 'react';
import ReactDOM from 'react-dom/server';
import PrettyError from 'pretty-error';
import App from './components/App';
import Html from './components/Html';
import { ErrorPageWithoutStyle } from './routes/error/ErrorPage';
import errorPageStyle from './routes/error/ErrorPage.css';
import createFetch from './createFetch';
import passport from './passport';
import router from './router';
import models from './data/models';
import schema from './data/schema';
import assets from './assets.json'; // eslint-disable-line import/no-unresolved
import configureStore from './store/configureStore';
import { setRuntimeVariable } from './actions/runtime';
import config from './config';
const app = express();
//
// Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the
// user agent is not known.
// -----------------------------------------------------------------------------
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || 'all';
//
// Register Node.js middleware
// -----------------------------------------------------------------------------
app.use(express.static(path.resolve(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//
// Authentication
// -----------------------------------------------------------------------------
app.use(
expressJwt({
secret: config.auth.jwt.secret,
credentialsRequired: false,
getToken: req => req.cookies.id_token,
}),
);
// Error handler for express-jwt
app.use((err, req, res, next) => {
// eslint-disable-line no-unused-vars
if (err instanceof Jwt401Error) {
console.error('[express-jwt-error]', req.cookies.id_token);
// `clearCookie`, otherwise user can't use web-app until cookie expires
res.clearCookie('id_token');
}
next(err);
});
app.use(passport.initialize());
if (__DEV__) {
app.enable('trust proxy');
}
app.get(
'/login/facebook',
passport.authenticate('facebook', {
scope: ['email', 'user_location'],
session: false,
}),
);
app.get(
'/login/facebook/return',
passport.authenticate('facebook', {
failureRedirect: '/login',
session: false,
}),
(req, res) => {
const expiresIn = 60 * 60 * 24 * 180; // 180 days
const token = jwt.sign(req.user, config.auth.jwt.secret, { expiresIn });
res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true });
res.redirect('/');
},
);
//
// Register API middleware
// -----------------------------------------------------------------------------
app.use(
'/graphql',
expressGraphQL(req => ({
schema,
graphiql: __DEV__,
rootValue: { request: req },
pretty: __DEV__,
})),
);
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
app.get('*', async (req, res, next) => {
try {
const css = new Set();
// Universal HTTP client
const fetch = createFetch(nodeFetch, {
baseUrl: config.api.serverUrl,
cookie: req.headers.cookie,
});
const initialState = {
user: req.user || null,
};
const store = configureStore(initialState, {
fetch,
// I should not use `history` on server.. but how I do redirection? follow universal-router
});
store.dispatch(
setRuntimeVariable({
name: 'initialNow',
value: Date.now(),
}),
);
// Global (context) variables that can be easily accessed from any React component
// https://facebook.github.io/react/docs/context.html
const context = {
// Enables critical path CSS rendering
// https://github.com/kriasoft/isomorphic-style-loader
insertCss: (...styles) => {
// eslint-disable-next-line no-underscore-dangle
styles.forEach(style => css.add(style._getCss()));
},
fetch,
// You can access redux through react-redux connect
store,
storeSubscription: null,
};
const route = await router.resolve({
...context,
path: req.path,
query: req.query,
});
if (route.redirect) {
res.redirect(route.status || 302, route.redirect);
return;
}
const data = { ...route };
data.children = ReactDOM.renderToString(
<App context={context} store={store}>
{route.component}
</App>,
);
data.styles = [{ id: 'css', cssText: [...css].join('') }];
data.scripts = [assets.vendor.js];
if (route.chunks) {
data.scripts.push(...route.chunks.map(chunk => assets[chunk].js));
}
data.scripts.push(assets.client.js);
data.app = {
apiUrl: config.api.clientUrl,
state: context.store.getState(),
};
const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
res.status(route.status || 200);
res.send(`<!doctype html>${html}`);
} catch (err) {
next(err);
}
});
//
// Error handling
// -----------------------------------------------------------------------------
const pe = new PrettyError();
pe.skipNodeFiles();
pe.skipPackage('express');
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
console.error(pe.render(err));
const html = ReactDOM.renderToStaticMarkup(
<Html
title="Internal Server Error"
description={err.message}
styles={[{ id: 'css', cssText: errorPageStyle._getCss() }]} // eslint-disable-line no-underscore-dangle
>
{ReactDOM.renderToString(<ErrorPageWithoutStyle error={err} />)}
</Html>,
);
res.status(err.status || 500);
res.send(`<!doctype html>${html}`);
});
//
// Launch the server
// -----------------------------------------------------------------------------
const promise = models.sync().catch(err => console.error(err.stack));
if (!module.hot) {
promise.then(() => {
app.listen(config.port, () => {
console.info(`The server is running at http://localhost:${config.port}/`);
});
});
}
//
// Hot Module Replacement
// -----------------------------------------------------------------------------
if (module.hot) {
app.hot = module.hot;
module.hot.accept('./router');
}
export default app;
|
frontend/src/NumberFormat.js | googleinterns/step78-2020 | import React from 'react';
import NumberFormat from 'react-number-format';
import PropTypes from 'prop-types';
export function NumberFormatCustom(props) {
const {inputRef, onChange, ...other} = props;
return (
<NumberFormat
{...other}
getInputRef={inputRef}
onValueChange={(values) => {
onChange({
target: {
value: values.value,
},
});
}}
thousandSeparator
isNumericString
/>
);
}
NumberFormatCustom.propTypes = {
inputRef: PropTypes.func.isRequired,
onChange: PropTypes.func.isRequired,
};
|
actor-sdk/sdk-web/src/components/Activity.react.js | ljshj/actor-platform | /*
* Copyright (C) 2015-2016 Actor LLC. <https://actor.im>
*/
import React, { Component } from 'react';
import { shouldComponentUpdate } from 'react-addons-pure-render-mixin';
import { Container } from 'flux/utils';
import { PeerTypes } from '../constants/ActorAppConstants';
import ActivityStore from '../stores/ActivityStore';
import DialogStore from '../stores/DialogStore';
import DialogInfoStore from '../stores/DialogInfoStore';
import UserProfile from './activity/UserProfile.react';
import GroupProfile from './activity/GroupProfile.react';
class ActivitySection extends Component {
static getStores() {
return [DialogStore, DialogInfoStore, ActivityStore];
}
static calculateState() {
return {
peer: DialogStore.getCurrentPeer(),
info: DialogInfoStore.getState(),
isOpen: ActivityStore.isOpen()
};
}
constructor(props) {
super(props);
this.shouldComponentUpdate = shouldComponentUpdate.bind(this);
}
componentDidUpdate() {
setImmediate(() => {
window.dispatchEvent(new Event('resize'));
});
}
renderBody() {
const { peer, info } = this.state;
switch (peer.type) {
case PeerTypes.USER:
return <UserProfile user={info} />;
case PeerTypes.GROUP:
return <GroupProfile group={info} />;
default:
return null;
}
}
render() {
const { peer, isOpen } = this.state;
if (!isOpen || !peer) {
return <section className="activity" />;
}
return (
<section className="activity activity--shown">
{this.renderBody()}
</section>
);
}
}
export default Container.create(ActivitySection);
|
App/Client/node_modules/react-router/modules/Route.js | qianyuchang/React-Chat | import React from 'react'
import invariant from 'invariant'
import { createRouteFromReactElement } from './RouteUtils'
import { component, components } from './PropTypes'
const { string, func } = React.PropTypes
/**
* A <Route> is used to declare which components are rendered to the
* page when the URL matches a given pattern.
*
* Routes are arranged in a nested tree structure. When a new URL is
* requested, the tree is searched depth-first to find a route whose
* path matches the URL. When one is found, all routes in the tree
* that lead to it are considered "active" and their components are
* rendered into the DOM, nested in the same order as in the tree.
*/
const Route = React.createClass({
statics: {
createRouteFromReactElement
},
propTypes: {
path: string,
component,
components,
getComponent: func,
getComponents: func
},
/* istanbul ignore next: sanity check */
render() {
invariant(
false,
'<Route> elements are for router configuration only and should not be rendered'
)
}
})
export default Route
|
client/index.js | azproduction/node-mc | import React from 'react';
import FluxComponent from 'flummox/component';
import ClientFlux from './flux';
import App from './app';
import TuiDom from '../lib/tui-dom';
import io from 'socket.io-client';
window.React = React;
let socket = io({
transports: ['websocket', 'polling']
});
let flux = new ClientFlux();
flux.connect(socket);
let appStores = {
tabs: (store) => ({
panels: {
leftPanel: store.getTab('leftPanel'),
rightPanel: store.getTab('rightPanel')
},
activePanelName: store.getActiveTabName()
}),
file: (store) => ({
isFileOpened: store.getFileName() !== null,
openedFileName: store.getFileName(),
openedFileContent: store.getFileContent()
})
};
let tuiDomStores = {
config: (store) => {
var config = store.getConfig();
return {
showStats: config.clientShowStats,
waitForDOMChanges: !config.clientRaf,
scale: config.clientScale,
isHeadlessBrowser: config.client === 'phantomjs',
useMutationObserver: config.clientMutationObserver
};
}
};
let content = (
<FluxComponent flux={flux} connectToStores={tuiDomStores}>
<TuiDom socket={socket}>
<FluxComponent flux={flux} connectToStores={appStores}>
<App />
</FluxComponent>
</TuiDom>
</FluxComponent>
);
React.render(content, document.querySelector('#app'));
|
js/components/NewsTab.js | tausifmuzaffar/bisApp |
import React, { Component } from 'react';
import { connect } from 'react-redux';
var moment = require('moment');
import { actions } from 'react-native-navigation-redux-helpers';
import { Image, WebView, AsyncStorage } from 'react-native';
import { Container, Header, Subtitle, Title, Content, H2, Button, Footer,
FooterTab,Card, CardItem, Text, Body, Left, Right, Icon, Segment,
Spinner } from 'native-base';
import { Actions } from 'react-native-router-flux';
import PrayerTimes from './PrayerTimes';
import JummahTimes from './JummahTimes';
import { openDrawer } from '../actions/drawer';
import { Col, Row, Grid } from 'react-native-easy-grid';
import styles from './styles';
const {
popRoute,
} = actions;
class NewsTab extends Component {
constructor(props) {
super(props);
this.state = {
announcements: [],
};
}
getAnnouncement(){
fetch("http://aleemstudio.com/MobileDeviceSupport/GetLastAnnouncementJSONList/")
.then((response) => response.json())
.then((responseJson) => {
this.setState({announcements: responseJson});
})
.done();
}
componentWillMount() {
this.getAnnouncement();
}
render() {
function replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
function cleanString(javaString){
let output;
output = replaceAll(javaString, "\r\n", '');
output = replaceAll(output, "\n", '');
output = replaceAll(output, "\r", '');
output = replaceAll(output, " ", ' ');
return output;
}
if(this.state.announcements !== []){
return (
<Content style={{ backgroundColor: '#F5F5F5' }} padder>
<Card style={styles.mb}>
<CardItem bordered style={{ backgroundColor: '#7E57C2' }}>
<Row>
<Col size={10}></Col>
<Col size={80}>
<Title style={{ color: '#FFF', textAlign: 'center' }}>News & Announcements</Title>
</Col>
<Col size={10}></Col>
</Row>
</CardItem>
{this.state.announcements.map(function(announcement, i){
return(
<CardItem bordered key={i}>
<Text>
{cleanString(announcement.text)}
</Text>
</CardItem>);
})}
</Card>
</Content>
);
} else {
return (<Spinner color="blue" />);
}
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
popRoute: key => dispatch(popRoute(key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
themeState: state.drawer.themeState,
});
export default connect(mapStateToProps, bindAction)(NewsTab);
|
src/components/svg/Ox.js | JoeTheDave/onitama | import PropTypes from 'prop-types';
import React from 'react';
export const Ox = ({ fillColor }) => (
<svg width="130px" height="130px" viewBox="0 0 545 760" preserveAspectRatio="xMidYMid meet">
<g transform="translate(0, 760) scale(0.1, -0.1)" fill={fillColor} stroke="none">
<path d="M2780 7588 c-52 -9 -95 -49 -87 -82 3 -12 20 -61 38 -111 l34 -90 -2
-335 c-1 -184 -7 -387 -13 -450 -10 -108 -9 -120 12 -191 22 -72 23 -87 15
-240 -4 -90 -5 -198 -2 -240 l6 -76 -36 -31 c-23 -21 -46 -32 -66 -32 -37 0
-162 -41 -229 -75 l-49 -25 -19 33 c-11 17 -33 61 -50 97 -46 98 -106 175
-170 219 -66 45 -109 89 -145 147 -40 64 -187 168 -272 192 -138 39 -415 160
-415 182 0 16 -26 12 -41 -6 -11 -13 -9 -23 10 -59 13 -24 38 -61 56 -82 36
-43 60 -92 69 -142 5 -30 49 -100 113 -180 18 -23 22 -42 24 -136 l3 -110 -56
-145 c-81 -208 -80 -207 -76 -370 2 -111 7 -152 19 -175 9 -16 29 -61 43 -100
15 -38 34 -79 44 -91 28 -34 146 -65 212 -56 88 11 332 -16 386 -44 28 -15 33
-15 70 3 21 11 82 33 134 48 52 15 102 29 111 32 11 3 20 -6 29 -27 12 -28 11
-33 -2 -41 -29 -16 -284 -213 -458 -354 -96 -78 -227 -172 -290 -210 -63 -38
-188 -115 -278 -172 -96 -60 -200 -117 -250 -137 -48 -19 -130 -53 -182 -76
-52 -22 -187 -70 -300 -106 -113 -35 -252 -81 -310 -103 -58 -21 -143 -46
-190 -54 -96 -18 -122 -34 -167 -101 -42 -61 -56 -117 -49 -186 31 -310 32
-313 68 -385 48 -94 91 -151 129 -170 25 -14 39 -14 80 -6 28 6 84 11 126 11
75 0 77 1 187 64 61 36 134 74 163 85 29 11 87 38 130 59 43 22 110 51 148 65
39 13 111 43 161 66 51 23 98 41 106 41 8 0 39 13 69 29 82 44 203 92 419 165
214 73 304 107 365 138 64 32 404 148 435 148 31 0 70 -33 70 -59 0 -9 -5
-137 -10 -286 -7 -183 -7 -528 0 -1070 14 -1091 20 -1221 80 -1685 48 -367 64
-446 97 -482 35 -39 56 -24 122 86 34 57 40 74 35 102 -5 27 -3 34 9 34 11 0
16 14 20 47 6 62 30 167 62 268 16 53 34 155 50 300 14 121 37 290 51 375 14
85 32 254 40 375 21 327 62 771 84 903 11 64 20 161 20 215 0 60 9 149 24 230
14 73 30 206 36 297 6 91 13 173 16 183 3 10 -4 58 -16 108 -20 87 -20 92 -4
110 10 11 41 26 69 34 48 14 87 13 526 -19 385 -29 497 -40 594 -62 66 -14
158 -29 205 -33 47 -4 105 -13 130 -19 25 -6 106 -16 181 -23 178 -14 201 -8
291 79 37 36 68 70 68 75 0 24 -171 325 -201 352 -17 17 -46 53 -65 81 -29 46
-128 142 -208 202 -32 25 -91 29 -165 11 -25 -5 -88 -11 -140 -13 -89 -3 -196
-22 -361 -64 -37 -9 -107 -16 -165 -17 -55 0 -224 -9 -376 -19 -152 -10 -288
-16 -302 -12 -16 4 -33 19 -43 38 -15 28 -15 50 -5 202 6 94 11 230 10 301 -1
72 4 149 10 172 8 31 41 74 133 174 125 138 135 147 179 148 14 1 52 18 85 39
32 21 82 46 109 56 29 11 67 36 90 60 82 84 86 192 14 411 -21 65 -63 104 -97
90 -9 -4 -73 -11 -142 -16 -69 -5 -152 -12 -185 -15 -33 -2 -80 -1 -105 3 -61
11 -80 48 -80 158 0 44 -5 130 -11 190 -13 134 3 381 33 525 45 212 24 290
-149 564 -35 55 -68 117 -73 138 -8 26 -20 43 -40 53 -16 9 -46 29 -65 47 -33
28 -39 30 -83 23 -61 -10 -103 -8 -166 8 -33 9 -67 10 -96 5z m-130 -3183 c40
-48 12 -179 -54 -252 -40 -43 -45 -45 -151 -68 -180 -38 -205 -44 -311 -65
-109 -22 -450 -116 -661 -182 -73 -23 -136 -39 -139 -35 -16 16 63 90 135 128
42 22 95 54 118 71 40 29 44 30 92 21 l50 -10 92 58 c51 33 109 62 128 65 20
4 55 20 79 36 67 46 190 100 382 168 96 34 182 66 190 71 22 12 36 11 50 -6z
m-1831 -706 c38 -13 38 -18 4 -51 -56 -52 -135 -86 -263 -113 -69 -15 -145
-33 -170 -40 -51 -16 -60 -13 -60 19 0 41 31 63 130 92 52 15 127 40 165 57
39 16 88 33 110 37 22 4 43 8 46 9 3 0 20 -4 38 -10z"
/>
</g>
</svg>
);
Ox.propTypes = {
fillColor: PropTypes.string.isRequired,
};
export default Ox;
|
misc/webgui/src/components/Statedevice.js | ChainsAutomation/chains | import React from 'react';
// Per service render
export default class StateDevice extends React.Component {
render() {
/*
console.log("StateDevice");
console.log(this.props);
//*/
const ddata = this.props.ddata;
let devData = [];
for (var dev in ddata['data']) {
const dItem = dev;
let dVal = ddata['data'][dev]['value'];
if (typeof(dVal) != 'string')
dVal = JSON.stringify(dVal);
const attr = <div key={dItem}><div className="header">{dItem}</div><div className="meta">{dVal}</div></div>;
//console.log(attr);
devData.push(attr);
}
return (
<div className="ui raised card">
<div className="content">
<div className="header">{this.props.name}</div>
<div className="meta">
<span className="category">{ddata.class}</span>
</div>
<div className="description">
{devData}
</div>
</div>
<div className="extra content">
<div className="right floated author">
<img className="ui avatar image" src={ddata.icon} /> {ddata.type}
</div>
</div>
</div>
);
}
}
/*
<div className="card">
<div className="image">
<img src="http://mrg.bz/IxQIgC" />
</div>
<div className="content">
{devData}
</div>
<div className="ui bottom attached basic buttons">
<button className="ui button"><i className="pencil icon"></i></button>
<button className="ui button"><i className="trash icon"></i></button>
</div>
</div>
*/
|
example/App/Pulse.js | nkbt/react-motion-loop | import React from 'react';
import {spring, presets} from 'react-motion';
import {ReactMotionLoop} from '../../src';
export const Pulse = () => (
<ReactMotionLoop
styleFrom={{
width: 0,
height: 0,
borderRadius: 0
}}
styleTo={{
width: spring(100, presets.stiff),
height: spring(100, presets.stiff),
borderRadius: spring(50, presets.stiff)
}}>
{style => <div className="element" style={style} />}
</ReactMotionLoop>
);
|
src/Settings/FirstDayOfWeekDialog.js | mkermani144/wanna | import React, { Component } from 'react';
import Dialog from 'material-ui/Dialog';
import { RadioButton, RadioButtonGroup } from 'material-ui/RadioButton';
import FlatButton from 'material-ui/FlatButton';
import { blue500, grey50 } from 'material-ui/styles/colors';
class FirstDayOfWeekDialog extends Component {
handleRequestClose = (e, target) => {
setTimeout(() => {
this.props.onRequestClose(target);
}, 300);
}
render() {
const actions = [
<FlatButton
label="Cancel"
primary
onClick={() => this.props.onRequestClose(this.props.firstDayOfWeek)}
/>,
];
const dialogContentStyle = {
maxWidth: 256,
};
const radioButtonStyle = {
marginTop: 16,
};
const dialogTitleStyle = {
backgroundColor: blue500,
color: grey50,
cursor: 'default',
};
return (
<Dialog
title="First day of week"
titleStyle={dialogTitleStyle}
contentStyle={dialogContentStyle}
actions={actions}
open={this.props.open}
onRequestClose={() => this.props.onRequestClose(this.props.firstDayOfWeek)}
>
<RadioButtonGroup
name="firstDayOfWeek"
defaultSelected={`${this.props.firstDayOfWeek}`}
onChange={this.handleRequestClose}
>
<RadioButton
label="Saturday"
value="6"
style={radioButtonStyle}
/>
<RadioButton
label="Sunday"
value="0"
style={radioButtonStyle}
/>
<RadioButton
label="Monday"
value="1"
style={radioButtonStyle}
/>
</RadioButtonGroup>
</Dialog>
);
}
}
export default FirstDayOfWeekDialog;
|
src/svg-icons/editor/attach-money.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorAttachMoney = (props) => (
<SvgIcon {...props}>
<path d="M11.8 10.9c-2.27-.59-3-1.2-3-2.15 0-1.09 1.01-1.85 2.7-1.85 1.78 0 2.44.85 2.5 2.1h2.21c-.07-1.72-1.12-3.3-3.21-3.81V3h-3v2.16c-1.94.42-3.5 1.68-3.5 3.61 0 2.31 1.91 3.46 4.7 4.13 2.5.6 3 1.48 3 2.41 0 .69-.49 1.79-2.7 1.79-2.06 0-2.87-.92-2.98-2.1h-2.2c.12 2.19 1.76 3.42 3.68 3.83V21h3v-2.15c1.95-.37 3.5-1.5 3.5-3.55 0-2.84-2.43-3.81-4.7-4.4z"/>
</SvgIcon>
);
EditorAttachMoney = pure(EditorAttachMoney);
EditorAttachMoney.displayName = 'EditorAttachMoney';
EditorAttachMoney.muiName = 'SvgIcon';
export default EditorAttachMoney;
|
4-routing/src/index.js | pirosikick/react-hands-on-20171023 | import React from 'react';
import ReactDOM from 'react-dom';
import * as firebase from 'firebase';
import firebaseConfig from './firebaseConfig.json';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
// firebaseを初期化
// firebaseのコンソールに表示されるJSONをコピーしてくる
firebase.initializeApp(firebaseConfig);
ReactDOM.render(<App />, root);
registerServiceWorker();
|
examples/huge-apps/components/App.js | dalexand/react-router | import React from 'react';
import Dashboard from './Dashboard';
import GlobalNav from './GlobalNav';
class App extends React.Component {
render() {
var courses = COURSES;
return (
<div>
<GlobalNav />
<div style={{ padding: 20 }}>
{this.props.children || <Dashboard courses={courses} />}
</div>
</div>
);
}
}
export default App;
|
src/components/DataTableSkeleton/DataTableSkeleton.js | carbon-design-system/carbon-components-react | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import { settings } from 'carbon-components';
const { prefix } = settings;
const DataTableSkeleton = ({
rowCount,
columnCount,
zebra,
compact,
headers,
...other
}) => {
const dataTableSkeletonClasses = classNames({
[`${prefix}--skeleton`]: true,
[`${prefix}--data-table`]: true,
[`${prefix}--data-table--zebra`]: zebra,
[`${prefix}--data-table--compact`]: compact,
});
let normalizedHeaders;
if (headers[0] === Object(headers[0]) && !Array.isArray(headers[0])) {
normalizedHeaders = headers.map(current => current.header);
} else {
normalizedHeaders = headers;
}
const rowRepeat = rowCount - 1;
const rows = Array(rowRepeat);
const columnsArray = Array.from({ length: columnCount }, (_, index) => index);
for (let i = 0; i < rowRepeat; i++) {
rows[i] = (
<tr key={i}>
{columnsArray.map(j => (
<td key={j} />
))}
</tr>
);
}
return (
<table className={dataTableSkeletonClasses} {...other}>
<thead>
<tr>
{columnsArray.map(i => (
<th key={i}>{normalizedHeaders[i]}</th>
))}
</tr>
</thead>
<tbody>
<tr>
{columnsArray.map(i => (
<td key={i}>
<span />
</td>
))}
</tr>
{rows}
</tbody>
</table>
);
};
DataTableSkeleton.propTypes = {
/**
* Specify the number of rows that you want to render in the skeleton state
*/
rowCount: PropTypes.number,
/**
* Specify the number of columns that you want to render in the skeleton state
*/
columnCount: PropTypes.number,
/**
* Optionally specify whether you want the DataTable to be zebra striped
*/
zebra: PropTypes.bool,
/**
* Optionally specify whether you want the Skeleton to be rendered as a
* compact DataTable
*/
compact: PropTypes.bool,
/**
* Optionally specify the displayed headers
*/
headers: PropTypes.oneOfType([
PropTypes.array,
PropTypes.shape({
key: PropTypes.string,
header: PropTypes.node,
}),
]),
};
DataTableSkeleton.defaultProps = {
rowCount: 5,
columnCount: 5,
zebra: false,
compact: false,
headers: [],
};
export default DataTableSkeleton;
|
src/components/SignereLogin.js | Korkemoms/amodahl.no | // @flow
import React from 'react'
import '../MyContent.scss'
import '../App.scss'
import MyHeader from '../components/MyHeader'
import DocumentTitle from 'react-document-title'
import queryString from 'query-string'
import {
Grid,
Table,
PageHeader,
Button
} from 'react-bootstrap'
/* Purely presentational component */
export default class SignereLogin extends React.Component {
componentDidMount () {
const urlParameters = queryString.parse(location.search)
if (urlParameters.signereRequestId) {
this.props.push('/login')
this.props.login({
type: 'signere',
signereRequestId: urlParameters.signereRequestId
})
}
}
render () {
const urlParameters = queryString.parse(location.search)
let loginButton
if (urlParameters.signereRequestId) {
loginButton = <Button
bsStyle='primary'
onClick={() => {
this.props.push('/login')
this.props.login({
type: 'signere',
signereRequestId: urlParameters.signereRequestId
})
}}>
Log in with Signere (stage 2)
</Button>
} else if (!this.props.url) {
loginButton = <Button
bsStyle='primary'
onClick={() => {
this.props.login({
type: 'signere',
navigate: this.props.push
})
}}>
Log in with Signere (stage 1)
</Button>
}
const testUserInfo = this.props.url
? <div>
<iframe style={{width: '100%', height: '400px', border: '0'}} src={this.props.url} />
<PageHeader>Test users</PageHeader>
<Table striped bordered condensed hover>
<thead>
<tr>
<th>Social security number</th>
<th>Name</th>
<th>One time code</th>
<th>Password</th>
</tr>
</thead>
<tbody>
<tr>
<td>11080258625</td>
<td>Gates, Bill</td>
<td>otp</td>
<td>qwer1234</td>
</tr>
<tr>
<td>02038073735</td>
<td>Musk, Elon</td>
<td>otp</td>
<td>qwer1234</td>
</tr>
<tr>
<td>02035031930</td>
<td>Jobs, Steve</td>
<td>otp</td>
<td>qwer1234</td>
</tr>
<tr>
<td>18120112345</td>
<td >Pan, Peter</td>
<td>otp</td>
<td>qwer1234</td>
</tr>
</tbody>
</Table>
</div>
: null
return (
<DocumentTitle title='Signere log in'>
<div>
<MyHeader headline='Log in with signere.no' />
<div className='mycontent'>
<Grid>
{loginButton}
{testUserInfo}
</Grid>
</div>
</div>
</DocumentTitle>
)
}
}
|
src/Divider/Divider.js | hai-cea/material-ui | import React from 'react';
import PropTypes from 'prop-types';
const Divider = (props, context) => {
const {
inset,
style,
...other
} = props;
const {
baseTheme,
prepareStyles,
} = context.muiTheme;
const styles = {
root: {
margin: 0,
marginTop: -1,
marginLeft: inset ? 72 : 0,
height: 1,
border: 'none',
backgroundColor: baseTheme.palette.borderColor,
},
};
return (
<hr {...other} style={prepareStyles(Object.assign(styles.root, style))} />
);
};
Divider.muiName = 'Divider';
Divider.propTypes = {
/**
* If true, the `Divider` will be indented.
*/
inset: PropTypes.bool,
/**
* Override the inline-styles of the root element.
*/
style: PropTypes.object,
};
Divider.defaultProps = {
inset: false,
};
Divider.contextTypes = {
muiTheme: PropTypes.object.isRequired,
};
export default Divider;
|
src/js/AppContainer.js | gabsprates/facomp-quiz | import React, { Component } from 'react';
import {
HashRouter as Router, Route
} from 'react-router-dom';
import io from 'socket.io-client'
import QuizBox from './Components/QuizBox';
import QuestionContainer from './Components/Question/QuestionContainer';
import config from '../../config/config';
import Requests from './Services/Requests';
export default class AppContainer extends Component {
constructor(props) {
super(props);
this.state = {
score: {
a: 0,
b: 0
},
team: false,
apertou: false,
batimento: 0
}
this.errorMessage = "";
var socket = io.connect(`${config.websocket}`);
socket.on('connect', () => {
socket.on('apertou', (e) => {
if (!this.state.team) {
console.log('disparou aperta');
this.setActiveTeam(e);
this.setState({ apertou: true });
}
});
socket.on('coracao', (e) => {
console.log('disparou coracao');
this.setBatimento(e.batimento);
});
});
if (!window.localStorage) {
this.errorMessage = (<span>
Seu navegador não tem suporte para esta aplicação.<br /><br />
Para mais detalhes: <strong>window.localStorage</strong>
</span>);
location.href = '#/erro';
}
this.limpaEquipeBatimentos = this.limpaEquipeBatimentos.bind(this);
this.setActiveTeam = this.setActiveTeam.bind(this);
this.setBatimento = this.setBatimento.bind(this);
this.limpaApertou = this.limpaApertou.bind(this);
this.limpaPlacar = this.limpaPlacar.bind(this);
}
setActiveTeam(e) {
const equipe = e.equipe;
this.setState({
team: {
score: this.state.score[equipe],
team: equipe
}
});
}
limpaApertou() {
this.setState({ apertou: false });
}
limpaEquipeBatimentos() {
this.setState({
team: false,
batimento: 0
});
}
addTeamScore(team = null, pts = 0) {
if (team) {
this.setState((prevState, props) => {
let score = prevState.score;
score[team] = prevState.score[team] + pts;
let equipe = prevState.team;
equipe.score = score[team];
return {
score: score,
team: equipe
};
});
}
}
limpaPlacar() {
this.setState({
score: { a: 0, b: 0 }
});
}
setBatimento(beat) {
this.setState({ batimento: beat });
}
render() {
return (
<div>
<Router>
<section>
<Route exact path='/' render={ ({ match }) => {
return <QuizBox
score={ this.state.score }
apertou={ this.state.apertou }
limpaPlacar={ this.limpaPlacar }
limpaApertou={ this.limpaApertou } />
}
} />
<Route path='/erro' render={ ({ match }) => {
return <div className="has-text-centered">
<h1 className="title is-1">
{ this.errorMessage }
</h1>
</div>
}
} />
<Route path='/question/:id/:number' render={ ({ match }) => {
if (this.state.team) {
return <QuestionContainer
controlScore={ (pts) => {
this.addTeamScore(this.state.team.team, pts);
} }
heartBeat={ this.state.batimento }
clearAll={ this.limpaEquipeBatimentos }
match={ match }
team={ this.state.team }
/>
}
location.href = '#/';
return false;
}
} />
</section>
</Router>
</div>
);
}
}
|
src/interface/common/CyclingVideo.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
class CyclingVideo extends React.PureComponent {
static propTypes = {
videos: PropTypes.arrayOf(PropTypes.string).isRequired,
randomValue: PropTypes.number,
};
constructor(props) {
super(props);
const randomValue = props.randomValue !== undefined ? props.randomValue : Math.random();
this.state = {
current: Math.floor(randomValue * props.videos.length),
};
this.handleEnded = this.handleEnded.bind(this);
}
handleEnded() {
this.setState({
current: (this.state.current + 1) % this.props.videos.length,
});
}
render() {
const { videos, ...others } = this.props;
const currentVideo = videos[this.state.current];
return (
<video
autoPlay
muted
onEnded={this.handleEnded}
key={currentVideo} // without this the element doesn't rerender properly and wouldn't start the next video
{...others}
>
<source src={currentVideo} type="video/mp4" />
</video>
);
}
}
export default CyclingVideo;
|
packages/material-ui-icons/src/ViewArray.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M4 18h3V5H4v13zM18 5v13h3V5h-3zM8 18h9V5H8v13z" /></g>
, 'ViewArray');
|
imports/ui/components/manage/manage-users-items.js | irvinlim/free4all | import React from 'react';
import Subheader from 'material-ui/Subheader';
import { GridList, GridTile } from 'material-ui/GridList';
import Paper from 'material-ui/Paper';
import ReactList from 'react-list';
import { Card, CardActions, CardText, CardHeader, CardTitle } from 'material-ui/Card';
import PaperCard from '../../layouts/paper-card';
import { List, ListItem } from 'material-ui/List';
import Link, { LinkButton } from '../../layouts/link';
import Chip from 'material-ui/Chip';
import FlatButton from 'material-ui/FlatButton';
import Dialog from 'material-ui/Dialog';
import * as UsersHelper from '../../../util/users';
import * as IconsHelper from '../../../util/icons';
import * as RolesHelper from '../../../util/roles';
import { Communities } from '../../../api/communities/communities';
import { banUser, unbanUser, deleteUser } from '../../../api/users/methods';
let users = [];
const makeChip = (role, index) => {
let label;
if (role == "moderator") {
label = "Mod";
} else if (role == "admin") {
label = "Admin";
} else {
return null;
}
return (
<Chip key={index} backgroundColor="#8595b7" labelStyle={{ fontSize: 12, textTransform: 'uppercase', color: "#fff", lineHeight: "24px", padding: "0 8px" }}>
{ label }
</Chip>
);
};
const communityDisplay = (community, isHome=false) => (
<span className="community-display" key={community._id}>
{ isHome ? IconsHelper.icon("home", { color: "#9c9c9c", fontSize: "16px", marginRight: 3 }) : null }
{ community.name }
</span>
);
const DialogUser = ({ open, handleClose, handleSubmit, children }) => {
const actions = [
<FlatButton label="Cancel" onTouchTap={ handleClose } />,
<FlatButton label="Confirm" onTouchTap={ handleSubmit } />
];
return (
<Dialog
title="Are you sure?"
open={ open }
actions={ actions }
onRequestClose={ handleClose }>
{ children }
</Dialog>
);
};
export class ManageUsersItems extends React.Component {
constructor(props) {
super(props);
this.state = {
confirmBanDialogOpen: false,
confirmDeleteDialogOpen: false,
confirmUser: null,
};
}
handleBanUnbanUser() {
const user = this.state.confirmUser;
const self = this;
if (!user)
return;
const action = RolesHelper.isBanned(user) ? unbanUser : banUser;
const actionWord = RolesHelper.isBanned(user) ? "unbanned" : "banned";
action.call({ userId: user._id }, (error) => {
if (error) {
Bert.alert(error.reason, 'danger');
} else {
Bert.alert(`Successfully ${actionWord} user.`, 'success');
self.handleCloseConfirmBanDialog();
}
});
}
handleDeleteUser() {
const user = this.state.confirmUser;
const self = this;
if (!user)
return;
deleteUser.call({ userId: user._id }, (error) => {
if (error) {
Bert.alert(error.reason, 'danger');
} else {
Bert.alert("Successfully deleted user.", 'success');
self.handleCloseConfirmDeleteDialog();
}
});
}
handleCloseConfirmBanDialog() {
this.setState({ confirmBanDialogOpen: false, confirmUser: null });
}
handleCloseConfirmDeleteDialog() {
this.setState({ confirmDeleteDialogOpen: false, confirmUser: null });
}
renderItem(index, key) {
const self = this;
const user = users[index];
const homeCommunity = user.profile.homeCommunityId ? Communities.findOne(user.profile.homeCommunityId) : null;
const userCommunities = user.communityIds ? Communities.find({ _id: { $in: user.communityIds.filter(x => x !== user.profile.homeCommunityId) } }) : null;
return (
<Card key={ key } className="manage-users-item profile">
<CardHeader
title={
<h3 style={{ marginTop: 0 }}>
{ UsersHelper.getFullName(user) }
{ user.roles ? <span className="role-chips">{ user.roles.map(makeChip) }</span> : null }
</h3>
}
subtitle={
<span className="user-communities-display">
{ homeCommunity ? communityDisplay(homeCommunity, true) : null }
{ userCommunities ? userCommunities.map(comm => communityDisplay(comm, false)) : null }
</span>
}
avatar={ UsersHelper.getAvatar(user, 80) }
actAsExpander={true}
showExpandableButton={true}
/>
<CardText expandable={true}>
<List>
<ListItem secondaryText="Last Login" primaryText={ UsersHelper.adminGetLastLoginDate(user) } leftIcon={ IconsHelper.icon("lock_open") } />
<ListItem secondaryText="Date Registered" primaryText={ UsersHelper.adminGetRegisteredDate(user) } insetChildren={true} />
<ListItem secondaryText="Primary Email" primaryText={ UsersHelper.adminGetFirstEmail(user) } leftIcon={ IconsHelper.icon("mail") } />
</List>
</CardText>
<CardActions>
<LinkButton label="View Profile" to={ `/profile/${user._id}` } />
<LinkButton label="Edit Profile" to={ `/manage/users/${user._id}` } />
<FlatButton label={ RolesHelper.isBanned(user._id) ? "Unban User" : "Ban User" } onTouchTap={ e => self.setState({ confirmBanDialogOpen: true, confirmUser: user }) } />
<FlatButton label="Delete User" onTouchTap={ e => this.setState({ confirmDeleteDialogOpen: true, confirmUser: user }) } />
</CardActions>
</Card>
);
}
render() {
users = this.props.users;
return (
<div id="manage-users-items">
<ReactList
itemRenderer={ this.renderItem.bind(this) }
length={ users.length }
type='simple'
/>
<DialogUser
open={ this.state.confirmBanDialogOpen }
handleClose={ this.handleCloseConfirmBanDialog.bind(this) }
handleSubmit={ this.handleBanUnbanUser.bind(this) }>
<p>Are you sure you want to { RolesHelper.isBanned(this.state.confirmUser) ? "unban" : "ban" } this user?</p>
</DialogUser>
<DialogUser
open={ this.state.confirmDeleteDialogOpen }
handleClose={ this.handleCloseConfirmDeleteDialog.bind(this) }
handleSubmit={ this.handleDeleteUser.bind(this) }>
<p>Are you sure you want to delete this user? This actions is <strong>irreversible</strong>!!!</p>
<p>Note that any recovery of the user will have to be done manually in the database.</p>
</DialogUser>
</div>
);
}
}
|
src/components/ui-elements/PTPanel/PTPanel.js | PulseTile/PulseTile-React | import React from 'react';
import PropTypes from 'prop-types';
import { Col, Panel } from 'react-bootstrap';
import { bootstrapUtils } from 'react-bootstrap/lib/utils';
bootstrapUtils.addStyle(Panel, 'secondary');
const PTPanel = props => <Col className={props.className}>
<Panel header={props.header} bsStyle="secondary" className={props.classNameForPanel}>
<div className="panel-body-inner">
{props.children}
</div>
</Panel>
</Col>
PTPanel.propTypes = {
header: PropTypes.element.isRequired,
children: PropTypes.element.isRequired,
classNameForPanel: PropTypes.string.isRequired,
className: PropTypes.string.isRequired,
};
export default PTPanel;
|
src/svg-icons/editor/format-strikethrough.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatStrikethrough = (props) => (
<SvgIcon {...props}>
<path d="M10 19h4v-3h-4v3zM5 4v3h5v3h4V7h5V4H5zM3 14h18v-2H3v2z"/>
</SvgIcon>
);
EditorFormatStrikethrough = pure(EditorFormatStrikethrough);
EditorFormatStrikethrough.displayName = 'EditorFormatStrikethrough';
EditorFormatStrikethrough.muiName = 'SvgIcon';
export default EditorFormatStrikethrough;
|
bai/src/components/WorkshopPageHeader/index.js | blackinai/blackinai.github.io | import { Container } from '@material-ui/core/';
import { withStyles } from '@material-ui/core/styles';
import PropTypes from 'prop-types';
import React from 'react';
const styles = (theme) => ({
root: {
flexGrow: 1
},
container: {
marginTop: theme.spacing(3),
marginBottom: theme.spacing(3),
display: 'flex',
position: 'relative',
},
item: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
padding: theme.spacing(0, 2),
},
image: {
height: 60,
},
title: {
marginTop: theme.spacing(3),
marginBottom: theme.spacing(3),
color: theme.palette.primary.light,
},
cardMedia: {
height: 300,
backgroundImage: 'url(image)',
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center',
color: theme.palette.common.white,
},
});
function WorkshopPageHeader(props) {
const { classes } = props;
const path_img = props.src;
return (
<div className={classes.root}>
<Container className={classes.cardMedia} style={{ backgroundImage: `url(${path_img})` }}>
{<img style={{ display: 'none' }} alt="" src={path_img} />}
</Container>
</div>
);
}
WorkshopPageHeader.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(WorkshopPageHeader);
|
src/packages/@ncigdc/modern_components/SampleType/SampleType.js | NCI-GDC/portal-ui | import React from 'react';
import { get } from 'lodash';
import GreyBox from '@ncigdc/uikit/GreyBox';
export default ({ repository, loading }) =>
loading ? (
<GreyBox style={{ width: '100px' }} />
) : (
get(
repository,
'cases.hits.edges[0].node.samples.hits.edges[0].node.sample_type',
'--',
)
);
|
src/ModalTitle.js | brynjagr/react-bootstrap | import React from 'react';
import classNames from 'classnames';
class ModalTitle extends React.Component {
render() {
return (
<h4
{...this.props}
className={classNames(this.props.className, this.props.modalClassName)}>
{ this.props.children }
</h4>
);
}
}
ModalTitle.propTypes = {
/**
* A css class applied to the Component
*/
modalClassName: React.PropTypes.string
};
ModalTitle.defaultProps = {
modalClassName: 'modal-title'
};
export default ModalTitle;
|
node_modules/react-bootstrap/es/CarouselItem.js | premcool/getmydeal | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import ReactDOM from 'react-dom';
import TransitionEvents from './utils/TransitionEvents';
// TODO: This should use a timeout instead of TransitionEvents, or else just
// not wait until transition end to trigger continuing animations.
var propTypes = {
direction: React.PropTypes.oneOf(['prev', 'next']),
onAnimateOutEnd: React.PropTypes.func,
active: React.PropTypes.bool,
animateIn: React.PropTypes.bool,
animateOut: React.PropTypes.bool,
index: React.PropTypes.number
};
var defaultProps = {
active: false,
animateIn: false,
animateOut: false
};
var CarouselItem = function (_React$Component) {
_inherits(CarouselItem, _React$Component);
function CarouselItem(props, context) {
_classCallCheck(this, CarouselItem);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleAnimateOutEnd = _this.handleAnimateOutEnd.bind(_this);
_this.state = {
direction: null
};
_this.isUnmounted = false;
return _this;
}
CarouselItem.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.props.active !== nextProps.active) {
this.setState({ direction: null });
}
};
CarouselItem.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
var _this2 = this;
var active = this.props.active;
var prevActive = prevProps.active;
if (!active && prevActive) {
TransitionEvents.addEndEventListener(ReactDOM.findDOMNode(this), this.handleAnimateOutEnd);
}
if (active !== prevActive) {
setTimeout(function () {
return _this2.startAnimation();
}, 20);
}
};
CarouselItem.prototype.componentWillUnmount = function componentWillUnmount() {
this.isUnmounted = true;
};
CarouselItem.prototype.handleAnimateOutEnd = function handleAnimateOutEnd() {
if (this.isUnmounted) {
return;
}
if (this.props.onAnimateOutEnd) {
this.props.onAnimateOutEnd(this.props.index);
}
};
CarouselItem.prototype.startAnimation = function startAnimation() {
if (this.isUnmounted) {
return;
}
this.setState({
direction: this.props.direction === 'prev' ? 'right' : 'left'
});
};
CarouselItem.prototype.render = function render() {
var _props = this.props,
direction = _props.direction,
active = _props.active,
animateIn = _props.animateIn,
animateOut = _props.animateOut,
className = _props.className,
props = _objectWithoutProperties(_props, ['direction', 'active', 'animateIn', 'animateOut', 'className']);
delete props.onAnimateOutEnd;
delete props.index;
var classes = {
item: true,
active: active && !animateIn || animateOut
};
if (direction && active && animateIn) {
classes[direction] = true;
}
if (this.state.direction && (animateIn || animateOut)) {
classes[this.state.direction] = true;
}
return React.createElement('div', _extends({}, props, {
className: classNames(className, classes)
}));
};
return CarouselItem;
}(React.Component);
CarouselItem.propTypes = propTypes;
CarouselItem.defaultProps = defaultProps;
export default CarouselItem; |
src/pages/index.js | MozillaDevelopers/playground | import React from 'react';
// components
import Hero from '../components/layout/Hero';
import DownloadWhite from '../components/DownloadWhite';
import TutorialList from '../components/TutorialList';
import DownloadLink from '../components/DownloadLink';
// photos
import logo from '../components/img/ff-logo.png';
const logoStyle = {
width: '80px',
};
const index = () => (
<div>
<Hero>
<img className="mb6" style={logoStyle} src={logo} alt="logo" />
<h1>Firefox DevTools Playground</h1>
<div className="container">
<div className="col-md-6 col-md-offset-3 mt3">
<p className="mb6">
Learn, build, improve, and create with Firefox DevTools.
</p>
<DownloadLink content="index-hero">
<DownloadWhite />
</DownloadLink>
</div>
</div>
</Hero>
<TutorialList />
</div>
);
export default index;
|
smsgw/static/js/app/app.react.js | VojtechBartos/smsgw | 'use strict';
import React from 'react';
import {RouteHandler} from 'react-router';
import {Map} from 'immutable';
import * as actions from '../users/actions';
import * as store from '../users/store';
import {flash} from '../flashMessages/actions';
import Component from '../components/component.react';
import Spinner from '../components/spinner.react';
import Wrapper from '../components/wrapper.react';
import Header from './header.react';
class App extends Component {
componentDidMount() {
// ask for currently logged in user
actions.getLoggedIn().catch((err) => {
flash(err.message, 'danger');
if (err.status === 401)
this.redirectWhenUnauthorized();
});
}
redirectWhenUnauthorized() {
actions.signOut();
this.props.router.transitionTo('signin');
}
render() {
const user = store.getLoggedIn();
if (actions.getLoggedIn.pending || !user)
return <Spinner fullscreen={true} />;
return (
<Wrapper>
<Header user={user} {...this.props} />
<RouteHandler user={user} {...this.props} />
</Wrapper>
);
}
}
App.propTypes = {
router: React.PropTypes.func,
pendingActions: React.PropTypes.instanceOf(Map).isRequired
};
export default App;
|
app/javascript/mastodon/features/ui/components/actions_modal.js | mimumemo/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import StatusContent from '../../../components/status_content';
import Avatar from '../../../components/avatar';
import RelativeTimestamp from '../../../components/relative_timestamp';
import DisplayName from '../../../components/display_name';
import IconButton from '../../../components/icon_button';
import classNames from 'classnames';
export default class ActionsModal extends ImmutablePureComponent {
static propTypes = {
status: ImmutablePropTypes.map,
actions: PropTypes.array,
onClick: PropTypes.func,
};
renderAction = (action, i) => {
if (action === null) {
return <li key={`sep-${i}`} className='dropdown-menu__separator' />;
}
const { icon = null, text, meta = null, active = false, href = '#' } = action;
return (
<li key={`${text}-${i}`}>
<a href={href} target='_blank' rel='noopener' onClick={this.props.onClick} data-index={i} className={classNames({ active })}>
{icon && <IconButton title={text} icon={icon} role='presentation' tabIndex='-1' inverted />}
<div>
<div className={classNames({ 'actions-modal__item-label': !!meta })}>{text}</div>
<div>{meta}</div>
</div>
</a>
</li>
);
}
render () {
const status = this.props.status && (
<div className='status light'>
<div className='boost-modal__status-header'>
<div className='boost-modal__status-time'>
<a href={this.props.status.get('url')} className='status__relative-time' target='_blank' rel='noopener'>
<RelativeTimestamp timestamp={this.props.status.get('created_at')} />
</a>
</div>
<a href={this.props.status.getIn(['account', 'url'])} className='status__display-name'>
<div className='status__avatar'>
<Avatar account={this.props.status.get('account')} size={48} />
</div>
<DisplayName account={this.props.status.get('account')} />
</a>
</div>
<StatusContent status={this.props.status} />
</div>
);
return (
<div className='modal-root__modal actions-modal'>
{status}
<ul>
{this.props.actions.map(this.renderAction)}
</ul>
</div>
);
}
}
|
plugins/react/frontend/components/common/DeleteConfirmationButtons/index.js | carteb/carte-blanche | /* eslint-disable max-len */
/**
* DeleteConfirmationButtons
*
* Shows buttons for delete confirmation
*/
import React from 'react';
import styles from './style.css';
class DeleteConfirmationButtons extends React.Component {
confirmDeleteVariation = (e) => {
e.preventDefault();
this.props.confirmDeleteVariation(this.props.variationPath);
}
cancelDeleteVariation = (e) => {
e.preventDefault();
this.props.cancelDeleteVariation(this.props.variationPath);
}
render() {
return (
<div>
<button onClick={this.confirmDeleteVariation} className={`${styles.base}`}>
Delete
</button>
<button onClick={this.cancelDeleteVariation} className={`${styles.base} `}>
Cancel
</button>
</div>
);
}
}
export default DeleteConfirmationButtons;
|
src/components/Footer/index.js | slightlytyler/bernie-tax-viz | import React, { Component } from 'react';
import cssModules from 'react-css-modules';
import hearticon from 'assets/hearticon.svg';
import twittericon from 'assets/twitter.svg';
import styles from './styles.styl';
@cssModules(styles, { allowMultiple: true, errorWhenNotFound: false })
export default class Footer extends Component {
render() {
return (
<footer styleName="footer">
<div styleName="container">
<section styleName="links special row">
<div styleName="inner">
<section styleName="border" />
<a href="https://vote.berniesanders.com/" styleName="link item">Vote</a>
<a href="https://go.berniesanders.com/page/content/contribute/" styleName="link item">Donate</a>
<a href="https://go.berniesanders.com/page/content/phonebank" styleName="link item">Phonebank</a>
</div>
</section>
<section styleName="links row">
<a href="http://taxfoundation.org/article/details-and-analysis-senator-bernie-sanders-s-tax-plan" styleName="link item">The analysis</a>
<a href="http://bernies-plan.dataviz.work" styleName="link item">What's next</a>
<a href="mailto:[email protected]" styleName="link item">Let's talk</a>
<a href="https://twitter.com/dataviz_work" styleName="link item"><img src={twittericon} styleName="twitter icon" />@dataviz_work</a>
</section>
<section styleName="credit row">
made with
<img src={hearticon} styleName="heart icon" />
by <a href="http://data-viz.work/" styleName="link">data-viz.work</a> & <a href="http://slightlytyler.com/" styleName="link">slightlytyler</a>
</section>
<section styleName="disclaimer row">
these are just like our thoughts man, not tax or legal advice
</section>
</div>
</footer>
);
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.