path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
public/app/components/application.js | vincent-tr/mylife-wine | 'use strict';
import React from 'react';
import base from './base/index';
import MainTabs from './main-tabs';
import DialogErrorContainer from '../containers/dialog-error-container';
import DialogInfoContainer from '../containers/dialog-info-container';
const styles = {
root: {
position : 'fixed',
top : 0,
bottom : 0,
left : 0,
right : 0
}
};
const Application = () => (
<base.Theme>
<base.StoreProvider>
<div style={styles.root}>
<MainTabs />
<DialogErrorContainer />
<DialogInfoContainer />
</div>
</base.StoreProvider>
</base.Theme>
);
export default Application;
|
app/hocs/withProgressChange.js | CityOfZion/neon-wallet | // @flow
import React from 'react'
import { compose } from 'recompose'
import { withData, withError, withProgress, type Actions } from 'spunky'
import { omit, castArray } from 'lodash-es'
const DATA_PROP: string = '__data__'
const ERROR_PROP: string = '__error__'
const PROGRESS_PROP: string = '__progress__'
type Props = {
__data__: Object,
__error__: string,
__progress__: string,
}
export default function withProgressChange(
actions: Actions,
progress: string,
callback: Function,
) {
const progresses = castArray(progress)
const mapDataToProps = data => ({
[DATA_PROP]: data,
})
const mapErrorToProps = error => ({
[ERROR_PROP]: error,
})
return (Component: Class<React.Component<*>>) => {
class WrappedComponent extends React.Component<Props> {
componentWillReceiveProps(nextProps) {
if (
!progresses.includes(this.props[PROGRESS_PROP]) &&
progresses.includes(nextProps[PROGRESS_PROP])
) {
callback(
this.getCallbackState(nextProps),
this.getCallbackProps(nextProps),
)
}
}
render() {
const passDownProps = omit(this.props, DATA_PROP, PROGRESS_PROP)
return <Component {...passDownProps} />
}
getCallbackState = props => ({
data: props[DATA_PROP],
error: props[ERROR_PROP],
})
getCallbackProps = props =>
omit(props, DATA_PROP, ERROR_PROP, PROGRESS_PROP)
}
return compose(
withProgress(actions, { propName: PROGRESS_PROP }),
withData(actions, mapDataToProps),
withError(actions, mapErrorToProps),
)(WrappedComponent)
}
}
|
ngiiedu-client/src/components/admin/school/list/popup/InfoPopup.js | jinifor/branchtest | import React from 'react';
import { connect } from 'react-redux';
import { actionSchoolInfoOpen } from '../../../../../actions/index';
//ํ์
์ฐฝ
import Dialog from 'material-ui/Dialog';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn,
} from 'material-ui/Table';
class InfoPopup extends React.Component {
constructor(props) {
super(props);
this.state = {
selectTableData: {}
};
}
componentWillReceiveProps(nextProps) {
const schoolId = nextProps.schoolId;
ajaxJson(
['GET',apiSvr+'/schools/'+schoolId+'.json'],
null,
function(res){
this.setState({
selectTableData:res.response.data
})
}.bind(this)
);
}
handleClose() {
this.props.controlInfoPopup(false);
}
render() {
//๋ฐ์ดํฐ ์์ธ์ ๋ณด ํ์ธ ๋ฒํผ
const infoButton = [
<FlatButton
label="ํ์ธ"
primary={true}
onClick={this.handleClose.bind(this)}
/>
];
return (
<div>
{/* ํ๊ต ์์ธ์ ๋ณด ๋ชจ๋ฌ */}
<Dialog
title="ํ๊ต์์ธ์ ๋ณด"
actions={infoButton}
modal={false}
open={this.props.infoOpen}
onRequestClose={this.handleClose.bind(this)}
>
<Table
fixedHeader={true}
selectable={false}
height={'300px'}
>
<TableHeader displaySelectAll={false}>
<TableRow>
<TableHeaderColumn>์ปฌ๋ผ๋ช
</TableHeaderColumn>
<TableHeaderColumn>์์ฑ๊ฐ</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody displayRowCheckbox={false}>
<TableRow>
<TableRowColumn>
ํ๊ต์์ด๋
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolId}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
ํ๊ต์ด๋ฆ
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolName}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
ํ๊ต๊ตฌ๋ถ
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolLevel}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
์ด์์ํ
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolStatus}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
๊ต์ก์ง์์ฒญ๋ช
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolEduOfficeName}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
๊ต์ก์ง์์ฒญ์ฝ๋
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolEduOfficeCode}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
์๋๊ต์ก์ฒญ๋ช
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolSidoOfficeName}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
์๋๊ต์ก์ฒญ์ฝ๋
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolSidoOfficeCode}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
์์ฌ์ง์ง๋ฒ์ฃผ์
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolAddr}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
์ค๋ฆฝ์ผ์
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolBuildDate}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
์ค๋ฆฝํํ
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolEstablishType}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
์๋
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolLat}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
๊ฒฝ๋
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolLon}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
๋ณธ๊ต๋ถ๊ต๊ตฌ๋ถ
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolBranchType}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
์์ฌ์ง๋๋ก๋ช
์ฃผ์
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolAddrRoad}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
๋ฐ์ดํฐ๊ธฐ์ค์ผ์
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolReferenceDate}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
์์ฑ์ผ์
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolDataCreateDate}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
๋ณ๊ฒฝ์ผ์
</TableRowColumn>
<TableRowColumn>
{this.state.selectTableData.schoolDateEditDate}
</TableRowColumn>
</TableRow>
</TableBody>
</Table>
</Dialog>
</div>
);
}
}
let mapStateToProps = (state) => {
return {
schoolId: state.schoolList.schoolId,
infoOpen: state.schoolList.infoOpen
};
};
let mapDispatchToProps = (dispatch) => {
return {
controlInfoPopup: (value) => dispatch(actionSchoolInfoOpen(value))
};
};
InfoPopup = connect(mapStateToProps, mapDispatchToProps)(InfoPopup);
export default InfoPopup;
|
src/parser/priest/holy/modules/talents/45/GuardianAngel.js | ronaldpereira/WoWAnalyzer | import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import TalentStatisticBox, { STATISTIC_ORDER } from 'interface/others/TalentStatisticBox';
import React from 'react';
import AbilityTracker from 'parser/shared/modules/AbilityTracker';
import Events from 'parser/core/Events';
const GS_BASE_COOLDOWN_TIME = (60 * 3) * 1000;
const GS_MODIFIED_COOLDOWN_TIME = (60 + 10) * 1000; // one minute plus 10 seconds to account for the duration of the buff.
// Example Log: /report/mFarpncVW9ALwTq4/7-Mythic+Zek'voz+-+Kill+(8:52)/14-Praydien
class GuardianAngel extends Analyzer {
static dependencies = {
abilityTracker: AbilityTracker,
};
get guardianSpiritCastCount() {
return this.abilityTracker.getAbility(SPELLS.GUARDIAN_SPIRIT.id).casts;
}
guardianSpiritRemovalCount = 0;
guardianSpiritHealCount = 0;
get guardianSpiritRefreshCount() {
return this.guardianSpiritRemovalCount - this.guardianSpiritHealCount;
}
get baseGuardianSpiritCastsPossible() {
return Math.floor(this.owner.fightDuration / GS_BASE_COOLDOWN_TIME);
}
get gsGuardianSpiritCastsPossible() {
return Math.floor(this.owner.fightDuration / GS_MODIFIED_COOLDOWN_TIME);
}
get gsValue() {
const castDelta = this.guardianSpiritCastCount - this.baseGuardianSpiritCastsPossible;
return (castDelta) >= 0 ? (castDelta) : 0;
}
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.GUARDIAN_ANGEL_TALENT.id);
if (!this.active) {
return;
}
this.addEventListener(Events.applybuff.by(SELECTED_PLAYER).spell(SPELLS.GUARDIAN_SPIRIT), this._parseGsRemove);
this.addEventListener(Events.heal.by(SELECTED_PLAYER).spell(SPELLS.GUARDIAN_SPIRIT), this._parseGsHeal);
}
_parseGsRemove(event) {
this.guardianSpiritRemovalCount += 1;
}
_parseGsHeal(event) {
this.guardianSpiritHealCount += 1;
}
statistic() {
return (
<TalentStatisticBox
talent={SPELLS.GUARDIAN_ANGEL_TALENT.id}
value={(
<>
{this.guardianSpiritRefreshCount} Guardian Spirit resets<br />
{this.guardianSpiritHealCount} Guardian Spirits consumed
</>
)}
tooltip={(
<>
You casted Guardian Spirit {this.gsValue} more times than you would have been able to without Guardian Angel.<br />
You could have theoretically cast Guardian Spirit {this.gsGuardianSpiritCastsPossible - this.guardianSpiritCastCount} more times.
</>
)}
position={STATISTIC_ORDER.CORE(3)}
/>
);
}
}
export default GuardianAngel;
|
src/parser/mage/shared/modules/features/MirrorImage.js | fyruna/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import { formatPercentage } from 'common/format';
import TalentStatisticBox, { STATISTIC_ORDER } from 'interface/others/TalentStatisticBox';
import Analyzer from 'parser/core/Analyzer';
const INCANTERS_FLOW_EXPECTED_BOOST = 0.12;
class MirrorImage extends Analyzer {
// all images summoned by player seem to have the same sourceID, and vary only by instanceID
mirrorImagesId;
damage = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.MIRROR_IMAGE_TALENT.id);
}
on_byPlayer_summon(event) {
// there are a dozen different Mirror Image summon IDs which is used where or why... this is the easy way out
if(event.ability.name === SPELLS.MIRROR_IMAGE_SUMMON.name) {
this.mirrorImagesId = event.targetID;
}
}
on_byPlayerPet_damage(event) {
if(this.mirrorImagesId === event.sourceID) {
this.damage += event.amount + (event.absorbed || 0);
}
}
get damagePercent() {
return this.owner.getPercentageOfTotalDamageDone(this.damage);
}
get damageIncreasePercent() {
return this.damagePercent / (1 - this.damagePercent);
}
get damageSuggestionThresholds() {
return {
actual: this.damageIncreasePercent,
isLessThan: {
minor: INCANTERS_FLOW_EXPECTED_BOOST,
average: INCANTERS_FLOW_EXPECTED_BOOST,
major: INCANTERS_FLOW_EXPECTED_BOOST - 0.03,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.damageSuggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<>Your <SpellLink id={SPELLS.MIRROR_IMAGE_TALENT.id} /> damage is below the expected passive gain from <SpellLink id={SPELLS.INCANTERS_FLOW_TALENT.id} />. Consider switching to <SpellLink id={SPELLS.INCANTERS_FLOW_TALENT.id} />.</>)
.icon(SPELLS.MIRROR_IMAGE_TALENT.icon)
.actual(`${formatPercentage(this.damageIncreasePercent)}% damage increase from Mirror Image`)
.recommended(`${formatPercentage(recommended)}% is the passive gain from Incanter's Flow`);
});
}
statistic() {
return (
<TalentStatisticBox
talent={SPELLS.MIRROR_IMAGE_TALENT.id}
position={STATISTIC_ORDER.CORE(100)}
value={`${formatPercentage(this.damagePercent)} %`}
label="Mirror Image damage"
tooltip={<>This is the portion of your total damage attributable to Mirror Image. Expressed as an increase vs never using Mirror Image, this is a <strong>{formatPercentage(this.damageIncreasePercent)}% damage increase</strong></>}
/>
);
}
}
export default MirrorImage;
|
src/DateFormatSpinnerInput/index.js | erisnuts/react-date-picker | import React from 'react'
import Component from 'react-class'
import { Flex, Item } from 'react-flex'
import DateFormatInput from '../DateFormatInput'
import assign from 'object-assign'
import joinFunctions from '../joinFunctions'
import assignDefined from '../assignDefined'
import join from '../join'
export default class DateFormatSpinnerInput extends Component {
constructor(props) {
super(props)
this.state = {
focused: false
}
}
componentWillUnmount() {
this.started = false
}
render() {
const props = this.props
const children = React.Children.toArray(props.children)
const input = this.inputChild = children.filter(c => c && c.type == 'input')[0]
const inputProps = input ? assign({}, input.props) : {}
const onKeyDown = joinFunctions(props.onKeyDown, inputProps.onKeyDown)
const onChange = joinFunctions(props.onChange, inputProps.onChange)
const disabled = props.disabled || inputProps.disabled
assignDefined(inputProps, {
size: props.size || inputProps.size,
minDate: props.minDate || inputProps.minDate,
maxDate: props.maxDate || inputProps.maxDate,
changeDelay: props.changeDelay === undefined ? inputProps.changeDelay : props.changeDelay,
tabIndex: props.tabIndex,
onKeyDown,
onChange,
disabled,
dateFormat: props.dateFormat === undefined ? inputProps.dateFormat : props.dateFormat,
stopPropagation: props.stopPropagation,
updateOnWheel: props.updateOnWheel,
onBlur: this.onBlur,
onFocus: this.onFocus
})
this.inputProps = inputProps
const arrowSize = this.props.arrowSize
this.arrows = {
1: <svg height={arrowSize} viewBox="0 0 24 24" width={arrowSize} >
<path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z" />
{/*<path d="M0 0h24v24H0z" fill="none"/>*/}
</svg>,
'-1': <svg height={arrowSize} viewBox="0 0 24 24" width={arrowSize} >
<path d="M7.41 7.84L12 12.42l4.59-4.58L18 9.25l-6 6-6-6z" />
{/*<path d="M0-.75h24v24H0z" fill="none"/>*/}
</svg>
}
const className = join(
props.className,
'react-date-picker__date-format-spinner',
disabled && 'react-date-picker__date-format-spinner--disabled',
this.isFocused() && 'react-date-picker__date-format-spinner--focused',
`react-date-picker__date-format-spinner--theme-${props.theme}`
)
return <Flex
inline
row
className={className}
disabled={props.disabled}
>
<DateFormatInput
ref={inputDOM => { this.input = inputDOM }}
value={props.value}
{...inputProps}
/>
{this.renderArrows()}
</Flex>
}
renderArrows() {
if (this.props.renderArrows) {
return this.props.renderArrows(this.props)
}
return <Flex
column
inline
>
{this.renderArrow(1)}
{this.renderArrow(-1)}
</Flex>
}
renderArrow(dir) {
return <Item
flexShrink={1}
className="react-date-picker__date-format-spinner-arrow"
style={{ overflow: 'hidden', height: this.props.arrowSize }}
onMouseDown={this.onMouseDown.bind(this, dir)}
onMouseUp={this.stop}
onMouseLeave={this.stop}
>
{this.arrows[dir]}
</Item>
}
onMouseDown(dir, event) {
if (this.props.disabled) {
event.preventDefault()
return
}
event.preventDefault()
if (this.isFocused()) {
this.start(dir)
} else {
this.focus()
setTimeout(() => {
this.increment(dir)
}, 1)
}
}
start(dir) {
this.started = true
this.startTime = Date.now()
this.step(dir)
this.timeoutId = setTimeout(() => {
this.step(dir)
this.timeoutId = setTimeout(() => {
const lazyStep = () => {
const delay = this.props.stepDelay - ((Date.now() - this.startTime) / 500)
this.step(dir, lazyStep, delay)
}
lazyStep()
}, this.props.secondStepDelay)
}, this.props.firstStepDelay)
}
isStarted() {
return !!(this.started && this.input)
}
increment(dir) {
this.input.onDirection(dir)
}
step(dir, callback, delay) {
if (this.isStarted()) {
this.increment(dir)
if (typeof callback == 'function') {
this.timeoutId = setTimeout(() => {
if (this.isStarted()) {
callback()
}
}, delay === undefined ? this.props.stepDelay : delay)
}
}
}
stop() {
this.started = false
if (this.timeoutId) {
global.clearTimeout(this.timeoutId)
}
}
focus() {
if (this.input) {
this.input.focus()
}
}
isFocused() {
return this.state.focused
}
onBlur(event) {
const { props } = this
const onBlur = joinFunctions(
props.onBlur,
this.inputChild && this.inputChild.props && this.inputChild.props.onBlur
)
if (onBlur) {
onBlur(event)
}
this.setState({
focused: false
})
}
onFocus(event) {
const { props } = this
const onFocus = joinFunctions(
props.onFocus,
this.inputChild && this.inputChild.props && this.inputChild.props.onFocus
)
if (onFocus) {
onFocus(event)
}
this.setState({
focused: true
})
}
}
DateFormatSpinnerInput.defaultProps = {
firstStepDelay: 150,
secondStepDelay: 100,
stepDelay: 50,
changeDelay: undefined,
theme: 'default',
disabled: false,
arrowSize: 15,
isDateInput: true,
stopPropagation: true,
updateOnWheel: true
}
|
fields/types/code/CodeField.js | rafmsou/keystone | import _ from 'lodash';
import CodeMirror from 'codemirror';
import Field from '../Field';
import React from 'react';
import { findDOMNode } from 'react-dom';
import { FormInput } from '../../../admin/client/App/elemental';
import classnames from 'classnames';
/**
* TODO:
* - Remove dependency on lodash
*/
// See CodeMirror docs for API:
// http://codemirror.net/doc/manual.html
module.exports = Field.create({
displayName: 'CodeField',
statics: {
type: 'Code',
},
getInitialState () {
return {
isFocused: false,
};
},
componentDidMount () {
if (!this.refs.codemirror) {
return;
}
var options = _.defaults({}, this.props.editor, {
lineNumbers: true,
readOnly: this.shouldRenderField() ? false : true,
});
this.codeMirror = CodeMirror.fromTextArea(findDOMNode(this.refs.codemirror), options);
this.codeMirror.setSize(null, this.props.height);
this.codeMirror.on('change', this.codemirrorValueChanged);
this.codeMirror.on('focus', this.focusChanged.bind(this, true));
this.codeMirror.on('blur', this.focusChanged.bind(this, false));
this._currentCodemirrorValue = this.props.value;
},
componentWillUnmount () {
// todo: is there a lighter-weight way to remove the cm instance?
if (this.codeMirror) {
this.codeMirror.toTextArea();
}
},
componentWillReceiveProps (nextProps) {
if (this.codeMirror && this._currentCodemirrorValue !== nextProps.value) {
this.codeMirror.setValue(nextProps.value);
}
},
focus () {
if (this.codeMirror) {
this.codeMirror.focus();
}
},
focusChanged (focused) {
this.setState({
isFocused: focused,
});
},
codemirrorValueChanged (doc, change) {
var newValue = doc.getValue();
this._currentCodemirrorValue = newValue;
this.props.onChange({
path: this.props.path,
value: newValue,
});
},
renderCodemirror () {
const className = classnames('CodeMirror-container', {
'is-focused': this.state.isFocused && this.shouldRenderField(),
});
return (
<div className={className}>
<FormInput
autoComplete="off"
multiline
name={this.getInputName(this.props.path)}
onChange={this.valueChanged}
ref="codemirror"
value={this.props.value}
/>
</div>
);
},
renderValue () {
return this.renderCodemirror();
},
renderField () {
return this.renderCodemirror();
},
});
|
frontend/jqwidgets/jqwidgets-react/react_jqxpasswordinput.js | yevgeny-sergeyev/nexl-js | /*
jQWidgets v5.7.2 (2018-Apr)
Copyright (c) 2011-2018 jQWidgets.
License: https://jqwidgets.com/license/
*/
import React from 'react';
const JQXLite = window.JQXLite;
export const jqx = window.jqx;
export default class JqxPasswordInput extends React.Component {
componentDidMount() {
let options = this.manageAttributes();
this.createComponent(options);
};
manageAttributes() {
let properties = ['disabled','height','localization','maxLength','placeHolder','passwordStrength','rtl','strengthColors','showStrength','showStrengthPosition','strengthTypeRenderer','showPasswordIcon','theme','width'];
let options = {};
for(let item in this.props) {
if(item === 'settings') {
for(let itemTwo in this.props[item]) {
options[itemTwo] = this.props[item][itemTwo];
}
} else {
if(properties.indexOf(item) !== -1) {
options[item] = this.props[item];
}
}
}
return options;
};
createComponent(options) {
if(!this.style) {
for (let style in this.props.style) {
JQXLite(this.componentSelector).css(style, this.props.style[style]);
}
}
if(this.props.className !== undefined) {
let classes = this.props.className.split(' ');
for (let i = 0; i < classes.length; i++ ) {
JQXLite(this.componentSelector).addClass(classes[i]);
}
}
if(!this.template) {
JQXLite(this.componentSelector).html(this.props.template);
}
JQXLite(this.componentSelector).jqxPasswordInput(options);
};
setOptions(options) {
JQXLite(this.componentSelector).jqxPasswordInput('setOptions', options);
};
getOptions() {
if(arguments.length === 0) {
throw Error('At least one argument expected in getOptions()!');
}
let resultToReturn = {};
for(let i = 0; i < arguments.length; i++) {
resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxPasswordInput(arguments[i]);
}
return resultToReturn;
};
on(name,callbackFn) {
JQXLite(this.componentSelector).on(name,callbackFn);
};
off(name) {
JQXLite(this.componentSelector).off(name);
};
disabled(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxPasswordInput('disabled', arg)
} else {
return JQXLite(this.componentSelector).jqxPasswordInput('disabled');
}
};
height(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxPasswordInput('height', arg)
} else {
return JQXLite(this.componentSelector).jqxPasswordInput('height');
}
};
localization(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxPasswordInput('localization', arg)
} else {
return JQXLite(this.componentSelector).jqxPasswordInput('localization');
}
};
maxLength(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxPasswordInput('maxLength', arg)
} else {
return JQXLite(this.componentSelector).jqxPasswordInput('maxLength');
}
};
placeHolder(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxPasswordInput('placeHolder', arg)
} else {
return JQXLite(this.componentSelector).jqxPasswordInput('placeHolder');
}
};
passwordStrength(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxPasswordInput('passwordStrength', arg)
} else {
return JQXLite(this.componentSelector).jqxPasswordInput('passwordStrength');
}
};
rtl(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxPasswordInput('rtl', arg)
} else {
return JQXLite(this.componentSelector).jqxPasswordInput('rtl');
}
};
strengthColors(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxPasswordInput('strengthColors', arg)
} else {
return JQXLite(this.componentSelector).jqxPasswordInput('strengthColors');
}
};
showStrength(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxPasswordInput('showStrength', arg)
} else {
return JQXLite(this.componentSelector).jqxPasswordInput('showStrength');
}
};
showStrengthPosition(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxPasswordInput('showStrengthPosition', arg)
} else {
return JQXLite(this.componentSelector).jqxPasswordInput('showStrengthPosition');
}
};
strengthTypeRenderer(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxPasswordInput('strengthTypeRenderer', arg)
} else {
return JQXLite(this.componentSelector).jqxPasswordInput('strengthTypeRenderer');
}
};
showPasswordIcon(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxPasswordInput('showPasswordIcon', arg)
} else {
return JQXLite(this.componentSelector).jqxPasswordInput('showPasswordIcon');
}
};
theme(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxPasswordInput('theme', arg)
} else {
return JQXLite(this.componentSelector).jqxPasswordInput('theme');
}
};
width(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxPasswordInput('width', arg)
} else {
return JQXLite(this.componentSelector).jqxPasswordInput('width');
}
};
performRender() {
JQXLite(this.componentSelector).jqxPasswordInput('render');
};
refresh() {
JQXLite(this.componentSelector).jqxPasswordInput('refresh');
};
val(value) {
if (value !== undefined) {
JQXLite(this.componentSelector).jqxPasswordInput('val', value)
} else {
return JQXLite(this.componentSelector).jqxPasswordInput('val');
}
};
render() {
let id = 'jqxPasswordInput' + JQXLite.generateID();
this.componentSelector = '#' + id;
return (
<input type='password' id={id}></input>
)
};
};
|
node_modules/react-bootstrap/es/Grid.js | okristian1/react-info | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import elementType from 'react-prop-types/lib/elementType';
import { bsClass, prefix, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
/**
* Turn any fixed-width grid layout into a full-width layout by this property.
*
* Adds `container-fluid` class.
*/
fluid: React.PropTypes.bool,
/**
* You can use a custom element for this component
*/
componentClass: elementType
};
var defaultProps = {
componentClass: 'div',
fluid: false
};
var Grid = function (_React$Component) {
_inherits(Grid, _React$Component);
function Grid() {
_classCallCheck(this, Grid);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Grid.prototype.render = function render() {
var _props = this.props,
fluid = _props.fluid,
Component = _props.componentClass,
className = _props.className,
props = _objectWithoutProperties(_props, ['fluid', 'componentClass', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = prefix(bsProps, fluid && 'fluid');
return React.createElement(Component, _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return Grid;
}(React.Component);
Grid.propTypes = propTypes;
Grid.defaultProps = defaultProps;
export default bsClass('container', Grid); |
docs/app/Examples/collections/Grid/ResponsiveVariations/GridExampleDeviceVisibility.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import { Grid, Segment } from 'semantic-ui-react'
const GridExampleDeviceVisibility = () => (
<Grid>
<Grid.Row columns={2} only='large screen'>
<Grid.Column>
<Segment>Large Screen</Segment>
</Grid.Column>
<Grid.Column>
<Segment>Large Screen</Segment>
</Grid.Column>
</Grid.Row>
<Grid.Row columns={2} only='widescreen'>
<Grid.Column>
<Segment>Widescreen</Segment>
</Grid.Column>
<Grid.Column>
<Segment>Widescreen</Segment>
</Grid.Column>
</Grid.Row>
<Grid.Row columns={2} only='mobile'>
<Grid.Column>
<Segment>Mobile</Segment>
</Grid.Column>
<Grid.Column>
<Segment>Mobile</Segment>
</Grid.Column>
</Grid.Row>
<Grid.Row columns={3}>
<Grid.Column only='computer'>
<Segment>Computer</Segment>
</Grid.Column>
<Grid.Column only='tablet mobile'>
<Segment>Tablet and Mobile</Segment>
</Grid.Column>
<Grid.Column>
<Segment>All Sizes</Segment>
</Grid.Column>
<Grid.Column>
<Segment>All Sizes</Segment>
</Grid.Column>
</Grid.Row>
<Grid.Row columns={4} only='computer'>
<Grid.Column>
<Segment>Computer</Segment>
</Grid.Column>
<Grid.Column>
<Segment>Computer</Segment>
</Grid.Column>
<Grid.Column>
<Segment>Computer</Segment>
</Grid.Column>
<Grid.Column>
<Segment>Computer</Segment>
</Grid.Column>
</Grid.Row>
<Grid.Row only='tablet'>
<Grid.Column>
<Segment>Tablet</Segment>
</Grid.Column>
<Grid.Column>
<Segment>Tablet</Segment>
</Grid.Column>
<Grid.Column>
<Segment>Tablet</Segment>
</Grid.Column>
</Grid.Row>
</Grid>
)
export default GridExampleDeviceVisibility
|
techCurriculum/ui/solutions/5.3/src/components/Card.js | tadas412/EngineeringEssentials | /**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
import React from 'react';
import User from './User';
import Message from './Message';
function Card(props) {
const tagElements = props.tags.map((tag, index) =>
<div key={index} className='badge badge-pill' id='tag'>
{tag}
</div>
)
return (
<div className='card'>
<User name={props.author}/>
<div className='card-main'>
<Message text={props.text}/>
</div>
{tagElements}
</div>
);
}
export default Card;
|
src/components/molecules/form-card-group.js | raulfdm/cv | import React from 'react';
import PropTypes from 'prop-types';
const FormCardGroup = ({ children, title }) => {
return (
<React.Fragment>
<section className="card">
<header className="card-header">
<h2 className="title is-3 card-header-title">{title}</h2>
</header>
<aside className="card-content">{children}</aside>
</section>
<br />
</React.Fragment>
);
};
FormCardGroup.propTypes = {
children: PropTypes.node,
title: PropTypes.string,
};
export default FormCardGroup;
|
installer/frontend/form.js | rithujohn191/tectonic-installer | import _ from 'lodash';
import React from 'react';
import { connect } from 'react-redux';
import { dispatch as dispatch_ } from './store';
import { configActions, registerForm } from './actions';
import { toError, toIgnore, toAsyncError, toExtraData, toInFly, toExtraDataInFly, toExtraDataError } from './utils';
import { ErrorComponent, ConnectedFieldList } from './components/ui';
import { TectonicGA } from './tectonic-ga';
import { PLATFORM_TYPE } from './cluster-config';
const { setIn, batchSetIn, append, removeAt } = configActions;
const nop = () => undefined;
let clock_ = 0;
class Node {
constructor (id, opts) {
if (!id) {
throw new Error('I need an id');
}
this.clock_ = 0;
this.id = id;
this.name = opts.name || id;
this.validator = opts.validator || nop;
this.dependencies = opts.dependencies || [];
this.ignoreWhen_ = opts.ignoreWhen;
this.asyncValidator_ = opts.asyncValidator;
this.getExtraStuff_ = opts.getExtraStuff;
}
updateClock (now) {
return this.clock_ = Math.max(now || clock_, this.clock_);
}
get isNow () {
const now = this.clock_;
return () => this.clock_ === now;
}
getExtraStuff (dispatch, cc, FIELDS, now) {
if (!this.getExtraStuff_) {
return Promise.resolve();
}
if (_.some(this.dependencies, d => FIELDS[d] && !FIELDS[d].isValid(cc))) {
// Dependencies are not all satisfied yet
return Promise.resolve();
}
this.updateClock(now);
const inFlyPath = toExtraDataInFly(this.id);
setIn(inFlyPath, true, dispatch);
const isNow = this.isNow;
return this.getExtraStuff_(dispatch, isNow).then(data => {
if (!isNow()) {
return;
}
batchSetIn(dispatch, [
[inFlyPath, undefined],
[toExtraData(this.id), data],
[toExtraDataError(this.id), undefined],
]);
}, e => {
if (!isNow()) {
return;
}
batchSetIn(dispatch, [
[inFlyPath, undefined],
[toExtraData(this.id), undefined],
[toExtraDataError(this.id), e.message || e.toString()],
]);
});
}
async validate (dispatch, getState, oldCC, now) {
const id = this.id;
const clusterConfig = getState().clusterConfig;
const value = this.getData(clusterConfig);
const syncErrorPath = toError(id);
const inFlyPath = toInFly(id);
const oldValue = this.getData(oldCC);
const batches = [];
if (_.get(clusterConfig, inFlyPath)) {
batches.push([inFlyPath, false]);
}
console.debug(`validating ${this.name}`);
const syncError = this.validator(value, clusterConfig, oldValue, oldCC);
if (!_.isEmpty(syncError)) {
console.info(`sync error ${this.name}: ${JSON.stringify(syncError)}`);
batches.push([syncErrorPath, syncError]);
batchSetIn(dispatch, batches);
return false;
}
const oldError = _.get(oldCC, syncErrorPath);
if (!_.isEmpty(oldError)) {
batches.push([syncErrorPath, undefined]);
batchSetIn(dispatch, batches);
}
const isValid = this.isValid(getState().clusterConfig, true);
if (!isValid) {
batchSetIn(dispatch, batches);
return false;
}
if (!this.asyncValidator_) {
batchSetIn(dispatch, batches);
return true;
}
batches.push([inFlyPath, true]);
batchSetIn(dispatch, batches);
let asyncError;
this.updateClock(now);
try {
asyncError = await this.asyncValidator_(dispatch, getState, value, oldValue, this.isNow, oldCC);
} catch (e) {
asyncError = e.message || e.toString();
}
if (this.clock_ !== now) {
console.log(`${this.name} is stale ${this.clock_} ${now}`);
return false;
}
batches.push([inFlyPath, false]);
const asyncErrorPath = toAsyncError(id);
if (!_.isEmpty(asyncError)) {
if (!_.isString(asyncError)) {
console.warn(`asyncError is not a string!?:\n${JSON.stringify(asyncError)}`);
if (asyncError.type && asyncError.payload) {
console.warn('Did you accidentally return a dispatch?');
asyncError = null;
} else {
asyncError = asyncError.toString ? asyncError.toString() : JSON.stringify(asyncError);
}
}
console.log(`asyncError for ${this.name}: ${asyncError}`);
batches.push([asyncErrorPath, asyncError]);
batchSetIn(dispatch, batches);
return false;
}
const oldAsyncError = _.get(getState().clusterConfig, asyncErrorPath);
if (oldAsyncError) {
batches.push([asyncErrorPath, undefined]);
}
batchSetIn(dispatch, batches);
return true;
}
ignoreWhen (dispatch, clusterConfig) {
if (!this.ignoreWhen_) {
return false;
}
const value = !!this.ignoreWhen_(clusterConfig);
console.debug(`ignoring ${this.id} value ${value}`);
setIn(toIgnore(this.id), value, dispatch);
return value;
}
isIgnored (clusterConfig) {
return _.get(clusterConfig, toIgnore(this.id));
}
}
async function promisify (dispatch, getState, oldCC, now, deps, FIELDS) {
const { clusterConfig } = getState();
// TODO: (kans) earlier return [] if not now?
const promises = deps.map(field => {
const { id } = field;
field.ignoreWhen(dispatch, clusterConfig);
return field.getExtraStuff(dispatch, clusterConfig, FIELDS, now)
.then(() => field.validate(dispatch, getState, oldCC, now))
.then(res => {
if (!res) {
console.debug(`${id} is invalid`);
} else {
console.debug(`${id} is valid`);
}
return res && id;
}).catch(err => {
console.error(err);
});
});
return await Promise.all(promises).then(p => p.filter(id => id));
}
export class Field extends Node {
constructor(id, opts = {}) {
super(id, opts);
if (!_.has(opts, 'default')) {
throw new Error(`${id} needs a default`);
}
this.default = opts.default;
}
getData (clusterConfig) {
return clusterConfig[this.id];
}
async update (dispatch, value, getState, FIELDS, FIELD_TO_DEPS, split) {
const oldCC = getState().clusterConfig;
const now = ++ clock_;
let id = this.id;
if (split && split.length) {
id = `${id}.${split.join('.')}`;
}
console.info(`updating ${this.name}`);
// TODO: (kans) - We need to lock the entire validation chain, not just validate proper
setIn(id, value, dispatch);
const isValid = await this.validate(dispatch, getState, oldCC, now);
if (!isValid) {
const dirty = getState().dirty;
if (dirty[this.name]) {
TectonicGA.sendEvent('Validation Error', 'user input', this.name, oldCC[PLATFORM_TYPE]);
}
console.debug(`${this.name} is invalid`);
return;
}
const visited = new Set();
const toVisit = [FIELD_TO_DEPS[this.id]];
if (!toVisit[0].length) {
console.debug(`no deps for ${this.name}`);
return;
}
while (toVisit.length) {
const deps = toVisit.splice(0, 1)[0];
// TODO: check for relationship between deps
const nextDepIDs = await promisify(dispatch, getState, oldCC, now, deps, FIELDS);
nextDepIDs.forEach(depID => {
const nextDeps = _.filter(FIELD_TO_DEPS[depID], d => !visited.has(d.id));
if (!nextDeps.length) {
return;
}
nextDeps.forEach(d => visited.add(d.id));
toVisit.push(nextDeps);
});
}
console.info(`finish validating ${this.name} ${isValid}`);
}
isValid (clusterConfig, syncOnly) {
const id = this.id;
const value = _.get(clusterConfig, id);
const ignore = _.get(clusterConfig, toIgnore(id));
let error = _.get(clusterConfig, toError(id));
if (!error && !syncOnly) {
error = _.get(clusterConfig, toAsyncError(id)) || _.get(clusterConfig, toExtraDataError(id));
}
return ignore || value !== '' && value !== undefined && _.isEmpty(error);
}
inFly (clusterConfig) {
return _.get(clusterConfig, toInFly(this.id)) || _.get(clusterConfig, toExtraDataInFly(this.id));
}
}
export class Form extends Node {
constructor(id, fields, opts = {}) {
super(id, opts);
this.isForm = true;
this.fields = fields;
this.fieldIDs = fields.map(f => f.id);
this.dependencies = [...this.fieldIDs].concat(this.dependencies);
this.errorComponent = connect(
({clusterConfig}) => ({
error: _.get(clusterConfig, toError(id)) || _.get(clusterConfig, toAsyncError(id)),
})
)(ErrorComponent);
registerForm(this, fields);
}
isValid (clusterConfig, syncOnly) {
const ignore = _.get(clusterConfig, toIgnore(this.id));
if (ignore) {
return true;
}
let error = _.get(clusterConfig, toError(this.id));
if (!syncOnly && !error) {
error = _.get(clusterConfig, toAsyncError(this.id));
}
if (error) {
return false;
}
const invalidFields = this.fields.filter(field => !field.isValid(clusterConfig));
return invalidFields.length === 0;
}
getData (clusterConfig) {
return this.fields.filter(f => !f.isIgnored(clusterConfig)).reduce((acc, f) => {
acc[f.name] = f.getData(clusterConfig);
return acc;
}, {});
}
inFly (clusterConfig) {
return _.get(clusterConfig, toInFly(this.id)) || _.some(this.fields, f => f.inFly(clusterConfig));
}
get canNavigateForward () {
return ({clusterConfig}) => !this.inFly(clusterConfig) && this.isValid(clusterConfig);
}
get Errors () {
return this.errorComponent;
}
}
const toValidator = (fields, listValidator) => (value, clusterConfig, oldValue) => {
const errs = listValidator ? listValidator(value, clusterConfig, oldValue) : [];
if (errs && !_.isObject(errs)) {
throw new Error(`FieldLists validator must return an Array-like Object, not:\n${errs}`);
}
_.each(value, (child, i) => {
errs[i] = errs[i] || {};
_.each(child, (childValue, name) => {
// TODO: check that the name is in the field...
const validator = _.get(fields, [name, 'validator']);
if (!validator) {
return;
}
const err = validator(childValue, clusterConfig, _.get(oldValue, [i, name]));
if (!err) {
return;
}
errs[i][name] = err;
});
});
return _.every(errs, err => _.isEmpty(err)) ? {} : errs;
};
const toDefaultOpts = opts => {
const default_ = {};
_.each(opts.fields, (v, k) => {
default_[k] = v.default;
});
return Object.assign({}, opts, {default: [default_], validator: toValidator(opts.fields, opts.validator)});
};
export class FieldList extends Field {
constructor(id, opts = {}) {
super(id, toDefaultOpts(opts));
this.fields = opts.fields;
}
get Map () {
if (this.OuterListComponent_) {
return this.OuterListComponent_;
}
const id = this.id;
const fields = this.fields;
this.OuterListComponent_ = function Outer ({children}) {
return React.createElement(ConnectedFieldList, {id, fields}, children);
};
return this.OuterListComponent_;
}
get addOnClick () {
return () => dispatch_(configActions.appendField(this.id));
}
get NonFieldErrors () {
if (this.errorComponent_) {
return this.errorComponent_;
}
const id = this.id;
this.errorComponent_ = connect(
({clusterConfig}) => ({error: _.get(clusterConfig, toError(id), {})}),
)(({error}) => React.createElement(ErrorComponent, {error: error[-1]}));
return this.errorComponent_;
}
append (dispatch, getState) {
const child = {};
_.each(this.fields, (f, name) => {
child[name] = _.cloneDeep(f.default);
});
append(this.id, child, dispatch);
this.validate(dispatch, getState, getState().clusterConfig, () => true);
}
remove (dispatch, i, getState) {
removeAt(this.id, i, dispatch);
this.validate(dispatch, getState, getState().clusterConfig, () => true);
}
}
|
src/routes/order/query/index.js | terryli1643/daoke-react-c | import React from 'react'
import PropTypes from 'prop-types'
import { routerRedux } from 'dva/router'
import { connect } from 'dva'
import List from './List'
import Filter from './Filter'
const Query = ({ location, dispatch, order, loading }) => {
const { list, pagination, isMotion } = order
const { pageSize } = pagination
const listProps = {
dataSource: list,
loading: loading.effects['order/query'],
pagination,
location,
}
const filterProps = {
isMotion,
filter: {
...location.query,
},
onFilterChange (value) {
dispatch(routerRedux.push({
pathname: location.pathname,
query: {
...value,
page: 1,
pageSize,
},
}))
},
}
return (
<div className="content-inner">
<Filter {...filterProps} />
<List {...listProps} />
</div>
)
}
Query.propTypes = {
order: PropTypes.object,
location: PropTypes.object,
dispatch: PropTypes.func,
loading: PropTypes.object,
activeTabKey: PropTypes.object,
}
export default connect(({ order, loading }) => ({ order, loading }))(Query)
|
src/components/table/Table.js | MMMalik/react-show-app | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Header from './Header';
import Row from './Row';
import Cell from './Cell';
export default class Table extends Component {
static propTypes = {
rows: PropTypes.arrayOf(PropTypes.object),
headers: PropTypes.arrayOf(PropTypes.object),
ranking: PropTypes.bool,
pagination: PropTypes.number
}
static defaultProps = {
rows: [],
headers: [],
ranking: true,
pagination: 20
}
state = {
sort: {
column: null,
sortOrder: 'none'
},
page: 1
}
setSort = (nextColumn) => {
return () => {
const { sortOrder, column } = this.state.sort;
let nextSortOrder = 'asc';
if (nextColumn === column) {
if (sortOrder === 'asc') {
nextSortOrder = 'desc';
}
else if (sortOrder === 'desc') {
nextSortOrder = 'none';
}
}
this.setState({
sort: {
column: nextSortOrder === 'none' ? null : nextColumn,
sortOrder: nextSortOrder
}
});
};
}
handleSort = (rowA, rowB) => {
const { column, sortOrder } = this.state.sort;
if (sortOrder === 'asc') return rowA.cells[column].value > rowB.cells[column].value ? 1 : -1;
else if (sortOrder === 'desc') return rowA.cells[column].value > rowB.cells[column].value ? -1 : 1;
}
onPageClick = (page) => {
return () => {
this.setState({
page
});
};
}
getPages() {
const { rows, pagination } = this.props;
const { page } = this.state;
const pages = rows.length % pagination > 0 ? rows.length / pagination + 1 : rows.length / pagination;
const result = [];
for(let i = 1; i <= pages; i += 1) {
result.push(
<a
key={i}
onClick={this.onPageClick(i)}
className={`btn ${page === i ? 'btn-primary bg-gray' : ''}`}
>
{i}
</a>
);
}
return result;
}
getHeaders() {
const { headers, ranking } = this.props;
const { column, sortOrder } = this.state.sort;
const _headers = headers
.map((header, index) => {
return (
<Header
key={header.id || header.value}
value={header.value}
onClick={header.sortable && this.setSort(index)}
sortable={header.sortable}
sortOrder={column === index ? sortOrder : 'none'}
/>
);
});
return ranking ? [<th key="ranking" />, ..._headers] : _headers;
}
getRows() {
const { rows, headers, ranking, pagination } = this.props;
const {
page,
sort: {
column
}
} = this.state;
const offset = pagination * (page - 1);
if (!rows.length) {
return (
<Row>
<td colSpan={ranking ? headers.length + 1 : headers.length}>
<div className="m2 bold">
No data available
</div>
</td>
</Row>
);
}
const sortedRows = column === null ? rows : [...rows].sort(this.handleSort);
const paginatedRows = pagination ? sortedRows.slice(offset, pagination * page) : sortedRows;
return paginatedRows
.map((row, i) => {
const cells =
row.cells
.map(cell => {
return (
<Cell
key={cell.id || cell.value}
value={cell.value}
/>
);
});
const _cells = ranking ? [(
<Cell
className="center"
key={i + 1}
value={pagination ? i + 1 + offset : i + 1}
/>
), ...cells] : cells;
return (
<Row key={row.id}>
{_cells}
</Row>
);
});
}
render() {
const { pagination } = this.props;
return (
<div>
<table className="table-light">
<thead>
<Row>
{this.getHeaders()}
</Row>
</thead>
<tbody>
{this.getRows()}
</tbody>
</table>
{
pagination &&
<div className="clearfix m2">
<div className="overflow-hidden sm-show center">
{this.getPages()}
</div>
</div>
}
</div>
);
}
}
|
app/jsx/context_cards/Rating.js | djbender/canvas-lms | /*
* Copyright (C) 2016 - 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 PropTypes from 'prop-types'
import I18n from 'i18n!student_context_trayRating'
import classnames from 'classnames'
import {Heading, Rating as InstUIRating, Text} from '@instructure/ui-elements'
class Rating extends React.Component {
static propTypes = {
metric: PropTypes.shape({
level: PropTypes.number
}).isRequired,
label: PropTypes.string.isRequired
}
formatValueText(currentRating, maxRating) {
const valueText = {}
valueText[I18n.t('High')] = currentRating === maxRating
valueText[I18n.t('Moderate')] = currentRating === 2
valueText[I18n.t('Low')] = currentRating === 1
valueText[I18n.t('None')] = currentRating === 0
return classnames(valueText)
}
render() {
const {label, metric} = this.props
return (
<div className="StudentContextTray-Rating">
<Heading level="h5" as="h4">
{label}
</Heading>
<div className="StudentContextTray-Rating__Stars">
<InstUIRating
formatValueText={this.formatValueText}
label={this.props.label}
valueNow={metric.level}
valueMax={3}
/>
<div>
<Text size="small" color="brand">
{this.formatValueText(metric.level, 3)}
</Text>
</div>
</div>
</div>
)
}
}
export default Rating
|
Console/app/node_modules/rc-time-picker/es/Select.js | RisenEsports/RisenEsports.github.io | import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactDom from 'react-dom';
import classnames from 'classnames';
var scrollTo = function scrollTo(element, to, duration) {
var requestAnimationFrame = window.requestAnimationFrame || function requestAnimationFrameTimeout() {
return setTimeout(arguments[0], 10);
};
// jump to target if duration zero
if (duration <= 0) {
element.scrollTop = to;
return;
}
var difference = to - element.scrollTop;
var perTick = difference / duration * 10;
requestAnimationFrame(function () {
element.scrollTop = element.scrollTop + perTick;
if (element.scrollTop === to) return;
scrollTo(element, to, duration - 10);
});
};
var Select = function (_Component) {
_inherits(Select, _Component);
function Select() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Select);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Select.__proto__ || Object.getPrototypeOf(Select)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
active: false
}, _this.onSelect = function (value) {
var _this$props = _this.props,
onSelect = _this$props.onSelect,
type = _this$props.type;
onSelect(type, value);
}, _this.handleMouseEnter = function (e) {
_this.setState({ active: true });
_this.props.onMouseEnter(e);
}, _this.handleMouseLeave = function () {
_this.setState({ active: false });
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Select, [{
key: 'componentDidMount',
value: function componentDidMount() {
// jump to selected option
this.scrollToSelected(0);
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps) {
// smooth scroll to selected option
if (prevProps.selectedIndex !== this.props.selectedIndex) {
this.scrollToSelected(120);
}
}
}, {
key: 'getOptions',
value: function getOptions() {
var _this2 = this;
var _props = this.props,
options = _props.options,
selectedIndex = _props.selectedIndex,
prefixCls = _props.prefixCls;
return options.map(function (item, index) {
var _classnames;
var cls = classnames((_classnames = {}, _defineProperty(_classnames, prefixCls + '-select-option-selected', selectedIndex === index), _defineProperty(_classnames, prefixCls + '-select-option-disabled', item.disabled), _classnames));
var onclick = null;
if (!item.disabled) {
onclick = _this2.onSelect.bind(_this2, item.value);
}
return React.createElement(
'li',
{
className: cls,
key: index,
onClick: onclick,
disabled: item.disabled
},
item.value
);
});
}
}, {
key: 'scrollToSelected',
value: function scrollToSelected(duration) {
// move to selected item
var select = ReactDom.findDOMNode(this);
var list = ReactDom.findDOMNode(this.refs.list);
if (!list) {
return;
}
var index = this.props.selectedIndex;
if (index < 0) {
index = 0;
}
var topOption = list.children[index];
var to = topOption.offsetTop;
scrollTo(select, to, duration);
}
}, {
key: 'render',
value: function render() {
var _classnames2;
if (this.props.options.length === 0) {
return null;
}
var prefixCls = this.props.prefixCls;
var cls = classnames((_classnames2 = {}, _defineProperty(_classnames2, prefixCls + '-select', 1), _defineProperty(_classnames2, prefixCls + '-select-active', this.state.active), _classnames2));
return React.createElement(
'div',
{
className: cls,
onMouseEnter: this.handleMouseEnter,
onMouseLeave: this.handleMouseLeave
},
React.createElement(
'ul',
{ ref: 'list' },
this.getOptions()
)
);
}
}]);
return Select;
}(Component);
Select.propTypes = {
prefixCls: PropTypes.string,
options: PropTypes.array,
selectedIndex: PropTypes.number,
type: PropTypes.string,
onSelect: PropTypes.func,
onMouseEnter: PropTypes.func
};
export default Select; |
lib/ui/src/components/notifications/item.js | storybooks/react-storybook | import React from 'react';
import PropTypes from 'prop-types';
import { styled, lighten, darken } from '@storybook/theming';
import { Link } from '@storybook/router';
const baseStyle = ({ theme }) => ({
display: 'block',
padding: '16px 20px',
borderRadius: 10,
fontSize: theme.typography.size.s1,
fontWeight: theme.typography.weight.bold,
lineHeight: `16px`,
boxShadow: '0 5px 15px 0 rgba(0, 0, 0, 0.1), 0 2px 5px 0 rgba(0, 0, 0, 0.05)',
color: theme.color.inverseText,
backgroundColor:
theme.base === 'light' ? darken(theme.background.app) : lighten(theme.background.app),
textDecoration: 'none',
});
const NotificationLink = styled(Link)(baseStyle);
const Notification = styled.div(baseStyle);
export const NotificationItemSpacer = styled.div({
height: 48,
});
export default function NotificationItem({ notification: { content, link } }) {
return link ? (
<NotificationLink to={link}>{content}</NotificationLink>
) : (
<Notification>{content}</Notification>
);
}
NotificationItem.propTypes = {
notification: PropTypes.shape({
content: PropTypes.string.isRequired,
link: PropTypes.string,
}).isRequired,
};
|
src/containers/Sales/CustomDetail/Order/Order.js | UncleYee/crm-ui | import React from 'react';
import TabItem from '../TabItem';
import Modal from 'react-bootstrap/lib/Modal';
import Button from 'react-bootstrap/lib/Button';
import {connect} from 'react-redux';
import {getCustomOrder} from 'redux/modules/custom';
import order from './order.png';
// ่ฎขๅ
@connect(state => ({
customOrder: state.custom.customOrder
}), {
getCustomOrder
})
export default class Chance extends React.Component {
static propTypes = {
getCustomOrder: React.PropTypes.func,
customOrder: React.PropTypes.object,
tenantId: React.PropTypes.string,
contractFlag: React.PropTypes.string
};
constructor(props) {
super(props);
this.state = {
id: '',
showModal: false
};
}
componentDidMount() {
this.props.getCustomOrder(this.props.tenantId);
}
close = () => {
this.setState({ showModal: false });
}
open = (id) => {
this.setState({
id,
showModal: true
});
}
render() {
const customOrder = this.props.customOrder || {};
const info = customOrder.list || [];
const styles = require('../ContactRecord/ContactRecord.scss');
const orderStyles = require('./Order.scss');
const Log = (props) => {
return (
<div className={styles.item} onClick={() => this.open(props.id)}>
<span className={orderStyles.detail}>
<span className={styles.label}>็ๆฌๅ็งฐ๏ผ</span>
{props.version}
</span>
<br/>
<span className={orderStyles.detail}>
<span className={styles.label}>่ฎขๅ้้ข๏ผ</span>
{props.amount}
</span>
<span className={orderStyles.detail}>
<span className={styles.label}>่ฎขๅๆปไบบๆฐ๏ผ</span>
{props.totaluser}
</span>
<span className={orderStyles.detail}>
<span className={styles.label}>ๅทฒๅผ็ฅจ๏ผ</span>
{props.invoicedamount}
</span>
<span className={orderStyles.detail}>
<span className={styles.label}>ๅทฒๅๆฌพ๏ผ</span>
{props.paymentamount}
</span>
<br/>
<span className={orderStyles.detail}>
<span className={styles.label}>็ง็จๆฅๆ๏ผ</span>
{props.rentduration}
</span>
</div>
);
};
return (
<div>
<TabItem img={order} close title={`่ฎขๅ(${customOrder.total || 0})`} icon={this.props.contractFlag === '1'} iconClick={() => window.top._hack_tab('queryTenantContractChartListInit.action?auditFlag=0', 2003, '่ฎขๅๅฝๅ
ฅ')}>
<div className={orderStyles.items}>
{info.map((item, index)=> {
return <Log key={index} {...item}/>;
})}
</div>
</TabItem>
<Modal dialogClassName={orderStyles.model} bsSize="large" show={this.state.showModal} onHide={this.close}>
<Modal.Header closeButton>
<Modal.Title>่ฎขๅ่ฏฆๆ
</Modal.Title>
</Modal.Header>
<Modal.Body>
<iframe className={orderStyles.iframe} src={`/tenantContractChartCheck.action?contractId=${this.state.id}&status=view`} frameBorder="0"></iframe>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.close}>ๅ
ณ้ญ</Button>
</Modal.Footer>
</Modal>
</div>
);
}
}
|
client/src/js/components/UserTile.js | muhammad-saleh/weightlyio | "use strict";
import React from 'react';
import UserStore from '../stores/UserStore';
import Constants from '../constants/Constants';
import AddWeight from './AddWeight';
import FloatingActionButton from 'material-ui/lib/floating-action-button';
import Card from './common/card';
export default class UserTile extends React.Component {
componentWillMount() {
this.state = UserStore.getState();
}
// profilePic(user) {
// if (user) {
// switch (user.provider) {
// case 'facebook':
// return `http://graph.facebook.com/${user.data.id}/picture`
// break;
// default:
// return `http://placehold.it/50x50`
//
// }
// }
// }
//
// userName(user) {
// if (user) {
// switch (user.provider) {
// case 'facebook':
// return user.data.first_name + ' ' + user.data.last_name
// break;
// default:
// return user.username
//
// }
// }
// }
handleLogout(e) {
e.preventDefault();
localStorage.removeItem('userToken');
window.location.hash = '';
window.location.href = window.location.href;
}
render() {
return (
<Card cssClass="userComponent">
<div className="userProfile">
<img src={this.state.user.picture} alt="User Image" className="img-circle"/>
</div>
<div className="allInfo">
<div className="userData">
<div className="userInfo">{this.state.user.name}</div>
<div className="logoutLink"><a onClick={this.handleLogout}>Logout</a></div>
</div>
<div className="addWeightBtn"><AddWeight/></div>
</div>
</Card>
)
}
}
|
client/src/components/setup-workflow/lists_configuration.js | safv12/trello-metrics | 'use strict';
import React, { Component } from 'react';
import HTML5Backend from 'react-dnd-html5-backend';
import OpenLists from './open_lists';
import DoneLists from './done_lists';
import IgnoreLists from './ignore_lists';
import InprogressLists from './inprogress_lists';
const ListConfiguration = ({ignoreLists, openLists, onMoveList,
inprogressLists, doneLists}) => {
return (
<div>
<div className="col-md-2 padding-s">
<IgnoreLists
className="list-group boards-list"
lists={ ignoreLists }
onMoveList={onMoveList} />
</div>
<div className="col-md-2 padding-s">
<OpenLists
className="list-group boards-list"
lists={ openLists }
onMoveList={onMoveList} />
</div>
<div className="col-md-2 padding-s">
<InprogressLists
className="list-group boards-list"
lists={ inprogressLists }
onMoveList={onMoveList} />
</div>
<div className="col-md-2 padding-s">
<DoneLists
className="list-group boards-list"
lists={ doneLists }
onMoveList={onMoveList} />
</div>
</div>
);
};
export const ItemTypes = {
CARD: 'card'
};
export default ListConfiguration;
|
src/routes/not-found/NotFound.js | jessiepullaro414/kiwi | /**
* 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 PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './NotFound.css';
class NotFound extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
};
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>{this.props.title}</h1>
<p>Sorry, the page you were trying to view does not exist.</p>
</div>
</div>
);
}
}
export default withStyles(s)(NotFound);
|
examples/counter/test/components/Counter.spec.js | jairtrejo/madera | import test from 'ava';
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import { Counter } from '../../components/Counter.jsx';
test('it renders two buttons', t => {
const wrapper = shallow(<Counter count={ 0 }/>);
t.is(wrapper.find('button').length, 2);
})
test('it calls inc on inc button click', t => {
const inc = sinon.spy();
const wrapper = shallow(<Counter inc={ inc }/>);
wrapper.find('#inc-btn').simulate('click');
t.true(inc.calledOnce);
})
test('it calls dec on dec button click', t => {
const dec = sinon.spy();
const wrapper = shallow(<Counter dec={ dec }/>);
wrapper.find('#dec-btn').simulate('click');
t.true(dec.calledOnce);
})
|
examples/with-mobx/pages/index.js | BlancheXu/test | import React from 'react'
import Page from '../components/Page'
export default class Counter extends React.Component {
render() {
return <Page title="Index Page" linkTo="/other" />
}
}
|
es/components/Form/Button.js | welovekpop/uwave-web-welovekpop.club | import _extends from "@babel/runtime/helpers/builtin/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/builtin/objectWithoutProperties";
import cx from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import MuiButton from "@material-ui/core/es/Button";
var Button = function Button(_ref) {
var children = _ref.children,
className = _ref.className,
text = _ref.text,
props = _objectWithoutProperties(_ref, ["children", "className", "text"]);
return React.createElement(MuiButton, _extends({
variant: "raised",
color: "primary",
className: cx('Button', className),
type: "submit"
}, props), text || children);
};
Button.propTypes = process.env.NODE_ENV !== "production" ? {
className: PropTypes.string,
text: PropTypes.string,
children: PropTypes.node
} : {};
export default Button;
//# sourceMappingURL=Button.js.map
|
react-redux-tutorial/01-setting-up/modules/App.js | react-scott/react-learn | /**
* Created by scott on 7/8/16.
*/
import React from 'react'
export default React.createClass({
render() {
return <div> Hello, React Router!</div>
}
})
|
src/containers/DashboardPage.js | dopry/netlify-cms | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { SIMPLE, EDITORIAL_WORKFLOW } from '../constants/publishModes';
import history from '../routing/history';
import UnpublishedEntriesPanel from './editorialWorkflow/UnpublishedEntriesPanel';
class DashboardPage extends Component {
componentWillMount() {
if (this.props.publishMode === SIMPLE) {
history.push(`/collections/${ this.props.firstCollection }`);
}
}
render() {
return (
<div>
<h1>Dashboard</h1>
<UnpublishedEntriesPanel />
</div>
);
}
}
DashboardPage.propTypes = {
firstCollection: PropTypes.string,
publishMode: PropTypes.oneOf([SIMPLE, EDITORIAL_WORKFLOW]),
};
function mapStateToProps(state) {
const { config, collections } = state;
return {
firstCollection: collections.first().get('name'),
publishMode: config.get('publish_mode'),
};
}
export default connect(mapStateToProps)(DashboardPage);
|
src/components/external/TestTimePicker.js | ChrisWhiten/react-rink | import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import classNames from 'classnames';
import _ from 'lodash';
import './TestTimePicker.css';
class TestTimePicker extends React.Component {
constructor(props) {
super(props);
this.state = {
};
this.onStartChange = this.onStartChange.bind(this);
this.onEndChange = this.onEndChange.bind(this);
}
componentDidMount() {
}
componentWillUnmount() {
}
onStartChange(e) {
this.props.onStartChange(e.target.value);
}
onEndChange(e) {
this.props.onEndChange(e.target.value);
}
render() {
const hourLabelClassName = classNames('hour-label', {
empty: !this.props.selectedStartTime
});
const disabledState = !this.props.selectedStartTime;
console.log('disabled state', disabledState)
return (
<div className='test-time-picker'>
<h4 className='test-time-picker-date'>
Saturday, January 5th
</h4>
<div className='hour-picker'>
{/* Start time */}
<div className='hour-wrapper'>
<div className={hourLabelClassName}>Starts</div>
<div className='select-container'>
<select className='hour-select' name='start' onChange={this.onStartChange}>
<option value>---</option>
{
this.props.availableStartTimes.map(t => {
return <option key={`start-${t.format('HH:mm')}`} value={t.format('HH:mm')}>{t.format('hh:mm A')}</option>
})
}
</select>
<div className='select-display'>{this.props.selectedStartTime && this.props.selectedStartTime.format('hh:mm A')}</div>
<div className='select-down-arrow'>
<svg width='20' height='45' viewBox='0 0 24 24'>
<g fill='none' fillRule='evenodd'>
<path d='M0 0h24v24H0z'></path>
<path fill='#9a9fa6' d='M6.697 10.354c-.195-.196-.138-.354.147-.354h10.312c.277 0 .338.163.147.354l-4.95 4.949a.505.505 0 0 1-.707 0l-4.949-4.95z'></path>
</g>
</svg>
</div>
</div>
</div>
{/* Separator arrow */}
<div className='test-time-picker-arrow'>
<svg className='test-time-picker-arrow-svg' width='16' height='16' viewBox='0 0 19 19'>
<path d='M10.7 0v14.394l6.597-6.597L19 9.5 9.5 19 0 9.5l1.703-1.703L8.3 14.394V0h2.4z' fill='#444B53' fillRule='evenodd'></path>
</svg>
</div>
{/* End time */}
<div className='hour-wrapper'>
<div className={hourLabelClassName}>Ends</div>
<div className='select-container'>
<select className='hour-select' name='end' onChange={this.onEndChange} disabled={disabledState}>
{
this.props.availableEndTimes && this.props.availableEndTimes.map(t => {
return <option key={`end-${t.format('HH:mm')}`} value={t.format('HH:mm')}>
{t.format('hh:mm A')} ({moment.duration(t.diff(this.props.selectedStartTime)).as('hours')} hours)
</option>
})
}
</select>
<div className='select-display'>{this.props.selectedEndTime && this.props.selectedEndTime.format('hh:mm A')}</div>
<div className='select-down-arrow'>
<svg width='20' height='45' viewBox='0 0 24 24'>
<g fill='none' fillRule='evenodd'>
<path d='M0 0h24v24H0z'></path>
<path fill='#9a9fa6' d='M6.697 10.354c-.195-.196-.138-.354.147-.354h10.312c.277 0 .338.163.147.354l-4.95 4.949a.505.505 0 0 1-.707 0l-4.949-4.95z'></path>
</g>
</svg>
</div>
</div>
</div>
</div>
</div>
);
}
}
TestTimePicker.propTypes = {
availableStartTimes: PropTypes.array,
};
export default TestTimePicker;
|
src/components/Note/Thumbnail/DCRecording.js | bibleexchange/be-front-new | import React from 'react';
import { Link } from 'react-router';
class DCRecordingNoteComponent extends React.Component {
render() {
return (
<div className='recording'>
<p>{this.props.recording.text}</p>
</div>
);
}
}
export default DCRecordingNoteComponent;
|
components/Video/PlayBtn/PlayBtn.js | NGMarmaduke/bloom | import PropTypes from 'prop-types';
import React from 'react';
import noop from '../../../utils/noop';
import ScreenReadable from '../../ScreenReadable/ScreenReadable';
import BtnContainer from '../../BtnContainer/BtnContainer';
import Icon from '../../Icon/Icon';
import css from './PlayBtn.css';
const PlayBtn = ({ play, pause, paused }) => {
const togglePlay = paused ? play : pause;
return (
<BtnContainer
className={ css.root }
onClick={ togglePlay }
>
{ paused ? (
<span>
<Icon name="play-c" className={ css.icon } />
<ScreenReadable>Play</ScreenReadable>
</span>
) : (
<ScreenReadable>Pause</ScreenReadable>
) }
</BtnContainer>
);
};
PlayBtn.propTypes = {
play: PropTypes.func,
pause: PropTypes.func,
paused: PropTypes.bool.isRequired,
};
PlayBtn.propTypes = {
play: noop,
pause: noop,
};
export default PlayBtn;
|
client/client.js | cesarandreu/quad-blog | // Polyfills
import 'whatwg-fetch'
import React from 'react'
import debug from 'debug'
import app from './app'
const log = debug('quad-blog:client:bootstrap')
// Get application node
const mountNode = document.getElementById('app')
// Debug messages
if (process.env.NODE_ENV !== 'production') {
debug.enable('quad-blog:*,Fluxible:*')
}
// Rehydrate if global.app is defined
// Otherwise bootstrap with a new context
if (global.app) {
app.rehydrate(global.app, bootstrap)
} else {
bootstrap(null, app.createContext())
}
/**
* Bootstrap the app
*/
function bootstrap (err, context) {
if (err) throw err
// For chrome dev tool support and debugging
global.context = context
global.React = React
log('React rendering')
React.render(context.createElement(), mountNode, () => {
log('React rendered')
})
}
|
src/components/Register/Register.js | sbiliaiev/transport-kharkiv | import React from 'react';
export default class Register extends React.Component {
render() {
return(<p>Register</p>);
}
} |
Badmeat/src/components/common/Spinner.js | jparr721/Badmeat | import React from 'react';
import { View, ActivityIndicator } from 'react-native';
const Spinner = (props) => {
return (
<View style={styles.spinnerStyle}>
<ActivityIndicator size={props.size || 'large'} />
</View>
)
};
const styles = {
spinnerStyle: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
};
export { Spinner };
|
react-family/src/router/router.js | DayangLee/Programming-learning | import React from 'react'
import {BrowserRouter as Router, Route, Switch, Link} from 'react-router-dom'
import Home from 'pages/Home/Home'
import Page1 from 'pages/Page1/Page1'
const getRouter = () => (
<Router>
<div>
<ul>
<li><Link to="/">้ฆ้กต</Link></li>
<li><Link to="/page1">Page1</Link></li>
</ul>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/page1" component={Page1}/>
</Switch>
</div>
</Router>
)
export default getRouter |
test/test_helper.js | briceth/reactBlog | import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
scripts/App.js | MarshalW/react-sortable | 'use strict';
import React, { Component } from 'react';
import update from 'react/lib/update';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd/modules/backends/HTML5';
import Item from './Item';
const style = {
width: '400px'
};
export default class App extends Component {
constructor(props){
super(props);
this.moveItem = this.moveItem.bind(this);
this.handleClick=this.handleClick.bind(this);
this.state = {
items: [{
id: 1,
text: 'ๅปบ็ซๅบๆฌ็ฅ่ฏ'
}, {
id: 2,
text: '่ฟๅๆๅ็ๅณๅฟ๏ผๆ
็ปช็็บชๅพ'
}, {
id: 3,
text: 'ๅบๆฌ้ขๅๆ'
}, {
id: 4,
text: 'ๆๆฏๅๆ'
}, {
id: 5,
text: 'ๆๆไบคๆ'
}, {
id: 6,
text: 'ไบคๆ่
็ๅฟ็ๆถๆ'
}],
selected:undefined
};
}
handleClick(id){
this.setState({
selected:id
});
}
moveItem(id, afterId) {
const { items } = this.state;
const item = items.filter(i => i.id === id)[0];
const afterItem = items.filter(i => i.id === afterId)[0];
const itemIndex = items.indexOf(item);
const afterIndex = items.indexOf(afterItem);
this.setState(update(this.state, {
items: {
$splice: [
[itemIndex, 1],
[afterIndex, 0, item]
]
}
}));
}
render(){
const {items}=this.state;
return (
<div style={style}>
{items.map(item=>{
return (
<Item key={item.id} id={item.id} text={item.text} moveItem={this.moveItem} handleClick={this.handleClick} selected={this.state.selected} target={this}/>
);
})}
</div>
);
}
}
export default DragDropContext(HTML5Backend)(App);
|
docs/app/Examples/collections/Grid/Content/GridExampleRows.js | koenvg/Semantic-UI-React | import React from 'react'
import { Grid, Image } from 'semantic-ui-react'
const GridExampleRows = () => (
<Grid columns={3}>
<Grid.Row>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/paragraph.png' />
</Grid.Column>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/paragraph.png' />
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/paragraph.png' />
</Grid.Column>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/paragraph.png' />
</Grid.Column>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/paragraph.png' />
</Grid.Column>
</Grid.Row>
</Grid>
)
export default GridExampleRows
|
admin/client/App/elemental/DropdownButton/index.js | rafmsou/keystone | /* eslint quote-props: ["error", "as-needed"] */
import React from 'react';
import { css, StyleSheet } from 'aphrodite/no-important';
import Button from '../Button';
function DropdownButton ({ children, ...props }) {
return (
<Button {...props}>
{children}
<span className={css(classes.arrow)} />
</Button>
);
};
// NOTE
// 1: take advantage of `currentColor` by leaving border top color undefined
// 2: even though the arrow is vertically centered, visually it appears too low
// because of lowercase characters beside it
const classes = StyleSheet.create({
arrow: {
borderLeft: '0.3em solid transparent',
borderRight: '0.3em solid transparent',
borderTop: '0.3em solid', // 1
display: 'inline-block',
height: 0,
marginTop: '-0.125em', // 2
verticalAlign: 'middle',
width: 0,
// add spacing
':first-child': {
marginRight: '0.5em',
},
':last-child': {
marginLeft: '0.5em',
},
},
});
module.exports = DropdownButton;
|
src/parser/priest/shadow/modules/spells/Voidform.js | sMteX/WoWAnalyzer | import React from 'react';
import { formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';
import { TooltipElement } from 'common/Tooltip';
import Analyzer from 'parser/core/Analyzer';
import Haste from 'parser/shared/modules/Haste';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import Panel from 'interface/others/Panel';
import Insanity from '../core/Insanity';
import VoidformsTab from './VoidformsTab';
const debug = false;
const logger = (message, color) => debug && console.log(`%c${message.join(' ')}`, `color: ${color}`);
const VOID_FORM_ACTIVATORS = [
SPELLS.VOID_ERUPTION.id,
SPELLS.DARK_ASCENSION_TALENT.id,
];
class Voidform extends Analyzer {
static dependencies = {
insanity: Insanity,
haste: Haste,
};
_previousVoidformCast = null;
_totalHasteAcquiredOutsideVoidform = 0;
_totalLingeringInsanityTimeOutsideVoidform = 0;
_inVoidform = false;
_voidforms = {};
get voidforms() {
return Object.keys(this._voidforms).map(key => this._voidforms[key]);
}
get nonExcludedVoidforms() {
return this.voidforms.filter(voidform => !voidform.excluded);
}
get averageVoidformStacks() {
if (this.voidforms.length === 0) {
return 0;
}
// ignores last voidform if seen as skewing
return this.nonExcludedVoidforms.reduce((p, c) => p + c.stacks.length, 0) / this.nonExcludedVoidforms.length;
}
get averageVoidformHaste() {
if (!this.currentVoidform) {
return (1 + this.haste.current);
}
const averageHasteGainedFromVoidform = (this.voidforms.reduce((total, voidform) => total + voidform.averageGainedHaste, 0)) / this.voidforms.length;
return (1 + this.haste.current) * (1 + averageHasteGainedFromVoidform);
}
get averageNonVoidformHaste() {
return (1 + this.haste.current) * (1 + (this._totalHasteAcquiredOutsideVoidform / this._totalLingeringInsanityTimeOutsideVoidform) / 100);
}
get inVoidform() {
return this.selectedCombatant.hasBuff(SPELLS.VOIDFORM_BUFF.id);
}
get currentVoidform() {
if (this.voidforms && this.voidforms.length > 0) {
return this._voidforms[this.voidforms[this.voidforms.length - 1].start];
} else {
return false;
}
}
get uptime() {
return this.selectedCombatant.getBuffUptime(SPELLS.VOIDFORM_BUFF.id) / (this.owner.fightDuration - this.selectedCombatant.getBuffUptime(SPELLS.DISPERSION.id));
}
get normalizeTimestamp() {
return (event) => Math.round((event.timestamp - this.currentVoidform.start) / 10) * 10;
}
get addVoidformEvent() {
return (name, event) => {
if (this.currentVoidform) {
this.currentVoidform[name] = [
...this.currentVoidform[name],
event,
];
}
};
}
addVoidformStack(event) {
if (!this.currentVoidform) return;
this.currentVoidform.stacks = [
...this.currentVoidform.stacks,
{ stack: event.stack, timestamp: this.normalizeTimestamp(event) },
];
logger(['Added voidform stack:', event.stack, `at`, this.normalizeTimestamp(event)], 'green');
}
removeLingeringInsanityStack(event) {
if (this.inVoidform) {
this.currentVoidform.lingeringInsanityStacks = [
...this.currentVoidform.lingeringInsanityStacks,
{ stack: event.stack, timestamp: this.normalizeTimestamp(event) },
];
logger(['Removed lingering stack:', event.stack, 'at', this.normalizeTimestamp(event)], 'orange');
} else {
this._totalHasteAcquiredOutsideVoidform += event.stack;
this._totalLingeringInsanityTimeOutsideVoidform += 1;
}
}
startVoidform(event) {
this._voidforms[event.timestamp] = {
start: event.timestamp,
lingeringInsanityStacks: [],
stacks: [],
excluded: false,
averageGainedHaste: 0,
[SPELLS.MINDBENDER_TALENT_SHADOW.id]: [],
[SPELLS.VOID_TORRENT_TALENT.id]: [],
[SPELLS.DISPERSION.id]: [],
};
logger(['Started voidform at:', event.timestamp], 'purple');
this.addVoidformStack({ ...event, stack: 1 });
}
endVoidform(event) {
this.currentVoidform.duration = this.normalizeTimestamp(event);
// artificially adds the starting lingering insanity stack:
if (this.currentVoidform.lingeringInsanityStacks.length > 0) {
const { stack: nextStack } = this.currentVoidform.lingeringInsanityStacks[0];
this.currentVoidform.lingeringInsanityStacks = [
{ stack: nextStack + 2, timestamp: 0 },
...this.currentVoidform.lingeringInsanityStacks,
];
}
// calculates the average gained haste from voidform stacks & lingering insanity within the voidform:
this.currentVoidform.averageGainedHaste = (this.currentVoidform.stacks.reduce((total, { stack, timestamp }, i) => {
const nextTimestamp = this.currentVoidform.stacks[i + 1] ? this.currentVoidform.stacks[i + 1].timestamp : timestamp + 1000;
return total + ((nextTimestamp - timestamp) / 1000) * stack / 100;
}, 0) + this.currentVoidform.lingeringInsanityStacks.reduce((total, { stack, timestamp }, i) => {
const nextTimestamp = this.currentVoidform.lingeringInsanityStacks[i + 1] ? this.currentVoidform.lingeringInsanityStacks[i + 1].timestamp : timestamp + 1000;
return total + ((nextTimestamp - timestamp) / 1000) * stack / 100;
}, 0)) / (this.currentVoidform.duration / 1000);
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (VOID_FORM_ACTIVATORS.includes(spellId)) {
this.startVoidform(event);
}
}
on_byPlayer_removebuff(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.VOIDFORM_BUFF.id) {
this.endVoidform(event);
}
}
on_byPlayer_applybuffstack(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.VOIDFORM_BUFF.id) {
if (!this.currentVoidform) {
// for prepull voidforms
this.startVoidform(event);
}
this.addVoidformStack(event);
}
}
on_byPlayer_removebuffstack(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.LINGERING_INSANITY.id) this.removeLingeringInsanityStack(event);
}
on_fightend() {
if (this.selectedCombatant.hasBuff(SPELLS.VOIDFORM_BUFF.id)) {
// excludes last one to avoid skewing the average (if in voidform when the encounter ends):
const averageVoidformStacks = this.voidforms.slice(0, -1).reduce((p, c) => p + c.stacks.length, 0) / (this.voidforms.length - 1);
const lastVoidformStacks = this.currentVoidform.stacks.length;
if (lastVoidformStacks + 5 < averageVoidformStacks) {
this.currentVoidform.excluded = true;
}
// end last voidform of the fight:
this.endVoidform({ timestamp: this.owner._timestamp });
}
debug && console.log(this.voidforms);
}
get suggestionUptimeThresholds() {
return {
actual: this.uptime,
isLessThan: {
minor: 0.7,
average: 0.65,
major: 0.6,
},
style: 'percentage',
};
}
get suggestionStackThresholds() {
return (voidform) => ({
actual: voidform.stacks.length,
isLessThan: {
minor: 20,
average: 19,
major: 18,
},
style: 'number',
});
}
suggestions(when) {
const {
isLessThan: {
minor,
average,
major,
},
} = this.suggestionUptimeThresholds;
when(this.uptime).isLessThan(minor)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<>Your <SpellLink id={SPELLS.VOIDFORM.id} /> uptime can be improved. Try to maximize the uptime by using your insanity generating spells and cast <SpellLink id={SPELLS.MINDBENDER_TALENT_SHADOW.id} /> on cooldown.
<br /><br />
Use the generators with the priority: <br />
<SpellLink id={SPELLS.VOID_BOLT.id} /> <br />
<SpellLink id={SPELLS.MIND_BLAST.id} /> <br />
<SpellLink id={SPELLS.MIND_FLAY.id} />
</>)
.icon(SPELLS.VOIDFORM_BUFF.icon)
.actual(`${formatPercentage(actual)}% Voidform uptime`)
.recommended(`>${formatPercentage(recommended)}% is recommended`)
.regular(average).major(major);
});
}
statistic() {
return (
<StatisticBox
position={STATISTIC_ORDER.CORE(1)}
icon={<SpellIcon id={SPELLS.VOIDFORM.id} />}
value={`${formatPercentage(this.selectedCombatant.getBuffUptime(SPELLS.VOIDFORM_BUFF.id) / (this.owner.fightDuration - this.selectedCombatant.getBuffUptime(SPELLS.DISPERSION.id)))} %`}
label={(
<TooltipElement content={`Time spent in dispersion (${Math.round(this.selectedCombatant.getBuffUptime(SPELLS.DISPERSION.id) / 1000)} seconds) is excluded from the fight.`}>
Voidform uptime
</TooltipElement>
)}
/>
);
}
tab() {
return {
title: 'Voidforms',
url: 'voidforms',
render: () => (
<Panel>
<VoidformsTab
voidforms={this.voidforms}
insanityEvents={this.insanity.events}
fightEnd={this.owner.fight.end_time}
surrenderToMadness={!!this.selectedCombatant.hasTalent(SPELLS.SURRENDER_TO_MADNESS_TALENT.id)}
/>
</Panel>
),
};
}
}
export default Voidform;
|
app/components/Img/index.js | kaizen7-nz/gold-star-chart | /**
*
* Img.js
*
* Renders an image, enforcing the usage of the alt="" tag
*/
import React from 'react';
import PropTypes from 'prop-types';
function Img(props) {
return (
<img className={props.className} src={props.src} alt={props.alt} />
);
}
// We require the use of src and alt, only enforced by react in dev mode
Img.propTypes = {
src: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object,
]).isRequired,
alt: PropTypes.string.isRequired,
className: PropTypes.string,
};
export default Img;
|
components/Message.js | athoof/odi | import React from 'react';
import {
AppRegistry,
StyleSheet,
View,
Text,
Dimensions,
TouchableOpacity,
Modal,
ScrollView,
Image,
TextInput,
Button,
} from 'react-native';
import _ from 'lodash';
// import io from 'socket.io-client';
// const socket = io('http://faharu.com:8000');
export default class Message extends React.Component {
constructor(props) {
super(props);
this.state = {
text: '',
selectedRecipient: null,
messageBuffer: [],
messageBufferParsed: [],
userList: [],
touchableOpacityArray: [],
users: [],
channel: 'lobby',
};
// this.socket = this.socket;
this.socket = new WebSocket('ws://faharu.com:8000');
// this.socket = new WebSocket('ws://faharu.com:8000/?ch=' + this.state.channel);
}
sendMessage() {
let d = new Date();
let timestamp = d.getTime();
let request = {
type: 'sendMessage',
fromClient: this.props.user.id,
users: this.state.users,
message: {
sender : this.props.user.id,
recipient : this.state.selectedRecipient,
messageBody : this.state.text,
timestamp : timestamp,
}
}
this.socket.send(JSON.stringify(request));
this.requestLoadMessages(this.state.selectedRecipient)
// }
this.textInput.clear();
}
clearBuffer() {
this.setState({messageBuffer: [], messageBufferParsed: []});
}
requestLoadMessages(selectedRecipient) {
let userArr = [this.props.user.id, selectedRecipient];
userArr = userArr.sort();
if (selectedRecipient !== this.state.selectedRecipient) {
console.log('conz selectedRecipient does not match', selectedRecipient, this.state.selectedRecipient)
this.clearBuffer();
}
let request = {
type: 'loadMessages',
fromClient: this.props.user.id,
users: userArr ? userArr : this.state.users,
};
this.socket.send(JSON.stringify(request));
}
parseMessageBuffer(messageBuffer) {
var mArr = [];
let buffer = messageBuffer ? messageBuffer : this.state.messageBuffer
if (typeof buffer !== 'undefined' && buffer !== null) {
// console.log('conzBUFFER', JSON.stringify(buffer))
buffer.messages.forEach((message) => {
let styleArr = [styles.chatBubble];
if (message.recipient == this.props.user) {
styleArr = [styles.chatBubble, styles.receivedChat];
}
mArr.push(<Text style={styleArr}>{message.messageBody}</Text>)
})
this.setState({messageBufferParsed: mArr});
if (!messageBuffer) return mArr;
} else {
return <Text style={styles.chatBubble}>No messages</Text>;
}
}
selectRecipient(user) {
let userArr = [this.props.user.id, user];
userArr = userArr.sort();
this.setState({selectedRecipient: user, users: userArr}, () => {
this.requestLoadMessages(this.state.selectedRecipient);
});
}
onLoadMessages(messageBuffer, users) {
// this.requestLoadMessages(this.state.selectedRecipient);
// console.log('conz loadMessages::', data.messageBuffer)
this.setState({
messageBuffer: messageBuffer,
// selectedRecipient: this.state.selectedRecipient,
users: users
});
console.log('conz::onLoadMessages', messageBuffer)
this.parseMessageBuffer(messageBuffer);
}
onAddNode() {
}
onUserUpdate() {
}
makeTouchableOpacity(userList, callback) {
if(userList !== null) {
console.log('conz userList', userList)
this.setState({userList: userList});
var touchArray = []
userList.forEach((user) => {
if (user.id !== this.props.user.id) {
touchArray.push(
<TouchableOpacity
style={styles.user}
onPress={() => { this.selectRecipient(user.id); } }
>
<Text style={styles.username}>{user.name}</Text>
<Image style={styles.photo} source={{uri: user.photo}} />
<View style={styles.overlay} />
</TouchableOpacity>
);
}
})
callback(null, touchArray);
this.setState({touchableOpacityArray: touchArray});
} else {
callback('No array');
console.log('conz no touchableOpacityArray')
}
}
onMessageReceived() {
this.onLoadMessages();
}
componentDidMount() {
this.socket.onopen = () => {
console.log('conz::onopen/message:8000');
this.socket.onmessage = (event) => {
let data = JSON.parse(event.data);
console.log('conz::onmessage/main.js', event)
// console.log('conz userList 1 ::', JSON.stringify(data.userList))
switch (data.type) {
case 'onLoadMessages':
console.log('conz::onLoadMessages')
this.onLoadMessages(data.messageBuffer, data.users);
break;
case 'onAddNode':
// this.requestLoadMessages();
break;
case 'onMessageReceived':
this.requestLoadMessages(this.state.selectedRecipient);
break;
case 'onGetUsers':
// console.log('conz userList 2 ::', data.userList)
this.setState({userList: data.userList});
// this.onGetUsers(data.userList);
this.makeTouchableOpacity(this.state.userList, (err, res) => {
if (err) throw err;
// console.log('conz touchable', res);
this.setState({touchableOpacityArray: res})
})
break;
case 'onSendMessage':
this.requestLoadMessages(this.state.selectedRecipient);
break;
}
}
}
}
componentWillUnmount() {
this.socket.close();
}
render() {
return (
<View style={styles.sidebar}>
<Text style={styles.label}>
Messaging
</Text>
<ScrollView style={styles.recipients} contentContainerStyle={styles.contentContainer} horizontal={true}>
{this.state.touchableOpacityArray}
</ScrollView>
<ScrollView
ref={ref => this.scrollView = ref}
style={styles.chatView}
contentContainerStyle={styles.chatContainer}
horizontal={false}
onContentSizeChange={(contentWidth, contentHeight) => {
this.scrollView.scrollToEnd({animated: true});
}}
>
{this.state.messageBufferParsed}
</ScrollView>
<TextInput
style={styles.textInput}
ref={(input) => { this.textInput = input }}
placeholder="Type a message"
onChangeText={(text) => {this.setState({text: text})} }
onSubmitEditing={() => { this.sendMessage(); }}
editable={this.state.selectedRecipient ? true : false}
/>
</View>
)
}
}
/*<Text style={[styles.chatBubble, styles.receivedChat]}>Receiving chat bubble</Text>
<Text style={styles.chatBubble}>This is an average length text message, with punctuations!</Text>
<Text style={styles.chatBubble}>This is an average length text message, with punctuations!</Text>*/
const styles = StyleSheet.create({
sidebar: {
...StyleSheet.absoluteFillObject,
backgroundColor: 'white',
alignItems: 'center',
},
label: {
fontSize: 24,
padding: 12,
},
textInput: {
color: 'gray',
width: '100%',
padding: 15,
fontSize: 18,
},
receivedChat: {
marginLeft: '10%',
},
chatContainer: {
justifyContent: 'flex-end',
},
chatView: {
backgroundColor: 'whitesmoke',
// alignItems: 'flex-start',
minWidth: '100%',
flex: 1,
},
chatBubble: {
margin: 5,
maxWidth: '90%',
minWidth: '50%',
width: 'auto',
height: 'auto',
padding: 20,
fontSize: 18,
color: 'gray',
backgroundColor: 'ivory',
borderBottomColor: 'steelblue',
// borderBottomWidth: StyleSheet.hairlineWidth,
borderRadius: 18,
alignItems: 'flex-end',
},
recipients: {
maxHeight: 100,
padding: 15,
width: '100%',
// alignItems: 'center',
maxWidth: 300,
borderTopColor: 'gray',
borderBottomColor: 'gray',
borderTopWidth: StyleSheet.hairlineWidth,
borderBottomWidth: StyleSheet.hairlineWidth,
},
contentContainer: {
justifyContent: 'center',
alignItems: 'center',
minWidth: '100%',
height: 75,
},
user: {
width: 75,
height: 75,
margin: 5,
},
username: {
lineHeight: 25,
textAlign: 'center',
position: 'absolute',
zIndex: 3,
color: 'white',
fontWeight: 'bold',
},
photo: {
width: 75,
height: 75,
borderRadius: 64,
},
overlay: {
flex: 1,
position: 'absolute',
left: 0,
top: 0,
opacity: 0.3,
backgroundColor: 'black',
width: 75,
height: 75,
borderRadius: 64,
zIndex: 2,
},
}) |
src/client/components/work/CompareBooks/CompareBooks.component.js | DBCDK/content-first | import React from 'react';
import {some} from 'lodash';
import TruncateMarkup from 'react-truncate-markup';
import Text from '../../base/Text';
import Button from '../../base/Button';
import T from '../../base/T';
import Icon from '../../base/Icon';
import BookCover from '../../general/BookCover/BookCover.component';
import Link from '../../general/Link.component';
import withWork from '../../hoc/Work/withWork.hoc';
import './CompareBooks.css';
const Card = ({work, children, main, styles}) => {
const mainClass = main ? 'card_main' : '';
return (
<div className={`card ${mainClass}`} style={styles}>
<BookCover pid={work.book.pid} />
<TruncateMarkup lines={2}>{children}</TruncateMarkup>
</div>
);
};
const Info = ({work, main}) => {
const mainClass = main ? 'info_main' : '';
const title = main
? T({component: 'work', name: 'infoCommon'})
: T({component: 'work', name: 'onlyCompared', vars: [work.book.title]});
return (
<div className={`info ${mainClass}`}>
<div className="info_color" />
<Text type="small">{title}</Text>
</div>
);
};
export class CompareBooks extends React.Component {
render() {
const {main, works, intersectTags, sortTagsByAppeal} = this.props;
if (!works) {
return null;
}
const comparedWork = works.filter(work => {
return work.book.pid !== main;
})[0];
// The compared works tags, sorted into Appeal categories
const comparedWorkAppel = sortTagsByAppeal(comparedWork);
// Array of tags which the Compared and Main Work has in common
const intersectedTags = intersectTags();
return (
<div className="compare-books">
<div className="cards">
{works.map((work, i) => {
const isMain = work.book.pid === main;
return (
<Card
key={`card-${work.book.pid}`}
work={work}
main={isMain}
styles={{order: isMain ? 99 : i}}
>
<span className="cards_title">
<Text type={'body'} variant={'weight-semibold'}>
{work.book.title}
</Text>
</span>
</Card>
);
})}
<div className="card_vs" style={{order: 98}}>
<Text type="small">
<T component="work" name="compare" />
</Text>
<Icon name="compare_arrows" />
</div>
</div>
<div className="compare">
<Text className="compare_title" type="body" variant="weight-bold">
<T component="work" name="appealsTitle" />
</Text>
<div className="compare_informations">
{works.map(work => {
return (
<Info
key={`info-${work.book.pid}`}
work={work}
main={work.book.pid === main}
/>
);
})}
</div>
<div className="compare_appeals">
{comparedWorkAppel.length > 0 ? (
comparedWorkAppel.map(g => {
return (
<div key={g.title}>
<Text
type="small"
variant="weight-bold"
className="compare_appeals-title"
>
{g.title}
</Text>
{g.data.map(t => {
const matchClass = some(intersectedTags, ['id', t.id])
? 'compare_match'
: '';
return (
<Link
className="compare_tag"
key={t.id}
href="/find"
params={{tags: t.id}}
>
<Button
key={t.title}
type="tertiary"
size="small"
className={`compare_tag ${matchClass}`}
dataCy={'tag-' + t.title}
>
{t.title}
</Button>
</Link>
);
})}
</div>
);
})
) : (
<Text type="body" className="compare_no-tags">
<T component="work" name="noAppeals" />
</Text>
)}
</div>
{/* DISABLE FOR NOW - until we have more valid data */}
{/* <Text className="compare_title" type="body" variant="weight-bold">
<T component="work" name="loansTitle" />
</Text>
<div className="compare_loans">
<div className="cards">
{works.map((work, i) => {
const isMain = work.book.pid === main;
return (
<Card
key={`card-${work.book.pid}`}
work={work}
main={isMain}
styles={{order: isMain ? 99 : i}}
>
<span>
<Text type={'small'} variant={null}>
<T
component="work"
name="loans"
renderAsHtml={true}
vars={[JSON.stringify(details[work.book.pid].loans)]}
/>
</Text>
</span>
</Card>
);
})}
<div className="card_loan" style={{order: 98}}>
<Text type="small">
<T
component="work"
name="loansCommon"
renderAsHtml={true}
vars={[
JSON.stringify(
details[comparedWork.book.pid]['common-loans']
)
]}
/>
</Text>
</div>
</div>
</div>
<div className="compare_loans_indicator">
<Text type="small">
<T component="work" name="aboutLoans" />
</Text>
</div> */}
</div>
</div>
);
}
}
export default withWork(CompareBooks, {
includeTags: true
});
|
app/components/Star.js | Toreant/monster_web | /**
* Created by apache on 15-11-15.
*/
import React from 'react';
import StarActions from '../actions/StarActions';
import StarStore from '../stores/StarStore';
class Star extends React.Component {
constructor(props) {
super(props);
this.state = StarStore.getState();
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
StarStore.listen(this.onChange);
}
componentWillUnmount() {
StarStore.unlisten(this.onChange);
}
onChange(state) {
this.setState(state);
}
handleClick(option) {
let column = this.props.column,
star_id = this.props.star;
// option 0-- ๅ
ณๆณจใ๏ผ๏ผ๏ผ ๅๆถๅ
ณๆณจ
if (option === 0) {
StarActions.getStar(star_id, column,this.props.plusClick);
} else {
StarActions.unStar(star_id, column,this.props.subClick);
}
}
render() {
let stared = '',option = 0;
if((!this.state.changed && this.props.stared === 'true') || this.state.stared ) {
stared = 'mon-stared';
option = 1;
} else {
option = 0;
stared = '';
}
return (
<div className="mon-star">
<a id="substitute" href="javascript:;" className={'fa fa-heart-o animated '+stared}
onClick={this.handleClick.bind(this,option)}>
</a>
</div>
);
}
}
export default Star; |
src/components/Login/Login.js | sbiliaiev/transport-kharkiv | import React from 'react';
import { browserHistory } from 'react-router';
import { Grid, Row, Col, Form, FormGroup, FormControl, Checkbox, ControlLabel, Button } from 'react-bootstrap';
import Header from './../Header/Header';
import { logInUser } from './../../api/cloudservice';
import './Login.css';
export default class Login extends React.Component {
constructor() {
super();
this.state = {
username: '',
password: '',
remember: false,
};
}
handleLoginChange = (event) => {
this.setState({username: event.target.value});
}
handlePasswordChange = (event) => {
this.setState({password: event.target.value});
}
handleRememberChange = () => {
this.setState({remember: !this.state.remember});
}
handleLoginSubmit = (event) => {
event.preventDefault();
console.log(this.state);
const callback = () => {
browserHistory.push('main');
};
logInUser(this.state, callback);
}
render() {
return(
<div>
<Header />
<Form horizontal className="login-form" onSubmit={this.handleLoginSubmit}>
<FormGroup controlId="formHorizontalEmail">
<Col componentClass={ControlLabel}
md={2} sm={2} xs={8} mdOffset={2} smOffset={2} xsOffset={2}>
Email
</Col>
<Col
md={4} sm={6} xs={8} smOffset={0} xsOffset={2}>
<FormControl type="email" placeholder="Email" onChange={this.handleLoginChange} />
</Col>
</FormGroup>
<FormGroup controlId="formHorizontalPassword">
<Col componentClass={ControlLabel}
md={2} sm={2} xs={8} mdOffset={2} smOffset={2} xsOffset={2}>
Password
</Col>
<Col
md={4} sm={6} xs={8} smOffset={0} xsOffset={2}>
<FormControl type="password" placeholder="Password" onChange={this.handlePasswordChange} />
</Col>
</FormGroup>
<FormGroup>
<Col md={4} sm={6} xs={8} mdOffset={4} smOffset={4} xsOffset={2}>
<Checkbox value={true} onChange={this.handleRememberChange}>Remember me</Checkbox>
</Col>
</FormGroup>
<FormGroup>
<Col md={4} sm={6} xs={8} mdOffset={4} smOffset={4} xsOffset={2}>
<Button type="submit">
Sign in
</Button>
</Col>
</FormGroup>
</Form>
</div>
);
}
} |
app/javascript/mastodon/features/ui/components/image_loader.js | lynlynlynx/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { LoadingBar } from 'react-redux-loading-bar';
import ZoomableImage from './zoomable_image';
export default class ImageLoader extends React.PureComponent {
static propTypes = {
alt: PropTypes.string,
src: PropTypes.string.isRequired,
previewSrc: PropTypes.string,
width: PropTypes.number,
height: PropTypes.number,
onClick: PropTypes.func,
zoomButtonHidden: PropTypes.bool,
}
static defaultProps = {
alt: '',
width: null,
height: null,
};
state = {
loading: true,
error: false,
width: null,
}
removers = [];
canvas = null;
get canvasContext() {
if (!this.canvas) {
return null;
}
this._canvasContext = this._canvasContext || this.canvas.getContext('2d');
return this._canvasContext;
}
componentDidMount () {
this.loadImage(this.props);
}
componentWillReceiveProps (nextProps) {
if (this.props.src !== nextProps.src) {
this.loadImage(nextProps);
}
}
componentWillUnmount () {
this.removeEventListeners();
}
loadImage (props) {
this.removeEventListeners();
this.setState({ loading: true, error: false });
Promise.all([
props.previewSrc && this.loadPreviewCanvas(props),
this.hasSize() && this.loadOriginalImage(props),
].filter(Boolean))
.then(() => {
this.setState({ loading: false, error: false });
this.clearPreviewCanvas();
})
.catch(() => this.setState({ loading: false, error: true }));
}
loadPreviewCanvas = ({ previewSrc, width, height }) => new Promise((resolve, reject) => {
const image = new Image();
const removeEventListeners = () => {
image.removeEventListener('error', handleError);
image.removeEventListener('load', handleLoad);
};
const handleError = () => {
removeEventListeners();
reject();
};
const handleLoad = () => {
removeEventListeners();
this.canvasContext.drawImage(image, 0, 0, width, height);
resolve();
};
image.addEventListener('error', handleError);
image.addEventListener('load', handleLoad);
image.src = previewSrc;
this.removers.push(removeEventListeners);
})
clearPreviewCanvas () {
const { width, height } = this.canvas;
this.canvasContext.clearRect(0, 0, width, height);
}
loadOriginalImage = ({ src }) => new Promise((resolve, reject) => {
const image = new Image();
const removeEventListeners = () => {
image.removeEventListener('error', handleError);
image.removeEventListener('load', handleLoad);
};
const handleError = () => {
removeEventListeners();
reject();
};
const handleLoad = () => {
removeEventListeners();
resolve();
};
image.addEventListener('error', handleError);
image.addEventListener('load', handleLoad);
image.src = src;
this.removers.push(removeEventListeners);
});
removeEventListeners () {
this.removers.forEach(listeners => listeners());
this.removers = [];
}
hasSize () {
const { width, height } = this.props;
return typeof width === 'number' && typeof height === 'number';
}
setCanvasRef = c => {
this.canvas = c;
if (c) this.setState({ width: c.offsetWidth });
}
render () {
const { alt, src, width, height, onClick } = this.props;
const { loading } = this.state;
const className = classNames('image-loader', {
'image-loader--loading': loading,
'image-loader--amorphous': !this.hasSize(),
});
return (
<div className={className}>
<LoadingBar loading={loading ? 1 : 0} className='loading-bar' style={{ width: this.state.width || width }} />
{loading ? (
<canvas
className='image-loader__preview-canvas'
ref={this.setCanvasRef}
width={width}
height={height}
/>
) : (
<ZoomableImage
alt={alt}
src={src}
onClick={onClick}
width={width}
height={height}
zoomButtonHidden={this.props.zoomButtonHidden}
/>
)}
</div>
);
}
}
|
app/javascript/mastodon/features/compose/containers/warning_container.js | musashino205/mastodon | import React from 'react';
import { connect } from 'react-redux';
import Warning from '../components/warning';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { me } from '../../../initial_state';
const buildHashtagRE = () => {
try {
const HASHTAG_SEPARATORS = '_\\u00b7\\u200c';
const ALPHA = '\\p{L}\\p{M}';
const WORD = '\\p{L}\\p{M}\\p{N}\\p{Pc}';
return new RegExp(
'(?:^|[^\\/\\)\\w])#((' +
'[' + WORD + '_]' +
'[' + WORD + HASHTAG_SEPARATORS + ']*' +
'[' + ALPHA + HASHTAG_SEPARATORS + ']' +
'[' + WORD + HASHTAG_SEPARATORS +']*' +
'[' + WORD + '_]' +
')|(' +
'[' + WORD + '_]*' +
'[' + ALPHA + ']' +
'[' + WORD + '_]*' +
'))', 'iu',
);
} catch {
return /(?:^|[^\/\)\w])#(\w*[a-zA-Zยท]\w*)/i;
}
};
const APPROX_HASHTAG_RE = buildHashtagRE();
const mapStateToProps = state => ({
needsLockWarning: state.getIn(['compose', 'privacy']) === 'private' && !state.getIn(['accounts', me, 'locked']),
hashtagWarning: state.getIn(['compose', 'privacy']) !== 'public' && APPROX_HASHTAG_RE.test(state.getIn(['compose', 'text'])),
directMessageWarning: state.getIn(['compose', 'privacy']) === 'direct',
});
const WarningWrapper = ({ needsLockWarning, hashtagWarning, directMessageWarning }) => {
if (needsLockWarning) {
return <Warning message={<FormattedMessage id='compose_form.lock_disclaimer' defaultMessage='Your account is not {locked}. Anyone can follow you to view your follower-only posts.' values={{ locked: <a href='/settings/profile'><FormattedMessage id='compose_form.lock_disclaimer.lock' defaultMessage='locked' /></a> }} />} />;
}
if (hashtagWarning) {
return <Warning message={<FormattedMessage id='compose_form.hashtag_warning' defaultMessage="This toot won't be listed under any hashtag as it is unlisted. Only public toots can be searched by hashtag." />} />;
}
if (directMessageWarning) {
const message = (
<span>
<FormattedMessage id='compose_form.direct_message_warning' defaultMessage='This toot will only be sent to all the mentioned users.' /> <a href='/terms' target='_blank'><FormattedMessage id='compose_form.direct_message_warning_learn_more' defaultMessage='Learn more' /></a>
</span>
);
return <Warning message={message} />;
}
return null;
};
WarningWrapper.propTypes = {
needsLockWarning: PropTypes.bool,
hashtagWarning: PropTypes.bool,
directMessageWarning: PropTypes.bool,
};
export default connect(mapStateToProps)(WarningWrapper);
|
react-flux-mui/js/material-ui/src/svg-icons/image/camera-front.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCameraFront = (props) => (
<SvgIcon {...props}>
<path d="M10 20H5v2h5v2l3-3-3-3v2zm4 0v2h5v-2h-5zM12 8c1.1 0 2-.9 2-2s-.9-2-2-2-1.99.9-1.99 2S10.9 8 12 8zm5-8H7C5.9 0 5 .9 5 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V2c0-1.1-.9-2-2-2zM7 2h10v10.5c0-1.67-3.33-2.5-5-2.5s-5 .83-5 2.5V2z"/>
</SvgIcon>
);
ImageCameraFront = pure(ImageCameraFront);
ImageCameraFront.displayName = 'ImageCameraFront';
ImageCameraFront.muiName = 'SvgIcon';
export default ImageCameraFront;
|
app/javascript/mastodon/containers/domain_container.js | cybrespace/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { blockDomain, unblockDomain } from '../actions/domain_blocks';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import Domain from '../components/domain';
import { openModal } from '../actions/modal';
const messages = defineMessages({
blockDomainConfirm: { id: 'confirmations.domain_block.confirm', defaultMessage: 'Hide entire domain' },
});
const makeMapStateToProps = () => {
const mapStateToProps = () => ({});
return mapStateToProps;
};
const mapDispatchToProps = (dispatch, { intl }) => ({
onBlockDomain (domain) {
dispatch(openModal('CONFIRM', {
message: <FormattedMessage id='confirmations.domain_block.message' defaultMessage='Are you really, really sure you want to block the entire {domain}? In most cases a few targeted blocks or mutes are sufficient and preferable.' values={{ domain: <strong>{domain}</strong> }} />,
confirm: intl.formatMessage(messages.blockDomainConfirm),
onConfirm: () => dispatch(blockDomain(domain)),
}));
},
onUnblockDomain (domain) {
dispatch(unblockDomain(domain));
},
});
export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Domain));
|
app/javascript/mastodon/components/permalink.js | unarist/mastodon | import React from 'react';
import PropTypes from 'prop-types';
export default class Permalink extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
className: PropTypes.string,
href: PropTypes.string.isRequired,
to: PropTypes.string.isRequired,
children: PropTypes.node,
onInterceptClick: PropTypes.func,
};
handleClick = e => {
if (this.props.onInterceptClick && this.props.onInterceptClick()) {
e.preventDefault();
return;
}
if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(this.props.to);
}
}
render () {
const { href, children, className, onInterceptClick, ...other } = this.props;
return (
<a target='_blank' href={href} onClick={this.handleClick} {...other} className={`permalink${className ? ' ' + className : ''}`}>
{children}
</a>
);
}
}
|
src/component/textInput.js | sjcrank/viz-data-generator | import React from 'react';
import classNames from 'classnames';
import { StyleSheet, css } from 'aphrodite/no-important';
import StyleGuide from '../util/styleGuide';
const Styles = StyleSheet.create({
container: {
display: 'inline-block',
},
label: {
display: 'inline-block',
boxShadow: 'inset 0 1px 0 0 #e0e6ed,inset 0 -1px 0 0 #e0e6ed,inset 1px 0 0 #e0e6ed',
borderRadius: '4px 0 0 4px',
padding: '0 18px',
lineHeight: '40px',
fontSize: StyleGuide.fontSize2,
height: '40px',
color: '#8492a6',
backgroundColor: '#f9fafc',
textAlign: 'center',
fontWeight: StyleGuide.weight4,
verticalAlign: 'middle',
margin: '0',
},
textInput: {
padding: '0 12px',
fontSize: StyleGuide.fontSize2,
color: '#3c4858',
boxShadow: 'inset 0 0 0 1px #e0e6ed',
borderWidth: 0,
backgroundColor: '#ffffff',
outlineStyle: 'none',
transitionProperty: 'all',
transitionTimingFunction: 'ease-in-out',
transitionDuration: '80ms',
fontWeight: StyleGuide.weight4,
verticalAlign: 'middle',
height: '40px',
lineHeight: '1',
margin: '0',
':hover': {
boxShadow: 'inset 0 0 0 1px #bacddb',
},
':focus': {
boxShadow: `inset 0 0 0 1px ${StyleGuide.colorBlue}`,
},
},
textInputWithoutLabel: {
borderRadius: '3px',
},
textInputWithLabel: {
borderRadius: '0 3px 3px 0',
},
textInputNumeric: {
textAlign: 'right',
},
textInputXSmall: {
width: '58px',
},
textInputSmall: {
width: '74px',
},
});
class TextInput extends React.Component {
constructor() {
super();
this.onChange = this.onChange.bind(this);
}
onChange(event) {
if(this.props.onChange) { this.props.onChange(event.target.name, event.target.value); }
}
render() {
const cn = classNames(
{ [css(Styles.textInput)]: true },
{ [css(Styles.textInputWithLabel)]: this.props.label },
{ [css(Styles.textInputWithoutLabel)]: !this.props.label },
{ [css(Styles.textInputNumeric)]: this.props.numeric },
{ [css(Styles.textInputSmall)]: this.props.size === 'small' },
{ [css(Styles.textInputXSmall)]: this.props.size === 'xsmall' },
);
return (
<div className={classNames(css(Styles.container), this.props.className)}>
{this.props.label && <div className={css(Styles.label)}>{this.props.label}</div>}
<input className={cn} type='text' name={this.props.name} value={this.props.value} onChange={this.onChange}/>
</div>
);
}
}
TextInput.propTypes = {
name: React.PropTypes.string.isRequired,
value: React.PropTypes.node.isRequired,
onChange: React.PropTypes.func,
className: React.PropTypes.string,
label: React.PropTypes.string,
numeric: React.PropTypes.bool,
size: React.PropTypes.oneOf(['small', 'xsmall']),
};
export default TextInput;
|
frontend/src/Calendar/Header/CalendarHeader.js | Radarr/Radarr | import moment from 'moment';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import * as calendarViews from 'Calendar/calendarViews';
import Icon from 'Components/Icon';
import Button from 'Components/Link/Button';
import LoadingIndicator from 'Components/Loading/LoadingIndicator';
import Menu from 'Components/Menu/Menu';
import MenuButton from 'Components/Menu/MenuButton';
import MenuContent from 'Components/Menu/MenuContent';
import ViewMenuItem from 'Components/Menu/ViewMenuItem';
import { align, icons } from 'Helpers/Props';
import translate from 'Utilities/String/translate';
import CalendarHeaderViewButton from './CalendarHeaderViewButton';
import styles from './CalendarHeader.css';
function getTitle(time, start, end, view, longDateFormat) {
const timeMoment = moment(time);
const startMoment = moment(start);
const endMoment = moment(end);
if (view === 'day') {
return timeMoment.format(longDateFormat);
} else if (view === 'month') {
return timeMoment.format('MMMM YYYY');
} else if (view === 'agenda') {
return `Agenda: ${startMoment.format('MMM D')} - ${endMoment.format('MMM D')}`;
}
let startFormat = 'MMM D YYYY';
let endFormat = 'MMM D YYYY';
if (startMoment.isSame(endMoment, 'month')) {
startFormat = 'MMM D';
endFormat = 'D YYYY';
} else if (startMoment.isSame(endMoment, 'year')) {
startFormat = 'MMM D';
endFormat = 'MMM D YYYY';
}
return `${startMoment.format(startFormat)} \u2014 ${endMoment.format(endFormat)}`;
}
// TODO Convert to a stateful Component so we can track view internally when changed
class CalendarHeader extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this.state = {
view: props.view
};
}
componentDidUpdate(prevProps) {
const view = this.props.view;
if (prevProps.view !== view) {
this.setState({ view });
}
}
//
// Listeners
onViewChange = (view) => {
this.setState({ view }, () => {
this.props.onViewChange(view);
});
};
//
// Render
render() {
const {
isFetching,
time,
start,
end,
longDateFormat,
isSmallScreen,
collapseViewButtons,
onTodayPress,
onPreviousPress,
onNextPress
} = this.props;
const view = this.state.view;
const title = getTitle(time, start, end, view, longDateFormat);
return (
<div>
{
isSmallScreen &&
<div className={styles.titleMobile}>
{title}
</div>
}
<div className={styles.header}>
<div className={styles.navigationButtons}>
<Button
buttonGroupPosition={align.LEFT}
isDisabled={view === calendarViews.AGENDA}
onPress={onPreviousPress}
>
<Icon name={icons.PAGE_PREVIOUS} />
</Button>
<Button
buttonGroupPosition={align.RIGHT}
isDisabled={view === calendarViews.AGENDA}
onPress={onNextPress}
>
<Icon name={icons.PAGE_NEXT} />
</Button>
<Button
className={styles.todayButton}
isDisabled={view === calendarViews.AGENDA}
onPress={onTodayPress}
>
Today
</Button>
</div>
{
!isSmallScreen &&
<div className={styles.titleDesktop}>
{title}
</div>
}
<div className={styles.viewButtonsContainer}>
{
isFetching &&
<LoadingIndicator
className={styles.loading}
size={20}
/>
}
{
collapseViewButtons ?
<Menu
className={styles.viewMenu}
alignMenu={align.RIGHT}
>
<MenuButton>
<Icon
name={icons.VIEW}
size={22}
/>
</MenuButton>
<MenuContent>
{
isSmallScreen ?
null :
<ViewMenuItem
name={calendarViews.MONTH}
selectedView={view}
onPress={this.onViewChange}
>
{translate('Month')}
</ViewMenuItem>
}
<ViewMenuItem
name={calendarViews.WEEK}
selectedView={view}
onPress={this.onViewChange}
>
{translate('Week')}
</ViewMenuItem>
<ViewMenuItem
name={calendarViews.FORECAST}
selectedView={view}
onPress={this.onViewChange}
>
{translate('Forecast')}
</ViewMenuItem>
<ViewMenuItem
name={calendarViews.DAY}
selectedView={view}
onPress={this.onViewChange}
>
{translate('Day')}
</ViewMenuItem>
<ViewMenuItem
name={calendarViews.AGENDA}
selectedView={view}
onPress={this.onViewChange}
>
{translate('Agenda')}
</ViewMenuItem>
</MenuContent>
</Menu> :
<div className={styles.viewButtons}>
<CalendarHeaderViewButton
view={calendarViews.MONTH}
selectedView={view}
buttonGroupPosition={align.LEFT}
onPress={this.onViewChange}
/>
<CalendarHeaderViewButton
view={calendarViews.WEEK}
selectedView={view}
buttonGroupPosition={align.CENTER}
onPress={this.onViewChange}
/>
<CalendarHeaderViewButton
view={calendarViews.FORECAST}
selectedView={view}
buttonGroupPosition={align.CENTER}
onPress={this.onViewChange}
/>
<CalendarHeaderViewButton
view={calendarViews.DAY}
selectedView={view}
buttonGroupPosition={align.CENTER}
onPress={this.onViewChange}
/>
<CalendarHeaderViewButton
view={calendarViews.AGENDA}
selectedView={view}
buttonGroupPosition={align.RIGHT}
onPress={this.onViewChange}
/>
</div>
}
</div>
</div>
</div>
);
}
}
CalendarHeader.propTypes = {
isFetching: PropTypes.bool.isRequired,
time: PropTypes.string.isRequired,
start: PropTypes.string.isRequired,
end: PropTypes.string.isRequired,
view: PropTypes.oneOf(calendarViews.all).isRequired,
isSmallScreen: PropTypes.bool.isRequired,
collapseViewButtons: PropTypes.bool.isRequired,
longDateFormat: PropTypes.string.isRequired,
onViewChange: PropTypes.func.isRequired,
onTodayPress: PropTypes.func.isRequired,
onPreviousPress: PropTypes.func.isRequired,
onNextPress: PropTypes.func.isRequired
};
export default CalendarHeader;
|
_experiment/react-fetch-github-repo/v2-fetch-in-react-didmount/src/App.js | David-Castelli/react-testing | import React from 'react';
import ReactDOM from 'react-dom';
class FetchDemo extends React.Component {
constructor(props) {
super(props); // la parola 'super' รจ usata per chiamare funzioni dal parente di un oggetto
// inizializzo lo state
this.state = {
repos: [] // setto l'array dei repo come vuoto
};
}
// metodo che si esegue quando il componente viene montato la prima volta
componentDidMount() {
const url = 'https://api.github.com/users/iGenius-Srl/repos';
// fetch dei dati
fetch(url)
// se riesce
.then(
response => response.json()
)
.then(
json => {
//console.log(json);
const repos = json; // creo un nuovo array con i dati di risultato
// aggiorno lo stato del componente con il nuovo array di repo, questo comando triggera il re-render
this.setState({ repos });
console.log(repos);
}
)
}
render() {
return (
<div>
<h1>Test Fetch data</h1>
<ul>
{this.state.repos.map(repo =>
<li key={repo.id}>{repo.name}</li>
)}
</ul>
</div>
);
}
}
ReactDOM.render(
<FetchDemo/>,
document.getElementById('app')
);
|
js/lessons/lesson5/CountdownTimer.js | leftstick/react-lesson | 'use strict';
import React from 'react';
class CountdownTimer extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<span type='text'>TODO: the number to be counted</span>
<button>
Start
</button>
</div>
);
}
}
CountdownTimer.propTypes = {
start: React.PropTypes.number
};
module.exports = CountdownTimer;
|
src/svg-icons/action/settings-brightness.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsBrightness = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16.01H3V4.99h18v14.02zM8 16h2.5l1.5 1.5 1.5-1.5H16v-2.5l1.5-1.5-1.5-1.5V8h-2.5L12 6.5 10.5 8H8v2.5L6.5 12 8 13.5V16zm4-7c1.66 0 3 1.34 3 3s-1.34 3-3 3V9z"/>
</SvgIcon>
);
ActionSettingsBrightness = pure(ActionSettingsBrightness);
ActionSettingsBrightness.displayName = 'ActionSettingsBrightness';
ActionSettingsBrightness.muiName = 'SvgIcon';
export default ActionSettingsBrightness;
|
clients/web-client/src/components/IDE/Subject/index.js | rlods/CodingChallenge | import React from 'react'
import Markdown from 'react-remarkable'
var ReactMarkdown = require('react-markdown');
import './Subject.css'
const Subject = props =>
<div className="subject">
<ReactMarkdown source={props.challenge.description} />
</div>
export default Subject |
src/components/common/svg-icons/image/brightness-4.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBrightness4 = (props) => (
<SvgIcon {...props}>
<path d="M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12s-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6c3.31 0 6 2.69 6 6s-2.69 6-6 6z"/>
</SvgIcon>
);
ImageBrightness4 = pure(ImageBrightness4);
ImageBrightness4.displayName = 'ImageBrightness4';
ImageBrightness4.muiName = 'SvgIcon';
export default ImageBrightness4;
|
src/Scrollable/Scrollable.js | collegepulse/material-react-components | import makeClass from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import Styles from './Scrollable.css';
class Scrollable extends React.Component {
render() {
const firstChild = React.Children.only(this.props.children);
return React.cloneElement(firstChild, {
className: makeClass(Styles.root, firstChild.props.className)
});
}
}
Scrollable.defaultProps = {
children: null
};
Scrollable.propTypes = {
children: PropTypes.node
};
export default Scrollable;
|
app/react-icons/fa/shopping-bag.js | scampersand/sonos-front | import React from 'react';
import IconBase from 'react-icon-base';
export default class FaShoppingBag extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m39.2 31.4l0.8 7q0.1 0.6-0.4 1.1-0.4 0.5-1 0.5h-37.2q-0.6 0-1-0.5-0.5-0.5-0.4-1.1l0.8-7h38.4z m-2.1-18.7l2 17.3h-38.2l2-17.3q0-0.5 0.4-0.9t1-0.4h5.7v2.9q0 1.2 0.8 2t2.1 0.8 2-0.8 0.8-2v-2.9h8.6v2.9q0 1.2 0.8 2t2 0.8 2.1-0.8 0.8-2v-2.9h5.7q0.6 0 1 0.4t0.4 0.9z m-8.5-4.1v5.7q0 0.6-0.5 1t-1 0.4-1-0.4-0.4-1v-5.7q0-2.4-1.7-4.1t-4-1.6-4 1.6-1.7 4.1v5.7q0 0.6-0.4 1t-1 0.4-1-0.4-0.5-1v-5.7q0-3.6 2.5-6.1t6.1-2.5 6.1 2.5 2.5 6.1z"/></g>
</IconBase>
);
}
}
|
fields/types/datearray/DateArrayFilter.js | cermati/keystone | import React from 'react';
import { findDOMNode } from 'react-dom';
import moment from 'moment';
import DayPicker from 'react-day-picker';
import {
FormInput,
FormSelect,
Grid,
} from '../../../admin/client/App/elemental';
const PRESENCE_OPTIONS = [
{ label: 'At least one element', value: 'some' },
{ label: 'No element', value: 'none' },
];
const MODE_OPTIONS = [
{ label: 'On', value: 'on' },
{ label: 'After', value: 'after' },
{ label: 'Before', value: 'before' },
{ label: 'Between', value: 'between' },
];
var DayPickerIndicator = React.createClass({
render () {
return (
<span className="DayPicker-Indicator">
<span className="DayPicker-Indicator__border" />
<span className="DayPicker-Indicator__bg" />
</span>
);
},
});
function getDefaultValue () {
return {
mode: MODE_OPTIONS[0].value,
presence: PRESENCE_OPTIONS[0].value,
value: moment(0, 'HH').format(),
before: moment(0, 'HH').format(),
after: moment(0, 'HH').format(),
};
}
var DateFilter = React.createClass({
displayName: 'DateFilter',
propTypes: {
filter: React.PropTypes.shape({
mode: React.PropTypes.oneOf(MODE_OPTIONS.map(i => i.value)),
presence: React.PropTypes.string,
}),
},
statics: {
getDefaultValue: getDefaultValue,
},
getDefaultProps () {
return {
format: 'DD-MM-YYYY',
filter: getDefaultValue(),
value: moment().startOf('day').toDate(),
};
},
getInitialState () {
return {
activeInputField: 'after',
month: new Date(), // The month to display in the calendar
};
},
componentDidMount () {
// focus the text input
if (this.props.filter.mode === 'between') {
findDOMNode(this.refs[this.state.activeInputField]).focus();
} else {
findDOMNode(this.refs.input).focus();
}
},
updateFilter (value) {
this.props.onChange({ ...this.props.filter, ...value });
},
selectPresence (e) {
const presence = e.target.value;
this.updateFilter({ presence });
findDOMNode(this.refs.input).focus();
},
selectMode (e) {
const mode = e.target.value;
this.updateFilter({ mode });
if (mode === 'between') {
setTimeout(() => { findDOMNode(this.refs[this.state.activeInputField]).focus(); }, 200);
} else {
findDOMNode(this.refs.input).focus();
}
},
handleInputChange (e) {
const { value } = e.target;
let { month } = this.state;
// Change the current month only if the value entered by the user is a valid
// date, according to the `L` format
if (moment(value, 'L', true).isValid()) {
month = moment(value, 'L').toDate();
}
this.updateFilter({ value: value });
this.setState({ month }, this.showCurrentDate);
},
setActiveField (field) {
this.setState({
activeInputField: field,
});
},
switchBetweenActiveInputFields (e, day, modifiers) {
if (modifiers && modifiers.disabled) return;
const { activeInputField } = this.state;
const send = {};
send[activeInputField] = day;
this.updateFilter(send);
const newActiveField = (activeInputField === 'before') ? 'after' : 'before';
this.setState(
{ activeInputField: newActiveField },
() => {
findDOMNode(this.refs[newActiveField]).focus();
}
);
},
selectDay (e, day, modifiers) {
if (modifiers && modifiers.disabled) return;
this.updateFilter({ value: day });
},
showCurrentDate () {
this.refs.daypicker.showMonth(this.state.month);
},
renderControls () {
let controls;
const { field, filter } = this.props;
const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0];
const placeholder = field.label + ' is ' + mode.label.toLowerCase() + '...';
// DayPicker stuff
const modifiers = {
selected: (day) => moment(filter.value).isSame(day),
};
if (mode.value === 'between') {
controls = (
<div>
<div style={{ marginBottom: '1em' }}>
<Grid.Row xsmall="one-half" gutter={10}>
<Grid.Col>
<FormInput ref="after" placeholder="From" onFocus={(e) => { this.setActiveField('after'); }} value={moment(filter.after).format(this.props.format)} />
</Grid.Col>
<Grid.Col>
<FormInput ref="before" placeholder="To" onFocus={(e) => { this.setActiveField('before'); }} value={moment(filter.before).format(this.props.format)} />
</Grid.Col>
</Grid.Row>
</div>
<div style={{ position: 'relative' }}>
<DayPicker
className="DayPicker--chrome"
modifiers={modifiers}
onDayClick={this.switchBetweenActiveInputFields}
/>
<DayPickerIndicator />
</div>
</div>
);
} else {
controls = (
<div>
<div style={{ marginBottom: '1em' }}>
<FormInput
onChange={this.handleInputChange}
onFocus={this.showCurrentDate}
placeholder={placeholder}
ref="input"
value={moment(filter.value).format(this.props.format)}
/>
</div>
<div style={{ position: 'relative' }}>
<DayPicker
className="DayPicker--chrome"
modifiers={modifiers}
onDayClick={this.selectDay}
ref="daypicker"
/>
<DayPickerIndicator />
</div>
</div>
);
}
return controls;
},
render () {
const { filter } = this.props;
const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0];
const presence = PRESENCE_OPTIONS.filter(i => i.value === filter.presence)[0];
return (
<div>
<div style={{ marginBottom: '1em' }}>
<FormSelect
onChange={this.selectPresence}
options={PRESENCE_OPTIONS}
value={presence.value}
/>
</div>
<div style={{ marginBottom: '1em' }}>
<FormSelect
onChange={this.selectMode}
options={MODE_OPTIONS}
value={mode.value}
/>
</div>
{this.renderControls()}
</div>
);
},
});
module.exports = DateFilter;
|
js/App/Components/TabViews/TabsView.android.js | telldus/telldus-live-mobile-v3 | /**
* Copyright 2016-present Telldus Technologies AB.
*
* This file is part of the Telldus Live! app.
*
* Telldus Live! app is free : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Telldus Live! app is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>.
*
*/
// @flow
'use strict';
import React from 'react';
import { MainTabBarAndroid } from '../../../BaseComponents';
import TabViews from './index';
import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs';
import {
prepareNavigator,
shouldNavigatorUpdate,
} from '../../Lib/NavigationService';
// NOTE [IMP]: Changing the order or updating the tabs
// need to reflect in places like tab hide/show logic and so
// Eg: Lib/NavigationService/prepareVisibleTabs
const ScreenConfigs = [
{
name: 'Dashboard',
Component: TabViews.Dashboard,
},
{
name: 'Devices',
Component: TabViews.Devices,
},
{
name: 'Sensors',
Component: TabViews.Sensors,
},
{
name: 'Scheduler',
Component: TabViews.Scheduler,
},
];
const NavigatorConfigs = {
swipeEnabled: false,
lazy: true,
animationEnabled: true,
tabBar: (props: Object): Object => <MainTabBarAndroid {...props}/>,
tabBarPosition: 'top',
tabBarOptions: {
scrollEnabled: true,
allowFontScaling: false,
},
};
const Tab = createMaterialTopTabNavigator();
const TabsView = React.memo<Object>((props: Object): Object => {
const {
hiddenTabsCurrentUser = [],
defaultStartScreenKey = 'Dashboard',
} = props.screenProps;
const _ScreenConfigs = ScreenConfigs.filter((sc: Object): boolean => hiddenTabsCurrentUser.indexOf(sc.name) === -1);
const _NavigatorConfigs = {
...NavigatorConfigs,
initialRouteName: defaultStartScreenKey,
};
return prepareNavigator(Tab, {ScreenConfigs: _ScreenConfigs, NavigatorConfigs: _NavigatorConfigs}, props);
}, (prevProps: Object, nextProps: Object): boolean => shouldNavigatorUpdate(prevProps, nextProps, [
'hideHeader',
'showAttentionCapture',
'showAttentionCaptureAddDevice',
'addingNewLocation',
'hiddenTabsCurrentUser',
'defaultStartScreenKey',
]));
module.exports = (TabsView: Object);
|
examples/src/components/States.js | MattMcFarland/react-select | import React from 'react';
import Select from 'react-select';
const STATES = require('../data/states');
var StatesField = React.createClass({
displayName: 'StatesField',
propTypes: {
label: React.PropTypes.string,
searchable: React.PropTypes.bool,
},
getDefaultProps () {
return {
label: 'States:',
searchable: true,
};
},
getInitialState () {
return {
country: 'AU',
disabled: false,
searchable: this.props.searchable,
selectValue: 'new-south-wales'
};
},
switchCountry (e) {
var newCountry = e.target.value;
console.log('Country changed to ' + newCountry);
this.setState({
country: newCountry,
selectValue: null
});
},
updateValue (newValue) {
console.log('State changed to ' + newValue);
this.setState({
selectValue: newValue
});
},
focusStateSelect () {
this.refs.stateSelect.focus();
},
toggleCheckbox (e) {
let newState = {};
newState[e.target.name] = e.target.checked;
this.setState(newState);
},
render () {
var options = STATES[this.state.country];
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select ref="stateSelect" options={options} simpleValue name="selected-state" disabled={this.state.disabled} value={this.state.selectValue} onChange={this.updateValue} searchable={this.state.searchable} />
<div style={{ marginTop: 14 }}>
<button type="button" onClick={this.focusStateSelect}>Focus Select</button>
<label className="checkbox" style={{ marginLeft: 10 }}>
<input type="checkbox" className="checkbox-control" name="searchable" checked={this.state.searchable} onChange={this.toggleCheckbox}/>
<span className="checkbox-label">Searchable</span>
</label>
<label className="checkbox" style={{ marginLeft: 10 }}>
<input type="checkbox" className="checkbox-control" name="disabled" checked={this.state.disabled} onChange={this.toggleCheckbox}/>
<span className="checkbox-label">Disabled</span>
</label>
</div>
<div className="checkbox-list">
<label className="checkbox">
<input type="radio" className="checkbox-control" checked={this.state.country === 'AU'} value="AU" onChange={this.switchCountry}/>
<span className="checkbox-label">Australia</span>
</label>
<label className="checkbox">
<input type="radio" className="checkbox-control" checked={this.state.country === 'US'} value="US" onChange={this.switchCountry}/>
<span className="checkbox-label">United States</span>
</label>
</div>
</div>
);
}
});
module.exports = StatesField;
|
src/components/Error.js | MMMalik/react-show-app | import React, { Component } from 'react';
import PropTypes from 'prop-types';
export default class Error extends Component {
static propTypes = {
status: PropTypes.string
}
render() {
const { status } = this.props;
let content = '';
if (status === '404') {
content = 'Error 404';
}
else if (status === '403') {
content = 'Error 403. Can\'t acces API, please try again later. Too many requests?';
}
else {
content = 'Something bad has just happend...';
}
return (
<div>{content}</div>
);
}
}
|
src/App.js | jdhanesh/ftdpwa | import React from 'react'
import { BrowserRouter, Route } from 'react-router-dom'
import 'normalize.css'
import promos from '../promo-contents.json'
import solar from '../solarrose.json'
import styles from './App.css'
import Header from './components/Header/Header'
import Footer from './components/Footer/Footer'
import Home from './components/Home/Home'
import Contents from './components/Contents/Contents'
import Scart from './components/Scart/Scart'
import Myaccount from './components/Myaccount/Myaccount'
import Product from './components/Product/Product'
// import Notfound from './components/Notfound/Notfound'
const App = () => (
<BrowserRouter>
<div>
<Header />
<div className={styles.container}>
<Route exact path='/' component={Home} />
<Route exact path='/scart' component={Scart} />
<Route exact path='/myaccount' component={Myaccount} />
<Route path='/:slug' component={props => {
const promo = promos.promos.filter(promo => props.match.params.slug === promo.slug)
if (promo.length < 1) {
return <div />
} else {
return <Contents promo={promo[0]} />
}
}} />
<Route path='/:id' component={props => {
const product = solar.response.products.filter(product => props.match.params.id === product.id)
if (product.length < 1) {
return <div><img className={'notfound'} src='./src/images/not-found-img.jpg' /></div>
} else {
return <Product prod='1' product={product[0]} />
}
}} />
</div>
<Footer />
</div>
</BrowserRouter>
)
export default App
|
packages/v4/src/content/training/trainingCard/trainingCard.js | patternfly/patternfly-org | import React from 'react';
import { Card, CardTitle, CardHeader, CardBody, CardFooter, Button } from '@patternfly/react-core';
import ArrowRightIcon from '@patternfly/react-icons/dist/esm/icons/arrow-right-icon';
import CubesIcon from '@patternfly/react-icons/dist/esm/icons/cubes-icon';
import ClockIcon from '@patternfly/react-icons/dist/esm/icons/clock-icon';
import RunningIcon from '@patternfly/react-icons/dist/esm/icons/running-icon';
import PuzzlePieceIcon from '@patternfly/react-icons/dist/esm/icons/puzzle-piece-icon';
import ChartBarIcon from '@patternfly/react-icons/dist/esm/icons/chart-bar-icon';
import SketchIcon from '@patternfly/react-icons/dist/esm/icons/sketch-icon';
import { Link } from 'theme-patternfly-org/components/link/link';
import { capitalize } from 'theme-patternfly-org/helpers/capitalize';
import './trainingCard.css';
const getTrainingIcon = trainingType => {
if (['html-css', 'react'].includes(trainingType)) {
return <CubesIcon className="pf-org__training-basics" />;
}
else if (trainingType === 'react-components') {
return <PuzzlePieceIcon className="pf-org__training-components" />;
}
else if (trainingType === 'design') {
return <SketchIcon className="pf-org__training-design" />;
}
return <ChartBarIcon className="pf-org__training-charts" />;
}
export const TrainingCard = ({
trainingType,
level,
title,
time,
description,
subsection,
katacodaId = null,
designUrl = null
}) => (
<Card className="pf-org__card" isCompact>
<CardHeader>
<Card className="pf-org__card-small">
{getTrainingIcon(trainingType)}
</Card>
<div className="pf-org__level">
<RunningIcon className={`pf-org__level-${level}`} />
{capitalize(level)}
</div>
</CardHeader>
<CardTitle>
{title}
</CardTitle>
<CardBody>
<div className="pf-org__time">
<ClockIcon />
{time}
</div>
{description}
</CardBody>
<CardFooter>
{katacodaId && (
<Link to={`/training/${katacodaId}`} >
<Button variant="link">
Start
<ArrowRightIcon />
</Button>
</Link>
)}
{designUrl && (
<Link to={designUrl} >
<Button variant="link">
Start
<ArrowRightIcon />
</Button>
</Link>
)}
</CardFooter>
</Card>
);
|
plugins/react/frontend/components/form/BaseSettings/index.js | carteb/carte-blanche | import React from 'react';
import Button from '../Button';
import styles from './styles.css';
const BaseSettings = ({ onChange, ...otherProps }) => {
const onChangeToUndefined = () => {
onChange({ value: undefined });
};
const onChangeToNull = () => {
onChange({ value: null });
};
return (
<div {...otherProps} className={styles.settingsContent}>
<Button onClick={onChangeToUndefined}>
Set to <span className={styles.highlighted}>undefined</span>
</Button>
<Button onClick={onChangeToNull}>
Set to <span className={styles.highlighted}>null</span>
</Button>
</div>
);
};
export default BaseSettings;
|
react/PreferencesIcon/PreferencesIcon.js | seekinternational/seek-asia-style-guide | import svgMarkup from './Preferences.svg';
import React from 'react';
import Icon from '../private/Icon/Icon';
export default function PreferencesIcon(props) {
return <Icon markup={svgMarkup} {...props} />;
}
PreferencesIcon.displayName = 'PreferencesIcon';
|
docs/src/app/components/pages/components/Popover/ExampleSimple.js | tan-jerene/material-ui | import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import Popover from 'material-ui/Popover';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
export default class PopoverExampleSimple extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false,
};
}
handleTouchTap = (event) => {
// This prevents ghost click.
event.preventDefault();
this.setState({
open: true,
anchorEl: event.currentTarget,
});
};
handleRequestClose = () => {
this.setState({
open: false,
});
};
render() {
return (
<div>
<RaisedButton
onTouchTap={this.handleTouchTap}
label="Click me"
/>
<Popover
open={this.state.open}
anchorEl={this.state.anchorEl}
anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
targetOrigin={{horizontal: 'left', vertical: 'top'}}
onRequestClose={this.handleRequestClose}
>
<Menu>
<MenuItem primaryText="Refresh" />
<MenuItem primaryText="Help & feedback" />
<MenuItem primaryText="Settings" />
<MenuItem primaryText="Sign out" />
</Menu>
</Popover>
</div>
);
}
}
|
lib/index.js | gness1804/shoot-the-breeze | import React from 'react';
import { render } from 'react-dom';
import Application from './components/Application';
import firebase from './firebase';
require('./style.scss');
render(<Application/>, document.getElementById('application'));
|
docs/src/js/component/wrapper/play-pause.react.js | vwxyutarooo/react-video-icons | 'use strict';
import React from 'react';
import PlayPause from 'play-pause';
export default class RppWrap extends React.Component {
constructor(props) {
super(props);
this.state = this.__getInitialState();
}
__getInitialState() {
return { isPlay: false }
}
_handleClick() {
console.debug('PlayPause component action');
this.setState({ isPlay: !(this.state.isPlay) });
}
render() {
return(
<button
type="button"
onClick={ () => this._handleClick() }
>
<PlayPause play={ this.state.isPlay } />
</button>
);
}
}
|
pkg/users/password-dialogs.js | martinpitt/cockpit | /*
* This file is part of Cockpit.
*
* Copyright (C) 2020 Red Hat, Inc.
*
* Cockpit is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Cockpit is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
*/
import cockpit from 'cockpit';
import React from 'react';
import { superuser } from "superuser";
import { Form, FormGroup, TextInput } from '@patternfly/react-core';
import { has_errors } from "./dialog-utils.js";
import { show_modal_dialog, apply_modal_dialog } from "cockpit-components-dialog.jsx";
import { password_quality, PasswordFormFields } from "cockpit-components-password.jsx";
const _ = cockpit.gettext;
function passwd_self(old_pass, new_pass) {
var old_exps = [
/Current password: $/,
/Current Password: $/,
/.*\(current\) UNIX password: $/,
];
var new_exps = [
/.*New password: $/,
/.*Retype new password: $/,
/.*Enter new \w*\s?password: $/,
/.*Retype new \w*\s?password: $/
];
var bad_exps = [
/.*BAD PASSWORD:.*/
];
var too_new_exps = [
/.*must wait longer to change.*/
];
return new Promise((resolve, reject) => {
var buffer = "";
var sent_new = false;
var failure = _("Old password not accepted");
var i;
var proc;
var timeout = window.setTimeout(function() {
failure = _("Prompting via passwd timed out");
proc.close("timeout");
}, 10 * 1000);
proc = cockpit.spawn(["/usr/bin/passwd"], { pty: true, environ: ["LC_ALL=C"], err: "out" })
.always(function() {
window.clearInterval(timeout);
})
.done(function() {
resolve();
})
.fail(function(ex) {
if (ex.exit_status || ex.problem == "timeout")
ex = new Error(failure);
reject(ex);
})
.stream(function(data) {
buffer += data;
for (i = 0; i < too_new_exps.length; i++) {
if (too_new_exps[i].test(buffer)) {
failure = _("You must wait longer to change your password");
}
}
if (sent_new) {
for (i = 0; i < bad_exps.length; i++) {
if (bad_exps[i].test(buffer)) {
failure = _("New password was not accepted");
}
}
}
for (i = 0; i < old_exps.length; i++) {
if (old_exps[i].test(buffer)) {
buffer = "";
this.input(old_pass + "\n", true);
return;
}
}
for (i = 0; i < new_exps.length; i++) {
if (new_exps[i].test(buffer)) {
buffer = "";
this.input(new_pass + "\n", true);
failure = _("Failed to change password");
sent_new = true;
return;
}
}
});
});
}
export function passwd_change(user, new_pass) {
return new Promise((resolve, reject) => {
cockpit.spawn(["chpasswd"], { superuser: "require", err: "out" })
.input(user + ":" + new_pass)
.done(function() {
resolve();
})
.fail(function(ex, response) {
if (ex.exit_status) {
console.log(ex);
if (response)
ex = new Error(response);
else
ex = new Error(_("Failed to change password"));
}
reject(ex);
});
});
}
function SetPasswordDialogBody({ state, errors, change }) {
const {
need_old, password_old, password, password_confirm,
password_strength, password_message
} = state;
return (
<Form isHorizontal onSubmit={apply_modal_dialog}>
{ need_old &&
<FormGroup label={_("Old password")}
helperTextInvalid={errors && errors.password_old}
validated={(errors && errors.password_old) ? "error" : "default"}
fieldId="account-set-password-old">
<TextInput className="check-passwords" type="password" id="account-set-password-old"
value={password_old} onChange={value => change("password_old", value)} />
</FormGroup> }
<PasswordFormFields password={password}
password_confirm={password_confirm}
password_label={_("New password")}
password_confirm_label={_("Confirm new password")}
password_strength={password_strength}
password_message={password_message}
error_password={errors && errors.password}
error_password_confirm={errors && errors.password_confirm}
idPrefix="account-set-password"
change={change} />
</Form>
);
}
export function set_password_dialog(account, current_user) {
let dlg = null;
const change_self = (account.name == current_user && !superuser.allowed);
const state = {
need_old: change_self,
password_old: "",
password: "",
password_confirm: "",
password_strength: "",
confirm_weak: false,
};
let errors = { };
let old_password = null;
function change(field, value) {
state[field] = value;
if (state.password != old_password) {
state.confirm_weak = false;
old_password = state.password;
if (state.password) {
password_quality(state.password)
.catch(ex => {
return { value: 0 };
})
.then(strength => {
state.password_strength = strength.value;
state.password_message = strength.message;
update();
});
} else {
state.password_strength = "";
}
}
update();
}
function validate(force) {
errors = { };
if (state.password != state.password_confirm)
errors.password_confirm = _("The passwords do not match");
return password_quality(state.password, force)
.catch(ex => {
errors.password = (ex.message || ex.toString()).replace("\n", " ");
errors.password += "\n" + cockpit.format(_("Click $0 again to use the password anyway."), _("Set password"));
})
.then(() => {
return !has_errors(errors);
});
}
function update() {
const props = {
id: "account-set-password-dialog",
title: _("Set password"),
body: <SetPasswordDialogBody state={state} errors={errors} change={change} />
};
const footer = {
actions: [
{
caption: _("Set password"),
style: "primary",
clicked: () => {
const second_click = state.confirm_weak;
state.confirm_weak = !state.confirm_weak;
return validate(second_click).then(valid => {
if (valid) {
if (change_self)
return passwd_self(state.password_old, state.password);
else
return passwd_change(account.name, state.password);
} else {
update();
return Promise.reject();
}
});
}
}
]
};
if (!dlg)
dlg = show_modal_dialog(props, footer);
else {
dlg.setProps(props);
dlg.setFooterProps(footer);
}
}
update();
}
export function reset_password_dialog(account) {
var msg = cockpit.format(_("The account '$0' will be forced to change their password on next login"),
account.name);
const props = {
id: "password-reset",
title: _("Force password change"),
body: <p>{msg}</p>
};
const footer = {
actions: [
{
caption: _("Reset password"),
style: "primary",
clicked: () => {
return cockpit.spawn(["/usr/bin/passwd", "-e", account.name],
{ superuser : true, err: "message" });
}
}
]
};
show_modal_dialog(props, footer);
}
|
src/svg-icons/image/filter-9.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFilter9 = (props) => (
<SvgIcon {...props}>
<path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zM15 5h-2c-1.1 0-2 .89-2 2v2c0 1.11.9 2 2 2h2v2h-4v2h4c1.1 0 2-.89 2-2V7c0-1.11-.9-2-2-2zm0 4h-2V7h2v2z"/>
</SvgIcon>
);
ImageFilter9 = pure(ImageFilter9);
ImageFilter9.displayName = 'ImageFilter9';
ImageFilter9.muiName = 'SvgIcon';
export default ImageFilter9;
|
src/components/Blocks/Html/index.js | StudentRND/www | import React from 'react'
import { graphql } from 'gatsby'
import reactReplace from 'react-string-replace'
import Sponsors from '../../Fragments/Sponsors'
import Programs from '../../Fragments/Programs'
import DonationMatch from '../../Fragments/DonationMatch'
import TrackingControl from '../../Fragments/TrackingControl'
import ProgramMap from '../../Fragments/ProgramMap'
export default class HtmlBlock extends React.Component {
render() {
return (
<div>
<div className="html">{this.renderHtml()}</div>
</div>
);
}
renderHtml() {
// TODO(@tylermenezes): Weird bug where react doubles all replacements when rehydrating if the replaced
// component isn't the last in the array.
const replace = {
'<Sponsors type="small" />': <Sponsors type="small" />,
'<Programs />': <Programs />,
'<TrackingControl />': <TrackingControl />,
'<DonationMatch />': <DonationMatch />,
'<ProgramMap />': <ProgramMap />,
};
var result = this.props.html.html;
Object.keys(replace).map((k) => { result = reactReplace(result, k, () => replace[k]); return null; });
return result.map((x) => typeof(x) === 'string' ? <div dangerouslySetInnerHTML={{__html: x}} /> : x);
}
}
export const query = graphql`
fragment HtmlBlockItems on ContentfulLayoutBlockHtml {
allowReact
html {
html
}
}
`;
|
src/components/EditOnGithub.js | dunglas/calavera-react-client | import React from 'react';
import pathToGitHubMarkdown from 'helpers/PathToGitHubMarkdown';
import { Glyphicon } from 'react-bootstrap';
export default function({ pagepath }) {
try {
const url = pathToGitHubMarkdown(pagepath);
return (
<span className="editongithub">
<a className="editongithub__link" href={url} target="_blank" >
<Glyphicon glyph="pencil" />
Edit on GitHub
</a>
</span>
);
} catch (error) {
// most probably, the GitHub repo has not be configured
return (<span></span>);
}
}
|
test/hompage-test.js | melissa-c/Comms | import test from 'ava'
import React from 'react'
import {shallow, render, mount} from 'enzyme'
import HomePage from '../src/components/homepage'
import Header from '../src/components/header'
test ('Homepage commponents adds to <HomePage> ', t => {
const wrapper = shallow(<HomePage />)
var homepg = wrapper.find('div').html()
t.deepEqual(homepg, '<div><div class="header"><div><button id="home" class="headerBtn"><img src="icon/home.png"/><p class="labels">home</p></button></div><div><button id="admin" class="headerBtn"><img src="icon/lock.png"/><p class="labels">admin</p></button></div><h1><span>Comms</span><br/> Companion</h1><div><button id="timer" class="headerBtn"><img src="icon/FPO_timer.png"/><p class="labels">timer</p></button></div></div><div><button class="navBtn"><img src="icon/clipboard.png"/>Schedule</button></div><div><button class="navBtn"><img src="icon/question.png"/>I would like...</button></div><div><button class="navBtn"><img src="icon/user.png"/>I can...</button></div></div>')
}) |
docs/src/layouts/LoginLayout.js | Semantic-Org/Semantic-UI-React | import React from 'react'
import { Button, Form, Grid, Header, Image, Message, Segment } from 'semantic-ui-react'
const LoginForm = () => (
<Grid textAlign='center' style={{ height: '100vh' }} verticalAlign='middle'>
<Grid.Column style={{ maxWidth: 450 }}>
<Header as='h2' color='teal' textAlign='center'>
<Image src='/logo.png' /> Log-in to your account
</Header>
<Form size='large'>
<Segment stacked>
<Form.Input fluid icon='user' iconPosition='left' placeholder='E-mail address' />
<Form.Input
fluid
icon='lock'
iconPosition='left'
placeholder='Password'
type='password'
/>
<Button color='teal' fluid size='large'>
Login
</Button>
</Segment>
</Form>
<Message>
New to us? <a href='#'>Sign Up</a>
</Message>
</Grid.Column>
</Grid>
)
export default LoginForm
|
src/svg-icons/maps/person-pin.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsPersonPin = (props) => (
<SvgIcon {...props}>
<path d="M19 2H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h4l3 3 3-3h4c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 3.3c1.49 0 2.7 1.21 2.7 2.7 0 1.49-1.21 2.7-2.7 2.7-1.49 0-2.7-1.21-2.7-2.7 0-1.49 1.21-2.7 2.7-2.7zM18 16H6v-.9c0-2 4-3.1 6-3.1s6 1.1 6 3.1v.9z"/>
</SvgIcon>
);
MapsPersonPin = pure(MapsPersonPin);
MapsPersonPin.displayName = 'MapsPersonPin';
MapsPersonPin.muiName = 'SvgIcon';
export default MapsPersonPin;
|
node_modules/native-base/src/basic/Left.js | tausifmuzaffar/bisApp | import React, { Component } from 'react';
import { View } from 'react-native';
import { connectStyle } from '@shoutem/theme';
import mapPropsToStyleNames from '../Utils/mapPropsToStyleNames';
class Left extends Component {
render() {
return (
<View ref={c => this._root = c} {...this.props} />
);
}
}
Left.propTypes = {
...View.propTypes,
style: React.PropTypes.object,
};
const StyledLeft = connectStyle('NativeBase.Left', {}, mapPropsToStyleNames)(Left);
export {
StyledLeft as Left,
};
|
src/svg-icons/action/account-balance.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAccountBalance = (props) => (
<SvgIcon {...props}>
<path d="M4 10v7h3v-7H4zm6 0v7h3v-7h-3zM2 22h19v-3H2v3zm14-12v7h3v-7h-3zm-4.5-9L2 6v2h19V6l-9.5-5z"/>
</SvgIcon>
);
ActionAccountBalance = pure(ActionAccountBalance);
ActionAccountBalance.displayName = 'ActionAccountBalance';
ActionAccountBalance.muiName = 'SvgIcon';
export default ActionAccountBalance;
|
es/svg-icons/CheckCircle.js | uplevel-technology/material-ui-next | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../SvgIcon';
/**
* @ignore - internal component.
*/
let CheckCircle = props => React.createElement(
SvgIcon,
props,
React.createElement('path', { d: 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z' })
);
CheckCircle = pure(CheckCircle);
CheckCircle.muiName = 'SvgIcon';
export default CheckCircle; |
website/src/components/guides/gradients/GradientsIllustrations.js | plouc/nivo | import React from 'react'
import { useTheme } from 'styled-components'
import { linearGradientDef } from '@nivo/core'
import { ResponsiveBar } from '@nivo/bar'
import { ResponsiveStream } from '@nivo/stream'
import { ResponsiveTreeMap } from '@nivo/treemap'
import { generateCountriesData } from '@nivo/generators'
import { FullWidthBanner } from '../../styled'
const GradientsIllustrations = () => {
const theme = useTheme()
return (
<FullWidthBanner>
<div className="guide__illustrations">
<div className="guide__illustrations__item">
<ResponsiveStream
margin={{ top: -2, right: -2, bottom: -2, left: -2 }}
data={generateCountriesData(['a', 'b', 'c'], { size: 9 })}
indexBy="country"
keys={['a', 'b', 'c']}
offsetType="expand"
axisLeft={null}
axisBottom={null}
enableGridX={false}
defs={[
linearGradientDef('example1A', [
{ offset: 0, color: '#faed94' },
{ offset: 30, color: '#faf047' },
{ offset: 100, color: '#e4b400' },
]),
linearGradientDef('example1B', [
{ offset: 0, color: '#a8f9eb' },
{ offset: 30, color: '#97e3d5' },
{ offset: 100, color: '#458a7d' },
]),
linearGradientDef('example1C', [
{ offset: 0, color: '#f9804e' },
{ offset: 30, color: '#f96a3d' },
{ offset: 100, color: '#a84f35' },
]),
]}
fill={[
{ match: { id: 'a' }, id: 'example1A' },
{ match: { id: 'b' }, id: 'example1B' },
{ match: { id: 'c' }, id: 'example1C' },
]}
isInteractive={false}
animate={false}
theme={theme.nivo}
/>
</div>
<div className="guide__illustrations__item">
<ResponsiveBar
margin={{ top: 15, right: 10, bottom: -2, left: 10 }}
data={generateCountriesData(['a', 'b', 'c'], { size: 7 })}
indexBy="country"
keys={['a', 'b', 'c']}
colors={{ scheme: 'spectral' }}
padding={0.2}
axisLeft={null}
axisBottom={null}
enableGridY={false}
enableLabel={false}
defs={[
linearGradientDef('example2', [
{ offset: 0, color: 'inherit' },
{ offset: 40, color: 'inherit' },
{ offset: 100, color: 'inherit', opacity: 0.6 },
]),
]}
fill={[{ match: '*', id: 'example2' }]}
borderWidth={1}
borderColor="inherit:darker(0.2)"
isInteractive={false}
animate={false}
theme={theme.nivo}
/>
</div>
<div className="guide__illustrations__item">
<ResponsiveTreeMap
margin={{ top: -2, right: -2, bottom: -2, left: -2 }}
data={{
country: 'root',
children: generateCountriesData(['value'], { size: 9 }),
}}
colors={{ scheme: 'spectral' }}
colorBy="path"
identity="country"
leavesOnly={false}
borderWidth={1}
nodeOpacity={1}
borderColor={{ theme: 'background' }}
outerPadding={10}
innerPadding={4}
enableParentLabel={false}
isInteractive={false}
animate={false}
enableLabel={false}
defs={[
linearGradientDef('example2', [
{ offset: 0, color: 'inherit' },
{ offset: 40, color: 'inherit' },
{ offset: 100, color: 'inherit', opacity: 0.3 },
]),
]}
fill={[{ match: '*', id: 'example2' }]}
theme={theme.nivo}
/>
</div>
<div className="guide__illustrations__legend">
gradients applied to various nivo components.
</div>
</div>
</FullWidthBanner>
)
}
export default GradientsIllustrations
|
src/components/PostEditor.js | Hylozoic/hylo-redux | /*
N.B.: in the database, Post has columns called "name" and "description".
Below, we use "title" and "details" instead for CSS and user-facing text,
because they make more sense.
*/
import React from 'react'
import cx from 'classnames'
import autoproxy from 'autoproxy'
import {
debounce, difference, compact, filter, find, get, includes, isEmpty, some,
startsWith, keys, uniq
} from 'lodash'
import { map } from 'lodash/fp'
import CommunityTagInput from './CommunityTagInput'
import Dropdown from './Dropdown'
import EventPostEditor from './EventPostEditor'
import ProjectPostEditor from './ProjectPostEditor'
import RichTextEditor from './RichTextEditor'
import Avatar from './Avatar'
import AutosizingTextarea from './AutosizingTextarea'
import Icon, { IconGoogleDrive } from './Icon'
import LinkPreview from './LinkPreview'
import Tooltip from './Tooltip'
import { connect } from 'react-redux'
import {
createPost,
cancelPostEdit,
fetchLinkPreview,
removeImage,
removeDoc,
updatePost,
updatePostEditor,
uploadImage,
uploadDoc,
notify,
showModal,
updateCommunityChecklist
} from '../actions'
import { attachmentParams } from '../util/shims'
import { findUrls } from '../util/linkify'
import { isKey, onEnter } from '../util/textInput'
import { responseMissingTagDescriptions } from '../util/api'
import {
CREATE_POST, FETCH_LINK_PREVIEW, UPDATE_POST, UPLOAD_IMAGE
} from '../actions/constants'
import { ADDED_POST, EDITED_POST, OPENED_POST_EDITOR, trackEvent } from '../util/analytics'
import { getCommunity, getCurrentCommunity, getDefaultTags } from '../models/community'
const { array, bool, func, object, string } = React.PropTypes
export const newPostId = 'new-post'
@autoproxy(connect((state, { community, post, parentPost, project, type, tag }) => {
const id = post ? post.id
: type === 'project' ? 'new-project'
: type === 'event' ? 'new-event' : newPostId
// this object tracks the edits that are currently being made
const postEdit = state.postEdits[id] || {}
const { editingTagDescriptions, creatingTagAndDescription, pending } = state
const postCommunities = map(id => getCommunity(id, state), postEdit.community_ids)
const currentCommunity = getCurrentCommunity(state)
return {
id,
postEdit,
parentPost,
mentionOptions: state.typeaheadMatches.post,
saving: pending[CREATE_POST] || pending[UPDATE_POST],
imagePending: pending[UPLOAD_IMAGE],
linkPreviewPending: pending[FETCH_LINK_PREVIEW],
currentCommunitySlug: get(currentCommunity, 'slug'),
editingTagDescriptions,
creatingTagAndDescription,
postCommunities,
defaultTags: map('name', getDefaultTags(currentCommunity, state))
}
}, null, null, {withRef: true}))
export class PostEditor extends React.PureComponent {
static propTypes = {
dispatch: func,
mentionOptions: array,
post: object,
id: string.isRequired,
postEdit: object,
parentPost: object,
community: object,
saving: bool,
onCancel: func,
imagePending: bool,
type: string,
tag: string,
currentCommunitySlug: string,
editingTagDescriptions: bool,
creatingTagAndDescription: bool,
postCommunities: array,
defaultTags: array,
placeholder: string,
onSave: func
}
static contextTypes = {
currentUser: object
}
constructor (props) {
super(props)
this.state = {name: this.props.postEdit.name}
}
componentDidMount () {
// initialize the communities list when opening the editor in a community
const { parentPost, community, postEdit: { communities }, tag } = this.props
if (!parentPost && community && isEmpty(communities)) this.addCommunity(community)
if (tag) this.updateStore({tag})
this.refs.title.focus()
}
updateStore = (data) => {
let { id, dispatch } = this.props
dispatch(updatePostEditor(data, id))
}
_self () {
return this.getWrappedInstance ? this.getWrappedInstance() : this
}
cancel () {
let { dispatch, id, onCancel } = this._self().props
dispatch(cancelPostEdit(id))
if (typeof onCancel === 'function') onCancel()
}
set = key => event => this.updateStore({[key]: event.target.value})
setDelayed = debounce((key, value) => this.updateStore({[key]: value}), 50)
addCommunity = ({ id }) => {
const { community_ids } = this.props.postEdit
this.updateStore({community_ids: (community_ids || []).concat(id)})
}
removeCommunity = ({ id }) => {
const { community_ids } = this.props.postEdit
this.updateStore({community_ids: filter(community_ids, cid => cid !== id)})
}
validate () {
let { parentPost, postEdit } = this.props
const { title } = this.refs
if (!postEdit.name) {
window.alert('The title of a post cannot be blank.')
title.focus()
return Promise.resolve(false)
}
if (!parentPost && isEmpty(postEdit.community_ids)) {
window.alert('Please pick at least one community.')
return Promise.resolve(false)
}
return Promise.resolve(true)
}
saveIfValid () {
const self = this._self()
// make sure the very last change to the details field is not lost
self.updateStore({description: self.refs.details.getContent()})
return self.validate().then(valid => valid && self.save())
}
saveWithTagDescriptions = tagDescriptions => {
this.updateStore({tagDescriptions})
return this.saveIfValid()
}
updatePostTagAndDescription = tagDescriptions => {
let tag = keys(tagDescriptions)[0]
this.updateStore({tag, tagDescriptions})
}
save () {
const {
dispatch, post, postEdit, id, postCommunities, currentCommunitySlug, onSave, parentPost
} = this.props
const params = {
type: this.editorType(),
...postEdit,
...attachmentParams(post && post.media, postEdit.media)
}
if (parentPost) params.parent_post_id = parentPost.id
return dispatch((post ? updatePost : createPost)(id, params, currentCommunitySlug))
.then(action => {
if (responseMissingTagDescriptions(action)) {
return dispatch(showModal('tag-editor', {
creating: false,
saveParent: this.saveWithTagDescriptions
}))
}
if (action.error) {
const message = 'There was a problem saving your post. Please try again in a moment.'
return dispatch(notify(message, {type: 'error', maxage: null}))
}
trackEvent(post ? EDITED_POST : ADDED_POST, {
tag: postEdit.tag,
community: {name: get(postCommunities[0], 'name')}
})
const community = postCommunities[0]
if (community) dispatch(updateCommunityChecklist(community.slug))
this.cancel()
if (onSave) return onSave()
})
}
// this method allows you to type as much as you want into the title field, by
// automatically truncating it to a specified length and prepending the
// removed portion to the details field.
updateTitle (event) {
const { value } = event.target
this.setState({name: value})
if (!this.delayedUpdate) {
this.delayedUpdate = debounce(this.updateStore, 300)
}
this.delayedUpdate({name: value})
}
goToDetails = () => {
this.setState({showDetails: true})
this.refs.details.focus()
}
tabToDetails = event => {
if (isKey(event, 'TAB') && !event.shiftKey) {
event.preventDefault()
this.goToDetails()
}
}
handleAddTag = tag => {
if (this.editorType()) return
tag = tag.replace(/^#/, '')
if (includes(this.props.defaultTags, tag)) {
this.updateStore({tag})
}
}
editorType () {
const type = this.props.postEdit.type || this.props.type
return includes(['event', 'project'], type) ? type : null
}
updateDescription (value) {
this.setDelayed('description', value)
const { dispatch, postEdit: { description, linkPreview } } = this.props
if (linkPreview) return
const currentUrls = findUrls(value)
if (isEmpty(currentUrls)) return
const newUrls = difference(currentUrls, findUrls(description))
if (isEmpty(newUrls)) return
const poll = (url, delay) =>
dispatch(fetchLinkPreview(url))
.then(({ payload }) => {
if (delay > 4) return // give up
if (!payload.id) {
setTimeout(() => poll(url, delay * 2), delay * 1000)
} else if (payload.title) {
this.updateStore({linkPreview: payload})
}
})
poll(newUrls[0], 0.5)
}
render () {
const {
parentPost, post, postEdit, dispatch, imagePending, saving, id, defaultTags, placeholder
} = this.props
const { currentUser } = this.context
const { description, community_ids, tag, linkPreview } = postEdit
const selectableTags = uniq(compact([this.props.tag, tag].concat(defaultTags)))
const { name, showDetails } = this.state
const editorType = this.editorType()
const shouldSelectTag = !includes(['project', 'event'], editorType)
const selectTag = tag => this.updateStore({tag})
const createTag = () => dispatch(showModal('tag-editor', {
useCreatedTag: this.updatePostTagAndDescription,
creating: true
}))
const Subeditor = editorType === 'event' ? EventPostEditor
: editorType === 'project' ? ProjectPostEditor : null
const removeLinkPreview = () => this.updateStore({linkPreview: null})
return <div className='post-editor clearfix'>
<PostEditorHeader person={currentUser} />
<div className='title-wrapper'>
<AutosizingTextarea type='text' ref='title' className='title'
value={name}
maxLength={120}
placeholder={placeholder || placeholderText(this.editorType())}
onKeyDown={onEnter(this.goToDetails)}
onChange={event => this.updateTitle(event)} />
</div>
{shouldSelectTag && <Dropdown className='hashtag-selector' keyControlled
onChange={this.goToDetails}
toggleChildren={<button ref='tagSelector' id='tag-selector' onKeyDown={this.tabToDetails}>
#{tag || 'all-topics'}
<span className='caret' />
</button>}>
{selectableTags.map(t => <li key={t}>
<a onClick={() => selectTag(t)}>#{t}</a>
</li>)}
<li><a onClick={() => selectTag(null)}>#all-topics</a></li>
<li className='create'><a onClick={() => createTag()}>Create New Topic</a></li>
</Dropdown>}
{id && <Tooltip id='selector'
index={1}
arrow='left'
position='bottom'
parentId='tag-selector'
title='Action Topics'>
<p>Use this pull-down menu to select from one of Hyloโs three Action Topics: Offer (something youโd like to share), Request (something youโre looking for), Intention (something youโd like to create), or create a new Topic.</p>
<p>Action Topics help you make good things happen in your community.</p>
</Tooltip>}
<RichTextEditor className={cx('details', {empty: !description && !showDetails})}
ref='details'
name={post ? `post${id}` : id}
content={description}
onChange={ev => this.updateDescription(ev.target.value)}
onAddTag={this.handleAddTag}
onBlur={() => this.setState({showDetails: false})} />
{!description && !showDetails &&
<div className='details-placeholder' onClick={this.goToDetails}>
More details
</div>}
{linkPreview && <LinkPreview {...{linkPreview}} onClose={removeLinkPreview} />}
{Subeditor && <Subeditor ref='subeditor'
{...{post, postEdit, update: this.updateStore}} />}
{!parentPost && <div className='communities'>
<span>in </span>
<CommunitySelector ids={community_ids}
onSelect={this.addCommunity}
onRemove={this.removeCommunity} />
</div>}
<div className='buttons'>
{!parentPost && <VisibilityDropdown
isPublic={postEdit.public || false}
setPublic={isPublic => this.updateStore({public: isPublic})} />}
<AttachmentsDropdown id={this.props.id}
media={postEdit.media}
path={`user/${currentUser.id}/seeds`}
imagePending={imagePending} />
<div className='right'>
<a className='cancel' onClick={() => this.cancel()}>
<Icon name='Fail' />
</a>
</div>
<button className='save right' ref='save' onClick={() => this.saveIfValid()}
disabled={saving}>
{post ? 'Save Changes' : 'Post'}
</button>
</div>
</div>
}
}
const VisibilityDropdown = ({ isPublic, setPublic }, { dispatch }) => {
const toggle = isPublic
? <button><Icon name='World' />Public <span className='caret' /></button>
: <button><Icon name='Users' />Only Communities <span className='caret' /></button>
const communityOption = <li key='community'><a onClick={() => setPublic(false)}><div>
<span className='option-title'> <Icon name='Users' />Only Communities</span>
<span className='description'>Allow communities and people who are tagged to see this post.</span>
</div></a></li>
const publicOption = <li key='public'><a onClick={() => setPublic(true)}><div>
<span className='option-title'><Icon name='World' />Public</span>
<span className='description'>Allow anyone on the internet to see this post.</span>
</div></a></li>
const options = isPublic
? [publicOption, communityOption]
: [communityOption, publicOption]
return <Dropdown toggleChildren={toggle} className='visibility'>
{options}
</Dropdown>
}
const AttachmentsDropdown = (props, { dispatch }) => {
const { id, imagePending, media, path } = props
const image = find(media, m => m.type === 'image')
const docs = filter(media, m => m.type === 'gdoc')
const length = (image ? 1 : 0) + docs.length
const attachDoc = () => dispatch(uploadDoc(id))
const attachImage = () => {
dispatch(uploadImage({
id,
path,
subject: 'post',
convert: {width: 800, format: 'jpg', fit: 'max', rotate: 'exif'}
}))
}
return <Dropdown className='attachments' toggleChildren={
<span>
<button>+</button>
{imagePending
? ' Uploading...'
: length > 0 && ` (${length})`}
</span>
}>
<li>
<a onClick={attachImage}>
<span>
<Icon name='Cloud-Upload' />
{image ? 'Change' : 'Upload'} Image
</span>
<div className='description'>
Upload an image from your computer, a URL or social media.
</div>
</a>
</li>
<li>
<a onClick={attachDoc}>
<span>
<IconGoogleDrive />Google Drive
</span>
<div className='description'>
Attach documents, images or videos from Google Drive.
</div>
</a>
</li>
{(image || some(docs)) && <li role='separator' className='divider' />}
{image && <li className='image'>
<a className='remove' onClick={() => dispatch(removeImage('post', id))}>
×
</a>
<img src={image.url} />
</li>}
{image && some(docs) && <li role='separator' className='divider' />}
{docs.map(doc => <li key={doc.url} className='doc'>
<a target='_blank' href={doc.url}>
<img src={doc.thumbnail_url} />
{doc.name}
</a>
<a className='remove' onClick={() => dispatch(removeDoc(doc, id))}>×</a>
</li>)}
</Dropdown>
}
AttachmentsDropdown.propTypes = {id: string, imagePending: bool, media: array, path: string}
AttachmentsDropdown.contextTypes = {dispatch: func}
class CommunitySelector extends React.Component {
constructor (props) {
super(props)
this.state = {term: ''}
}
static propTypes = {
ids: array,
onSelect: func.isRequired,
onRemove: func.isRequired
}
static contextTypes = {
currentUser: object.isRequired
}
render () {
const { term } = this.state
const { ids, onSelect, onRemove } = this.props
const { currentUser: { memberships } } = this.context
const match = c =>
startsWith(c.name.toLowerCase(), term.toLowerCase()) &&
!includes(ids, c.id)
const choices = term
? filter(memberships.map(m => m.community), match)
: []
return <CommunityTagInput ids={ids}
handleInput={term => this.setState({term})}
choices={choices}
onSelect={onSelect}
onRemove={onRemove} />
}
}
const PostEditorHeader = ({ person }) =>
<div className='header'>
<Avatar person={person} isLink={false} />
<div>
<span className='name'>{person.name}</span>
</div>
</div>
export default class PostEditorWrapper extends React.Component {
static propTypes = {
post: object,
parentPost: object,
community: object,
type: string,
expanded: bool,
tag: string,
onCancel: func,
placeholder: string
}
static contextTypes = {
currentUser: object
}
constructor (props) {
super(props)
this.state = {expanded: props.expanded}
}
toggle = () => {
if (!this.state.expanded) {
trackEvent(OPENED_POST_EDITOR, {community: this.props.community})
}
this.setState({expanded: !this.state.expanded})
}
render () {
let { expanded, onCancel, type, ...otherProps } = this.props
// if PostEditorWrapper is being initialized with expanded=true, we don't
// want to set up onCancel, because the entire component will probably be
// unmounted when canceling takes place
onCancel = onCancel || (expanded ? () => {} : this.toggle)
if (!this.state.expanded) {
const { currentUser } = this.context
if (!currentUser) return null
return <div className='post-editor post-editor-wrapper' onClick={this.toggle}>
<PostEditorHeader person={currentUser} />
<div className='prompt'>
{otherProps.placeholder || placeholderText(type)}
</div>
</div>
}
return <PostEditor {...{onCancel, type, ...otherProps}} />
}
}
const placeholderText = type =>
type === 'event' ? 'Create an event'
: type === 'project' ? 'Start a project'
: 'Start a conversation'
|
src/components/PricingRow/PricingRow.js | ben-miller/adddr.io | /**
* adddr (https://www.adddr.io/)
*
* 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 PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './PricingRow.css';
class PricingRow extends React.Component {
static propTypes = {
label: PropTypes.string.isRequired,
free: PropTypes.string.isRequired,
basic: PropTypes.string.isRequired,
enterprise: PropTypes.string.isRequired,
darkBg: PropTypes.bool.isRequired,
};
render() {
const { label, free, basic, enterprise, darkBg } = this.props;
const cssClass = darkBg ? s.dark : s.light;
return (
<tr className={cssClass}>
{[label, free, basic, enterprise].map((x, i) =>
<td key={x.label} className={i === 0 ? s.label : null}>
{x}
</td>,
)}
</tr>
);
}
}
export default withStyles(s)(PricingRow);
|
src/client.js | shilu89757/react-redux-universal-hot-example | /**
* THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER.
*/
import 'babel/polyfill';
import React from 'react';
import BrowserHistory from 'react-router/lib/BrowserHistory';
import Location from 'react-router/lib/Location';
import queryString from 'query-string';
import createStore from './redux/create';
import ApiClient from './helpers/ApiClient';
import universalRouter from './helpers/universalRouter';
const history = new BrowserHistory();
const client = new ApiClient();
const dest = document.getElementById('content');
const store = createStore(client, window.__data);
const search = document.location.search;
const query = search && queryString.parse(search);
const location = new Location(document.location.pathname, query);
universalRouter(location, history, store)
.then(({component}) => {
if (__DEVTOOLS__) {
const { DevTools, DebugPanel, LogMonitor } = require('redux-devtools/lib/react');
console.info('You will see a "Warning: React attempted to reuse markup in a container but the checksum was' +
' invalid." message. That\'s because the redux-devtools are enabled.');
React.render(<div>
{component}
<DebugPanel top right bottom key="debugPanel">
<DevTools store={store} monitor={LogMonitor}/>
</DebugPanel>
</div>, dest);
} else {
React.render(component, dest);
}
}, (error) => {
console.error(error);
});
if (process.env.NODE_ENV !== 'production') {
window.React = React; // enable debugger
const reactRoot = window.document.getElementById('content');
if (!reactRoot || !reactRoot.firstChild || !reactRoot.firstChild.attributes || !reactRoot.firstChild.attributes['data-react-checksum']) {
console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.');
}
}
|
src/component/layout/SideBarUserItem.js | babizhu/webApp | /**
* Created by liu_k on 2015/12/10.
*/
import React, { Component } from 'react';
import { Icon } from 'antd';
import styles from '../../css/layout/sidebar.scss'
class SideBarUserItem extends Component {
render() {
let{ userData,iconMode} = this.props;
//let user = this.props.userData;
//let iconMode = this.props.iconMode;//ๆฏๅฆไป
ๆพ็คบๅพๆ ๆจกๅผ
let mediaStyle = {
padding: '20px'
};
let mediaLeftStyle = {
paddingRight: '10px'
};
let mediaShow={
display :'table-cell'
};
if (iconMode) {
mediaStyle = {
padding: '23px 10px'
};
mediaLeftStyle = {
paddingRight: '0px'
};
mediaShow={
display :'none'
}
}
return (
<div className="sidebar-user">
<div className="category-content">
<div className="media" style={mediaStyle}>
<div className="media-left" style={mediaLeftStyle}>
<img src={userData.photoUrl} className="img-circle img-sm" alt=""/>
</div>
<div className="media-body" ref='mediaBody' style={mediaShow}>
<span>{userData.name}</span>
<div className="text-size-mini">
<Icon type="environment-o"/> {userData.address}
</div>
</div>
<div className="media-right" ref='mediaRight' style={mediaShow}>
<Icon type="setting"/>
</div>
</div>
</div>
</div>
);
}
}
SideBarUserItem.propTypes = {};
SideBarUserItem.defaultProps = {};
export default SideBarUserItem;
|
packages/material-ui-icons/src/LaptopWindows.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let LaptopWindows = props =>
<SvgIcon {...props}>
<path d="M20 18v-1c1.1 0 1.99-.9 1.99-2L22 5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2v1H0v2h24v-2h-4zM4 5h16v10H4V5z" />
</SvgIcon>;
LaptopWindows = pure(LaptopWindows);
LaptopWindows.muiName = 'SvgIcon';
export default LaptopWindows;
|
src/components/CheshireCat.js | pieroit/cheshire-cat |
import React from 'react'
class CheshireCat extends React.Component {
render() {
let children = React.Children.map( this.props.children, child => {
//console.log(child.type.name)
return (
<child.type {...child.props} />
)
} )
return (
<div className="cheshire-cat">
{children}
</div>
)
}
}
export default CheshireCat |
components/qrScene.js | marxsk/zobro | import React from 'react';
import {
StyleSheet,
View,
Text,
TouchableOpacity,
TouchableHighlight,
VibrationIOS,
Alert,
} from 'react-native';
import Camera from 'react-native-camera';
import animalDb from '../animals';
import * as scenes from '../scenes';
import Dimensions from 'Dimensions';
var WINDOW_WIDTH = Dimensions.get('window').width;
var WINDOW_HEIGHT = Dimensions.get('window').height;
class QRCodeScreen extends React.Component {
constructor(props) {
super(props);
this.state = { qrCodeAlreadyRead: false };
}
componentWillMount() {
this.props.bg();
}
_onPressCancel() {
// Alert.alert('-' + JSON.stringify(this.props));
var $this = this;
requestAnimationFrame(function() {
$this.props.navigator.pop();
if ($this.props.onCancel) {
$this.props.onCancel();
}
});
}
_onBarCodeReadOnce(result, navigator) {
var $this = this;
this.setState({qrCodeAlreadyRead: true});
scenes.navigatePush(navigator, scenes.ANIMAL_DETAIL, {animal: result.data});
}
render() {
this.barCodeFlag = true;
this._onBarCodeRead = (result) => {
return this._onBarCodeReadOnce(result, this.props.navigator);
};
// <CancelButton onPress={this._onPressCancel} title={this.props.cancelButtonTitle} />
if (this.state.qrCodeAlreadyRead) {
return (
<Camera style={styles.camera}>
<View style={styles.rectangleContainer}>
<View style={styles.rectangle}/>
</View>
</Camera>
);
} else {
return (
<Camera onBarCodeRead={this._onBarCodeRead} style={styles.camera}>
<View style={styles.rectangleContainer}>
<View style={styles.rectangle}/>
</View>
</Camera>
);
}
}
}
QRCodeScreen.propTypes = {
bg: React.PropTypes.func.isRequired,
cancelButtonVisible: React.PropTypes.bool,
cancelButtonTitle: React.PropTypes.string,
onSucess: React.PropTypes.func,
onCancel: React.PropTypes.func,
//@fix navigator: React.PropTypes.func.isRequired,
};
QRCodeScreen.defaultProps = {
cancelButtonVisible: false,
cancelButtonTitle: 'Zruลกit',
}
class CancelButton extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={styles.cancelButton}>
<TouchableOpacity onPress={this.props.onPress}>
<Text style={styles.cancelButtonText}>{this.props.title}</Text>
</TouchableOpacity>
</View>
);
}
}
var styles = StyleSheet.create({
camera: {
height: WINDOW_HEIGHT,
alignItems: 'center',
},
rectangleContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'transparent',
},
rectangle: {
height: 2*WINDOW_WIDTH/4,
width: 2*WINDOW_WIDTH/4,
borderWidth: 2,
borderColor: '#00FF00',
backgroundColor: 'transparent',
},
cancelButton: {
flexDirection: 'row',
justifyContent: 'center',
backgroundColor: 'white',
borderRadius: 3,
padding: 15,
width: 100,
bottom: 1*WINDOW_HEIGHT/5,
},
cancelButtonText: {
fontSize: 17,
fontWeight: '500',
color: '#0097CE',
},
});
module.exports = QRCodeScreen;
|
app/bootstrap.js | hichameyessou/blip | /**
* Copyright (c) 2014, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with appContext program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import React from 'react';
import { render } from 'react-dom';
import bows from 'bows';
import _ from 'lodash';
import './core/language'; // Set the language before loading components
import blipCreateStore from './redux/store';
import { getRoutes } from './routes';
import config from './config';
import api from './core/api';
import personUtils from './core/personutils';
import detectTouchScreen from './core/notouch';
/* global __DEV_TOOLS__ */
// For React developer tools
window.React = React;
export let appContext = {
log: __DEV_TOOLS__ ? bows('App') : _.noop,
api: api,
personUtils: personUtils,
DEBUG: !!(window.localStorage && window.localStorage.debug),
config: config
};
// This anonymous function must remain in ES5 format because
// the argument parameter used is not bound when using arrow functions
// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
appContext.trackMetric = function() {
const args = Array.prototype.slice.call(arguments);
return appContext.api.metrics.track.apply(appContext.api.metrics, args);
};
appContext.props = {
log: appContext.log,
api: appContext.api,
personUtils: appContext.personUtils,
trackMetric: appContext.trackMetric,
DEBUG: appContext.DEBUG,
config: appContext.config
};
appContext.init = callback => {
function beginInit() {
initNoTouch();
}
function initNoTouch() {
detectTouchScreen();
initApi();
}
function initApi() {
appContext.api.init(callback);
}
beginInit();
};
appContext.render = Component => {
render(
<Component store={appContext.store} routing={appContext.routing} />,
document.getElementById('app'),
);
};
/**
* Application start function. This is what should be called
* by anything wanting to start Blip and bootstrap to the DOM
*
* This renders the AppComponent into the DOM providing appContext
* as the context for AppComponent so that the required dependencies
* are passed in!
*
*/
appContext.start = (Component) => {
appContext.init(() => {
appContext.log('Starting app...');
appContext.store = blipCreateStore(appContext.api);
appContext.routing = getRoutes(appContext, appContext.store);
appContext.render(Component)
appContext.log('App started');
});
};
export default appContext;
|
src/svg-icons/notification/airline-seat-legroom-reduced.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationAirlineSeatLegroomReduced = (props) => (
<SvgIcon {...props}>
<path d="M19.97 19.2c.18.96-.55 1.8-1.47 1.8H14v-3l1-4H9c-1.65 0-3-1.35-3-3V3h6v6h5c1.1 0 2 .9 2 2l-2 7h1.44c.73 0 1.39.49 1.53 1.2zM5 12V3H3v9c0 2.76 2.24 5 5 5h4v-2H8c-1.66 0-3-1.34-3-3z"/>
</SvgIcon>
);
NotificationAirlineSeatLegroomReduced = pure(NotificationAirlineSeatLegroomReduced);
NotificationAirlineSeatLegroomReduced.displayName = 'NotificationAirlineSeatLegroomReduced';
NotificationAirlineSeatLegroomReduced.muiName = 'SvgIcon';
export default NotificationAirlineSeatLegroomReduced;
|
quiver_engine/quiverboard/src/components/Header/Header.js | wmkouw/quiver-time | import React from 'react';
import { IndexLink } from 'react-router';
import './Header.scss';
export const Header = () => (
<div>
</div>
);
export default Header;
|
reactjs/hello/src/index.js | guoxiaoyong/simple-useful | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
function Square(props) {
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
);
}
class Board extends React.Component {
renderSquare(i) {
return (
<Square
value={this.props.squares[i]}
onClick={() => this.props.onClick(i)}
/>
);
}
render() {
return (
<div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
class Game extends React.Component {
constructor(props) {
console.log('properties: ', props);
super(props);
this.state = {
history: [
{
squares: Array(9).fill(null)
}
],
stepNumber: 0,
xIsNext: true
};
}
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? "X" : "O";
this.setState({
history: history.concat([
{
squares: squares
}
]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext
});
}
jumpTo(step) {
this.setState({
stepNumber: step,
xIsNext: (step % 2) === 0
});
}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);
const moves = history.map((step, move) => {
const desc = move ?
'Go to move #' + move :
'Go to game start';
return (
<li key={move}>
<button onClick={() => this.jumpTo(move)}>{desc}</button>
</li>
);
});
let status;
if (winner) {
status = "Winner: " + winner;
} else {
status = "Next player: " + (this.state.xIsNext ? "X" : "O");
}
return (
<div className="game">
<div className="game-board">
<Board
squares={current.squares}
onClick={i => this.handleClick(i)}
/>
</div>
<div className="game-info">
<div>{status}</div>
<ol>{moves}</ol>
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(<Game />, document.getElementById("root"));
function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}
|
ui/src/core/components/FooterItem.js | Hajto/erlangpl | // @flow
import React from 'react';
import { OverlayTrigger, Popover } from 'react-bootstrap';
type Props = {
title: string,
id: string,
item: ?React$Element<any>,
popover: ?React$Element<any>
};
const FooterItem = ({ title, item, popover, id }: Props) => {
return (
<div className="Footer-item">
<OverlayTrigger
trigger={['hover']}
placement="top"
overlay={
<Popover id={id} title={title}>
{popover}
</Popover>
}
>
{item}
</OverlayTrigger>
</div>
);
};
export default FooterItem;
|
lib/components/term-group.js | wilsontayar/hyper | import React from 'react';
import {connect} from 'react-redux';
import Component from '../component';
import {decorate, getTermProps, getTermGroupProps} from '../utils/plugins';
import {resizeTermGroup} from '../actions/term-groups';
import Term_ from './term';
import SplitPane_ from './split-pane';
const Term = decorate(Term_, 'Term');
const SplitPane = decorate(SplitPane_, 'SplitPane');
class TermGroup_ extends Component {
constructor(props, context) {
super(props, context);
this.bound = new WeakMap();
}
bind(fn, thisObj, uid) {
if (!this.bound.has(fn)) {
this.bound.set(fn, {});
}
const map = this.bound.get(fn);
if (!map[uid]) {
map[uid] = fn.bind(thisObj, uid);
}
return map[uid];
}
renderSplit(groups) {
const [first, ...rest] = groups;
if (rest.length === 0) {
return first;
}
const direction = this.props.termGroup.direction.toLowerCase();
return (<SplitPane
direction={direction}
sizes={this.props.termGroup.sizes}
onResize={this.props.onTermGroupResize}
borderColor={this.props.borderColor}
>
{ groups }
</SplitPane>);
}
renderTerm(uid) {
const session = this.props.sessions[uid];
const termRef = this.props.terms[uid];
const props = getTermProps(uid, this.props, {
isTermActive: uid === this.props.activeSession,
term: termRef ? termRef.term : null,
customCSS: this.props.customCSS,
fontSize: this.props.fontSize,
cursorColor: this.props.cursorColor,
cursorShape: this.props.cursorShape,
cursorBlink: this.props.cursorBlink,
fontFamily: this.props.fontFamily,
uiFontFamily: this.props.uiFontFamily,
fontSmoothing: this.props.fontSmoothing,
foregroundColor: this.props.foregroundColor,
backgroundColor: this.props.backgroundColor,
modifierKeys: this.props.modifierKeys,
padding: this.props.padding,
colors: this.props.colors,
url: session.url,
cleared: session.cleared,
cols: session.cols,
rows: session.rows,
copyOnSelect: this.props.copyOnSelect,
bell: this.props.bell,
bellSoundURL: this.props.bellSoundURL,
onActive: this.bind(this.props.onActive, null, uid),
onResize: this.bind(this.props.onResize, null, uid),
onTitle: this.bind(this.props.onTitle, null, uid),
onData: this.bind(this.props.onData, null, uid),
onURLAbort: this.bind(this.props.onURLAbort, null, uid),
borderColor: this.props.borderColor,
quickEdit: this.props.quickEdit,
uid
});
// This will create a new ref_ function for every render,
// which is inefficient. Should maybe do something similar
// to this.bind.
return (<Term
key={uid}
ref_={term => this.props.ref_(uid, term)}
{...props}
/>);
}
template() {
const {childGroups, termGroup} = this.props;
if (termGroup.sessionUid) {
return this.renderTerm(termGroup.sessionUid);
}
const groups = childGroups.map(child => {
const props = getTermGroupProps(child.uid, this.props.parentProps, Object.assign({}, this.props, {
termGroup: child
}));
return (<DecoratedTermGroup
key={child.uid}
{...props}
/>);
});
return this.renderSplit(groups);
}
}
const TermGroup = connect(
(state, ownProps) => ({
childGroups: ownProps.termGroup.children.map(uid =>
state.termGroups.termGroups[uid]
)
}),
(dispatch, ownProps) => ({
onTermGroupResize(splitSizes) {
dispatch(resizeTermGroup(ownProps.termGroup.uid, splitSizes));
}
})
)(TermGroup_);
const DecoratedTermGroup = decorate(TermGroup, 'TermGroup');
export default TermGroup;
|
src/containers/Uielements/Tree/lineTree.js | EncontrAR/backoffice | import React from 'react';
import Tree from '../../../components/uielements/tree';
const TreeNode = Tree.TreeNode;
export default function() {
return (
<Tree showLine defaultExpandedKeys={['0-0-0']}>
<TreeNode title="parent 1" key="0-0">
<TreeNode title="parent 1-0" key="0-0-0">
<TreeNode title="leaf" key="0-0-0-0" />
<TreeNode title="leaf" key="0-0-0-1" />
<TreeNode title="leaf" key="0-0-0-2" />
</TreeNode>
<TreeNode title="parent 1-1" key="0-0-1">
<TreeNode title="leaf" key="0-0-1-0" />
</TreeNode>
<TreeNode title="parent 1-2" key="0-0-2">
<TreeNode title="leaf" key="0-0-2-0" />
<TreeNode title="leaf" key="0-0-2-1" />
</TreeNode>
</TreeNode>
</Tree>
);
}
|
src/pages/AppInfo.js | cuebrick/TypeWriter | import React from 'react';
import { Link } from 'react-router-dom';
import PackageInfo from '../../package';
// import HomeImage from '../images/home.svg';
class AppInfo extends React.Component{
render(){
return(
<div className="container">
<h3>Typing Play ์ ๋ํ ์ ๋ณด</h3>
<div className="app-info-item">์์ข
์ (Won, Jong-sun)์ ๊ฐ์ธ ํ๋ก์ ํธ๋ก ๋ง๋ค์ด ์ก์ต๋๋ค.</div>
<div className="app-info-item">
<h4>Contact</h4>
<p className="author">
๋ฌธ์ ๋๋ ๊ฐ์ ์ ๋ํ ์๊ฒฌ์ด ์์ผ๋ฉด ์๋์ ๋ฐฉ๋ฒ์ผ๋ก ์ฐ๋ฝํด ์ฃผ์ธ์.<br/>
e-mail : <a href="mailto:cuebrick@gmail.com">cuebrick@gmail.com</a><br/>
์น์ฌ์ดํธ : <a href="http://thiscript.com" target="_blank">http://thiscript.com</a>
</p>
</div>
<div className="app-info-item">
<h4>Program Version</h4>
<p>Typing Play {PackageInfo.version} last updated on April 24th, 2018</p>
</div>
<div className="app-info-item">
<h4>Open Source Licenses</h4>
<ul className="open-source-list">
<li>
<h5>ReactJS</h5>
<a href="https://reactjs.org/">https://reactjs.org/</a>
</li>
<li>
<h5>Hangul.js</h5>
<a href="https://www.npmjs.com/package/hangul-js">https://www.npmjs.com/package/hangul-js</a>
</li>
<li>
<h5>jQuery</h5>
<a href="https://www.jquery.com">https://www.jquery.com</a>
</li>
<li>
<h5>activate-power-mode</h5>
<a href="https://www.npmjs.com/package/activate-power-mode" target="_blank">https://www.npmjs.com/package/activate-power-mode</a>
</li>
</ul>
</div>
<div className="button-ui">
<Link to="/">
<button className="home-btn"><img src={"./images/home.svg"} width="15" height="15"/></button>
</Link>
<Link to="/levels"><button>๋จ๊ณ ๋ชฉ๋ก์ผ๋ก ์ด๋</button></Link>
<Link to="/about"><button>Typing Play ์ผ๋ฐ ์ ๋ณด</button></Link>
<Link to="/settings">
<button className="settings-btn"><img src={"./images/settings.svg"} width="15" height="15"/></button>
</Link>
</div>
</div>
)
}
}
export default AppInfo; |
admin/client/App/shared/FlashMessage.js | webteckie/keystone | /**
* A single flash message component. Used by FlashMessages.js
*/
import React from 'react';
import { Alert } from 'elemental';
const FlashMessage = React.createClass({
propTypes: {
message: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.string,
]),
type: React.PropTypes.string,
},
// Render the message
renderMessage (message) {
// If the message is only a string, render the string
if (typeof message === 'string') {
return (
<span>
{message}
</span>
);
}
// Get the title and the detail of the message
const title = message.title ? <h4>{message.title}</h4> : null;
const detail = message.detail ? <p>{message.detail}</p> : null;
// If the message has a list attached, render a <ul>
const list = message.list ? (
<ul style={{ marginBottom: 0 }}>
{message.list.map((item, i) => <li key={`i${i}`}>{item}</li>)}
</ul>
) : null;
return (
<span>
{title}
{detail}
{list}
</span>
);
},
render () {
return <Alert type={this.props.type}>{this.renderMessage(this.props.message)}</Alert>;
},
});
module.exports = FlashMessage;
|
frontend/app/js/components/plugin/screen.js | serverboards/serverboards | import React from 'react'
import plugin from 'app/utils/plugin'
import Loading from '../loading'
import {merge, to_keywordmap, match_traits, map_get} from 'app/utils'
import PropTypes from 'prop-types';
import {SectionMenu} from 'app/components'
import store from 'app/utils/store'
import i18n from 'app/utils/i18n'
import {ErrorBoundary} from 'app/components/error'
import Tip from 'app/components/tip'
const empty_box_img = require('imgs/026-illustration-nocontent.svg')
const plugin_load = plugin.load
const plugin_do_screen = plugin.do_screen
function SelectService(props){
const services = props.services || []
const uuid = props.selected && props.selected.uuid
return (
<div className="menu">
<div style={{width: 30}}/>
<div className="ui attached tabular menu">
{services.length > 0 ? services.map( s => (
<a key={s.uuid} className={`item ${s.uuid == uuid ? "active" : ""}`} onClick={() => props.onService(s.uuid)}>
{s.name}
</a>
)) : (
<h3 className="ui red header">{i18n("No services for this screen. Create one.")}</h3>
)}
</div>
</div>
)
}
class ExternalScreen extends React.Component{
constructor(props){
super(props)
this.state = {
umount: undefined,
service: props.service,
component: undefined,
}
}
componentWillUnmount(){
if (this.state.umount){
this.state.umount()
$(this.refs.el).html('')
}
}
componentDidMount(){
this.reloadScreen()
}
reloadScreen(){
this.componentWillUnmount()
const {props, state} = this
const plugin = props.plugin
const component = props.component
const context = {
plugin_id: plugin,
component_id: component,
screen_id: `${plugin}/${component}`
}
const load_js = () => {
if (this.state.cleanupf){
this.state.cleanupf() // Call before setting a new one
this.setState({cleanupf(){}})
}
const plugin_js=`${plugin}/${component}.js`
const pprops = {
...(props.data || this.props.location.state),
...props,
project: props.project,
service: state.service
}
const el = this.refs.el
plugin_load(plugin_js).then(() =>
plugin_do_screen(`${plugin}/${component}`, el, pprops, context)
).then( ({umount, component}) => {
this.setState({umount, component})
}).catch( (e) => {
console.warn("Could not load JS %o: %o", plugin_js, e)
})
}
$(this.refs.el)
.attr('data-pluginid', plugin)
.attr('data-screenid', `${plugin}/${component}`)
const hints = to_keywordmap(map_get(this.props, ["screen", "extra", "hints"], []))
const plugin_html = `${plugin}/${component}.html`
const plugin_css = `${plugin}/${component}.css`
// console.log("Screen hints", hints, this.props)
Promise.all([
!hints["nohtml"] && plugin_load(plugin_html, {base_url: plugin}),
!hints["nocss"] && plugin_load(plugin_css, {base_url: plugin})
]).then( (html) => {
$(this.refs.el).html(html)
load_js()
}).catch( (e) => {
console.warn("Could not load HTML %o: %o", plugin_html, e)
$(this.refs.el).html('')
load_js()
})
}
handleService(current){
const service = this.props.services.find( s => s.uuid == current )
this.setState({current, service}, this.reloadScreen.bind(this))
}
componentWillReceiveProps(newprops){
const nuuid = newprops.service && newprops.service.uuid
const puuid = this.props.service && this.props.service.uuid
const suuid = this.state.service && this.state.service.uuid
if (nuuid != puuid && nuuid != suuid){
this.setState({service: newprops.service}, this.reloadScreen.bind(this))
}
}
render(){
const {props, state} = this
const plugin = props.plugin || props.params.plugin
const component = props.component || props.params.component
if (props.require_service && !state.service){
return (
<Tip
title={i18n("No compatible service exists")}
description={i18n("This screen requires a compatible service, and none was found.\n\nPlease add a compatible service type and try again.")}
top_img={empty_box_img}
middle_img={null}
/>
)
}
let content
const Screen = state.component
if (Screen)
content = (
<Screen {...props} {...state}/>
)
else
content = (
<div ref="el" className="ui central white background expand">
<Loading>
External plugin {plugin}/{component}
</Loading>
</div>
)
return (
<React.Fragment>
{props.show_menu && (
<ErrorBoundary>
<SectionMenu
menu={SelectService}
onService={this.handleService.bind(this)}
services={props.services}
selected={state.service}
/>
</ErrorBoundary>
)}
<ErrorBoundary>
{content}
</ErrorBoundary>
</React.Fragment>
)
}
}
ExternalScreen.contextTypes = {
router: PropTypes.object
}
export default ExternalScreen
|
tilapp/src/containers/Scenes/Auth/Screens/Welcome/index.js | tilap/tilapp | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Text, Button, View } from 'native-base';
import Paper from '~/components/Paper/';
class WelcomeScreen extends Component {
render() {
return (
<View>
<Paper>
<Text>Hi {this.props.firstname}!</Text>
<Text>
Welcome on the app. You can now contact book sellers and chat with them or sell your own book.
</Text>
</Paper>
<Text />
<Button full onPress={() => this.props.closeAuthScreen()}>
<Text>Continue</Text>
</Button>
<Button transparent full onPress={() => this.props.navigation.navigate('Presentation')}>
<Text>Watch the presentation</Text>
</Button>
</View>
);
}
}
WelcomeScreen.propTypes = {
closeAuthScreen: PropTypes.func.isRequired,
navigation: PropTypes.any.isRequired,
firstname: PropTypes.string.isRequired,
}
const mapStateToProps = ({ services: { account: { firstname } }}) => ({ firstname });
WelcomeScreen.navigationOptions = {
title: 'Welcome',
};
export default connect(mapStateToProps)(WelcomeScreen);
|
app/javascript/mastodon/features/ui/components/mute_modal.js | gol-cha/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import Toggle from 'react-toggle';
import Button from '../../../components/button';
import { closeModal } from '../../../actions/modal';
import { muteAccount } from '../../../actions/accounts';
import { toggleHideNotifications, changeMuteDuration } from '../../../actions/mutes';
const messages = defineMessages({
minutes: { id: 'intervals.full.minutes', defaultMessage: '{number, plural, one {# minute} other {# minutes}}' },
hours: { id: 'intervals.full.hours', defaultMessage: '{number, plural, one {# hour} other {# hours}}' },
days: { id: 'intervals.full.days', defaultMessage: '{number, plural, one {# day} other {# days}}' },
indefinite: { id: 'mute_modal.indefinite', defaultMessage: 'Indefinite' },
});
const mapStateToProps = state => {
return {
account: state.getIn(['mutes', 'new', 'account']),
notifications: state.getIn(['mutes', 'new', 'notifications']),
muteDuration: state.getIn(['mutes', 'new', 'duration']),
};
};
const mapDispatchToProps = dispatch => {
return {
onConfirm(account, notifications, muteDuration) {
dispatch(muteAccount(account.get('id'), notifications, muteDuration));
},
onClose() {
dispatch(closeModal());
},
onToggleNotifications() {
dispatch(toggleHideNotifications());
},
onChangeMuteDuration(e) {
dispatch(changeMuteDuration(e.target.value));
},
};
};
export default @connect(mapStateToProps, mapDispatchToProps)
@injectIntl
class MuteModal extends React.PureComponent {
static propTypes = {
account: PropTypes.object.isRequired,
notifications: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
onConfirm: PropTypes.func.isRequired,
onToggleNotifications: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
muteDuration: PropTypes.number.isRequired,
onChangeMuteDuration: PropTypes.func.isRequired,
};
componentDidMount() {
this.button.focus();
}
handleClick = () => {
this.props.onClose();
this.props.onConfirm(this.props.account, this.props.notifications, this.props.muteDuration);
}
handleCancel = () => {
this.props.onClose();
}
setRef = (c) => {
this.button = c;
}
toggleNotifications = () => {
this.props.onToggleNotifications();
}
changeMuteDuration = (e) => {
this.props.onChangeMuteDuration(e);
}
render () {
const { account, notifications, muteDuration, intl } = this.props;
return (
<div className='modal-root__modal mute-modal'>
<div className='mute-modal__container'>
<p>
<FormattedMessage
id='confirmations.mute.message'
defaultMessage='Are you sure you want to mute {name}?'
values={{ name: <strong>@{account.get('acct')}</strong> }}
/>
</p>
<p className='mute-modal__explanation'>
<FormattedMessage
id='confirmations.mute.explanation'
defaultMessage='This will hide posts from them and posts mentioning them, but it will still allow them to see your posts and follow you.'
/>
</p>
<div className='setting-toggle'>
<Toggle id='mute-modal__hide-notifications-checkbox' checked={notifications} onChange={this.toggleNotifications} />
<label className='setting-toggle__label' htmlFor='mute-modal__hide-notifications-checkbox'>
<FormattedMessage id='mute_modal.hide_notifications' defaultMessage='Hide notifications from this user?' />
</label>
</div>
<div>
<span><FormattedMessage id='mute_modal.duration' defaultMessage='Duration' />: </span>
{/* eslint-disable-next-line jsx-a11y/no-onchange */}
<select value={muteDuration} onChange={this.changeMuteDuration}>
<option value={0}>{intl.formatMessage(messages.indefinite)}</option>
<option value={300}>{intl.formatMessage(messages.minutes, { number: 5 })}</option>
<option value={1800}>{intl.formatMessage(messages.minutes, { number: 30 })}</option>
<option value={3600}>{intl.formatMessage(messages.hours, { number: 1 })}</option>
<option value={21600}>{intl.formatMessage(messages.hours, { number: 6 })}</option>
<option value={86400}>{intl.formatMessage(messages.days, { number: 1 })}</option>
<option value={259200}>{intl.formatMessage(messages.days, { number: 3 })}</option>
<option value={604800}>{intl.formatMessage(messages.days, { number: 7 })}</option>
</select>
</div>
</div>
<div className='mute-modal__action-bar'>
<Button onClick={this.handleCancel} className='mute-modal__cancel-button'>
<FormattedMessage id='confirmation_modal.cancel' defaultMessage='Cancel' />
</Button>
<Button onClick={this.handleClick} ref={this.setRef}>
<FormattedMessage id='confirmations.mute.confirm' defaultMessage='Mute' />
</Button>
</div>
</div>
);
}
}
|
examples/src/components/RemoteSelectField.js | snowkeeper/react-select | import React from 'react';
import Select from 'react-select';
var RemoteSelectField = React.createClass({
displayName: 'RemoteSelectField',
propTypes: {
hint: React.PropTypes.string,
label: React.PropTypes.string,
},
loadOptions (input, callback) {
input = input.toLowerCase();
var rtn = {
options: [
{ label: 'One', value: 'one' },
{ label: 'Two', value: 'two' },
{ label: 'Three', value: 'three' }
],
complete: true
};
if (input.slice(0, 1) === 'a') {
if (input.slice(0, 2) === 'ab') {
rtn = {
options: [
{ label: 'AB', value: 'ab' },
{ label: 'ABC', value: 'abc' },
{ label: 'ABCD', value: 'abcd' }
],
complete: true
};
} else {
rtn = {
options: [
{ label: 'A', value: 'a' },
{ label: 'AA', value: 'aa' },
{ label: 'AB', value: 'ab' }
],
complete: false
};
}
} else if (!input.length) {
rtn.complete = false;
}
setTimeout(function() {
callback(null, rtn);
}, 500);
},
renderHint () {
if (!this.props.hint) return null;
return (
<div className="hint">{this.props.hint}</div>
);
},
render () {
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select asyncOptions={this.loadOptions} className="remote-example" />
{this.renderHint()}
</div>
);
}
});
module.exports = RemoteSelectField;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.