path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
src/components/pages/Account/Reset.js
|
ESTEBANMURUZABAL/my-ecommerce-template
|
/**
* Imports.
*/
import React from 'react';
import connectToStores from 'fluxible-addons-react/connectToStores';
import {FormattedMessage} from 'react-intl';
// Flux
import IntlStore from '../../../stores/Application/IntlStore';
import ResetStore from '../../../stores/Account/ResetStore';
import resetRequest from '../../../actions/Account/resetRequest';
// Required components
import Button from '../../common/buttons/Button';
import Heading from '../../common/typography/Heading';
import InputField from '../../common/forms/InputField';
import Modal from '../../common/modals/Modal';
import Text from '../../common/typography/Text';
// Translation data for this component
import intlData from './Reset.intl';
/**
* Component.
*/
class Reset extends React.Component {
static contextTypes = {
executeAction: React.PropTypes.func.isRequired,
getStore: React.PropTypes.func.isRequired,
router: React.PropTypes.func.isRequired
};
//*** Page Title and Snippets ***//
static pageTitleAndSnippets = function (context) {
return {
title: context.getStore(IntlStore).getMessage(intlData, 'title')
}
};
//*** Initial State ***//
state = {
loading: this.context.getStore(ResetStore).isLoading(),
error: this.context.getStore(ResetStore).getError(),
email: undefined,
fieldErrors: {},
errorMessage: undefined,
showSuccessModal: false
};
//*** Component Lifecycle ***//
componentDidMount() {
// Component styles
require('./Reset.scss');
}
componentWillReceiveProps(nextProps) {
// Find field error descriptions in request response
let fieldErrors = {};
if (this.state.loading && !nextProps._loading && nextProps._error) {
if (nextProps._error.validation && nextProps._error.validation.keys) {
nextProps._error.validation.keys.forEach(function (field) {
fieldErrors[field] = nextProps._error.validation.details[field];
});
} else if (nextProps._error.hasOwnProperty('message')) {
this.setState({errorMessage: nextProps._error.message});
} else {
this.setState({
errorMessage: this.context.getStore(IntlStore).getMessage(intlData, 'unknownError')
});
}
}
// Check for a successful reset request
if (this.state.loading && !nextProps._loading && !nextProps._error) {
this.setState({showSuccessModal: true});
}
// Update state
this.setState({
loading: nextProps._loading,
error: nextProps._error,
fieldErrors: fieldErrors
})
}
//*** View Controllers ***//
handleFieldChange = (param, value) => {
this.setState({[param]: value});
};
handleSubmitClick = () => {
let intlStore = this.context.getStore(IntlStore);
this.setState({errorMessage: null});
this.setState({fieldErrors: {}});
let fieldErrors = {};
if (!this.state.email) {
fieldErrors.email = intlStore.getMessage(intlData, 'fieldRequired');
}
this.setState({fieldErrors: fieldErrors});
if (Object.keys(fieldErrors).length === 0) {
this.context.executeAction(resetRequest, {email: this.state.email});
}
};
handleModalContinueClick = () => {
this.context.router.transitionTo('homepage', {locale: this.context.getStore(IntlStore).getCurrentLocale()});
};
//*** Template ***//
render() {
//
// Helper methods & variables
//
let intlStore = this.context.getStore(IntlStore);
let successModal = () => {
if (this.state.showSuccessModal) {
return (
<Modal title={intlStore.getMessage(intlData, 'successModalTitle')}>
<div className="reset__modal-body">
<Text size="medium">
<FormattedMessage
message={intlStore.getMessage(intlData, 'successModalBody')}
locales={intlStore.getCurrentLocale()} />
</Text>
</div>
<div className="reset__modal-footer">
<Button type="primary" onClick={this.handleModalContinueClick}>
<FormattedMessage message={intlStore.getMessage(intlData, 'successModalContinue')}
locales={intlStore.getCurrentLocale()} />
</Button>
</div>
</Modal>
);
}
};
//
// Return
//
return (
<div className="reset">
{successModal()}
<div className="reset__container">
<div className="reset__header">
<Heading>
<FormattedMessage message={intlStore.getMessage(intlData, 'title')}
locales={intlStore.getCurrentLocale()} />
</Heading>
</div>
{this.state.errorMessage ?
<div className="reset__error-message">
<Text size="small">{this.state.errorMessage}</Text>
</div>
:
null
}
<div className="reset__form">
<div className="reset__form-item">
<InputField label={intlStore.getMessage(intlData, 'email')}
onChange={this.handleFieldChange.bind(null, 'email')}
onEnterPress={this.handleSubmitClick}
error={this.state.fieldErrors['email']}
value={this.state.email} />
</div>
<div className="reset__form-actions">
<Button type="primary" onClick={this.handleSubmitClick} disabled={this.state.loading}>
<FormattedMessage message={intlStore.getMessage(intlData, 'submit')}
locales={intlStore.getCurrentLocale()} />
</Button>
</div>
</div>
</div>
</div>
);
}
}
/**
* Flux
*/
Reset = connectToStores(Reset, [ResetStore], (context) => {
return {
_error: context.getStore(ResetStore).getError(),
_loading: context.getStore(ResetStore).isLoading()
};
});
/**
* Export
*/
export default Reset;
|
cm19/ReactJS/your-first-react-app-exercises-master/exercise-17/theme/context.js
|
Brandon-J-Campbell/codemash
|
import React from 'react';
export default React.createContext();
|
examples/async/index.js
|
contolini/redux
|
import 'babel-core/polyfill';
import React from 'react';
import { Provider } from 'react-redux';
import App from './containers/App';
import configureStore from './store/configureStore';
const store = configureStore();
React.render(
<Provider store={store}>
{() => <App />}
</Provider>,
document.getElementById('root')
);
|
app/containers/DashboardContainer/index.js
|
Blacksage959/Michael.McCann
|
/*
*
* DashboardContainer
*
*/
import React from 'react';
import Helmet from 'react-helmet';
export default class DashboardContainer extends React.PureComponent {
constructor(props){
super(props);
this.state ={
title:"",
body:"",
image:"",
preview:"",
}
}
handleTitle = (event) => {
this.setState({
title:event.target.value
})
console.log(this.state.title);
}
handleBody = (event) => {
this.setState({
body:event.target.value
})
console.log(this.state.body);
}
handleImage = (event) => {
event.preventDefault();
let reader = new FileReader();
let file = event.target.files[0];
reader.onloadend= () => {
this.setState({
image:file,
preview: reader.result
})
}
reader.readAsDataURL(file);
}
storeArticle = () => {
var data = new FormData();
data.append("title",this.state.title);
data.append("body",this.state.body);
data.append("image",this.state.image);
fetch("http://owlversee.com/api/storeArticle",{
method:"post",
body:data
})
.then(function(response) {
return response.json();
})
.then(function(json) {
if(json.success) {
alert(json.success);
}
else if(json.error) {
alert(json.error);
}
})
}
render() {
const dashEnv={
height:"100vh",
width:"100%",
backgroundColor:"rgba(3,150,3,.3)",
padding:"10%",
justifyContent:"center",
}
const dashForm={
backgroundColor:"rgba(160,255,160,1)",
display:"flex",
flexDirection:"column",
padding:"5%",
boxShadow:"0 0 20px 5px rgba(0,0,0,0.4)",
borderRadius:"2px",
}
const dashBoxColor={
height:"auto",
width:"auto",
backgroundColor:"rgba(220,255,220,1)",
marginBottom:"3%",
border:"1px solid green",
maxHeight:"500px",
overflow:"hidden",
padding:"10"
}
const dashTitle={
fontSize:"3em",
textAlign:"center",
fontWeight:"bold",
fontVariant:"small-caps",
fontFamily:"Lato",
color:"green",
}
const imgConstraint={
maxHeight:"600px",
margin:"10",
}
return (
<div style={dashEnv}>
<div style={dashForm}>
<Helmet title="DashboardContainer" meta={[ { name: 'description', content: 'Description of DashboardContainer' }]}/>
<div style={dashTitle}>
GreenWorx Article Dash
</div>
<div style={dashBoxColor}>
<input onChange={this.handleTitle} type="text" placeholder="New Title"/>
</div>
<div style={dashBoxColor}>
<textarea onChange={this.handleBody} rows="5" placeholder="Write Body"> </textarea>
</div>
<div style={dashBoxColor}>
<input onChange={this.handleImage} type="file"/>
<img style={imgConstraint} src={this.state.preview}/>
</div>
<div style={dashBoxColor}>
<input onTouchTap={this.storeArticle} type="submit"/>
</div>
</div>
</div>
);
}
}
|
analysis/druidferal/src/modules/features/EnergyCapTracker.js
|
yajinni/WoWAnalyzer
|
import React from 'react';
import SPELLS from 'common/SPELLS';
import RESOURCE_TYPES from 'game/RESOURCE_TYPES';
import { formatPercentage } from 'common/format';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';
import Statistic from 'parser/ui/Statistic';
import RegenResourceCapTracker from 'parser/shared/modules/resources/resourcetracker/RegenResourceCapTracker';
import BoringResourceValue from 'parser/ui/BoringResourceValue';
import { t } from '@lingui/macro';
import SpellEnergyCost from './SpellEnergyCost';
const BASE_ENERGY_REGEN = 11;
const BASE_ENERGY_MAX = 100;
const MOMENT_OF_CLARITY_MAX_ADDITION = 30;
const BERSERK_MAX_ADDITION = 50;
const RESOURCE_REFUND_ON_MISS = 0.8;
/**
* Sets up RegenResourceCapTracker to accurately track the regenerating energy of a Feral druid.
* Taking into account the effect of buffs, talents, and items on the energy cost of abilities,
* the maximum energy amount, and the regeneration rate.
* Note that some cost reduction effects are already accounted for in the log.
*
* No need to override getReducedDrain:
* Reduced drain cost from Berserk/Incarnation on Ferocious Bite is already applied in the log.
*/
class EnergyCapTracker extends RegenResourceCapTracker {
get percentCapped() {
return (this.naturalRegen - this.missedRegen) / this.naturalRegen;
}
get suggestionThresholds() {
return {
actual: this.percentCapped,
isLessThan: {
minor: .8,
average: .70,
major: .65,
},
style: 'percentage',
};
}
static dependencies = {
...RegenResourceCapTracker.dependencies,
// Needed for the `resourceCost` prop of events
spellResourceCost: SpellEnergyCost,
};
static resourceType = RESOURCE_TYPES.ENERGY;
static baseRegenRate = BASE_ENERGY_REGEN;
static isRegenHasted = true;
static cumulativeEventWindow = 400;
static buffsChangeMax = [
SPELLS.BERSERK.id,
SPELLS.INCARNATION_KING_OF_THE_JUNGLE_TALENT.id,
];
static resourceRefundOnMiss = RESOURCE_REFUND_ON_MISS;
static exemptFromRefund = [
SPELLS.THRASH_FERAL.id,
SPELLS.SWIPE_CAT.id,
SPELLS.BRUTAL_SLASH_TALENT.id,
];
currentMaxResource() {
let max = BASE_ENERGY_MAX;
if (this.selectedCombatant.hasTalent(SPELLS.MOMENT_OF_CLARITY_TALENT.id)) {
max += MOMENT_OF_CLARITY_MAX_ADDITION;
}
if (this.combatantHasBuffActive(SPELLS.BERSERK.id) || this.combatantHasBuffActive(SPELLS.INCARNATION_KING_OF_THE_JUNGLE_TALENT.id)) {
// combatantHasBuffActive is used so that if the buff faded at this timestamp it will not count.
max += BERSERK_MAX_ADDITION;
}
// What should be x.5 becomes x in-game.
return Math.floor(max);
}
suggestions(when) {
when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => suggest(
<>
You're allowing your energy to reach its cap. While at its maximum value you miss out on the energy that would have regenerated. Although it can be beneficial to let energy pool ready to be used at the right time, try to spend some before it reaches the cap.
</>,
)
.icon('spell_shadow_shadowworddominate')
.actual(t({
id: "druid.feral.suggestions.energy.efficiency",
message: `${formatPercentage(actual)}% regenerated energy lost per minute due to being capped.`
}))
.recommended(`<${recommended}% is recommended.`));
}
statistic() {
return (
<Statistic
tooltip={(
<>
Although it can be beneficial to wait and let your energy pool ready to be used at the right time, you should still avoid letting it reach the cap.<br />
You spent <strong>{formatPercentage(this.cappedProportion)}%</strong> of the fight at capped energy, causing you to miss out on a total of <strong>{this.missedRegen.toFixed(0)}</strong> energy from regeneration.
</>
)}
size="flexible"
position={STATISTIC_ORDER.CORE(1)}
>
<BoringResourceValue resource={RESOURCE_TYPES.ENERGY} value={`${formatPercentage(this.percentCapped)}%`} label="Wasted energy per minute from being capped" />
</Statistic>
);
}
}
export default EnergyCapTracker;
|
src/icons/SendIcon.js
|
kiloe/ui
|
import React from 'react';
import Icon from '../Icon';
export default class SendIcon extends Icon {
getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M4.02 42L46 24 4.02 6 4 20l30 4-30 4z"/></svg>;}
};
|
docs/src/PageFooter.js
|
yickli/react-bootstrap
|
import React from 'react';
import packageJSON from '../../package.json';
let version = packageJSON.version;
if (/docs/.test(version)) {
version = version.split('-')[0];
}
const PageHeader = React.createClass({
render() {
return (
<footer className='bs-docs-footer' role='contentinfo'>
<div className='container'>
<div className='bs-docs-social'>
<ul className='bs-docs-social-buttons'>
<li>
<iframe className='github-btn'
src='http://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=watch&count=true'
width={95}
height={20}
title='Star on GitHub' />
</li>
<li>
<iframe className='github-btn'
src='http://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=fork&count=true'
width={92}
height={20}
title='Fork on GitHub' />
</li>
<li>
<iframe
src="http://platform.twitter.com/widgets/follow_button.html?screen_name=react_bootstrap&show_screen_name=true"
width={230}
height={20}
allowTransparency="true"
frameBorder='0'
scrolling='no'>
</iframe>
</li>
</ul>
</div>
<p>Code licensed under <a href='https://github.com/react-bootstrap/react-bootstrap/blob/master/LICENSE' target='_blank'>MIT</a>.</p>
<ul className='bs-docs-footer-links muted'>
<li>Currently v{version}</li>
<li>·</li>
<li><a href='https://github.com/react-bootstrap/react-bootstrap/'>GitHub</a></li>
<li>·</li>
<li><a href='https://github.com/react-bootstrap/react-bootstrap/issues?state=open'>Issues</a></li>
<li>·</li>
<li><a href='https://github.com/react-bootstrap/react-bootstrap/releases'>Releases</a></li>
</ul>
</div>
</footer>
);
}
});
export default PageHeader;
|
src/components/Icon/Icon.js
|
Amine-H/Amine-H.github.io
|
// @flow strict
import React from 'react';
import styles from './Icon.module.scss';
type Props = {
name: string,
icon: {
viewBox?: string,
path?: string
}
};
const Icon = ({ name, icon }: Props) => (
<svg className={styles['icon']} viewBox={icon.viewBox}>
<title>{name}</title>
<path d={icon.path} />
</svg>
);
export default Icon;
|
src/components/App.js
|
eddiekollar/ReactSimple
|
import React, { Component } from 'react';
import Home from './Home';
class App extends Component {
render() {
return (
<div>
<h2>Welcome to React Simple</h2>
<p >
To get started, edit <code>src/components/App.js</code> or <code>src/components/Home.js</code> and save to reload.
</p>
<Home />
</div>
);
}
}
export default App;
|
app/javascript/mastodon/components/autosuggest_textarea.js
|
tateisu/mastodon
|
import React from 'react';
import AutosuggestAccountContainer from '../features/compose/containers/autosuggest_account_container';
import AutosuggestEmoji from './autosuggest_emoji';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { isRtl } from '../rtl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Textarea from 'react-textarea-autosize';
import classNames from 'classnames';
const textAtCursorMatchesToken = (str, caretPosition) => {
let word;
let left = str.slice(0, caretPosition).search(/\S+$/);
let right = str.slice(caretPosition).search(/\s/);
if (right < 0) {
word = str.slice(left);
} else {
word = str.slice(left, right + caretPosition);
}
if (!word || word.trim().length < 3 || ['@', ':', '#'].indexOf(word[0]) === -1) {
return [null, null];
}
word = word.trim().toLowerCase();
if (word.length > 0) {
return [left + 1, word];
} else {
return [null, null];
}
};
export default class AutosuggestTextarea extends ImmutablePureComponent {
static propTypes = {
value: PropTypes.string,
suggestions: ImmutablePropTypes.list,
disabled: PropTypes.bool,
placeholder: PropTypes.string,
onSuggestionSelected: PropTypes.func.isRequired,
onSuggestionsClearRequested: PropTypes.func.isRequired,
onSuggestionsFetchRequested: PropTypes.func.isRequired,
onChange: PropTypes.func.isRequired,
onKeyUp: PropTypes.func,
onKeyDown: PropTypes.func,
onPaste: PropTypes.func.isRequired,
autoFocus: PropTypes.bool,
};
static defaultProps = {
autoFocus: true,
};
state = {
suggestionsHidden: true,
focused: false,
selectedSuggestion: 0,
lastToken: null,
tokenStart: 0,
};
onChange = (e) => {
const [ tokenStart, token ] = textAtCursorMatchesToken(e.target.value, e.target.selectionStart);
if (token !== null && this.state.lastToken !== token) {
this.setState({ lastToken: token, selectedSuggestion: 0, tokenStart });
this.props.onSuggestionsFetchRequested(token);
} else if (token === null) {
this.setState({ lastToken: null });
this.props.onSuggestionsClearRequested();
}
this.props.onChange(e);
}
onKeyDown = (e) => {
const { suggestions, disabled } = this.props;
const { selectedSuggestion, suggestionsHidden } = this.state;
if (disabled) {
e.preventDefault();
return;
}
if (e.which === 229 || e.isComposing) {
// Ignore key events during text composition
// e.key may be a name of the physical key even in this case (e.x. Safari / Chrome on Mac)
return;
}
switch(e.key) {
case 'Escape':
if (suggestions.size === 0 || suggestionsHidden) {
document.querySelector('.ui').parentElement.focus();
} else {
e.preventDefault();
this.setState({ suggestionsHidden: true });
}
break;
case 'ArrowDown':
if (suggestions.size > 0 && !suggestionsHidden) {
e.preventDefault();
this.setState({ selectedSuggestion: Math.min(selectedSuggestion + 1, suggestions.size - 1) });
}
break;
case 'ArrowUp':
if (suggestions.size > 0 && !suggestionsHidden) {
e.preventDefault();
this.setState({ selectedSuggestion: Math.max(selectedSuggestion - 1, 0) });
}
break;
case 'Enter':
case 'Tab':
// Select suggestion
if (this.state.lastToken !== null && suggestions.size > 0 && !suggestionsHidden) {
e.preventDefault();
e.stopPropagation();
this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestions.get(selectedSuggestion));
}
break;
}
if (e.defaultPrevented || !this.props.onKeyDown) {
return;
}
this.props.onKeyDown(e);
}
onBlur = () => {
this.setState({ suggestionsHidden: true, focused: false });
}
onFocus = (e) => {
this.setState({ focused: true });
if (this.props.onFocus) {
this.props.onFocus(e);
}
}
onSuggestionClick = (e) => {
const suggestion = this.props.suggestions.get(e.currentTarget.getAttribute('data-index'));
e.preventDefault();
this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestion);
this.textarea.focus();
}
componentWillReceiveProps (nextProps) {
if (nextProps.suggestions !== this.props.suggestions && nextProps.suggestions.size > 0 && this.state.suggestionsHidden && this.state.focused) {
this.setState({ suggestionsHidden: false });
}
}
setTextarea = (c) => {
this.textarea = c;
}
onPaste = (e) => {
if (e.clipboardData && e.clipboardData.files.length === 1) {
this.props.onPaste(e.clipboardData.files);
e.preventDefault();
}
}
renderSuggestion = (suggestion, i) => {
const { selectedSuggestion } = this.state;
let inner, key;
if (typeof suggestion === 'object') {
inner = <AutosuggestEmoji emoji={suggestion} />;
key = suggestion.id;
} else if (suggestion[0] === '#') {
inner = suggestion;
key = suggestion;
} else {
inner = <AutosuggestAccountContainer id={suggestion} />;
key = suggestion;
}
return (
<div role='button' tabIndex='0' key={key} data-index={i} className={classNames('autosuggest-textarea__suggestions__item', { selected: i === selectedSuggestion })} onMouseDown={this.onSuggestionClick}>
{inner}
</div>
);
}
render () {
const { value, suggestions, disabled, placeholder, onKeyUp, autoFocus, children } = this.props;
const { suggestionsHidden } = this.state;
const style = { direction: 'ltr' };
if (isRtl(value)) {
style.direction = 'rtl';
}
return [
<div className='compose-form__autosuggest-wrapper' key='autosuggest-wrapper'>
<div className='autosuggest-textarea'>
<label>
<span style={{ display: 'none' }}>{placeholder}</span>
<Textarea
inputRef={this.setTextarea}
className='autosuggest-textarea__textarea'
disabled={disabled}
placeholder={placeholder}
autoFocus={autoFocus}
value={value}
onChange={this.onChange}
onKeyDown={this.onKeyDown}
onKeyUp={onKeyUp}
onFocus={this.onFocus}
onBlur={this.onBlur}
onPaste={this.onPaste}
style={style}
aria-autocomplete='list'
/>
</label>
</div>
{children}
</div>,
<div className='autosuggest-textarea__suggestions-wrapper' key='suggestions-wrapper'>
<div className={`autosuggest-textarea__suggestions ${suggestionsHidden || suggestions.isEmpty() ? '' : 'autosuggest-textarea__suggestions--visible'}`}>
{suggestions.map(this.renderSuggestion)}
</div>
</div>,
];
}
}
|
client/menu/menu.js
|
sekainogenkai/faito
|
import {Buttons} from '../game/input';
import {DummyInputTarget} from '../player';
import React from 'react';
// maybe use this method later https://facebook.github.io/react-native/docs/style.html
const styles = {
menu: {
position: "absolute",
top: 0,
left: 0,
bottom: 0,
right: 0,
height: '100%',
width: '100%',
overflow: 'auto',
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: 'center',
},
mainMenuItem: {
padding: '10px 40px 10px 40px',
fontSize: '4em',
},
selected: {
color: '#eeffff',
backgroundColor: 'red',
border: '5px dotted black',
},
nonSelected: {
backgroundColor: 'white',
}
};
class DummyMenuInputTarget {
down() {
}
up() {
}
action() {
}
}
class MenuInputTarget extends DummyInputTarget {
constructor() {
super();
this.setTarget(new DummyMenuInputTarget());
}
buttonDown(button) {
switch (button) {
case Buttons.JoyDown: this._target.down(); break;
case Buttons.JoyUp: this._target.up(); break;
case Buttons.A: this._target.action(); break;
}
}
setTarget(target) {
this._target = target;
}
}
export default class Menu extends React.Component {
constructor(props) {
super(props);
this.state = Object.assign(this.state || {}, {
menuPages: [React.Children.only(props.children)],
});
this._inputTarget = new MenuInputTarget();
// In the future could make per-player cursors in the
// menu. For now, just traditional shared menu.
this.setSharedInputTargetFinder();
}
/**
* Set the target to the shared one so that when switching to
* normal menus they get input at all.
*/
setSharedInputTargetFinder() {
this.props.players.setInputTargetFinder((i, player) => this._inputTarget);
}
/**
* MenuPages call this get input focused on them.
*/
setMenuInputTarget(target) {
// In case the menu page overrode input handling, switch back to normal.
this.setSharedInputTargetFinder();
this._inputTarget.setTarget(target);
}
/**
* Push a new MenuPage onto the stack, causing it to be displayed
* in place of the current one.
*/
pushMenuPage(menuPage) {
this.setState({
menuPages: this.state.menuPages.concat([menuPage]),
});
}
popMenuPage() {
// If this would remove the last one, hide the menu instead.
const nextMenuPages = this.state.menuPages.slice(0, this.state.menuPages.length - 1);
const nextMenuPage = nextMenuPages[nextMenuPages.length - 1];
this.setState({
menuPages: nextMenuPages,
});
if (!nextMenuPage) {
this.props.onHide();
}
}
clearMenu() {
this.setState({
menuPages: [],
});
this.props.onHide();
}
render() {
const children = this.state.menuPages[this.state.menuPages.length - 1] || [];
return <div className="menu" style={styles.menu}>
{React.Children.map(children, (child, i) => React.cloneElement(child, {
menu: this,
// In case the MenuPage wants to override input handling.
players: this.props.players,
// If we don’t have a different key, React applies the
// state from from MenuPage to sub menu, etc., because
// it thinks we’re rerendering the same instance.
key: `${this.state.menuPages.length}`,
}))}
</div>;
}
}
/**
* To create a custom MenuPage, you must define componentDidMount
* and connect inputs. Do not extend this class. Just accept
* and use the passed in menu and players objects.
*/
export class MenuPage extends React.Component {
constructor(props) {
super(props);
this.state = {
currentIndex: 0,
};
this.items = [];
}
handleMenuItemMounted(i, menuItem) {
this.items[i] = menuItem;
if (!menuItem.selectable && this.state.currentIndex == i) {
this.setState({
currentIndex: this.state.currentIndex + 1,
});
}
}
action() {
this.items[this.state.currentIndex].action(this.props.menu);
}
componentDidMount() {
this.props.menu.setMenuInputTarget(this);
}
move(direction) {
let newIndex = this.state.currentIndex;
while (true) {
newIndex += direction;
if (newIndex < 0 || newIndex >= this.items.length) {
return;
}
if ((this.items[newIndex] || {}).selectable) {
break;
}
}
this.setState({
currentIndex: newIndex,
});
}
down() {
this.move(1);
}
up() {
this.move(-1);
}
render() {
return <div className="menu-page">
{React.Children.map(this.props.children, (child, i) => React.cloneElement(child, {
active: i === this.state.currentIndex,
key: i,
mounted: menuItem => this.handleMenuItemMounted(i, menuItem),
}))}
</div>;
}
}
export class MenuItem extends React.Component {
constructor(props) {
super(props);
this.selectable = true;
}
componentDidMount() {
this.props.mounted(this);
}
render() {
return <div className="menu-item" style={{
...(this.props.active ? styles.selected : styles.nonSelected),
...styles.mainMenuItem }}>
{this.props.children}
</div>;
}
}
export class ButtonMenuItem extends MenuItem {
constructor(props) {
super(props);
}
action(menu) {
this.props.action(menu);
}
}
export class LabelMenuItem extends MenuItem {
constructor(props){
super(props);
this.selectable = false;
}
}
|
src/common/StatusLabel/InactiveStatusLabel.js
|
Syncano/syncano-dashboard
|
import React from 'react';
import { FontIcon } from 'material-ui';
import { colors as Colors } from 'material-ui/styles';
const InactiveStatusLabel = ({ style }) => (
<FontIcon
style={style}
className="synicon-close"
color={Colors.red400}
/>
);
export default InactiveStatusLabel;
|
src/client/assets/js/nodes/processors/uibuilder/features/palette/components/Palette.js
|
me-box/iot.red
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actionCreators as paletteActions, viewConstants, selector } from '../';
import "./Palette.scss";
import FontIcon from 'react-md/lib/FontIcons';
import Paper from 'react-md/lib/Papers';
import Button from 'react-md/lib/Buttons/Button';
import PaletteLayout from './PaletteLayout';
@connect(selector, (dispatch) => {
return {
actions: bindActionCreators(paletteActions, dispatch)
}
})
export default class Palette extends Component {
render() {
const {h} = this.props;
return (
<Paper zDepth={2} style={{position:'absolute', zIndex:1, overflowY:'visible', height:h, color:"white", background:"#3f51b5", width:viewConstants.PALETTE_WIDTH}}>
<PaletteLayout {...this.props} />
</Paper>
);
}
}
|
examples/date-type/src/DateField.js
|
fourlabsldn/fl-form-builder
|
import React from 'react';
import ReactDOM from 'react-dom';
import { curry } from 'lodash/fp';
const updateField = curry((update, state, initialState, fieldName, e) => {
const value = e.target.value || initialState[fieldName];
const newState = Object.assign({}, state, { [fieldName]: value });
update(newState);
});
const updateDate = curry((numCount, propName, state, update, e) => {
const value = e.target.value
.toString()
.replace(/[^0-9]/g, '') // remove non-numeric characters
.replace(/^0*/, '') // remove leading zeroes
.slice(-numCount); // we only case about the last `numCount` digits
const newValue = value;
const newState = Object.assign({}, state, { [propName]: newValue });
update(newState);
const fieldFilled = newValue.length === numCount;
const nextField = ReactDOM.findDOMNode(e.target).nextElementSibling;
if (fieldFilled && nextField && nextField.nodeName === 'INPUT') {
nextField.focus();
}
});
const typeInfo = {
// Compulsory
type: 'DateField',
displayName: 'Date Field',
group: 'Custom Components',
required: false,
// Component specific fields
title: 'My date component',
day: '',
month: '',
year: '',
};
// For Text Fields the initialState function will only return an object.
const initialState = () => Object.assign({}, typeInfo);
// When configuration is open, this is what is going to be displayed
/**
* @method RenderConfigMode
* @param {Object} state : State
* @param {Function} update : State -> void // Will trigger a re-render
*/
const RenderEditor = ({ state, update }) => {
return (
<div>
{state.configShowing
? (
<h2>
<input
type="text"
className="fl-fb-Field-editable"
onChange={updateField(update, state, initialState, 'title')}
defaultValue={state.title}
/>
</h2>
)
: <h2>{state.title}</h2>
}
<input
type="text"
placeholder="DD"
value={state.day}
onChange={updateDate(2, 'day', state, update)}
/>
/
<input
type="text"
placeholder="MM"
value={state.month}
onChange={updateDate(2, 'month', state, update)}
/>
/
<input
type="text"
placeholder="YYYY"
value={state.year}
onChange={updateDate(4, 'year', state, update)}
/>
</div>
);
};
const ImageCards = {
info: typeInfo,
initialState,
RenderEditor,
};
export default ImageCards;
|
ui/src/containers/SideNav/CollapsibleNav.js
|
LearningLocker/learninglocker
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { routeNodeSelector } from 'redux-router5';
import { VelocityComponent } from 'velocity-react';
import { compose } from 'recompose';
import { connect } from 'react-redux';
import { includesSegment } from 'router5.helpers';
import Link from 'ui/containers/Link';
import { activeLinkClassName, SubNav } from 'ui/containers/SideNav/styled';
class CollapsibleNav extends Component {
static propTypes = {
icon: PropTypes.string,
label: PropTypes.string,
children: PropTypes.node,
routeName: PropTypes.string,
routeParams: PropTypes.object,
activeRoute: PropTypes.object
};
constructor(props, context) {
super(props, context);
this.state = {
bodyHeight: 0
};
}
setBodyHeight = () => {
if (this.bodyDom) {
this.setState({
bodyHeight: this.bodyDom.clientHeight
});
}
}
saveBodyRef = (ref) => {
this.bodyDom = ref;
this.setBodyHeight();
}
onClick = (e) => {
e.preventDefault();
const { onClick, routeName } = this.props;
onClick(routeName);
}
animationComplete = isExpanded => () => {
if (isExpanded) {
this.bodyDom.style.height = 'auto';
}
}
render = () => {
const { bodyHeight } = this.state;
const {
children,
label,
icon,
routeName,
routeParams,
activeRoute,
manuallyExpanded
} = this.props;
const isExpanded = includesSegment(activeRoute.name, routeName) || manuallyExpanded;
const animationProps = isExpanded ? {
height: [bodyHeight, [100, 14]],
} : {
height: [0, [100, 14]],
};
return (
<li>
<Link
routeName={routeName}
routeParams={routeParams}
activeClassName={`${activeLinkClassName}`}
isActive={isExpanded}
onClick={this.onClick}>
<i className={icon} /> {label}
</Link>
<VelocityComponent
animation={animationProps}
duration={350}
complete={this.animationComplete(isExpanded)} >
<SubNav
className={'nav animated fadeIn'}
ref={this.saveBodyRef}
style={{ overflow: 'hidden' }}>
{children}
</SubNav>
</VelocityComponent>
</li>
);
}
}
export default compose(
connect((state, { routeName }) => ({
activeRoute: routeNodeSelector(routeName)(state).route
}))
)(CollapsibleNav);
|
src/svg-icons/action/restore-page.js
|
pomerantsev/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionRestorePage = (props) => (
<SvgIcon {...props}>
<path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm-2 16c-2.05 0-3.81-1.24-4.58-3h1.71c.63.9 1.68 1.5 2.87 1.5 1.93 0 3.5-1.57 3.5-3.5S13.93 9.5 12 9.5c-1.35 0-2.52.78-3.1 1.9l1.6 1.6h-4V9l1.3 1.3C8.69 8.92 10.23 8 12 8c2.76 0 5 2.24 5 5s-2.24 5-5 5z"/>
</SvgIcon>
);
ActionRestorePage = pure(ActionRestorePage);
ActionRestorePage.displayName = 'ActionRestorePage';
ActionRestorePage.muiName = 'SvgIcon';
export default ActionRestorePage;
|
example/src/pages/ResponsiveImages.js
|
ethanselzer/react-image-magnify
|
import React, { Component } from 'react';
import {
Col,
Grid,
Jumbotron,
Row
} from 'react-bootstrap';
import Helmet from 'react-helmet';
import Header from '../components/Header';
import ResponsiveImages from '../components/ResponsiveImages';
import 'bootstrap/dist/css/bootstrap.css';
import '../styles/app.css';
export default class extends Component {
render() {
return (
<div>
<Helmet title="React Image Magnify" />
<Header {...this.props}/>
<Jumbotron>
<Grid>
<Row>
<Col sm={12}>
</Col>
</Row>
</Grid>
</Jumbotron>
<Grid>
<Row>
<Col sm={12}>
<ResponsiveImages />
</Col>
</Row>
</Grid>
</div>
);
}
}
|
src/server.js
|
peeyush1234/react-nodejs-skeleton
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import path from 'path';
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import expressJwt from 'express-jwt';
import expressGraphQL from 'express-graphql';
import jwt from 'jsonwebtoken';
import React from 'react';
import ReactDOM from 'react-dom/server';
import UniversalRouter from 'universal-router';
import PrettyError from 'pretty-error';
// import winston from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';
import expressWinston from 'express-winston';
import App from './components/App';
import Html from './components/Html';
import { ErrorPageWithoutStyle } from './routes/error/ErrorPage';
import errorPageStyle from './routes/error/ErrorPage.css';
import passport from './core/passport';
import models from './data/models';
import schema from './data/schema';
import routes from './routes';
import assets from './assets.json'; // eslint-disable-line import/no-unresolved
import { port, auth, logDir } from './config';
const app = express();
//
// Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the
// user agent is not known.
// -----------------------------------------------------------------------------
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || 'all';
//
// Register Node.js middleware
// -----------------------------------------------------------------------------
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//
// Logging
// -----------------------------------------------------------------------------
const tsFormat = () => (new Date()).toLocaleTimeString();
app.use(expressWinston.logger({
transports: [
new DailyRotateFile({
filename: `${logDir}/react-node-skeleton-app.log`,
timestamp: tsFormat,
level: __DEV__ ? 'verbose' : 'info',
}),
],
meta: true,
msg: 'HTTP {{req.method}} {{req.url}}',
expressFormat: true,
colorize: true,
}));
//
// Authentication
// -----------------------------------------------------------------------------
app.use(expressJwt({
secret: auth.jwt.secret,
credentialsRequired: false,
getToken: req => req.cookies.id_token,
}));
app.use(passport.initialize());
if (__DEV__) {
app.enable('trust proxy');
}
app.get('/login/facebook',
passport.authenticate('facebook', { scope: ['email', 'user_location'], session: false }),
);
app.get('/login/facebook/return',
passport.authenticate('facebook', { failureRedirect: '/login', session: false }),
(req, res) => {
const expiresIn = 60 * 60 * 24 * 180; // 180 days
const token = jwt.sign(req.user, auth.jwt.secret, { expiresIn });
res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true });
res.redirect('/');
},
);
//
// Register API middleware
// -----------------------------------------------------------------------------
app.use('/graphql', expressGraphQL(req => ({
schema,
graphiql: __DEV__,
rootValue: { request: req },
pretty: __DEV__,
})));
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
app.get('*', async (req, res, next) => {
try {
const css = new Set();
// Global (context) variables that can be easily accessed from any React component
// https://facebook.github.io/react/docs/context.html
const context = {
// Enables critical path CSS rendering
// https://github.com/kriasoft/isomorphic-style-loader
insertCss: (...styles) => {
// eslint-disable-next-line no-underscore-dangle
styles.forEach(style => css.add(style._getCss()));
},
};
const route = await UniversalRouter.resolve(routes, {
path: req.path,
query: req.query,
});
if (route.redirect) {
res.redirect(route.status || 302, route.redirect);
return;
}
const data = { ...route };
data.children = ReactDOM.renderToString(<App context={context}>{route.component}</App>);
data.styles = [
{ id: 'css', cssText: [...css].join('') },
];
data.scripts = [
assets.vendor.js,
assets.client.js,
];
if (assets[route.chunk]) {
data.scripts.push(assets[route.chunk].js);
}
const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
res.status(route.status || 200);
res.send(`<!doctype html>${html}`);
} catch (err) {
next(err);
}
});
//
// Error handling
// -----------------------------------------------------------------------------
const pe = new PrettyError();
pe.skipNodeFiles();
pe.skipPackage('express');
app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
console.log(pe.render(err)); // eslint-disable-line no-console
const html = ReactDOM.renderToStaticMarkup(
<Html
title="Internal Server Error"
description={err.message}
styles={[{ id: 'css', cssText: errorPageStyle._getCss() }]} // eslint-disable-line no-underscore-dangle
>
{ReactDOM.renderToString(<ErrorPageWithoutStyle error={err} />)}
</Html>,
);
res.status(err.status || 500);
res.send(`<!doctype html>${html}`);
});
//
// Launch the server
// -----------------------------------------------------------------------------
/* eslint-disable no-console */
models.sync().catch(err => console.error(err.stack)).then(() => {
app.listen(port, () => {
console.log(`The server is running at http://localhost:${port}/`);
});
});
/* eslint-enable no-console */
|
app/src/components/Users/index.js
|
jeremyhon/sia-challenge
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Route, Switch, Link, withRouter } from 'react-router-dom';
import { fetchUsers } from './actions';
import List from './views/list';
import Form from './views/form';
import Detail from './views/detail';
class Users extends Component {
componentWillMount() {
const { dispatch } = this.props;
dispatch(fetchUsers());
}
handleUpdate() {}
handleChange() {}
handleSubmit({ username, password }) {
this.props.onLogin({ username, password });
}
render() {
const { users } = this.props;
return (
<main>
<div className="page-head">
<div className="page-title">
<h1 className="page-header text-overflow">Users</h1>
<div className="searchbox">
<div className="input-group custom-search-form">
<input type="text" className="form-control" placeholder="Search.." />
<span className="input-group-btn">
<button className="text-muted" type="button">
<i className="demo-pli-magnifi-glass" />
</button>
</span>
</div>
</div>
</div>
<ol className="breadcrumb">
<li>
<Link to="/">Home</Link>
</li>
<li className="active">Users</li>
</ol>
</div>
<div className="page-content">
<div className="row">
<Switch>
<Route exact path="/users" render={props => <List {...props} users={users.users} />} />
<Route
exact
path="/users/add"
render={props => (
<Form
{...props}
handleUpdate={this.handleUpdate.bind(this)}
handleChange={this.handleChange.bind(this)}
handleSubmit={this.handleSubmit.bind(this)}
/>
)}
/>
<Route
path="/users/:userId"
render={props => {
return <Detail {...props} user={users.users.find(u => props.match.params.userId)} />;
}}
/>
</Switch>
</div>
</div>
</main>
);
}
}
function mapStateToProps(state) {
const { auth, users } = state;
const { isAuthenticated, error } = auth;
return {
users,
isAuthenticated,
error
};
}
export default withRouter(connect(mapStateToProps)(Users));
|
src/ButtonInput.js
|
snadn/react-bootstrap
|
import React from 'react';
import Button from './Button';
import FormGroup from './FormGroup';
import InputBase from './InputBase';
import childrenValueValidation from './utils/childrenValueInputValidation';
class ButtonInput extends InputBase {
renderFormGroup(children) {
let {bsStyle, value, ...other} = this.props;
return <FormGroup {...other}>{children}</FormGroup>;
}
renderInput() {
let {children, value, ...other} = this.props;
let val = children ? children : value;
return <Button {...other} componentClass="input" ref="input" key="input" value={val} />;
}
}
ButtonInput.types = ['button', 'reset', 'submit'];
ButtonInput.defaultProps = {
type: 'button'
};
ButtonInput.propTypes = {
type: React.PropTypes.oneOf(ButtonInput.types),
bsStyle(props) {
//defer to Button propTypes of bsStyle
return null;
},
children: childrenValueValidation,
value: childrenValueValidation
};
export default ButtonInput;
|
src/components/Username/WithCard.js
|
u-wave/web
|
import React from 'react';
import PropTypes from 'prop-types';
import useUserCard from '../../hooks/useUserCard';
import UsernameBase from '.';
const { useCallback } = React;
function UsernameWithCard({ user }) {
const userCard = useUserCard(user);
const onUsernameClick = useCallback((event) => {
event.preventDefault();
userCard.open();
// The `userCard.open` reference never changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<>
{userCard.card}
<button
type="button"
onClick={onUsernameClick}
ref={userCard.refAnchor}
>
<UsernameBase user={user} />
</button>
</>
);
}
UsernameWithCard.propTypes = {
user: PropTypes.object.isRequired,
};
export default UsernameWithCard;
|
packages/icons/src/md/maps/RestaurantMenu.js
|
suitejs/suitejs
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdRestaurantMenu(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M15.71 26.417l5.66-5.66L7.34 6.727c-3.12 3.12-3.12 8.19 0 11.31l8.37 8.38zm13.57-3.63c3.05 1.43 7.36.42 10.54-2.76 3.83-3.83 4.56-9.3 1.63-12.23-2.94-2.93-8.42-2.2-12.24 1.63-3.18 3.18-4.18 7.49-2.76 10.54-4.45 4.44-19.53 19.52-19.53 19.52l2.83 2.83 13.76-13.76 13.76 13.76 2.83-2.83-13.76-13.76 2.94-2.94z" />
</IconBase>
);
}
export default MdRestaurantMenu;
|
src/server.js
|
cssinjs/cssinjs
|
import React from 'react'
import {renderToString} from 'react-dom/server'
import {match, RouterContext} from 'react-router'
import {stripIndents} from 'common-tags'
import {minify} from 'html-minifier'
import {SheetsRegistry} from 'react-jss'
import {version} from '../package.json'
import routes from './routes'
import config from './config'
const minifyOptions = {
minifyCSS: true,
minifyJS: true
}
const renderAnalytics = () =>
stripIndents`
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-89548578-1', 'auto');
ga('send', 'pageview');
</script>
`
const renderSidecar = () =>
stripIndents`
<script>
((window.gitter = {}).chat = {}).options = {
room: '${config.site.gitter}'
};
</script>
<script src="https://sidecar.gitter.im/dist/sidecar.v1.js" async defer></script>
`
const renderDoc = ({app, css, analytics, sidecar}) =>
stripIndents`
<!doctype html>
<html lang="en">
<head>
<title>${config.site.head.title}</title>
<meta name="description" content="${config.site.head.description}" />
<meta name="keywords" content="${config.site.head.keywords.join(' ')}" />
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta httpEquiv="Content-Language" content="en" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta property="og:title" content="${config.site.og.title}" />
<meta property="og:description" content="${config.site.og.description}" />
<meta property="og:type" content="${config.site.og.type}" />
<meta property="og:image" content="${config.site.og.image}" />
<meta property="og:url" content="${config.site.og.url}" />
<link rel="shortcut icon" href="/images/favicon.ico" />
<style id="critical-css" type="text/css">
${css}
</style>
<link rel="stylesheet" type="text/css" href="/vendor.styles.v${version}.css" />
</head>
<body>
${app}
<script src="/vendor.bundle.v${version}.js"></script>
<script src="/bundle.v${version}.js"></script>
${analytics}
${sidecar}
</body>
</html>
`
export default (location, callback) => {
const registry = new SheetsRegistry()
match({routes: routes({registry}), location}, (error, redirectLocation, renderProps) => {
const html = renderDoc({
app: renderToString(<RouterContext {...renderProps} />),
css: registry.toString(),
analytics: renderAnalytics(),
sidecar: renderSidecar()
})
callback(minify(html, minifyOptions))
})
}
|
app/index.js
|
Andrew-Hird/bFM-desktop
|
import React from 'react';
import { render } from 'react-dom';
import { hashHistory } from 'react-router';
import { AppContainer } from 'react-hot-loader';
import { syncHistoryWithStore } from 'react-router-redux';
import Root from './containers/Root';
import configureStore from './store/configureStore';
import './app.global.css';
const store = configureStore();
const history = syncHistoryWithStore(hashHistory, store);
render(
<AppContainer>
<Root store={store} history={history} />
</AppContainer>,
document.getElementById('root')
);
if (module.hot) {
module.hot.accept('./containers/Root', () => {
const NextRoot = require('./containers/Root'); // eslint-disable-line global-require
render(
<AppContainer>
<NextRoot store={store} history={history} />
</AppContainer>,
document.getElementById('root')
);
});
}
|
examples/auth-with-shared-root/components/About.js
|
bs1180/react-router
|
import React from 'react'
const About = React.createClass({
render() {
return <h1>About</h1>
}
})
export default About
|
code/workspaces/web-app/src/components/app/NavLink.js
|
NERC-CEH/datalab
|
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import { NavLink } from 'react-router-dom';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import Icon from '@material-ui/core/Icon';
const styles = theme => ({
listIcon: {
color: 'inherit',
minWidth: '24px', // standard size of MUI icons - overrides default value
paddingRight: theme.spacing(2),
},
});
const AdapterNavLink = React.forwardRef((props, ref) => <NavLink innerRef={ref} {...props} />);
const Link = ({ classes, to, label, icon, ...rest }) => {
// Simple li element must be wrapped with forward ref to avoid React warnings
const LiLink = React.forwardRef(({ activeClassName, exact, ...liProps }, ref) => <li ref={ref} {...liProps} />);
return (
<ListItem
to={to}
component={to ? AdapterNavLink : LiLink}
button={true}
{...rest}>
{icon ? <ListItemIcon className={classes.listIcon}><Icon style={{ color: 'inherit' }}>{icon}</Icon></ListItemIcon> : undefined}
{label}
</ListItem>
);
};
export default withStyles(styles)(Link);
|
src/svg-icons/editor/format-indent-increase.js
|
ruifortes/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatIndentIncrease = (props) => (
<SvgIcon {...props}>
<path d="M3 21h18v-2H3v2zM3 8v8l4-4-4-4zm8 9h10v-2H11v2zM3 3v2h18V3H3zm8 6h10V7H11v2zm0 4h10v-2H11v2z"/>
</SvgIcon>
);
EditorFormatIndentIncrease = pure(EditorFormatIndentIncrease);
EditorFormatIndentIncrease.displayName = 'EditorFormatIndentIncrease';
EditorFormatIndentIncrease.muiName = 'SvgIcon';
export default EditorFormatIndentIncrease;
|
src/Parser/Mage/Shared/Modules/Features/RuneOfPower.js
|
enragednuke/WoWAnalyzer
|
import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';
import { formatNumber, formatPercentage } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import Combatants from 'Parser/Core/Modules/Combatants';
import AbilityTracker from 'Parser/Core/Modules/AbilityTracker';
import Analyzer from 'Parser/Core/Analyzer';
import getDamageBonus from '../GetDamageBonus';
const DAMAGE_BONUS = 0.4;
const RUNE_DURATION = 10;
const INCANTERS_FLOW_EXPECTED_BOOST = 0.12;
// FIXME due to interactions with Ignite, the damage boost number will be underrated for Fire Mages. Still fine for Arcane and Frost.
class RuneOfPower extends Analyzer {
static dependencies = {
combatants: Combatants,
abilityTracker: AbilityTracker,
};
damage = 0;
on_initialized() {
this.active = this.combatants.selected.hasTalent(SPELLS.RUNE_OF_POWER_TALENT.id);
}
on_byPlayer_damage(event) {
if (this.combatants.selected.hasBuff(SPELLS.RUNE_OF_POWER_BUFF.id)) {
this.damage += getDamageBonus(event, DAMAGE_BONUS);
}
}
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.damageIncreasePercent).isLessThan(this.damageSuggestionThresholds.isLessThan.minor)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span>Your <SpellLink id={SPELLS.RUNE_OF_POWER_TALENT.id} /> damage boost is below the expected passive gain from <SpellLink id={SPELLS.INCANTERS_FLOW_TALENT.id} />. Either find ways to make better use of the talent, or switch to <SpellLink id={SPELLS.INCANTERS_FLOW_TALENT.id} />.</span>)
.icon(SPELLS.RUNE_OF_POWER_TALENT.icon)
.actual(`${formatPercentage(this.damageIncreasePercent)}% damage increase from Rune of Power`)
.recommended(`${formatPercentage(recommended)}% is the passive gain from Incanter's Flow`)
.regular(this.damageSuggestionThresholds.isLessThan.average).major(this.damageSuggestionThresholds.isLessThan.major);
});
const casts = this.abilityTracker.getAbility(SPELLS.RUNE_OF_POWER_TALENT.id).casts;
if (!casts) {
return;
}
const uptimeMs = this.combatants.selected.getBuffUptime(SPELLS.RUNE_OF_POWER_BUFF.id);
const roundedSecondsPerCast = ((uptimeMs / casts) / 1000).toFixed(1);
when(roundedSecondsPerCast).isLessThan(RUNE_DURATION)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span>You sometimes aren't standing in your <SpellLink id={SPELLS.RUNE_OF_POWER_TALENT.id} /> for its full duration. Try to only use it when you know you won't have to move for the duration of the effect.</span>)
.icon(SPELLS.RUNE_OF_POWER_TALENT.icon)
.actual(`Average ${roundedSecondsPerCast}s standing in each Rune of Power`)
.recommended(`the full duration of ${formatNumber(RUNE_DURATION)}s is recommended`)
.regular(recommended - 1).major(recommended - 3);
});
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.RUNE_OF_POWER_TALENT.id} />}
value={`${formatPercentage(this.damagePercent)} %`}
label="Rune of Power damage"
tooltip={`This is the portion of your total damage attributable to Rune of Power's boost. Expressed as an increase vs never using Rune of Power, this is a <b>${formatPercentage(this.damageIncreasePercent)}% damage increase</b>. Note that this number does <i>not</i> factor in the opportunity cost of casting Rune of Power instead of another damaging spell`}
/>
);
}
statisticOrder = STATISTIC_ORDER.OPTIONAL(100);
}
export default RuneOfPower;
|
examples/todomvc/containers/Root.js
|
knowbody/redux
|
import React, { Component } from 'react';
import TodoApp from './TodoApp';
import { createStore, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from '../reducers';
const store = createStore(rootReducer);
export default class Root extends Component {
render() {
return (
<Provider store={store}>
{() => <TodoApp /> }
</Provider>
);
}
}
|
react-flux-mui/js/material-ui/src/svg-icons/image/grid-off.js
|
pbogdan/react-flux-mui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageGridOff = (props) => (
<SvgIcon {...props}>
<path d="M8 4v1.45l2 2V4h4v4h-3.45l2 2H14v1.45l2 2V10h4v4h-3.45l2 2H20v1.45l2 2V4c0-1.1-.9-2-2-2H4.55l2 2H8zm8 0h4v4h-4V4zM1.27 1.27L0 2.55l2 2V20c0 1.1.9 2 2 2h15.46l2 2 1.27-1.27L1.27 1.27zM10 12.55L11.45 14H10v-1.45zm-6-6L5.45 8H4V6.55zM8 20H4v-4h4v4zm0-6H4v-4h3.45l.55.55V14zm6 6h-4v-4h3.45l.55.54V20zm2 0v-1.46L17.46 20H16z"/>
</SvgIcon>
);
ImageGridOff = pure(ImageGridOff);
ImageGridOff.displayName = 'ImageGridOff';
ImageGridOff.muiName = 'SvgIcon';
export default ImageGridOff;
|
src/client.js
|
pavlosvos/krifominima
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 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 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import FastClick from 'fastclick';
import UniversalRouter from 'universal-router';
import queryString from 'query-string';
import { createPath } from 'history/PathUtils';
import history from './core/history';
import App from './components/App';
import { ErrorReporter, deepForceUpdate } from './core/devUtils';
// Global (context) variables that can be easily accessed from any React component
// https://facebook.github.io/react/docs/context.html
const context = {
// Enables critical path CSS rendering
// https://github.com/kriasoft/isomorphic-style-loader
insertCss: (...styles) => {
// eslint-disable-next-line no-underscore-dangle
const removeCss = styles.map(x => x._insertCss());
return () => { removeCss.forEach(f => f()); };
},
};
function updateTag(tagName, keyName, keyValue, attrName, attrValue) {
const node = document.head.querySelector(`${tagName}[${keyName}="${keyValue}"]`);
if (node && node.getAttribute(attrName) === attrValue) return;
// Remove and create a new tag in order to make it work with bookmarks in Safari
if (node) {
node.parentNode.removeChild(node);
}
if (typeof attrValue === 'string') {
const nextNode = document.createElement(tagName);
nextNode.setAttribute(keyName, keyValue);
nextNode.setAttribute(attrName, attrValue);
document.head.appendChild(nextNode);
}
}
function updateMeta(name, content) {
updateTag('meta', 'name', name, 'content', content);
}
function updateCustomMeta(property, content) { // eslint-disable-line no-unused-vars
updateTag('meta', 'property', property, 'content', content);
}
function updateLink(rel, href) { // eslint-disable-line no-unused-vars
updateTag('link', 'rel', rel, 'href', href);
}
// Switch off the native scroll restoration behavior and handle it manually
// https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration
const scrollPositionsHistory = {};
if (window.history && 'scrollRestoration' in window.history) {
window.history.scrollRestoration = 'manual';
}
let onRenderComplete = function initialRenderComplete() {
const elem = document.getElementById('css');
if (elem) elem.parentNode.removeChild(elem);
onRenderComplete = function renderComplete(route, location) {
document.title = route.title;
updateMeta('description', route.description);
// Update necessary tags in <head> at runtime here, ie:
// updateMeta('keywords', route.keywords);
// updateCustomMeta('og:url', route.canonicalUrl);
// updateCustomMeta('og:image', route.imageUrl);
// updateLink('canonical', route.canonicalUrl);
// etc.
let scrollX = 0;
let scrollY = 0;
const pos = scrollPositionsHistory[location.key];
if (pos) {
scrollX = pos.scrollX;
scrollY = pos.scrollY;
} else {
const targetHash = location.hash.substr(1);
if (targetHash) {
const target = document.getElementById(targetHash);
if (target) {
scrollY = window.pageYOffset + target.getBoundingClientRect().top;
}
}
}
// Restore the scroll position if it was saved into the state
// or scroll to the given #hash anchor
// or scroll to top of the page
window.scrollTo(scrollX, scrollY);
// Google Analytics tracking. Don't send 'pageview' event after
// the initial rendering, as it was already sent
if (window.ga) {
window.ga('send', 'pageview', createPath(location));
}
};
};
// Make taps on links and buttons work fast on mobiles
FastClick.attach(document.body);
const container = document.getElementById('app');
let appInstance;
let currentLocation = history.location;
let routes = require('./routes').default;
// Re-render the app when window.location changes
async function onLocationChange(location) {
// Remember the latest scroll position for the previous location
scrollPositionsHistory[currentLocation.key] = {
scrollX: window.pageXOffset,
scrollY: window.pageYOffset,
};
// Delete stored scroll position for next page if any
if (history.action === 'PUSH') {
delete scrollPositionsHistory[location.key];
}
currentLocation = location;
try {
// Traverses the list of routes in the order they are defined until
// it finds the first route that matches provided URL path string
// and whose action method returns anything other than `undefined`.
const route = await UniversalRouter.resolve(routes, {
path: location.pathname,
query: queryString.parse(location.search),
});
// Prevent multiple page renders during the routing process
if (currentLocation.key !== location.key) {
return;
}
if (route.redirect) {
history.replace(route.redirect);
return;
}
appInstance = ReactDOM.render(
<App context={context}>{route.component}</App>,
container,
() => onRenderComplete(route, location),
);
} catch (error) {
console.error(error); // eslint-disable-line no-console
// Current url has been changed during navigation process, do nothing
if (currentLocation.key !== location.key) {
return;
}
// Display the error in full-screen for development mode
if (process.env.NODE_ENV !== 'production') {
appInstance = null;
document.title = `Error: ${error.message}`;
ReactDOM.render(<ErrorReporter error={error} />, container);
return;
}
// Avoid broken navigation in production mode by a full page reload on error
window.location.reload();
}
}
// Handle client-side navigation by using HTML5 History API
// For more information visit https://github.com/mjackson/history#readme
history.listen(onLocationChange);
onLocationChange(currentLocation);
// Enable Hot Module Replacement (HMR)
if (module.hot) {
module.hot.accept('./routes', () => {
routes = require('./routes').default; // eslint-disable-line global-require
if (appInstance) {
try {
// Force-update the whole tree, including components that refuse to update
deepForceUpdate(appInstance);
} catch (error) {
appInstance = null;
document.title = `Hot Update Error: ${error.message}`;
ReactDOM.render(<ErrorReporter error={error} />, container);
return;
}
}
onLocationChange(currentLocation);
});
}
|
packages/bonde-admin-canary/src/components/Tutorial/Dialog/index.js
|
ourcities/rebu-client
|
import React from 'react'
import PropTypes from 'prop-types'
import Context from '../Context'
import DialogTooltip from './DialogTooltip'
export class RegisterDialog extends React.Component {
componentDidMount () {
const { name, context } = this.props
context.registerStep(name)
}
render () {
const { context, ...props } = this.props
return context.currentStep === props.step ? (
<DialogTooltip
total={context.total}
currentStep={context.currentStep}
onNext={context.onNext}
onClose={context.onClose}
{...props}
/>
) : props.children
}
}
const Dialog = (props) => (
<Context.Consumer>
{context => <RegisterDialog context={context} {...props} />}
</Context.Consumer>
)
Dialog.propTypes = {
name: PropTypes.string.isRequired,
step: PropTypes.number.isRequired
}
export default Dialog
|
src/js/components/icons/base/PlatformFreebsd.js
|
kylebyerly-hp/grommet
|
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-platform-freebsd`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'platform-freebsd');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fillRule="evenodd" d="M23.7253418,0.403330656 C24.9975688,1.67496208 21.4706794,7.26490597 20.8744345,7.86115088 C20.2781896,8.45650302 18.7637754,7.90875554 17.4918461,6.63682558 C16.2196191,5.36519416 15.6715737,3.85048208 16.2678187,3.25423717 C16.8640636,2.65769514 22.4534125,-0.868896418 23.7253418,0.403330656 L23.7253418,0.403330656 Z M5.88500669,1.74874919 C3.94274831,0.64670772 1.17931401,-0.579104582 0.300120884,0.300088547 C-0.590973233,1.19058772 0.680063246,4.01650237 1.79341076,5.96233113 C2.78417662,4.23935071 4.19415887,2.78890453 5.88500669,1.74874919 L5.88500669,1.74874919 Z M21.785166,7.42259564 C21.9639794,8.02925383 21.9315489,8.53058725 21.6417578,8.81978414 C20.9639901,9.49755113 19.1338994,8.77634479 17.4844083,7.20599597 C17.3689674,7.10275387 17.2550141,6.99564356 17.1428465,6.88317878 C16.5466016,6.28633892 16.0821617,5.65081997 15.785527,5.06617893 C15.2077288,4.02989107 15.0631307,3.11410221 15.4999004,2.67762963 C15.7379223,2.43960776 16.1187574,2.37474692 16.583198,2.45864948 C16.8863778,2.2673395 17.2437081,2.05371455 17.6358493,1.83503223 C16.0414007,1.00344305 14.2288637,0.533647279 12.305647,0.533647279 C5.92785039,0.533647279 0.757122899,5.70348271 0.757122899,12.0821714 C0.757122899,18.4596702 5.92785039,23.6301005 12.305647,23.6301005 C18.683741,23.6301005 23.8544685,18.4596702 23.8544685,12.0821714 C23.8544685,10.0223894 23.313861,8.09084213 22.3692121,6.41635843 C22.1648105,6.78856511 21.9663598,7.12982838 21.785166,7.42259564 L21.785166,7.42259564 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'PlatformFreebsd';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
frontend/containers/form/CaptchaForm.js
|
datoszs/czech-lawyers
|
import React from 'react';
import PropTypes from 'prop-types';
import {Form} from 'react-bootstrap';
import {reduxForm, Field} from 'redux-form/immutable';
import Captcha from 'react-google-recaptcha';
import {wrapEventStop} from '../../util';
import {siteKey} from '../../serverAPI';
const CaptchaComponent = ({input, handleSubmit, captchaRef}) => (
<Captcha
onChange={(value) => {
input.onChange(value);
handleSubmit();
}}
sitekey={siteKey}
size="invisible"
ref={captchaRef}
/>
);
CaptchaComponent.propTypes = {
input: PropTypes.shape({
onChange: PropTypes.func.isRequired,
}).isRequired,
handleSubmit: PropTypes.func.isRequired,
captchaRef: PropTypes.func.isRequired,
};
const CaptchaFormComponent = ({inline, children, handleSubmit}) => {
let captcha;
return (
<Form inline={inline} onSubmit={wrapEventStop(() => captcha.execute())}>
{children}
<Field
name="captcha_token"
component={CaptchaComponent}
handleSubmit={handleSubmit}
captchaRef={(component) => {
captcha = component;
}}
/>
</Form>
);
};
CaptchaFormComponent.propTypes = {
inline: PropTypes.bool,
children: PropTypes.node.isRequired,
handleSubmit: PropTypes.func.isRequired,
};
CaptchaFormComponent.defaultProps = {
inline: false,
};
const onSubmit = (values, dispatch, {action}) => dispatch(action(values));
const CaptchaForm = (reduxForm({onSubmit})(CaptchaFormComponent));
CaptchaForm.propTypes = {
form: PropTypes.string.isRequired,
action: PropTypes.func.isRequired,
};
export default CaptchaForm;
|
packages/bonde-admin/src/pages/admin/container.js
|
ourcities/rebu-client
|
import React from 'react'
import { Switch } from 'react-router-dom'
import { graphql } from 'react-apollo'
import FetchCurrentUser from '@/account/queries/current-user'
import { connect } from 'react-redux'
import { load } from '@/account/redux/action-creators'
import { Loading } from '@/components/await'
// Routes
import BetaBotPage from './bot'
import CommunityListPage from './communities/list'
import CommunityCreatePage from './communities/create'
import SidebarContainer from './sidebar'
import PrivateRoute from './private-route'
class Logged extends React.Component {
componentDidMount () {
if (this.props.user) {
this.props.load(this.props.user)
}
}
componentWillReceiveProps (nextProps) {
if (!this.props.user && nextProps.user) {
this.props.load(nextProps.user)
}
}
render () {
return this.props.loading ? <Loading /> : (
<Switch>
<PrivateRoute
exact
path='/bot'
component={BetaBotPage}
/>
<PrivateRoute
exact
path='/communities'
component={CommunityListPage}
/>
<PrivateRoute
exact
path='/communities/new'
component={CommunityCreatePage}
/>
<PrivateRoute
path='/'
component={SidebarContainer}
/>
</Switch>
)
}
}
const config = {
options: { fetchPolicy: 'network-only' },
props: ({ ownProps, data: { loading, currentUser } }) => ({
loading,
user: currentUser
})
}
export default graphql(FetchCurrentUser, config)(
connect(undefined, { load })(Logged)
)
|
app/javascript/mastodon/features/public_timeline/index.js
|
rekif/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import { expandPublicTimeline } from '../../actions/timelines';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import ColumnSettingsContainer from './containers/column_settings_container';
import { connectPublicStream } from '../../actions/streaming';
const messages = defineMessages({
title: { id: 'column.public', defaultMessage: 'Federated timeline' },
});
const mapStateToProps = (state, { onlyMedia, columnId }) => {
const uuid = columnId;
const columns = state.getIn(['settings', 'columns']);
const index = columns.findIndex(c => c.get('uuid') === uuid);
return {
hasUnread: state.getIn(['timelines', `public${onlyMedia ? ':media' : ''}`, 'unread']) > 0,
onlyMedia: (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyMedia']) : state.getIn(['settings', 'public', 'other', 'onlyMedia']),
};
};
export default @connect(mapStateToProps)
@injectIntl
class PublicTimeline extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static defaultProps = {
onlyMedia: false,
};
static propTypes = {
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
intl: PropTypes.object.isRequired,
columnId: PropTypes.string,
multiColumn: PropTypes.bool,
hasUnread: PropTypes.bool,
onlyMedia: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch, onlyMedia } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('PUBLIC', { other: { onlyMedia } }));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
componentDidMount () {
const { dispatch, onlyMedia } = this.props;
dispatch(expandPublicTimeline({ onlyMedia }));
this.disconnect = dispatch(connectPublicStream({ onlyMedia }));
}
componentDidUpdate (prevProps) {
if (prevProps.onlyMedia !== this.props.onlyMedia) {
const { dispatch, onlyMedia } = this.props;
this.disconnect();
dispatch(expandPublicTimeline({ onlyMedia }));
this.disconnect = dispatch(connectPublicStream({ onlyMedia }));
}
}
componentWillUnmount () {
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
setRef = c => {
this.column = c;
}
handleLoadMore = maxId => {
const { dispatch, onlyMedia } = this.props;
dispatch(expandPublicTimeline({ maxId, onlyMedia }));
}
handleSettingChanged = (key, checked) => {
const { columnId } = this.props;
if (!columnId && key[0] === 'other' && key[1] === 'onlyMedia') {
this.context.router.history.replace(`/timelines/public${checked ? '/media' : ''}`);
}
}
render () {
const { intl, shouldUpdateScroll, columnId, hasUnread, multiColumn, onlyMedia } = this.props;
const pinned = !!columnId;
return (
<Column ref={this.setRef} label={intl.formatMessage(messages.title)}>
<ColumnHeader
icon='globe'
active={hasUnread}
title={intl.formatMessage(messages.title)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
>
<ColumnSettingsContainer onChange={this.handleSettingChanged} columnId={columnId} />
</ColumnHeader>
<StatusListContainer
timelineId={`public${onlyMedia ? ':media' : ''}`}
onLoadMore={this.handleLoadMore}
trackScroll={!pinned}
scrollKey={`public_timeline-${columnId}`}
emptyMessage={<FormattedMessage id='empty_column.public' defaultMessage='There is nothing here! Write something publicly, or manually follow users from other instances to fill it up' />}
shouldUpdateScroll={shouldUpdateScroll}
/>
</Column>
);
}
}
|
src/components/Button/ButtonAnchor.js
|
GetAmbassador/react-ions
|
import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router'
import style from './style.scss'
import classNames from 'classnames/bind'
const ButtonAnchor = props => {
const cx = classNames.bind(style)
const collapseClass = props.collapse ? 'collapse' : null
const btnAnchorClasses = cx(style.btn, props.optClass, props.className, props.size, collapseClass)
let buttonAnchor
const handleClick = e => {
if (props.disabled) {
e.preventDefault()
}
}
if (props.internal) {
buttonAnchor = <Link
to={props.path}
className={btnAnchorClasses}
size={props.size}
disabled={props.disabled}
onClick={handleClick}
style={props.style}>
{props.children}
</Link>
} else {
buttonAnchor = <a href={props.path} className={btnAnchorClasses} target={props.target} disabled={props.disabled} onClick={handleClick}>{props.children}</a>
}
return buttonAnchor
}
ButtonAnchor.propTypes = {
/**
* A string to allow for inline styles
*/
style: PropTypes.string,
/**
* A class name to be used for local styles or integrations (required to support styled-components)
**/
className: PropTypes.string,
/**
* Optional styles to add to the button.
*/
optClass: PropTypes.string,
/**
* The size of button.
*/
size: PropTypes.string,
/**
* Whether the button is disabled.
*/
disabled: PropTypes.bool,
/**
* A path to pass to the anchor tag.
*/
path: PropTypes.string,
/**
* Whether the link it to an internal page, or external (default)
*/
internal: PropTypes.bool,
/**
* Whether to display only an icon on small screens
*/
collapse: PropTypes.bool
}
export default ButtonAnchor
|
src/Card/CardSubtitle.js
|
kradio3/react-mdc-web
|
import PropTypes from 'prop-types';
import React from 'react';
import classnames from 'classnames';
const propTypes = {
className: PropTypes.string,
children: PropTypes.node,
};
const CardSubtitle = ({ className, children }) => (
<h2
className={classnames('mdc-card__subtitle', className)}
>
{children}
</h2>
);
CardSubtitle.propTypes = propTypes;
export default CardSubtitle;
|
app/containers/LoginCallback/index.js
|
belongapp/belong
|
import React from 'react';
import { connect } from 'react-redux';
import { loginCallbackRequest } from './actions';
export class LoginCallback extends React.Component { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
dispatchLoginCallbackRequest: React.PropTypes.func.isRequired,
};
componentWillMount() {
this.props.dispatchLoginCallbackRequest();
}
render() {
return <span>Welcome back, one moment please...</span>;
}
}
export function mapDispatchToProps(dispatch) {
return {
dispatchLoginCallbackRequest() {
dispatch(loginCallbackRequest());
},
};
}
export default connect(null, mapDispatchToProps)(LoginCallback);
|
test/helpers.js
|
zerkms/react-bootstrap
|
import React from 'react';
import { cloneElement } from 'react';
export function shouldWarn(about) {
console.warn.called.should.be.true;
console.warn.calledWithMatch(about).should.be.true;
console.warn.reset();
}
/**
* Helper for rendering and updating props for plain class Components
* since `setProps` is deprecated.
* @param {ReactElement} element Root element to render
* @param {HTMLElement?} mountPoint Optional mount node, when empty it uses an unattached div like `renderIntoDocument()`
* @return {ComponentInstance} The instance, with a new method `renderWithProps` which will return a new instance with updated props
*/
export function render(element, mountPoint){
let mount = mountPoint || document.createElement('div');
let instance = React.render(element, mount);
if (!instance.renderWithProps) {
instance.renderWithProps = function(newProps) {
return render(
cloneElement(element, newProps), mount);
};
}
return instance;
}
|
static/src/components/Layout.js
|
Termnator/mikebot
|
// @flow
import React from 'react';
import ReactDOM from 'react-dom';
import AirhornStatsStore from '../stores/AirhornStatsStore';
import Cloud from './Cloud';
import IslandPond from './islands/IslandPond';
import IslandTree from './islands/IslandTree';
import IslandTrees from './islands/IslandTrees';
import IslandTent from './islands/IslandTent';
import IslandDoubleTree from './islands/IslandDoubleTree';
import IslandForest from './islands/IslandForest';
import IslandLog from './islands/IslandLog';
import IslandShrooms from './islands/IslandShrooms';
import IslandSmall from './islands/IslandSmall';
import Content from './Content';
import Footer from './Footer';
import StatsPanel from './StatsPanel';
import Parallax from '../libs/parallax';
import ReactTooltip from 'react-tooltip';
import Browser from 'detect-browser';
import Constants from '../Constants';
import '../style/style.styl';
const REF_PARALLAX = 'PARALLAX_REF';
const REF_SMALL_ISLANDS = "SMALL_ISLANDS_REF";
const REF_LARGE_ISLANDS = "LARGE_ISLANDS_REF";
const REF_FOOTER = "FOOTER_REF";
type State = {
count: number,
uniqueUsers: number,
uniqueGuilds: number,
uniqueChannels: number,
secretCount: number,
showStats: boolean,
statsHasBeenShown: boolean,
changeCount: boolean,
pausedSmallIslands: Array<boolean>,
pausedLargeIslands: Array<boolean>,
footerHeight: number
};
let changeCountTimeout: number;
function isVisible(el, num): boolean {
const rect = el.getBoundingClientRect();
return ((rect.top >= -20 && rect.top <= window.innerHeight) ||
(rect.bottom >= -20 && rect.bottom <= window.innerHeight)) &&
((rect.left >= -20 && rect.left <= window.innerWidth) ||
(rect.right >= -20 && rect.right <= window.innerWidth));
}
const Layout = React.createClass({
getInitialState(): State {
const pausedLargeIslands = [false];
const pausedSmallIslands = [];
for (let i = 0; i < Constants.SMALL_ISLAND_COUNT; i++) {
pausedSmallIslands.push(false);
}
for (let i = 0; i < Constants.LARGE_ISLAND_COUNT; i++) {
pausedLargeIslands.push(false);
}
return {
count: 0,
uniqueUsers: 0,
uniqueGuilds: 0,
uniqueChannels: 0,
secretCount: 0,
showStats: false,
statsHasBeenShown: false,
changeCount: false,
pausedLargeIslands,
pausedSmallIslands,
footerHeight: 80
};
},
componentWillMount() {
AirhornStatsStore.on('change', this.updateStats);
window.addEventListener('resize', this.resized);
},
componentDidMount() {
new Parallax(this.refs[REF_PARALLAX]);
setTimeout(() => this.resized(), 100);
},
resized() {
const pausedSmallIslands = [];
for (let i = 0; i < Constants.SMALL_ISLAND_COUNT; i++) {
const visible = isVisible(this.refs[REF_SMALL_ISLANDS].children[i], i);
pausedSmallIslands.push(!visible);
}
const pausedLargeIslands = [];
for (let i = 0; i < Constants.LARGE_ISLAND_COUNT; i++) {
const visible = isVisible(this.refs[REF_LARGE_ISLANDS].children[i], i);
pausedLargeIslands.push(!visible);
}
const footerHeight = ReactDOM.findDOMNode(this.refs[REF_FOOTER]).getBoundingClientRect().height;
this.setState({
pausedSmallIslands,
pausedLargeIslands,
footerHeight
});
},
updateStats() {
this.setState({
count: AirhornStatsStore.getCount(),
uniqueUsers: AirhornStatsStore.getUniqueUsers(),
uniqueGuilds: AirhornStatsStore.getUniqueGuilds(),
uniqueChannels: AirhornStatsStore.getUniqueChannels(),
secretCount: AirhornStatsStore.getSecretCount(),
showStats: AirhornStatsStore.shouldShowStatsPanel(),
statsHasBeenShown: this.state.statsHasBeenShown || AirhornStatsStore.shouldShowStatsPanel(),
changeCount: this.state.count != AirhornStatsStore.getCount()
});
clearTimeout(changeCountTimeout);
changeCountTimeout = setTimeout(
this.finishChangeCountAnimation,
Constants.Animation.COUNT_CHANGE_TIME);
},
finishChangeCountAnimation() {
this.setState({
changeCount: false
});
},
render() {
const smallIslands = [];
for (let i = 0; i < Constants.SMALL_ISLAND_COUNT; i++) {
const type = i % Constants.UNIQUE_SMALL_ISLAND_COUNT;
smallIslands.push(<IslandSmall number={i} type={type} key={i} paused={this.state.pausedSmallIslands[i]} />);
}
const clouds = [];
for (let i = 0; i < Constants.CLOUD_COUNT; i++) {
const type = i % Constants.UNIQUE_CLOUD_COUNT;
clouds.push(<Cloud number={i} type={type} key={i} />);
}
let toolTip;
if (!this.state.showStats) {
toolTip = <ReactTooltip effect="solid" type="light" class="tool-tip" offset={{top: -8}} />;
}
return (
<div className={`container ${Browser.name}`}>
<Content />
<div ref={REF_LARGE_ISLANDS}>
<IslandPond paused={this.state.pausedLargeIslands[0]} />
<IslandTree paused={this.state.pausedLargeIslands[1]} />
<IslandTrees paused={this.state.pausedLargeIslands[2]} />
<IslandTent paused={this.state.pausedLargeIslands[3]} />
<IslandDoubleTree paused={this.state.pausedLargeIslands[4]} />
<IslandForest paused={this.state.pausedLargeIslands[5]} />
<IslandForest paused={this.state.pausedLargeIslands[6]} number="1" />
<IslandLog paused={this.state.pausedLargeIslands[7]} />
<IslandShrooms paused={this.state.pausedLargeIslands[8]} />
<IslandShrooms paused={this.state.pausedLargeIslands[9]} number="1" />
</div>
<div ref={REF_SMALL_ISLANDS}>{smallIslands}</div>
<div id="parallax" ref={REF_PARALLAX}>
{clouds}
</div>
<StatsPanel
show={this.state.showStats}
count={this.state.count}
uniqueUsers={this.state.uniqueUsers}
uniqueGuilds={this.state.uniqueGuilds}
uniqueChannels={this.state.uniqueChannels}
secretCount={this.state.secretCount}
hasBeenShown={this.state.statsHasBeenShown}
bottom={this.state.footerHeight} />
<Footer
ref={REF_FOOTER}
count={this.state.count}
changeCount={this.state.changeCount}
showStatsPanel={this.state.showStats}
statsHasBeenShown={this.state.statsHasBeenShown} />
{toolTip}
</div>
);
}
});
export default Layout;
|
app/javascript/mastodon/features/compose/components/upload.js
|
danhunsaker/mastodon
|
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Motion from '../../ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { FormattedMessage } from 'react-intl';
import classNames from 'classnames';
import Icon from 'mastodon/components/icon';
export default class Upload extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
media: ImmutablePropTypes.map.isRequired,
onUndo: PropTypes.func.isRequired,
onOpenFocalPoint: PropTypes.func.isRequired,
};
handleUndoClick = e => {
e.stopPropagation();
this.props.onUndo(this.props.media.get('id'));
}
handleFocalPointClick = e => {
e.stopPropagation();
this.props.onOpenFocalPoint(this.props.media.get('id'));
}
render () {
const { media } = this.props;
const focusX = media.getIn(['meta', 'focus', 'x']);
const focusY = media.getIn(['meta', 'focus', 'y']);
const x = ((focusX / 2) + .5) * 100;
const y = ((focusY / -2) + .5) * 100;
return (
<div className='compose-form__upload' tabIndex='0' role='button'>
<Motion defaultStyle={{ scale: 0.8 }} style={{ scale: spring(1, { stiffness: 180, damping: 12 }) }}>
{({ scale }) => (
<div className='compose-form__upload-thumbnail' style={{ transform: `scale(${scale})`, backgroundImage: `url(${media.get('preview_url')})`, backgroundPosition: `${x}% ${y}%` }}>
<div className={classNames('compose-form__upload__actions', { active: true })}>
<button className='icon-button' onClick={this.handleUndoClick}><Icon id='times' /> <FormattedMessage id='upload_form.undo' defaultMessage='Delete' /></button>
<button className='icon-button' onClick={this.handleFocalPointClick}><Icon id='pencil' /> <FormattedMessage id='upload_form.edit' defaultMessage='Edit' /></button>
</div>
</div>
)}
</Motion>
</div>
);
}
}
|
react/features/notifications/components/native/Notification.js
|
bgrozev/jitsi-meet
|
// @flow
import React from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { translate } from '../../../base/i18n';
import { Icon, IconClose } from '../../../base/icons';
import AbstractNotification, {
type Props
} from '../AbstractNotification';
import styles from './styles';
/**
* Implements a React {@link Component} to display a notification.
*
* @extends Component
*/
class Notification extends AbstractNotification<Props> {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const {
isDismissAllowed
} = this.props;
return (
<View
pointerEvents = 'box-none'
style = { styles.notification }>
<View style = { styles.contentColumn }>
<View
pointerEvents = 'box-none'
style = { styles.notificationContent }>
{
this._renderContent()
}
</View>
</View>
{
isDismissAllowed
&& <TouchableOpacity onPress = { this._onDismissed }>
<Icon
src = { IconClose }
style = { styles.dismissIcon } />
</TouchableOpacity>
}
</View>
);
}
/**
* Renders the notification's content. If the title or title key is present
* it will be just the title. Otherwise it will fallback to description.
*
* @returns {Array<ReactElement>}
* @private
*/
_renderContent() {
const { t, title, titleArguments, titleKey } = this.props;
const titleText = title || (titleKey && t(titleKey, titleArguments));
const description = this._getDescription();
if (description && description.length) {
return description.map((line, index) => (
<Text
key = { index }
numberOfLines = { 1 }
style = { styles.contentText }>
{ line }
</Text>
));
}
return (
<Text
numberOfLines = { 1 }
style = { styles.contentText } >
{ titleText }
</Text>
);
}
_getDescription: () => Array<string>;
_onDismissed: () => void;
}
export default translate(Notification);
|
src/svg-icons/hardware/security.js
|
owencm/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareSecurity = (props) => (
<SvgIcon {...props}>
<path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4zm0 10.99h7c-.53 4.12-3.28 7.79-7 8.94V12H5V6.3l7-3.11v8.8z"/>
</SvgIcon>
);
HardwareSecurity = pure(HardwareSecurity);
HardwareSecurity.displayName = 'HardwareSecurity';
HardwareSecurity.muiName = 'SvgIcon';
export default HardwareSecurity;
|
src/js/components/ui/Textarea/Textarea.js
|
nekuno/client
|
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import styles from './Textarea.scss';
export default class Textarea extends Component {
static propTypes = {
placeholder : PropTypes.string,
defaultValue: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
onChange : PropTypes.func
};
constructor(props) {
super(props);
this.state = {
empty: !props.defaultValue,
focused: false
};
this.onChange = this.onChange.bind(this);
this.getValue = this.getValue.bind(this);
}
setValue(value) {
if (this.refs.textarea) {
this.refs.textarea.value = value;
}
}
getValue() {
return this.refs.textarea ? this.refs.textarea.value : null;
}
onChange() {
if (this.props.onChange) {
this.props.onChange(this.getValue());
}
this.setState({empty: !this.getValue()});
}
render() {
const {placeholder, defaultValue} = this.props;
const {empty} = this.state;
return (
<div className={styles.inputWrapper}>
<div className={styles.input}>
<textarea ref="textarea" placeholder={placeholder} value={this.state.value} onChange={this.onChange} defaultValue={defaultValue} />
</div>
</div>
);
}
}
|
src/containers/NotFoundPage/__tests__/index.js
|
skyuplam/technical-test01
|
import { shallow } from 'enzyme';
import React from 'react';
import NotFound from '../index';
describe('<NotFound />', () => {
it('should render the Page Not Found text', () => {
const renderedComponent = shallow(
<NotFound />
);
expect(renderedComponent.contains(
<h1>
Page not found.
</h1>)).toEqual(true);
});
});
|
app/javascript/mastodon/features/compose/components/reply_indicator.js
|
TheInventrix/mastodon
|
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Avatar from '../../../components/avatar';
import IconButton from '../../../components/icon_button';
import DisplayName from '../../../components/display_name';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { isRtl } from '../../../rtl';
const messages = defineMessages({
cancel: { id: 'reply_indicator.cancel', defaultMessage: 'Cancel' },
});
export default @injectIntl
class ReplyIndicator extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map,
onCancel: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleClick = () => {
this.props.onCancel();
}
handleAccountClick = (e) => {
if (e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(`/accounts/${this.props.status.getIn(['account', 'id'])}`);
}
}
render () {
const { status, intl } = this.props;
if (!status) {
return null;
}
const content = { __html: status.get('contentHtml') };
const style = {
direction: isRtl(status.get('search_index')) ? 'rtl' : 'ltr',
};
return (
<div className='reply-indicator'>
<div className='reply-indicator__header'>
<div className='reply-indicator__cancel'><IconButton title={intl.formatMessage(messages.cancel)} icon='times' onClick={this.handleClick} inverted /></div>
<a href={status.getIn(['account', 'url'])} onClick={this.handleAccountClick} className='reply-indicator__display-name'>
<div className='reply-indicator__display-avatar'><Avatar account={status.get('account')} size={24} /></div>
<DisplayName account={status.get('account')} />
</a>
</div>
<div className='reply-indicator__content' style={style} dangerouslySetInnerHTML={content} />
</div>
);
}
}
|
src/svg-icons/notification/time-to-leave.js
|
barakmitz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationTimeToLeave = (props) => (
<SvgIcon {...props}>
<path d="M18.92 5.01C18.72 4.42 18.16 4 17.5 4h-11c-.66 0-1.21.42-1.42 1.01L3 11v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 15c-.83 0-1.5-.67-1.5-1.5S5.67 12 6.5 12s1.5.67 1.5 1.5S7.33 15 6.5 15zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 10l1.5-4.5h11L19 10H5z"/>
</SvgIcon>
);
NotificationTimeToLeave = pure(NotificationTimeToLeave);
NotificationTimeToLeave.displayName = 'NotificationTimeToLeave';
NotificationTimeToLeave.muiName = 'SvgIcon';
export default NotificationTimeToLeave;
|
hops/src/App.js
|
Hops-401/hops-native
|
import React, { Component } from 'react';
import { StyleSheet, Text, View, AppRegistry } from 'react-native';
import { NativeRouter, Route, Link, Switch } from 'react-router-native';
import Home from './components/home';
import LoginContainer from './containers/LoginContainer';
import SignUpContainer from './containers/SignUpContainer';
function requireAuth(nextState, replace) {
if (!this.props.isLoggedIn) {
replace({
pathname: '/login'
})
}
}
export default class app extends Component {
render() {
return (
<NativeRouter>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/login" component={LoginContainer} />
<Route exact path="/signup" component={SignUpContainer} />
</Switch>
</NativeRouter>
);
};
};
AppRegistry.registerComponent('app', () => app);
|
docs/app/Examples/modules/Accordion/Variations/AccordionExampleInverted.js
|
clemensw/stardust
|
import _ from 'lodash'
import faker from 'faker'
import React from 'react'
import { Accordion, Segment } from 'semantic-ui-react'
const panels = _.times(3, () => ({
title: faker.lorem.sentence(),
content: faker.lorem.paragraphs(),
}))
const AccordionExampleInverted = () => (
<Segment inverted>
<Accordion panels={panels} inverted />
</Segment>
)
export default AccordionExampleInverted
|
miniact3/client/index.js
|
eliorivero/miniact
|
import React from 'react';
import ReactDOM from 'react-dom';
class DaleReact extends React.Component {
render() {
return <div>{ this.props.app } listo en React!</div>;
}
}
ReactDOM.render(<DaleReact app="Miniact" />, document.getElementById( 'miniact' ) );
|
modules/pages/client/components/FaqTribes.component.js
|
Trustroots/trustroots
|
import React from 'react';
import Faq from '@/modules/pages/client/components/Faq.component.js';
import { Trans, useTranslation } from 'react-i18next';
export default function FaqTribes() {
const { t } = useTranslation('pages');
return (
<Faq category="circles">
<div className="faq-question" id="what-are-circles">
<h3>{t('What are circles?')}</h3>
{t(
'Trustroots circles (previously known as "tribes") are a way for you to immediately find the people you will easily connect with.',
)}
<br />
<br />
<Trans t={t} ns="pages">
You can start now by joining <a href="/circles">circles</a> that you
identify yourself with.
</Trans>
<br />
<br />
{t('When searching for hosts, you can filter members by circles.')}
<br />
<br />
{t(
'Your circles will also show up in your profile, telling others more about you.',
)}
<br />
<br />
{t(
"We'll aim to add ways to the site that will fill your trips and your life with adventure! Imagine walking around in a city you're visiting for the first time and suddently you start receiving invitations from people to stay with them or go to awesome or inspiring events, or just to a dumpster dive dinner. That's the adventure Trustroots wants to enable. And circles is a step towards this.",
)}
<br />
<br />
<Trans t={t} ns="pages">
See also{' '}
<a href="https://ideas.trustroots.org/2016/05/09/introducing-trustroots-tribes/">
the blog post
</a>{' '}
introducing circles.
</Trans>
</div>
<div className="faq-question" id="no-suitable-circles">
<h3>{t("I don't find a circle that suits me")}</h3>
<Trans t={t} ns="pages">
<a href="/support">Send us</a> new circle ideas! In the future you
will be able to create new circles by yourself.
</Trans>
</div>
<div className="faq-question" id="tribes-rename-to-circles">
<h3>{t('Why did you rename "tribes" to "circles"?')}</h3>
{t(
'We found the term be problematic for having connotations of colonialism and wanted to switch to a more inclusive term in August 2020.',
)}
<br />
<br />
<a href="https://ideas.trustroots.org/2020/08/04/introducing-circles/">
{t('Read more')}
</a>
</div>
</Faq>
);
}
FaqTribes.propTypes = {};
|
app/jsx/context_cards/SubmissionProgressBars.js
|
venturehive/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_tray'
import classnames from 'classnames'
import Heading from 'instructure-ui/lib/components/Heading'
import Progress from 'instructure-ui/lib/components/Progress'
import Tooltip from 'instructure-ui/lib/components/Tooltip'
import Typography from 'instructure-ui/lib/components/Typography'
import Link from 'instructure-ui/lib/components/Link'
class SubmissionProgressBars extends React.Component {
static propTypes = {
submissions: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
score: PropTypes.number,
user: PropTypes.shape({
_id: PropTypes.string.isRequired
}).isRequired,
assignment: PropTypes.shape({
html_url: PropTypes.string.isRequired,
points_possible: PropTypes.number,
})
}).isRequired
).isRequired,
}
static displayGrade (submission) {
const {score, grade, excused} = submission
const pointsPossible = submission.assignment.points_possible
let display
if (excused) {
display = 'EX'
} else if (grade.match(/%/)) {
// Grade is a percentage, just show it
display = grade
} else if (grade.match(/complete/)) {
// Grade is complete/incomplete, show icon
display = SubmissionProgressBars.renderIcon(grade)
} else {
// Default to show score out of points possible
display = `${score}/${pointsPossible}`
}
return display
}
static displayScreenreaderGrade (submission) {
const {score, grade, excused} = submission
const pointsPossible = submission.assignment.points_possible
let display
if (excused) {
display = I18n.t('excused')
} else if (grade.match(/%/) || grade.match(/complete/)) {
// Grade is a percentage or in/complete, just show it
display = grade
} else {
// Default to show score out of points possible
display = `${score}/${pointsPossible}`
}
return display
}
static renderIcon (grade) {
const iconClass = classnames({
'icon-check': grade === 'complete',
'icon-x': grade === 'incomplete'
})
return (
<div>
<span className='screenreader-only'>
{I18n.t("%{grade}", {grade: grade})}
</span>
<i className={iconClass}></i>
</div>
)
}
render () {
const {submissions} = this.props
if (submissions.length > 0) {
return (
<section
className="StudentContextTray__Section StudentContextTray-Progress">
<Heading level="h4" as="h3" border="bottom">
{I18n.t("Last %{length} Graded Items", {length: submissions.length})}
</Heading>
{submissions.map((submission) => {
return (
<div key={submission.id} className="StudentContextTray-Progress__Bar">
<Tooltip
tip={submission.assignment.name}
as={Link}
href={`${submission.assignment.html_url}/submissions/${submission.user_id}`}
placement="top"
>
<Progress
size="small"
successColor={false}
label={I18n.t('Grade')}
valueMax={submission.assignment.points_possible}
valueNow={submission.score || 0}
formatValueText={() => SubmissionProgressBars.displayScreenreaderGrade(submission)}
formatDisplayedValue={() => (
<Typography size="x-small" color="secondary">
{SubmissionProgressBars.displayGrade(submission)}
</Typography>
)}
/>
</Tooltip>
</div>
)
})}
</section>
)
} else { return null }
}
}
export default SubmissionProgressBars
|
src/svg-icons/editor/monetization-on.js
|
w01fgang/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorMonetizationOn = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1.41 16.09V20h-2.67v-1.93c-1.71-.36-3.16-1.46-3.27-3.4h1.96c.1 1.05.82 1.87 2.65 1.87 1.96 0 2.4-.98 2.4-1.59 0-.83-.44-1.61-2.67-2.14-2.48-.6-4.18-1.62-4.18-3.67 0-1.72 1.39-2.84 3.11-3.21V4h2.67v1.95c1.86.45 2.79 1.86 2.85 3.39H14.3c-.05-1.11-.64-1.87-2.22-1.87-1.5 0-2.4.68-2.4 1.64 0 .84.65 1.39 2.67 1.91s4.18 1.39 4.18 3.91c-.01 1.83-1.38 2.83-3.12 3.16z"/>
</SvgIcon>
);
EditorMonetizationOn = pure(EditorMonetizationOn);
EditorMonetizationOn.displayName = 'EditorMonetizationOn';
EditorMonetizationOn.muiName = 'SvgIcon';
export default EditorMonetizationOn;
|
components/BookDetailApp/BookDetailApp.react.js
|
react-douban/douban-book-web
|
import React from 'react'
import { render } from 'react-dom'
import request from 'request'
import BookDetail from './BookDetail.react'
import Config from '../Config.react'
const BookDetailApp = React.createClass({
getInitialState() {
return {
book: {},
loading: true
}
},
componentDidMount() {
const bookId = this.props.bookId;
this.fetchBookInfo(bookId);
},
fetchBookInfo(bookId, callback) {
request.get(Config.domain + Config.apiContext + '/search/' + bookId, (err, response, body) => {
if (response.statusCode != 200) {
this.setState({message: body});
if (callback && typeof callback === 'function') {
callback();
}
return;
}
const data = JSON.parse(body);
this.setState({book: data, loading: false});
});
},
render() {
return (
<BookDetail book={this.state.book} loading={this.state.loading} />
);
}
});
export default BookDetailApp;
|
src/containers/Transition/Transition.js
|
dongxiaofen/react-redux-motion
|
import React, { Component } from 'react';
import { TransitionDemo } from 'components';
export default class Transition extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div style={{width: '500px', margin: '0 auto'}}>
<TransitionDemo />
</div>
);
}
}
|
src/components/lists/AddressOutputList.js
|
openvcash/vcash-electron
|
import React from 'react'
import List from 'react-list'
import { translate } from 'react-i18next'
import { inject, observer } from 'mobx-react'
/** Component */
import AddressOutputListItem from './AddressOutputListItem.js'
@translate(['common'])
@inject('gui', 'send')
@observer
class AddressOutputList extends React.Component {
constructor(props) {
super(props)
this.t = props.t
this.gui = props.gui
this.send = props.send
}
/**
* Mark or unmark the output for spending.
* @function setOutput
* @param {object} e - Checkbox element event.
*/
setOutput = e => {
this.send.setOutput(e.target.id)
}
render() {
return (
<div>
<div className="flex-sb list-header">
<p>{this.t('txId')}</p>
<p>{this.t('amount')} (XVC)</p>
</div>
<div
className="list-plain"
style={{ maxHeight: this.gui.window.height - 502 }}
>
<List
length={this.send.addrOutputs.length}
itemRenderer={(index, key) => (
<AddressOutputListItem
index={index}
key={key}
gui={this.gui}
send={this.send}
setOutput={this.setOutput}
/>
)}
/>
{this.send.addrOutputs.length === 0 && (
<div className="list-item-plain even">
<div className="flex-center">
<p>{this.t('addrUnused')}</p>
</div>
</div>
)}
</div>
</div>
)
}
}
export default AddressOutputList
|
packages/react-cookie-demo/src/client.js
|
eXon/react-cookie
|
import React from 'react';
import ReactDOM from 'react-dom';
import { CookiesProvider } from 'react-cookie';
import App from './components/App';
const appEl = document.getElementById('main-app');
ReactDOM.render(
<CookiesProvider>
<App />
</CookiesProvider>,
appEl
);
|
imports/client/components/About/AboutBand.js
|
evancorl/skate-scenes
|
import React from 'react';
import Scroll from 'react-scroll';
const ScrollElement = Scroll.Element;
class AboutBand extends React.Component {
shouldComponentUpdate() {
return false;
}
render() {
const languages = ['HTML', 'CSS', 'JavaScript', 'C#', 'SQL', 'PHP'];
const tools = ['Meteor', 'React', 'Sass', 'ASP.NET', 'MySQL', 'Mongo'];
return (
<ScrollElement name="about" id="about" className="about-band inner-ver">
<div className="inner-hor">
<div className="col-wide">
<h1 className="about-title">About</h1>
<p className="about-text">
I'm a full-stack web and hybrid app developer based in Houston, TX. I made my first
website at age 13 to post skateboarding photos of my friends, and I've been coding
ever since. My experience includes writing core application logic for the back-end,
building REST APIs, database modeling/migration, front-end development using
JavaScript view libraries, and much more. My mission is to continually hone my
coding skills by learning every day and applying best practices.
</p>
<h2 className="about-subtitle">My favorite languages</h2>
<ul className="language-list about-list">
{languages.map((language, i) => (
<li key={i} className="language-item about-item">
{language}
</li>
))}
</ul>
<h2 className="about-subtitle">My favorite tools</h2>
<ul className="tool-list about-list">
{tools.map((tool, i) => (
<li key={i} className="tool-item about-item">
<img className="tool-img" src={`/images/tools/${tool.toLowerCase()}.png`} />
<div className="tool-name">{tool}</div>
</li>
))}
</ul>
</div>
</div>
</ScrollElement>
);
}
}
export default AboutBand;
|
src/interface/report/PlayerSelection/index.js
|
ronaldpereira/WoWAnalyzer
|
import React from 'react';
import PropTypes from 'prop-types';
import SPECS from 'game/SPECS';
import ROLES from 'game/ROLES';
import PlayerTile from './PlayerTile';
import './PlayerSelection.scss';
const ROLE_SORT_KEY = {
[ROLES.TANK]: 0,
[ROLES.HEALER]: 1,
[ROLES.DPS.MELEE]: 2,
[ROLES.DPS.RANGED]: 2,
};
function sortPlayers(a, b) {
const aSpec = SPECS[a.combatant.specID];
const bSpec = SPECS[b.combatant.specID];
const aRoleSortKey = aSpec ? ROLE_SORT_KEY[aSpec.role] : -1;
const bRoleSortKey = bSpec ? ROLE_SORT_KEY[bSpec.role] : -1;
if (aRoleSortKey !== bRoleSortKey) {
return aRoleSortKey - bRoleSortKey;
}
const aSpecSortKey = aSpec ? aSpec.className : '';
const bSpecSortKey = bSpec ? bSpec.className : '';
if (aSpecSortKey !== bSpecSortKey) {
return aSpecSortKey.localeCompare(bSpecSortKey);
}
return a.name.localeCompare(b.name);
}
const PlayerSelection = ({ players, makeUrl }) => (
<div className="player-selection">
{players.sort(sortPlayers).map(player => (
<PlayerTile key={player.guid} player={player} makeUrl={makeUrl} />
))}
</div>
);
PlayerSelection.propTypes = {
players: PropTypes.arrayOf(PropTypes.object).isRequired,
makeUrl: PropTypes.func.isRequired,
};
export default PlayerSelection;
|
src/client/assets/js/nodes/outputs/export/node.js
|
me-box/databox-sdk
|
import React from 'react';
//import composeNode from 'utils/composeNode';
import Textfield from 'components/form/Textfield';
import Select from 'components/form/Select';
import Cell from 'components/Cell';
import Cells from 'components/Cells';
import { formatSchema } from 'utils/utils';
import {configNode} from 'utils/ReactDecorators';
@configNode()
export default class Node extends React.Component {
render() {
const {node,values={},updateNode} = this.props;
const nameprops = {
id: "name",
value: values.name || "",
onChange: (property, event)=>{
updateNode("name", event.target.value);
},
}
const urlsprops = {
id: "urls",
value: values.urls || "",
onChange: (property, event)=>{
updateNode("urls", event.target.value.trim());
},
}
const nameinput = <div className="centered"><Textfield {...nameprops}/></div>
const urlsinput = <div className="centered"><Textfield {...urlsprops}/></div>
return <div>
<Cells>
<Cell title={"name"} content={nameinput}/>
<Cell title={"urls"} content={urlsinput}/>
</Cells>
</div>
}
}
|
lib/ui/widgets/notification.js
|
SignalK/instrumentpanel
|
import React from 'react';
import { render } from 'react-dom';
import {Bus} from 'baconjs';
import util from 'util'
import BaseWidget from './basewidget';
var notificationLevels = {
"nominal": 0,
"normal": 1,
"alert": 2,
"warn": 3,
"alarm": 4,
"emergency": 5
};
let defaultValue = {
state: 'nominal',
message: 'no alarm',
timestamp: '',
level: 0,
color: notificationLevels["nominal"],
date: null
}
function shortLabel(label) {
return label.replace('notifications.','').replace('.urn:mrn:imo:mmsi:',' ');
}
function Notification(id, options, streamBundle, instrumentPanel) {
BaseWidget.call(this, id, options, streamBundle, instrumentPanel);
this.options.label = shortLabel(this.options.path);
this.notification = {
value: defaultValue
};
this.valueBus = new Bus();
this.valueStream.onValue(value => {
var levelChange = false;
var oldLevel;
if (value === null || typeof value !== 'object'){
value = defaultValue;
}
oldLevel = this.notification.value.level || 0;
this.notification.value = value;
if (!this.notification.value.message) {
this.notification.value.message = '';
}
this.notification.value.level = notificationLevels[this.notification.value.state || 'nominal'];
this.notification.value.color = this.instrumentPanel.notificationColors[this.notification.value.level];
this.notification.value.date = new Date(this.notification.value.timestamp);
this.instrumentPanel.updateNotificationLevel(oldLevel !== this.notification.value.level);
this.valueBus.push(value);
})
this.optionsBundle.optionsStream.onValue(
( ([options,currentvalue]) => {
this.options.label = shortLabel(this.options.label);
})
)
class NotificationComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
message: '',
};
}
componentDidMount() {
if (this.unsubscribe) {
this.unsubscribe();
}
this.setState({message: this.props.notification.value.message});
this.unsubscribe = this.props.valueStream.onValue((value => {
if (value === null) { value = {}; value.message = ''; }
if (this.state.message !== value.message) {
this.setState({message: value.message});
}
}).bind(this));
}
componentWillUnmount() {
if (this.unsubscribe) {
this.unsubscribe();
}
}
render() {
try {
return (
<div style={{marginLeft: '5px'}}>
<p>
[{this.props.options.label + '] ' + this.props.notification.value.state + ': '}
{(typeof this.props.notification.value.timestamp !== 'undefined') ? this.props.notification.value.timestamp + ': ' : ''}
{this.state.message}
</p>
</div>
);
} catch (ex) {console.log(ex)}
return (<div>safety mode</div>)
}
};
this.widget = React.createElement(NotificationComponent,{
key: id,
options: this.options,
instrumentPanel: this.instrumentPanel,
notification: this.notification,
valueStream: this.valueBus.toProperty()
});
}
util.inherits(Notification, BaseWidget);
Notification.prototype.getReactElement = function() {
return this.widget;
}
Notification.prototype.getType = function() {
return "notification";
}
Notification.prototype.getInitialDimensions = function() {
return {h:2, w:100};
}
export default {
constructor: Notification,
type: "notification",
paths: ['notifications.*']
}
|
tests/site2/code/components/projects.js
|
dominikwilkowski/cuttlebelle
|
import PropTypes from 'prop-types';
import React from 'react';
/**
* The Projects component for Listing two projects
*/
const Projects = ({ projects }) => (
<table>
<tbody>
<tr><td>
{ projects[ 0 ] }
</td><td>
{ projects[ 1 ] }
</td></tr>
</tbody>
</table>
);
Projects.propTypes = {
/**
* projects:
* - partial4.md # add whatever partial you want
* - partial5.md
*/
projects: PropTypes.array.isRequired,
};
Projects.defaultProps = {};
export default Projects;
|
app/containers/Page/index.js
|
ZhengRaymond/portfolio
|
/*** PRESENTATIONAL COMPONENT ***/
import React from 'react';
import styled from 'styled-components';
import Header, { SubHeader } from 'components/header';
import { fadein, fadein2 } from 'styles/animations';
import './page.css';
var FAExternalLink = require('react-icons/lib/fa/external-link');
const PanelGroup = styled.div`
display: flex;
flex-wrap: wrap;
align-items: stretch;
justify-content: center;
text-align: center;
position: relative;
width: 75vw;
margin-bottom: 20vh;
animation: ${fadein2} 3.5s;
`
const PanelBox = styled.div`
position: relative;
min-height: 30vh;
padding-top: 9vh;
margin: 2vh;
background-color: rgba(255, 255, 255, 0.9);
box-shadow: 0 5px 15px 5px #eee;
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
transition: all 0.5s, padding-top 0.5s 0.3s;
&.open {
box-shadow: 0 0px 25px 10px #e8f0ff;
padding-top: 20px;
transition: all 0.5s;
}
`
const Details = styled.div`
opacity: 0;
max-height: 0;
padding: 0 20px 20px 20px;
overflow-y: hidden;
text-align: left;
font-size: 2vmin;
transition: opacity 1s ease, max-height 1s ease;
&.open {
max-height: 500px;
opacity: 1;
transition: opacity 1s ease 0.2s, max-height 1s ease;
}
@media (max-device-width: 700px) {
padding: 0;
}
`
const Section = styled.div`
margin: 20px;
`
const Link = styled.a`
position: absolute;
right: 35px;
top: 28px;
font-size: 20px;
cursor: pointer;
transition: all 0.5s;
z-index: 2;
color: black;
&:hover {
color: #aaa;
transition: all 0.3s;
}
@media (max-device-width: 700px) {
font-size: 12px;
right: 22px;
top: 18px;
}
`
function formatSubtitle(subtitles) {
var str = '';
var len = subtitles.length - 1;
subtitles.forEach((subtitle, index) => {
str += subtitle;
if (index !== len) {
str += ' | '
}
})
return str;
}
class Panel extends React.Component {
constructor(props) {
super(props);
this.state = {
active: false
}
this.toggle = this.toggle.bind(this);
}
toggle() {
this.setState({ active: !this.state.active })
}
render() {
return (
<div style={{width: "100%", position: "relative"}}>
<Link target="_blank" href={this.props.data.link}><FAExternalLink/></Link>
<PanelBox className={this.state.active ? 'open' : ''} onClick={this.toggle}>
<Header animation={false} size="medium">{this.props.data.title}</Header>
<SubHeader animation={false} size="small">{formatSubtitle(this.props.data.subtitle)}</SubHeader>
<Details className={this.state.active ? 'open' : ''}>
{
_.map(this.props.data.details, (detail, index) => <Section key={index}>{detail}</Section>)
}
{
<div style={{ textAlign: 'center', fontStyle: 'italic' }}>{"Skills used: " + this.props.data.skills.toString()}</div>
}
</Details>
</PanelBox>
</div>
)
}
}
export default class Page extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
this.state = {
activePanel: 'null'
}
this.toggle = this.toggle.bind(this);
}
toggle(value) {
this.setState({ activePanel: value })
}
render() {
return (
<PanelGroup>
<Header animation={false}>{this.props.title}</Header>
{
_.map(this.props.data, (piece) => {
return <Panel key={piece.title} data={piece} active={piece.title === this.state.activePanel} onClick={this.toggle}/>
})
}
</PanelGroup>
);
}
}
/*** ***/
|
src/App.js
|
sombreroEnPuntas/trust-builder
|
import React, { Component } from 'react';
import reviews from './mocks/reviews';
import Widget from './widget';
import './App.scss';
class App extends Component {
render() {
return (
<div className="App">
<Widget reviews={reviews} totalCards={reviews.length} />
</div>
);
}
}
export default App;
|
until_201803/react/modern/router/src/RouterExample.js
|
shofujimoto/examples
|
import React from 'react'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
const RouterApp = () => (
<Router>
<div style={{margin: 20}}>
<Route exact path='/' component={Home} />
<Route path='/easy' component={EasyCourse} />
<Route path='/normal' component={NormalCourse} />
<Route path='/hard' component={HardCourse} />
</div>
</Router>
)
const Home = () => (
<div>
<h1>React Router Lesson</h1>
<p>コースを選択してください。</p>
<ul>
<li><a href='easy'>Easy</a></li>
<li><a href='normal'>Normal</a></li>
<li><a href='hard'>Hard</a></li>
</ul>
</div>
)
const EasyCourse = () => (
<div>
<h1>Easy Course</h1>
<p><a href="/">Back</a></p>
</div>
)
const NormalCourse = () => (
<div>
<h1>Normal Course</h1>
<p><a href="/">Back</a></p>
</div>
)
const HardCourse = () => (
<div>
<h1>Hard Course</h1>
<p><a href="/">Back</a></p>
</div>
)
export default RouterApp
|
src/jsx-render-engine/strategy/react-router/v4.js
|
yeojz/metalsmith-react-templates
|
import React from 'react';
import {renderToStaticMarkup, renderToString} from 'react-dom/server';
import {StaticRouter} from 'react-router';
import constants from '../../constants';
import Provider from './Provider';
function getRouter(location, context, defaultProps, routes) {
return (
<StaticRouter location={location} context={context}>
<Provider defaultProps={defaultProps}>
{routes}
</Provider>
</StaticRouter>
);
}
function v4reactRouterTemplates(props = {}, options = {}) {
let context = {};
const router = getRouter(
props.location,
context,
props.defaultProps,
options.routes
);
const markup = (options.isStatic)
? renderToStaticMarkup(router)
: renderToString(router);
if (!markup) {
return Promise.reject(constants.INVALID_MARKUP);
}
if (context.url) {
return Promise.reject(constants.REDIRECT_LOCATION);
}
return Promise.resolve(markup);
}
export default v4reactRouterTemplates;
|
client/index.js
|
denistakeda/evolution
|
/**
* Client entry point
*/
import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import App from './App';
import { configureStore } from './store';
import transit from "transit-immutable-js";
// Initialize store
const store = configureStore(transit.fromJSON(window.__INITIAL_STATE__));
const mountApp = document.getElementById('root');
render(
<AppContainer>
<App store={store} />
</AppContainer>,
mountApp
);
// For hot reloading of react components
if (module.hot) {
module.hot.accept('./App', () => {
// If you use Webpack 2 in ES modules mode, you can
// use <App /> here rather than require() a <NextApp />.
const NextApp = require('./App').default; // eslint-disable-line global-require
render(
<AppContainer>
<NextApp store={store} />
</AppContainer>,
mountApp
);
});
}
|
client/src/components/Confirmation.js
|
jeffersonsteelflex69/mytv
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router';
import api from '../lib/api';
class Confirmation extends Component {
componentDidMount(){
if(!Object.keys(this.props.location.query).length > 0)
return
let code = this.props.location.query["code"];
if(typeof code == "undefined")
return
document.getElementById("code").value = code;
}
confirmUser(e){
e.preventDefault();
let userPool = this.props.app.aws.cognito.userPool;
let email = document.getElementById("email").value;
let code = document.getElementById("code").value;
this.props.confirmUser(userPool, email, code);
}
render(){
return (
<div id="login">
<div className="login-container">
<div className="login-brand">
<div className="login-logo">
<img src="/public/img/white-tv.png" alt=""/>
</div>
<div className="login-text">MyTV</div>
</div>
<div className="login-header">Confirm Account</div>
<div id="error"></div>
<div className="login-fields">
<form onSubmit={this.confirmUser.bind(this)}>
<div className="login-field">
<span>Email</span>
<input id="email" type="text" name="email" />
</div>
<div className="login-field">
<span>Code</span>
<input id="code" type="text" name="code" />
</div>
<div className="login-submit">
<input type="submit" onClick={this.confirmUser.bind(this)} value="Confirm Account" />
</div>
</form>
</div>
<div className="login-home-link"><Link to="/">← Go home</Link></div>
</div>
</div>
);
}
}
Confirmation.contextTypes = {
router: PropTypes.object.isRequired
};
export default Confirmation;
|
fields/components/columns/CloudinaryImageSummary.js
|
pr1ntr/keystone
|
import React from 'react';
const IMAGE_SIZE = 18;
const linkStyle = {
marginRight: 8,
};
const boxStyle = {
borderRadius: 3,
display: 'inline-block',
height: IMAGE_SIZE,
overflow: 'hidden',
verticalAlign: 'middle',
width: IMAGE_SIZE,
};
const imageStyle = {
display: 'block',
height: IMAGE_SIZE,
left: '50%',
position: 'relative',
WebkitTransform: 'translateX(-50%)',
MozTransform: 'translateX(-50%)',
msTransform: 'translateX(-50%)',
transform: 'translateX(-50%)',
};
const textStyle = {
color: '#888',
display: 'inline-block',
fontSize: '.8rem',
marginLeft: 8,
verticalAlign: 'middle',
};
var CloudinaryImageSummary = React.createClass({
displayName: 'CloudinaryImageSummary',
propTypes: {
image: React.PropTypes.object.isRequired,
label: React.PropTypes.oneOf(['dimensions', 'publicId']),
},
renderLabel () {
if (!this.props.label) return;
const { label, image } = this.props;
let text;
if (label === 'dimensions') {
text = `${image.width} × ${image.height}`;
} else {
text = `${image.public_id}.${image.format}`;
}
return (
<span style={textStyle}>
{text}
</span>
);
},
renderImageThumbnail () {
if (!this.props.image) return;
const url = this.props.image.url.replace(/image\/upload/, `image/upload/c_thumb,g_face,h_${IMAGE_SIZE},w_${IMAGE_SIZE}`);
return <img src={url} style={imageStyle} className="img-load" />;
},
render () {
return (
<span style={linkStyle}>
<span style={boxStyle}>
{this.renderImageThumbnail()}
</span>
{this.renderLabel()}
</span>
);
},
});
module.exports = CloudinaryImageSummary;
|
webpack/components/WithOrganization/withOrganization.js
|
tstrachota/katello
|
import React, { Component } from 'react';
import { orgId } from '../../services/api';
import SetOrganization from '../SelectOrg/SetOrganization';
import titleWithCaret from '../../helpers/caret';
function withOrganization(WrappedComponent, redirectPath) {
return class CheckOrg extends Component {
componentDidUpdate(prevProps) {
const { location } = this.props;
// TODO: use topbar react component
const orgTitle = location.state && location.state.orgChanged;
const prevOrgTitle = prevProps.location.state && prevProps.location.state.orgChanged;
if (orgTitle !== prevOrgTitle) {
document.getElementById('organization-dropdown').children[0].innerHTML = titleWithCaret(orgTitle);
}
}
render() {
if (!orgId()) {
return <SetOrganization redirectPath={redirectPath} />;
}
return <WrappedComponent {...this.props} />;
}
};
}
export default withOrganization;
|
src/svg-icons/action/gavel.js
|
pradel/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionGavel = (props) => (
<SvgIcon {...props}>
<path d="M1 21h12v2H1zM5.245 8.07l2.83-2.827 14.14 14.142-2.828 2.828zM12.317 1l5.657 5.656-2.83 2.83-5.654-5.66zM3.825 9.485l5.657 5.657-2.828 2.828-5.657-5.657z"/>
</SvgIcon>
);
ActionGavel = pure(ActionGavel);
ActionGavel.displayName = 'ActionGavel';
export default ActionGavel;
|
packages/icons/src/md/hardware/Headset.js
|
suitejs/suitejs
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdHeadset(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M24 5C14.06 5 6 13.06 6 23v14c0 3.31 2.69 6 6 6h6V27h-8v-4c0-7.73 6.27-14 14-14s14 6.27 14 14v4h-8v16h6c3.31 0 6-2.69 6-6V23c0-9.94-8.06-18-18-18z" />
</IconBase>
);
}
export default MdHeadset;
|
example/src/index.js
|
ryo33/redux-pages
|
import React from 'react'
import ReactDOM from 'react-dom'
import {
createStore, combineReducers, applyMiddleware
} from 'redux'
import { Provider } from 'react-redux'
import createLogger from 'redux-logger'
import createHistory from 'history/createHashHistory'
import { createPagesReducer } from 'redux-pages'
import App from './App'
import { pages, rootPage } from './pages'
import { reducers } from './reducers'
import middlewares from './middlewares'
// Create a reducer
const pageReducer = createPagesReducer(rootPage.name, {})
const reducer = combineReducers({
...reducers,
page: pageReducer
})
// Define the selector for the page state
const pageSelector = state => state.page
// Define getCurrentPath and pushPath
const history = createHistory({
})
const getCurrentPath = () => history.location.pathname
const pushPath = (path) => history.push(path)
const logger = createLogger()
// Create the pagesMiddleware
const pagesMiddleware = pages
.middleware(pageSelector, getCurrentPath, pushPath)
// Create the store
const store = createStore(
reducer,
applyMiddleware(pagesMiddleware, ...middlewares, logger),
)
// Apply the current path
pages.handleNavigation(store, history.location.pathname)
// Listen for changes
history.listen((location, action) => {
pages.handleNavigation(store, location.pathname)
})
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
src/routes/register/Register.js
|
foxleigh81/foxweb
|
/**
* 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 './Register.css';
class Register 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>...</p>
</div>
</div>
);
}
}
export default withStyles(s)(Register);
|
client/admin/settings/inputs/PasswordSettingInput.js
|
subesokun/Rocket.Chat
|
import { Box, Field, Flex, PasswordInput } from '@rocket.chat/fuselage';
import React from 'react';
import { ResetSettingButton } from '../ResetSettingButton';
export function PasswordSettingInput({
_id,
label,
value,
placeholder,
readonly,
autocomplete,
disabled,
hasResetButton,
onChangeValue,
onResetButtonClick,
}) {
const handleChange = (event) => {
onChangeValue && onChangeValue(event.currentTarget.value);
};
return <>
<Flex.Container>
<Box>
<Field.Label htmlFor={_id} title={_id}>{label}</Field.Label>
{hasResetButton && <ResetSettingButton data-qa-reset-setting-id={_id} onClick={onResetButtonClick} />}
</Box>
</Flex.Container>
<Field.Row>
<PasswordInput
data-qa-setting-id={_id}
id={_id}
value={value}
placeholder={placeholder}
disabled={disabled}
readOnly={readonly}
autoComplete={autocomplete === false ? 'off' : undefined}
onChange={handleChange}
/>
</Field.Row>
</>;
}
|
packages/material-ui-icons/src/VerticalAlignBottom.js
|
dsslimshaddy/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let VerticalAlignBottom = props =>
<SvgIcon {...props}>
<path d="M16 13h-3V3h-2v10H8l4 4 4-4zM4 19v2h16v-2H4z" />
</SvgIcon>;
VerticalAlignBottom = pure(VerticalAlignBottom);
VerticalAlignBottom.muiName = 'SvgIcon';
export default VerticalAlignBottom;
|
frontend/src/Components/Form/AutoCompleteInput.js
|
lidarr/Lidarr
|
import jdu from 'jdu';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import AutoSuggestInput from './AutoSuggestInput';
class AutoCompleteInput extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this.state = {
suggestions: []
};
}
//
// Control
getSuggestionValue(item) {
return item;
}
renderSuggestion(item) {
return item;
}
//
// Listeners
onInputChange = (event, { newValue }) => {
this.props.onChange({
name: this.props.name,
value: newValue
});
}
onInputBlur = () => {
this.setState({ suggestions: [] });
}
onSuggestionsFetchRequested = ({ value }) => {
const { values } = this.props;
const lowerCaseValue = jdu.replace(value).toLowerCase();
const filteredValues = values.filter((v) => {
return jdu.replace(v).toLowerCase().contains(lowerCaseValue);
});
this.setState({ suggestions: filteredValues });
}
onSuggestionsClearRequested = () => {
this.setState({ suggestions: [] });
}
//
// Render
render() {
const {
name,
value,
...otherProps
} = this.props;
const { suggestions } = this.state;
return (
<AutoSuggestInput
{...otherProps}
name={name}
value={value}
suggestions={suggestions}
getSuggestionValue={this.getSuggestionValue}
renderSuggestion={this.renderSuggestion}
onInputBlur={this.onInputBlur}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
/>
);
}
}
AutoCompleteInput.propTypes = {
name: PropTypes.string.isRequired,
value: PropTypes.string,
values: PropTypes.arrayOf(PropTypes.string).isRequired,
onChange: PropTypes.func.isRequired
};
AutoCompleteInput.defaultProps = {
value: ''
};
export default AutoCompleteInput;
|
src/mui/input/BooleanInput.js
|
matteolc/admin-on-rest
|
import React from 'react';
import PropTypes from 'prop-types';
import Toggle from 'material-ui/Toggle';
import FieldTitle from '../../util/FieldTitle';
const styles = {
block: {
margin: '1rem 0',
maxWidth: 250,
},
label: {
color: 'rgba(0, 0, 0, 0.298039)',
},
toggle: {
marginBottom: 16,
},
};
const BooleanInput = ({ input, label, source, elStyle, resource }) => (
<div style={elStyle || styles.block}>
<Toggle
defaultToggled={!!input.value}
onToggle={input.onChange}
labelStyle={styles.label}
style={styles.toggle}
label={<FieldTitle label={label} source={source} resource={resource} />}
/>
</div>
);
BooleanInput.propTypes = {
addField: PropTypes.bool.isRequired,
elStyle: PropTypes.object,
input: PropTypes.object,
label: PropTypes.string,
resource: PropTypes.string,
source: PropTypes.string,
};
BooleanInput.defaultProps = {
addField: true,
};
export default BooleanInput;
|
src/subscribe.js
|
DigitalGlobe/jetset
|
import React from 'react';
import { Map as iMap } from 'immutable';
import store from './store';
import logger, { formatBranchArgs } from './lib/log';
const isObject = item => !Array.isArray( item ) && typeof item === 'object';
function subscribe({ local, paths }) {
return Component => {
const rootPath = local ? [ 'local', Component.name + `_${Math.round(Math.random() * Date.now())}`] : [];
const nPaths = paths.reduce(( memo, item ) => {
if ( isObject( item ) ) {
Object.keys( item ).forEach( key => memo.set( key, item[ key ] ) );
} else {
memo.set( item );
}
return memo;
}, new Map());
return class Subscriber extends React.Component {
subscriptions = null
constructor( props ) {
super( props );
this.state = [ ...nPaths.entries() ].reduce(( memo, [ key, val ] ) => {
if ( val ) {
memo[key] = val;
// TODo this shouldn't happen here
store.setStateQuiet( rootPath.concat( key ), val );
} else {
const storeVal = store.getState( rootPath.concat( key ) );
memo[key] = storeVal && storeVal.toJS ? storeVal.toJS() : storeVal;
}
return memo;
}, {});
}
componentWillMount = () => {
this.subscriptions = [ ...nPaths.keys() ].map( this.subscribeTo );
}
componentWillUnmount = () => this.subscriptions.forEach( store.unsubscribe )
subscribeTo = path => store.subscribeTo( rootPath.concat( path ), this.onChange.bind( this, path ) );
onChange = ( path, state ) => {
/* eslint-disable no-console */
const branch = formatBranchArgs( rootPath.concat( path ) );
logger( `\uD83C\uDF00 <${Component.name || 'StatelessFunction'}> is re-rendering based on changes on branch: ${branch}` );
this.setState({ [path]: state && state.toJS ? state.toJS() : state });
}
merge = ( val, path ) => {
if ( Array.isArray( val ) || typeof val !== 'object' ) {
return this.replace( val, path );
} else {
const fullPath = rootPath.concat( path || [] );
const state = store.getState( fullPath ) || iMap();
return store.setState( fullPath, state.mergeDeep( val ) );
}
}
replace = ( val, path ) => store.setState( rootPath.concat( path || [] ), val )
methods = () => {
const keyState = [ ...nPaths.keys() ].reduce(( memo, path ) => {
const currentState = { ...this.state }[path];
return {
...memo,
[path]: {
get: () => currentState,
set: val => this.merge( val, path ),
replace: val => this.replace( path, val )
}
};
}, {});
const localState = {
get: () => ({ ...this.state }),
set: val => this.merge( val ),
replace: val => this.replace( val )
};
return { ...keyState, localState };
}
render = () => (
<Component
{ ...this.props }
{ ...this.methods() }
/>
)
};
};
}
export function localState( ...paths ) {
return subscribe({ local: true, paths });
}
export function globalState( ...paths ) {
return subscribe({ local: false, paths });
}
|
201601react/许海英/react/app/index.js
|
zhufengreact/homework
|
'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './container/App';
let root = document.getElementById('app');
ReactDOM.render( <App />, root );
|
src/containers/weather-list.js
|
86mattw/weather
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Chart from '../components/chart';
class WeatherList extends Component {
renderWeather(cityData) {
const name = cityData.city.name;
const temps = cityData.list.map(weather => weather.main.temp);
const pressures = cityData.list.map(weather => weather.main.pressure);
const humidities = cityData.list.map(weather => weather.main.humidity);
return (
<tr key={name}>
<td>{name}</td>
<td><Chart color="orange" data={temps} units="K" /></td>
<td><Chart color="green" data={pressures} units="hPa" /></td>
<td><Chart color="black" data={humidities} units="%" /></td>
</tr>
);
}
render() {
return (
<table className="table table-hover">
<thead>
<tr>
<th>City</th>
<th>Temperature (K)</th>
<th>Pressure (hPa)</th>
<th>Humidity (%)</th>
</tr>
</thead>
<tbody>
{this.props.weather.map(this.renderWeather)}
</tbody>
</table>
);
}
}
function mapStateToProps({ weather }) {
return { weather };
}
export default connect(mapStateToProps)(WeatherList);
|
app/containers/NotFoundPage/index.js
|
mamaracas/MEventsRegistration
|
/**
* NotFoundPage
*
* This is the page we show when the user visits a url that doesn't have a route
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import H1 from 'components/H1';
import messages from './messages';
export default function NotFound() {
return (
<article>
<H1>
<FormattedMessage {...messages.header} />
</H1>
</article>
);
}
|
examples/full-example/src/isomorphic/base/components/lazy_content.js
|
yahoo/mendel
|
/* Copyright 2015, Yahoo Inc.
Copyrights licensed under the MIT License.
See the accompanying LICENSE file for terms. */
import React from 'react';
class Button extends React.Component {
render() {
return <span style={{ color: 'blue' }}>
Content inside lazy
</span>;
}
}
export default Button;
|
src/parser/priest/shadow/modules/talents/ShadowCrash.js
|
sMteX/WoWAnalyzer
|
import React from 'react';
import SPELLS from 'common/SPELLS/index';
import Analyzer from 'parser/core/Analyzer';
import TalentStatisticBox, { STATISTIC_ORDER } from 'interface/others/TalentStatisticBox';
import ItemDamageDone from 'interface/others/ItemDamageDone';
import { formatNumber } from 'common/format';
import AbilityTracker from 'parser/priest/shadow/modules/core/AbilityTracker';
// Example Log: /report/zgBQ3kr6aAv19MXq/22-Normal+Zul+-+Kill+(2:26)/3-Selur
class ShadowCrash extends Analyzer {
static dependencies = {
abilityTracker: AbilityTracker,
};
damage = 0;
totalTargetsHit = 0;
get averageTargetsHit() {
return this.totalTargetsHit / this.abilityTracker.getAbility(SPELLS.SHADOW_CRASH_TALENT.id).casts;
}
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.SHADOW_CRASH_TALENT.id);
}
on_byPlayer_damage(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.SHADOW_CRASH_TALENT_DAMAGE.id) {
return;
}
this.totalTargetsHit += 1;
this.damage += event.amount;
}
statistic() {
return (
<TalentStatisticBox
talent={SPELLS.SHADOW_CRASH_TALENT.id}
value={<ItemDamageDone amount={this.damage} />}
tooltip={`Average targets hit: ${formatNumber(this.averageTargetsHit)}`}
position={STATISTIC_ORDER.CORE(5)}
/>
);
}
}
export default ShadowCrash;
|
packages/material-ui-icons/src/AirlineSeatFlat.js
|
cherniavskii/material-ui
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M22 11v2H9V7h9c2.21 0 4 1.79 4 4zM2 14v2h6v2h8v-2h6v-2H2zm5.14-1.9c1.16-1.19 1.14-3.08-.04-4.24-1.19-1.16-3.08-1.14-4.24.04-1.16 1.19-1.14 3.08.04 4.24 1.19 1.16 3.08 1.14 4.24-.04z" /></g>
, 'AirlineSeatFlat');
|
packages/veritone-widgets/src/widgets/MediaPlayer/DefaultControlBar.js
|
veritone/veritone-sdk
|
import React from 'react';
import { connect } from 'react-redux';
import cx from 'classnames';
import { get } from 'lodash';
import { bindActionCreators } from 'redux';
import {
VolumeMenuButton,
ControlBar,
ReplayControl,
ForwardControl,
PlayToggle,
playerActions,
videoActions,
CurrentTimeDisplay,
TimeDivider,
DurationDisplay,
ProgressControl,
FullscreenToggle
} from 'video-react';
import { shape, objectOf, any, bool, number } from 'prop-types';
import { withStyles } from '@material-ui/styles';
import { RestartMediaButton } from 'veritone-react-common';
import 'video-react/dist/video-react.css';
import styles from './styles';
@withStyles(styles)
@connect(
state => ({
playerState: state.player,
hasStarted: state.player.hasStarted
}),
dispatch => ({
videoReactActions: bindActionCreators(
{ ...playerActions, ...videoActions },
dispatch
)
})
)
export default class DefaultControlBar extends React.Component {
static propTypes = {
playerRef: shape({
current: objectOf(any)
}),
hasStarted: bool,
btnRestart: bool,
btnReplay: bool,
btnForward: bool,
btnPlayToggle: bool,
btnVolume: bool,
btnFullscreenToggle: bool,
ctrlProgress: bool,
displayTime: bool,
autoHide: bool,
autoHideTime: number,
classes: shape({ any })
};
static defaultProps = {
btnRestart: true,
btnReplay: true,
btnForward: true,
btnPlayToggle: true,
btnVolume: true,
btnFullscreenToggle: true,
ctrlProgress: true,
displayTime: true,
autoHide: true,
autoHideTime: 1000
};
render() {
const manager = get(this.props.playerRef, 'current.manager');
let player, actions, store;
if (manager) {
player = manager.getState().player;
actions = manager.getActions();
store = manager.store;
}
if (!manager) {
return null;
}
const {
hasStarted,
btnRestart,
btnReplay,
btnForward,
btnPlayToggle,
btnVolume,
btnFullscreenToggle,
ctrlProgress,
displayTime,
autoHide,
autoHideTime,
classes
} = this.props;
return (
<div
className={cx(
'video-react',
{
'video-react-has-started': hasStarted || get(player, 'hasStarted', false)
},
classes.externalStyles
)}
data-test="DefaultControlBar"
>
<ControlBar
className={cx('mediaPlayerControls')}
// need to provide these manually because ControlBar is
// supposed to be a child of Player and get them automatically
autoHide={autoHide}
autoHideTime={autoHideTime}
player={player}
manager={manager}
actions={actions}
store={store}
disableDefaultControls
>
{btnRestart && <RestartMediaButton order={1.1} />}
{btnReplay && <ReplayControl seconds={10} order={1.2} />}
{btnForward && <ForwardControl seconds={10} order={1.3} />}
{btnPlayToggle && <PlayToggle order={2} />}
{displayTime && <CurrentTimeDisplay player={player} order={3.1} />}
{displayTime && <TimeDivider order={3.2} />}
{displayTime && <DurationDisplay player={player} order={3.3} />}
{ctrlProgress && <ProgressControl order={6} />}
{btnVolume && <VolumeMenuButton vertical={ctrlProgress} order={7} />}
{btnFullscreenToggle && <FullscreenToggle order={8} />}
</ControlBar>
</div>
);
}
}
|
src/Stepper/StepButton.spec.js
|
hwo411/material-ui
|
/* eslint-env mocha */
import React from 'react';
import {shallow} from 'enzyme';
import {assert} from 'chai';
import {spy} from 'sinon';
import StepButton from './StepButton';
import StepLabel from './StepLabel';
import getMuiTheme from '../styles/getMuiTheme';
describe('<StepButton />', () => {
const muiTheme = getMuiTheme();
const themedShallow = (node) => {
const context = {muiTheme, stepper: {orientation: 'horizontal'}};
return shallow(node, {context});
};
it('should merge user styles in', () => {
const wrapper = themedShallow(
<StepButton style={{backgroundColor: 'purple'}}>Step One</StepButton>
);
assert.strictEqual(wrapper.props().style.backgroundColor, 'purple');
});
it('should render an EnhancedButton with a StepLabel', () => {
const wrapper = themedShallow(
<StepButton>Step One</StepButton>
);
assert.ok(wrapper.is('EnhancedButton'), 'should be an EnhancedButton');
const stepLabel = wrapper.find(StepLabel);
assert.strictEqual(stepLabel.length, 1, 'should have a stepLabel');
assert.strictEqual(stepLabel.props().children, 'Step One');
});
it('should pass iconContainerStyle to StepLabel', () => {
const wrapper = themedShallow(
<StepButton
iconContainerStyle={{width: 50, color: 'cyan', marginTop: 200, border: '1px solid violet'}}
icon={1}
>
StepOne
</StepButton>
);
const iconContainerStyle = wrapper.find(StepLabel).props().iconContainerStyle;
assert.strictEqual(iconContainerStyle.width, 50);
assert.strictEqual(iconContainerStyle.color, 'cyan');
assert.strictEqual(iconContainerStyle.marginTop, 200);
assert.strictEqual(iconContainerStyle.border, '1px solid violet');
});
it('should pass props to StepLabel', () => {
const wrapper = themedShallow(
<StepButton
active={true}
completed={true}
disabled={true}
label="Step One"
>
Step One
</StepButton>
);
const stepLabel = wrapper.find(StepLabel);
assert.strictEqual(stepLabel.prop('active'), true, 'should be active');
assert.strictEqual(stepLabel.prop('completed'), true, 'should be completed');
assert.strictEqual(stepLabel.prop('disabled'), true, 'should be disabled');
});
it('should pass props to EnhancedButton', () => {
const wrapper = themedShallow(
<StepButton disabled={true}>Step One</StepButton>
);
const stepLabel = wrapper.find('EnhancedButton');
assert.strictEqual(stepLabel.prop('disabled'), true);
});
describe('event handlers', () => {
describe('handleMouseEnter/Leave', () => {
const handleMouseEnter = spy();
const handleMouseLeave = spy();
const wrapper = themedShallow(
<StepButton
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
Step One
</StepButton>
);
it('should set the hovered state', () => {
wrapper.simulate('mouseEnter');
assert.strictEqual(wrapper.state('hovered'), true, 'should be hovered');
assert.strictEqual(handleMouseEnter.callCount, 1, 'should call handleMouseEnter once');
wrapper.simulate('mouseLeave');
assert.strictEqual(wrapper.state('hovered'), false, 'should not be hovered');
assert.strictEqual(handleMouseEnter.callCount, 1, 'should call handleMouseEnter once');
assert.strictEqual(handleMouseLeave.callCount, 1, 'should call handleMouseLeave once');
});
it('should set the EnhancedButton backgroundColor on hover', () => {
wrapper.setState({hovered: false});
assert.strictEqual(wrapper.prop('style').backgroundColor, muiTheme.stepper.backgroundColor);
wrapper.setState({hovered: true});
assert.strictEqual(wrapper.prop('style').backgroundColor, muiTheme.stepper.hoverBackgroundColor);
});
});
describe('handleTouchStart', () => {
const handleTouchStart = spy();
const handleMouseEnter = spy();
const wrapper = themedShallow(
<StepButton
onTouchStart={handleTouchStart}
onMouseEnter={handleMouseEnter}
>
Step One
</StepButton>
);
it('should set the touched state', () => {
assert.strictEqual(wrapper.state('touched'), false, 'should not be touched');
wrapper.simulate('touchStart');
assert.strictEqual(wrapper.state('touched'), true, 'should be touched');
assert.strictEqual(handleTouchStart.callCount, 1, 'should call handleTouchStart once');
});
it('should not set the hovered state with touch set', () => {
wrapper.simulate('mouseEnter');
assert.strictEqual(wrapper.state('hovered'), false, 'should not be hovered');
assert.strictEqual(handleMouseEnter.callCount, 1, 'should call handleMouseEnter once');
});
});
it('should bubble callbacks used internally', () => {
const handleMouseEnter = spy();
const handleMouseLeave = spy();
const handleTouchStart = spy();
const wrapper = themedShallow(
<StepButton
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
onTouchStart={handleTouchStart}
>
Step One
</StepButton>
);
wrapper.simulate('mouseEnter');
assert.strictEqual(handleMouseEnter.callCount, 1, 'should call handleMouseEnter once');
wrapper.simulate('mouseLeave');
assert.strictEqual(handleMouseEnter.callCount, 1, 'should call handleMouseEnter once');
assert.strictEqual(handleMouseLeave.callCount, 1, 'should call handleMouseLeave once');
wrapper.simulate('touchStart');
assert.strictEqual(handleMouseEnter.callCount, 1, 'should call handleMouseEnter once');
assert.strictEqual(handleMouseLeave.callCount, 1, 'should call handleMouseLeave once');
assert.strictEqual(handleTouchStart.callCount, 1, 'should call handleTouchStart once');
wrapper.simulate('mouseEnter');
wrapper.simulate('touchStart');
assert.strictEqual(handleMouseEnter.callCount, 2, 'should call handleMouseEnter twice');
assert.strictEqual(handleMouseLeave.callCount, 1, 'should call handleMouseLeave once');
assert.strictEqual(handleTouchStart.callCount, 2, 'should call handleTouchStart twice');
});
});
});
|
client/modules/comments/components/.stories/create_comment.js
|
TheAncientGoat/mantra-sample-blog-coffee
|
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
const CreateComment = require('../create_comment.coffee');
storiesOf('comments.CreateComment', module)
.add('default view', () => {
return (
<div className='comments'>
<CreateComment postId='the-id' create={action('create comment')}/>
</div>
);
})
.add('with error', () => {
return (
<div className='comments'>
<CreateComment
error='This is the error message'
postId='the-id'
create={action('create comment')}
/>
</div>
);
});
|
admin/client/App/components/Navigation/Mobile/SectionItem.js
|
frontyard/keystone
|
/**
* A mobile section
*/
import React from 'react';
import MobileListItem from './ListItem';
import { Link } from 'react-router';
const MobileSectionItem = React.createClass({
displayName: 'MobileSectionItem',
propTypes: {
children: React.PropTypes.node.isRequired,
className: React.PropTypes.string,
currentListKey: React.PropTypes.string,
href: React.PropTypes.string.isRequired,
lists: React.PropTypes.array,
},
// Render the lists
renderLists () {
if (!this.props.lists || this.props.lists.length <= 1) return null;
const navLists = this.props.lists.map((item) => {
// Get the link and the classname
const href = item.external ? item.path : `${Keystone.adminPath}/${item.path}`;
const className = (this.props.currentListKey && this.props.currentListKey === item.path) ? 'MobileNavigation__list-item is-active' : 'MobileNavigation__list-item';
return (
<MobileListItem key={item.path} href={href} className={className} onClick={this.props.onClick}>
{item.label}
</MobileListItem>
);
});
return (
<div className="MobileNavigation__lists">
{navLists}
</div>
);
},
render () {
return (
<div className={this.props.className}>
<Link
className="MobileNavigation__section-item"
to={this.props.href}
tabIndex="-1"
onClick={this.props.onClick}
>
{this.props.children}
</Link>
{this.renderLists()}
</div>
);
},
});
module.exports = MobileSectionItem;
|
src/components/charts/charts/svg/path.js
|
noahehall/udacity-corporate-dashboard
|
import React from 'react';
export const Path = ({ // eslintignore https://developer.mozilla.org/en-US/docs/Web/SVG/Element/path
chartType = 'pie',
d,
fill = 'blue',
id = '',
stroke = 'gray',
}) => <path
className={`${chartType}-path`}
d={d}
fill={fill}
id={id}
stroke={stroke}
/>;
Path.propTypes = {
chartType: React.PropTypes.string,
d: React.PropTypes.string.isRequired,
fill: React.PropTypes.string,
id: React.PropTypes.string,
stroke: React.PropTypes.string,
};
export default Path;
|
common/components/Header.js
|
BostonGlobe/elections-2016
|
import React from 'react'
import svgs from './../utils/svgs.js'
import Navigation from './Navigation.js'
const Header = () => (
<header className='header' key='header'>
<a href='#content' className='skip-to-main'>Skip to main content</a>
<div className='header__logo'>
<a
href='http://www.bostonglobe.com/'
className='header__logo-link'
dangerouslySetInnerHTML={{ __html: svgs.globeLogo }} />
</div>
<Navigation />
</header>
)
export default Header
|
packages/@lyra/form-builder/src/inputs/BlockEditor/Toolbar/DecoratorButtons.js
|
VegaPublish/vega-studio
|
// @flow
import type {
BlockContentFeature,
BlockContentFeatures,
SlateChange,
SlateValue
} from '../typeDefs'
import React from 'react'
import {keyMaps} from '../plugins/SetMarksOnKeyComboPlugin'
import {toggleMark} from '../utils/changes'
import CustomIcon from './CustomIcon'
import FormatBoldIcon from 'part:@lyra/base/format-bold-icon'
import FormatItalicIcon from 'part:@lyra/base/format-italic-icon'
import FormatStrikethroughIcon from 'part:@lyra/base/format-strikethrough-icon'
import FormatUnderlinedIcon from 'part:@lyra/base/format-underlined-icon'
import FormatCodeIcon from 'part:@lyra/base/format-code-icon'
import LyraLogoIcon from 'part:@lyra/base/lyra-logo-icon'
import ToggleButton from 'part:@lyra/components/toggles/button'
import ToolbarClickAction from './ToolbarClickAction'
import styles from './styles/DecoratorButtons.css'
type DecoratorItem = BlockContentFeature & {active: boolean, disabled: boolean}
type Props = {
blockContentFeatures: BlockContentFeatures,
editorValue: SlateValue,
onChange: (change: SlateChange) => void
}
function getIcon(type: string) {
switch (type) {
case 'strong':
return FormatBoldIcon
case 'em':
return FormatItalicIcon
case 'underline':
return FormatUnderlinedIcon
case 'strike-through':
return FormatStrikethroughIcon
case 'code':
return FormatCodeIcon
default:
return LyraLogoIcon
}
}
const NOOP = () => {}
export default class DecoratorButtons extends React.Component<Props> {
hasDecorator(decoratorName: string) {
const {editorValue} = this.props
return editorValue.marks.some(mark => mark.type === decoratorName)
}
getItems() {
const {blockContentFeatures, editorValue} = this.props
const {focusBlock} = editorValue
const disabled = focusBlock ? focusBlock.isVoid : false
return blockContentFeatures.decorators.map(
(decorator: BlockContentFeature) => {
return {
...decorator,
active: this.hasDecorator(decorator.value),
disabled
}
}
)
}
handleClick = (item: DecoratorItem) => {
const {onChange, editorValue} = this.props
const change = editorValue.change()
change.call(toggleMark, item.value)
onChange(change)
}
renderDecoratorButton = (item: DecoratorItem) => {
const {editorValue} = this.props
const icon = item.blockEditor ? item.blockEditor.icon : null
const Icon = icon || getIcon(item.value)
// We must not do a click-event here, because that messes with the editor focus!
const onAction = () => {
this.handleClick(item)
}
const shortCut = keyMaps[item.value] ? `(${keyMaps[item.value]})` : ''
const title = `${item.title} ${shortCut}`
return (
<span className={styles.buttonWrapper} key={item.value}>
<ToolbarClickAction
onAction={onAction}
editorValue={editorValue}
key={`decoratorButton${item.value}`}
>
<ToggleButton
selected={!!item.active}
disabled={item.disabled}
onClick={NOOP}
title={title}
className={styles.button}
icon={Icon}
/>
</ToolbarClickAction>
</span>
)
}
render() {
const items = this.getItems()
return (
<div className={styles.root}>{items.map(this.renderDecoratorButton)}</div>
)
}
}
|
containers/SearchBar/index.js
|
bmagic/acdh-client
|
import React from 'react'
import { connect } from 'react-redux'
import { createStructuredSelector } from 'reselect'
import PropTypes from 'prop-types'
import { searchChange } from 'actions/programs'
import { makeSearch } from 'selectors/programs'
export class SearchBar extends React.PureComponent {
render () {
return (
<div className='search-bar field'>
<input type='text' className='input' value={this.props.search} placeholder='Rechercher une émission' onChange={this.props.onChange} />
</div>
)
}
}
SearchBar.propTypes = {
search: PropTypes.string,
onChange: PropTypes.func
}
const mapStateToProps = createStructuredSelector({
search: makeSearch()
})
export function mapDispatchToProps (dispatch) {
return {
onChange: (e) => {
dispatch(searchChange(e.target.value))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SearchBar)
|
node_modules/semantic-ui-react/dist/es/views/Statistic/StatisticValue.js
|
mowbell/clickdelivery-fed-test
|
import _extends from 'babel-runtime/helpers/extends';
import _isNil from 'lodash/isNil';
import cx from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { customPropTypes, getElementType, getUnhandledProps, META, useKeyOnly } from '../../lib';
/**
* A statistic can contain a numeric, icon, image, or text value.
*/
function StatisticValue(props) {
var children = props.children,
className = props.className,
text = props.text,
value = props.value;
var classes = cx(useKeyOnly(text, 'text'), 'value', className);
var rest = getUnhandledProps(StatisticValue, props);
var ElementType = getElementType(StatisticValue, props);
return React.createElement(
ElementType,
_extends({}, rest, { className: classes }),
_isNil(children) ? value : children
);
}
StatisticValue.handledProps = ['as', 'children', 'className', 'text', 'value'];
StatisticValue._meta = {
name: 'StatisticValue',
parent: 'Statistic',
type: META.TYPES.VIEW
};
process.env.NODE_ENV !== "production" ? StatisticValue.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Format the value with smaller font size to fit nicely beside number values. */
text: PropTypes.bool,
/** Primary content of the StatisticValue. Mutually exclusive with the children prop. */
value: customPropTypes.contentShorthand
} : void 0;
export default StatisticValue;
|
client/src/components/loader/index.js
|
commoncode/ontap
|
import React from 'react';
const Loader = () => (
<div className="loader">
OnTap
</div>
);
export default Loader;
|
src/components/video_detail.js
|
martezconner/react_vidhub
|
import React from 'react';
const VideoDetail = ({video}) => {
if (!video) {
return <div>Loading...</div>;
}
const videoId = video.id.videoId;
const url = `https://www.youtube.com/embed/${videoId}`;
return (
<div className="video-detail col-md-8">
<div className="embed-responsive embed-responsive-16by9">
<iframe className="embed-responsive-item" src={url}></iframe>
</div>
<div className="details">
<div>{video.snippet.title}</div>
<div>{video.snippet.description}</div>
</div>
</div>
);
};
export default VideoDetail;
|
apps/app/src/pages/Repository/BuildDetail/Context.js
|
argos-ci/argos
|
import React from 'react'
import gql from 'graphql-tag'
import { useMutation } from '@apollo/react-hooks'
export const BuildContextFragment = gql`
fragment BuildContextFragment on Build {
id
createdAt
number
status
repository {
name
owner {
login
}
}
baseScreenshotBucket {
id
createdAt
updatedAt
name
commit
branch
}
compareScreenshotBucket {
id
createdAt
updatedAt
name
commit
branch
}
screenshotDiffs {
id
createdAt
updatedAt
baseScreenshot {
id
name
url
}
compareScreenshot {
id
name
url
}
url
score
jobStatus
validationStatus
}
}
`
const BuildContext = React.createContext()
export function BuildProvider({ build: initialBuild, children }) {
const [build, setBuild] = React.useState(initialBuild)
const [
setValidationStatus,
{ loading: queryLoading, error: queryError, data },
] = useMutation(gql`
mutation setValidationStatus(
$buildId: ID!
$validationStatus: ValidationStatus!
) {
setValidationStatus(
buildId: $buildId
validationStatus: $validationStatus
) {
...BuildContextFragment
}
}
${BuildContextFragment}
`)
React.useEffect(() => {
if (data && data.setValidationStatus) {
setBuild(data.setValidationStatus)
}
}, [data])
const value = React.useMemo(
() => ({
build,
setValidationStatus,
queryLoading,
queryError,
}),
[build, queryError, queryLoading, setValidationStatus],
)
return <BuildContext.Provider value={value}>{children}</BuildContext.Provider>
}
export function useBuild() {
const { build } = React.useContext(BuildContext)
return build
}
export function useValidationStatusBuild() {
const {
setValidationStatus,
queryLoading: loading,
queryError: error,
} = React.useContext(BuildContext)
return { setValidationStatus, loading, error }
}
|
src/svg-icons/maps/pin-drop.js
|
mit-cml/iot-website-source
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsPinDrop = (props) => (
<SvgIcon {...props}>
<path d="M18 8c0-3.31-2.69-6-6-6S6 4.69 6 8c0 4.5 6 11 6 11s6-6.5 6-11zm-8 0c0-1.1.9-2 2-2s2 .9 2 2-.89 2-2 2c-1.1 0-2-.9-2-2zM5 20v2h14v-2H5z"/>
</SvgIcon>
);
MapsPinDrop = pure(MapsPinDrop);
MapsPinDrop.displayName = 'MapsPinDrop';
MapsPinDrop.muiName = 'SvgIcon';
export default MapsPinDrop;
|
src/containers/Home/Home.js
|
dbertella/react-hot-reload-starter
|
import React, { Component } from 'react';
import { SimpleForm } from 'components';
class Home extends Component {
render() {
return (
<div>
<h1>Home</h1>
<SimpleForm />
</div>
);
}
}
export default Home;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.