path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
HTML/前端/my-react-app-spring-boot-yao/src/hello.js | xiaoxiaoyao/MyApp | import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
); |
src/Parser/HolyPaladin/Modules/Items/Tier19_4set.js | mwwscott0/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import HIT_TYPES from 'Parser/Core/HIT_TYPES';
import Module from 'Parser/Core/Module';
import calculateEffectiveHealing from 'Parser/Core/calculateEffectiveHealing';
import Combatants from 'Parser/Core/Modules/Combatants';
const INFUSION_OF_LIGHT_BUFF_EXPIRATION_BUFFER = 150; // the buff expiration can occur several MS before the heal event is logged, this is the buffer time that an IoL charge may have dropped during which it will still be considered active.
const INFUSION_OF_LIGHT_BUFF_MINIMAL_ACTIVE_TIME = 200; // if someone heals with FoL and then immediately casts a HS race conditions may occur. This prevents that (although the buff is probably not applied before the FoL).
const INFUSION_OF_LIGHT_FOL_HEALING_INCREASE = 0.5;
const debug = false;
class Tier19_4set extends Module {
static dependencies = {
combatants: Combatants,
};
healing = 0;
totalIolProcsUsed = 0;
bonusIolProcsUsed = 0;
bonusIolProcsUsedOnFol = 0;
on_initialized() {
this.active = this.combatants.selected.hasBuff(SPELLS.HOLY_PALADIN_T19_4SET_BONUS_BUFF.id);
}
iolProcsUsedSinceLastHolyShock = 0;
on_byPlayer_heal(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.HOLY_SHOCK_HEAL.id) {
if (event.hitType === HIT_TYPES.CRIT) {
debug && console.log((event.timestamp - this.owner.fight.start_time) / 1000, 'Holy Shock crit!', event);
this.iolProcsUsedSinceLastHolyShock = 0;
}
}
if (spellId === SPELLS.FLASH_OF_LIGHT.id || spellId === SPELLS.HOLY_LIGHT.id) {
const hasIol = this.combatants.selected.getBuff(SPELLS.INFUSION_OF_LIGHT.id, event.timestamp, INFUSION_OF_LIGHT_BUFF_EXPIRATION_BUFFER, INFUSION_OF_LIGHT_BUFF_MINIMAL_ACTIVE_TIME);
if (hasIol) {
this.iolProcsUsedSinceLastHolyShock += 1;
debug && console.log((event.timestamp - this.owner.fight.start_time) / 1000, 'IoL', event.ability.name, this.iolProcsUsedSinceLastHolyShock, event);
this.totalIolProcsUsed += 1;
if (this.iolProcsUsedSinceLastHolyShock === 2) {
debug && console.log((event.timestamp - this.owner.fight.start_time) / 1000, 'Bonus IOL', event, event);
this.bonusIolProcsUsed += 1;
if (spellId === SPELLS.FLASH_OF_LIGHT.id) {
this.bonusIolProcsUsedOnFol += 1;
this.healing += calculateEffectiveHealing(event, INFUSION_OF_LIGHT_FOL_HEALING_INCREASE);
}
}
} else {
debug && console.log((event.timestamp - this.owner.fight.start_time) / 1000, 'Regular', event.ability.name, event);
}
}
}
on_byPlayer_damage(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.HOLY_SHOCK_DAMAGE.id) {
if (event.hitType === HIT_TYPES.CRIT) {
debug && console.log((event.timestamp - this.owner.fight.start_time) / 1000, 'Holy Shock crit!');
this.iolProcsUsedSinceLastHolyShock = 0;
}
}
}
on_beacon_heal(beaconTransferEvent, healEvent) {
const spellId = healEvent.ability.guid;
if (spellId !== SPELLS.FLASH_OF_LIGHT.id) {
return;
}
const combatant = this.combatants.players[healEvent.targetID];
if (!combatant) {
// If combatant doesn't exist it's probably a pet.
debug && console.log('Skipping beacon heal event since combatant couldn\'t be found:', beaconTransferEvent, 'for heal:', healEvent);
return;
}
const hasIol = this.combatants.selected.getBuff(SPELLS.INFUSION_OF_LIGHT.id, healEvent.timestamp, INFUSION_OF_LIGHT_BUFF_EXPIRATION_BUFFER, INFUSION_OF_LIGHT_BUFF_MINIMAL_ACTIVE_TIME);
if (!hasIol) {
return;
}
if (this.iolProcsUsedSinceLastHolyShock === 2) {
debug && console.log((beaconTransferEvent.timestamp - this.owner.fight.start_time) / 1000, 'Beacon transfer', beaconTransferEvent);
this.healing += calculateEffectiveHealing(beaconTransferEvent, INFUSION_OF_LIGHT_FOL_HEALING_INCREASE);
}
}
item() {
return {
id: `spell-${SPELLS.HOLY_PALADIN_T19_4SET_BONUS_BUFF.id}`,
icon: <SpellIcon id={SPELLS.HOLY_PALADIN_T19_4SET_BONUS_BUFF.id} />,
title: <SpellLink id={SPELLS.HOLY_PALADIN_T19_4SET_BONUS_BUFF.id} />,
result: (
<dfn data-tip={`The actual effective healing contributed by the tier 19 4 set bonus. <b>This does not include any healing "gained" from the Holy Light cast time reduction.</b> You used a total of ${this.totalIolProcsUsed} Infusion of Light procs, ${this.bonusIolProcsUsed} of those were from procs from the 4 set bonus and ${this.bonusIolProcsUsedOnFol} of those bonus procs were used on Flash of Light.`}>
{this.owner.formatItemHealingDone(this.healing)}
</dfn>
),
};
}
}
export default Tier19_4set;
|
src/containers/Editor.js | petercollingridge/math-for-programmers-prototype | import React, { Component } from 'react';
import PropTypes from 'prop-types';
// CodeMirror Imports
import CodeMirror from 'react-codemirror2';
import 'codemirror/mode/stex/stex';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/monokai.css';
class Editor extends Component {
constructor(props) {
super(props);
this.state = {
waiting: false,
timer: null
};
// Function Bindings
this.tabToSpaces = this.tabToSpaces.bind(this);
this.codeChange = this.codeChange.bind(this);
}
/*
Prevents uppdating the code too fast
for correct Preview rendering
*/
codeChange(cm, meta, code) {
const { updateCode } = this.props;
const { waiting, timer } = this.state;
const delay = 500;
if (waiting) {
clearTimeout(timer);
const newTimer = setTimeout(() => {
this.setState({
waiting: false
});
updateCode(code);
}, delay);
this.setState({
timer: newTimer
});
} else {
const newTimer = setTimeout(updateCode(code), delay);
this.setState({
waiting: true,
timer: newTimer
});
}
}
tabToSpaces(cm) {
const spaces = Array(cm.getOption('indentUnit') + 1).join(' ');
cm.replaceSelection(spaces);
}
render() {
const { code } = this.props;
const options = {
lineNumbers: true,
lineWrapping: true,
extraKeys: {
Tab: this.tabToSpaces
},
mode: 'stex',
tabSize: 2,
theme: 'monokai'
};
return (
<CodeMirror
editorDidMount={cm => cm.focus()}
onValueChange={this.codeChange}
onValueSet={cm => {
// Prevent First line from being edited
cm.markText(
{ line: 0, ch: 0 },
{ line: 1, ch: 0 },
{
atomic: true,
inclusiveLeft: true,
readOnly: true
}
);
// Prevent Last line from being edited
const lastLine = cm.lineCount() - 1;
cm.markText(
{ line: lastLine, ch: 0 },
{ line: lastLine },
{
atomic: true,
inclusiveLeft: true,
inclusiveRight: true,
readOnly: true
}
);
}}
options={options}
value={code}
/>
);
}
}
Editor.propTypes = {
code: PropTypes.string.isRequired,
updateCode: PropTypes.func.isRequired
};
export default Editor;
|
src/components/Scenario.js | kalpetros/hawkpass | import PropTypes from 'prop-types';
import React from 'react';
import { Panel } from './Panel';
export const Scenario = props => {
const { per_second, per_minute, per_hour, per_day, per_year } = props.values;
return (
<div className="grid grid-cols-2 sm:grid-cols-5 gap-4">
<Panel>
<div className="text-xl font-semibold truncate">{per_second}</div>
<div className="truncate">seconds</div>
</Panel>
<Panel>
<div className="text-xl font-semibold truncate">{per_minute}</div>
<div className="truncate">minutes</div>
</Panel>
<Panel>
<div className="text-xl font-semibold truncate">{per_hour}</div>
<div className="truncate">hours</div>
</Panel>
<Panel>
<div className="text-xl font-semibold truncate">{per_day}</div>
<div className="truncate">days</div>
</Panel>
<Panel>
<div className="text-xl font-semibold truncate">{per_year}</div>
<div className="truncate">years</div>
</Panel>
</div>
);
};
Scenario.defaultProps = {
values: {
per_second: '-',
per_minute: '-',
per_hour: '-',
per_day: '-',
per_year: '-',
},
};
Scenario.propTypes = {
values: PropTypes.object.isRequired,
};
|
ui/src/app/components/Types.js | kuppuswamy/foodie | import React from 'react';
import AddTypeMutation from '../mutations/AddTypeMutation';
import EditTypeMutation from '../mutations/EditTypeMutation';
import DeleteTypeMutation from '../mutations/DeleteTypeMutation';
export default class Types extends React.Component {
state = {
text: '',
editID: null,
showModal: false
};
_handleChange = (e) => {
this.setState({text: e.target.value});
};
_onAdd = () => {
if (this.state.text.trim() !== '') {
AddTypeMutation.commit(this.props.relay.environment, this.state.text);
}
this.setState({text: '', showModal: false});
};
_onEdit = (type) => {
this.setState({text: type.name, editID: type.id, showModal: true}, () => this.typeName.focus());
};
_onCancel = () => {
this.setState({text: '', editID: null, showModal: false});
};
_onSave = () => {
let type = {name: this.state.text, id: this.state.editID};
this.setState({text: '', editID: null, showModal: false});
EditTypeMutation.commit(this.props.relay.environment, type);
};
_onDelete = (type) => {
DeleteTypeMutation.commit(this.props.relay.environment, type);
};
_showModal = () => {
this.setState({showModal: true}, () => this.typeName.focus());
};
_onEnter = e => {
if (e.keyCode === 13) {
if (this.state.editID) this._onSave(); else this._onAdd();
}
};
render = () => {
let {types} = this.props;
return (
<div>
<div className={`modal ${this.state.showModal ? 'is-active' : ''}`}>
<div className="modal-background" onClick={e => this._onCancel()}/>
<div className="modal-card">
<header className="modal-card-head">
<p className="modal-card-title">{this.state.editID ? 'Edit' : 'Add'} type</p>
<button className="delete" aria-label="close" onClick={e => this._onCancel()}/>
</header>
<section className="modal-card-body">
<div className="field">
<p className="control is-expanded">
<input ref={n => this.typeName = n} className="input" type="text" placeholder="Name"
value={this.state.text} onChange={this._handleChange} onKeyDown={e => this._onEnter(e)}/>
</p>
</div>
</section>
<footer className="modal-card-foot">
{
this.state.editID ? (
<button className="button is-primary" onClick={e => this._onSave()}>Save</button>
) : (
<button className="button is-primary" onClick={e => this._onAdd()}>Add</button>
)
}
<button className="button" onClick={e => this._onCancel()}>Cancel</button>
</footer>
</div>
</div>
<h1 className="title">Types</h1>
<div className="field">
<p className="control">
<a className="button is-warning" onClick={e => this._showModal()}>Add</a>
</p>
</div>
{
types.edges.length ?
types.edges.map((type, key) => (
<div className="field card" key={type.node.id}>
<div className="card-content">
<p className="subtitle is-4">
{type.node.name}{' - #'}{type.node.id}
</p>
</div>
<footer className="card-footer">
<a className="card-footer-item" onClick={e => this._onEdit(type.node)}>Edit</a>
<a className="card-footer-item" onClick={e => this._onDelete(type.node)}>Delete</a>
</footer>
</div>
)) : (
<div className="field card has-text-centered">
<div className="card-content">
<p className="subtitle is-4">
<i>Add a type<br/>of food.</i>
</p>
</div>
</div>
)
}
</div>
);
}
} |
src/components/Sidebar/SelectMessage.js | vogelino/design-timeline | import React from 'react';
export default () => (
<div className="sidebar_selectMessage">
Please select an item to view its content
</div>
);
|
src/js/components/members/newMemberForm.js | jrnail23/sitterswap-ui | import React from 'react'
import Input from '../common/textInput'
import {Link} from 'react-router'
export default class extends React.Component {
static propTypes = {
member: React.PropTypes.shape({
firstName: React.PropTypes.string.isRequired,
lastName: React.PropTypes.string.isRequired,
emailAddress: React.PropTypes.string.isRequired
}).isRequired,
onChange: React.PropTypes.func.isRequired,
onSave: React.PropTypes.func.isRequired,
errors: React.PropTypes.object
}
render () {
return (
<div>
<form>
<Input name='firstName'
label='First Name'
value={this.props.member.firstName}
onChange={this.props.onChange}
error={this.props.errors.firstName} />
<Input name='lastName'
label='Last Name'
value={this.props.member.lastName}
onChange={this.props.onChange}
error={this.props.errors.lastName} />
<Input name='emailAddress'
label='Email Address'
value={this.props.member.emailAddress}
onChange={this.props.onChange}
error={this.props.errors.emailAddress} />
<Link to='/members' className='btn btn-default'>Cancel</Link>
<input type='submit'
value='Save'
className='btn btn-primary'
onClick={this.props.onSave} />
</form>
</div>
)
}
}
|
src/utils/griddleConnect.js | GriddleGriddle/Griddle | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
/// This method appends options onto existing connect parameters
export const mergeConnectParametersWithOptions = (
originalConnect,
newOptions
) => {
const [
mapStateFromProps,
mapDispatchFromProps,
mergeProps,
options
] = originalConnect;
return [
mapStateFromProps,
mapDispatchFromProps,
mergeProps,
{ ...options, ...newOptions }
];
};
const griddleConnect = (...connectOptions) => OriginalComponent =>
class extends React.Component {
static contextTypes = {
storeKey: PropTypes.string
};
constructor(props, context) {
super(props, context);
const newOptions = mergeConnectParametersWithOptions(connectOptions, {
storeKey: context.storeKey
});
this.ConnectedComponent = connect(...newOptions)(OriginalComponent);
}
render() {
return <this.ConnectedComponent {...this.props} />;
}
};
export { griddleConnect as connect };
|
spec/javascripts/jsx/grading/CourseTabContainerSpec.js | djbender/canvas-lms | /*
* Copyright (C) 2017 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import {mount} from 'enzyme'
import $ from 'jquery'
import _ from 'underscore'
import CourseTabContainer from 'jsx/grading/CourseTabContainer'
import 'jqueryui/tabs'
QUnit.module('CourseTabContainer', {
renderComponent(props = {}) {
const defaults = {}
const mergedProps = _.defaults(props, defaults)
this.wrapper = mount(React.createElement(CourseTabContainer, mergedProps))
},
setup() {
sandbox.stub($, 'getJSON').returns({success: () => ({error: () => {}}), done: () => {}})
},
teardown() {
this.wrapper.unmount()
}
})
test('tabs are present when there are grading periods', function() {
this.renderComponent({hasGradingPeriods: true})
const $el = this.wrapper.getDOMNode()
strictEqual($el.querySelectorAll('.ui-tabs').length, 1)
strictEqual($el.querySelectorAll('.ui-tabs ul.ui-tabs-nav li').length, 2)
equal($el.querySelector('#grading-periods-tab').getAttribute('style'), 'display: block;')
equal($el.querySelector('#grading-standards-tab').getAttribute('style'), 'display: none;')
})
test('tabs are not present when there are no grading periods', function() {
this.renderComponent({hasGradingPeriods: false})
equal(this.wrapper.find('.ui-tabs').length, 0)
})
test('jquery-ui tabs() is called when there are grading periods', function() {
const tabsSpy = sandbox.spy($.fn, 'tabs')
this.renderComponent({hasGradingPeriods: true})
ok(tabsSpy.calledOnce)
})
test('jquery-ui tabs() is not called when there are no grading periods', function() {
const tabsSpy = sandbox.spy($.fn, 'tabs')
this.renderComponent({hasGradingPeriods: false})
notOk(tabsSpy.called)
})
test('does not render grading periods if there are no grading periods', function() {
this.renderComponent({hasGradingPeriods: false})
notOk(this.wrapper.instance().gradingPeriods)
})
test('renders the grading periods if there are grading periods', function() {
this.renderComponent({hasGradingPeriods: true})
ok(this.wrapper.instance().gradingPeriods)
})
test('renders the grading standards if there are no grading periods', function() {
this.renderComponent({hasGradingPeriods: false})
ok(this.wrapper.instance().gradingStandards)
})
test('renders the grading standards if there are grading periods', function() {
this.renderComponent({hasGradingPeriods: true})
ok(this.wrapper.instance().gradingStandards)
})
|
src/renderer/components/app-wrapper.js | sirbrillig/gitnews-menubar | import PropTypes from 'prop-types';
import { ipcRenderer } from 'electron';
import React from 'react';
import { connect } from 'react-redux';
import {
markAllNotesSeen,
scrollToTop,
markAppHidden,
markAppShown,
} from 'common/lib/reducer';
class AppWrapper extends React.Component {
constructor(props) {
super(props);
ipcRenderer.on('hide-app', () => {
this.props.markAppHidden();
});
ipcRenderer.on('show-app', () => {
this.props.markAppShown();
});
ipcRenderer.on('menubar-click', () => {
this.props.markAllNotesSeen();
this.props.scrollToTop();
});
}
render() {
return this.props.children;
}
}
AppWrapper.propTypes = {
// Functions
quitApp: PropTypes.func.isRequired,
// All following are provided by connect
markAllNotesSeen: PropTypes.func.isRequired,
scrollToTop: PropTypes.func.isRequired,
// Values
version: PropTypes.string.isRequired,
};
const actions = {
markAllNotesSeen,
scrollToTop,
markAppHidden,
markAppShown,
};
export default connect(null, actions)(AppWrapper);
|
fields/types/color/ColorField.js | suryagh/keystone | import ColorPicker from 'react-color';
import Field from '../Field';
import React from 'react';
import { FormInput, InputGroup } from 'elemental';
const PICKER_TYPES = ['chrome', 'compact', 'material', 'photoshop', 'sketch', 'slider', 'swatches'];
const TRANSPARENT_BG
= `<svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g fill="#CCCCCC">
<path d="M0,0 L8,0 L8,8 L0,8 L0,0 Z M8,8 L16,8 L16,16 L8,16 L8,8 Z M0,16 L8,16 L8,24 L0,24 L0,16 Z M16,0 L24,0 L24,8 L16,8 L16,0 Z M16,16 L24,16 L24,24 L16,24 L16,16 Z" />
</g>
</svg>`;
module.exports = Field.create({
displayName: 'ColorField',
propTypes: {
onChange: React.PropTypes.func,
path: React.PropTypes.string,
pickerType: React.PropTypes.oneOf(PICKER_TYPES),
value: React.PropTypes.string,
},
getInitialState () {
return {
displayColorPicker: false,
};
},
getDefaultProps () {
return {
pickerType: 'sketch',
};
},
updateValue (value) {
this.props.onChange({
path: this.props.path,
value: value,
});
},
handleInputChange (event) {
var newValue = event.target.value;
if (/^([0-9A-F]{3}){1,2}$/.test(newValue)) {
newValue = '#' + newValue;
}
if (newValue === this.props.value) return;
this.updateValue(newValue);
},
handleClick () {
this.setState({ displayColorPicker: !this.state.displayColorPicker });
},
handleClose () {
this.setState({ displayColorPicker: false });
},
handlePickerChange (color) {
var newValue = '#' + color.hex;
if (newValue === this.props.value) return;
this.updateValue(newValue);
},
renderSwatch () {
return (this.props.value) ? (
<span className="field-type-color__swatch" style={{ backgroundColor: this.props.value }} />
) : (
<span className="field-type-color__swatch" dangerouslySetInnerHTML={{ __html: TRANSPARENT_BG }} />
);
},
renderField () {
return (
<div className="field-type-color__wrapper">
<InputGroup>
<InputGroup.Section grow>
<FormInput ref="field" onChange={this.valueChanged} name={this.props.path} value={this.props.value} autoComplete="off" />
</InputGroup.Section>
<InputGroup.Section>
<button type="button" onClick={this.handleClick} className="FormInput FormSelect field-type-color__button">
{this.renderSwatch()}
</button>
</InputGroup.Section>
</InputGroup>
<div className="field-type-color__picker">
<ColorPicker
color={this.props.value}
display={this.state.displayColorPicker}
onChangeComplete={this.handlePickerChange}
onClose={this.handleClose}
position={window.innerWidth > 480 ? 'right' : 'below'}
type={this.props.pickerType}
/>
</div>
</div>
);
},
});
|
packages/ringcentral-widgets/components/IncomingCallPad/index.js | u9520107/ringcentral-js-widget | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Tooltip from 'rc-tooltip';
import 'rc-tooltip/assets/bootstrap_white.css';
import ForwardForm from '../ForwardForm';
import ReplyWithMessage from '../ReplyWithMessage';
import ActiveCallButton from '../ActiveCallButton';
import MultiCallAnswerButton from '../MultiCallAnswerButton';
import MessageIcon from '../../assets/images/MessageFill.svg';
import ForwardIcon from '../../assets/images/Forward.svg';
import IgnoreIcon from '../../assets/images/Ignore.svg';
import VoicemailIcon from '../../assets/images/Voicemail.svg';
import AnswerIcon from '../../assets/images/Answer.svg';
import styles from './styles.scss';
import i18n from './i18n';
export default class IncomingCallPad extends Component {
constructor(props) {
super(props);
this.state = {
showForward: false,
replyMessage: null,
showReplyWithMessage: false,
toVoiceMailEnabled: true,
replyMessageEnabled: true,
};
this.onShowForwardChange = (visible) => {
this.setState({
showForward: visible,
});
};
this.closeForwardForm = () => {
this.onShowForwardChange(false);
};
this.onShowReplyWithMessageChange = (visible) => {
this.setState({
showReplyWithMessage: visible,
});
};
this.onReplyMessageChange = (message) => {
this.setState({ replyMessage: message });
};
this.closeReplyWithMessage = () => {
this.onShowReplyWithMessageChange(false);
};
this.toVoiceMail = () => {
this.props.toVoiceMail();
if (this.props.toVoiceMail) {
this.setState({
toVoiceMailEnabled: false
});
this.voicemailTimeout = setTimeout(() => {
this.props.reject();
}, 3000);
}
};
this.replyWithMessage = (value) => {
this.props.replyWithMessage(value);
if (this.props.replyWithMessage) {
this.setState({
replyMessageEnabled: false
});
this.replyTimeout = setTimeout(() => {
this.props.reject();
}, 3000);
}
};
}
componentWillReceiveProps(newProps) {
if (this.props.sessionId !== newProps.sessionId) {
if (this.replyTimeout) {
clearTimeout(this.replyTimeout);
this.replyTimeout = null;
}
if (this.voicemailTimeout) {
clearTimeout(this.voicemailTimeout);
this.voicemailTimeout = null;
}
}
}
componentWillUnmount() {
if (this.replyTimeout) {
clearTimeout(this.replyTimeout);
this.replyTimeout = null;
}
if (this.voicemailTimeout) {
clearTimeout(this.voicemailTimeout);
this.voicemailTimeout = null;
}
}
render() {
const {
currentLocale,
reject,
answer,
forwardingNumbers,
formatPhone,
className,
hasOtherActiveCall,
answerAndEnd,
answerAndHold,
} = this.props;
// const isMultiCall = true;
const multiCallButtons = (
<div className={classnames(styles.buttonRow, styles.multiCallsButtonGroup)}>
<MultiCallAnswerButton
onClick={answerAndEnd}
title={i18n.getString('answerAndEnd', currentLocale)}
className={styles.callButton}
isEndOtherCall
/>
<ActiveCallButton
onClick={this.toVoiceMail}
title={i18n.getString('toVoicemail', currentLocale)}
buttonClassName={this.state.toVoiceMailEnabled ? styles.voiceMailButton : ''}
icon={VoicemailIcon}
iconWidth={274}
iconX={116}
showBorder={!this.state.toVoiceMailEnabled}
className={styles.callButton}
disabled={!this.state.toVoiceMailEnabled}
/>
<MultiCallAnswerButton
onClick={answerAndHold}
title={i18n.getString('answerAndHold', currentLocale)}
className={styles.callButton}
isEndOtherCall={false}
/>
</div>
);
const singleCallButtons = (
<div className={classnames(styles.buttonRow, styles.answerButtonGroup)}>
<ActiveCallButton
onClick={this.toVoiceMail}
title={i18n.getString('toVoicemail', currentLocale)}
buttonClassName={this.state.toVoiceMailEnabled ? styles.voiceMailButton : ''}
icon={VoicemailIcon}
iconWidth={274}
iconX={116}
showBorder={!this.state.toVoiceMailEnabled}
className={styles.bigCallButton}
disabled={!this.state.toVoiceMailEnabled}
/>
<ActiveCallButton
onClick={answer}
title={i18n.getString('answer', currentLocale)}
buttonClassName={styles.answerButton}
icon={AnswerIcon}
showBorder={false}
className={styles.bigCallButton}
/>
</div>
);
return (
<div className={classnames(styles.root, className)}>
<div
className={styles.forwardContainner}
ref={(containner) => {
this.forwardContainner = containner;
}}
/>
<div
className={styles.replyWithMessageContainner}
ref={(containner) => {
this.replyWithMessageContainner = containner;
}}
/>
<div className={styles.buttonRow}>
<Tooltip
defaultVisible={false}
visible={this.state.showForward}
onVisibleChange={this.onShowForwardChange}
placement="topRight"
trigger="click"
arrowContent={<div className="rc-tooltip-arrow-inner" />}
getTooltipContainer={() => this.forwardContainner}
overlay={
<ForwardForm
forwardingNumbers={forwardingNumbers}
currentLocale={currentLocale}
onCancel={this.closeForwardForm}
formatPhone={formatPhone}
onForward={this.props.onForward}
searchContact={this.props.searchContact}
searchContactList={this.props.searchContactList}
phoneTypeRenderer={this.props.phoneTypeRenderer}
/>
}
>
<ActiveCallButton
icon={ForwardIcon}
iconWidth={250}
iconX={125}
onClick={() => null}
title={i18n.getString('forward', currentLocale)}
className={styles.callButton}
/>
</Tooltip>
<Tooltip
defaultVisible={false}
visible={this.state.showReplyWithMessage}
onVisibleChange={this.onShowReplyWithMessageChange}
placement="top"
trigger="click"
arrowContent={<div className="rc-tooltip-arrow-inner" />}
getTooltipContainer={() => this.replyWithMessageContainner}
overlay={
<ReplyWithMessage
currentLocale={currentLocale}
onCancel={this.closeReplyWithMessage}
value={this.state.replyMessage}
onChange={this.onReplyMessageChange}
onReply={this.replyWithMessage}
disabled={!this.state.replyMessageEnabled}
/>
}
>
<ActiveCallButton
onClick={() => null}
icon={MessageIcon}
title={i18n.getString('reply', currentLocale)}
className={styles.callButton}
/>
</Tooltip>
<ActiveCallButton
onClick={reject}
icon={IgnoreIcon}
title={i18n.getString('ignore', currentLocale)}
className={styles.callButton}
/>
</div>
{hasOtherActiveCall ? multiCallButtons : singleCallButtons}
</div>
);
}
}
IncomingCallPad.propTypes = {
answer: PropTypes.func.isRequired,
reject: PropTypes.func.isRequired,
toVoiceMail: PropTypes.func.isRequired,
currentLocale: PropTypes.string.isRequired,
forwardingNumbers: PropTypes.array.isRequired,
formatPhone: PropTypes.func,
onForward: PropTypes.func.isRequired,
replyWithMessage: PropTypes.func.isRequired,
className: PropTypes.string,
answerAndEnd: PropTypes.func,
answerAndHold: PropTypes.func,
hasOtherActiveCall: PropTypes.bool,
sessionId: PropTypes.string.isRequired,
searchContactList: PropTypes.array.isRequired,
searchContact: PropTypes.func.isRequired,
phoneTypeRenderer: PropTypes.func,
};
IncomingCallPad.defaultProps = {
formatPhone: phone => phone,
className: null,
answerAndEnd: () => null,
answerAndHold: () => null,
hasOtherActiveCall: false,
phoneTypeRenderer: undefined,
};
|
website/src/index.js | chrisl8/ArloBot | import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.css';
import './index.css';
import App from './containers/App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root'),
);
|
components/Messenger/Messenger.js | tbescherer/TrumpAnxietyHotline | import React from 'react';
import store from '../../core/store.js';
import {keycodes} from './constants.js';
class Messenger extends React.Component {
constructor(props) {
super(props);
this.post = this.post.bind(this);
this.changeBlogText = this.changeBlogText.bind(this);
this.renderPosts = this.renderPosts.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.postAdminMessage = this.postAdminMessage.bind(this);
this.state = {
alone: true,
user_id: "",
posts: [],
blogText: "",
error: "",
conversationID: ""
}
}
startConversationAndListen = () => {
let conversationRef = firebase.database().ref('conversations');
let that = this;
var newConvoKey = conversationRef.push().key;
conversationRef.transaction(function(conversation) {
if (conversation === null) {
let update = {};
update['open_conversation'] = newConvoKey;
update[newConvoKey] = {};
return update;
} else if (conversation.open_conversation && conversation[conversation.open_conversation]["participant1"]["id"] !== firebase.auth().currentUser.uid) {
console.log("no second participant");
newConvoKey = conversation.open_conversation;
let now = new Date();
let participantData = {
'id': firebase.auth().currentUser.uid,
'connected_datetime': now.toTimeString()
}
that.setState({'alone': false});
conversation[newConvoKey]["participant2"] = participantData;
conversation = that.postAdminMessage(conversation, newConvoKey, "Second participant connected at " + now.toTimeString())
conversation = that.postAdminMessage(conversation, newConvoKey, "OK, you're both here, let it all out!")
conversation['open_conversation'] = false;
return conversation;
} else {
conversation['open_conversation'] = newConvoKey;
let now = new Date();
let participantData = {
'id': firebase.auth().currentUser.uid,
'connected_datetime': now.toDateString()
}
conversation[newConvoKey] = {
'participant1': participantData
};
conversation = that.postAdminMessage(conversation, newConvoKey, "First participant connected at " + now.toTimeString())
conversation = that.postAdminMessage(conversation, newConvoKey, "Waiting for a second participant...")
var participantRef = firebase.database().ref('conversations/' + newConvoKey + '/participant2').limitToLast(1);
participantRef.on('value', function(data){
console.log(data.val());
if (data.val() !== null) {
that.setState({'alone': false})
}
})
return conversation;
}
}, function(error, committed, snapshot){
that.setState({conversationID: newConvoKey});
var recentPostsRef = firebase.database().ref('conversations/' + newConvoKey + '/posts').limitToLast(100);
recentPostsRef.on('child_added', function(data){
store.dispatch({type:'ADD_POST', data: {'posts': data.val()}});
});
recentPostsRef.on('child_removed', function(data){
store.dispatch({type:'DELETE_POST', data: {'posts': data.val()}});
});
});
};
postAdminMessage(conversationsRef, conversationID, postBody) {
let now = new Date();
let newPostKey = firebase.database().ref().child('conversations').push().key;
let postData = {};
let existingConvo = conversationsRef[conversationID];
let postInfo = {
'text': postBody,
'user_id': 'admin',
'post_datetime': now.toDateString(),
}
let existingPosts = existingConvo["posts"] || {};
existingPosts[newPostKey] = postInfo;
existingConvo["posts"] = existingPosts;
conversationsRef[conversationID] = existingConvo;
return conversationsRef;
}
componentWillMount() {
let that = this;
that.startConversationAndListen();
firebase.auth().signInAnonymously().catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
});
that.context.store.subscribe(function() {
let state = that.context.store.getState();
that.setState({posts: state.posts});
});
}
post() {
let newPostKey = firebase.database().ref().child('conversations').push().key;
let update = {}
let that = this;
let now = new Date();
console.log(firebase.auth().currentUser.uid);
let postData = {
'text': this.state.blogText,
'user_id': firebase.auth().currentUser.uid,
'post_datetime': now.toDateString(),
}
update['/conversations/' + this.state.conversationID + "/posts/" + newPostKey] = postData;
firebase.database().ref().update(update).then(function() {
that.setState({blogText: ""});
}).catch((e) => {
that.setState({error: true});
});
}
startOrJoinConversation() {
let newConversationKey = firebase.database().ref.child('conversations')
}
deletePost() {
console.log("should delete here");
}
changeBlogText(event) {
this.setState({blogText: event.target.value})
}
renderPosts() {
let posts = this.state.posts.map(function(post) {
let isCurrentUser = (firebase.auth().currentUser && post.user_id === firebase.auth().currentUser.uid);
return (
<div key={post.text} style={{marginLeft: '10px'}}>
{isCurrentUser ? "You" : (post.user_id == "admin" ? "Admin" : "Anonymous Ally")}: {post.text}
</div>
)
})
let style;
if (this.state.alone) {
style = {}
} else {
style = {background: '#4CAF50'}
}
return (
<div style={{width: '90%', display: 'block', position: 'relative', margin: 'auto', marginTop: '10px', paddingBottom: '10px'}} className="mdl-card mdl-shadow--2dp">
<div className="mdl-card__title" style={{fontSize: '24px', background: '#CFD8DC'}}>
Your Shared Anxiety
<div
className="mdl-button mdl-js-button mdl-button--fab mdl-button--colored"
style={Object.assign({cursor: 'default', marginRight: '0px'}, style)}
/>
</div>
<div className="mdl-card__supporting-text" style={{height: '400px', overflowY: 'scroll', width: '100%', padding: '0px'}}>
{posts}
</div>
{this.renderPostArea()}
</div>
)
}
handleKeyDown (e) {
var that = this;
if (e.keyCode == keycodes.ENTER) {
that.post();
} else {
console.log(e)
}
}
renderPostArea() {
return (
<div style={{paddingLeft: '20px', paddingRight: '20px'}}>
<div className="mdl-textfield mdl-js-textfield" style={{width: '100%'}}>
<input onChange={this.changeBlogText} placeholder="Enter your message..." onKeyDown={this.handleKeyDown} value={this.state.blogText} className="mdl-textfield__input" type="text" id="sample1"/>
</div>
{(this.state.error ? <div>Must be logged in</div> : null)}
</div>
)
}
render() {
return (
<div>
{this.renderPosts()}
</div>
)
}
}
Messenger.contextTypes = {
store: React.PropTypes.object
};
export default Messenger;
|
src/components/molecules/Loading/index.js | SIB-Colombia/biodiversity_catalogue_v2_frontend | import React from 'react';
import styled from 'styled-components';
import {Link} from 'components';
import RefreshIndicator from 'material-ui/RefreshIndicator';
import CircularProgress from 'material-ui/CircularProgress';
const Wrapper = styled.div `
text-align: center;
padding: 40px 20px;
.text{
color:#555;
font-size: 12px;
padding-top: 10px;
font-weight: lighter;
}
`
class Loading extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<Wrapper className="animated fadeInUp">
<CircularProgress size={30} thickness={3} color={'#EF7748'}/>
{this.props.text && <div className="text">{this.props.text}</div>}
</Wrapper>
)
}
}
export default Loading;
|
actor-apps/app-web/src/app/components/dialog/TypingSection.react.js | fhchina/actor-platform | import React from 'react';
import { PureRenderMixin } from 'react/addons';
import classNames from 'classnames';
import DialogStore from 'stores/DialogStore';
export default React.createClass({
mixins: [PureRenderMixin],
getInitialState() {
return {
typing: null,
show: false
};
},
componentDidMount() {
DialogStore.addTypingListener(this.onTypingChange);
},
componentWillUnmount() {
DialogStore.removeTypingListener(this.onTypingChange);
},
onTypingChange() {
const typing = DialogStore.getSelectedDialogTyping();
if (typing === null) {
this.setState({show: false});
} else {
this.setState({typing: typing, show: true});
}
},
render() {
const typing = this.state.typing;
const show = this.state.show;
const typingClassName = classNames('typing', {
'typing--hidden': show === false
});
return (
<div className={typingClassName}>
<div className="typing-indicator"><i></i><i></i><i></i></div>
<span>{typing}</span>
</div>
);
}
});
|
src/routes/admin/index.js | ADourgarian/Syscoin-Payroll | /**
* 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 React from 'react';
import Layout from '../../components/Layout';
const title = 'Admin Page';
const isAdmin = false;
export default {
path: '/admin',
async action() {
if (!isAdmin) {
return { redirect: '/login' };
}
const Admin = await require.ensure([], require => require('./Admin').default, 'admin');
return {
title,
chunk: 'admin',
component: <Layout><Admin title={title} /></Layout>,
};
},
};
|
src/components/profile/Profile.js | n8e/melange | import React from 'react';
import PropTypes from 'prop-types';
import './Profile.css';
const Profile = ({ name, nameColor, textColor, profile, handleClick, handleChange }) => (
<div className="profile-card">
<h3>Profile</h3>
<div className="profile-entry">
<strong style={{ marginRight: '10px' }}>User Name:</strong>
<input name="name" type="text" value={name || ''} placeholder="user name" className="profile-input" onChange={handleChange} />
</div>
<div className="profile-entry">
<strong style={{ marginRight: '10px' }}>Email:</strong>
<input name="email" type="text" value={profile.email || ''} placeholder="email" disabled className="profile-input" onChange={handleChange} />
</div>
<div className="profile-entry">
<strong style={{ marginRight: '10px' }}>Name Color:</strong>
<input name="nameColor" type="text" value={nameColor || ''} placeholder="name color" className="profile-input" onChange={handleChange} />
</div>
<div className="profile-entry">
<strong style={{ marginRight: '10px' }}>Text Color:</strong>
<input name="textColor" type="text" value={textColor || ''} placeholder="text color" className="profile-input" onChange={handleChange} />
</div>
<div className="profile-entry">
<button className="edit-button" onClick={handleClick}>Update Profile</button>
</div>
</div>
);
Profile.propTypes = {
profile: PropTypes.shape({
email: PropTypes.string,
}).isRequired,
name: PropTypes.string.isRequired,
nameColor: PropTypes.string.isRequired,
textColor: PropTypes.string.isRequired,
handleClick: PropTypes.func.isRequired,
handleChange: PropTypes.func.isRequired,
};
export default Profile;
|
src/components/field_group.js | b0ts/react-redux-sweetlightstudios-website | import React from 'react';
import { FormGroup, ControlLabel, FormControl, HelpBlock } from 'react-bootstrap';
const FieldGroup = ({ id, label, help, ...props }) => (
<FormGroup controlId={id}>
<ControlLabel>{label}</ControlLabel>
<FormControl {...props} />
{help && <HelpBlock>{help}</HelpBlock>}
</FormGroup>
);
export default FieldGroup;
|
src/svg-icons/editor/insert-invitation.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorInsertInvitation = (props) => (
<SvgIcon {...props}>
<path d="M17 12h-5v5h5v-5zM16 1v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2h-1V1h-2zm3 18H5V8h14v11z"/>
</SvgIcon>
);
EditorInsertInvitation = pure(EditorInsertInvitation);
EditorInsertInvitation.displayName = 'EditorInsertInvitation';
EditorInsertInvitation.muiName = 'SvgIcon';
export default EditorInsertInvitation;
|
react/CrossIcon/CrossIcon.sketch.js | seek-oss/seek-style-guide | import React from 'react';
import CrossIcon from './CrossIcon';
import generateSketchIconSizes from '../private/generateSketchIconSizes';
export const symbols = {
...generateSketchIconSizes('Cross', <CrossIcon />)
};
|
src/client/client-views/org.js | davidbstein/moderator | import React from 'react'
import {connect} from 'react-redux'
import API from '../client-model/API'
import EventCard from './event-card'
export default connect(
storeState => storeState,
dispatch => ({API: new API(dispatch)})
)(
class Org extends React.Component {
constructor(props) {
super(props);
}
render() {
const o = this.props.state.org;
return <div className="org">
<div className="page-header">
<div className="page-header-container">
<div className="org-title page-title">
<a href="/"> {o.title || o.domain} Moderator </a>
</div>
<div className="logout-button"><a href="/logout">logout</a></div>
</div>
</div>
<div className="underheader" />
<div className="org-event-list">
{
Object.values(this.props.state.event_lookup).sort(
(a, b) => b.id - a.id
).map(
(e) => {
console.log(e);
return <EventCard key={e.id} event={e} />
}
)
}
</div>
<div className="new-event-link-container">
<p>
<a href="/new_event">
Click here to create a new event.
</a>
</p>
<p> More information on moderator <a href="/about"> here </a></p>
</div>
</div>
}
}
);
|
router_tutorial/07-more-nesting/modules/Repo.js | Muzietto/react-playground | import React from 'react';
export default React.createClass({
render() {
return (
<div>
<h3>link of Repos remains active because Repo is nested in Repos and Repos is nested in /</h3>
<h6>here under comes the repo name</h6>
<h4>{this.props.params.repoName}</h4>
<h6>here under comes the user name</h6>
<h4>{this.props.params.userName}</h4>
</div>
);
}
}); |
renderer/components/Icon/ConnectOnboarding.js | LN-Zap/zap-desktop | import React from 'react'
const SvgConnectOnboarding = props => (
<svg height="1em" viewBox="0 0 96 62" width="1em" {...props}>
<g fill="none" fillRule="evenodd" stroke="currentColor">
<circle cx={30} cy={30} r={30} transform="translate(1 1)" />
<circle cx={30} cy={30} r={30} transform="translate(35 1)" />
</g>
</svg>
)
export default SvgConnectOnboarding
|
tests/Rules-isEmptyString-spec.js | yesmeck/formsy-react | import React from 'react';
import TestUtils from 'react-addons-test-utils';
import Formsy from './..';
import { InputFactory } from './utils/TestInput';
const TestInput = InputFactory({
render() {
return <input value={this.getValue()} readOnly/>;
}
});
const TestForm = React.createClass({
render() {
return (
<Formsy.Form>
<TestInput name="foo" validations="isEmptyString" value={this.props.inputValue}/>
</Formsy.Form>
);
}
});
export default {
'should pass with a default value': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should fail with non-empty string': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue="abc"/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should pass with an empty string': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue=""/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
},
'should fail with undefined': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={undefined}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should fail with null': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={null}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should fail with a number': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={42}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should fail with a zero': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={0}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
}
};
|
pages/index0.js | adjohnson916/site-gatsby | import React from 'react'
import { Link } from 'react-router'
import { prefixLink } from 'gatsby-helpers'
// Styles for highlighted code blocks.
import 'css/zenburn.css'
export default class Sass extends React.Component {
render () {
return (
<div>
<h1>
Hi people
</h1>
<p>Welcome to your new Gatsby site</p>
<h2>Below are some pages showing different capabilities built-in to Gatsby</h2>
<h3>Supported file types</h3>
<ul>
<li>
<Link to={prefixLink('/markdown/')}>Markdown</Link>
</li>
<li>
<Link to={prefixLink('/react/')}>JSX (React components)</Link>
</li>
<li>
<Link to={prefixLink('/coffee-react/')}>CJSX (Coffeescript React components)</Link>
</li>
<li>
<Link to={prefixLink('/html/')}>HTML</Link>
</li>
<li>
<Link to={prefixLink('/json/')}>JSON</Link>
</li>
<li>
<Link to={prefixLink('/yaml/')}>YAML</Link>
</li>
<li>
<Link to={prefixLink('/toml/')}>TOML</Link>
</li>
</ul>
<h3>Supported CSS processors</h3>
<ul>
<li>
<Link to={prefixLink('/postcss/')}>PostCSS</Link>
</li>
<li>
<Link to={prefixLink('/sass/')}>Sass</Link>
</li>
<li>
<Link to={prefixLink('/less/')}>Less</Link>
</li>
</ul>
</div>
)
}
}
|
app/react-icons/fa/volume-off.js | scampersand/sonos-front | import React from 'react';
import IconBase from 'react-icon-base';
export default class FaVolumeOff extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m28.6 7.9v24.2q0 0.6-0.4 1t-1 0.5-1-0.5l-7.4-7.4h-5.9q-0.6 0-1-0.4t-0.4-1v-8.6q0-0.6 0.4-1t1-0.4h5.9l7.4-7.4q0.4-0.5 1-0.5t1 0.5 0.4 1z"/></g>
</IconBase>
);
}
}
|
src/components/EditableSelectInput/EditableSelectInput.stories.js | austinknight/ui-components | import React from "react";
import { storiesOf } from "@storybook/react";
import EditableSelectInput from "./";
import { wrapComponentWithContainerAndTheme, colors } from "../styles";
const darkExample = {
height: "220px",
backgroundColor: "#2a434a",
padding: "16px"
};
const genericOptions = [
{ value: "1", label: "Option One" },
{ value: "2", label: "Option Two" },
{ value: "3", label: "Option Three" },
{ value: "4", label: "Option Four" },
{ value: "5", label: "Option Five" },
{ value: "6", label: "Option Six" },
{ value: "7", label: "Option Seven" },
{ value: "8", label: "Option Eight" },
{ value: "9", label: "Option Nine" },
{ value: "10", label: "Option Ten" },
{
value: "11",
label:
"A really long string A really long string A really long string A really long string A really long string A really long string A really long string A really long string A really long string A really long string"
}
];
function renderChapterWithTheme(theme) {
return {
info: `
Usage
~~~
import React from 'react';
import {EditableSelectInput} from 'insidesales-components';
~~~
`,
chapters: [
{
sections: [
{
title: "Default Theme",
sectionFn: () =>
wrapComponentWithContainerAndTheme(
theme,
<div style={darkExample}>
<EditableSelectInput
options={genericOptions}
value="555-555-5555"
placeholder={"Phone Number"}
/>
</div>
)
}
]
}
]
};
}
storiesOf("Form", module)
.addWithChapters("Default EditableSelectInput", renderChapterWithTheme({}))
.addWithChapters(
"EditableSelectInput w/ BlueYellow Theme",
renderChapterWithTheme(colors.blueYellowTheme)
);
|
app/javascript/mastodon/features/ui/components/tabs_bar.js | RobertRence/Mastodon | import React from 'react';
import PropTypes from 'prop-types';
import NavLink from 'react-router-dom/NavLink';
import { FormattedMessage, injectIntl } from 'react-intl';
import { debounce } from 'lodash';
import { isUserTouching } from '../../../is_mobile';
export const links = [
<NavLink className='tabs-bar__link primary' to='/statuses/new' data-preview-title-id='tabs_bar.compose' data-preview-icon='pencil' ><i className='fa fa-fw fa-pencil' /><FormattedMessage id='tabs_bar.compose' defaultMessage='Compose' /></NavLink>,
<NavLink className='tabs-bar__link primary' to='/timelines/home' data-preview-title-id='column.home' data-preview-icon='home' ><i className='fa fa-fw fa-home' /><FormattedMessage id='tabs_bar.home' defaultMessage='Home' /></NavLink>,
<NavLink className='tabs-bar__link primary' to='/notifications' data-preview-title-id='column.notifications' data-preview-icon='bell' ><i className='fa fa-fw fa-bell' /><FormattedMessage id='tabs_bar.notifications' defaultMessage='Notifications' /></NavLink>,
<NavLink className='tabs-bar__link secondary' to='/timelines/public/local' data-preview-title-id='column.community' data-preview-icon='users' ><i className='fa fa-fw fa-users' /><FormattedMessage id='tabs_bar.local_timeline' defaultMessage='Local' /></NavLink>,
<NavLink className='tabs-bar__link secondary' exact to='/timelines/public' data-preview-title-id='column.public' data-preview-icon='globe' ><i className='fa fa-fw fa-globe' /><FormattedMessage id='tabs_bar.federated_timeline' defaultMessage='Federated' /></NavLink>,
<NavLink className='tabs-bar__link primary' style={{ flexGrow: '0', flexBasis: '30px' }} to='/getting-started' data-preview-title-id='getting_started.heading' data-preview-icon='asterisk' ><i className='fa fa-fw fa-asterisk' /></NavLink>,
];
export function getIndex (path) {
return links.findIndex(link => link.props.to === path);
}
export function getLink (index) {
return links[index].props.to;
}
@injectIntl
export default class TabsBar extends React.Component {
static contextTypes = {
router: PropTypes.object.isRequired,
}
static propTypes = {
intl: PropTypes.object.isRequired,
}
setRef = ref => {
this.node = ref;
}
handleClick = (e) => {
// Only apply optimization for touch devices, which we assume are slower
// We thus avoid the 250ms delay for non-touch devices and the lag for touch devices
if (isUserTouching()) {
e.preventDefault();
e.persist();
requestAnimationFrame(() => {
const tabs = Array(...this.node.querySelectorAll('.tabs-bar__link'));
const currentTab = tabs.find(tab => tab.classList.contains('active'));
const nextTab = tabs.find(tab => tab.contains(e.target));
const { props: { to } } = links[Array(...this.node.childNodes).indexOf(nextTab)];
if (currentTab !== nextTab) {
if (currentTab) {
currentTab.classList.remove('active');
}
const listener = debounce(() => {
nextTab.removeEventListener('transitionend', listener);
this.context.router.history.push(to);
}, 50);
nextTab.addEventListener('transitionend', listener);
nextTab.classList.add('active');
}
});
}
}
render () {
const { intl: { formatMessage } } = this.props;
return (
<nav className='tabs-bar' ref={this.setRef}>
{links.map(link => React.cloneElement(link, { key: link.props.to, onClick: this.handleClick, 'aria-label': formatMessage({ id: link.props['data-preview-title-id'] }) }))}
</nav>
);
}
}
|
docs/includes/nav/Sidebar.js | harjeethans/materialistic | import React from 'react';
import {Link} from 'react-router';
function Sidebar(props) {
const renderSidebarItems = function(items){
return (
items.map((item, index) => {
return (
<li className="mdl-list__item" key={index}>
<span className="mdl-list__item-primary-content">
<Link className="mdl-navigation__link" to={'/' +item.href}>{item.text}</Link></span>
</li>
);
})
);
}
return (
<ul className="demo-list-item mdl-list">
{renderSidebarItems(props.items)}
</ul>
);
}
Sidebar.propTypes = {
items: React.PropTypes.array
};
Sidebar.defaultProps = {
items: [1]
};
export default Sidebar;
|
frontend/modules/recipe_form/components/TabbedView.js | RyanNoelk/OpenEats | import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import { Popover, OverlayTrigger } from 'react-bootstrap'
import {
injectIntl,
defineMessages,
} from 'react-intl';
class TabbedView extends React.Component {
constructor(props) {
super(props);
this.state = {
display: this.props.display || 0,
};
}
switchView = val => {
this.setState({ display: val })
};
render() {
const { formatMessage } = this.props.intl;
const messages = defineMessages({
preview: {
id: 'recipe.create.preview',
description: 'Preview',
defaultMessage: 'Preview',
},
editor: {
id: 'recipe.create.editor',
description: 'Editor',
defaultMessage: 'Editor',
},
});
let { children, label, infoTitle, infoDesc, errors } = this.props;
let { display } = this.state;
let contentClassName = classNames({
'content': true,
'has-error': !!this.props.errors
});
let navClassName = classNames({
'nav': true,
'nav-tabs': true,
'has-error': !!this.props.errors
});
const popoverHoverFocus = (
<Popover id="help" title={ infoTitle }>
{ infoDesc }
</Popover>
);
return (
<div className="live-editor">
<ul className={ navClassName }>
<li className={ classNames({ left: true, active: true })}>
<span>
{ label }
<OverlayTrigger
trigger={['hover']}
placement="top"
overlay={ popoverHoverFocus }
>
<span className="glyphicon glyphicon-info-sign"/>
</OverlayTrigger>
</span>
</li>
<li className={ classNames({ active: display === 0 })}>
<span onClick={ this.switchView.bind(this, 0) }>
{ formatMessage(messages.editor) }
</span>
</li>
<li className={ classNames({ active: display === 1 })}>
<span onClick={ this.switchView.bind(this, 1) }>
{ formatMessage(messages.preview) }
</span>
</li>
</ul>
<div className={ contentClassName }>{ children[display] }</div>
<div className="help-inline">{ errors }</div>
</div>
)
}
}
TabbedView.PropTypes = {
label: PropTypes.string.isRequired,
display: PropTypes.number,
errors: PropTypes.string,
className: PropTypes.string,
infoTitle: PropTypes.string,
infoDesc: PropTypes.string,
intl: PropTypes.obj,
};
export default injectIntl(TabbedView)
|
app/components/shape_tween.js | laynemcnish/personal-site | import React, { Component } from 'react';
import d3 from 'd3';
export default class ShapeTween extends Component {
componentDidMount () {
var node = React.findDOMNode(this);
var width = 960,
height = 500;
var projection = d3.geo.albers()
.rotate([120, 0])
.center([15, 35])
.scale(1200);
var svg = d3.select(node).append("svg")
.attr("width", width)
.attr("height", height);
d3.json("california.json", function(polygon) {
console.log(polygon);
var coordinates0 = polygon.coordinates[0].map(projection),
coordinates1 = circle(coordinates0),
path = svg.append("path"),
d0 = "M" + coordinates0.join("L") + "Z",
d1 = "M" + coordinates1.join("L") + "Z";
loop();
function loop() {
path
.attr("d", d0)
.transition()
.duration(5000)
.attr("d", d1)
.transition()
.delay(5000)
.attr("d", d0)
.each("end", loop);
}
});
function circle(coordinates) {
var circle = [],
length = 0,
lengths = [length],
polygon = d3.geom.polygon(coordinates),
p0 = coordinates[0],
p1,
x,
y,
i = 0,
n = coordinates.length;
// Compute the distances of each coordinate.
while (++i < n) {
p1 = coordinates[i];
x = p1[0] - p0[0];
y = p1[1] - p0[1];
lengths.push(length += Math.sqrt(x * x + y * y));
p0 = p1;
}
var area = polygon.area(),
radius = Math.sqrt(Math.abs(area) / Math.PI),
centroid = polygon.centroid(-1 / (6 * area)),
angleOffset = -Math.PI / 2, // TODO compute automatically
angle,
i = -1,
k = 2 * Math.PI / lengths[lengths.length - 1];
// Compute points along the circle’s circumference at equivalent distances.
while (++i < n) {
angle = angleOffset + lengths[i] * k;
circle.push([
centroid[0] + radius * Math.cos(angle),
centroid[1] + radius * Math.sin(angle)
]);
}
return circle;
}
}
render () {
return React.DOM.div(null, '');
}
}
|
src/containers/pages/create-deck/after-class-selection/left-container/filter-sidebar.js | vFujin/HearthLounge | import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import IconFilter from '../../../../shared-assets/filters/redux-icon-filter';
import InputFilter from '../../../../shared-assets/filters/redux-input-filter';
import SliderFilter from '../../../../shared-assets/filters/redux-slider-filter';
import {connect} from 'react-redux';
import {toggleSelectedIcon} from "../../../../../utils/filter/toggle-selected-icon";
import {updateDeckCreationFilters} from "../../../../../redux/create-deck/actions/create-deck.action";
const FilterSidebar = ({faction, mechanics, name, race, type, cardName, cardRace, cardMechanics, cardFaction, cardType, cardHealth, cardAttack, cardDurability, cardStandardSet, cardWildSet, cardRarity, updateDeckCreationFilters}) => {
const handleSelect = (value, selector) =>{
updateDeckCreationFilters({[`card${_.startCase(selector)}`]:value});
};
const handleIconClick = (e, selector) =>{
toggleSelectedIcon(e, selector, updateDeckCreationFilters, true);
};
return (
<div className="sidebar__body">
<InputFilter attribute={name} value={cardName} filter="name" multiple={false} handleSelect={handleSelect}/>
<InputFilter attribute={race} value={cardRace} filter="race" multiple={true} handleSelect={handleSelect}/>
<InputFilter attribute={mechanics} value={cardMechanics} filter="mechanics" multiple={true} handleSelect={handleSelect}/>
<InputFilter attribute={faction} value={cardFaction} filter="faction" multiple={true} handleSelect={handleSelect}/>
<InputFilter attribute={type} value={cardType} filter="type" multiple={true} handleSelect={handleSelect}/>
<SliderFilter filter="health" value={cardHealth} defaultValue={[0, 30]} max={50} marks={{0:0, 30:30, 50:50}} handleSelect={handleSelect}/>
<SliderFilter filter="attack" value={cardAttack} defaultValue={[0, 5]} max={30} marks={{0:0, 5:5, 30:30}} handleSelect={handleSelect}/>
<SliderFilter filter="durability" value={cardDurability} defaultValue={[0, 7]} max={10} marks={{0:0, 7:7, 10:10}} handleSelect={handleSelect}/>
<IconFilter header={true} headerLabel="standard set" filter="cardSet" value={cardStandardSet} wrapperClass="sidebar-icons" isStandard={true} handleIconClick={handleIconClick}/>
<IconFilter header={true} headerLabel="wild set" filter="cardSet" value={cardWildSet} wrapperClass="sidebar-icons" isStandard={false} handleIconClick={handleIconClick}/>
<IconFilter header={true} headerLabel="rarity" filter="rarity" value={cardRarity} wrapperClass="sidebar-icons" handleIconClick={handleIconClick}/>
</div>
);
};
FilterSidebar.propTypes = {
faction: PropTypes.array,
mechanics: PropTypes.array,
name: PropTypes.array,
query: PropTypes.object,
race: PropTypes.array,
type: PropTypes.array,
};
const mapStateToProps = (state) => {
const {cardName, cardRace, cardMechanics, cardFaction, cardType, cardHealth, cardAttack, cardDurability, cardStandardSet, cardWildSet, cardRarity} = state.deckCreation;
return {
filtersQuery: {
cardName,
cardRace,
cardMechanics,
cardFaction,
cardType,
cardHealth,
cardAttack,
cardDurability,
cardRarity,
cardStandardSet,
cardWildSet
}
};
};
const mapDispatchToProps = (dispatch) => {
return {
updateDeckCreationFilters: deckCreationFilters => dispatch(updateDeckCreationFilters(deckCreationFilters)),
}
};
export default connect(mapStateToProps, mapDispatchToProps)(FilterSidebar);
|
public/js/cat_source/es6/components/modals/LoginModal.js | matecat/MateCat | import PropTypes from 'prop-types'
import update from 'immutability-helper'
import _ from 'lodash'
import React from 'react'
import TextField from '../common/TextField'
import * as RuleRunner from '../common/ruleRunner'
import * as FormRules from '../common/formRules'
import {checkRedeemProject as checkRedeemProjectApi} from '../../api/checkRedeemProject'
import {loginUser} from '../../api/loginUser'
class LoginModal extends React.Component {
constructor(props) {
super(props)
this.state = {
showErrors: false,
validationErrors: {},
generalError: '',
requestRunning: false,
}
this.state.validationErrors = RuleRunner.run(this.state, fieldValidations)
this.handleFieldChanged = this.handleFieldChanged.bind(this)
this.handleSubmitClicked = this.handleSubmitClicked.bind(this)
this.sendLoginData = this.sendLoginData.bind(this)
this.errorFor = this.errorFor.bind(this)
}
// TODO: find a way to abstract this into the plugin
otherServiceLogin() {
let url = config.pluggable.other_service_auth_url
let self = this
this.checkRedeemProject()
let newWindow = window.open(url, 'name', 'height=900,width=900')
if (window.focus) {
newWindow.focus()
}
let interval = setInterval(function () {
if (newWindow.closed) {
clearInterval(interval)
let loc
if (self.props.goToManage) {
window.location = '/manage/'
} else if ((loc = window.localStorage.getItem('wanted_url'))) {
window.localStorage.removeItem('wanted_url')
window.location.href = loc
} else {
window.location.reload()
}
}
}, 600)
}
googole_popup() {
let url = this.props.googleUrl
let self = this
this.checkRedeemProject()
let newWindow = window.open(url, 'name', 'height=600,width=900')
if (window.focus) {
newWindow.focus()
}
let interval = setInterval(function () {
if (newWindow.closed) {
clearInterval(interval)
let loc
if (self.props.goToManage) {
window.location = '/manage/'
} else if ((loc = window.localStorage.getItem('wanted_url'))) {
window.localStorage.removeItem('wanted_url')
window.location.href = loc
} else {
window.location.reload()
}
}
}, 600)
}
handleFieldChanged(field) {
return (e) => {
let newState = update(this.state, {
[field]: {$set: e.target.value},
})
newState.validationErrors = RuleRunner.run(newState, fieldValidations)
newState.generalError = ''
this.setState(newState)
}
}
handleSubmitClicked() {
let self = this
this.setState({showErrors: true})
if ($.isEmptyObject(this.state.validationErrors) == false) return null
if (this.state.requestRunning) {
return false
}
this.setState({requestRunning: true})
this.checkRedeemProject().then(
this.sendLoginData()
.then(() => {
if (self.props.goToManage) {
window.location = '/manage/'
} else {
window.location.reload()
}
})
.catch(() => {
const text = 'Login failed.'
self.setState({
generalError: text,
requestRunning: false,
})
}),
)
}
checkRedeemProject() {
if (this.props.redeemMessage) {
return checkRedeemProjectApi()
} else {
return Promise.resolve()
}
}
sendLoginData() {
return loginUser(this.state.emailAddress, this.state.password)
}
errorFor(field) {
return this.state.validationErrors[field]
}
openRegisterModal() {
$('#modal').trigger('openregister')
}
openForgotPassword() {
$('#modal').trigger('openforgotpassword')
}
googleLoginButton() {
if (!(config.pluggable && config.pluggable.auth_disable_google)) {
return (
<a
className="google-login-button btn-confirm-medium"
onClick={this.googole_popup.bind(this)}
/>
)
}
}
otherServiceLoginButton() {
if (config.pluggable && config.pluggable.other_service_auth_url) {
return (
<a
className="btn-confirm-medium"
onClick={this.otherServiceLogin.bind(this)}
>
{config.pluggable.other_service_button_label}
</a>
)
}
}
loginFormContainerCode() {
if (!(config.pluggable && config.pluggable.auth_disable_email)) {
let generalErrorHtml = ''
let buttonSignInClass =
_.size(this.state.validationErrors) === 0 ? '' : 'disabled'
if (this.state.generalError.length) {
generalErrorHtml = (
<div style={{color: 'red', fontSize: '14px'}} className="text">
{this.state.generalError}
</div>
)
}
let loaderClass = this.state.requestRunning ? 'show' : ''
return (
<div className="login-form-container">
<div className="form-divider">
<div className="divider-line"></div>
<span>OR</span>
<div className="divider-line"></div>
</div>
<TextField
showError={this.state.showErrors}
onFieldChanged={this.handleFieldChanged('emailAddress')}
placeholder="Email"
name="emailAddress"
errorText={this.errorFor('emailAddress')}
tabindex={1}
onKeyPress={(e) => {
e.key === 'Enter' ? this.handleSubmitClicked() : null
}}
/>
<TextField
type="password"
showError={this.state.showErrors}
onFieldChanged={this.handleFieldChanged('password')}
placeholder="Password (minimum 8 characters)"
name="password"
errorText={this.errorFor('password')}
tabindex={2}
onKeyPress={(e) => {
e.key === 'Enter' ? this.handleSubmitClicked() : null
}}
/>
<a
className={
'login-button btn-confirm-medium sing-in ' + buttonSignInClass
}
onKeyPress={(e) => {
e.key === 'Enter' ? this.handleSubmitClicked() : null
}}
onClick={this.handleSubmitClicked.bind()}
tabIndex={3}
>
<span className={'button-loader ' + loaderClass} /> Sign in{' '}
</a>
{generalErrorHtml}
<br />
<span className="forgot-password" onClick={this.openForgotPassword}>
Forgot password?
</span>
</div>
)
}
}
render() {
let htmlMessage = (
<div className="login-container-right">
<h2>Sign up now to:</h2>
<ul className="">
<li>Manage your TMs, glossaries and MT engines</li>
<li>Access the management panel</li>
<li>Translate Google Drive files</li>
</ul>
<a
className="register-button btn-confirm-medium"
onClick={this.openRegisterModal}
>
Sign up
</a>
</div>
)
if (this.props.redeemMessage) {
htmlMessage = (
<div className="login-container-right">
<h2 style={{fontSize: '21px'}}>
Sign up or sign in to add the project to your management panel and:
</h2>
<ul className="add-project-manage">
<li>Track the progress of your translations</li>
<li>Monitor the activity for increased security</li>
<li>Manage TMs, MT and glossaries</li>
</ul>
<a
className="register-button btn-confirm-medium sing-up"
onClick={this.openRegisterModal}
>
Sign up
</a>
</div>
)
}
return (
<div className="login-modal">
{htmlMessage}
<div className="login-container-left">
{this.otherServiceLoginButton()}
{this.googleLoginButton()}
{this.loginFormContainerCode()}
</div>
</div>
)
}
}
const fieldValidations = [
RuleRunner.ruleRunner(
'emailAddress',
'Email address',
FormRules.requiredRule,
FormRules.checkEmail,
),
RuleRunner.ruleRunner(
'password',
'Password',
FormRules.requiredRule,
FormRules.minLength(8),
),
]
LoginModal.propTypes = {
googleUrl: PropTypes.string,
}
export default LoginModal
|
src/routes.js | allyrippley/7ds | import React from 'react'
import { Route, IndexRoute } from 'react-router'
import App from './containers/App'
import Main from './containers/Main'
import AboutPage from './containers/About'
import Portfolio from './containers/Portfolio'
import PortfolioPage from './containers/Portfolio/Page'
import Contact from './containers/ContactForm'
import NotFoundPage from './components/NotFoundPage/kitty.js'
export default (
<Route path="/" component={App}>
<IndexRoute component={Main}/>
<Route path="/fuel-savings" component={Main}/>
<Route path="/portfolio/page/:id" component={PortfolioPage}/>
<Route path="/portfolio" component={Portfolio}/>
<Route path="/contact" component={Contact}/>
<Route path="/about" component={AboutPage}/>
<Route path="*" component={NotFoundPage}/>
</Route>
)
|
client/modules/App/__tests__/Components/Footer.spec.js | Trulsabe/reactLinuxMern | import React from 'react';
import test from 'ava';
import { shallow } from 'enzyme';
import { Footer } from '../../components/Footer/Footer';
test('renders the footer properly', t => {
const wrapper = shallow(
<Footer />
);
t.is(wrapper.find('p').length, 2);
t.is(wrapper.find('p').first().text(), '© 2016 · Hashnode · LinearBytes Inc.');
});
|
example-slack-message/src/App.js | atFriendly/react-native-friendly-chat | import React, { Component } from 'react';
import { View, Platform } from 'react-native';
import PropTypes from 'prop-types';
import { GiftedChat } from 'react-native-gifted-chat';
import emojiUtils from 'emoji-utils';
import SlackMessage from './SlackMessage';
class App extends Component {
renderMessage(props) {
const { currentMessage: { text: currText } } = props;
let messageTextStyle;
// Make "pure emoji" messages much bigger than plain text.
if (currText && emojiUtils.isPureEmojiString(currText)) {
messageTextStyle = {
fontSize: 28,
// Emoji get clipped if lineHeight isn't increased; make it consistent across platforms.
lineHeight: Platform.OS === 'android' ? 34 : 30,
};
}
return (
<SlackMessage {...props} messageTextStyle={messageTextStyle} />
);
}
render() {
return (
<GiftedChat
messages={[]}
renderMessage={this.renderMessage}
/>
);
}
}
export default App;
|
src/components/tablePrices/presentation/TPDeadlines.js | edu-affiliates/promo_calculators | 'use strict';
import React from 'react';
import {connect} from 'react-redux'
import {changeDeadline} from '../../../store/actions'
class TPDeadlines extends React.Component {
constructor(props) {
super(props);
}
render() {
const {deadlineList, deadline} = this.props;
let list = deadlineList.map((d) => {
return <li key={d.id} className={`${(deadline === d.name) ? 'active' : ''} tp-deadline__item`}>{d.name}</li>
});
return (
<div className="tp-deadline">
<div className="tp-deadline__top">
<div className="tp-deadline__title">DEADLINE</div>
<div className="tp-deadline__icon">
<img src={require("../../../images/icons/tp.svg")}/>
</div>
</div>
<ul className="tp-deadline__list">
{list}
</ul>
</div>
)
}
}
//container to match redux state to component props and dispatch redux actions to callback props
const mapStateToProps = (reduxState, ownProps) => {
const state = reduxState.calculatorSmall[ownProps.calcId];
return {
deadlineList: state.currentDeadlines,
deadline: state.deadline.name,
}
};
const mapDispatchToProps = (reduxState, ownProps) => {
return {
changeDeadline: (id) => {
dispatch(changeDeadline(id, ownProps.calcId))
}
}
};
export default connect(mapStateToProps, mapDispatchToProps)(TPDeadlines);
|
src/components/course/CourseForm.js | RockingChewee/react-redux-building-applications | import React from 'react';
import TextInput from '../common/TextInput';
import SelectInput from '../common/SelectInput';
const CourseForm = ({course, allAuthors, onSave, onChange, saving, errors}) => {
return (
<form>
<h1>Manage Course</h1>
<TextInput
name="title"
label="Title"
value={course.title}
onChange={onChange}
error={errors.title}/>
<SelectInput
name="authorId"
label="Author"
value={course.authorId}
defaultOption="Select Author"
options={allAuthors}
onChange={onChange}
error={errors.authorId}/>
<TextInput
name="category"
label="Category"
value={course.category}
onChange={onChange}
error={errors.category}/>
<TextInput
name="length"
label="Length"
value={course.length}
onChange={onChange}
error={errors.length}/>
<input
type="submit"
disabled={saving}
value={saving ? 'Saving...' : 'Save'}
className="btn btn-primary"
onClick={onSave}/>
</form>
);
};
CourseForm.propTypes = {
course: React.PropTypes.object.isRequired,
allAuthors: React.PropTypes.array,
onSave: React.PropTypes.func.isRequired,
onChange: React.PropTypes.func.isRequired,
saving: React.PropTypes.bool,
errors: React.PropTypes.object
};
export default CourseForm;
|
packages/my-joy-instances/src/containers/create-instance/index.js | geek/joyent-portal | /* eslint-disable camelcase */
import React from 'react';
import { Margin } from 'styled-components-spacing';
import ReduxForm from 'declarative-redux-form';
import { stopAsyncValidation, SubmissionError, destroy } from 'redux-form';
import { connect } from 'react-redux';
import { set, destroyAll } from 'react-redux-values';
import { graphql, compose } from 'react-apollo';
import intercept from 'apr-intercept';
import constantCase from 'constant-case';
import queryString from 'query-string';
import get from 'lodash.get';
import lvalues from 'lodash.values';
import omit from 'lodash.omit';
import uniqBy from 'lodash.uniqby';
import {
ViewContainer,
H2,
Button,
Message,
MessageTitle,
MessageDescription
} from 'joyent-ui-toolkit';
import Name from '@containers/create-instance/name';
import Image from '@containers/create-instance/image';
import Package from '@containers/create-instance/package';
import Tags from '@containers/create-instance/tags';
import Metadata from '@containers/create-instance/metadata';
import UserScript from '@containers/create-instance/user-script';
import Networks from '@containers/create-instance/networks';
import Firewall from '@containers/create-instance/firewall';
import CNS from '@containers/create-instance/cns';
import Affinity from '@containers/create-instance/affinity';
import CreateInstanceMutation from '@graphql/create-instance.gql';
import GetInstance from '@graphql/get-instance-small.gql';
import createClient from '@state/apollo-client';
import parseError from '@state/parse-error';
import { Forms, Values } from '@root/constants';
const {
IC_F,
IC_NAME_F,
IC_IMG_F,
IC_PKG_F_SELECT,
IC_NW_F,
IC_US_F,
IC_FW_F_ENABLED
} = Forms;
const {
IC_MD_V_MD,
IC_TAG_V_TAGS,
IC_AFF_V_AFF,
IC_CNS_V_ENABLED,
IC_CNS_V_SERVICES,
IC_V_VALIDATING
} = Values;
const CreateInstance = ({
history,
match,
query,
step,
error,
disabled,
shouldAsyncValidate,
handleAsyncValidate,
handleSubmit,
validating
}) => (
<ViewContainer>
<Margin top={4} bottom={4}>
<H2>Create Instances</H2>
</Margin>
{error ? (
<Margin bottom={4}>
<Message error>
<MessageTitle>Ooops!</MessageTitle>
<MessageDescription>{error}</MessageDescription>
</Message>
</Margin>
) : null}
{query.image ? (
<Image
history={history}
match={match}
query={query}
step="image"
expanded={step === 'image'}
/>
) : null}
<Name
history={history}
match={match}
query={query}
step="name"
expanded={step === 'name'}
/>
{!query.image ? (
<Image
history={history}
match={match}
query={query}
step="image"
expanded={step === 'image'}
/>
) : null}
<Package
history={history}
match={match}
step="package"
expanded={step === 'package'}
/>
<Tags
history={history}
match={match}
step="tags"
expanded={step === 'tags'}
/>
<Metadata
history={history}
match={match}
step="metadata"
expanded={step === 'metadata'}
/>
<UserScript
history={history}
match={match}
step="user-script"
expanded={step === 'user-script'}
/>
<Networks
history={history}
match={match}
step="networks"
expanded={step === 'networks'}
/>
<Firewall
history={history}
match={match}
step="firewall"
expanded={step === 'firewall'}
/>
<CNS history={history} match={match} step="cns" expanded={step === 'cns'} />
<Affinity
history={history}
match={match}
step="affinity"
expanded={step === 'affinity'}
/>
<Margin top={7} bottom={10}>
{error ? (
<Margin bottom={4}>
<Message error>
<MessageTitle>Ooops!</MessageTitle>
<MessageDescription>{error}</MessageDescription>
</Message>
</Margin>
) : null}
<ReduxForm
form={IC_F}
shouldAsyncValidate={shouldAsyncValidate}
asyncValidate={handleAsyncValidate}
onSubmit={handleSubmit}
>
{({ handleSubmit, submitting }) => (
<form onSubmit={handleSubmit}>
<Button disabled={disabled} loading={submitting || validating}>
Deploy
</Button>
</form>
)}
</ReduxForm>
</Margin>
</ViewContainer>
);
export default compose(
graphql(CreateInstanceMutation, { name: 'createInstance' }),
connect(({ form, values }, { match, location }) => {
const query = queryString.parse(location.search);
const step = get(match, 'params.step', 'name');
const validating = get(values, IC_V_VALIDATING, false);
const isNameInvalid = get(form, `${IC_NAME_F}.asyncErrors.name`, null);
const error = get(form, `${IC_F}.error`, null);
const name = get(form, `${IC_NAME_F}.values.name`, '');
const image = get(form, `${IC_IMG_F}.values.image`, '');
const pkg = get(form, `${IC_PKG_F_SELECT}.values.package`, '');
const networks = get(form, `${IC_NW_F}.values`, {});
const enabled =
!isNameInvalid &&
name.length &&
image.length &&
pkg.length &&
lvalues(networks).filter(Boolean).length;
if (!enabled) {
return {
validating,
error,
query,
disabled: !enabled,
step
};
}
const metadata = get(values, IC_MD_V_MD, []);
const tags = get(values, IC_TAG_V_TAGS, []).map(tag => tag); // clone
const affinity = get(values, IC_AFF_V_AFF, null);
const cns = get(values, IC_CNS_V_ENABLED, true);
const cnsServices = get(values, IC_CNS_V_SERVICES, null);
const userScript = get(form, `${IC_US_F}.values.value`, '');
const firewall_enabled = get(
form,
`${IC_FW_F_ENABLED}.values.enabled`,
false
);
tags.push({
name: 'triton.cns.disable',
value: !cns
});
if (cnsServices && cns) {
tags.push({
name: 'triton.cns.services',
value: cnsServices.join(',')
});
}
return {
validating,
error,
query,
forms: Object.keys(form), // improve this
name,
pkg,
image,
affinity,
metadata,
userScript,
tags,
firewall_enabled,
networks,
step
};
}),
connect(null, (dispatch, ownProps) => {
const {
name,
pkg,
image,
affinity,
metadata,
userScript,
tags,
firewall_enabled,
networks,
forms,
createInstance,
history
} = ownProps;
const parseAffRule = ({
conditional,
placement,
identity,
name,
pattern,
value
}) => {
const type = constantCase(
`${conditional}_${placement === 'same' ? 'equal' : 'not_equal'}`
);
const patterns = {
equalling: value => value,
starting: value => `/^${value}/`
};
const _name = identity === 'name' ? 'instance' : name;
const _value = patterns[pattern](type === 'name' ? name : value);
return {
type,
key: _name,
value: _value
};
};
return {
shouldAsyncValidate: ({ trigger }) => {
return trigger === 'submit';
},
handleAsyncValidate: async () => {
dispatch(set({ name: IC_V_VALIDATING, value: true }));
const [nameError, res] = await intercept(
createClient().query({
fetchPolicy: 'network-only',
query: GetInstance,
variables: { name }
})
);
if (nameError) {
return dispatch([
set({ name: IC_V_VALIDATING, value: false }),
stopAsyncValidation(IC_F, { _error: parseError(nameError) })
]);
}
const { data } = res;
const { machines = [] } = data;
if (machines.length) {
return dispatch([
set({ name: IC_V_VALIDATING, value: false }),
stopAsyncValidation(IC_F, { _error: `${name} already exists.` })
]);
}
dispatch(set({ name: IC_V_VALIDATING, value: false }));
},
handleSubmit: async () => {
const _affinity = affinity ? parseAffRule(affinity) : null;
const _name = name.toLowerCase();
const _metadata = metadata.map(a => omit(a, 'open'));
const _tags = uniqBy(tags.map(a => omit(a, 'expanded')), 'name').map(
a => omit(a, 'expanded')
);
const _networks = Object.keys(networks).filter(
network => networks[network]
);
if (userScript && userScript.length) {
_metadata.push({ name: 'user-script', value: userScript });
}
const [err, res] = await intercept(
createInstance({
variables: {
name: _name,
package: pkg,
image,
affinity: _affinity ? [_affinity] : [],
metadata: _metadata,
tags: _tags,
firewall_enabled,
networks: _networks.length ? _networks : undefined
}
})
);
if (err) {
throw new SubmissionError({
_error: parseError(err)
});
}
dispatch([destroyAll(), forms.map(name => destroy(name))]);
history.push(`/instances/${res.data.createMachine.id}`);
}
};
})
)(CreateInstance);
|
packages/icons/src/md/image/ExposureNeg2.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdExposureNeg2(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M31.09 33.58l5.73-6.13c.75-.79 1.44-1.57 2.08-2.35.63-.78 1.18-1.56 1.64-2.33.46-.78.82-1.55 1.07-2.33.26-.78.39-1.57.39-2.37 0-1.07-.18-2.04-.54-2.92-.36-.87-.88-1.62-1.57-2.23-.69-.61-1.53-1.08-2.53-1.42-1-.33-2.14-.5-3.42-.5-1.38 0-2.62.21-3.7.64-1.08.43-1.99 1.01-2.73 1.75s-1.3 1.61-1.68 2.6c-.36.94-.54 1.95-.56 3.01h4.28c.01-.62.09-1.21.26-1.74.18-.58.45-1.08.81-1.5.36-.42.81-.74 1.35-.98.55-.23 1.19-.35 1.93-.35.61 0 1.15.1 1.62.31.47.21.87.49 1.19.85.32.36.57.8.74 1.29.17.5.25 1.04.25 1.63 0 .43-.06.87-.17 1.3-.11.43-.3.9-.58 1.4-.28.5-.65 1.05-1.11 1.66-.46.6-1.05 1.29-1.75 2.07l-8.35 9.11V37H43v-3.42H31.09zM5 23v4h16v-4H5z" />
</IconBase>
);
}
export default MdExposureNeg2;
|
frontend/src/components/Auth/presenter.js | plusbeauxjours/nomadgram | import React from 'react';
import styles from './styles.scss';
import PropTypes from 'prop-types';
import LoginForm from 'components/LoginForm';
import SignupForm from 'components/SignupForm';
const Auth = (
{
action,
changeAction
},
context
) => (
<main className={styles.auth}>
<div className={styles.column}>
<img src={require("images/phone.png" )} alt={context.t('Check our app. Is cool')} />
</div>
<div className={styles.column}>
<div className={`${styles.whiteBox} ${styles.formBox}`}>
{action === 'login' && <LoginForm />}
{action === 'signup' && <SignupForm />}
</div>
<div className={styles.whiteBox}>
{action === "login" && (
<p className={styles.text}>
{context.t("Don't have an account?")}{" "}
<span className={styles.changeLink} onClick={changeAction}>
{context.t('Sign up')}
</span>
</p>
)}
{action === "signup" && (
<p className={styles.text}>
{context.t('Have an account?')}{" "}
<span className={styles.changeLink} onClick={changeAction}>
{context.t('Log in')}
</span>
</p>
)}
</div>
<div className={styles.appBox}>
<span>{context.t('Get the app')}</span>
<div className={styles.appstores}>
<img
src={require("images/ios.png")}
alt={context.t('Download it on the Apple Appstore')}
/>
<img
src={require("images/android.png")}
alt={context.t('Download it on tha Android Appstore')}
/>
</div>
</div>
</div>
</main>
);
Auth.propTypes = {
action: PropTypes.string.isRequired,
changeAction: PropTypes.func.isRequired,
};
Auth.contextTypes = {
t: PropTypes.func.isRequired
};
export default Auth; |
app/index.js | binayverma/weathernow | import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import { browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { AppContainer } from 'react-hot-loader';
import configureStore from './store/configureStore';
import Root from './containers/Root';
import './styles/index.scss';
import './styles/footer.scss';
const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store);
render(
<AppContainer>
<Root store={store} history={history} />
</AppContainer>,
document.getElementById('root')
);
if (module.hot) {
module.hot.accept('./containers/Root', () => {
const NewRoot = require('./containers/Root').default;
render(
<AppContainer>
<NewRoot store={store} history={history} />
</AppContainer>,
document.getElementById('root')
);
});
}
|
examples/vuecli3-custom/styleguide/components/SectionsRenderer.js | vue-styleguidist/vue-styleguidist | import React from 'react';
import PropTypes from 'prop-types';
import Styled from 'rsg-components/Styled';
import Heading from 'rsg-components/Heading';
// Avoid circular ref
// Import default implementation using `rsg-components-default`
import DefaultSectionsRenderer from 'rsg-components-default/Sections/SectionsRenderer';
const styles = ({ fontFamily, space }) => ({
headingSpacer: {
marginBottom: space[2],
},
descriptionText: {
marginTop: space[0],
fontFamily: fontFamily.base,
},
});
export function SectionsRenderer({ classes, children }) {
return (
<div>
{!!children.length &&
<div className={classes.headingSpacer}>
<Heading level={1}>Example Components</Heading>
<p className={classes.descriptionText}>These are the greatest components</p>
</div>}
<DefaultSectionsRenderer>{children}</DefaultSectionsRenderer>
</div>
);
}
SectionsRenderer.propTypes = {
classes: PropTypes.object.isRequired,
children: PropTypes.node,
};
export default Styled(styles)(SectionsRenderer);
|
src/components/Home.js | aalselius/Test | import React, { Component } from 'react';
import Image from './Image.js';
import ImageHeader from './ImageHeader.js';
import InfoText from './InfoText.js';
import Header from './Header.js';
class Home extends Component {
constructor() {
super();
this.state = {
imageUrl: '',
url:'',
inputType: '',
imageNumber: 0,
json:'',
images:[],
text: 'cat',
loaded: false,
}
}
componentDidMount() {
this.url = "http://api.giphy.com/v1/gifs/trending?api_key=dc6zaTOxFJmzC";
console.log(this.url);
fetch(this.url)
.then((data) => {
return data.json();
})
.then((json) => {
console.log(json);
this.setState({json:json});
this.setState({imageUrl:this.state.json.data[0].images.downsized.url});
this.setState({loaded: true});
})
;
}
changeLink = (arrow) => {
if (arrow === "left") {
this.setState({imageNumber: this.state.imageNumber -1}); //previous state, if 0 => 25
if (this.state.imageNumber <= 0) {
this.setState({imageNumber: 24}); //previous state, if 0 => 25
}
} else if (arrow === "right") {
this.setState({imageNumber: this.state.imageNumber +1}); // previous state, if 25 => 0
if (this.state.imageNumber >= 24) {
this.setState({imageNumber: 0}); //previous state, if 0 => 25
}
}
console.log(this.state.imageNumber);
let xx=this.state.json;
this.setState ({imageUrl:xx.data[this.state.imageNumber].images.downsized.url});
}
updateText = (event) => {
this.setState({text: event.target.value})
}
handleSubmit = (event) => {
if(event.keyCode === 13) {
this.setState({text: event.target.value})
console.log(this.state.text);
// set new url
this.updateUrl(this.state.text);
event.target.value='';
}
}
render() {
return (
<div className="pageContainer">
<Header headerText="Home" headerClass="sideHeader"/>
<ImageHeader text="Popular Giphy"/>
{this.state.loaded ? (
<div>
<div className="imageContainer">
<i className="fa fa-angle-left" onClick={()=>this.changeLink("left")}></i>
<Image url={this.state.imageUrl}/>
<i className="fa fa-angle-right" onClick={()=>this.changeLink("right")}></i>
</div>
<InfoText infoText="I don't take responsibility for giphys shown on this site. There is no filter on the giphys."/>
</div>
) : (
<div className="imageContainer"><i className="fa fa-spinner" aria-hidden="true"></i></div>
)}
</div>
);
}
}
export default Home; |
client/views/admin/settings/SettingsRoute.js | VoiSmart/Rocket.Chat | import React from 'react';
import NotAuthorizedPage from '../../../components/NotAuthorizedPage';
import { useRouteParameter } from '../../../contexts/RouterContext';
import { useIsPrivilegedSettingsContext } from '../../../contexts/SettingsContext';
import EditableSettingsProvider from '../../../providers/EditableSettingsProvider';
import GroupSelector from './GroupSelector';
export function SettingsRoute() {
const hasPermission = useIsPrivilegedSettingsContext();
const groupId = useRouteParameter('group');
if (!hasPermission) {
return <NotAuthorizedPage />;
}
return (
<EditableSettingsProvider>
<GroupSelector groupId={groupId} />
</EditableSettingsProvider>
);
}
export default SettingsRoute;
|
src/components/posts_index.js | 937aaron/reduxblog | import _ from 'lodash'
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';
import { Link } from 'react-router-dom';
class PostsIndex extends Component {
componentDidMount() {
this.props.fetchPosts()
}
renderPosts(){
return _.map(this.props.posts, post => {
return(
<li className="list-group-item" key={post.id}>
<Link to={`/posts/${post.id}`}>
{post.title}
</Link>
</li>
);
});
}
render() {
return (
<div>
<div className="text-xs-right">
<Link className="btn btn-primary" to="/posts/new">Add a Post +</Link>
</div>
<h3>Posts:</h3>
<ul className="list-group">
{this.renderPosts()}
</ul>
</div>
)
}
}
function mapStateToProps(state) {
return { posts: state.posts };
}
export default connect(mapStateToProps, { fetchPosts }) (PostsIndex);
|
examples/tms/app.js | bartvde/sdk | /** TMS SDK application example.
*
*/
import {createStore, combineReducers, applyMiddleware} from 'redux';
import thunkMiddleware from 'redux-thunk';
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import SdkZoomControl from '@boundlessgeo/sdk/components/map/zoom-control';
import SdkZoomSlider from '@boundlessgeo/sdk/components/map/zoom-slider';
import SdkMapReducer from '@boundlessgeo/sdk/reducers/map';
import * as mapActions from '@boundlessgeo/sdk/actions/map';
import RendererSwitch from '../rendererswitch';
// This will have webpack include all of the SDK styles.
import '@boundlessgeo/sdk/stylesheet/sdk.scss';
/* eslint-disable no-underscore-dangle */
const store = createStore(combineReducers({
map: SdkMapReducer,
}), window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
applyMiddleware(thunkMiddleware));
function main() {
// Start with a reasonable global view of the map.
store.dispatch(mapActions.setView([-93, 45], 2));
// add the TMS source
store.dispatch(mapActions.addSource('tms', {
type: 'raster',
scheme: 'tms',
tileSize: 256,
attribution: '<a href="http://mapbox.com">MapBox</a> | <a href="http://mapbox.com/tos">Terms of Service</a>',
maxzoom: 8,
tiles: [
'http://a.tiles.mapbox.com/v1/mapbox.geography-class/{z}/{x}/{y}.png',
'http://b.tiles.mapbox.com/v1/mapbox.geography-class/{z}/{x}/{y}.png',
'http://c.tiles.mapbox.com/v1/mapbox.geography-class/{z}/{x}/{y}.png',
'http://d.tiles.mapbox.com/v1/mapbox.geography-class/{z}/{x}/{y}.png',
],
}));
// add the TMS layer
store.dispatch(mapActions.addLayer({
id: 'geographyclass',
source: 'tms',
type: 'raster',
}));
// place the map on the page.
ReactDOM.render(<Provider store={store}>
<RendererSwitch>
<SdkZoomControl /><SdkZoomSlider />
</RendererSwitch>
</Provider>, document.getElementById('map'));
}
main();
|
src/index.dev.js | DeepBlueCLtd/lesco | import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import App from './App';
import {Provider} from 'react-redux';
import {syncHistoryWithStore} from 'react-router-redux';
import {browserHistory} from 'react-router';
import initialState from './reducers/initialState';
import configureStore from './store/configureStore.prod';
// store initialization
const store = configureStore(initialState);
// Create an enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore(browserHistory, store);
const rootEl = document.getElementById('root');
render(
<AppContainer>
<Provider store={store}>
<App history={history} store={store}/>
</Provider>
</AppContainer>,
rootEl
);
if (module.hot) {
module.hot.accept('./App', () => {
// If you use Webpack 2 in ES modules mode, you can
// use <App /> here rather than require() a <NextApp />.
const NextApp = require('./App').default;
render(
<AppContainer>
<Provider store={store}>
<NextApp history={history} store={store} />
</Provider>
</AppContainer>,
rootEl
);
});
} |
ui/star_wars/src/Ship.js | iporaitech/pwr2-docker | import React from 'react';
import Relay from 'react-relay';
class StarWarsShip extends React.Component {
render() {
const {ship} = this.props;
return <div>{ship.name}</div>;
}
}
export default Relay.createContainer(StarWarsShip, {
fragments: {
ship: () => Relay.QL`
fragment on Ship {
id,
name
}
`,
},
});
|
examples/js/custom/delete-button/fully-custom-delete-button.js | AllenFang/react-bootstrap-table | /* eslint max-len: 0 */
/* eslint no-unused-vars: 0 */
/* eslint no-alert: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
export default class FullyCustomDeleteButtonTable extends React.Component {
createCustomDeleteButton = (onBtnClick) => {
return (
<button style={ { color: 'red' } } onClick={ onBtnClick }>Delete it!!!</button>
);
}
render() {
const options = {
deleteBtn: this.createCustomDeleteButton
};
const selectRow = {
mode: 'checkbox'
};
return (
<BootstrapTable selectRow={ selectRow } data={ products } options={ options } deleteRow>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
client/modules/App/components/DevTools.js | lordknight1904/bigvnadmin | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor
toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-w"
>
<LogMonitor />
</DockMonitor>
);
|
example/examples/CustomOverlay.js | amitv87/react-native-maps | import React from 'react';
import {
StyleSheet,
View,
Dimensions,
} from 'react-native';
import MapView from 'react-native-maps';
import XMarksTheSpot from './CustomOverlayXMarksTheSpot';
const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
class CustomOverlay extends React.Component {
constructor(props) {
super(props);
this.state = {
region: {
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
},
coordinates: [
{
longitude: -122.442753,
latitude: 37.798790,
},
{
longitude: -122.424728,
latitude: 37.801232,
},
{
longitude: -122.422497,
latitude: 37.790651,
},
{
longitude: -122.440693,
latitude: 37.788209,
},
],
center: {
longitude: -122.4326648935676,
latitude: 37.79418561114521,
},
};
}
render() {
const { coordinates, center, region } = this.state;
return (
<View style={styles.container}>
<MapView
provider={this.props.provider}
style={styles.map}
initialRegion={region}
>
<XMarksTheSpot coordinates={coordinates} center={center} />
</MapView>
</View>
);
}
}
CustomOverlay.propTypes = {
provider: MapView.ProviderPropType,
};
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
...StyleSheet.absoluteFillObject,
},
});
module.exports = CustomOverlay;
|
fields/types/text/TextColumn.js | geminiyellow/keystone | import React from 'react';
import ItemsTableCell from '../../../admin/src/components/ItemsTableCell';
import ItemsTableValue from '../../../admin/src/components/ItemsTableValue';
var TextColumn = React.createClass({
displayName: 'TextColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
linkTo: React.PropTypes.string,
},
// cropping text is necessary for textarea, which uses this column
renderValue () {
let value = this.props.data.fields[this.props.col.path];
return value ? value.substr(0, 100) : null;
},
render () {
return (
<ItemsTableCell>
<ItemsTableValue href={this.props.linkTo} padded interior field={this.props.col.type}>
{this.renderValue()}
</ItemsTableValue>
</ItemsTableCell>
);
}
});
module.exports = TextColumn;
|
app/containers/Assessments/Assessments.js | klpdotorg/tada-frontend | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import isEmpty from 'lodash.isempty';
import { AssessmentTable } from '../../components/Assessments';
import {
getAssessments,
openDeactivateAssessmentsModal,
deactivateAssessments,
openDeleteAssessmentsModal,
deleteAssessments,
} from '../../actions';
class GetAssessments extends Component {
componentDidMount() {
const { programId } = this.props;
this.props.getAssessments(programId);
}
componentWillReceiveProps(nextProps) {
if (this.props.programId !== nextProps.programId) {
this.props.getAssessments(nextProps.programId);
}
}
render() {
return <AssessmentTable {...this.props} />;
}
}
GetAssessments.propTypes = {
getAssessments: PropTypes.func,
programId: PropTypes.number,
};
const mapStateToProps = (state) => {
const { selectedAssessments } = state.assessments;
const programId = state.programs.selectedProgram;
const assessments = Object.keys(state.assessments.assessments);
const { isAdmin, groups } = state.profile;
return {
programId: Number(programId),
assessments,
canEdit: isEmpty(selectedAssessments),
isAdmin,
groups,
};
};
const Assessments = connect(mapStateToProps, {
getAssessments,
openDeactivateAssessmentsModal,
deactivateAssessments,
openDeleteAssessmentsModal,
deleteAssessments,
})(GetAssessments);
export default Assessments;
|
client/components/surveys/results/ResultsPage.js | AnatolyBelobrovik/itechartlabs | import React from 'react';
import PropTypes from 'prop-types';
import ResultsSummary from './summary/ResultsSummary';
import ResultsIndividual from './individual/ResultsIndividual';
import classnames from 'classnames';
const ResultsPage = ({ id, currentPage, showSummary, answers, totalAnswers, questions, hasMandatoryLabel, showIndividualResponse }) => {
return (
<div id={'page' + id}
className={classnames('tab-pane fade in',
{ 'active': id === currentPage })}
>
{showSummary
?
<ResultsSummary
answers={answers}
questions={questions}
hasMandatoryLabel={hasMandatoryLabel}
totalAnswers={totalAnswers}
showIndividualResponse={showIndividualResponse}
/>
:
<ResultsIndividual
answers={answers}
questions={questions}
hasMandatoryLabel={hasMandatoryLabel}
/>}
</div>
);
};
ResultsPage.propTypes = {
id: PropTypes.number.isRequired,
totalAnswers: PropTypes.number.isRequired,
showSummary: PropTypes.bool.isRequired,
showIndividualResponse: PropTypes.func.isRequired,
currentPage: PropTypes.number.isRequired,
answers: PropTypes.array.isRequired,
questions: PropTypes.array.isRequired,
hasMandatoryLabel: PropTypes.bool.isRequired,
};
export default ResultsPage;
|
src/components/RadioInput.js | andresilveira/stendebach_pillows | import React from 'react';
import Input from './Input';
import '../bootstrap.min.css'
const RadioInput = ({ label, ...inputProps}) => (
<div className="form-check">
<label className="form-check-label">
<Input className="form-check-input" type="radio" {...inputProps} /> { label || inputProps.value }
</label>
</div>
)
export default RadioInput;
|
src/svg-icons/editor/vertical-align-bottom.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorVerticalAlignBottom = (props) => (
<SvgIcon {...props}>
<path d="M16 13h-3V3h-2v10H8l4 4 4-4zM4 19v2h16v-2H4z"/>
</SvgIcon>
);
EditorVerticalAlignBottom = pure(EditorVerticalAlignBottom);
EditorVerticalAlignBottom.displayName = 'EditorVerticalAlignBottom';
EditorVerticalAlignBottom.muiName = 'SvgIcon';
export default EditorVerticalAlignBottom;
|
src/components/app.js | abramin/reduxStarter | import React, { Component } from 'react';
export default class App extends Component {
render() {
return (
<div className='foo'>React simple starter</div>
);
}
}
|
addons/docs/src/frameworks/react/__testfixtures__/8428-js-static-prop-types/input.js | kadirahq/react-storybook | import React from 'react';
import PropTypes from 'prop-types';
// eslint-disable-next-line react/prefer-stateless-function
export default class Test extends React.Component {
static propTypes = {
/**
* Please work...
*/
test: PropTypes.string,
};
render() {
return <div>test</div>;
}
}
export const component = Test;
|
packages/wix-style-react/src/TableToolbar/TableToolbar.js | wix/wix-style-react | import React from 'react';
import PropTypes from 'prop-types';
import { Toolbar, ItemGroup, Item, Label, Divider } from './Toolbar';
import Heading from '../Heading';
import Text from '../Text';
export const Title = props => {
const { dataHook } = props;
return (
<Heading dataHook={dataHook} appearance="H3">
{props.children}
</Heading>
);
};
Title.displayName = 'TableToolbar.Title';
Title.propTypes = {
children: PropTypes.node,
dataHook: PropTypes.string,
};
export const SelectedCount = props => {
const { dataHook } = props;
return (
<Text dataHook={dataHook} weight="normal" size="medium">
{props.children}
</Text>
);
};
SelectedCount.displayName = 'TableToolbar.SelectedCount';
SelectedCount.propTypes = {
children: PropTypes.node,
dataHook: PropTypes.string,
};
export const TableToolbar = Toolbar;
// Aliases for convenience
TableToolbar.ItemGroup = ItemGroup;
TableToolbar.Item = Item;
TableToolbar.Label = Label;
TableToolbar.SelectedCount = SelectedCount;
TableToolbar.Title = Title;
TableToolbar.Divider = Divider;
|
src/svg-icons/content/create.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentCreate = (props) => (
<SvgIcon {...props}>
<path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/>
</SvgIcon>
);
ContentCreate = pure(ContentCreate);
ContentCreate.displayName = 'ContentCreate';
ContentCreate.muiName = 'SvgIcon';
export default ContentCreate;
|
src/components/topic/summary/export/DownloadMapFilesContainer.js | mitmedialab/MediaCloud-Web-Tools | import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import withFilteredAsyncData from '../../FilteredAsyncDataContainer';
import { fetchTopicMapFiles } from '../../../../actions/topicActions';
import DownloadMapFiles from './DownloadMapFiles';
const DownloadMapFilesContainer = ({ filters, files }) => (
<DownloadMapFiles filters={filters} files={files} />
);
DownloadMapFilesContainer.propTypes = {
// from parent
filters: PropTypes.object.isRequired,
topicId: PropTypes.number.isRequired,
// from state
fetchStatus: PropTypes.string.isRequired,
files: PropTypes.array,
};
const mapStateToProps = state => ({
fetchStatus: state.topics.selected.summary.mapFiles.fetchStatus,
files: state.topics.selected.summary.mapFiles.timespan_maps,
});
const fetchAsyncData = (dispatch, props) => {
dispatch(fetchTopicMapFiles(props.topicId, props.filters));
};
export default
connect(mapStateToProps)(
withFilteredAsyncData(fetchAsyncData)(
DownloadMapFilesContainer
)
);
|
ui/src/components/RollupRuleEditor.js | m3db/m3ctl | // Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import {Button, Input, Form, Icon, Select, Card, Tag} from 'antd';
import {toClass} from 'recompose';
import _ from 'lodash';
import {withFormik} from 'formik';
import * as util from 'utils';
import PoliciesEditor from './PolicyEditor';
import {filterPoliciesBasedOnTag} from 'utils';
import {getHelpText} from 'utils/helpText';
import HelpTooltip from './HelpTooltip';
// @TODO Move to config service
const REQUIRED_TAGS = ['dc', 'env', 'service', 'type'];
const FormItem = Form.Item;
const formItemLayout = {
labelCol: {
xs: {span: 24},
sm: {span: 4},
},
wrapperCol: {
xs: {span: 24},
sm: {span: 18},
},
};
function removeRequiredTags(tags, requiredTags) {
return _.filter(tags, t => !_.includes(requiredTags, t));
}
function addRequiredTags(tags, requiredTags) {
return _.concat(tags, requiredTags);
}
function RollupRuleEditor({values, handleChange, handleSubmit, setFieldValue}) {
const typeTag = util.getTypeTag(values.filter);
return (
<Form onSubmit={handleSubmit}>
<div className="clearfix">
<div className="col col-12 px1">
<FormItem
required
colon={false}
label="Rule Name"
{...formItemLayout}>
<Input
name="name"
autoComplete="off"
value={values.name}
onChange={handleChange}
/>
</FormItem>
</div>
<div className="col col-12 px1">
<FormItem
required
colon={false}
label="Metric Filter"
help={getHelpText('metric-filter')}
{...formItemLayout}>
<Input
name="filter"
autoComplete="off"
value={values.filter}
onChange={e => {
const newTypeTag = util.getTypeTag(e.target.value);
const targets = _.map(values.targets, t => ({
...t,
policies: filterPoliciesBasedOnTag(t.policies, newTypeTag),
}));
setFieldValue('target', targets);
handleChange(e);
}}
/>
</FormItem>
</div>
<div className="col col-12 px1">
<FormItem
required
label={
<span>
Targets <HelpTooltip helpTextKey="target" />
</span>
}
colon={false}
{...formItemLayout}>
<TargetsEditor
typeTag={typeTag}
value={values.targets}
onChange={e => setFieldValue('targets', e)}
/>
</FormItem>
</div>
<div className="clearfix my2">
<Button type="primary" htmlType="submit" className="right">
Add
</Button>
</div>
</div>
</Form>
);
}
const TargetsEditorBase = props => {
const {value: targets = [], onChange, typeTag} = props;
const handleChange = (index, property, newValue) => {
targets[index][property] = newValue;
onChange(targets);
};
return (
<div>
{_.isEmpty(targets) && <div>No targets</div>}
{_.map(targets, (t, i) => {
return (
<Card
className="mb1"
key={i}
title={t.name}
extra={
<a
onClick={() => {
onChange(_.filter(targets, (__, index) => index !== i));
}}>
<Icon type="delete" />
</a>
}>
<label className="mb1">Rollup Metric Name</label>
<Input
className="mb2"
value={t.name}
onChange={e => handleChange(i, 'name', e.target.value)}
/>
<label>
Rollup Tags <HelpTooltip helpTextKey="rollup-tag" />
</label>
<div className="mb2">
{_.map(REQUIRED_TAGS, requiredTag => <Tag>{requiredTag}</Tag>)}
<Select
className="inline-block"
placeholder="Additional Tags"
style={{minWidth: 200, width: 'inherit'}}
onChange={e =>
handleChange(i, 'tags', addRequiredTags(e, REQUIRED_TAGS))}
value={removeRequiredTags(t.tags, REQUIRED_TAGS)}
autoComplete="off"
mode="tags"
tokenSeparators={[',']}
notFoundContent={false}
/>
</div>
<label>
Policies <HelpTooltip helpTextKey="policy" />
</label>
<PoliciesEditor
typeTag={typeTag}
value={t.policies}
onChange={e => handleChange(i, 'policies', e)}
/>
</Card>
);
})}
<Button
type="dashed"
onClick={() =>
onChange(targets.concat({name: '', tags: [], policies: []}))}>
Add Target
</Button>
</div>
);
};
const TargetsEditor = toClass(TargetsEditorBase);
export default withFormik({
enableReinitialize: true,
mapPropsToValues: ({rollupRule}) => {
return rollupRule || {};
},
handleSubmit: (values, {props}) => {
props.onSubmit({
...values,
targets: _.map(values.targets, target => {
return {
...target,
tags: _.union(target.tags, REQUIRED_TAGS),
};
}),
});
},
})(RollupRuleEditor);
|
src/components/multiple.js | cyranosky/rrtimes_hlj | import React from 'react'
import PropTypes from 'prop-types'
const multiple = ({onAChange, onBChange, a, b, c}) => (
<div>
<input onChange={onAChange} value={a} />
*
<input onChange={onBChange} value={b} />
=
<input value={c} />
</div>
)
export default multiple
|
src/routes/chart/Container.js | shaohuawang2015/goldbeans-admin | import React from 'react'
import PropTypes from 'prop-types'
import styles from './Container.less'
import { ResponsiveContainer } from 'recharts'
const Container = ({ children, ratio = 5 / 2, minHeight = 250, maxHeight = 350 }) => <div className={styles.container} style={{ minHeight, maxHeight }}>
<div style={{ marginTop: `${100 / ratio}%` || '100%' }}></div>
<div className={styles.content} style={{ minHeight, maxHeight }}>
<ResponsiveContainer>
{children}
</ResponsiveContainer>
</div>
</div>
Container.propTypes = {
children: PropTypes.element.isRequired,
ratio: PropTypes.number,
minHeight: PropTypes.number,
maxHeight: PropTypes.number,
}
export default Container
|
webapp/src/Congratulation.js | gocaine/go-dart | import React from 'react';
const Congratulation = ({game, player}) => {
if (game.Ongoing == 4) {
return (
<div className="card horizontal">
<div className="card-stacked">
<div className="card-content">
Congratulations {player.Name}
</div>
</div>
</div>
)
}
}
export default Congratulation; |
web/static/js/components/mainform.js | ottolin/txportal | import React from 'react';
import {connect} from 'react-redux';
import {mainformTabSelected} from '../actions/mainform';
// UI
import Navbar from 'react-bootstrap/lib/Navbar';
import NavItem from 'react-bootstrap/lib/NavItem';
import NavDropdown from 'react-bootstrap/lib/NavDropdown';
import Nav from 'react-bootstrap/lib/Nav';
import MenuItem from 'react-bootstrap/lib/MenuItem';
import TxtResultList from "./txt_result_list";
import Butter from "./butter";
import Worker from './worker';
import Scheduler from "./scheduler/scheduler.js";
// CSS
import '../../css/mainform.css';
class MainForm extends React.Component{
constructor(props) {
super(props);
}
componentDidMount() {
}
handleSelect(key) {
this.props.dispatch(mainformTabSelected(key));
}
render() {
var content = <div/>;
switch(this.props.activePageId) {
case 1:
content = <TxtResultList/>;
break;
case 2:
content = <Butter/>;
break;
case 3:
content = <Scheduler/>;
break;
default:
content = <div/>;
break;
}
return (
<div>
<Navbar brand="Tx Portal" activeKey={this.props.activePageId} fixedTop={true} fluid={true}>
<Nav>
<NavDropdown eventKey={1} title="TXT" id="txt-dropdown">
<MenuItem eventKey="1.1" href="javascript:void(0);" onSelect={this.handleSelect.bind(this, 1)}>Results</MenuItem>
<MenuItem eventKey="1.2">Statistics</MenuItem>
<MenuItem eventKey="1.3" href="javascript:void(0);" onSelect={this.handleSelect.bind(this, 3)}>Scheduler</MenuItem>
</NavDropdown>
<NavDropdown eventKey={2} title="Butter" id="butter-dropdown">
<MenuItem eventKey="2.1" href="javascript:void(0);" onSelect={this.handleSelect.bind(this, 2)}>Results</MenuItem>
<MenuItem eventKey="2.2">Workers</MenuItem>
</NavDropdown>
</Nav>
</Navbar>
<div className='portal-content'> {content} </div>
</div>
)
}
}
function select(state) {
return state.mainform;
}
export default connect(select)(MainForm);
|
node_modules/react-router/es/MemoryRouter.js | amiechen/amiechen.github.io | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import warning from 'warning';
import React from 'react';
import PropTypes from 'prop-types';
import createHistory from 'history/createMemoryHistory';
import Router from './Router';
/**
* The public API for a <Router> that stores location in memory.
*/
var MemoryRouter = function (_React$Component) {
_inherits(MemoryRouter, _React$Component);
function MemoryRouter() {
var _temp, _this, _ret;
_classCallCheck(this, MemoryRouter);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.history = createHistory(_this.props), _temp), _possibleConstructorReturn(_this, _ret);
}
MemoryRouter.prototype.componentWillMount = function componentWillMount() {
warning(!this.props.history, '<MemoryRouter> ignores the history prop. To use a custom history, ' + 'use `import { Router }` instead of `import { MemoryRouter as Router }`.');
};
MemoryRouter.prototype.render = function render() {
return React.createElement(Router, { history: this.history, children: this.props.children });
};
return MemoryRouter;
}(React.Component);
MemoryRouter.propTypes = {
initialEntries: PropTypes.array,
initialIndex: PropTypes.number,
getUserConfirmation: PropTypes.func,
keyLength: PropTypes.number,
children: PropTypes.node
};
export default MemoryRouter; |
src/Header/Header.js | aTseniklidou/Randix-Game | import React from 'react';
import { IndexLink, Link } from 'react-router';
import classes from './Header.scss';
import Soundtrack from 'components/Game/assets/Wallpaper.mp3';
import { styles } from './Styles';
import VolumeOn from 'material-ui/svg-icons/AV/volume-up';
import VolumeOff from 'material-ui/svg-icons/AV/volume-off';
import TwoPlayer from 'material-ui/svg-icons/Social/people';
import Computer from 'material-ui/svg-icons/Hardware/computer';
import Online from 'material-ui/svg-icons/Social/public';
import Rules from 'material-ui/svg-icons/AV/library-books';
import About from 'material-ui/svg-icons/Editor/mode-edit';
import { Tabs, Tab } from 'material-ui';
import 'bootstrap/dist/css/bootstrap.css';
let isMuted = false;
const ostPlayPause = (sound) => {
if (isMuted) {
sound.play();
} else {
sound.pause();
}
isMuted = !isMuted;
};
export const Header = () => {
return (
<div>
<h1 className={classes.title}>Randix!</h1>
<audio id='ost' loop src={Soundtrack} />
<Tabs tabItemContainerStyle={styles.tab} value={window.location.pathname}>
<Tab
value='/Randix-Game/'
style={styles.tab}
icon={<Rules />}
label="Rules"
containerElement={<IndexLink style={styles.tab} to="/Randix-Game/" />}
/>
<Tab
value='/Randix-Game/Online'
style={styles.tab}
icon={<Online />}
label="Online Mode"
containerElement={<Link style={styles.tab} to="/Randix-Game/Online" />}
/>
<Tab
value='/Randix-Game/TwoPlayer'
style={styles.tab}
icon={<TwoPlayer />}
label="VS Player"
containerElement={<Link style={styles.tab} to="/Randix-Game/TwoPlayer" />}
/>
<Tab
value='/Randix-Game/vsComp'
style={styles.tab}
icon={<Computer />}
label="VS Computer"
containerElement={<Link style={styles.tab} to="/Randix-Game/vsComp" />}
/>
<Tab
value='/Randix-Game/about'
style={styles.tab}
icon={<About />}
label="About"
containerElement={<Link style={styles.tab} to="/Randix-Game/about" />}
/>
<Tab
style={styles.tab}
value='sound'
icon={<VolumeOn />}
label="Sound On/Off"
onClick = {() => ostPlayPause(document.getElementById('ost'))}
/>
</Tabs>
</div>
);
};
export default Header;
|
index.ios.js | vinicius-ov/Livefy | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TextInput,
ListView,
Button,
ActivityIndicator,
Image,
TouchableHighlight,
Alert
} from 'react-native';
export default class Livefyy extends Component {
constructor(props) {
super(props);
this.state = { dataSource: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }),
loaded: false,
videoId: 'PPlgwo0bfQk',
queryTerm: 'paramore',};
}
_getVideosByQueryTerm() {
if (this.state.queryTerm === ''){
Alert.alert('Busca vazia!');
}else{
this._performSearch();
}
}
_performArtistSearch(){
this.state.isLoading = true;
fetch('https://www.googleapis.com/youtube/v3/search?part=id,snippet&q='+this.state.queryTerm+',full,live&maxResults=20&key=AIzaSyCdgUFUubI6tRilTsqKghw18gig7Dri3dE')
.then((response) => response.json())
.then((responseJson) => {
this.setState({ dataSource: this.state.dataSource.cloneWithRows(responseJson.items),
loaded: true, });
})
.catch((error) => {
Alert.alert('error');
});
}
_performVideoSearch(rowData){
this.state.isLoading = true;
//aqui vai a chamada para o backend no mundo ideal
fetch('https://www.googleapis.com/youtube/v3/videos?part=snippet&id='+ rowData.id.videoId +'&key=AIzaSyCdgUFUubI6tRilTsqKghw18gig7Dri3dE')
.then((response) => response.json())
.then((responseJson) => {
//parse description for timestamps
let result = responseJson.items[0].snippet;
let desc = result.description;
let parts = desc.split('\n');
let list = [];
let i;
for (i in parts){
let patt = new RegExp("([0-9]{2}:)?[0-9]{2}:[0-9]{2}");
let res = /([0-9]{0,2}:)?[0-9]{2}:[0-9]{2}/.exec(parts[i]); //here goes time as (hh:)mm:ss
//let res = patt.exec(parts[i]);
for (eachItem in res){
console.log(res[eachItem]);
}
}
//Alert.alert(res)
})
.catch((error) => {
Alert.alert(JSON.stringify(error));
});
}
render() {
return (
<View >
<View style={{flexDirection:'row', alignSelf:'center', paddingTop:40, paddingBottom:20}}>
<TextInput
style={styles.textInput}
onChangeText={(queryTerm) => this.setState({queryTerm})}
value={this.state.queryTerm}
placeholder = 'Buscar artista aqui'
/>
<Button
title='Buscar'
onPress={() => this._performArtistSearch()}
/>
</View>
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) =>
<TouchableHighlight
underlayColor='#ffc299'
onPress={() => {
//console.log(videoId);
//console.log(rowData.id.videoId);
//this.setState({videoId});
this._performVideoSearch(rowData);
}} >
<View style={{flexDirection:'row', paddingTop: 10, paddingLeft:10, paddingBottom: 10}}>
<Image
style={{width: 120, height: 90}}
source={{uri: rowData.snippet.thumbnails.medium.url}}
/>
<Text style={{paddingLeft: 10}}>
{rowData.snippet.title}
</Text>
</View>
</TouchableHighlight>
} //renderRow
/>
</View> //master view
);
} //render
} //class
const styles = StyleSheet.create({
textInput: {
height: 40,
width: 280,
borderColor: 'gray',
borderWidth: 2,
}
});
AppRegistry.registerComponent('Livefyy', () => Livefyy);
|
src/components/detail/index.js | lopesdasilva/trakt-it | /* Components */
import React, { Component } from 'react';
import { Container, Header, Title, Content, Card, CardItem, Icon, Button } from 'native-base';
import ReactNative, {
StyleSheet,
View,
Text,
ListView,
Image
} from 'react-native';
var ResponsiveImage = require('react-native-responsive-image');
/* Constants */
import Dimensions from 'Dimensions';
let windowWidth = Dimensions.get('window').width;
let windowHeight = Dimensions.get('window').height;
module.exports = React.createClass({
getInitialState(){
console.log(this.props.navigator.navigationContext.currentRoute.data);
return{
data: this.props.navigator.navigationContext.currentRoute.data
};
},
/* Renderizacao do view completo */
render() {
return (
<Container>
<Header>
<Button transparent onPress={() => {this.props.navigator.pop()}}>
<Icon name='ios-arrow-back' />
</Button>
<Title>{this.state.data.title}</Title>
</Header>
<Content>
<View>
{ this.renderDetail() }
</View>
</Content>
</Container>
)
},
/* Renderizacao do detalhe*/
renderDetail(){
return(
<CardItem cardBody>
<Image style={{ resizeMode: 'cover' }} source={{uri: this.state.data.images.fanart.full,
initWidth: windowWidth,
initHeight: windowHeight/3}} />
<Text>
{this.state.data.title}
</Text>
<Button transparent textStyle={{color: '#87838B'}}>
<Text>{this.state.data.rating} Stars</Text>
</Button>
</CardItem>
);
},
});
/*
* ESTILOS
*/
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#EEE'
},
imageContainer: {
flex: 1,
backgroundColor: '#EEE'
},
detailContainer: {
flex: 3,
backgroundColor: '#EEE'
}
});
|
front_end/front_end_app/src/server/frontend/render.js | Horizon-Framework/horizon | import DocumentTitle from 'react-document-title';
import Html from './html.react';
import Promise from 'bluebird';
import React from 'react';
import Router from 'react-router';
import config from '../config';
import immutable from 'immutable';
import initialState from '../initialstate';
import routes from '../../client/routes';
import stateMerger from '../lib/merger';
import useragent from 'useragent';
export default function render(req, res, ...customStates) {
const appState = immutable.fromJS(initialState).mergeWith(stateMerger, ...customStates).toJS();
return renderPage(req, res, appState);
}
function renderPage(req, res, appState) {
return new Promise((resolve, reject) => {
const router = Router.create({
routes,
location: req.originalUrl,
onError: reject,
onAbort: (abortReason) => {
// Some requireAuth higher order component requested redirect.
if (abortReason.constructor.name === 'Redirect') {
const {to, params, query} = abortReason;
const path = router.makePath(to, params, query);
res.redirect(path);
resolve();
return;
}
reject(abortReason);
}
});
router.run((Handler, routerState) => {
const ua = useragent.is(req.headers['user-agent']);
const html = getPageHtml(Handler, appState, {
hostname: req.hostname,
// TODO: Remove once Safari and IE without Intl will die.
needIntlPolyfill: ua.safari || (ua.ie && ua.version < '11')
});
const notFound = routerState.routes.some(route => route.name === 'not-found');
const status = notFound ? 404 : 200;
res.status(status).send(html);
resolve();
});
});
}
function getPageHtml(Handler, appState, {hostname, needIntlPolyfill}) {
const appHtml = `<div id="app">${
React.renderToString(<Handler initialState={appState} />)
}</div>`;
const appScriptSrc = config.isProduction
? '/build/app.js?v=' + config.version
: `//${hostname}:8888/build/app.js`;
let scriptHtml = '';
if (needIntlPolyfill) {
scriptHtml += `
<script src="/node_modules/intl/dist/Intl.min.js"></script>
<script src="/node_modules/intl/locale-data/jsonp/en-US.js"></script>`;
}
scriptHtml += `
<script>
window._initialState = ${JSON.stringify(appState)};
</script>
<script src="${appScriptSrc}"></script>
`;
if (config.isProduction && config.googleAnalyticsId !== 'UA-XXXXXXX-X')
scriptHtml += `
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','${config.googleAnalyticsId}');ga('send','pageview');
</script>`;
const title = DocumentTitle.rewind();
return '<!DOCTYPE html>' + React.renderToStaticMarkup(
<Html
bodyHtml={appHtml + scriptHtml}
isProduction={config.isProduction}
title={title}
version={config.version}
/>
);
}
|
sms_sponsorship/webapp/src/components/ChildDetails.js | ecino/compassion-modules | import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import ListItem from '@material-ui/core/ListItem';
import ChildDescription from './ChildDescription';
import Collapse from '@material-ui/core/Collapse';
import ExpandLess from '@material-ui/icons/ExpandLess';
import ExpandMore from '@material-ui/icons/ExpandMore';
import Typography from '@material-ui/core/Typography';
const styles = {
root: {
width: '100%',
},
};
class NestedList extends React.Component {
state = { open: false };
handleClick = () => {
this.setState(state => ({ open: !state.open }));
};
render() {
const { classes, t } = this.props;
return (
<div className={classes.root}>
<ListItem button onClick={this.handleClick} style={{backgroundColor: '#0054A6', color: 'white', justifyContent: 'center'}}>
{/*<ListItemText primary="More details" />*/}
<Typography variant="button" style={{color: 'white'}}>{t('more')}</Typography>
{this.state.open ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Collapse in={this.state.open} timeout="auto" unmountOnExit>
<ChildDescription appContext={this.props.appContext}/>
</Collapse>
</div>
);
}
}
NestedList.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(NestedList);
|
imports/ui/layouts/App.js | KyneSilverhide/expense-manager | import React from 'react';
import injectTapEventPlugin from 'react-tap-event-plugin';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import createPalette from 'material-ui/styles/palette';
import createMuiTheme from 'material-ui/styles/theme';
import { green, brown, red } from 'material-ui/styles/colors';
import Grid from 'material-ui/Grid';
import AppNavigation from '../containers/AppNavigation.js';
injectTapEventPlugin();
const palette = createPalette({
primary: brown,
accent: green,
erorr: red,
type: 'light',
});
const { styleManager, theme } = MuiThemeProvider.createDefaultContext({
theme: createMuiTheme({ palette }),
});
const App = ({ children }) => (
<MuiThemeProvider theme={theme} styleManager={styleManager}>
<Grid container>
<AppNavigation />
<Grid id="app-content" item xs={12}>
{children}
</Grid>
</Grid>
</MuiThemeProvider>
);
App.propTypes = {
children: React.PropTypes.node,
};
export default App;
|
src/utils/index.js | brancusi/lingo-client-react | import React from 'react';
import ReactDOM from 'react-dom';
import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react';
export function createConstants (...constants) {
return constants.reduce((acc, constant) => {
acc[constant] = constant;
return acc;
}, {});
}
export function createReducer (initialState, reducerMap) {
return (state = initialState, action) => {
const reducer = reducerMap[action.type];
return reducer ? reducer(state, action.payload) : state;
};
}
export function createDevToolsWindow (store) {
const win = window.open(
null,
'redux-devtools', // give it a name so it reuses the same window
'menubar=no,location=no,resizable=yes,scrollbars=no,status=no'
);
// reload in case it's reusing the same window with the old content
win.location.reload();
// wait a little bit for it to reload, then render
setTimeout(() => {
// Wait for the reload to prevent:
// "Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element."
win.document.write('<div id="react-devtools-root"></div>');
ReactDOM.render(
<DebugPanel top right bottom left key="debugPanel" >
<DevTools store={store} monitor={LogMonitor} />
</DebugPanel>
, win.document.getElementById('react-devtools-root'));
}, 10);
}
|
react-release/dominion-js/src/index.js | ExplosiveHippo/Dominion.js | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
src/svg-icons/action/accessibility.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAccessibility = (props) => (
<SvgIcon {...props}>
<path d="M12 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 7h-6v13h-2v-6h-2v6H9V9H3V7h18v2z"/>
</SvgIcon>
);
ActionAccessibility = pure(ActionAccessibility);
ActionAccessibility.displayName = 'ActionAccessibility';
export default ActionAccessibility;
|
front_end/front_end_app/src/client/lib/validation.js | Horizon-Framework/horizon | /*
Simple serial sync/async chriso/validator.js validation wrapper with promises.
*/
import Promise from 'bluebird';
import React from 'react';
import validator from 'validator';
export class ValidationError extends Error {
constructor(message, prop) {
super();
this.message = message;
this.prop = prop;
}
}
export function focusInvalidField(component) {
return (error) => {
if (error instanceof ValidationError) {
if (!error.prop) return;
const node = React.findDOMNode(component);
if (!node) return;
const el = node.querySelector(`[name=${error.prop}]`);
if (!el) return;
el.focus();
return;
}
throw error;
};
}
export default class Validation {
constructor(object) {
this._object = object;
this._prop = null;
this._validator = validator;
this.promise = Promise.resolve();
}
custom(callback, {required} = {}) {
const prop = this._prop;
const value = this._object[prop];
const object = this._object;
this.promise = this.promise.then(() => {
if (required && !this._isEmptyString(value)) return;
callback(value, prop, object);
});
return this;
}
_isEmptyString(value) {
return !this._validator.toString(value).trim();
}
prop(prop) {
this._prop = prop;
return this;
}
required(getRequiredMessage) {
return this.custom((value, prop) => {
const msg = getRequiredMessage
? getRequiredMessage(prop, value)
: this.getRequiredMessage(prop, value);
throw new ValidationError(msg, prop);
}, {required: true});
}
getRequiredMessage(prop, value) {
return `Please fill out '${prop}' field.`;
}
email() {
return this.custom((value, prop) => {
if (this._validator.isEmail(value)) return;
throw new ValidationError(
this.getEmailMessage(prop, value),
prop
);
});
}
getEmailMessage() {
return `Email address is not valid.`;
}
simplePassword() {
return this.custom((value, prop) => {
const minLength = 5;
if (value.length >= minLength) return;
throw new ValidationError(
this.getSimplePasswordMessage(minLength),
prop
);
});
}
getSimplePasswordMessage(minLength) {
return `Password must contain at least ${minLength} characters.`;
}
}
|
src/pages/tree/Searchtree/Searchtree.js | hyy1115/react-redux-webpack2 | import React from 'react'
class Searchtree extends React.Component {
render() {
return (
<div>Searchtree</div>
)
}
}
export default Searchtree |
src/icons/font/AttachmentIcon.js | skystebnicki/chamel | import React from 'react';
import PropTypes from 'prop-types';
import FontIcon from '../../FontIcon';
import ThemeService from '../../styles/ChamelThemeService';
/**
* Attachment button
*
* @param props
* @param context
* @returns {ReactDOM}
* @constructor
*/
const AttachmentIcon = (props, context) => {
let theme =
context.chamelTheme && context.chamelTheme.fontIcon
? context.chamelTheme.fontIcon
: ThemeService.defaultTheme.fontIcon;
return (
<FontIcon {...props} className={theme.iconAttachment}>
{'attachment'}
</FontIcon>
);
};
/**
* An alternate theme may be passed down by a provider
*/
AttachmentIcon.contextTypes = {
chamelTheme: PropTypes.object,
};
export default AttachmentIcon;
|
app/javascript/mastodon/components/column.js | alarky/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import scrollTop from '../scroll';
export default class Column extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
};
scrollTop () {
const scrollable = this.node.querySelector('.scrollable');
if (!scrollable) {
return;
}
this._interruptScrollAnimation = scrollTop(scrollable);
}
handleWheel = () => {
if (typeof this._interruptScrollAnimation !== 'function') {
return;
}
this._interruptScrollAnimation();
}
setRef = c => {
this.node = c;
}
render () {
const { children } = this.props;
return (
<div role='region' className='column' ref={this.setRef} onWheel={this.handleWheel}>
{children}
</div>
);
}
}
|
src/svg-icons/notification/sync-problem.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationSyncProblem = (props) => (
<SvgIcon {...props}>
<path d="M3 12c0 2.21.91 4.2 2.36 5.64L3 20h6v-6l-2.24 2.24C5.68 15.15 5 13.66 5 12c0-2.61 1.67-4.83 4-5.65V4.26C5.55 5.15 3 8.27 3 12zm8 5h2v-2h-2v2zM21 4h-6v6l2.24-2.24C18.32 8.85 19 10.34 19 12c0 2.61-1.67 4.83-4 5.65v2.09c3.45-.89 6-4.01 6-7.74 0-2.21-.91-4.2-2.36-5.64L21 4zm-10 9h2V7h-2v6z"/>
</SvgIcon>
);
NotificationSyncProblem = pure(NotificationSyncProblem);
NotificationSyncProblem.displayName = 'NotificationSyncProblem';
NotificationSyncProblem.muiName = 'SvgIcon';
export default NotificationSyncProblem;
|
app/javascript/mastodon/components/status_action_bar.js | ambition-vietnam/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import IconButton from './icon_button';
import DropdownMenuContainer from '../containers/dropdown_menu_container';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { me } from '../initial_state';
const messages = defineMessages({
delete: { id: 'status.delete', defaultMessage: 'Delete' },
edit: {id: 'status.edit', defaultMessage: 'Edit'},
mention: { id: 'status.mention', defaultMessage: 'Mention @{name}' },
mute: { id: 'account.mute', defaultMessage: 'Mute @{name}' },
block: { id: 'account.block', defaultMessage: 'Block @{name}' },
reply: { id: 'status.reply', defaultMessage: 'Reply' },
share: { id: 'status.share', defaultMessage: 'Share' },
more: { id: 'status.more', defaultMessage: 'More' },
replyAll: { id: 'status.replyAll', defaultMessage: 'Reply to thread' },
reblog: { id: 'status.reblog', defaultMessage: 'Boost' },
cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be boosted' },
favourite: { id: 'status.favourite', defaultMessage: 'Favourite' },
open: { id: 'status.open', defaultMessage: 'Expand this status' },
report: { id: 'status.report', defaultMessage: 'Report @{name}' },
muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' },
unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' },
pin: { id: 'status.pin', defaultMessage: 'Pin on profile' },
unpin: { id: 'status.unpin', defaultMessage: 'Unpin from profile' },
embed: { id: 'status.embed', defaultMessage: 'Embed' },
translate: { id: 'status.translate', defaultMessage: 'Translate' },
});
@injectIntl
export default class StatusActionBar extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
onReply: PropTypes.func,
onFavourite: PropTypes.func,
onReblog: PropTypes.func,
onEdit: PropTypes.func,
onDelete: PropTypes.func,
onMention: PropTypes.func,
onMute: PropTypes.func,
onBlock: PropTypes.func,
onReport: PropTypes.func,
onEmbed: PropTypes.func,
onMuteConversation: PropTypes.func,
onPin: PropTypes.func,
onTranslate: PropTypes.func,
withDismiss: PropTypes.bool,
intl: PropTypes.object.isRequired,
};
// Avoid checking props that are functions (and whose equality will always
// evaluate to false. See react-immutable-pure-component for usage.
updateOnProps = [
'status',
'withDismiss',
]
handleReplyClick = () => {
this.props.onReply(this.props.status, this.context.router.history);
}
handleShareClick = () => {
navigator.share({
text: this.props.status.get('search_index'),
url: this.props.status.get('url'),
});
}
handleFavouriteClick = () => {
this.props.onFavourite(this.props.status);
}
handleReblogClick = (e) => {
this.props.onReblog(this.props.status, e);
}
handleEditClick = () => {
this.props.onEdit(this.props.status, this.context.router.history);
}
handleDeleteClick = () => {
this.props.onDelete(this.props.status);
}
handlePinClick = () => {
this.props.onPin(this.props.status);
}
handleMentionClick = () => {
this.props.onMention(this.props.status.get('account'), this.context.router.history);
}
handleMuteClick = () => {
this.props.onMute(this.props.status.get('account'));
}
handleBlockClick = () => {
this.props.onBlock(this.props.status.get('account'));
}
handleOpen = () => {
this.context.router.history.push(`/statuses/${this.props.status.get('id')}`);
this.props.onReply(this.props.status, this.context.router.history);
}
handleEmbed = () => {
this.props.onEmbed(this.props.status);
}
handleReport = () => {
this.props.onReport(this.props.status);
}
handleConversationMuteClick = () => {
this.props.onMuteConversation(this.props.status);
}
handleTranslateClick = () => {
this.props.onTranslate(this.props.status);
}
render () {
const { status, intl, withDismiss } = this.props;
const mutingConversation = status.get('muted');
const anonymousAccess = !me;
const publicStatus = ['public', 'unlisted'].includes(status.get('visibility'));
let menu = [];
let reblogIcon = 'retweet';
let replyIcon;
let replyTitle;
menu.push({ text: intl.formatMessage(messages.open), action: this.handleOpen });
menu.push({ text: intl.formatMessage(messages.translate), action: this.handleTranslateClick });
if (publicStatus) {
menu.push({ text: intl.formatMessage(messages.embed), action: this.handleEmbed });
}
menu.push(null);
if (status.getIn(['account', 'id']) === me || withDismiss) {
menu.push({ text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMuteClick });
menu.push(null);
}
if (status.getIn(['account', 'id']) === me) {
if (publicStatus) {
menu.push({ text: intl.formatMessage(status.get('pinned') ? messages.unpin : messages.pin), action: this.handlePinClick });
}
menu.push({ text: intl.formatMessage(messages.edit), action: this.handleEditClick });
menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDeleteClick });
} else {
menu.push({ text: intl.formatMessage(messages.mention, { name: status.getIn(['account', 'username']) }), action: this.handleMentionClick });
menu.push(null);
menu.push({ text: intl.formatMessage(messages.mute, { name: status.getIn(['account', 'username']) }), action: this.handleMuteClick });
menu.push({ text: intl.formatMessage(messages.block, { name: status.getIn(['account', 'username']) }), action: this.handleBlockClick });
menu.push({ text: intl.formatMessage(messages.report, { name: status.getIn(['account', 'username']) }), action: this.handleReport });
}
if (status.get('visibility') === 'direct') {
reblogIcon = 'envelope';
} else if (status.get('visibility') === 'private') {
reblogIcon = 'lock';
}
if (status.get('in_reply_to_id', null) === null) {
replyIcon = 'reply';
replyTitle = intl.formatMessage(messages.reply);
} else {
replyIcon = 'reply-all';
replyTitle = intl.formatMessage(messages.replyAll);
}
const shareButton = ('share' in navigator) && status.get('visibility') === 'public' && (
<IconButton className='status__action-bar-button' title={intl.formatMessage(messages.share)} icon='share-alt' onClick={this.handleShareClick} />
);
return (
<div className='status__action-bar'>
<IconButton className='status__action-bar-button' disabled={anonymousAccess} title={replyTitle} icon={replyIcon} onClick={this.handleReplyClick} />
<IconButton className='status__action-bar-button' disabled={anonymousAccess || !publicStatus} active={status.get('reblogged')} pressed={status.get('reblogged')} title={!publicStatus ? intl.formatMessage(messages.cannot_reblog) : intl.formatMessage(messages.reblog)} icon={reblogIcon} onClick={this.handleReblogClick} />
<IconButton className='status__action-bar-button star-icon' disabled={anonymousAccess} animate active={status.get('favourited')} pressed={status.get('favourited')} title={intl.formatMessage(messages.favourite)} icon='star' onClick={this.handleFavouriteClick} />
{shareButton}
<div className='status__action-bar-dropdown'>
<DropdownMenuContainer disabled={anonymousAccess} status={status} items={menu} icon='ellipsis-h' size={18} direction='right' title={intl.formatMessage(messages.more)} />
</div>
</div>
);
}
}
|
frontend/component/CommentEditor.js | plusse7en/practice-node-project | import React from 'react';
import jQuery from 'jquery';
import {addTopic} from '../lib/client';
import {redirectURL} from '../lib/utils';
import MarkdownEditor from './MarkdownEditor';
export default class CommentEditor extends React.Component {
constructor(props) {
super(props);
this.state = props.comment || {};
}
handleChange(name, e) {
this.setState({[name]: e.target.value});
}
handleSubmit(e) {
const $btn = jQuery(e.target);
$btn.button('loading');
this.props.onSave(this.state, () => {
$btn.button('reset');
});
}
render() {
return (
<div className="panel panel-primary">
<div className="panel-heading">{this.props.title}</div>
<div className="panel-body">
<form>
<div className="form-group">
<MarkdownEditor value={this.state.content} onChange={this.handleChange.bind(this, 'content')} />
</div>
<button type="button" className="btn btn-primary" onClick={this.handleSubmit.bind(this)}>发表</button>
</form>
</div>
</div>
)
}
}
|
src/hooks/useReduxContext.js | rackt/react-redux | import { useContext } from 'react'
import { ReactReduxContext } from '../components/Context'
/**
* A hook to access the value of the `ReactReduxContext`. This is a low-level
* hook that you should usually not need to call directly.
*
* @returns {any} the value of the `ReactReduxContext`
*
* @example
*
* import React from 'react'
* import { useReduxContext } from 'react-redux'
*
* export const CounterComponent = ({ value }) => {
* const { store } = useReduxContext()
* return <div>{store.getState()}</div>
* }
*/
export function useReduxContext() {
const contextValue = useContext(ReactReduxContext)
if (process.env.NODE_ENV !== 'production' && !contextValue) {
throw new Error(
'could not find react-redux context value; please ensure the component is wrapped in a <Provider>'
)
}
return contextValue
}
|
src/svg-icons/action/power-settings-new.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPowerSettingsNew = (props) => (
<SvgIcon {...props}>
<path d="M13 3h-2v10h2V3zm4.83 2.17l-1.42 1.42C17.99 7.86 19 9.81 19 12c0 3.87-3.13 7-7 7s-7-3.13-7-7c0-2.19 1.01-4.14 2.58-5.42L6.17 5.17C4.23 6.82 3 9.26 3 12c0 4.97 4.03 9 9 9s9-4.03 9-9c0-2.74-1.23-5.18-3.17-6.83z"/>
</SvgIcon>
);
ActionPowerSettingsNew = pure(ActionPowerSettingsNew);
ActionPowerSettingsNew.displayName = 'ActionPowerSettingsNew';
export default ActionPowerSettingsNew;
|
app/javascript/flavours/glitch/features/report/thanks.js | glitch-soc/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { FormattedMessage } from 'react-intl';
import Button from 'flavours/glitch/components/button';
import { connect } from 'react-redux';
import {
unfollowAccount,
muteAccount,
blockAccount,
} from 'mastodon/actions/accounts';
const mapStateToProps = () => ({});
export default @connect(mapStateToProps)
class Thanks extends React.PureComponent {
static propTypes = {
submitted: PropTypes.bool,
onClose: PropTypes.func.isRequired,
account: ImmutablePropTypes.map.isRequired,
dispatch: PropTypes.func.isRequired,
};
handleCloseClick = () => {
const { onClose } = this.props;
onClose();
};
handleUnfollowClick = () => {
const { dispatch, account, onClose } = this.props;
dispatch(unfollowAccount(account.get('id')));
onClose();
};
handleMuteClick = () => {
const { dispatch, account, onClose } = this.props;
dispatch(muteAccount(account.get('id')));
onClose();
};
handleBlockClick = () => {
const { dispatch, account, onClose } = this.props;
dispatch(blockAccount(account.get('id')));
onClose();
};
render () {
const { account, submitted } = this.props;
return (
<React.Fragment>
<h3 className='report-dialog-modal__title'>{submitted ? <FormattedMessage id='report.thanks.title_actionable' defaultMessage="Thanks for reporting, we'll look into this." /> : <FormattedMessage id='report.thanks.title' defaultMessage="Don't want to see this?" />}</h3>
<p className='report-dialog-modal__lead'>{submitted ? <FormattedMessage id='report.thanks.take_action_actionable' defaultMessage='While we review this, you can take action against @{name}:' values={{ name: account.get('username') }} /> : <FormattedMessage id='report.thanks.take_action' defaultMessage='Here are your options for controlling what you see on Mastodon:' />}</p>
{account.getIn(['relationship', 'following']) && (
<React.Fragment>
<h4 className='report-dialog-modal__subtitle'><FormattedMessage id='report.unfollow' defaultMessage='Unfollow @{name}' values={{ name: account.get('username') }} /></h4>
<p className='report-dialog-modal__lead'><FormattedMessage id='report.unfollow_explanation' defaultMessage='You are following this account. To not see their posts in your home feed anymore, unfollow them.' /></p>
<Button secondary onClick={this.handleUnfollowClick}><FormattedMessage id='account.unfollow' defaultMessage='Unfollow' /></Button>
<hr />
</React.Fragment>
)}
<h4 className='report-dialog-modal__subtitle'><FormattedMessage id='account.mute' defaultMessage='Mute @{name}' values={{ name: account.get('username') }} /></h4>
<p className='report-dialog-modal__lead'><FormattedMessage id='report.mute_explanation' defaultMessage='You will not see their posts. They can still follow you and see your posts and will not know that they are muted.' /></p>
<Button secondary onClick={this.handleMuteClick}>{!account.getIn(['relationship', 'muting']) ? <FormattedMessage id='report.mute' defaultMessage='Mute' /> : <FormattedMessage id='account.muted' defaultMessage='Muted' />}</Button>
<hr />
<h4 className='report-dialog-modal__subtitle'><FormattedMessage id='account.block' defaultMessage='Block @{name}' values={{ name: account.get('username') }} /></h4>
<p className='report-dialog-modal__lead'><FormattedMessage id='report.block_explanation' defaultMessage='You will not see their posts. They will not be able to see your posts or follow you. They will be able to tell that they are blocked.' /></p>
<Button secondary onClick={this.handleBlockClick}>{!account.getIn(['relationship', 'blocking']) ? <FormattedMessage id='report.block' defaultMessage='Block' /> : <FormattedMessage id='account.blocked' defaultMessage='Blocked' />}</Button>
<div className='flex-spacer' />
<div className='report-dialog-modal__actions'>
<Button onClick={this.handleCloseClick}><FormattedMessage id='report.close' defaultMessage='Done' /></Button>
</div>
</React.Fragment>
);
}
}
|
app/jsx/components/ICRadioButton.js | sfu/canvas_spaces | import React from 'react';
import PropTypes from 'prop-types';
const ICRadioButton = props => (
<div className="ic-Radio">
<input
id={props.id}
type="radio"
name={props.name}
value={props.value}
checked={props.checked}
onChange={props.onChange}
/>
<label htmlFor={props.id} className="ic-Label">
{props.label}
</label>
</div>
);
ICRadioButton.propTypes = {
id: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
checked: PropTypes.bool.isRequired,
onChange: PropTypes.func,
};
export default ICRadioButton;
|
src/index.js | surce2010/react-webpack-gallery | import 'core-js/fn/object/assign';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/Main';
// Render the main component into the dom
ReactDOM.render(<App />, document.getElementById('app'));
|
src/js/components/Heading/stories/Color.js | HewlettPackard/grommet | import React from 'react';
import { Heading } from 'grommet';
export const Color = () => (
// Uncomment <Grommet> lines when using outside of storybook
// <Grommet theme={...}>
<Heading color="accent-1">Colored Heading</Heading>
// </Grommet>
);
export default {
title: 'Type/Heading/Color',
};
|
examples/column-ordering/src/App.js | tannerlinsley/react-table | import React from 'react'
import styled from 'styled-components'
import { useTable, useColumnOrder } from 'react-table'
import makeData from './makeData'
const Styles = styled.div`
padding: 1rem;
table {
border-spacing: 0;
border: 1px solid black;
tr {
:last-child {
td {
border-bottom: 0;
}
}
}
th,
td {
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid black;
border-right: 1px solid black;
background: white;
:last-child {
border-right: 0;
}
}
}
`
function shuffle(arr) {
arr = [...arr]
const shuffled = []
while (arr.length) {
const rand = Math.floor(Math.random() * arr.length)
shuffled.push(arr.splice(rand, 1)[0])
}
return shuffled
}
function Table({ columns, data }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
visibleColumns,
prepareRow,
setColumnOrder,
state,
} = useTable(
{
columns,
data,
},
useColumnOrder
)
const randomizeColumns = () => {
setColumnOrder(shuffle(visibleColumns.map(d => d.id)))
}
return (
<>
<button onClick={() => randomizeColumns({})}>Randomize Columns</button>
<table {...getTableProps()}>
<thead>
{headerGroups.map((headerGroup, i) => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.slice(0, 10).map((row, i) => {
prepareRow(row)
return (
<tr {...row.getRowProps()}>
{row.cells.map((cell, i) => {
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
})}
</tr>
)
})}
</tbody>
</table>
<pre>
<code>{JSON.stringify(state, null, 2)}</code>
</pre>
</>
)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
},
{
Header: 'Last Name',
accessor: 'lastName',
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
},
{
Header: 'Visits',
accessor: 'visits',
},
{
Header: 'Status',
accessor: 'status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
},
],
},
],
[]
)
const data = React.useMemo(() => makeData(10), [])
return (
<Styles>
<Table columns={columns} data={data} />
</Styles>
)
}
export default App
|
app/components/Window.js | josser/pickler | import React, { Component } from 'react';
import photon from "photon/sass/photon.scss";
export default class Window extends Component {
render () {
return (
<div className="window">
{this.props.children}
</div>
)
}
}
|
client/src/components/ListOfProjects/ListOfProjects.js | karthijey/calltocode.org | import React from 'react'
import PropTypes from 'prop-types'
import styles from './ListOfProjects.css'
import projects from '../../data/projects.json'
import emailApiClient from '../../api/email'
import { connect } from 'react-redux'
function ListOfProjects (props) {
const liClassName = props.loggedIn ? styles.listOrgLoggedIn : styles.listOrg
const projectListItems = projects.map((project, index) => {
return (
<li
key={index}
className={liClassName}
onClick={props.loggedIn ? mailToOrganization(project) : null}>
Name:{project.name} Role:{project.role}
</li>
)
})
return (
<section className={styles.orgSection}>
<h1 className={styles.title}>Apply Below</h1>
<ul>
{projectListItems}
</ul>
</section>
)
}
function mailToOrganization (project) {
return () => {
const {email, name, role} = project
const projectInfo = {email, name, role}
emailApiClient.send(projectInfo)
}
}
function mapStateToProps (state) {
return { loggedIn: state.login.loggedIn }
}
ListOfProjects.propTypes = {
loggedIn: PropTypes.bool.isRequired
}
export default connect(mapStateToProps)(ListOfProjects)
|
docs/src/app/components/pages/get-started/Examples.js | rhaedes/material-ui | import React from 'react';
import Title from 'react-title-component';
import MarkdownElement from '../../MarkdownElement';
import examplesText from './examples.md';
const Examples = () => (
<div>
<Title render={(previousTitle) => `Examples - ${previousTitle}`} />
<MarkdownElement text={examplesText} />
</div>
);
export default Examples;
|
react/gameday2/utils/layoutUtils.js | phil-lopreiato/the-blue-alliance | /* eslint-disable import/prefer-default-export */
import React from 'react'
import SvgIcon from 'material-ui/SvgIcon'
import { NUM_VIEWS_FOR_LAYOUT, LAYOUT_SVG_PATHS } from '../constants/LayoutConstants'
// Convenience wrapper around NUM_VIEWS_FOR_LAYOUT that has bounds checking and
// a sensible default.
export function getNumViewsForLayout(layoutId) {
if (layoutId >= 0 && layoutId < NUM_VIEWS_FOR_LAYOUT.length) {
return NUM_VIEWS_FOR_LAYOUT[layoutId]
}
return 1
}
export function getLayoutSvgIcon(layoutId, color = '#757575') {
const pathData = LAYOUT_SVG_PATHS[layoutId]
return (
<SvgIcon color={color} viewBox="0 0 23 15">
<path d={pathData} />
</SvgIcon>
)
}
export { getNumViewsForLayout as default }
|
node_modules/react-router/es6/Lifecycle.js | rakshitmidha/Weather_App_React | import warning from './routerWarning';
import React from 'react';
import invariant from 'invariant';
var object = React.PropTypes.object;
/**
* The Lifecycle mixin adds the routerWillLeave lifecycle method to a
* component that may be used to cancel a transition or prompt the user
* for confirmation.
*
* On standard transitions, routerWillLeave receives a single argument: the
* location we're transitioning to. To cancel the transition, return false.
* To prompt the user for confirmation, return a prompt message (string).
*
* During the beforeunload event (assuming you're using the useBeforeUnload
* history enhancer), routerWillLeave does not receive a location object
* because it isn't possible for us to know the location we're transitioning
* to. In this case routerWillLeave must return a prompt message to prevent
* the user from closing the window/tab.
*/
var Lifecycle = {
contextTypes: {
history: object.isRequired,
// Nested children receive the route as context, either
// set by the route component using the RouteContext mixin
// or by some other ancestor.
route: object
},
propTypes: {
// Route components receive the route object as a prop.
route: object
},
componentDidMount: function componentDidMount() {
process.env.NODE_ENV !== 'production' ? warning(false, 'the `Lifecycle` mixin is deprecated, please use `context.router.setRouteLeaveHook(route, hook)`. http://tiny.cc/router-lifecyclemixin') : void 0;
!this.routerWillLeave ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The Lifecycle mixin requires you to define a routerWillLeave method') : invariant(false) : void 0;
var route = this.props.route || this.context.route;
!route ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The Lifecycle mixin must be used on either a) a <Route component> or ' + 'b) a descendant of a <Route component> that uses the RouteContext mixin') : invariant(false) : void 0;
this._unlistenBeforeLeavingRoute = this.context.history.listenBeforeLeavingRoute(route, this.routerWillLeave);
},
componentWillUnmount: function componentWillUnmount() {
if (this._unlistenBeforeLeavingRoute) this._unlistenBeforeLeavingRoute();
}
};
export default Lifecycle; |
web/src/Home/Banner/Banner.js | ncpierson/soundoftext | import React, { Component } from 'react';
import { OutboundLink } from 'react-ga';
const NAME = 'HEARLING_REMINDER_20210419';
class Banner extends Component {
constructor() {
super();
const dismissedBanner = localStorage.getItem('dismissedBanner') || '';
const hasDismissed = dismissedBanner === NAME;
this.state = { hasDismissed };
}
handleDismiss = () => {
localStorage.setItem('dismissedBanner', NAME);
this.setState({ hasDismissed: true });
};
render() {
const { hasDismissed } = this.state;
if (hasDismissed) return null;
return (
<section className="section section--colored">
<div className="grid">
<div className="card grid__item">
<div className="card__content">
<h3 className="card__title">
<span aria-label="sparkles" role="img">
✨
</span>{' '}
<span>Try Hearling!</span>
</h3>
<p>
Interested in high quality voices, or tired of the 200 character
limit on Sound of Text? Try Hearling! You will gain access to
over 200 voices, in 34 different languages ‒ powered by machine
learning.
</p>
<p>
<em>This isn't just an ad!</em> Hearling is made by the same
developer as Sound of Text, and I encourage you to try it out!
It is completely free, or you can subscribe to Hearling Pro for
$5 per month to gain access to quicker clip creation (and
support the developer!)
</p>
</div>
<div className="card__actions">
<OutboundLink
className="card__action"
eventLabel="hearling:banner"
target="_blank"
to="https://hearling.com"
>
Visit Hearling
</OutboundLink>
<button className="card__action" onClick={this.handleDismiss}>
Dismiss
</button>
</div>
</div>
</div>
</section>
);
}
}
export default Banner;
|
packages/react-example/src/index.js | ilkkahanninen/petiole | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-petiole';
import store from './store';
import App from './components/App';
import './index.css';
ReactDOM.render(
(
<Provider store={store}>
<App />
</Provider>
),
document.getElementById('root')
);
|
src/fields/picker/index.js | bietkul/react-native-form-builder | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { View, Text } from 'native-base';
import { Platform, Picker, TouchableOpacity } from 'react-native';
import Panel from '../../components/panel';
import styles from './../../styles';
const Item = Picker.Item;
export default class PickerField extends Component {
static propTypes = {
attributes: PropTypes.object,
theme: PropTypes.object,
updateValue: PropTypes.func,
ErrorComponent: PropTypes.func,
}
handleChange(value) {
const attributes = this.props.attributes;
this.props.updateValue(attributes.name, attributes.options[value]);
}
render() {
const { theme, attributes, ErrorComponent } = this.props;
const isValueValid = attributes.options.indexOf(attributes.value) > -1;
const pickerValue = attributes.options.indexOf(attributes.value).toString();
if (Platform.OS !== 'ios') {
return (
<View
style={{...styles.pickerMainAndroid, ...{
backgroundColor: theme.pickerBgColor,
borderBottomColor: theme.inputBorderColor,
borderBottomWidth: theme.borderWidth,
}}}
>
<View style={{ flex: 7 }}>
<Text style={{ color: theme.inputColorPlaceholder }}>{attributes.label}</Text>
</View>
<View style={{ flex: 3 }}>
<Picker
style={{ padding: 2 }}
textStyle={{ color: theme.pickerColorSelected }}
iosHeader="Select one"
mode={attributes.mode}
selectedValue={pickerValue}
onValueChange={value => this.handleChange(value)}
>{
attributes.options.map((item, index) => (
<Item key={index} label={item} value={`${index}`} />
))
}
</Picker>
</View>
<ErrorComponent {...{ attributes, theme }} />
</View>
);
}
return (
<View
style={Object.assign(styles.pickerMainIOS, {
backgroundColor: theme.pickerBgColor,
borderBottomColor: theme.inputBorderColor,
borderBottomWidth: theme.borderWidth,
})}
>
<TouchableOpacity
onPress={() => this.panel.toggle()}
style={{
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 10,
}}
>
<Text style={{ color: theme.inputColorPlaceholder }}>
{attributes.label}
</Text>
<Text style={{ color: theme.inputColorPlaceholder }}>
{isValueValid ? attributes.value : 'None'}
</Text>
</TouchableOpacity>
<ErrorComponent {...{ attributes, theme }} />
<View style={{ flex: 1 }}>
<Panel
ref={(c) => { this.panel = c; }}
>
<Picker
style={{ padding: 2 }}
textStyle={{ color: theme.pickerColorSelected }}
mode={attributes.mode}
selectedValue={pickerValue}
onValueChange={value => this.handleChange(value)}
>{
attributes.options.map((item, index) => (
<Item key={index} label={item} value={`${index}`} />
))
}
</Picker>
</Panel>
</View>
</View>
);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.