path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
libs/utils/react.js | allanfish/elementui | import React from 'react'
function firstChild(props) {
const childrenArray = React.Children.toArray(props.children);
return childrenArray[0] || null;
}
export {firstChild} |
client/src/js/components/Container.js | LlamaSantos/realtime-readit | import React from 'react';
import { RouteHandler } from 'react-router';
import Header from 'components/Header'
export default React.createClass({
render () {
return (
<div className="container">
<Header />
<RouteHandler />
</div>
);
}
});
|
docs/src/app/components/pages/components/SvgIcon/ExampleIcons.js | pradel/material-ui | import React from 'react';
import ActionHome from 'material-ui/svg-icons/action/home';
import ActionFlightTakeoff from 'material-ui/svg-icons/action/flight-takeoff';
import FileCloudDownload from 'material-ui/svg-icons/file/cloud-download';
import HardwareVideogameAsset from 'material-ui/svg-icons/hardware/videogame-asset';
import {red500, yellow500, blue500} from 'material-ui/styles/colors';
const iconStyles = {
marginRight: 24,
};
const SvgIconExampleIcons = () => (
<div>
<ActionHome style={iconStyles} />
<ActionFlightTakeoff style={iconStyles} color={red500} />
<FileCloudDownload style={iconStyles} color={yellow500} />
<HardwareVideogameAsset style={iconStyles} color={blue500} />
</div>
);
export default SvgIconExampleIcons;
|
routes.js | loganwedwards/react-static-boilerplate | import React from 'react';
import { Router, Route, IndexRoute } from 'react-router';
import AppBase from './pages/app-base';
import About from './pages/about';
import Home from './pages/home';
import Team from './pages/team';
export default (
<Router>
<Route path="/" component={AppBase}>
<IndexRoute component={Home} />
<Route path="about" component={About}></Route>
<Route path="team" component={Team}></Route>
</Route>
</Router>
);
|
app/components/common/Avatar.js | rvpanoz/luna | import React from 'react';
import cx from 'classnames';
import PropTypes from 'prop-types';
import MuiAvatar from '@material-ui/core/Avatar';
import { AVATAR } from 'styles/common';
const Avatar = ({
className,
bordered,
link,
small,
medium,
ultraLarge,
...props
}) => (
<MuiAvatar
className={cx(
AVATAR.root,
className,
bordered && AVATAR.bordered,
link && AVATAR.link,
small && AVATAR.small,
medium && AVATAR.medium,
ultraLarge && AVATAR.ultraLarge
)}
{...props}
/>
);
Avatar.propTypes = {
className: PropTypes.string,
bordered: PropTypes.bool,
link: PropTypes.string,
small: PropTypes.bool,
medium: PropTypes.bool,
ultraLarge: PropTypes.bool,
};
export default Avatar;
|
modules/Lifecycle.js | opichals/react-router | import React from 'react';
import invariant from 'invariant';
var { object } = React.PropTypes;
/**
* The Lifecycle mixin adds the routerWillLeave lifecycle method
* to a component that may be used to cancel a transition or prompt
* the user for confirmation.
*
* On standard transitions, routerWillLeave receives a single argument: the
* location we're transitioning to. To cancel the transition, return false.
* To prompt the user for confirmation, return a prompt message (string).
*
* routerWillLeave does not receive a location object during the beforeunload
* event in web browsers (assuming you're using the useBeforeUnload history
* enhancer). In this case, it is not possible for us to know the location
* we're transitioning to so routerWillLeave must return a prompt message to
* prevent the user from closing the tab.
*/
var Lifecycle = {
propTypes: {
// Route components receive the route object as a prop.
route: object
},
contextTypes: {
history: object.isRequired,
// Nested children receive the route as context, either
// set by the route component using the RouteContext mixin
// or by some other ancestor.
route: object
},
_getRoute() {
var route = this.props.route || this.context.route;
invariant(
route,
'The Lifecycle mixin needs to be used either on 1) a <Route component> or ' +
'2) a descendant of a <Route component> that uses the RouteContext mixin'
);
return route;
},
componentWillMount() {
invariant(
this.routerWillLeave,
'The Lifecycle mixin requires you to define a routerWillLeave method'
);
this.context.history.registerRouteHook(
this._getRoute(),
this.routerWillLeave
);
},
componentWillUnmount() {
this.context.history.unregisterRouteHook(
this._getRoute(),
this.routerWillLeave
);
}
};
export default Lifecycle;
|
client-redux-ex/app/AppCore.js | alexadam/react-start | import React from 'react';
import ReactDOM from 'react-dom';
import Main from './components/main.js';
// const App = (props) => (
// <div>
// <h1>Hello World</h1>
// </div>
// );
ReactDOM.render((
<Main/>
), document.getElementById('app'));
|
src/components/Footer/Footer.js | Maryanushka/masterskaya | /**
* 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 withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Footer.css';
import Link from '../Link';
class Footer extends React.Component {
render() {
return (
<div className={s.root}>
<div className={s.footer_container}>
<iframe src={'https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2544.445443859823!2d30.70386341519805!3d50.3768942794653!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x40d4c3901c5bc785%3A0x1452061acb8b27e9!2z0J_QtdGA0LXRj9GB0LvQsNCy0YHRjNC60LAg0LLRg9C70LjRhtGPLCAxLCDQmtC40ZfQsg!5e0!3m2!1sru!2sua!4v1497578027615'}></iframe>
<div className={s.footer_container_contact}>
<h1>Контакти</h1>
<Link to="+380664455900" className={s.footer_container_contact_phone}>+38 066 445 59 00</Link>
<p className={s.footer_container_contact_adress}>м. Мукачево, вул. Переяславська, 1</p>
<ul className={s.footer_container_menu}>
<li><Link to="/catalog">Каталог продукції</Link></li>
<li><Link to="/catalog">Про нас</Link></li>
<li><Link to="/catalog">Наші роботи</Link></li>
</ul>
</div>
</div>
</div>
);
}
}
export default withStyles(s)(Footer);
|
src/components/CritButtons.js | rcbdev/crit-cards | import React from 'react';
import CritButton from './CritButton';
export default function CritButtons({critTypes, addEffect}){
const buttonRows = [];
for(const critMiss of Object.keys(critTypes)){
buttonRows.push(
<div key={critMiss}>
{critTypes[critMiss].map(t => <CritButton key={critMiss + t} critMiss={critMiss} attackType={t} addEffect={addEffect} />)}
</div>
);
}
return (
<div style={{textAlign: "center"}}>
{buttonRows}
</div>
);
}
|
app/javascript/mastodon/components/display_name.js | haleyashleypraesent/ProjectPrionosuchus | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import escapeTextContentForBrowser from 'escape-html';
import emojify from '../emoji';
class DisplayName extends React.PureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
};
render () {
const displayName = this.props.account.get('display_name').length === 0 ? this.props.account.get('username') : this.props.account.get('display_name');
const displayNameHTML = { __html: emojify(escapeTextContentForBrowser(displayName)) };
return (
<span className='display-name'>
<strong className='display-name__html' dangerouslySetInnerHTML={displayNameHTML} /> <span className='display-name__account'>@{this.props.account.get('acct')}</span>
</span>
);
}
}
export default DisplayName;
|
src/svg-icons/maps/edit-location.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsEditLocation = (props) => (
<SvgIcon {...props}>
<path d="M12 2C8.14 2 5 5.14 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.86-3.14-7-7-7zm-1.56 10H9v-1.44l3.35-3.34 1.43 1.43L10.44 12zm4.45-4.45l-.7.7-1.44-1.44.7-.7c.15-.15.39-.15.54 0l.9.9c.15.15.15.39 0 .54z"/>
</SvgIcon>
);
MapsEditLocation = pure(MapsEditLocation);
MapsEditLocation.displayName = 'MapsEditLocation';
MapsEditLocation.muiName = 'SvgIcon';
export default MapsEditLocation;
|
app/javascript/mastodon/components/column.js | increments/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import detectPassiveEvents from 'detect-passive-events';
import { scrollTop } from '../scroll';
export default class Column extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
};
scrollTop () {
const scrollable = this.node.querySelector('.scrollable');
if (!scrollable) {
return;
}
this._interruptScrollAnimation = scrollTop(scrollable);
}
handleWheel = () => {
if (typeof this._interruptScrollAnimation !== 'function') {
return;
}
this._interruptScrollAnimation();
}
setRef = c => {
this.node = c;
}
componentDidMount () {
this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false);
}
componentWillUnmount () {
this.node.removeEventListener('wheel', this.handleWheel);
}
render () {
const { children } = this.props;
return (
<div role='region' className='column' ref={this.setRef}>
{children}
</div>
);
}
}
|
src/components/AnchorButton/AnchorButton.js | cdtinney/cdtinney.github.io | import React from 'react';
import PropTypes from 'prop-types';
import Anchor from '../Anchor';
import Theme from '../../proptypes/Theme';
import withTheme from '../../hocs/withTheme';
import classNames from '../../utils/classNames';
import classes from './AnchorButton.module.css';
const colorEnum = {
primary: classes.primary,
secondary: classes.secondary,
};
export function AnchorButton({
theme,
href,
external,
title,
text,
ariaLabel,
color,
className,
}) {
return (
<Anchor
href={href}
external={external}
title={title}
ariaLabel={ariaLabel}
color={color}
className={classNames(
classes.anchorButton,
colorEnum[color],
theme.button,
className,
)}
>
{ text }
</Anchor>
);
}
AnchorButton.propTypes = {
theme: Theme.isRequired,
href: PropTypes.string.isRequired,
external: PropTypes.bool,
title: PropTypes.string,
text: PropTypes.string.isRequired,
ariaLabel: PropTypes.string,
color: PropTypes.string,
className: PropTypes.string,
};
AnchorButton.defaultProps = {
external: false,
title: null,
ariaLabel: null,
color: 'primary',
className: '',
};
export default withTheme(AnchorButton);
|
packages/material-ui-icons/src/CloudCircle.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let CloudCircle = 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 2zm4.5 14H8c-1.66 0-3-1.34-3-3s1.34-3 3-3l.14.01C8.58 8.28 10.13 7 12 7c2.21 0 4 1.79 4 4h.5c1.38 0 2.5 1.12 2.5 2.5S17.88 16 16.5 16z" />
</SvgIcon>;
CloudCircle = pure(CloudCircle);
CloudCircle.muiName = 'SvgIcon';
export default CloudCircle;
|
examples/huge-apps/routes/Course/routes/Assignments/components/Assignments.js | skevy/react-router | import React from 'react';
class Assignments extends React.Component {
render () {
return (
<div>
<h3>Assignments</h3>
{this.props.children || <p>Choose an assignment from the sidebar.</p>}
</div>
);
}
}
export default Assignments;
|
src/Input.js | xiaoking/react-bootstrap | import React from 'react';
import InputBase from './InputBase';
import * as FormControls from './FormControls';
import deprecationWarning from './utils/deprecationWarning';
class Input extends InputBase {
render() {
if (this.props.type === 'static') {
deprecationWarning('Input type=static', 'StaticText');
return <FormControls.Static {...this.props} />;
}
return super.render();
}
}
Input.propTypes = {
type: React.PropTypes.string
};
export default Input;
|
app/js/NavBar.js | jacobSingh/tabwrangler | /* @flow */
import PauseButton from './PauseButton';
import React from 'react';
export type NavBarTabID = 'about' | 'corral' | 'lock' | 'options';
type Props = {
activeTabId: NavBarTabID,
onClickTab: (tabId: NavBarTabID) => void,
};
export default class NavBar extends React.PureComponent<Props> {
handleClickAboutTab = (event: SyntheticMouseEvent<HTMLElement>) => {
event.preventDefault();
this.props.onClickTab('about');
};
handleClickCorralTab = (event: SyntheticMouseEvent<HTMLElement>) => {
event.preventDefault();
this.props.onClickTab('corral');
};
handleClickLockTab = (event: SyntheticMouseEvent<HTMLElement>) => {
event.preventDefault();
this.props.onClickTab('lock');
};
handleClickOptionsTab = (event: SyntheticMouseEvent<HTMLElement>) => {
event.preventDefault();
this.props.onClickTab('options');
};
render() {
return (
<div>
<div className="pull-right nav-buttons">
<PauseButton />
</div>
<ul className="nav nav-tabs">
<li className={this.props.activeTabId === 'corral' ? 'active' : null}>
<a href="#corral" onClick={this.handleClickCorralTab}>
{chrome.i18n.getMessage('tabCorral_name')}
</a>
</li>
<li className={this.props.activeTabId === 'lock' ? 'active' : null}>
<a href="#lock" onClick={this.handleClickLockTab}>
{chrome.i18n.getMessage('tabLock_name')}
</a>
</li>
<li className={this.props.activeTabId === 'options' ? 'active' : null}>
<a href="#options" onClick={this.handleClickOptionsTab}>
{chrome.i18n.getMessage('options_name')}
</a>
</li>
<li className={this.props.activeTabId === 'about' ? 'active' : null}>
<a href="#about" onClick={this.handleClickAboutTab}>
{chrome.i18n.getMessage('about_name')}
</a>
</li>
</ul>
</div>
);
}
}
|
app/containers/LanguageProvider/index.js | Get-In-Touch/get-in-touch | /*
*
* LanguageProvider
*
* this component connects the redux state language locale to the
* IntlProvider component and i18n messages (loaded from `app/translations`)
*/
import React from 'react';
import { connect } from 'react-redux';
import { IntlProvider } from 'react-intl';
export class LanguageProvider extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<IntlProvider locale={this.props.locale} messages={this.props.messages[this.props.locale]}>
{React.Children.only(this.props.children)}
</IntlProvider>
);
}
}
LanguageProvider.propTypes = {
locale: React.PropTypes.string,
messages: React.PropTypes.object,
children: React.PropTypes.element.isRequired,
};
function mapStateToProps(state) {
return { state };
}
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(LanguageProvider);
|
src/svg-icons/editor/merge-type.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorMergeType = (props) => (
<SvgIcon {...props}>
<path d="M17 20.41L18.41 19 15 15.59 13.59 17 17 20.41zM7.5 8H11v5.59L5.59 19 7 20.41l6-6V8h3.5L12 3.5 7.5 8z"/>
</SvgIcon>
);
EditorMergeType = pure(EditorMergeType);
EditorMergeType.displayName = 'EditorMergeType';
EditorMergeType.muiName = 'SvgIcon';
export default EditorMergeType;
|
src/svg-icons/content/undo.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentUndo = (props) => (
<SvgIcon {...props}>
<path d="M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z"/>
</SvgIcon>
);
ContentUndo = pure(ContentUndo);
ContentUndo.displayName = 'ContentUndo';
ContentUndo.muiName = 'SvgIcon';
export default ContentUndo;
|
app/components/VersionCheckError.js | tidepool-org/chrome-uploader | /*
* == BSD2 LICENSE ==
* Copyright (c) 2016, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
* == BSD2 LICENSE ==
*/
import cx from 'classnames';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import ErrorMessages from '../constants/errorMessages';
import styles from '../../styles/components/VersionCheck.module.less';
import CloudOff from '@mui/icons-material/CloudOff';
const remote = require('@electron/remote');
const i18n = remote.getGlobal( 'i18n' );
export default class VersionCheckError extends Component {
static propTypes = {
errorMessage: PropTypes.string.isRequired,
errorText: PropTypes.object.isRequired
};
static defaultProps = {
errorText: {
CONNECT: i18n.t('Please check your connection, quit & relaunch to try again.'),
ERROR_DETAILS: i18n.t('Details for Tidepool\'s developers:'),
OFFLINE: i18n.t('You\'re not connected to the Internet.'),
SERVERS_DOWN: i18n.t('We can\'t connect to Tidepool right now.'),
TRY_AGAIN: i18n.t('Quit & relaunch the Uploader to try again.')
}
};
constructor(props) {
super(props);
}
render() {
const { errorMessage } = this.props;
const userErrorText = this.props.errorText;
const offline = errorMessage === ErrorMessages.E_OFFLINE;
const errorDetails = offline ? null : (
<div className={styles.error}>
<p className={styles.errorText}>{userErrorText.ERROR_DETAILS}</p>
<p className={styles.errorText}>{errorMessage}</p>
</div>
);
const firstLine = offline
? userErrorText.OFFLINE
: userErrorText.SERVERS_DOWN;
const secondLine = offline
? userErrorText.CONNECT
: userErrorText.TRY_AGAIN;
const versionCheckClass = cx({
[styles.failed]: !offline,
[styles.offline]: offline
});
return (
<div className={styles.modalWrap}>
<div className={styles.modal}>
<div className={versionCheckClass}>
<div className={styles.text}>
<CloudOff classes={{root: styles.icon}}/>
<p className={styles.lineOne}>{firstLine}</p>
<p className={styles.lineTwo}>{secondLine}</p>
</div>
{errorDetails}
</div>
</div>
</div>
);
}
}
|
actor-apps/app-web/src/app/components/common/AvatarItem.react.js | tsdl2013/actor-platform | import React from 'react';
import classNames from 'classnames';
class AvatarItem extends React.Component {
static propTypes = {
image: React.PropTypes.string,
placeholder: React.PropTypes.string.isRequired,
size: React.PropTypes.string,
title: React.PropTypes.string.isRequired
};
constructor(props) {
super(props);
}
render() {
const title = this.props.title;
const image = this.props.image;
const size = this.props.size;
let placeholder,
avatar;
let placeholderClassName = classNames('avatar__placeholder', `avatar__placeholder--${this.props.placeholder}`);
let avatarClassName = classNames('avatar', {
'avatar--tiny': size === 'tiny',
'avatar--small': size === 'small',
'avatar--medium': size === 'medium',
'avatar--big': size === 'big',
'avatar--huge': size === 'huge',
'avatar--square': size === 'square'
});
placeholder = <span className={placeholderClassName}>{title[0]}</span>;
if (image) {
avatar = <img alt={title} className="avatar__image" src={image}/>;
}
return (
<div className={avatarClassName}>
{avatar}
{placeholder}
</div>
);
}
}
export default AvatarItem;
|
src/table/rc-table-row.js | wisedu/bh-react | import React from 'react';
const TableRow = React.createClass({
propTypes: {
onDestroy: React.PropTypes.func,
record: React.PropTypes.object,
prefixCls: React.PropTypes.string,
},
componentWillUnmount() {
this.props.onDestroy(this.props.record);
},
render() {
const props = this.props;
const prefixCls = props.prefixCls;
const columns = props.columns;
const record = props.record;
const index = props.index;
const cells = [];
const expanded = props.expanded;
const expandable = props.expandable;
const expandIconAsCell = props.expandIconAsCell;
for (let i = 0; i < columns.length; i++) {
const col = columns[i];
const colClassName = col.className || '';
const render = col.render;
let text = record[col.dataIndex];
let expandIcon = null;
let tdProps;
let colSpan;
let rowSpan;
let notRender = false;
if (i === 0 && expandable) {
expandIcon = (<span
className={`${prefixCls}-expand-icon ${prefixCls}-${expanded ? 'expanded' : 'collapsed'}`}
onClick={props.onExpand.bind(null, !expanded, record)}/>);
}
if (expandIconAsCell && i === 0) {
cells.push(<td className={`${prefixCls}-expand-icon-cell`}
key="rc-table-expand-icon-cell">{expandIcon}</td>);
expandIcon = null;
}
if (render) {
text = render(text, record, index) || {};
tdProps = text.props || {};
if (!React.isValidElement(text) && 'children' in text) {
text = text.children;
}
rowSpan = tdProps.rowSpan;
colSpan = tdProps.colSpan;
}
if (rowSpan === 0 || colSpan === 0) {
notRender = true;
}
if (!notRender) {
cells.push(<td key={col.key} colSpan={colSpan} rowSpan={rowSpan} className={`${colClassName}`}>
{expandIcon}
{text}
</td>);
}
}
return (
<tr className={`${prefixCls} ${props.className}`} style={{display: props.visible ? '' : 'none'}}>{cells}</tr>);
},
});
export default TableRow;
|
src/index.js | yejodido/flux-sails-webpack-transform | import React from 'react';
import TodoApp from './components/environment/TodoApp';
React.render(<TodoApp />, document.getElementById('root'));
|
react-app/src/containers/AdminEditFormContainer.js | floodfx/gma-village | import React, { Component } from 'react';
import AdminForm from '../components/AdminForm';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import LoadingIndicator from '../components/LoadingIndicator';
import Alert from '../components/Alert';
import { ActionCreators } from '../actions';
class AdminEditFormContainer extends Component {
componentWillMount() {
const { authCookie, params } = this.props;
this.props.fetchAdmin(authCookie.account_kit_access_token, params.adminId);
}
componentWillUnmount() {
this.props.resetAdminUser();
this.props.resetUploadImage();
}
handleSubmit = (values) => {
delete values.profilePhoto; // remove profile photo from form (uploaded already)
const { authCookie } = this.props;
this.props.saveAdminUser(authCookie.account_kit_access_token, values);
}
handleFile = (e) => {
const image = e.target.files[0];
window.loadImage(
image, (canvas) => {
if(canvas.type === "error") {
console.log("Error loading image", image);
} else {
canvas.toBlob(
(blob) => {
this.props.preUploadImageRequest(blob);
},
image.type
);
}
},
{orientation: true}
)
}
render() {
const {saving, saved, admin, error, loading, profile_image_url} = this.props;
if(loading) {
return (
<LoadingIndicator text="Loading..." />
);
} else {
return (
<div>
{saved &&
<Alert type="success" heading="Success" text="Saved Admin." />
}
{error &&
<Alert type="danger" heading="Error" text={error} />
}
<AdminForm
heading="Edit Admin"
onSubmit={this.handleSubmit}
handleFile={this.handleFile}
saving={saving}
profile_image_url={profile_image_url || admin.profile_image_url}
profile_image_loading={this.props.profile_image_loading}
initialValues={admin}
/>
{saved &&
<Alert type="success" heading="Success" text="Saved Admin." />
}
</div>
)
}
}
}
AdminEditFormContainer.defaultProps = {
admin: undefined,
saving: false,
saved: false,
loading: true,
};
const mapStateToProps = (state) => {
const { auth, adminProfile, saveAdmin, uploadImage } = state
return {
authCookie: auth.cookie,
loading: adminProfile.loading,
saving: saveAdmin.saving,
error: saveAdmin.error,
admin: adminProfile.admin,
saved: saveAdmin.saved,
signed_url: uploadImage.signed_url,
profile_image_url: uploadImage.image_url,
profile_image_loading: uploadImage.loading
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(ActionCreators, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(AdminEditFormContainer)
|
src/containers/NotFound/NotFound.js | rkxtd/react-devops-kit | import React from 'react';
export default function NotFound() {
return (
<div className="container">
<h1>Doh! 404!</h1>
<p>These are <em>not</em> the droids you are looking for!</p>
</div>
);
}
|
src/component/Icon.js | dentemple/developer-portfolio | import React from 'react'
import logo from '../style/img/logo.svg'
const Icon = () => {
const style = {
backgroundColor: 'black'
}
return (
<img src={logo} style={style} className='Hero-logo' alt='logo' />
)
}
export default Icon
|
src/Project.js | johant87/do-it-front | import React from 'react';
import TaskList from './TaskList';
import jQuery from 'jquery';
import { Router, Route, Link, browserHistory } from 'react-router';
class Project extends React.Component {
constructor() {
super();
this.state = {
project: {}
};
}
updateProject(event) {
console.log("doing something")
let projectId = this.props.params.projectId;
let component = this;
let oldState = {
id: this.state.id,
title: this.state.title,
finished: this.state.finished
}
this.state.finished = true;
console.log("changing state!");
let changedState = {
finished: this.state.finished
}
let newState = jQuery.extend(oldState, changedState);
this.setState(newState);
jQuery.ajax({
type: "PUT",
url: "https://dry-shelf-45398.herokuapp.com/projects/" + projectId + ".json",
data: JSON.stringify({
project: newState
}),
contentType: "application/json",
dataType: "json"
})
.done(function(data) {
console.log(data);
component.setState({
id: data.project.id,
title: data.project.title,
finished: data.project.finished
});
})
.fail(function(error) {
console.log(error);
});
}
componentDidMount() {
this.fetchProject();
}
fetchProject() {
let projectId = this.props.params.projectId;
let component = this;
jQuery.getJSON(" https://dry-shelf-45398.herokuapp.com/projects/" + projectId + ".json", function(data) {
console.log(data);
component.setState({
project: data.project
});
});
}
render() {
return (
<div>
<div className="container">
<div className="row">
<div className="col-md-2"></div>
<div className="col-md-8 bg-dark no-gutter box-shadow">
<div className="projects border-radius">
<div className="project-items task-title-remove-padding">
<h2 className="margin-top margin-bottom"><span className="margin-right"><Link to="/" href="#"><i className="fa fa-chevron-left"></i></Link></span> {this.state.project.title}</h2>
</div>
</div>
</div>
<div className="col-md-2"></div>
</div>
</div>
<TaskList projectdone={this.state.project.finished}
projectFinished={this.updateProject} projectId={this.props.params.projectId} />
</div>
);
}
}
export default Project;
|
submissions/masiulis/src/components/components/components/sith-list-item.js | okmttdhr/flux-challenge | import React from 'react';
export default class extends React.Component {
static propTypes = {
name: React.PropTypes.string,
homeworld: React.PropTypes.string,
obiPlanet: React.PropTypes.string,
}
render() {
const textColor = this.props.homeworld === this.props.obiPlanet ? 'red' : '';
return (
<li className="css-slot" style={{color: textColor}}>
<h3>{this.props.name}</h3>
<h6>{this.props.homeworld && `Homeworld: ${this.props.homeworld}`}</h6>
</li>
)
}
}
|
packages/showcase/showcase-sections/radar-showcase.js | uber/react-vis | import React from 'react';
import {mapSection} from '../showcase-components/showcase-utils';
import {REACTVIS_BASE_URL} from '../showcase-links';
import {showCase} from '../index';
const {
AnimatedRadarChart,
BasicRadarChart,
FourQuadrantRadarChart,
RadarChartWithTooltips,
RadarChartSeriesTooltips
} = showCase;
const RADAR = [
{
name: 'Basic Radar Chart',
component: BasicRadarChart,
componentName: 'BasicRadarChart',
sourceLink: `${REACTVIS_BASE_URL}/radar-chart/index.js`,
docsLink:
'http://uber.github.io/react-vis/documentation/other-charts/radar-chart'
},
{
name: 'Animated Radar Chart',
component: AnimatedRadarChart,
componentName: 'AnimatedRadarChart'
},
{
name: 'Four Quadrant Radar Chart',
component: FourQuadrantRadarChart,
componentName: 'FourQuadrantRadarChart'
},
{
name: 'Radar Chart with Tooltips',
component: RadarChartWithTooltips,
componentName: 'RadarChartWithTooltips'
},
{
name: 'Radar Chart with Series Tooltips',
component: RadarChartSeriesTooltips,
componentName: 'RadarChartSeriesTooltips'
}
];
function RadarShowcase() {
return (
<article id="radar-charts">
<h1>Radar Chart</h1>
{RADAR.map(mapSection)}
</article>
);
}
export default RadarShowcase;
|
src/TabPane.js | dongtong/react-bootstrap | import React from 'react';
import deprecationWarning from './utils/deprecationWarning';
import Tab from './Tab';
const TabPane = React.createClass({
componentWillMount() {
deprecationWarning(
'TabPane', 'Tab',
'https://github.com/react-bootstrap/react-bootstrap/pull/1091'
);
},
render() {
return (
<Tab {...this.props} />
);
}
});
export default TabPane;
|
app/javascript/mastodon/features/notifications/components/notification.js | kibousoft/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import StatusContainer from '../../../containers/status_container';
import AccountContainer from '../../../containers/account_container';
import { FormattedMessage } from 'react-intl';
import Permalink from '../../../components/permalink';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { HotKeys } from 'react-hotkeys';
export default class Notification extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
notification: ImmutablePropTypes.map.isRequired,
hidden: PropTypes.bool,
onMoveUp: PropTypes.func.isRequired,
onMoveDown: PropTypes.func.isRequired,
onMention: PropTypes.func.isRequired,
};
handleMoveUp = () => {
const { notification, onMoveUp } = this.props;
onMoveUp(notification.get('id'));
}
handleMoveDown = () => {
const { notification, onMoveDown } = this.props;
onMoveDown(notification.get('id'));
}
handleOpen = () => {
const { notification } = this.props;
if (notification.get('status')) {
this.context.router.history.push(`/statuses/${notification.get('status')}`);
} else {
this.handleOpenProfile();
}
}
handleOpenProfile = () => {
const { notification } = this.props;
this.context.router.history.push(`/accounts/${notification.getIn(['account', 'id'])}`);
}
handleMention = e => {
e.preventDefault();
const { notification, onMention } = this.props;
onMention(notification.get('account'), this.context.router.history);
}
getHandlers () {
return {
moveUp: this.handleMoveUp,
moveDown: this.handleMoveDown,
open: this.handleOpen,
openProfile: this.handleOpenProfile,
mention: this.handleMention,
reply: this.handleMention,
};
}
renderFollow (account, link) {
return (
<HotKeys handlers={this.getHandlers()}>
<div className='notification notification-follow focusable' tabIndex='0'>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<i className='fa fa-fw fa-user-plus' />
</div>
<FormattedMessage id='notification.follow' defaultMessage='{name} followed you' values={{ name: link }} />
</div>
<AccountContainer id={account.get('id')} withNote={false} hidden={this.props.hidden} />
</div>
</HotKeys>
);
}
renderMention (notification) {
return (
<StatusContainer
id={notification.get('status')}
withDismiss
hidden={this.props.hidden}
onMoveDown={this.handleMoveDown}
onMoveUp={this.handleMoveUp}
/>
);
}
renderFavourite (notification, link) {
return (
<HotKeys handlers={this.getHandlers()}>
<div className='notification notification-favourite focusable' tabIndex='0'>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<i className='fa fa-fw fa-star star-icon' />
</div>
<FormattedMessage id='notification.favourite' defaultMessage='{name} favourited your status' values={{ name: link }} />
</div>
<StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={!!this.props.hidden} />
</div>
</HotKeys>
);
}
renderReblog (notification, link) {
return (
<HotKeys handlers={this.getHandlers()}>
<div className='notification notification-reblog focusable' tabIndex='0'>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<i className='fa fa-fw fa-retweet' />
</div>
<FormattedMessage id='notification.reblog' defaultMessage='{name} boosted your status' values={{ name: link }} />
</div>
<StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={this.props.hidden} />
</div>
</HotKeys>
);
}
render () {
const { notification } = this.props;
const account = notification.get('account');
const displayNameHtml = { __html: account.get('display_name_html') };
const link = <bdi><Permalink className='notification__display-name' href={account.get('url')} title={account.get('acct')} to={`/accounts/${account.get('id')}`} dangerouslySetInnerHTML={displayNameHtml} /></bdi>;
switch(notification.get('type')) {
case 'follow':
return this.renderFollow(account, link);
case 'mention':
return this.renderMention(notification);
case 'favourite':
return this.renderFavourite(notification, link);
case 'reblog':
return this.renderReblog(notification, link);
}
return null;
}
}
|
app/scripts/components/node-details/node-details-table-headers.js | hustbill/autorender-js | import React from 'react';
import { defaultSortDesc, getTableColumnsStyles } from '../../utils/node-details-utils';
import { NODE_DETAILS_TABLE_CW, NODE_DETAILS_TABLE_XS_LABEL } from '../../constants/styles';
export default class NodeDetailsTableHeaders extends React.Component {
handleClick(ev, headerId, currentSortedBy, currentSortedDesc) {
ev.preventDefault();
const header = this.props.headers.find(h => h.id === headerId);
const sortedBy = header.id;
const sortedDesc = sortedBy === currentSortedBy
? !currentSortedDesc : defaultSortDesc(header);
this.props.onClick(sortedBy, sortedDesc);
}
render() {
const { headers, sortedBy, sortedDesc } = this.props;
const colStyles = getTableColumnsStyles(headers);
return (
<tr>
{headers.map((header, index) => {
const headerClasses = ['node-details-table-header', 'truncate'];
const onClick = (ev) => {
this.handleClick(ev, header.id, sortedBy, sortedDesc);
};
// sort by first metric by default
const isSorted = header.id === sortedBy;
const isSortedDesc = isSorted && sortedDesc;
const isSortedAsc = isSorted && !isSortedDesc;
if (isSorted) {
headerClasses.push('node-details-table-header-sorted');
}
const style = colStyles[index];
const label =
(style.width === NODE_DETAILS_TABLE_CW.XS && NODE_DETAILS_TABLE_XS_LABEL[header.id]) ?
NODE_DETAILS_TABLE_XS_LABEL[header.id] : header.label;
return (
<td
className={headerClasses.join(' ')} style={style} onClick={onClick}
title={header.label} key={header.id}>
{isSortedAsc
&& <span className="node-details-table-header-sorter fa fa-caret-up" />}
{isSortedDesc
&& <span className="node-details-table-header-sorter fa fa-caret-down" />}
{label}
</td>
);
})}
</tr>
);
}
}
|
node_modules/semantic-ui-react/dist/es/collections/Form/FormTextArea.js | jessicaappelbaum/cljs-update | import _extends from 'babel-runtime/helpers/extends';
import React from 'react';
import { customPropTypes, getElementType, getUnhandledProps, META } from '../../lib';
import TextArea from '../../addons/TextArea';
import FormField from './FormField';
/**
* Sugar for <Form.Field control={TextArea} />
* @see Form
* @see TextArea
*/
function FormTextArea(props) {
var control = props.control;
var rest = getUnhandledProps(FormTextArea, props);
var ElementType = getElementType(FormTextArea, props);
return React.createElement(ElementType, _extends({}, rest, { control: control }));
}
FormTextArea.handledProps = ['as', 'control'];
FormTextArea._meta = {
name: 'FormTextArea',
parent: 'Form',
type: META.TYPES.COLLECTION
};
process.env.NODE_ENV !== "production" ? FormTextArea.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** A FormField control prop */
control: FormField.propTypes.control
} : void 0;
FormTextArea.defaultProps = {
as: FormField,
control: TextArea
};
export default FormTextArea; |
[JS-ES6][React] Raji client - second version/app/lib/containers/Series.js | datyayu/cemetery | import React from 'react';
import Header from '../components/header/Header';
import FilterList from '../components/filters/FilterList';
import SeriesList from '../components/series/SeriesList';
import {series as seriesArray} from '../../../db/series.json';
const Series = () =>
<div className="content">
<div className="Series">
<Header title="Series" search={false} />
<FilterList />
{
!seriesArray ?
<img src="/assets/img/spinner.gif" />
:
<SeriesList list={seriesArray}/>
}
</div>
</div>
;
export default Series;
|
src/components/App.js | nicholasbair/Perro-react | import React, { Component } from 'react';
import TopNav from './TopNav';
export default class App extends Component {
render() {
return (
<div>
<TopNav />
{this.props.children}
</div>
);
}
}
|
app/containers/ProfileText/components/education/index.js | ledminh/ledminh-home | import React from 'react';
import styled from 'styled-components';
import H1 from 'containers/ProfileText/h1';
import {
SECTION_EDUCATION,
PROFILE_NOW
} from 'containers/HomePage/constants';
import {about_me} from 'data';
import {renderEducation} from './utils';
const hidden = `
display: none;
`;
const show = `
display: block;
`;
const Style = styled.div`
${(props) => (props.current_section === SECTION_EDUCATION)? show : hidden}
`;
const Education = ({current_profile, current_section}) => (
<Style current_section={current_section}>
<H1 background={(current_profile === PROFILE_NOW)? '#494949' : '#3f5a84'}>EDUCATION</H1>
{renderEducation(about_me[current_profile].education)}
</Style>
);
export default Education;
|
lib/MultiColumnList/CellMeasurer.js | folio-org/stripes-components | import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import noop from 'lodash/noop';
class CellMeasurer extends React.Component {
static propTypes = {
children: PropTypes.node,
columnName: PropTypes.string,
onMeasure: PropTypes.func,
rowIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
shouldMeasure: PropTypes.bool,
widthCache: PropTypes.object,
}
static defaultProps = {
onMeasure: noop
}
componentDidMount() {
this.measureNode();
}
componentDidUpdate() {
this.measureNode();
}
element = React.createRef();
measureNode = () => {
const { widthCache, rowIndex, shouldMeasure, onMeasure, columnName } = this.props;
if (shouldMeasure) {
const elem = ReactDOM.findDOMNode(this); // eslint-disable-line react/no-find-dom-node
if (elem && elem.offsetParent !== null) {
const width = elem.offsetWidth;
widthCache.set(rowIndex, width);
if (onMeasure) onMeasure(rowIndex, columnName, width);
}
}
};
render() {
return this.props.children;
}
}
export default CellMeasurer;
|
node_modules/react-bootstrap/es/CarouselItem.js | acalabano/get-committed | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import TransitionEvents from './utils/TransitionEvents';
// TODO: This should use a timeout instead of TransitionEvents, or else just
// not wait until transition end to trigger continuing animations.
var propTypes = {
direction: PropTypes.oneOf(['prev', 'next']),
onAnimateOutEnd: PropTypes.func,
active: PropTypes.bool,
animateIn: PropTypes.bool,
animateOut: PropTypes.bool,
index: PropTypes.number
};
var defaultProps = {
active: false,
animateIn: false,
animateOut: false
};
var CarouselItem = function (_React$Component) {
_inherits(CarouselItem, _React$Component);
function CarouselItem(props, context) {
_classCallCheck(this, CarouselItem);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleAnimateOutEnd = _this.handleAnimateOutEnd.bind(_this);
_this.state = {
direction: null
};
_this.isUnmounted = false;
return _this;
}
CarouselItem.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.props.active !== nextProps.active) {
this.setState({ direction: null });
}
};
CarouselItem.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
var _this2 = this;
var active = this.props.active;
var prevActive = prevProps.active;
if (!active && prevActive) {
TransitionEvents.addEndEventListener(ReactDOM.findDOMNode(this), this.handleAnimateOutEnd);
}
if (active !== prevActive) {
setTimeout(function () {
return _this2.startAnimation();
}, 20);
}
};
CarouselItem.prototype.componentWillUnmount = function componentWillUnmount() {
this.isUnmounted = true;
};
CarouselItem.prototype.handleAnimateOutEnd = function handleAnimateOutEnd() {
if (this.isUnmounted) {
return;
}
if (this.props.onAnimateOutEnd) {
this.props.onAnimateOutEnd(this.props.index);
}
};
CarouselItem.prototype.startAnimation = function startAnimation() {
if (this.isUnmounted) {
return;
}
this.setState({
direction: this.props.direction === 'prev' ? 'right' : 'left'
});
};
CarouselItem.prototype.render = function render() {
var _props = this.props,
direction = _props.direction,
active = _props.active,
animateIn = _props.animateIn,
animateOut = _props.animateOut,
className = _props.className,
props = _objectWithoutProperties(_props, ['direction', 'active', 'animateIn', 'animateOut', 'className']);
delete props.onAnimateOutEnd;
delete props.index;
var classes = {
item: true,
active: active && !animateIn || animateOut
};
if (direction && active && animateIn) {
classes[direction] = true;
}
if (this.state.direction && (animateIn || animateOut)) {
classes[this.state.direction] = true;
}
return React.createElement('div', _extends({}, props, {
className: classNames(className, classes)
}));
};
return CarouselItem;
}(React.Component);
CarouselItem.propTypes = propTypes;
CarouselItem.defaultProps = defaultProps;
export default CarouselItem; |
client/modules/Post/__tests__/components/PostList.spec.js | thanhdatvo/tuoihoctro.react | import React from 'react';
import test from 'ava';
import { shallow } from 'enzyme';
import PostList from '../../components/Post/PostList';
const posts = [
{ name: 'Prashant', title: 'Hello Mern', slug: 'hello-mern', cuid: 'f34gb2bh24b24b2', content: "All cats meow 'mern!'" },
{ name: 'Mayank', title: 'Hi Mern', slug: 'hi-mern', cuid: 'f34gb2bh24b24b3', content: "All dogs bark 'mern!'" },
];
test('renders the list', t => {
const wrapper = shallow(
<PostList posts={posts} handleShowPost={() => {}} handleDeletePost={() => {}} />
);
t.is(wrapper.find('PostListItem').length, 2);
});
|
src/svg-icons/image/photo-filter.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImagePhotoFilter = (props) => (
<SvgIcon {...props}>
<path d="M19.02 10v9H5V5h9V3H5.02c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-9h-2zM17 10l.94-2.06L20 7l-2.06-.94L17 4l-.94 2.06L14 7l2.06.94zm-3.75.75L12 8l-1.25 2.75L8 12l2.75 1.25L12 16l1.25-2.75L16 12z"/>
</SvgIcon>
);
ImagePhotoFilter = pure(ImagePhotoFilter);
ImagePhotoFilter.displayName = 'ImagePhotoFilter';
ImagePhotoFilter.muiName = 'SvgIcon';
export default ImagePhotoFilter;
|
app/javascript/mastodon/components/radio_button.js | imas/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
export default class RadioButton extends React.PureComponent {
static propTypes = {
value: PropTypes.string.isRequired,
checked: PropTypes.bool,
name: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
label: PropTypes.node.isRequired,
};
render () {
const { name, value, checked, onChange, label } = this.props;
return (
<label className='radio-button'>
<input
name={name}
type='radio'
value={value}
checked={checked}
onChange={onChange}
/>
<span className={classNames('radio-button__input', { checked })} />
<span>{label}</span>
</label>
);
}
}
|
src/js/components/layout/statistics-modal.js | daniel-madera/pijs | import React from 'react'
import { observer, inject } from 'mobx-react'
import { Modal, Table, Button } from 'react-bootstrap'
@inject('userStore')
@observer
export default class StatisticsModal extends React.Component {
render() {
const { statistics } = this.props.userStore
return (
<Modal show={this.props.show} onHide={this.props.close} className='modal-large'>
<Modal.Header closeButton>
<h4>Moje úspěchy</h4>
</Modal.Header>
<Modal.Body>
{statistics &&
<div>
<Table responsive>
<tbody>
<tr>
<th>Počet mých zvládnutých slov</th><td>{statistics.user.mastered_words}</td>
</tr>
<tr>
<th>Počet unikátních mých zvládnutých slov</th><td>{statistics.user.mastered_unique_words}</td>
</tr>
{statistics.groups.map(g =>
<tr key={g.id}>
<th>Počet zvládnutých slov ve třídě {g.title}, zakladatel: {g.owner}</th><td>{g.mastered_words}</td>
</tr>
)}
</tbody>
</Table>
</div>
}
</Modal.Body>
<Modal.Footer>
<Button bsStyle="info" onClick={this.props.close}>Zavřít</Button>
</Modal.Footer>
</Modal>
);
}
}
|
src/components/SearchLayer/SearchLayer.js | MinisterioPublicoRJ/inLoco-2.0 | import React from 'react'
const SearchLayer = ({onSearchClick, onKeyUpSearch, onBtnCleanSearch, searchString}) => {
let input
var searchIconClass = 'search-layer--icon fa fa-'
var onIconClick = null
if (searchString !== undefined && searchString.length === 0) {
searchIconClass += 'search'
} else {
searchIconClass += 'close'
onIconClick = () => {
input.value = ''
onBtnCleanSearch()
}
}
const preventSubmit = (e) => {
e.preventDefault()
}
const inputField = node => {
input = node
if (node) {
node.focus()
}
}
const inputOnKeyUp = () => {
onKeyUpSearch(input.value)
}
const inputOnClick = () => {
onSearchClick()
}
return (
<form action="#" className="search-layer" onSubmit={preventSubmit}>
<label htmlFor="searchLayer" className="search-layer--title">
Ou pesquise por aqui:
<span className={searchIconClass} onClick={onIconClick}></span>
<input
type="text"
id="searchLayer"
ref={inputField}
onClick={inputOnClick}
onKeyUp={inputOnKeyUp}
className="search-layer--input"
placeholder="Ex.: Escolas"/>
</label>
</form>
)
}
export default SearchLayer
|
docs/src/app/components/pages/components/AppBar/ExampleIconMenu.js | ngbrown/material-ui | import React from 'react';
import AppBar from 'material-ui/AppBar';
import IconButton from 'material-ui/IconButton';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import NavigationClose from 'material-ui/svg-icons/navigation/close';
const AppBarExampleIconMenu = () => (
<AppBar
title="Title"
iconElementLeft={<IconButton><NavigationClose /></IconButton>}
iconElementRight={
<IconMenu
iconButtonElement={
<IconButton><MoreVertIcon /></IconButton>
}
targetOrigin={{horizontal: 'right', vertical: 'top'}}
anchorOrigin={{horizontal: 'right', vertical: 'top'}}
>
<MenuItem primaryText="Refresh" />
<MenuItem primaryText="Help" />
<MenuItem primaryText="Sign out" />
</IconMenu>
}
/>
);
export default AppBarExampleIconMenu;
|
src/containers/Forms/OtherInput/OtherInput.js | johnnycx127/react-demo | import React, { Component } from 'react';
import { Form, Select, InputNumber, DatePicker, TimePicker, Switch, Radio,
Cascader, Slider, Button, Col, Upload, Icon } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const areaData = [{
value: 'shanghai',
label: '上海',
children: [{
value: 'shanghaishi',
label: '上海市',
children: [{
value: 'pudongxinqu',
label: '浦东新区',
}],
}],
}];
class OtherInputForm extends Component {
handleSubmit = (e) => {
e.preventDefault();
console.log('收到表单值:', this.props.form.getFieldsValue());
}
normFile = (e) => {
if (Array.isArray(e)) {
return e;
}
return e && e.fileList;
}
render() {
const { getFieldProps } = this.props.form;
return (
<Form horizontal onSubmit={this.handleSubmit} >
<FormItem
label="InputNumber 数字输入框"
labelCol={{ span: 8 }}
wrapperCol={{ span: 10 }}
>
<InputNumber min={1} max={10} style={{ width: 100 }}
{...getFieldProps('inputNumber', { initialValue: 3 })}
/>
<span className="ant-form-text"> 台机器</span>
</FormItem>
<FormItem
label="我是标题"
labelCol={{ span: 8 }}
wrapperCol={{ span: 10 }}
>
<p className="ant-form-text" id="static" name="static">唧唧复唧唧木兰当户织呀</p>
<p className="ant-form-text">
<a href="#">链接文字</a>
</p>
</FormItem>
<FormItem
label="Switch 开关"
labelCol={{ span: 8 }}
wrapperCol={{ span: 10 }}
required
>
<Switch {...getFieldProps('switch', { valuePropName: 'checked' })} />
</FormItem>
<FormItem
label="Slider 滑动输入条"
labelCol={{ span: 8 }}
wrapperCol={{ span: 10 }}
required
>
<Slider marks={['A', 'B', 'C', 'D', 'E', 'F', 'G']} {...getFieldProps('slider')} />
</FormItem>
<FormItem
label="Select 选择器"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
required
>
<Select style={{ width: 200 }}
{...getFieldProps('select')}
>
<Option value="jack">jack</Option>
<Option value="lucy">lucy</Option>
<Option value="disabled" disabled>disabled</Option>
<Option value="yiminghe">yiminghe</Option>
</Select>
</FormItem>
<FormItem
label="级联选择"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
required
hasFeedback
>
<Cascader style={{ width: 200 }} options={areaData} {...getFieldProps('area')} />
</FormItem>
<FormItem
label="DatePicker 日期选择框"
labelCol={{ span: 8 }}
required
>
<Col span="6">
<FormItem>
<DatePicker {...getFieldProps('startDate')} />
</FormItem>
</Col>
<Col span="1">
<p className="ant-form-split">-</p>
</Col>
<Col span="6">
<FormItem>
<DatePicker {...getFieldProps('endDate')} />
</FormItem>
</Col>
</FormItem>
<FormItem
label="TimePicker 时间选择器"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
required
>
<TimePicker {...getFieldProps('time')} />
</FormItem>
<FormItem
label="选项"
labelCol={{ span: 8 }}
>
<RadioGroup {...getFieldProps('rg')}>
<RadioButton value="a">选项一</RadioButton>
<RadioButton value="b">选项二</RadioButton>
<RadioButton value="c">选项三</RadioButton>
</RadioGroup>
</FormItem>
<FormItem
label="logo图"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
help="提示信息要长长长长长长长长长长长长长长"
>
<Upload name="logo" action="/upload.do" listType="picture" onChange={this.handleUpload}
{...getFieldProps('upload', {
valuePropName: 'fileList',
normalize: this.normFile,
})}
>
<Button type="ghost">
<Icon type="upload" /> 点击上传
</Button>
</Upload>
</FormItem>
<FormItem wrapperCol={{ span: 16, offset: 8 }} style={{ marginTop: 24 }}>
<Button type="primary" htmlType="submit">确定</Button>
</FormItem>
</Form>
);
}
}
export default Form.create()(OtherInputForm);
|
src/demos/components/SvgChart.js | moarwick/react-mt-svg-lines | import React from 'react'
const SvgChart = () => {
return (
<svg viewBox="0 0 100 100">
<g strokeMiterlimit="10">
<path fill="none" stroke="#A6C3C9" d="M22.5 4v90"/>
<path fill="none" stroke="#A6C3C9" d="M5 22.5h90"/>
<path fill="none" stroke="#A6C3C9" d="M40.5 4v90"/>
<path fill="none" stroke="#A6C3C9" d="M5 40.5h90"/>
<path fill="none" stroke="#A6C3C9" d="M58.5 4v90"/>
<path fill="none" stroke="#A6C3C9" d="M5 58.5h90"/>
<path fill="none" stroke="#A6C3C9" d="M76.5 4v90"/>
<path fill="none" stroke="#A6C3C9" d="M5 76.5h90"/>
<path data-mt="skip" fill="none" stroke="#4B699A" strokeWidth="2" d="M4.5 4.5h90v90h-90z"/>
<path fill="#FBB03A" stroke="#8E542D" d="M15.5 52.5h12v33h-12z"/>
<path fill="#FBB03A" stroke="#8E542D" d="M34.5 34.5h12v51h-12z"/>
<path fill="#FBB03A" stroke="#8E542D" d="M51.5 38.5h12v47h-12z"/>
<path fill="#FBB03A" stroke="#8E542D" d="M70.5 17.5h12v68h-12z"/>
<path fill="none" stroke="#009245" strokeWidth="5" strokeLinecap="round" d="M10.2 78.6c6.9-12.5 23.1-21.3 37.2-25.5 17.4-5.1 33.8-9.8 40.2-30.2"/>
</g>
</svg>
)
}
export default SvgChart
|
src/interface/icons/GitHubMarkSmall.js | sMteX/WoWAnalyzer | import React from 'react';
// From the GitHub branding website.
const Icon = ({ ...other }) => (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1000" className="icon" {...other}>
<path d="M512 0C229.25 0 0 229.25 0 512c0 226.25 146.688 418.125 350.156 485.812 25.594 4.688 34.938-11.125 34.938-24.625 0-12.188-0.469-52.562-0.719-95.312C242 908.812 211.906 817.5 211.906 817.5c-23.312-59.125-56.844-74.875-56.844-74.875-46.531-31.75 3.53-31.125 3.53-31.125 51.406 3.562 78.47 52.75 78.47 52.75 45.688 78.25 119.875 55.625 149 42.5 4.654-33 17.904-55.625 32.5-68.375C304.906 725.438 185.344 681.5 185.344 485.312c0-55.938 19.969-101.562 52.656-137.406-5.219-13-22.844-65.094 5.062-135.562 0 0 42.938-13.75 140.812 52.5 40.812-11.406 84.594-17.031 128.125-17.219 43.5 0.188 87.312 5.875 128.188 17.281 97.688-66.312 140.688-52.5 140.688-52.5 28 70.531 10.375 122.562 5.125 135.5 32.812 35.844 52.625 81.469 52.625 137.406 0 196.688-119.75 240-233.812 252.688 18.438 15.875 34.75 47 34.75 94.75 0 68.438-0.688 123.625-0.688 140.5 0 13.625 9.312 29.562 35.25 24.562C877.438 930 1024 738.125 1024 512 1024 229.25 794.75 0 512 0z" />
</svg>
);
export default Icon;
|
app/javascript/mastodon/features/ui/components/link_footer.js | abcang/mastodon | import { connect } from 'react-redux';
import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage, defineMessages, injectIntl } from 'react-intl';
import { Link } from 'react-router-dom';
import { invitesEnabled, limitedFederationMode, version, repository, source_url } from 'mastodon/initial_state';
import { logOut } from 'mastodon/utils/log_out';
import { openModal } from 'mastodon/actions/modal';
const messages = defineMessages({
logoutMessage: { id: 'confirmations.logout.message', defaultMessage: 'Are you sure you want to log out?' },
logoutConfirm: { id: 'confirmations.logout.confirm', defaultMessage: 'Log out' },
});
const mapDispatchToProps = (dispatch, { intl }) => ({
onLogout () {
dispatch(openModal('CONFIRM', {
message: intl.formatMessage(messages.logoutMessage),
confirm: intl.formatMessage(messages.logoutConfirm),
closeWhenConfirm: false,
onConfirm: () => logOut(),
}));
},
});
export default @injectIntl
@connect(null, mapDispatchToProps)
class LinkFooter extends React.PureComponent {
static propTypes = {
withHotkeys: PropTypes.bool,
onLogout: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleLogoutClick = e => {
e.preventDefault();
e.stopPropagation();
this.props.onLogout();
return false;
}
render () {
const { withHotkeys } = this.props;
return (
<div className='getting-started__footer'>
<ul>
{invitesEnabled && <li><a href='/invites' target='_blank'><FormattedMessage id='getting_started.invite' defaultMessage='Invite people' /></a> · </li>}
{withHotkeys && <li><Link to='/keyboard-shortcuts'><FormattedMessage id='navigation_bar.keyboard_shortcuts' defaultMessage='Hotkeys' /></Link> · </li>}
<li><a href='/auth/edit'><FormattedMessage id='getting_started.security' defaultMessage='Security' /></a> · </li>
{!limitedFederationMode && <li><a href='/about/more' target='_blank'><FormattedMessage id='navigation_bar.info' defaultMessage='About this server' /></a> · </li>}
<li><a href='https://joinmastodon.org/apps' target='_blank'><FormattedMessage id='navigation_bar.apps' defaultMessage='Mobile apps' /></a> · </li>
<li><a href='/terms' target='_blank'><FormattedMessage id='getting_started.terms' defaultMessage='Terms of service' /></a> · </li>
<li><a href='/settings/applications' target='_blank'><FormattedMessage id='getting_started.developers' defaultMessage='Developers' /></a> · </li>
<li><a href='https://docs.joinmastodon.org' target='_blank'><FormattedMessage id='getting_started.documentation' defaultMessage='Documentation' /></a> · </li>
<li><a href='/auth/sign_out' onClick={this.handleLogoutClick}><FormattedMessage id='navigation_bar.logout' defaultMessage='Logout' /></a></li>
</ul>
<p>
<FormattedMessage
id='getting_started.open_source_notice'
defaultMessage='Mastodon is open source software. You can contribute or report issues on GitHub at {github}.'
values={{ github: <span><a href={source_url} rel='noopener noreferrer' target='_blank'>{repository}</a> (v{version})</span> }}
/>
</p>
</div>
);
}
};
|
js/Bugsnag.js | BarberHour/barber-hour | import React, { Component } from 'react';
import { Client } from 'bugsnag-react-native';
import { connect } from 'react-redux';
import { bugsnagKey } from './env';
class Bugsnag extends Component {
constructor(props) {
super(props);
this.client = new Client(bugsnagKey);
}
componentDidMount() {
var { user } = this.props;
if (user.isLoggedIn) {
this.client.setUser(user.token, user.name, user.email);
}
}
componentDidUpdate(prevProps) {
if (!prevProps.user.isLoggedIn && this.props.user.isLoggedIn) {
var { user } = this.props;
this.client.setUser(user.token, user.name, user.email);
} else if (prevProps.user.isLoggedIn && !this.props.user.isLoggedIn) {
this.client.setUser('', '', '');
}
}
render() {
return this.props.children;
}
}
function select(store) {
return {
user: store.user
};
}
export default connect(select)(Bugsnag);
|
js/jqwidgets/demos/react/app/complexinput/changeevent/app.js | luissancheza/sice | import React from 'react';
import ReactDOM from 'react-dom';
import JqxComplexInput from '../../../jqwidgets-react/react_jqxcomplexinput.js';
import JqxPanel from '../../../jqwidgets-react/react_jqxpanel.js';
class App extends React.Component {
componentDidMount() {
this.refs.myComplexInput.on('change', (event) => {
let args = event.args;
if (args) {
let value = args.value;
let oldValue = args.oldValue;
let realPart = args.realPart;
let imaginaryPart = args.imaginaryPart;
this.refs.myPanel.append('<strong>' + event.type + '</strong><br />' +
'value: ' + value + ', old value: ' + oldValue +
',<br /> real part: ' + realPart + ', imaginary part: ' + imaginaryPart + '<br />');
}
});
}
render() {
return (
<div>
<JqxComplexInput ref='myComplexInput'
width={300} height={25} value={'15 + 7i'} spinButtons={true}
/>
<div style={{ marginTop: 20 }}>Events log:</div>
<JqxPanel ref='myPanel' width={300} height={150} />
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/App.js | jefferydutra/TestableModularReactTalk | import React from 'react';
import AvailableCharacters from './Components/AvailableCharacters';
import MyFavoriteCharacters from './Components/MyFavoriteCharacters';
import FilterBar from './Components/FilterBar';
import SectionTitle from './Components/SectionTitle';
import getAvailableCharacters from './getAvailableCharacters';
import getCharacterWithUpdatedFavoriteSeries from './getCharacterWithUpdatedFavoriteSeries';
const availableCharacters = getAvailableCharacters();
require('./Styles/App.css');
const App = React.createClass({
propTypes: {
title: React.PropTypes.string.isRequired
},
getInitialState() {
return {
availableCharacters,
myFavoriteCharacters: {},
filteredAvailableCharacters: availableCharacters,
filterText: ''
};
},
onFilterTextChange(event) {
const filterText = event.target.value;
const filteredAvailableCharacters = this.state.availableCharacters.filter((character) =>
character.name.toLowerCase()
.indexOf(filterText) >= 0
);
this.setState({
filterText,
filteredAvailableCharacters
});
},
setAsFavoriteSeries(characterId, favoriteSeriesName) {
const myFavoriteCharacters = getCharacterWithUpdatedFavoriteSeries(
this.state.myFavoriteCharacters,
characterId,
favoriteSeriesName
);
this.setState({ myFavoriteCharacters });
},
addToFavoriteCharacters(character) {
const myFavoriteCharacters = Object.assign(
{},
this.state.myFavoriteCharacters,
{ [character.id]: character }
);
this.setState({ myFavoriteCharacters });
},
render() {
return (
<div>
<h1>{this.props.title}</h1>
<div className="container">
<div className="app">
<div className="app__menu">
<SectionTitle>
Available Characters
</SectionTitle>
<FilterBar
filterText={this.state.filterText}
title={this.props.title}
onFilterTextChange={this.onFilterTextChange}
/>
<AvailableCharacters
myFavoriteCharacters={this.state.myFavoriteCharacters}
addToFavoriteCharacters={this.addToFavoriteCharacters}
availableCharacters={this.state.filteredAvailableCharacters}
/>
</div>
<MyFavoriteCharacters
setAsFavoriteSeries={this.setAsFavoriteSeries}
myFavoriteCharacters={this.state.myFavoriteCharacters}
/>
</div>
</div>
</div>
);
}
});
export default App;
|
spec/javascripts/jsx/gradezilla/default_gradebook/components/GradebookSettingsModalSpec.js | venturehive/canvas-lms | /*
* Copyright (C) 2017 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react';
import { mount } from 'enzyme';
import GradebookSettingsModal from 'jsx/gradezilla/default_gradebook/components/GradebookSettingsModal';
import GradebookSettingsModalApi from 'jsx/gradezilla/default_gradebook/apis/GradebookSettingsModalApi';
import { destroyContainer } from 'jsx/shared/FlashAlert';
let clock;
QUnit.module('GradebookSettingsModal', {
setup () {
clock = sinon.useFakeTimers();
this.qunitTimeout = QUnit.config.testTimeout;
QUnit.config.testTimeout = 1000;
const applicationElement = document.createElement('div');
applicationElement.id = 'application';
document.getElementById('fixtures').appendChild(applicationElement);
},
mountComponent (customProps = {}) {
const defaultProps = {
courseId: '1',
locale: 'en',
newGradebookDevelopmentEnabled: true,
onClose () {},
gradedLateOrMissingSubmissionsExist: true,
onLatePolicyUpdate () {}
};
const props = { ...defaultProps, ...customProps };
this.wrapper = mount(<GradebookSettingsModal {...props} />);
return this.wrapper.get(0);
},
stubLatePolicyFetchSuccess (component, customData) {
const data = {
latePolicy: {
id: '15',
missingSubmissionDeductionEnabled: false,
missingSubmissionDeduction: 0,
lateSubmissionDeductionEnabled: false,
lateSubmissionDeduction: 0,
lateSubmissionInterval: 'day',
lateSubmissionMinimumPercentEnabled: false,
lateSubmissionMinimumPercent: 0,
...customData
}
};
const fetchSuccess = Promise.resolve({ data });
const promise = fetchSuccess.then(component.onFetchLatePolicySuccess)
this.stub(component, 'fetchLatePolicy').returns(promise);
return promise;
},
teardown () {
QUnit.config.testTimeout = this.qunitTimeout;
this.wrapper.unmount();
destroyContainer();
document.getElementById('fixtures').innerHTML = '';
clock.restore();
}
});
test('modal is initially closed', function () {
this.mountComponent();
equal(this.wrapper.find('Modal').prop('open'), false);
});
test('calling open causes the modal to be rendered', function () {
const component = this.mountComponent();
const fetchLatePolicy = this.stubLatePolicyFetchSuccess(component);
component.open();
return fetchLatePolicy.then(() => {
equal(this.wrapper.find('Modal').prop('open'), true);
});
});
test('calling close closes the modal', function () {
const component = this.mountComponent();
const fetchLatePolicy = this.stubLatePolicyFetchSuccess(component);
component.open();
return fetchLatePolicy.then(() => {
equal(this.wrapper.find('Modal').prop('open'), true, 'modal is open');
component.close();
equal(this.wrapper.find('Modal').prop('open'), false, 'modal is closed');
});
});
test('clicking cancel closes the modal', function () {
const component = this.mountComponent();
const fetchLatePolicy = this.stubLatePolicyFetchSuccess(component);
component.open();
clock.tick(50); // wait for Modal to transition open
return fetchLatePolicy.then(() => {
equal(this.wrapper.find('Modal').prop('open'), true);
document.getElementById('gradebook-settings-cancel-button').click();
equal(this.wrapper.find('Modal').prop('open'), false);
});
});
test('the "Update" button is disabled when the modal opens', function () {
const component = this.mountComponent();
const fetchLatePolicy = this.stubLatePolicyFetchSuccess(component);
component.open();
clock.tick(50); // wait for Modal to transition open
return fetchLatePolicy.then(() => {
const updateButton = document.getElementById('gradebook-settings-update-button')
ok(updateButton.getAttribute('aria-disabled'));
});
});
test('the "Update" button is enabled if a setting is changed', function () {
const component = this.mountComponent();
const fetchLatePolicy = this.stubLatePolicyFetchSuccess(component);
component.open();
clock.tick(50); // wait for Modal to transition open
return fetchLatePolicy.then(() => {
component.changeLatePolicy({ ...component.state.latePolicy, changes: { lateSubmissionDeductionEnabled: true } });
const updateButton = document.getElementById('gradebook-settings-update-button');
notOk(updateButton.getAttribute('aria-disabled'));
});
});
test('the "Update" button is disabled if a setting is changed, but there are validation errors', function () {
const component = this.mountComponent();
const fetchLatePolicy = this.stubLatePolicyFetchSuccess(component);
component.open();
clock.tick(50); // wait for Modal to transition open
return fetchLatePolicy.then(() => {
component.changeLatePolicy({
...component.state.latePolicy,
changes: { lateSubmissionDeductionEnabled: true },
validationErrors: { missingSubmissionDeduction: 'Missing submission percent must be numeric' }
});
const updateButton = document.getElementById('gradebook-settings-update-button');
ok(updateButton.getAttribute('aria-disabled'));
});
});
test('clicking "Update" sends a request to update the late policy', function () {
this.stub(GradebookSettingsModalApi, 'updateLatePolicy').returns(Promise.resolve());
const component = this.mountComponent();
const fetchLatePolicy = this.stubLatePolicyFetchSuccess(component);
component.open();
clock.tick(50); // wait for Modal to transition open
return fetchLatePolicy.then(() => {
const changes = { lateSubmissionDeductionEnabled: true };
component.changeLatePolicy({ ...component.state.latePolicy, changes });
const button = document.getElementById('gradebook-settings-update-button');
button.click();
equal(GradebookSettingsModalApi.updateLatePolicy.callCount, 1, 'updateLatePolicy is called once');
const changesArg = GradebookSettingsModalApi.updateLatePolicy.getCall(0).args[1];
propEqual(changesArg, changes, 'updateLatePolicy is called with the late policy changes');
});
});
test('clicking "Update" sends a post request to create a late policy if one does not yet exist', function () {
this.stub(GradebookSettingsModalApi, 'createLatePolicy').returns(Promise.resolve());
// When a late policy does not exist, the API call returns 'Not Found'
const component = this.mountComponent();
const fetchLatePolicy = this.stubLatePolicyFetchSuccess(component, { newRecord: true });
component.open();
clock.tick(50); // wait for Modal to transition open
return fetchLatePolicy.then(() => {
const changes = { lateSubmissionDeductionEnabled: true };
component.changeLatePolicy({ ...component.state.latePolicy, changes});
document.getElementById('gradebook-settings-update-button').click();
equal(GradebookSettingsModalApi.createLatePolicy.callCount, 1, 'createLatePolicy is called once');
const changesArg = GradebookSettingsModalApi.createLatePolicy.getCall(0).args[1];
propEqual(changesArg, changes, 'createLatePolicy is called with the late policy changes');
});
});
test('onUpdateLatePolicySuccess calls the onLatePolicyUpdate prop', function () {
const onLatePolicyUpdate = this.stub();
const component = this.mountComponent({ onLatePolicyUpdate });
component.onUpdateLatePolicySuccess();
strictEqual(onLatePolicyUpdate.callCount, 1);
});
|
public/js/15C.js | ritchieanesco/frontendmastersreact | /* Adding REDUX */
import React from 'react'
import { connect } from 'react-redux'
import ShowCard from './15D'
import Header from './15F'
const { arrayOf, shape, string } = React.PropTypes
// render () function call is called enhanced object literal e6 syntax
// es6 is not about writing function
const Search = React.createClass({
propTypes: {
shows: arrayOf(shape({
title: string,
description: string
})),
searchTerm: string
},
render () {
// showSearch without the value is short for showSearch={true}
return (
<div className='search'>
<Header showSearch />
{ /* <pre><code>{JSON.stringify(preload, null, 4)}</code></pre> */ }
<div>
{this.props.shows
.filter((show) => {
return `${show.title} ${show.description}`.toUpperCase().indexOf(this.props.searchTerm.toUpperCase()) >= 0
})
.map((show) => {
return (
<ShowCard key={show.imdbID} {...show} />
)
})
}
</div>
</div>
)
}
})
/* <ShowCard key={show.imdbID} show={show} /> {...show} spread passes in the specified object */
const mapStateToProps = (state) => {
return {
searchTerm: state.searchTerm
}
}
export default connect(mapStateToProps)(Search)
|
app/containers/LanguageProvider/index.js | ethanve/bakesale | /*
*
* LanguageProvider
*
* this component connects the redux state language locale to the
* IntlProvider component and i18n messages (loaded from `app/translations`)
*/
import React from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { IntlProvider } from 'react-intl';
import { selectLocale } from './selectors';
export class LanguageProvider extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<IntlProvider locale={this.props.locale} messages={this.props.messages[this.props.locale]}>
{React.Children.only(this.props.children)}
</IntlProvider>
);
}
}
LanguageProvider.propTypes = {
locale: React.PropTypes.string,
messages: React.PropTypes.object,
children: React.PropTypes.element.isRequired,
};
const mapStateToProps = createSelector(
selectLocale(),
(locale) => ({ locale })
);
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(LanguageProvider);
|
src/js/app.js | waagsociety/ams.datahub.client | import React from 'react'
import ReactDOM from 'react-dom'
import store from './store'
import Index from './pages'
ReactDOM.render(<Index store={store}/>, document.querySelector('#app')) |
src/components/Button.js | madox2/fortune-app | import React from 'react'
import {TouchableHighlight, Text, StyleSheet} from 'react-native'
export const Button = ({children, onPress, style}) => (
<TouchableHighlight
onPress={onPress}
style={[styles.button, style]}
underlayColor="#ddd">
<Text style={styles.label}>{children}</Text>
</TouchableHighlight>
)
const styles = StyleSheet.create({
button: {
padding: 14,
paddingRight: 20,
paddingLeft: 20,
flex: 1,
alignItems: 'center',
borderWidth: 1,
borderColor: 'silver',
},
label: {
fontSize: 18,
},
})
|
src/pages/App.js | GamerZUnited/GamerZUninted-FrontEnd | import React from 'react'
import {connect} from 'react-redux'
import {Router, Route, Link} from 'react-router'
import { Provider } from 'react-redux'
import invariant from 'invariant'
import {ReduxRouter} from 'redux-router'
import {load} from '../actions/AppActions'
import routes from '../routes'
class App extends React.Component {
componentWillMount() {
const {dispatch} = this.props
//example to load data
//dispatch(load())
}
renderRouter () {
return (
<ReduxRouter>
{routes}
</ReduxRouter>
);
}
render () {
return (
<Provider store={this.props.store}>
{this.renderRouter()}
</Provider>
);
}
}
export default App
|
entry_types/scrolled/package/src/frontend/inlineEditing/SectionDecorator.js | tf/pageflow | import React from 'react';
import classNames from 'classnames';
import styles from './SectionDecorator.module.css';
import contentElementStyles from './ContentElementDecorator.module.css';
import {Toolbar} from './Toolbar';
import {ForcePaddingContext} from '../Foreground';
import {useEditorSelection} from './EditorState';
import {MotifAreaVisibilityProvider} from '../MotifArea';
import {useI18n} from '../i18n';
import transitionIcon from './images/arrows.svg';
export function SectionDecorator(props) {
const {t} = useI18n({locale: 'ui'});
const {isSelected, select, resetSelection} = useEditorSelection({
id: props.id,
type: 'sectionSettings'
});
const transitionSelection = useEditorSelection({
id: props.id,
type: 'sectionTransition'
});
const nextTransitionSelection = useEditorSelection({
id: props.nextSection && props.nextSection.id,
type: 'sectionTransition'
});
const lastContentElement = props.contentElements[props.contentElements.length - 1];
const {isSelected: isLastContentElementSelected} = useEditorSelection({
id: lastContentElement && lastContentElement.id,
type: 'contentElement'
});
function selectIfOutsideContentItem(event) {
if (!event.target.closest(`.${contentElementStyles.wrapper}`)) {
isSelected ? resetSelection() : select();
}
}
return (
<div aria-label={t('pageflow_scrolled.inline_editing.select_section')}
className={className(isSelected, transitionSelection)}
onMouseDown={selectIfOutsideContentItem}>
<div className={styles.controls}>
{renderEditTransitionButton({id: props.previousSection && props.id,
selection: transitionSelection,
position: 'before'})}
{renderEditTransitionButton({id: props.nextSection && props.nextSection.id,
selection: nextTransitionSelection,
position: 'after'})}
</div>
<MotifAreaVisibilityProvider visible={isSelected}>
<ForcePaddingContext.Provider value={isLastContentElementSelected || isSelected}>
{props.children}
</ForcePaddingContext.Provider>
</MotifAreaVisibilityProvider>
</div>
);
}
function className(isSectionSelected, transitionSelection) {
return classNames(styles.wrapper, {
[styles.selected]: isSectionSelected,
[styles.transitionSelected]: transitionSelection.isSelected
});
}
function renderEditTransitionButton({id, position, selection}) {
if (!id) {
return null;
}
return (
<div className={styles[`transitionToolbar-${position}`]}>
<EditTransitionButton id={id}
selection={selection}
position={position} />
</div>
);
}
function EditTransitionButton({id, position, selection}) {
const {t} = useI18n({locale: 'ui'});
return (
<EditSectionButton id={id}
selection={selection}
text={t(`pageflow_scrolled.inline_editing.edit_section_transition_${position}`)}
icon={transitionIcon} />
);
}
function EditSectionButton({id, selection, icon, text}) {
return (
<Toolbar buttons={[{name: 'button', active: selection.isSelected, icon, text}]}
iconSize={20}
onButtonClick={() => selection.select()} />
);
}
|
app/components/TextPanel/theme/MediumEditor/index.js | Zurico/t7 | import blacklist from 'blacklist';
import React from 'react';
import ReactDOM from 'react-dom';
import MediumEditor from 'medium-editor';
export default class ReactMediumEditor extends React.Component {
static defaultProps = {
tag: 'div'
};
constructor(props) {
super(props);
this.state = {
text: this.props.text
};
}
componentDidMount() {
const dom = ReactDOM.findDOMNode(this);
this.medium = new MediumEditor(dom, this.props.options);
this.medium.subscribe('editableInput', (e) => {
this._updated = true;
this.change(dom.innerHTML);
});
}
componentDidUpdate() {
this.medium.restoreSelection();
}
componentWillUnmount() {
this.medium.destroy();
}
componentWillReceiveProps(nextProps) {
if (nextProps.text !== this.state.text && !this._updated) {
this.setState({ text: nextProps.text });
}
if (this._updated) this._updated = false;
}
render() {
const tag = this.props.tag;
const props = blacklist(this.props, 'options', 'text', 'tag', 'contentEditable', 'dangerouslySetInnerHTML');
Object.assign(props, {
dangerouslySetInnerHTML: { __html: this.state.text }
});
if (this.medium) {
this.medium.saveSelection();
}
return React.createElement(tag, props);
}
change(text) {
if (this.props.onChange) this.props.onChange(text, this.medium);
}
}
|
src/interface/App.js | fyruna/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { Route, Switch, withRouter } from 'react-router-dom';
import lazyLoadComponent from 'common/lazyLoadComponent';
import TooltipProvider from 'interface/common/TooltipProvider/index';
import retryingPromise from 'common/retryingPromise';
import { API_DOWN, clearError, INTERNET_EXPLORER, internetExplorerError, REPORT_NOT_FOUND, UNKNOWN_NETWORK_ISSUE } from 'interface/actions/error';
import { fetchUser } from 'interface/actions/user';
import { getError } from 'interface/selectors/error';
import { getOpenModals } from 'interface/selectors/openModals';
import ApiDownBackground from 'interface/common/images/api-down-background.gif';
import FullscreenError from 'interface/common/FullscreenError';
import makeAnalyzerUrl from 'interface/common/makeAnalyzerUrl';
import Footer from 'interface/layout/Footer/index';
import HomePage from 'interface/home/Page';
import ThunderSoundEffect from 'interface/audio/Thunder Sound effect.mp3';
import ReportPage from 'interface/report';
import PortalTarget from 'interface/PortalTarget';
import 'react-toggle/style.css';
import './layout/App.scss';
import Tracker from './Tracker';
import Hotkeys from './Hotkeys';
const CharacterParsesPage = lazyLoadComponent(() => retryingPromise(() => import(/* webpackChunkName: 'CharacterParsesPage' */ 'interface/character/Page').then(exports => exports.default)));
function isIE() {
const myNav = navigator.userAgent.toLowerCase();
return myNav.includes('msie') || myNav.includes('trident');
}
class App extends React.Component {
static propTypes = {
push: PropTypes.func.isRequired,
error: PropTypes.shape({
error: PropTypes.string.isRequired,
details: PropTypes.any,
}),
clearError: PropTypes.func.isRequired,
internetExplorerError: PropTypes.func.isRequired,
fetchUser: PropTypes.func.isRequired,
openModals: PropTypes.number.isRequired,
};
constructor(props) {
super(props);
if (isIE()) {
props.internetExplorerError();
}
TooltipProvider.load();
if (process.env.REACT_APP_FORCE_PREMIUM !== 'true') {
const initializeAds = () => {
(window.adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-8048055232081854",
enable_page_level_ads: true,
});
};
if (process.env.REACT_APP_FORCE_PREMIUM === 'false') {
// Force no premium, so skip user request (this is essential in development mode)
initializeAds();
} else {
// If Premium is forced (development environments), fetching the user would probably fail too
props.fetchUser().then(user => {
if (user === false || (user && !user.premium)) {
initializeAds();
}
});
}
}
}
renderError(error) {
if (error.error === API_DOWN) {
return (
<FullscreenError
error="The API is down."
details="This is usually because we're leveling up with another patch."
background={ApiDownBackground}
>
<div className="text-muted">
Aside from the great news that you'll be the first to experience something new that is probably going to pretty amazing, you'll probably also enjoy knowing that our updates usually only take about 10 seconds. So just <a href={window.location.href}>give it another try</a>.
</div>
{/* I couldn't resist */}
<audio autoPlay>
<source src={ThunderSoundEffect} />
</audio>
</FullscreenError>
);
}
if (error.error === REPORT_NOT_FOUND) {
return (
<FullscreenError
error="Report not found."
details="Either you entered a wrong report, or it is private."
background="https://media.giphy.com/media/DAgxA6qRfa5La/giphy.gif"
>
<div className="text-muted">
Private logs can not be used, if your guild has private logs you will have to <a href="https://www.warcraftlogs.com/help/start/">upload your own logs</a> or change the existing logs to the <i>unlisted</i> privacy option instead.
</div>
<div>
<button type="button" className="btn btn-primary" onClick={() => {
this.props.clearError();
this.props.push(makeAnalyzerUrl());
}}>
< Back
</button>
</div>
</FullscreenError>
);
}
if (error.error === UNKNOWN_NETWORK_ISSUE) {
return (
<FullscreenError
error="An API error occured."
details="Something went wrong talking to our servers, please try again."
background="https://media.giphy.com/media/m4TbeLYX5MaZy/giphy.gif"
>
<div className="text-muted">
{error.details.message}
</div>
<div>
<a className="btn btn-primary" href={window.location.href}>Refresh</a>
</div>
</FullscreenError>
);
}
if (error.error === INTERNET_EXPLORER) {
return (
<FullscreenError
error="A wild INTERNET EXPLORER appeared!"
details="This browser is too unstable for WoWAnalyzer to work properly."
background="https://media.giphy.com/media/njYrp176NQsHS/giphy.gif"
>
{/* Lower case the button so it doesn't seem to aggressive */}
<a className="btn btn-primary" href="http://outdatedbrowser.com/" style={{ textTransform: 'none' }}>Download a proper browser</a>
</FullscreenError>
);
}
return (
<FullscreenError
error="An unknown error occured."
details={error.details.message || error.details}
background="https://media.giphy.com/media/m4TbeLYX5MaZy/giphy.gif"
>
<div>
<button type="button" className="btn btn-primary" onClick={() => {
this.props.clearError();
this.props.push(makeAnalyzerUrl());
}}>
< Back
</button>
</div>
</FullscreenError>
);
}
renderContent() {
const { error } = this.props;
if (error) {
return this.renderError(error);
}
return (
<Switch>
<Route
path="/character/:region/:realm/:name"
render={({ match }) => (
<CharacterParsesPage
region={decodeURI(match.params.region.replace(/\+/g, ' ')).toUpperCase()}
realm={decodeURI(match.params.realm.replace(/\+/g, ' '))}
name={decodeURI(match.params.name.replace(/\+/g, ' '))}
/>
)}
/>
<Route
path="/report/:reportCode?/:fightId?/:player?/:resultTab?"
component={ReportPage}
/>
<Route component={HomePage} />
</Switch>
);
}
render() {
const { error, openModals } = this.props;
return (
<>
<div className={`app ${openModals > 0 ? 'modal-open' : ''}`}>
{this.renderContent()}
</div>
{!error && <Footer />}
<PortalTarget />
<Tracker />
<Hotkeys />
</>
);
}
}
const mapStateToProps = state => ({
error: getError(state),
openModals: getOpenModals(state),
});
const ConnectedComponent = connect(
mapStateToProps,
{
push,
clearError,
internetExplorerError,
fetchUser,
}
)(App);
// This needs the `withRouter` so its props change (causing a render) when the route changes
export default withRouter(ConnectedComponent);
|
src/index.js | bobinette/papernet-front | import React from 'react';
import ReactDOM from 'react-dom';
import { IndexRedirect, IndexRoute, Router, Route, browserHistory } from 'react-router';
// Redux
import { applyMiddleware, combineReducers, compose, createStore } from 'redux';
import thunkMiddleware from 'redux-thunk';
import createSagaMiddleware from 'redux-saga';
import { Provider } from 'react-redux';
// Toastr
import ReduxToastr, { reducer as toastrReducer } from 'react-redux-toastr';
// Init style before importing components
import 'style/base.scss';
import 'font-awesome/scss/font-awesome.scss';
import 'katex/dist/katex.min.css';
import 'react-redux-toastr/src/styles/index.scss';
import 'style/toastr.scss';
// App wrapper
import App from 'app';
// Paper page
import { PaperViewContainer, paperReducer } from 'paper';
// Profile page
import { ProfileContainer, profileReducer } from 'profile';
// Privacy policy
import { Privacy, TermsOfUse } from 'legal';
// Components
import Footer from 'components/footer';
// Scenes
import CronsScene, { cronsReducer } from 'scenes/crons';
import EditPaperScene, { editPaperReducer } from 'scenes/edit-paper';
import googleDriveReducer from 'scenes/edit-paper/components/google-drive-modal/api/reducer';
import HomeScene, { homeReducer } from 'scenes/home';
import ImportScene, { importsReducer } from 'scenes/imports';
import LoginScene, { GoogleLogin, loginReducer } from 'scenes/login';
import SearchScene, { searchReducer } from 'scenes/search';
// Reducers
import authReducer from 'services/auth/reducer';
// Sagas
import rootSaga from 'sagas';
// Create store
const reducers = {
auth: authReducer,
crons: cronsReducer,
editPaper: editPaperReducer,
googleDrive: googleDriveReducer,
home: homeReducer,
imports: importsReducer,
login: loginReducer,
paper: paperReducer,
profile: profileReducer,
search: searchReducer,
toastr: toastrReducer,
};
const reducer = combineReducers(reducers);
const sagaMiddleware = createSagaMiddleware();
const middlewares = compose(
applyMiddleware(thunkMiddleware),
applyMiddleware(sagaMiddleware),
window.devToolsExtension ? window.devToolsExtension() : f => f,
);
const store = createStore(reducer, middlewares);
sagaMiddleware.run(rootSaga);
ReactDOM.render(
<Provider store={store}>
<App>
<div className="Router">
<Router history={browserHistory}>
<Route path="/">
<IndexRedirect to="/papers" />
<Route path="papers" component={HomeScene} />
<Route path="papers/new" component={EditPaperScene} />
<Route path="papers/:id" component={PaperViewContainer} />
<Route path="papers/:id/edit" component={EditPaperScene} />
<Route path="login">
<IndexRoute component={LoginScene} />
<Route path="google" component={GoogleLogin} />
</Route>
<Route path="search" component={SearchScene} />
<Route path="search/crons" component={CronsScene} />
<Route path="imports" component={ImportScene} />
<Route path="privacy" component={Privacy} />
<Route path="terms-of-use" component={TermsOfUse} />
<Route path="profile" component={ProfileContainer} />
</Route>
</Router>
</div>
<Footer />
<ReduxToastr newestOnTop preventDuplicates timeOut={2000} transitionIn="fadeIn" transitionOut="fadeOut" />
</App>
</Provider>,
document.getElementById('app'),
);
|
views/invocation.js | JimLiu/black-screen | import React from 'react';
import Prompt from './prompt';
export default React.createClass({
componentWillMount() {
this.props.invocation
.on('data', _ => this.setState({canBeDecorated: this.props.invocation.canBeDecorated()}))
.on('status', status => this.setState({status: status}));
},
componentDidUpdate: scrollToBottom,
getInitialState() {
return {
status: this.props.invocation.status,
decorate: false,
canBeDecorated: false
};
},
render() {
if (this.state.canBeDecorated && this.state.decorate) {
var buffer = this.props.invocation.decorate();
} else {
buffer = this.props.invocation.getBuffer().render();
}
const classNames = 'invocation ' + this.state.status;
return (
<div className={classNames}>
<Prompt prompt={this.props.invocation.getPrompt()}
status={this.state.status}
invocation={this.props.invocation}
invocationView={this}/>
{buffer}
</div>
);
}
});
|
src/routes/UIElement/dropOption/index.js | 102010cncger/antd-admin | import React from 'react'
import { DropOption } from 'components'
import { Table, Row, Col, Card, message } from 'antd'
const DropOptionPage = () => (<div className="content-inner">
<Row gutter={32}>
<Col lg={8} md={12}>
<Card title="默认">
<DropOption menuOptions={[{ key: '1', name: '编辑' }, { key: '2', name: '删除' }]} />
</Card>
</Col>
<Col lg={8} md={12}>
<Card title="样式">
<DropOption menuOptions={[{ key: '1', name: '编辑' }, { key: '2', name: '删除' }]} buttonStyle={{ border: 'solid 1px #eee', width: 60 }} />
</Card>
</Col>
<Col lg={8} md={12}>
<Card title="事件">
<DropOption
menuOptions={[{ key: '1', name: '编辑' }, { key: '2', name: '删除' }]}
buttonStyle={{ border: 'solid 1px #eee', width: 60 }}
onMenuClick={({ key }) => {
switch (key) {
case '1':
message.success('点击了编辑')
break
case '2':
message.success('点击了删除')
break
default:
break
}
}}
/>
</Card>
</Col>
</Row>
<h2 style={{ margin: '16px 0' }}>Props</h2>
<Row>
<Col lg={18} md={24}>
<Table
rowKey={(record, key) => key}
pagination={false}
bordered
scroll={{ x: 800 }}
columns={[
{
title: '参数',
dataIndex: 'props',
},
{
title: '说明',
dataIndex: 'desciption',
},
{
title: '类型',
dataIndex: 'type',
},
{
title: '默认值',
dataIndex: 'default',
},
]}
dataSource={[
{
props: 'menuOptions',
desciption: '下拉操作的选项,格式为[{name:string,key:string}]',
type: 'Array',
default: '必选',
},
{
props: 'onMenuClick',
desciption: '点击 menuitem 调用此函数,参数为 {item, key, keyPath}',
type: 'Function',
default: '-',
},
{
props: 'buttonStyle',
desciption: '按钮的样式',
type: 'Object',
default: '-',
},
{
props: 'dropdownProps',
desciption: '下拉菜单的参数,可参考antd的【Dropdown】组件',
type: 'Object',
default: '-',
},
]}
/>
</Col>
</Row>
</div>)
export default DropOptionPage
|
src/components/views/groups/GroupTile.js | aperezdc/matrix-react-sdk | /*
Copyright 2017 Vector Creations Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import {MatrixClient} from 'matrix-js-sdk';
import { Draggable, Droppable } from 'react-beautiful-dnd';
import sdk from '../../../index';
import dis from '../../../dispatcher';
import FlairStore from '../../../stores/FlairStore';
function nop() {}
const GroupTile = React.createClass({
displayName: 'GroupTile',
propTypes: {
groupId: PropTypes.string.isRequired,
// Whether to show the short description of the group on the tile
showDescription: PropTypes.bool,
// Height of the group avatar in pixels
avatarHeight: PropTypes.number,
},
contextTypes: {
matrixClient: PropTypes.instanceOf(MatrixClient).isRequired,
},
getInitialState() {
return {
profile: null,
};
},
getDefaultProps() {
return {
showDescription: true,
avatarHeight: 50,
};
},
componentWillMount: function() {
FlairStore.getGroupProfileCached(this.context.matrixClient, this.props.groupId).then((profile) => {
this.setState({profile});
}).catch((err) => {
console.error('Error whilst getting cached profile for GroupTile', err);
});
},
onMouseDown: function(e) {
e.preventDefault();
dis.dispatch({
action: 'view_group',
group_id: this.props.groupId,
});
},
render: function() {
const BaseAvatar = sdk.getComponent('avatars.BaseAvatar');
const AccessibleButton = sdk.getComponent('elements.AccessibleButton');
const profile = this.state.profile || {};
const name = profile.name || this.props.groupId;
const avatarHeight = this.props.avatarHeight;
const descElement = this.props.showDescription ?
<div className="mx_GroupTile_desc">{ profile.shortDescription }</div> :
<div />;
const httpUrl = profile.avatarUrl ? this.context.matrixClient.mxcUrlToHttp(
profile.avatarUrl, avatarHeight, avatarHeight, "crop",
) : null;
// XXX: Use onMouseDown as a workaround for https://github.com/atlassian/react-beautiful-dnd/issues/273
// instead of onClick. Otherwise we experience https://github.com/vector-im/riot-web/issues/6156
return <AccessibleButton className="mx_GroupTile" onMouseDown={this.onMouseDown} onClick={nop}>
<Droppable droppableId="my-groups-droppable" type="draggable-TagTile">
{ (droppableProvided, droppableSnapshot) => (
<div ref={droppableProvided.innerRef}>
<Draggable
key={"GroupTile " + this.props.groupId}
draggableId={"GroupTile " + this.props.groupId}
index={this.props.groupId}
type="draggable-TagTile"
>
{ (provided, snapshot) => (
<div>
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
<div className="mx_GroupTile_avatar">
<BaseAvatar
name={name}
idName={this.props.groupId}
url={httpUrl}
width={avatarHeight}
height={avatarHeight} />
</div>
</div>
{ /* Instead of a blank placeholder, use a copy of the avatar itself. */ }
{ provided.placeholder ?
<div className="mx_GroupTile_avatar">
<BaseAvatar
name={name}
idName={this.props.groupId}
url={httpUrl}
width={avatarHeight}
height={avatarHeight} />
</div> :
<div />
}
</div>
) }
</Draggable>
</div>
) }
</Droppable>
<div className="mx_GroupTile_profile">
<div className="mx_GroupTile_name">{ name }</div>
{ descElement }
<div className="mx_GroupTile_groupId">{ this.props.groupId }</div>
</div>
</AccessibleButton>;
},
});
export default GroupTile;
|
src/components/Modal/ModalHeader.js | propertybase/react-lds | import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import { IconButton, ButtonIcon } from '../Button';
import { THEMES, getThemeClass } from '../../utils';
const ModalHeader = (props) => {
const {
id, onClose, theme, title, tagline
} = props;
const isEmpty = !tagline && !title;
return (
<header
className={cx(
'slds-modal__header',
{ 'slds-modal__header_empty': isEmpty },
...getThemeClass(theme),
)}
>
{onClose && (
<IconButton
className="slds-modal__close"
flavor="inverse"
onClick={onClose}
tabIndex={0}
>
<ButtonIcon
sprite="utility"
icon="close"
size="large"
/>
</IconButton>
)}
{title && (
<h2
className="slds-text-heading_medium slds-hyphenate"
id={id}
>
{title}
</h2>
)}
{tagline && <p className="slds-m-top_x-small">{tagline}</p>}
</header>
);
};
ModalHeader.defaultProps = {
id: null,
onClose: null,
title: null,
tagline: null,
theme: null,
};
ModalHeader.propTypes = {
id: PropTypes.string,
onClose: PropTypes.func,
theme: PropTypes.oneOf(THEMES),
title: PropTypes.string,
tagline: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
};
export default ModalHeader;
|
src/svg-icons/action/shopping-basket.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionShoppingBasket = (props) => (
<SvgIcon {...props}>
<path d="M17.21 9l-4.38-6.56c-.19-.28-.51-.42-.83-.42-.32 0-.64.14-.83.43L6.79 9H2c-.55 0-1 .45-1 1 0 .09.01.18.04.27l2.54 9.27c.23.84 1 1.46 1.92 1.46h13c.92 0 1.69-.62 1.93-1.46l2.54-9.27L23 10c0-.55-.45-1-1-1h-4.79zM9 9l3-4.4L15 9H9zm3 8c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>
</SvgIcon>
);
ActionShoppingBasket = pure(ActionShoppingBasket);
ActionShoppingBasket.displayName = 'ActionShoppingBasket';
ActionShoppingBasket.muiName = 'SvgIcon';
export default ActionShoppingBasket;
|
frontend/src/courses/components/navigation/index.js | OptimusCrime/youkok2 | import React from 'react';
import {calculateRelativeButtons} from "../../utilities";
import {RELATIVE_BUTTONS_LEFT, RELATIVE_BUTTONS_RIGHT} from "../../constants";
export const Navigation = ({position, page, numberOfPages, changePage}) => (
<div className={`courses-navigation courses-navigation-${position}`} role="toolbar">
<div
className={`courses-navigation__group courses-navigation__group--left ${page === 0 ? 'courses-navigation__group--hidden' : ''}`}
role="group"
>
<NavigationButton page={0} changePage={changePage}>
<i className="fa fa-angle-double-left" aria-hidden="true"/>
</NavigationButton>
<NavigationButton page={page - 1} changePage={changePage}>
<i className="fa fa-angle-left" aria-hidden="true"/>
</NavigationButton>
</div>
<div className="courses-navigation__group courses-navigation__group--center" role="group">
{numberOfPages > 0 &&
<NavigationRelativeButtons
page={page}
numberOfPages={numberOfPages}
changePage={changePage}
/>
}
</div>
<div
className={`courses-navigation__group courses-navigation__group--right ${(page === numberOfPages) ? 'courses-navigation__group--hidden' : ''}`}
role="group"
>
<NavigationButton page={page + 1} changePage={changePage}>
<i className="fa fa-angle-right" aria-hidden="true"/>
</NavigationButton>
<NavigationButton page={numberOfPages} changePage={changePage}>
<i className="fa fa-angle-double-right" aria-hidden="true"/>
</NavigationButton>
</div>
</div>
);
const NavigationRelativeButtons = ({ page, numberOfPages, changePage }) => {
const buttons = [];
// Left side
buttons.push(calculateRelativeButtons(page, numberOfPages, RELATIVE_BUTTONS_LEFT)
.map(page =>
<NavigationButton
page={page}
changePage={changePage}
key={page}
>
{page + 1}
</NavigationButton>
));
// Current page
buttons.push(
<NavigationButton
page={page}
changePage={changePage}
disabled={true}
key={page}
>
{page + 1}
</NavigationButton>
);
// Right side
buttons.push(calculateRelativeButtons(page, numberOfPages, RELATIVE_BUTTONS_RIGHT)
.map(page =>
<NavigationButton
page={page}
changePage={changePage}
key={page}
>
{page + 1}
</NavigationButton>
));
return buttons;
};
const NavigationButton = ({children, page, changePage, disabled = false}) => (
<button
type="button"
className="btn"
disabled={disabled}
onClick={() => {
if (!disabled) {
changePage(page);
}
}}
>
{children}
</button>
);
|
examples/shared-root/app.js | clloyd/react-router | import React from 'react'
import { createHistory, useBasename } from 'history'
import { Router, Route, Link } from 'react-router'
const history = useBasename(createHistory)({
basename: '/shared-root'
})
class App extends React.Component {
render() {
return (
<div>
<p>
This illustrates how routes can share UI w/o sharing the URL.
When routes have no path, they never match themselves but their
children can, allowing "/signin" and "/forgot-password" to both
be render in the <code>SignedOut</code> component.
</p>
<ol>
<li><Link to="/home" activeClassName="active">Home</Link></li>
<li><Link to="/signin" activeClassName="active">Sign in</Link></li>
<li><Link to="/forgot-password" activeClassName="active">Forgot Password</Link></li>
</ol>
{this.props.children}
</div>
)
}
}
class SignedIn extends React.Component {
render() {
return (
<div>
<h2>Signed In</h2>
{this.props.children}
</div>
)
}
}
class Home extends React.Component {
render() {
return (
<h3>Welcome home!</h3>
)
}
}
class SignedOut extends React.Component {
render() {
return (
<div>
<h2>Signed Out</h2>
{this.props.children}
</div>
)
}
}
class SignIn extends React.Component {
render() {
return (
<h3>Please sign in.</h3>
)
}
}
class ForgotPassword extends React.Component {
render() {
return (
<h3>Forgot your password?</h3>
)
}
}
React.render((
<Router history={history}>
<Route path="/" component={App}>
<Route component={SignedOut}>
<Route path="signin" component={SignIn} />
<Route path="forgot-password" component={ForgotPassword} />
</Route>
<Route component={SignedIn}>
<Route path="home" component={Home} />
</Route>
</Route>
</Router>
), document.getElementById('example'))
|
app/javascript/mastodon/features/directory/components/account_card.js | masto-donte-com-br/mastodon | import React from 'react';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { makeGetAccount } from 'mastodon/selectors';
import Avatar from 'mastodon/components/avatar';
import DisplayName from 'mastodon/components/display_name';
import Permalink from 'mastodon/components/permalink';
import Button from 'mastodon/components/button';
import { FormattedMessage, injectIntl, defineMessages } from 'react-intl';
import { autoPlayGif, me, unfollowModal } from 'mastodon/initial_state';
import ShortNumber from 'mastodon/components/short_number';
import {
followAccount,
unfollowAccount,
unblockAccount,
unmuteAccount,
} from 'mastodon/actions/accounts';
import { openModal } from 'mastodon/actions/modal';
import classNames from 'classnames';
const messages = defineMessages({
unfollow: { id: 'account.unfollow', defaultMessage: 'Unfollow' },
follow: { id: 'account.follow', defaultMessage: 'Follow' },
cancel_follow_request: { id: 'account.cancel_follow_request', defaultMessage: 'Cancel follow request' },
requested: { id: 'account.requested', defaultMessage: 'Awaiting approval. Click to cancel follow request' },
unblock: { id: 'account.unblock_short', defaultMessage: 'Unblock' },
unmute: { id: 'account.unmute_short', defaultMessage: 'Unmute' },
unfollowConfirm: { id: 'confirmations.unfollow.confirm', defaultMessage: 'Unfollow' },
edit_profile: { id: 'account.edit_profile', defaultMessage: 'Edit profile' },
});
const makeMapStateToProps = () => {
const getAccount = makeGetAccount();
const mapStateToProps = (state, { id }) => ({
account: getAccount(state, id),
});
return mapStateToProps;
};
const mapDispatchToProps = (dispatch, { intl }) => ({
onFollow(account) {
if (
account.getIn(['relationship', 'following']) ||
account.getIn(['relationship', 'requested'])
) {
if (unfollowModal) {
dispatch(
openModal('CONFIRM', {
message: (
<FormattedMessage
id='confirmations.unfollow.message'
defaultMessage='Are you sure you want to unfollow {name}?'
values={{ name: <strong>@{account.get('acct')}</strong> }}
/>
),
confirm: intl.formatMessage(messages.unfollowConfirm),
onConfirm: () => dispatch(unfollowAccount(account.get('id'))),
}),
);
} else {
dispatch(unfollowAccount(account.get('id')));
}
} else {
dispatch(followAccount(account.get('id')));
}
},
onBlock(account) {
if (account.getIn(['relationship', 'blocking'])) {
dispatch(unblockAccount(account.get('id')));
}
},
onMute(account) {
if (account.getIn(['relationship', 'muting'])) {
dispatch(unmuteAccount(account.get('id')));
}
},
});
export default
@injectIntl
@connect(makeMapStateToProps, mapDispatchToProps)
class AccountCard extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
intl: PropTypes.object.isRequired,
onFollow: PropTypes.func.isRequired,
onBlock: PropTypes.func.isRequired,
onMute: PropTypes.func.isRequired,
};
handleMouseEnter = ({ currentTarget }) => {
if (autoPlayGif) {
return;
}
const emojis = currentTarget.querySelectorAll('.custom-emoji');
for (var i = 0; i < emojis.length; i++) {
let emoji = emojis[i];
emoji.src = emoji.getAttribute('data-original');
}
}
handleMouseLeave = ({ currentTarget }) => {
if (autoPlayGif) {
return;
}
const emojis = currentTarget.querySelectorAll('.custom-emoji');
for (var i = 0; i < emojis.length; i++) {
let emoji = emojis[i];
emoji.src = emoji.getAttribute('data-static');
}
}
handleFollow = () => {
this.props.onFollow(this.props.account);
};
handleBlock = () => {
this.props.onBlock(this.props.account);
};
handleMute = () => {
this.props.onMute(this.props.account);
}
handleEditProfile = () => {
window.open('/settings/profile', '_blank');
}
render() {
const { account, intl } = this.props;
let actionBtn;
if (me !== account.get('id')) {
if (!account.get('relationship')) { // Wait until the relationship is loaded
actionBtn = '';
} else if (account.getIn(['relationship', 'requested'])) {
actionBtn = <Button className={classNames('logo-button')} text={intl.formatMessage(messages.cancel_follow_request)} title={intl.formatMessage(messages.requested)} onClick={this.handleFollow} />;
} else if (account.getIn(['relationship', 'muting'])) {
actionBtn = <Button className='logo-button' text={intl.formatMessage(messages.unmute)} onClick={this.handleMute} />;
} else if (!account.getIn(['relationship', 'blocking'])) {
actionBtn = <Button disabled={account.getIn(['relationship', 'blocked_by'])} className={classNames('logo-button', { 'button--destructive': account.getIn(['relationship', 'following']) })} text={intl.formatMessage(account.getIn(['relationship', 'following']) ? messages.unfollow : messages.follow)} onClick={this.handleFollow} />;
} else if (account.getIn(['relationship', 'blocking'])) {
actionBtn = <Button className='logo-button' text={intl.formatMessage(messages.unblock)} onClick={this.handleBlock} />;
}
} else {
actionBtn = <Button className='logo-button' text={intl.formatMessage(messages.edit_profile)} onClick={this.handleEditProfile} />;
}
return (
<div className='account-card'>
<Permalink href={account.get('url')} to={`/@${account.get('acct')}`} className='account-card__permalink'>
<div className='account-card__header'>
<img
src={
autoPlayGif ? account.get('header') : account.get('header_static')
}
alt=''
/>
</div>
<div className='account-card__title'>
<div className='account-card__title__avatar'><Avatar account={account} size={56} /></div>
<DisplayName account={account} />
</div>
</Permalink>
{account.get('note').length > 0 && (
<div
className='account-card__bio translate'
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
dangerouslySetInnerHTML={{ __html: account.get('note_emojified') }}
/>
)}
<div className='account-card__actions'>
<div className='account-card__counters'>
<div className='account-card__counters__item'>
<ShortNumber value={account.get('statuses_count')} />
<small>
<FormattedMessage id='account.posts' defaultMessage='Posts' />
</small>
</div>
<div className='account-card__counters__item'>
<ShortNumber value={account.get('followers_count')} />{' '}
<small>
<FormattedMessage
id='account.followers'
defaultMessage='Followers'
/>
</small>
</div>
<div className='account-card__counters__item'>
<ShortNumber value={account.get('following_count')} />{' '}
<small>
<FormattedMessage
id='account.following'
defaultMessage='Following'
/>
</small>
</div>
</div>
<div className='account-card__actions__button'>
{actionBtn}
</div>
</div>
</div>
);
}
}
|
NewsDemoNavTab/Component/ZPScorllView.js | HAPENLY/ReactNative-Source-code-Demo | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
ScrollView,
Image,
} from 'react-native';
//引入Dimensions
var Dimensions = require('Dimensions');
var {width}= Dimensions.get('window');
//引入计时器类库
var TimerMixin = require('react-timer-mixin');
//引入Json数据
// var ImageData = require('./ImageData.json');
//ES5中实现
var ZPScrollView = React.createClass({
//设置定时器
mixins:[TimerMixin],
//设置可变的和初始值
getInitialState(){
return{
//当前的页码
currentPage:0,
//设置标题
title:this.props.ImageDataArr[0].title,
}
},
//设置固定值
getDefaultProps(){
return{
//每个多少时间
time :1000,
// 所有的Image对象数组
ImageDataArr:[],
}
},
render(){
return(
<View style={styles.container}>
{/*添加ScrollView*/}
<ScrollView
//绑定一下scrollView 方便下文获取
ref="scrollView"
//设置是否水平排
horizontal={true}
//是否自动翻页
pagingEnabled={true}
//隐藏滚动条
showsHorizontalScrollIndicator={false}
//当一帧滚动结束的时候调用(重写系统的onAnimationEnd函数)
onMomentumScrollEnd = {(e) =>this.onAnimationEnd(e)}
//开始拖拽的时候调用
onScrollBeginDrag = {()=>this.onScrollBeginDrag()}
//停止拖拽的时候调用
onScrollEndDrag ={this.onScrollEndDrag}
>
{this.renderAllImage()}
</ScrollView>
{/*返回五个焦点指示器*/}
<View style={styles.PageViewStyle}>
{/*返回对应的标题*/}
<Text style={{color:'white'}}>{this.state.title}</Text>
<View style={{flexDirection:'row'}}>
{/*返回五个圆点*/}
{this.renderPagerCircle()}
</View>
</View>
</View>
)
},
//调用开始拖拽
onScrollBeginDrag(){
this.clearInterval(this.timer);
},
//停止拖拽的时候调用
onScrollEndDrag(){
this.startTime();
},
//实现一些复杂操作
componentDidMount(){
//开始定时器
this.startTime();
},
//开启定时器
startTime(){
//1.拿到scrollView
var scrollView = this.refs.scrollView;
var imgcount = this.props.ImageDataArr.length;
//2.添加定时器
this.timer = this.setInterval(function(){
//console.log('1');
//2.1设置圆点
//定义临时变量,记入当前页码
var activePage;
//2.2判断
if((this.state.currentPage+1)>=imgcount){
//越界
activePage = 0;
}else {
activePage = this.state.currentPage+1;
}
//2.3 更新状态机
this.setState({
currentPage:activePage
});
//2.4让scrollView滚动起来
var offSerx = activePage * width;
scrollView.scrollResponderScrollTo({x:offSerx,y:0,animated:true});
},this.props.time)
},
//返回所有的图片
renderAllImage(){
//定义图片数组
var allImage = [];
//拿到图像上数组
var imagesArr= this.props.ImageDataArr;
for(var i=0;i<imagesArr.length;i++){
//去除单独的对象
var imgItem = imagesArr[i];
// console.log(imgItem);
// debugger;
//创建组件装入数组
allImage.push(
<Image key={i} source={{uri:imgItem.imgsrc}} style={{width:width,height:120}}/>
);
}
return allImage;
},
//返回所有圆点
renderPagerCircle(){
//定义数字放置所有圆点
var indicatorArr = [];
//自定义一个样式用来判断是否是当前页
var style ;
//拿到图像上数组
var imagesArr= this.props.ImageDataArr;
console.log(imagesArr);
//遍历所有的数据
for(var i=0;i<imagesArr.length;i++){
style = (i===this.state.currentPage)? {color:'orange'} :{color:'#ffffff'};
//把圆点装入数组(&bull: 特殊转义字符就是一个点)
//如果想放置两个样式的话格式是:style={[style,style]}
indicatorArr.push(
<Text key={i} style={[{fontSize:25},style]}>•</Text>
)
}
return indicatorArr;
},
//实现当一帧滚动结束的时候调用
onAnimationEnd(e){
//1.首先求出水平方向的偏移量
var offSetX = e.nativeEvent.contentOffset.x;
//2.求出当前的页数Math.floor:用于取正数值
var currentPage =Math.floor(offSetX / width);
console.log(currentPage);
//3.更新状态机,重新绘制UI
this.setState({
//当前的页码
currentPage:currentPage,
title:this.props.ImageDataArr[currentPage].title,
})
},
});
const styles = StyleSheet.create({
container: {
// marginTop:25,
},
PageViewStyle:{
width:width,
height:25,
backgroundColor:'rgba(0,0,0,0.4)',
//绝对定位
position:'absolute',
bottom:0,
//设置株主轴的方向
flexDirection:'row',
//设置侧轴方向的对齐方式
alignItems:'center',
//设置主轴的对齐方式(将标题和圆点两端对齐)
justifyContent:'space-between'
}
});
//输出
module.exports = ZPScrollView; |
blueocean-material-icons/src/js/components/svg-icons/image/center-focus-weak.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ImageCenterFocusWeak = (props) => (
<SvgIcon {...props}>
<path d="M5 15H3v4c0 1.1.9 2 2 2h4v-2H5v-4zM5 5h4V3H5c-1.1 0-2 .9-2 2v4h2V5zm14-2h-4v2h4v4h2V5c0-1.1-.9-2-2-2zm0 16h-4v2h4c1.1 0 2-.9 2-2v-4h-2v4zM12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>
</SvgIcon>
);
ImageCenterFocusWeak.displayName = 'ImageCenterFocusWeak';
ImageCenterFocusWeak.muiName = 'SvgIcon';
export default ImageCenterFocusWeak;
|
src/component/hero-container/index.js | arn1313/kritter-frontend | import React from 'react';
import ReactDOM from 'react-dom';
import scrollToComponent from 'react-scroll-to-component';
import './_heroContainer.scss';
import img from '../../img/Kritter.png';
import AuthForm from '../auth-form';
import SignUpForm from '../sign-up-form'
import { signupRequest, loginRequest, userFetchRequest } from '../../action/auth-actions';
import { stringify } from 'querystring';
import { connect } from 'react-redux';
import * as utils from '../../lib/utils';
import { Link } from 'react-router-dom';
import '../auth-form/_auth-form.scss';
class Hero extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<section id="signupBackground" style={{ textAlign: 'center' }}>
<div >
{/* <h1 className="land-head">Kritter</h1> */}
<h2 className="create">Create a New Account</h2>
{/* <AuthForm
className="signup"
auth='signup'
onComplete={this.props.signup}
buttonText={'submit'}
userFetchRequest={this.props.userFetchRequest} /> */}
<SignUpForm
userFetchRequest={this.props.userFetchRequest}
onComplete={this.props.signup}
buttonText={'submit'} />
</div>
<div className="six columns login-thing">
{/* <h1 className="land-head2">dflgjdfkg</h1> */}
<Link to="/welcome/login"><h2 className="login-link">...or Login</h2></Link>
</div>
</section>
);
}
}
let mapStateToProps = state => ({
user: state.user,
auth: state.auth,
post: state.post,
});
let mapDispatchToProps = dispatch => ({
signup: user => dispatch(signupRequest(user)),
login: user => dispatch(loginRequest(user)),
userFetchRequest: () => dispatch(userFetchRequest()),
});
export default connect(mapStateToProps, mapDispatchToProps)(Hero);
|
frontend/client/components/weeks.js | rkuykendall/weeklypulls | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import autobind from 'autobind-decorator';
import { observable, toJS } from 'mobx';
import { observer, propTypes } from 'mobx-react';
import _ from 'lodash';
import utils from '../utils';
import Comic from './comic';
@autobind
@observer
class Week extends Component {
@observable minimized = null;
constructor (props) {
super(props);
}
defaultMinimized () {
const futureWeek = utils.future(this.props.week)
, allRead = !this.props.comics.some(comics => !(comics.read || comics.skipped));
return futureWeek || allRead;
}
getMinimized () {
if (this.minimized === null) {
return this.defaultMinimized();
}
return this.minimized;
}
toggleMinimized () {
if (this.minimized === null) {
this.minimized = !this.defaultMinimized();
}
else {
this.minimized = !this.minimized;
}
}
loadWeek () {
this.props.store.loadWeek(this.props.week);
}
get extraComics () {
const {
comics,
store,
week,
} = this.props;
const comicIds = comics.map(comic => comic.id);
return store.extraComics(week).filter(comic => !comicIds.includes(comic.id));
}
render () {
const {
comics,
store,
week,
} = this.props
, weekLoading = store.isLoading.get(`week.${week}`);
return (
<div className='week'>
<h5>{week} <a onClick={this.toggleMinimized}>[{this.minimized ? '+' : '-'}]</a></h5>
{!this.getMinimized() && (<div>
{_.sortBy(comics, 'title').map(comic => (
<Comic
comic={comic}
key={`week${week}_comic${comic.id}`}
pulled
store={store}
/>
))}
{_.sortBy(this.extraComics, 'title').map(comic => (
<Comic
comic={comic}
key={`week${week}_comic${comic.id}`}
pulled={false}
store={store}
/>
))}
{!this.extraComics.length &&
<a onClick={this.loadWeek} disabled={weekLoading}>
{weekLoading ? 'Loading...' : 'Load All'}
</a>}
</div>)}
</div>
);
}
static propTypes = {
comics: propTypes.arrayOrObservableArray,
mark: PropTypes.func,
store: PropTypes.object,
week: PropTypes.string,
}
}
@autobind
@observer
class Weeks extends Component {
render () {
const {
store,
} = this.props;
const comics = this.props.series.reduce((flat, toFlatten) => {
return flat.concat(toJS(toFlatten.api.comics));
}, []);
const weeks = Array.from(new Set(comics.map(comic => comic.on_sale)));
weeks.sort();
const firstUnreadWeek = _.findIndex(weeks, week => comics.filter(comic => (comic.on_sale === week)).some(comics => !(comics.read || comics.skipped)));
const weeksUnread = weeks.slice(firstUnreadWeek, weeks.length);
return (
<div className='weeks'>
{weeksUnread.map(week => (
<Week
comics={comics.filter(comic => (comic.on_sale === week))}
key={week}
mark={this.props.mark}
store={store}
week={week}
/>)
)}
</div>
);
}
static propTypes = {
mark: PropTypes.func,
series: propTypes.arrayOrObservableArray,
store: PropTypes.object,
}
}
export default Weeks;
|
src/components/NotFoundView/NotFoundView.js | findinstore/instore-webapp | import React from 'react';
import { Link } from 'react-router';
export class NotFoundView extends React.Component {
render() {
return (
<div className="container text-center">
<h1>This is a demo 404 page!</h1>
<hr />
<Link to="/">Back To Home View</Link>
</div>
);
}
}
export default NotFoundView;
|
simpleapp/app/component/inventitem.js | ladanv/learn-react-js | import React, { Component } from 'react';
import $ from 'jquery';
import config from '../../config';
import Panel from './panel/Panel';
import InputFormGroup from './form/InputFormGroup';
import TextFormGroup from './form/TextFormGroup';
class InventItem extends Component {
constructor(props) {
super(props);
this.state = {
item: null
};
}
componentDidMount() {
this.loadInventItemFromServer();
}
componentWillUnmount() {
this.serverRequest.abort();
}
render() {
var item = this.state.item;
if (!item) {
return null;
}
return (
<Panel header={config.inventory}>
<form>
<InputFormGroup key='name' id='name' label={config.inventItemName}
placeholder={config.inventItemNamePlaceholder} value={item.name} />
<InputFormGroup key='category' id='category' label={config.inventItemCategory}
placeholder={config.inventItemCategoryPlaceholder} value={item.category} />
<TextFormGroup key='description' id='description' label={config.inventItemDescription}
placeholder={config.inventItemDescriptionPlaceholder} value={item.description} />
</form>
</Panel>
);
}
loadInventItemFromServer() {
var itemUrl = config.apiUrl + '/inventory/' + this.props.params.itemId;
this.serverRequest = $.get(itemUrl, function (result) {
this.setState({
item: result
});
}.bind(this));
}
}
export default InventItem;
|
vcomp/Example.js | chezhe/Vidi | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Image
} from 'react-native';
import {Surface} from 'gl-react-native'
import HelloGL from './HelloGL'
import Saturation from './Saturation'
import HueRotate from './HueRotate'
import PieProgress from './PieProgress'
import OneFingerResponse from './OneFingerResponse'
import AE from "../AdvancedEffects"
export default class Example extends Component {
render(){
return (
<AE>
</AE>
)
// return (
// <Surface width={341} height={341}>
// <Bass width={256} height={180} factor={10}> https://img3.doubanio.com/view/photo/photo/public/p2257141972.jpg
// </Bass>
// </Surface>
// )
// return (
// <Surface width={341} height={341}>
// <HelloGL width={256} height={180} />
// </Surface>
// )
// return (
// <Surface width={341} height={341}>
// <PieProgress
// width={256}
// height={256}
// progress={0.1}
// colorInside={[0,0,0,0]}
// colorOutside={[0,0,0,0.5]}
// radius={0.4}
// />
// </Surface>
// )
// return (
// <Surface width={341} height={341}>
// <HueRotate hue={255}>
// <Image style={{ width: 300, height: 300 }} source={{ uri: "https://img3.doubanio.com/view/photo/photo/public/p2257141972.jpg" }}/>
// <Text style={styles.demoText1}>Throw me to the wolves</Text>
// <Text style={styles.demoText2}>{"text"}</Text>
// </HueRotate>
// </Surface>
// )
// return (
// <Surface width={341} height={341}>
// <Saturation
// factor={1.0}
// image="http://i.imgur.com/iPKTONG.jpg"
// />
// </Surface>
// )
// return (
// <Surface width={511} height={341}>
// <HelloGL blue={0.5} />
// </Surface>
// )
}
}
const styles = StyleSheet.create({
demoText1:{
fontSize: 20,
top: -100
},
demoText2:{
fontSize: 50,
top: -70
}
});
|
src/components/row.js | Greynight/Grid | import React from 'react';
class Row extends React.Component {
constructor(props) {
super(props);
this.READ_TEMPLATE = 'template';
this.EDIT_TEMPLATE = 'writableTemplate';
this.state = {
templateType: this.READ_TEMPLATE
};
}
getColumns = () => {
return this.props.columns;
};
getSchema = () => {
return this.props.schema;
};
getConfig = () => {
return this.props.config;
};
getRowData = () => {
return this.props.data;
};
getActions = () => {
return this.props.actions;
};
getTemplateType = (columnSchema) => {
let templateType = '';
if (this.isColumnEditable(columnSchema) || this.getRowData().id === null) {
templateType = this.state.templateType;
} else {
templateType = this.READ_TEMPLATE;
}
return templateType;
};
changeToReadMode = () => {
this.setState({
templateType: this.READ_TEMPLATE
});
};
changeToEditMode = () => {
this.setState({
templateType: this.EDIT_TEMPLATE
});
};
isSelectionEnabled = () => {
return this.getConfig().enableSelection;
};
isEditingEnabled = () => {
return this.getConfig().enableEditing;
};
isColumnEditable = (columnSchema) => {
return columnSchema.isEditable;
};
createUniqueCellId = (rowId, cellNum) => {
return `cell-${rowId}-${cellNum}`;
};
createUniqueCheckboxCellId = (rowId) => {
return `checkbox-${rowId}`;
};
createUniqueActionCellId = (rowId) => {
return `action-${rowId}`;
};
createColumnKey = (cellId) => {
return `td-${cellId}`;
};
}
export default Row;
|
src/components/dataVisualization/eCharts/Radar.js | SmiletoSUN/react-redux-demo | import React from 'react';
import ECharts from 'echarts-for-react';
const option = {
title: {
text: '基础雷达图',
},
tooltip: {},
legend: {
data: ['预算分配(Allocated Budget)', '实际开销(Actual Spending)'],
},
radar: {
// shape: 'circle',
name: {
textStyle: {
color: '#fff',
backgroundColor: '#999',
borderRadius: 3,
padding: [3, 5],
},
},
indicator: [
{ name: '销售(sales)', max: 6500 },
{ name: '管理(Administration)', max: 16000 },
{ name: '信息技术(Information Techology)', max: 30000 },
{ name: '客服(Customer Support)', max: 38000 },
{ name: '研发(Development)', max: 52000 },
{ name: '市场(Marketing)', max: 25000 },
],
},
series: [{
name: '预算 vs 开销(Budget vs spending)',
type: 'radar',
// areaStyle: {normal: {}},
data: [
{
value: [4300, 10000, 28000, 35000, 50000, 19000],
name: '预算分配(Allocated Budget)',
},
{
value: [5000, 14000, 28000, 31000, 42000, 21000],
name: '实际开销(Actual Spending)',
},
],
}],
};
const Radar = () => (
<ECharts
option={option}
className="react_for_echarts"
/>
);
export default Radar;
|
src/Projects/projects.js | jasongforbes/jforbes.io | import React from 'react';
import { Helmet } from 'react-helmet';
import PropTypes from 'prop-types';
import Grid from '@material-ui/core/Grid';
import Hidden from '@material-ui/core/Hidden';
import Typography from '@material-ui/core/Typography';
import { withStyles } from '@material-ui/core/styles';
const styles = theme => ({
content: {
margin: '80px 0px',
[theme.breakpoints.down('sm')]: {
margin: '40px 0px',
},
},
link: {
...theme.typography.button,
color: theme.palette.primary.light,
textAlign: 'left',
lineHeight: '2em',
},
});
const Projects = ({ classes }) => (
<div className={classes.content}>
<Helmet>
<title>Projects - Jason Forbes</title>
<meta
name="description"
content="A List of personal side-projects, including jforbes.io and dorian.js."
/>
</Helmet>
<Grid container spacing={0}>
<Hidden mdUp>
<Grid item xs={1} />
</Hidden>
<Grid item xs={10} md={12}>
<Typography variant="h3">Projects</Typography>
<div>
<a href="https://github.com/jasongforbes/jforbes.io" className={classes.link}>
jforbes.io
</a>
<Typography variant="body1">
A personal blog and responsive landing page written in React.
</Typography>
</div>
<div>
<a href="https://github.com/jasongforbes/dorian-js" className={classes.link}>
Dorian.js
</a>
<Typography variant="body1">
A simple blogging platform which converts user written markdown files into HTML. It is
available via the MIT OpenSource License. One of the goals of this project is to provide
a simple use-case for learning React and front-end web-development. The aim was to make
a personal landing-page framework which was extensible while retaining simplicity.
</Typography>
</div>
</Grid>
<Hidden mdUp>
<Grid item xs={1} />
</Hidden>
</Grid>
</div>
);
Projects.propTypes = {
classes: PropTypes.objectOf(PropTypes.string).isRequired,
};
export default withStyles(styles)(Projects);
|
src/components/post/edit-post-button.js | voidxnull/libertysoil-site | /*
This file is a part of libertysoil.org website
Copyright (C) 2015 Loki Education (Social Enterprise)
This program 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, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
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 { Link } from 'react-router';
import { URL_NAMES, getUrl } from '../../utils/urlGenerator';
let EditPostButton = (props) => {
if (!props.current_user || props.current_user.id !== props.post.user_id) {
return <script/>;
}
let post_edit_url = getUrl(URL_NAMES.EDIT_POST, { uuid: props.post.id });
return (
<div className="card__toolbar_item">
<Link to={post_edit_url}><span className="fa fa-pencil-square-o"></span></Link>
</div>
);
};
export default EditPostButton;
|
ui/src/main/js/pages/Updates.js | medallia/aurora | import React from 'react';
import Breadcrumb from 'components/Breadcrumb';
import PanelGroup, { Container, StandardPanelTitle } from 'components/Layout';
import UpdateList from 'components/UpdateList';
import { getInProgressStates, getTerminalStates } from 'utils/Update';
export const MAX_QUERY_SIZE = 100;
export class UpdatesFetcher extends React.Component {
constructor(props) {
super(props);
this.state = { updates: null };
}
componentWillMount() {
const that = this;
const query = new JobUpdateQuery();
query.updateStatuses = this.props.states;
query.limit = MAX_QUERY_SIZE;
this.props.api.getJobUpdateSummaries(query, (response) => {
const updates = response.result.getJobUpdateSummariesResult.updateSummaries;
that.setState({updates});
that.props.clusterFn(response.serverInfo.clusterName);
});
}
render() {
return (<Container>
<PanelGroup noPadding title={<StandardPanelTitle title={this.props.title} />}>
<UpdateList updates={this.state.updates} />
</PanelGroup>
</Container>);
}
}
export default class Updates extends React.Component {
constructor(props) {
super(props);
this.state = { cluster: null };
this.clusterFn = this.setCluster.bind(this);
}
setCluster(cluster) {
// TODO(dmcg): We should just have the Scheduler return the cluster as a global.
this.setState({cluster});
}
render() {
const api = this.props.api;
return (<div className='update-page'>
<Breadcrumb cluster={this.state.cluster} />
<UpdatesFetcher
api={api}
clusterFn={this.clusterFn}
states={getInProgressStates()}
title='Updates In Progress' />
<UpdatesFetcher
api={api}
clusterFn={this.clusterFn}
states={getTerminalStates()}
title='Recently Completed Updates' />
</div>);
}
}
|
src/config/routes.js | bmacheski/gh-contributors | 'use strict';
import React from 'react';
import Main from '../components/Main';
import RepoSearch from '../components/RepoSearch';
import RepoList from '../components/RepoList';
import ContribList from '../components/ContribList'
import { Router, DefaultRoute, Route } from 'react-router';
export default (
<Route name="app" path="/" handler={Main}>
<Route name="reporesults" path="search/:username" handler={RepoList} />
<Route name="contribresults" path="contrib/:username/:repo" handler={ContribList} />
<DefaultRoute handler={RepoSearch} />
</Route>
);
|
fields/components/columns/IdColumn.js | ligson/keystone | import React from 'react';
import ItemsTableCell from '../../../admin/src/components/ItemsTableCell';
import ItemsTableValue from '../../../admin/src/components/ItemsTableValue';
var IdColumn = React.createClass({
displayName: 'IdColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
list: React.PropTypes.object,
},
renderValue () {
let value = this.props.data.id;
if (!value) return null;
return (
<ItemsTableValue padded interior title={value} href={'/keystone/' + this.props.list.path + '/' + value} field={this.props.col.type}>
{value}
</ItemsTableValue>
);
},
render () {
return (
<ItemsTableCell>
{this.renderValue()}
</ItemsTableCell>
);
}
});
module.exports = IdColumn;
|
src/containers/board/newBoard.js | motion123/mbookmakerUI | /**
* Created by tomihei on 17/03/31.
*/
import React from 'react'
import { connect } from 'react-redux'
import NewBoard from '../../components/Board/newBoard';
import * as newBoard from '../../actions/newBoard'
function mapStateToProps(state) {
return {
title: state.newBoard.title,
description: state.newBoard.description,
isFetching: state.newBoard.isFetching,
open: state.newBoard.open,
secret: state.newBoard.secret,
errorMessage:state.newBoard.errorMessage,
}
}
// clickでactionを飛ばず
function mapDispatchToProps(dispatch) {
return {
closeDialog: () => {
dispatch(newBoard.closeDialog())
},
changeTitle: (title) => {
dispatch(newBoard.changeTitle(title))
},
changeDescription: (desc) => {
dispatch(newBoard.changeDescription(desc))
},
changeSecret: (secret) => {
dispatch(newBoard.changeSecret(secret))
},
requestNewBoard: (data) => {
dispatch(newBoard.newBoardRequest(data))
}
}
}
//connect関数でReduxとReactコンポーネントを繋ぐ
export default connect(
mapStateToProps,
mapDispatchToProps
)(NewBoard)
|
examples/auth-with-shared-root/components/Dashboard.js | rdjpalmer/react-router | import React from 'react'
import auth from '../utils/auth'
const Dashboard = React.createClass({
render() {
const token = auth.getToken()
return (
<div>
<h1>Dashboard</h1>
<p>You made it!</p>
<p>{token}</p>
{this.props.children}
</div>
)
}
})
export default Dashboard
|
pnpm-offline/.pnpm-store-offline/1/registry.npmjs.org/react-bootstrap/0.31.0/es/Tooltip.js | JamieMason/npm-cache-benchmark | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import isRequiredForA11y from 'react-prop-types/lib/isRequiredForA11y';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
/**
* An html id attribute, necessary for accessibility
* @type {string|number}
* @required
*/
id: isRequiredForA11y(PropTypes.oneOfType([PropTypes.string, PropTypes.number])),
/**
* Sets the direction the Tooltip is positioned towards.
*/
placement: PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
/**
* The "top" position value for the Tooltip.
*/
positionTop: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* The "left" position value for the Tooltip.
*/
positionLeft: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* The "top" position value for the Tooltip arrow.
*/
arrowOffsetTop: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* The "left" position value for the Tooltip arrow.
*/
arrowOffsetLeft: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
};
var defaultProps = {
placement: 'right'
};
var Tooltip = function (_React$Component) {
_inherits(Tooltip, _React$Component);
function Tooltip() {
_classCallCheck(this, Tooltip);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Tooltip.prototype.render = function render() {
var _extends2;
var _props = this.props,
placement = _props.placement,
positionTop = _props.positionTop,
positionLeft = _props.positionLeft,
arrowOffsetTop = _props.arrowOffsetTop,
arrowOffsetLeft = _props.arrowOffsetLeft,
className = _props.className,
style = _props.style,
children = _props.children,
props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'className', 'style', 'children']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2));
var outerStyle = _extends({
top: positionTop,
left: positionLeft
}, style);
var arrowStyle = {
top: arrowOffsetTop,
left: arrowOffsetLeft
};
return React.createElement(
'div',
_extends({}, elementProps, {
role: 'tooltip',
className: classNames(className, classes),
style: outerStyle
}),
React.createElement('div', { className: prefix(bsProps, 'arrow'), style: arrowStyle }),
React.createElement(
'div',
{ className: prefix(bsProps, 'inner') },
children
)
);
};
return Tooltip;
}(React.Component);
Tooltip.propTypes = propTypes;
Tooltip.defaultProps = defaultProps;
export default bsClass('tooltip', Tooltip); |
src/components/card/Suggestions.js | yuri/treillage | import React from 'react';
import PropTypes from 'prop-types';
import { PASS } from '../../services/rules';
import { Button } from '../inputs/Button';
export const Suggestions = ({ suggestions, handleIgnore }) => {
const styles = {
message: {
fontSize: '14px',
fontStyle: 'italic',
},
button: {
display: 'none',
},
pass: {
color: 'green',
},
error: {
color: 'red',
whiteSpace: 'pre',
},
};
const renderHelp = (rule) => {
let help;
switch (rule) {
case 'maxLength':
help = (
<div>
{'Consider making a '}
<a href="https://docs.google.com/document/u/0/?tgif=d">Google Doc</a>
{' Or a '}
<a href="https://github.com/rangle/hub/wiki/_new">Wiki Article</a>
{' for more space.'}
</div>
);
break;
default:
break;
}
return help;
};
return (
<div style={styles.message}>
{suggestions.length === 0
? <div style={styles.pass}>{PASS}</div>
: suggestions.map((suggestion, i) => (
<div key={`rule-suggestion-${i}`}>
<div style={styles.error}>{suggestion.text}</div>
{renderHelp(suggestion.rule)}
{suggestion.options &&
suggestion.options.map((option, j) => option === 'ignorable' &&
<Button
style={styles.button}
size="mini"
key={`suggestion-${i}-option-${j}`}
onClick={() => handleIgnore(suggestion)}
>
{'Ignore'}
</Button>)}
</div>
))}
</div>
);
};
Suggestions.propTypes = {
suggestions: PropTypes.array,
handleIgnore: PropTypes.func,
};
|
config/componentData.js | tlraridon/ps-react-train-tlr | module.exports = [{"name":"EyeIcon","description":"SVG Eye Icon.","code":"import React from 'react';\r\n\r\n/** SVG Eye Icon. */\r\nfunction EyeIcon() {\r\n // Attribution: Fabián Alexis at https://commons.wikimedia.org/wiki/File:Antu_view-preview.svg\r\n return (\r\n <svg width=\"16\" height=\"16\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 22 22\">\r\n <g transform=\"matrix(.02146 0 0 .02146 1 1)\" fill=\"#4d4d4d\">\r\n <path d=\"m466.07 161.53c-205.6 0-382.8 121.2-464.2 296.1-2.5 5.3-2.5 11.5 0 16.9 81.4 174.9 258.6 296.1 464.2 296.1 205.6 0 382.8-121.2 464.2-296.1 2.5-5.3 2.5-11.5 0-16.9-81.4-174.9-258.6-296.1-464.2-296.1m0 514.7c-116.1 0-210.1-94.1-210.1-210.1 0-116.1 94.1-210.1 210.1-210.1 116.1 0 210.1 94.1 210.1 210.1 0 116-94.1 210.1-210.1 210.1\" />\r\n <circle cx=\"466.08\" cy=\"466.02\" r=\"134.5\" />\r\n </g>\r\n </svg>\r\n )\r\n}\r\n\r\nexport default EyeIcon;\r\n","examples":[{"name":"ExampleEyeIcon","description":"","code":"import React from 'react';\r\nimport EyeIcon from 'ps-react-train-tlr/EyeIcon';\r\n\r\nexport default function ExampleEyeIcon() {\r\n return <EyeIcon />\r\n}"}]},{"name":"HelloWorld","description":"A Hello World component that uses a custom message.","props":{"message":{"type":{"name":"string"},"required":true,"description":"Message to display.","defaultValue":{"value":"'world'","computed":false}}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\n\r\n/** A Hello World component that uses a custom message. */\r\nfunction HelloWorld({message}) {\r\n return <div>Hello {message}</div>\r\n}\r\n\r\nHelloWorld.propTypes = {\r\n /** Message to display. */\r\n message: PropTypes.string.isRequired\r\n};\r\n\r\nHelloWorld.defaultProps = {\r\n message: 'world'\r\n}\r\n\r\nexport default HelloWorld;","examples":[{"name":"ExampleHelloWorld","description":"Component with a Custom Message","code":"import React from 'react';\r\nimport HelloWorld from 'ps-react-train-tlr/HelloWorld';\r\n\r\n/** Component with a Custom Message */\r\nexport default function ExampleHelloWorld() {\r\n return <HelloWorld message='Pluralsight viewers!' />\r\n}"}]},{"name":"Label","description":"Label with required field display, htmlFor, and block styling.","props":{"htmlFor":{"type":{"name":"string"},"required":true,"description":"HTML ID for associated input"},"label":{"type":{"name":"string"},"required":true,"description":"Label text"},"required":{"type":{"name":"bool"},"required":false,"description":"Display asterisk after label if true"}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\n\r\n/** Label with required field display, htmlFor, and block styling. */\r\nfunction Label({htmlFor, label, required}) {\r\n return (\r\n <label style={{display: 'block'}} htmlFor={htmlFor}>\r\n {label} { required && <span style={{color: 'red'}}> *</span> }\r\n </label>\r\n )\r\n}\r\n\r\nLabel.propTypes = {\r\n /** HTML ID for associated input */\r\n htmlFor: PropTypes.string.isRequired,\r\n\r\n /** Label text */\r\n label: PropTypes.string.isRequired,\r\n\r\n /** Display asterisk after label if true */\r\n required: PropTypes.bool\r\n};\r\n\r\nexport default Label;\r\n","examples":[{"name":"ExampleOptional","description":"Optional Label","code":"import React from 'react';\r\nimport Label from 'ps-react-train-tlr/Label';\r\n\r\n/** Optional Label */\r\nexport default function ExampleOptional() {\r\n return <Label htmlFor=\"test\" label=\"test\" />\r\n}"},{"name":"ExampleRequired","description":"Required Label","code":"import React from 'react';\r\nimport Label from 'ps-react-train-tlr/Label';\r\n\r\n/** Required Label */\r\nexport default function ExampleRequired() {\r\n return <Label htmlFor=\"test\" label=\"test\" required />\r\n}"}]},{"name":"PasswordInput","description":"Password input with integrated label, quality tips, and show password toggle.","props":{"htmlId":{"type":{"name":"string"},"required":true,"description":"Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing."},"name":{"type":{"name":"string"},"required":true,"description":"Input name. Recommend setting this to match object's property so a single change handler can be used by convention."},"value":{"type":{"name":"any"},"required":false,"description":"Password value"},"label":{"type":{"name":"string"},"required":false,"description":"Input label","defaultValue":{"value":"'Password'","computed":false}},"onChange":{"type":{"name":"func"},"required":true,"description":"Function called when password input value changes"},"maxLength":{"type":{"name":"number"},"required":false,"description":"Max password length accepted","defaultValue":{"value":"50","computed":false}},"placeholder":{"type":{"name":"string"},"required":false,"description":"Placeholder displayed when no password is entered"},"showVisibilityToggle":{"type":{"name":"bool"},"required":false,"description":"Set to true to show the toggle for displaying the currently entered password","defaultValue":{"value":"false","computed":false}},"quality":{"type":{"name":"number"},"required":false,"description":"Display password quality visually via ProgressBar, accepts a number between 0 and 100"},"error":{"type":{"name":"string"},"required":false,"description":"Validation error to display"}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\nimport ProgressBar from '../ProgressBar';\r\nimport EyeIcon from '../EyeIcon';\r\nimport TextInput from '../TextInput';\r\n\r\n/** Password input with integrated label, quality tips, and show password toggle. */\r\nclass PasswordInput extends React.Component {\r\n constructor(props) {\r\n super(props);\r\n this.state = {\r\n showPassword: false\r\n }\r\n }\r\n\r\n toggleShowPassword = event => {\r\n this.setState(prevState => {\r\n return { showPassword: !prevState.showPassword };\r\n });\r\n if (event) event.preventDefault();\r\n }\r\n\r\n render() {\r\n const { htmlId, value, label, error, onChange, placeholder, maxLength, showVisibilityToggle, quality, ...props } = this.props;\r\n const { showPassword } = this.state;\r\n\r\n return (\r\n <TextInput\r\n htmlId={htmlId}\r\n label={label}\r\n placeholder={placeholder}\r\n type={showPassword ? 'text' : 'password'}\r\n onChange={onChange}\r\n value={value}\r\n maxLength={maxLength}\r\n error={error}\r\n required\r\n {...props}>\r\n {\r\n showVisibilityToggle &&\r\n <a\r\n href=\"\"\r\n onClick={this.toggleShowPassword}\r\n style={{ marginLeft: 5 }}>\r\n <EyeIcon />\r\n </a>\r\n }\r\n {\r\n value.length > 0 && quality && <ProgressBar percent={quality} width={130} />\r\n }\r\n </TextInput>\r\n );\r\n }\r\n}\r\n\r\nPasswordInput.propTypes = {\r\n /** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */\r\n htmlId: PropTypes.string.isRequired,\r\n\r\n /** Input name. Recommend setting this to match object's property so a single change handler can be used by convention.*/\r\n name: PropTypes.string.isRequired,\r\n\r\n /** Password value */\r\n value: PropTypes.any,\r\n\r\n /** Input label */\r\n label: PropTypes.string,\r\n\r\n /** Function called when password input value changes */\r\n onChange: PropTypes.func.isRequired,\r\n\r\n /** Max password length accepted */\r\n maxLength: PropTypes.number,\r\n\r\n /** Placeholder displayed when no password is entered */\r\n placeholder: PropTypes.string,\r\n\r\n /** Set to true to show the toggle for displaying the currently entered password */\r\n showVisibilityToggle: PropTypes.bool,\r\n\r\n /** Display password quality visually via ProgressBar, accepts a number between 0 and 100 */\r\n quality: PropTypes.number,\r\n\r\n /** Validation error to display */\r\n error: PropTypes.string\r\n};\r\n\r\nPasswordInput.defaultProps = {\r\n maxLength: 50,\r\n showVisibilityToggle: false,\r\n label: 'Password'\r\n};\r\n\r\nexport default PasswordInput;\r\n","examples":[{"name":"ExampleAllFeatures","description":"All features enabled","code":"import React from 'react';\r\nimport PasswordInput from 'ps-react-train-tlr/PasswordInput';\r\n\r\n/** All features enabled */\r\nclass ExampleAllFeatures extends React.Component {\r\n constructor(props) {\r\n super(props);\r\n\r\n this.state = {\r\n password: ''\r\n };\r\n }\r\n\r\n getQuality() {\r\n const length = this.state.password.length;\r\n return length > 10 ? 100 : length * 10;\r\n }\r\n\r\n render() {\r\n return (\r\n <div>\r\n <PasswordInput\r\n htmlId=\"password-input-example-all-features\"\r\n name=\"password\"\r\n onChange={ event => this.setState({ password: event.target.value })}\r\n value={this.state.password}\r\n minLength={8}\r\n placeholder=\"Enter password\"\r\n showVisibilityToggle\r\n quality={this.getQuality()}\r\n {...this.props} />\r\n </div>\r\n )\r\n }\r\n}\r\n\r\nexport default ExampleAllFeatures;\r\n"}]},{"name":"ProgressBar","description":"A colorful bar that conveys progress.","props":{"percent":{"type":{"name":"number"},"required":true,"description":"Percent of progress completed"},"width":{"type":{"name":"number"},"required":true,"description":"Bar width"},"height":{"type":{"name":"number"},"required":false,"description":"Bar height","defaultValue":{"value":"5","computed":false}}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\n\r\n/** A colorful bar that conveys progress. */\r\nclass ProgressBar extends React.Component {\r\n getColor = (percent) => {\r\n if (this.props.percent === 100) return 'green';\r\n return this.props.percent > 50 ? 'lightgreen' : 'red';\r\n }\r\n\r\n getWidthAsPercentOfTotalWidth = () => {\r\n return parseInt(this.props.width * (this.props.percent / 100), 10);\r\n }\r\n\r\n render() {\r\n const {percent, width, height} = this.props;\r\n return (\r\n <div style={{border: 'solid 1px lightgray', width: width}}>\r\n <div style={{\r\n width: this.getWidthAsPercentOfTotalWidth(),\r\n height,\r\n backgroundColor: this.getColor(percent)\r\n }} />\r\n </div>\r\n );\r\n }\r\n}\r\n\r\nProgressBar.propTypes = {\r\n /** Percent of progress completed */\r\n percent: PropTypes.number.isRequired,\r\n\r\n /** Bar width */\r\n width: PropTypes.number.isRequired,\r\n\r\n /** Bar height */\r\n height: PropTypes.number\r\n};\r\n\r\nProgressBar.defaultProps = {\r\n height: 5\r\n};\r\n\r\nexport default ProgressBar;","examples":[{"name":"Example100Percent","description":"100% Progress","code":"import React from 'react';\r\nimport ProgressBar from 'ps-react-train-tlr/ProgressBar';\r\n\r\n/** 100% Progress */\r\nexport default function Example100Percent() {\r\n return <ProgressBar percent={100} width={150} />\r\n}"},{"name":"Example10Percent","description":"10% Progress","code":"import React from 'react';\r\nimport ProgressBar from 'ps-react-train-tlr/ProgressBar';\r\n\r\n/** 10% Progress */\r\nexport default function Example10Percent() {\r\n return <ProgressBar percent={10} width={150} />\r\n}"},{"name":"Example50Percent","description":"50% Progress","code":"import React from 'react';\r\nimport ProgressBar from 'ps-react-train-tlr/ProgressBar';\r\n\r\n/** 50% Progress */\r\nexport default function Example50Percent() {\r\n return <ProgressBar percent={50} width={150} height={20} />\r\n}"},{"name":"Example70Percent","description":"70% Progress","code":"import React from 'react';\r\nimport ProgressBar from 'ps-react-train-tlr/ProgressBar';\r\n\r\n/** 70% Progress */\r\nexport default function Example70Percent() {\r\n return <ProgressBar percent={70} width={150} />\r\n}"}]},{"name":"RegistrationForm","description":"Registration form with built-in validation.","props":{"confirmationMessage":{"type":{"name":"string"},"required":false,"description":"Message displayed upon successful submission","defaultValue":{"value":"\"Thank you for your registration.\"","computed":false}},"onSubmit":{"type":{"name":"func"},"required":true,"description":"Called when form is submitted"},"minPasswordLength":{"type":{"name":"number"},"required":false,"description":"Minimum password length","defaultValue":{"value":"8","computed":false}}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\nimport TextInput from '../TextInput';\r\nimport PasswordInput from '../PasswordInput';\r\n\r\n/** Registration form with built-in validation. */\r\nclass RegistrationForm extends React.Component {\r\n constructor(props) {\r\n super(props);\r\n\r\n this.state = {\r\n user: {\r\n email: '',\r\n password: ''\r\n },\r\n errors: {},\r\n submitted: false,\r\n };\r\n }\r\n\r\n onChange = (event) => {\r\n const user = this.state.user;\r\n user[event.target.name] = event.target.value;\r\n this.setState({user});\r\n }\r\n\r\n // Returns a number from 0 to 100 that represents password quality.\r\n // For simplicity, just returning % of min length entered.\r\n // Could enhance with checks for number, upper case letters, special chars, unique chars, etc.\r\n passwordQuality(password) {\r\n if (!password) return null;\r\n if (password.length >= this.props.minPasswordLength) return 100;\r\n const percentOfMinLength = parseInt(password.length/this.props.minPasswordLength * 100, 10);\r\n return percentOfMinLength;\r\n }\r\n\r\n validate({email, password}) {\r\n const errors = {};\r\n const {minPasswordLength} = this.props;\r\n\r\n if (!email) errors.email = 'Email required.';\r\n if (password.length < minPasswordLength) errors.password = `Password must be at least ${minPasswordLength} characters.`;\r\n\r\n this.setState({errors});\r\n const formIsValid = Object.getOwnPropertyNames(errors).length === 0;\r\n return formIsValid;\r\n }\r\n\r\n onSubmit = () => {\r\n const {user} = this.state;\r\n const formIsValid = this.validate(user);\r\n if (formIsValid) {\r\n this.props.onSubmit(user);\r\n this.setState({submitted: true});\r\n }\r\n }\r\n\r\n render() {\r\n const {errors, submitted} = this.state;\r\n const {email, password} = this.state.user;\r\n\r\n return (\r\n submitted ?\r\n <h2>{this.props.confirmationMessage}</h2> :\r\n <form id='registrationForm'>\r\n <div>\r\n <TextInput\r\n htmlId=\"registration-form-email\"\r\n name=\"email\"\r\n onChange={this.onChange}\r\n label=\"Email\"\r\n value={email}\r\n error={errors.email}\r\n required />\r\n\r\n <PasswordInput\r\n htmlId=\"registration-form-password\"\r\n name=\"password\"\r\n value={password}\r\n onChange={this.onChange}\r\n quality={this.passwordQuality(password)}\r\n showVisibilityToggle\r\n maxLength={50}\r\n error={errors.password} />\r\n\r\n <input type=\"submit\" value=\"Register\" onClick={this.onSubmit} />\r\n </div>\r\n </form>\r\n )\r\n }\r\n}\r\n\r\nRegistrationForm.propTypes = {\r\n /** Message displayed upon successful submission */\r\n confirmationMessage: PropTypes.string,\r\n\r\n /** Called when form is submitted */\r\n onSubmit: PropTypes.func.isRequired,\r\n\r\n /** Minimum password length */\r\n minPasswordLength: PropTypes.number\r\n}\r\n\r\nRegistrationForm.defaultProps = {\r\n confirmationMessage: \"Thank you for your registration.\",\r\n minPasswordLength: 8\r\n};\r\n\r\nexport default RegistrationForm;\r\n","examples":[{"name":"ExampleRegistrationForm","description":"","code":"import React from 'react';\r\nimport RegistrationForm from 'ps-react-train-tlr/RegistrationForm';\r\n\r\nexport default class ExampleRegistrationForm extends React.Component {\r\n onSubmit = (user) => {\r\n console.log(user);\r\n }\r\n\r\n render() {\r\n return <RegistrationForm onSubmit={this.onSubmit} confirmationMessage='Success!' />\r\n }\r\n}"}]},{"name":"TextInput","description":"Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker.","props":{"htmlId":{"type":{"name":"string"},"required":true,"description":"Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing."},"name":{"type":{"name":"string"},"required":true,"description":"Input name. Recommend setting this to match object's property so a single change handler can be used."},"label":{"type":{"name":"string"},"required":true,"description":"Input label"},"type":{"type":{"name":"enum","value":[{"value":"'text'","computed":false},{"value":"'number'","computed":false},{"value":"'password'","computed":false}]},"required":false,"description":"Input type","defaultValue":{"value":"\"text\"","computed":false}},"required":{"type":{"name":"bool"},"required":false,"description":"Mark label with asterisk if set to true","defaultValue":{"value":"false","computed":false}},"onChange":{"type":{"name":"func"},"required":true,"description":"Function to call onChange"},"placeholder":{"type":{"name":"string"},"required":false,"description":"Placeholder to display when empty"},"value":{"type":{"name":"any"},"required":false,"description":"Value"},"error":{"type":{"name":"string"},"required":false,"description":"String to display when error occurs"},"children":{"type":{"name":"node"},"required":false,"description":"Child component to display next to the input"}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\nimport Label from '../Label';\r\n\r\n/** Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker. */\r\nfunction TextInput({htmlId, name, label, type = \"text\", required = false, onChange, placeholder, value, error, children, ...props}) {\r\n return (\r\n <div style={{marginBottom: 16}}>\r\n <Label htmlFor={htmlId} label={label} required={required} />\r\n <input\r\n id={htmlId}\r\n type={type}\r\n name={name}\r\n placeholder={placeholder}\r\n value={value}\r\n onChange={onChange}\r\n style={error && {border: 'solid 1px red'}}\r\n {...props}/>\r\n {children}\r\n {error && <div className=\"error\" style={{color: 'red'}}>{error}</div>}\r\n </div>\r\n );\r\n};\r\n\r\nTextInput.propTypes = {\r\n /** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */\r\n htmlId: PropTypes.string.isRequired,\r\n\r\n /** Input name. Recommend setting this to match object's property so a single change handler can be used. */\r\n name: PropTypes.string.isRequired,\r\n\r\n /** Input label */\r\n label: PropTypes.string.isRequired,\r\n\r\n /** Input type */\r\n type: PropTypes.oneOf(['text', 'number', 'password']),\r\n\r\n /** Mark label with asterisk if set to true */\r\n required: PropTypes.bool,\r\n\r\n /** Function to call onChange */\r\n onChange: PropTypes.func.isRequired,\r\n\r\n /** Placeholder to display when empty */\r\n placeholder: PropTypes.string,\r\n\r\n /** Value */\r\n value: PropTypes.any,\r\n\r\n /** String to display when error occurs */\r\n error: PropTypes.string,\r\n\r\n /** Child component to display next to the input */\r\n children: PropTypes.node\r\n};\r\n\r\nexport default TextInput;\r\n","examples":[{"name":"ExampleError","description":"Required TextBox with error","code":"import React from 'react';\r\nimport TextInput from 'ps-react-train-tlr/TextInput';\r\n\r\n/** Required TextBox with error */\r\nexport default class ExampleError extends React.Component {\r\n render() {\r\n return (\r\n <TextInput\r\n htmlId=\"example-optional\"\r\n label=\"First Name\"\r\n name=\"firstname\"\r\n onChange={() => {}}\r\n required\r\n error=\"First name is required.\"\r\n />\r\n )\r\n }\r\n}\r\n"},{"name":"ExampleOptional","description":"Optional Textbox","code":"import React from 'react';\r\nimport TextInput from 'ps-react-train-tlr/TextInput';\r\n\r\n/** Optional Textbox */\r\nexport default class ExampleOptional extends React.Component {\r\n render() {\r\n return (\r\n <TextInput\r\n htmlId=\"excample-optional\"\r\n label=\"First Name\"\r\n name=\"firstname\"\r\n placeholder=\"First Name\"\r\n onChange={() => {}}\r\n />\r\n )\r\n }\r\n}"}]},{"name":"TextInputBEM","description":"Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker.","props":{"htmlId":{"type":{"name":"string"},"required":true,"description":"Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing."},"name":{"type":{"name":"string"},"required":true,"description":"Input name. Recommend setting this to match object's property so a single change handler can be used."},"label":{"type":{"name":"string"},"required":true,"description":"Input label"},"type":{"type":{"name":"enum","value":[{"value":"'text'","computed":false},{"value":"'number'","computed":false},{"value":"'password'","computed":false}]},"required":false,"description":"Input type","defaultValue":{"value":"\"text\"","computed":false}},"required":{"type":{"name":"bool"},"required":false,"description":"Mark label with asterisk if set to true","defaultValue":{"value":"false","computed":false}},"onChange":{"type":{"name":"func"},"required":true,"description":"Function to call onChange"},"placeholder":{"type":{"name":"string"},"required":false,"description":"Placeholder to display when empty"},"value":{"type":{"name":"any"},"required":false,"description":"Value"},"error":{"type":{"name":"string"},"required":false,"description":"String to display when error occurs"},"children":{"type":{"name":"node"},"required":false,"description":"Child component to display next to the input"}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\nimport Label from '../Label';\r\n\r\n/** Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker. */\r\nfunction TextInput({htmlId, name, label, type = \"text\", required = false, onChange, placeholder, value, error, children, ...props}) {\r\n return (\r\n <div className='textinput'>\r\n <Label htmlFor={htmlId} label={label} required={required} />\r\n <input\r\n id={htmlId}\r\n type={type}\r\n name={name}\r\n placeholder={placeholder}\r\n value={value}\r\n onChange={onChange}\r\n className={error && 'textinput__input--state--error'}\r\n {...props}/>\r\n {children}\r\n {error && <div className='textinput__error'>{error}</div>}\r\n </div>\r\n );\r\n};\r\n\r\nTextInput.propTypes = {\r\n /** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */\r\n htmlId: PropTypes.string.isRequired,\r\n\r\n /** Input name. Recommend setting this to match object's property so a single change handler can be used. */\r\n name: PropTypes.string.isRequired,\r\n\r\n /** Input label */\r\n label: PropTypes.string.isRequired,\r\n\r\n /** Input type */\r\n type: PropTypes.oneOf(['text', 'number', 'password']),\r\n\r\n /** Mark label with asterisk if set to true */\r\n required: PropTypes.bool,\r\n\r\n /** Function to call onChange */\r\n onChange: PropTypes.func.isRequired,\r\n\r\n /** Placeholder to display when empty */\r\n placeholder: PropTypes.string,\r\n\r\n /** Value */\r\n value: PropTypes.any,\r\n\r\n /** String to display when error occurs */\r\n error: PropTypes.string,\r\n\r\n /** Child component to display next to the input */\r\n children: PropTypes.node\r\n};\r\n\r\nexport default TextInput;\r\n","examples":[{"name":"TextInputBEM","description":"Required Textbox with Error","code":"import React from 'react';\r\nimport TextInputBEM from 'ps-react-train-tlr/TextInputBEM';\r\n\r\n/** Required Textbox with Error */\r\nexport default class ErrorOptional_BEM extends React.Component {\r\n render() {\r\n return (\r\n <TextInputBEM\r\n htmlId=\"example-error\"\r\n label=\"First Name\"\r\n name=\"firstname\"\r\n placeholder=\"First Name\"\r\n onChange={() => {}}\r\n required\r\n error=\"Required\"\r\n />\r\n )\r\n }\r\n}"}]},{"name":"TextInputCSSModules","description":"Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker.","props":{"htmlId":{"type":{"name":"string"},"required":true,"description":"Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing."},"name":{"type":{"name":"string"},"required":true,"description":"Input name. Recommend setting this to match object's property so a single change handler can be used."},"label":{"type":{"name":"string"},"required":true,"description":"Input label"},"type":{"type":{"name":"enum","value":[{"value":"'text'","computed":false},{"value":"'number'","computed":false},{"value":"'password'","computed":false}]},"required":false,"description":"Input type","defaultValue":{"value":"\"text\"","computed":false}},"required":{"type":{"name":"bool"},"required":false,"description":"Mark label with asterisk if set to true","defaultValue":{"value":"false","computed":false}},"onChange":{"type":{"name":"func"},"required":true,"description":"Function to call onChange"},"placeholder":{"type":{"name":"string"},"required":false,"description":"Placeholder to display when empty"},"value":{"type":{"name":"any"},"required":false,"description":"Value"},"error":{"type":{"name":"string"},"required":false,"description":"String to display when error occurs"},"children":{"type":{"name":"node"},"required":false,"description":"Child component to display next to the input"}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\nimport Label from '../Label';\r\nimport styles from './textInput.css';\r\n\r\n/** Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker. */\r\nfunction TextInput({htmlId, name, label, type = \"text\", required = false, onChange, placeholder, value, error, children, ...props}) {\r\n return (\r\n <div className={styles.fieldset}>\r\n <Label htmlFor={htmlId} label={label} required={required} />\r\n <input\r\n id={htmlId}\r\n type={type}\r\n name={name}\r\n placeholder={placeholder}\r\n value={value}\r\n onChange={onChange}\r\n className={error && styles.inputError}\r\n {...props}/>\r\n {children}\r\n {error && <div className={styles.error}>{error}</div>}\r\n </div>\r\n );\r\n};\r\n\r\nTextInput.propTypes = {\r\n /** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */\r\n htmlId: PropTypes.string.isRequired,\r\n\r\n /** Input name. Recommend setting this to match object's property so a single change handler can be used. */\r\n name: PropTypes.string.isRequired,\r\n\r\n /** Input label */\r\n label: PropTypes.string.isRequired,\r\n\r\n /** Input type */\r\n type: PropTypes.oneOf(['text', 'number', 'password']),\r\n\r\n /** Mark label with asterisk if set to true */\r\n required: PropTypes.bool,\r\n\r\n /** Function to call onChange */\r\n onChange: PropTypes.func.isRequired,\r\n\r\n /** Placeholder to display when empty */\r\n placeholder: PropTypes.string,\r\n\r\n /** Value */\r\n value: PropTypes.any,\r\n\r\n /** String to display when error occurs */\r\n error: PropTypes.string,\r\n\r\n /** Child component to display next to the input */\r\n children: PropTypes.node\r\n};\r\n\r\nexport default TextInput;\r\n","examples":[{"name":"ExampleErrorCSSModules","description":"Required Textbox with Error","code":"import React from 'react';\r\nimport TextInputCSSModules from 'ps-react-train-tlr/TextInputCSSModules';\r\n\r\n/** Required Textbox with Error */\r\nexport default class ErrorOptional extends React.Component {\r\n render() {\r\n return (\r\n <TextInputCSSModules\r\n htmlId=\"example-error\"\r\n label=\"First Name\"\r\n name=\"firstname\"\r\n placeholder=\"First Name\"\r\n onChange={() => {}}\r\n required\r\n error=\"THIS IS REQUIRED!\"\r\n />\r\n )\r\n }\r\n}"}]},{"name":"TextInputStyledComponents","description":"Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker.","props":{"htmlId":{"type":{"name":"string"},"required":true,"description":"Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing."},"name":{"type":{"name":"string"},"required":true,"description":"Input name. Recommend setting this to match object's property so a single change handler can be used."},"label":{"type":{"name":"string"},"required":true,"description":"Input label"},"type":{"type":{"name":"enum","value":[{"value":"'text'","computed":false},{"value":"'number'","computed":false},{"value":"'password'","computed":false}]},"required":false,"description":"Input type","defaultValue":{"value":"\"text\"","computed":false}},"required":{"type":{"name":"bool"},"required":false,"description":"Mark label with asterisk if set to true","defaultValue":{"value":"false","computed":false}},"onChange":{"type":{"name":"func"},"required":true,"description":"Function to call onChange"},"placeholder":{"type":{"name":"string"},"required":false,"description":"Placeholder to display when empty"},"value":{"type":{"name":"any"},"required":false,"description":"Value"},"error":{"type":{"name":"string"},"required":false,"description":"String to display when error occurs"},"children":{"type":{"name":"node"},"required":false,"description":"Child component to display next to the input"}},"code":"import React from 'react';\r\nimport PropTypes from 'prop-types';\r\nimport Label from '../Label';\r\nimport styled from 'styled-components';\r\n\r\n/** Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker. */\r\nfunction TextInputStyledComponent({htmlId, name, label, type = \"text\", required = false, onChange, placeholder, value, error, children, ...props}) {\r\n\r\n const Error = styled.div`\r\n color: red;\r\n `;\r\n const Input = styled.input`\r\n border: ${error && 'solid 1px red'};\r\n display: block;\r\n `;\r\n\r\n const Fieldset = styled.div`\r\n margin-bottom: 16px;\r\n `;\r\n\r\n return (\r\n <Fieldset>\r\n <Label htmlFor={htmlId} label={label} required={required} />\r\n <Input\r\n id={htmlId}\r\n type={type}\r\n name={name}\r\n placeholder={placeholder}\r\n value={value}\r\n onChange={onChange}\r\n {...props}/>\r\n {children}\r\n {error && <Error>{error}</Error>}\r\n </Fieldset>\r\n );\r\n};\r\n\r\nTextInputStyledComponent.propTypes = {\r\n /** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */\r\n htmlId: PropTypes.string.isRequired,\r\n\r\n /** Input name. Recommend setting this to match object's property so a single change handler can be used. */\r\n name: PropTypes.string.isRequired,\r\n\r\n /** Input label */\r\n label: PropTypes.string.isRequired,\r\n\r\n /** Input type */\r\n type: PropTypes.oneOf(['text', 'number', 'password']),\r\n\r\n /** Mark label with asterisk if set to true */\r\n required: PropTypes.bool,\r\n\r\n /** Function to call onChange */\r\n onChange: PropTypes.func.isRequired,\r\n\r\n /** Placeholder to display when empty */\r\n placeholder: PropTypes.string,\r\n\r\n /** Value */\r\n value: PropTypes.any,\r\n\r\n /** String to display when error occurs */\r\n error: PropTypes.string,\r\n\r\n /** Child component to display next to the input */\r\n children: PropTypes.node\r\n};\r\n\r\nexport default TextInputStyledComponent;\r\n","examples":[{"name":"ExampleError","description":"Required TextBox with error","code":"import React from 'react';\r\nimport TextInputStyledComponent from 'ps-react-train-tlr/TextInputStyledComponents';\r\n\r\n/** Required TextBox with error */\r\nexport default class ExampleError extends React.Component {\r\n render() {\r\n return (\r\n <TextInputStyledComponent\r\n htmlId=\"example-optional\"\r\n label=\"First Name\"\r\n name=\"firstname\"\r\n onChange={() => {}}\r\n required\r\n error=\"Give me a name, man!\"\r\n />\r\n )\r\n }\r\n}\r\n"}]}] |
blueocean-material-icons/src/js/components/svg-icons/navigation/more-vert.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const NavigationMoreVert = (props) => (
<SvgIcon {...props}>
<path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/>
</SvgIcon>
);
NavigationMoreVert.displayName = 'NavigationMoreVert';
NavigationMoreVert.muiName = 'SvgIcon';
export default NavigationMoreVert;
|
dev/web/www/js/components/navbar/Logout.js | zajacmarekcom/letswrite | import React from 'react'
import {Navbar, Nav, NavItem} from 'react-bootstrap'
import { LinkContainer } from 'react-router-bootstrap'
class Logout extends React.Component {
getUserWelcome(){
return 'Welcome ' + this.props.user.firstName + ' ' + this.props.user.lastName
}
render() {
return (
<Navbar.Collapse>
<Nav>
<LinkContainer to='/story/new-story'>
<NavItem className='navbar--highlighted-item'>New story</NavItem>
</LinkContainer>
</Nav>
<Nav pullRight>
<Navbar.Text>{this.getUserWelcome()}</Navbar.Text>
<NavItem onClick={this.props.logoutUser}>Logout</NavItem>
</Nav>
</Navbar.Collapse>
)
}
}
export default Logout |
src/components/SearchBox.js | danielzy95/mechanic-finder | import React from 'react';
import PropTypes from 'prop-types';
import { Link, withRouter } from 'react-router-dom';
import styles from './SearchBox.css';
const linkStyle = { color: "#fff", textDecoration: "none" };
function search(history, value) {
value = value.trim();
if (value.length > 0)
history.push(`/buscar?q=${value}`);
}
const Input = withRouter(({ value, onChange, history }) => (
<input type="text" placeholder="e.g Auseva"
value={value} onChange={onChange}
onKeyPress={e => { if (e.which == 13) search(history, value); }} autoFocus />
));
const Button = withRouter(({ history, searchText, children }) => (
<button onClick={() => search(history, searchText)} style={{ cursor: 'pointer' }}>{children}</button>
));
const SearchBox = ({ className = '', style = {}, value, onChange }) => (
<div className={`${styles.root} ${className}`} style={style}>
<Input value={value} onChange={onChange} />
<Button searchText={value}>Search</Button>
</div>
);
SearchBox.propTypes = {
className: PropTypes.string,
style: PropTypes.object,
value: PropTypes.string,
onChange: PropTypes.func
};
export default SearchBox; |
lib/routes-creater/routeUtils.js | kuflash/react-router-sitemap | import React from 'react';
/**
* @description Use React method to test if is a valid React Element.
* @param {Object} object - Which to test if is valid React Element.
* @return {Boolean}
* @ignore
*/
const isValidChild = object => {
return object === null || React.isValidElement(object);
};
/**
* @param {Object|array}
* @return {Boolean}
* @ignore
*/
const isReactChildren = object => {
return isValidChild(object) || (Array.isArray(object) && object.every(isValidChild));
};
/**
* @description Creates and returns a routes object from the given ReactChildren. JSX
* provides a convenient way to visualize how routes in the hierarchy are
* nested.
* @param {ReactChildren} children - ReactChildren in JSX
* @return {Object} routes object
* @ignore
*/
const createRoutesFromReactChildren = children => {
const routes = [];
/**
* @param {Object} element - ReactChild
* @return {Object} route object
* @ignore
*/
const createRouteFromReactElement = element => {
const type = element.type;
const route = Object.assign({}, type.defaultProps, element.props);
if (route.children) {
const childRoutes = createRoutesFromReactChildren(route.children, route);
if (childRoutes.length) {
route.childRoutes = childRoutes;
}
delete route.children;
}
return route;
};
React.Children.forEach(children, function (element) {
if (React.isValidElement(element)) {
// Component classes may have a static create* method.
if (element.type.createRouteFromReactElement) {
const route = element.type.createRouteFromReactElement(element);
if (route) {
routes.push(route);
}
} else {
routes.push(createRouteFromReactElement(element));
}
}
});
return routes;
};
export {
isValidChild,
isReactChildren,
createRoutesFromReactChildren
};
|
node_modules/react-bootstrap/es/InputGroupButton.js | yeshdev1/Everydays-project | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var InputGroupButton = function (_React$Component) {
_inherits(InputGroupButton, _React$Component);
function InputGroupButton() {
_classCallCheck(this, InputGroupButton);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
InputGroupButton.prototype.render = function render() {
var _props = this.props,
className = _props.className,
props = _objectWithoutProperties(_props, ['className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement('span', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return InputGroupButton;
}(React.Component);
export default bsClass('input-group-btn', InputGroupButton); |
client/src/index.js | mohandere/tukaram-gatha | import React from 'react';
import ReactDOM from 'react-dom';
import {IntlProvider, FormattedMessage, addLocaleData} from 'react-intl';
import mr from 'react-intl/locale-data/mr';
addLocaleData(mr);
import App from './App';
import './index.css';
const m = {
'welcome': 'स्वागत आहे',
'tukaram-gatha': 'तुकाराम गाथा',
'tukaram-maharaj': 'तुकाराम महाराज',
'sant-tukaram-gatha': 'संत तुकाराम गाथा',
'abhanga': 'अभंग',
'index': 'अनुक्रमणिका',
'serial': 'अनुक्रमांक',
'page': 'पृष्ठ',
'home': 'मुख्य पृष्ठ',
'about': 'माहिती',
'read': 'वाचा',
'previous': 'मागील',
'next': 'पुढे',
'read-more': 'अधिक वाचा',
'go': 'जा',
'go-back': 'मागे जा',
'search': 'शोधा',
'character': 'वर्ण',
'gallery': 'प्रतिमा संग्रह',
'events': 'प्रसंग',
'other': 'इतर',
'no-results': 'अभंग शोधले नाही.'
};
ReactDOM.render(
<IntlProvider locale="mr" messages={m}>
<App />
</IntlProvider>,
document.getElementById('root')
);
|
assets/js/client.es6.js | curioussavage/reddit-mobile | import 'babel/polyfill';
import '../../src/lib/dnt';
import errorLog from '../../src/lib/errorLog';
function onError(message, url, line, column) {
errorLog({
userAgent: window.navigator.userAgent,
message,
url,
line,
column,
requestUrl: window.location.toString()
}, {
hivemind: window.bootstrap && window.bootstrap.config ? window.bootstrap.config.statsURL : undefined,
});
}
// Register as early as possible
window.onerror = onError;
import React from 'react';
import ReactDOM from 'react-dom';
import throttle from 'lodash/function/throttle';
import forOwn from 'lodash/object/forOwn';
import ClientReactApp from 'horse-react/src/client';
import attachFastClick from 'fastclick';
import mixin from '../../src/app-mixin';
import querystring from 'querystring';
import superagent from 'superagent';
var App = mixin(ClientReactApp);
import defaultConfig from '../../src/config';
import constants from '../../src/constants';
import cookies from 'cookies-js';
import getTimes from '../../src/lib/timing';
import setLoggedOutCookies from '../../src/lib/loid';
import routes from '../../src/routes';
import trackingEvents from './trackingEvents';
import EUCountries from '../../src/EUCountries';
const isSafari = window.navigator.userAgent.indexOf('Safari') > -1;
let _lastWinWidth = 0;
let winWidth = window.innerWidth;
var beginRender = 0;
var $body = document.body || document.getElementsByTagName('body')[0];
var $head = document.head || document.getElementsByTagName('head')[0];
var config = defaultConfig();
function loadShim() {
var shimScript = document.createElement('script');
shimScript.type = 'text\/javascript';
shimScript.onload = function() {
initialize(false);
}
$head.appendChild(shimScript, document.currentScript);
shimScript.src = window.bootstrap.config.assetPath + '/js/es5-shims.js';
}
function onLoad(fn) {
if (document.readyState !== 'complete' && document.readyState !== 'interactive') {
window.addEventListener('DOMContentLoaded', fn);
} else {
fn();
}
}
function redirect(status, path) {
if ((typeof status === 'string') && !path) {
path = status;
}
if (path.indexOf('/login') > -1 || path.indexOf('/register') > -1 ) {
window.location = path;
} else {
this.redirect(path);
}
}
// A few es5 sanity checks
if (!Object.create || !Array.prototype.map || !Object.freeze) {
onLoad(loadShim);
} else {
onLoad(function() {
initialize(true);
});
}
var referrer;
function modifyContext (ctx) {
let baseCtx = this.getState('ctx');
let app = this;
const EUCookie = parseInt(cookies.get('EUCookieNotice')) || 0;
const isEUCountry = EUCountries.indexOf(this.getState('country')) !== -1;
ctx = Object.assign({}, baseCtx, ctx, {
dataCache: app.getState('dataCache') || {},
compact: (cookies.get('compact') || '').toString() === 'true',
showOver18Interstitial: (cookies.get('over18') || 'false').toString() === 'false',
showEUCookieMessage: (EUCookie < constants.EU_COOKIE_HIDE_AFTER_VIEWS) && isEUCountry,
showGlobalMessage: cookies.get((app.config.globalMessage || {}).key) === undefined,
redirect: redirect.bind(app),
env: 'CLIENT',
winWidth: window.innerWidth,
});
if (!ctx.token) {
ctx.loid = cookies.get('loid');
ctx.loidcreated = cookies.get('loidcreated');
}
ctx.headers.referer = referrer;
return ctx;
}
function setTitle(props={}) {
let $title = document.getElementsByTagName('title')[0];
if (props.title) {
if ($title.textContent) {
$title.textContent = props.title;
} else if ($title.innerText) {
$title.innerText = props.title;
}
}
}
function refreshToken (app) {
app.setState('refreshingToken', true);
return new Promise(function(resolve, reject) {
superagent
.get('/oauth2/refresh')
.end(function(err, res) {
if (err) {
reject(err);
}
var token = res.body;
var now = new Date();
var expires = new Date(token.tokenExpires);
Object.assign(app.getState('ctx'), {
token: token.token,
tokenExpires: token.tokenExpires
});
app.setState('refreshingToken', false);
app.emit('token:refresh', token);
window.setTimeout(function() {
refreshToken(app).then(function(){
Object.assign(app.getState('ctx'), {
token: token.token,
tokenExpires: token.tokenExpires
});
app.setState('refreshingToken', false);
app.emit('token:refresh', token);
});
}, (expires - now) * .9);
});
})
}
function findLinkParent(el) {
if (el.parentNode) {
if (el.parentNode.tagName === 'A') {
return el.parentNode;
}
return findLinkParent(el.parentNode);
}
}
function elementInDropdown(el) {
if (el.classList && el.classList.contains(constants.DROPDOWN_CSS_CLASS)) {
return true;
} else if (el.parentNode) {
return elementInDropdown(el.parentNode);
} else {
return false;
}
}
function sendTimings() {
// Send the timings during the next cycle.
if (window.bootstrap.actionName) {
if (Math.random() < .1) { // 10% of requests
var timings = Object.assign({
actionName: 'm.server.' + window.bootstrap.actionName,
}, getTimes());
timings.mountTiming = (Date.now() - beginRender) / 1000;
superagent
.post('/timings')
.timeout(constants.DEFAULT_API_TIMEOUT)
.send({
rum: timings,
})
.end(function(){});
}
}
}
function render (app, ...args) {
return new Promise(function(resolve, reject) {
if (app.getState('refreshingToken')) {
ReactDOM.render(app.loadingpage(), app.config.mountPoint);
app.on('token:refresh', function() {
app.render(...args).then(resolve, reject);
});
} else {
app.render(...args).then(resolve, reject);
}
});
}
function initialize(bindLinks) {
const dataCache = window.bootstrap.dataCache;
var plugin;
var p;
referrer = document.referrer;
config.mountPoint = document.getElementById('app-container');
forOwn(config, function(val, key) {
if (window.bootstrap.config[key]) {
config[key] = window.bootstrap.config[key];
}
});
config.seed = window.bootstrap.seed || Math.random();
var app = new App(config);
routes(app);
app.setState('userSubscriptions', dataCache.userSubscriptions);
if (dataCache.user) {
app.setState('user', dataCache.user);
app.setState('preferences', dataCache.preferences);
cookies.set('over18', dataCache.preferences.body.over_18);
}
app.emitter.setMaxListeners(30);
if (app.getState('token')) {
var now = new Date();
var expires = new Date(app.getState('tokenExpires'));
var refreshMS = (expires - now);
// refresh a little before it expires, to be safe
refreshMS *= .90;
// if it's within a minute, refresh now
refreshMS = Math.max(refreshMS - (1000 * 60), 0);
window.setTimeout(function() {
refreshToken(app).then(function(){});
}, refreshMS);
} else if (!cookies.get('loid')) {
setLoggedOutCookies(cookies, app);
}
app.router.get('/oauth2/login', function * () {
window.location = '/oauth2/login';
});
// env comes from bootstrap from the server, update now that the client is loading
app.state.ctx.env = 'CLIENT';
modifyContext = modifyContext.bind(app);
app.modifyContext = modifyContext;
var history = window.history || window.location.history;
app.pushState = (data, title, url) => {
if (history) {
history.pushState(data, title, url);
}
};
app.redirect = function(url) {
app.pushState(null, null, url);
// Set to the browser's interpretation of the current name (to make
// relative paths easier), and send in the old url.
render(app, app.fullPathName(), false, modifyContext).then(function(props) {
setTitle(props);
});
}
app.forceRender = function (view, props) {
ReactDOM.render(view(props), app.config.mountPoint);
}
var scrollCache = {};
var initialUrl = app.fullPathName();
function postRender(href) {
return function(props) {
if(scrollCache[href]) {
$body.scrollTop = scrollCache[href];
} else {
$body.scrollTop = 0;
}
setTitle(props);
if (!props.data.get('subreddit')) {
setMetaColor(constants.DEFAULT_KEY_COLOR);
}
}
}
function logMissingHref($link) {
const $linkClone = $link.cloneNode(true);
const $tmpWrapper = document.createElement('div');
$tmpWrapper.appendChild($linkClone);
const linkStringified = $tmpWrapper.innerHTML;
const error = {
message: 'A tag missing HREF',
linkStringified,
};
const options = {
redirect: false,
replaceBody: false,
};
app.error(error, app.getState('ctx'), app, options);
}
function attachEvents() {
attachFastClick(document.body);
if (history && bindLinks) {
$body.addEventListener('click', function(e) {
let $link = e.target;
if ($link.tagName !== 'A') {
$link = findLinkParent($link);
if (!$link) {
return;
}
}
const href = $link.getAttribute('href');
if (!href) {
logMissingHref($link);
return;
}
const currentUrl = app.fullPathName();
// If it has a target=_blank, or an 'external' data attribute, or it's
// an absolute url, let the browser route rather than forcing a capture.
if (
($link.target === '_blank' || $link.dataset.noRoute === 'true') ||
href.indexOf('//') > -1
) {
return;
}
// If the href contains script ignore it
if (/^javascript:/.test(href)) {
return;
}
e.preventDefault();
scrollCache[currentUrl] = window.scrollY;
if (href.indexOf('#') === 0) {
return;
}
initialUrl = href;
// Update the referrer before navigation
const a = document.createElement('a');
a.href = currentUrl;
referrer = a.href;
app.pushState(null, null, href);
// Set to the browser's interpretation of the current name (to make
// relative paths easier), and send in the old url.
render(app, app.fullPathName(), false, modifyContext).then(postRender(href));
});
window.addEventListener('popstate', function(e) {
var href = app.fullPathName();
scrollCache[initialUrl] = window.scrollY;
render(app, href, false, modifyContext).then(postRender(href));
initialUrl = href;
});
}
}
// Don't re-render tracking pixel on first load. App reads from state
// (bootstrap) on first load, so override state, and then set the proper
// config value after render.
beginRender = Date.now();
// If we're using an old render cache from a restore, nuke it
if ((beginRender - window.bootstrap.render) > 1000 * 60 * 5) {
app.setState('dataCache');
}
render(app, app.fullPathName(), true, modifyContext).then(function() {
app.setState('dataCache');
attachEvents();
referrer = document.location.href;
sendTimings();
});
app.on('route:desktop', function(route) {
let options = {};
let date = new Date();
date.setFullYear(date.getFullYear() + 2);
options.expires = date;
if (window.location.host.indexOf('localhost') === -1) {
var domain = '.' + window.bootstrap.config.reddit.match(/https?:\/\/(.+)/)[1].split('.').splice(1,2).join('.');
options.domain = domain;
}
cookies.set('__cf_mob_redir', '0', options);
if (route.indexOf('?') === -1) {
route += '?ref_source=mweb';
} else {
route += '&ref_source=mweb';
}
window.location = `https://www.reddit.com${route}`;
});
app.on(constants.COMPACT_TOGGLE, function(compact) {
app.setState('compact', compact);
});
app.on(constants.TOGGLE_OVER_18, function(val) {
cookies.set('over18', val);
});
app.on(constants.HIDE_GLOBAL_MESSAGE, function(message) {
let options = {
expires: new Date(message.expires),
};
cookies.set(message.key, 'globalMessageSeen', options);
});
const elementCanScroll = function elementCanScroll(el) {
const top = el.scrollTop;
if (top <= 0) {
el.scrollTop = 1;
return false;
}
const totalScroll = top + el.offsetHeight;
if (totalScroll === el.scrollHeight) {
el.scrollTop = top - 1;
return false;
}
return true;
};
const stopScroll = throttle(function stopScroll(e) {
let touchMoveAllowed = false;
let target = e.target;
while (target !== null) {
if (target.classList && target.classList.contains(constants.OVERLAY_MENU_CSS_CLASS)) {
if (elementCanScroll(target)) {
touchMoveAllowed = true;
}
break;
}
target = target.parentNode;
}
if (!touchMoveAllowed) {
e.preventDefault();
}
}, 50);
app.on(constants.OVERLAY_MENU_OPEN, function(open) {
if (!$body.classList) {
return;
}
// Scrolling on Safari is weird, possibly iOS 9. Overflow hidden doesn't
// prevent the page background from scrolling as you'd expect.
// When we're on Safari we do a fancy check to stop touchmove events
// from scrolling the background.
// We don't use position: fixed becuase the repaint from changing position
// is slow in safari. Plus there's extra bookkeeping for preserving the
// scroll position.
if (open) {
if ($body.classList.contains(constants.OVERLAY_MENU_VISIBLE_CSS_CLASS)) {
return;
}
$body.classList.add(constants.OVERLAY_MENU_VISIBLE_CSS_CLASS);
if (isSafari) {
$body.addEventListener('touchmove', stopScroll);
}
} else {
$body.classList.remove(constants.OVERLAY_MENU_VISIBLE_CSS_CLASS);
if (isSafari) {
$body.removeEventListener('touchmove', stopScroll);
}
}
});
function closeDropdowns() {
// close any opened dropdown by faking another dropdown opening
app.emit(constants.DROPDOWN_OPEN);
}
window.addEventListener('click', function(e) {
if (!elementInDropdown(e.target)) {
closeDropdowns();
}
});
window.addEventListener('scroll', throttle(function(e) {
app.emit(constants.SCROLL);
}.bind(app), 100));
window.addEventListener('resize', throttle(function(e) {
// Prevent resize from firing when chrome shows/hides nav bar
if (winWidth !== _lastWinWidth) {
_lastWinWidth = winWidth;
app.emit(constants.RESIZE);
}
}.bind(app), 100));
function setMetaColor (color) {
const metas = Array.prototype.slice.call(document.getElementsByTagName('meta'));
const tag = metas.find(function(m) {
return m.getAttribute('name') === 'theme-color';
});
tag.content = color;
}
app.on(constants.SET_META_COLOR, setMetaColor);
if (window.bootstrap.config.googleAnalyticsId) {
trackingEvents(app);
}
}
module.exports = initialize;
|
src/svg-icons/action/done-all.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionDoneAll = (props) => (
<SvgIcon {...props}>
<path d="M18 7l-1.41-1.41-6.34 6.34 1.41 1.41L18 7zm4.24-1.41L11.66 16.17 7.48 12l-1.41 1.41L11.66 19l12-12-1.42-1.41zM.41 13.41L6 19l1.41-1.41L1.83 12 .41 13.41z"/>
</SvgIcon>
);
ActionDoneAll = pure(ActionDoneAll);
ActionDoneAll.displayName = 'ActionDoneAll';
ActionDoneAll.muiName = 'SvgIcon';
export default ActionDoneAll;
|
renderer/components/Form/FiatAmountInput.js | LN-Zap/zap-desktop | import React from 'react'
import PropTypes from 'prop-types'
import { compose } from 'redux'
import { asField } from 'informed'
import { convert } from '@zap/utils/btc'
import { formatValue, parseNumber } from '@zap/utils/crypto'
import { withNumberInputMask, withNumberValidation } from 'hocs'
import { BasicInput } from './Input'
/**
* @name FiatAmountInput
*/
class FiatAmountInput extends React.Component {
static propTypes = {
currency: PropTypes.string.isRequired,
currentTicker: PropTypes.object.isRequired,
fieldApi: PropTypes.object.isRequired,
fieldState: PropTypes.object.isRequired,
isRequired: PropTypes.bool,
onBlur: PropTypes.func,
onChange: PropTypes.func,
}
componentDidUpdate(prevProps) {
const { currency, currentTicker, fieldApi, fieldState } = this.props
// Reformat the value when the currency unit has changed.
if (currency !== prevProps.currency) {
let { value } = fieldState
const lastPriceInOrigCurrency = currentTicker[prevProps.currency]
const lastPriceInNewCurrency = currentTicker[currency]
// Convert to BTC.
const btcValue = convert('fiat', 'btc', value, lastPriceInOrigCurrency)
// Convert to new currency.
const newFiatValue = convert('btc', 'fiat', btcValue, lastPriceInNewCurrency)
const [integer, fractional] = parseNumber(newFiatValue, FiatAmountInput.getRules().precision)
value = formatValue(integer, fractional)
fieldApi.setValue(value)
}
// If the value has changed, reformat it if needed.
const valueBefore = prevProps.fieldState.value
const valueAfter = fieldState.value
if (valueAfter !== valueBefore) {
const [integer, fractional] = parseNumber(valueAfter, FiatAmountInput.getRules().precision)
const formattedValue = formatValue(integer, fractional)
if (formattedValue !== valueAfter) {
fieldApi.setValue(formattedValue)
}
}
}
static getRules() {
return {
precision: 2,
step: '0.01',
placeholder: '0.00',
pattern: '[0-9]*.?[0-9]{0,2}?',
}
}
render() {
const rules = FiatAmountInput.getRules()
return (
<BasicInput
{...this.props}
pattern={rules.pattern}
placeholder={rules.placeholder}
step={rules.step}
type="number"
/>
)
}
}
const FiatAmountInputAsField = compose(
withNumberValidation,
asField,
withNumberInputMask
)(FiatAmountInput)
// Wrap the select field to apply conditional validation.
const WrappedFiatAmountInputAsField = props => {
const { isRequired } = props
return <FiatAmountInputAsField moreThan={isRequired ? 0 : null} {...props} />
}
WrappedFiatAmountInputAsField.propTypes = {
isRequired: PropTypes.bool,
}
export default WrappedFiatAmountInputAsField
|
src/interface/report/ReportLoader.js | sMteX/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import { compose } from 'redux';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { t } from '@lingui/macro';
import { fetchFights, LogNotFoundError } from 'common/fetchWclApi';
import { captureException } from 'common/errorLogger';
import { i18n } from 'interface/RootLocalizationProvider';
import { setReport } from 'interface/actions/report';
import { getReportCode } from 'interface/selectors/url/report';
import makeAnalyzerUrl from 'interface/common/makeAnalyzerUrl';
import ActivityIndicator from 'interface/common/ActivityIndicator';
import DocumentTitle from 'interface/common/DocumentTitle';
import handleApiError from './handleApiError';
// During peak traffic we might want to disable automatic refreshes to avoid hitting the rate limit.
// During regular traffic we should enable this as the fight caching is confusing users.
// Actually leaving this disabled for now so we can continue to serve reports when WCL goes down and high traffic to a specific report page doesn't bring us down (since everything would be logged). To solve the issue of confusion, I'll try improving the fight selection text instead.
const REFRESH_BY_DEFAULT = false;
class ReportLoader extends React.PureComponent {
static propTypes = {
children: PropTypes.func.isRequired,
reportCode: PropTypes.string,
setReport: PropTypes.func.isRequired,
history: PropTypes.shape({
push: PropTypes.func.isRequired, // adds to browser history
}).isRequired,
};
state = {
error: null,
report: null,
};
constructor(props) {
super(props);
this.handleRefresh = this.handleRefresh.bind(this);
}
setState(error = null, report = null) {
super.setState({
error,
report,
});
// We need to set the report in the global state so the NavigationBar, which is not a child of this component, can also use it
this.props.setReport(report);
}
resetState() {
this.setState(null, null);
}
componentDidMount() {
if (this.props.reportCode) {
// noinspection JSIgnoredPromiseFromCall
this.loadReport(this.props.reportCode, REFRESH_BY_DEFAULT);
}
}
componentDidUpdate(prevProps, prevState) {
if (this.props.reportCode && this.props.reportCode !== prevProps.reportCode) {
// noinspection JSIgnoredPromiseFromCall
this.loadReport(this.props.reportCode);
}
}
async loadReport(reportCode, refresh = false) {
try {
this.resetState();
const report = await fetchFights(reportCode, refresh);
if (this.props.reportCode !== reportCode) {
return; // the user switched report already
}
this.setState(null, {
...report,
code: reportCode, // Pass the code so know which report this is
// TODO: Remove the code prop
});
// We need to set the report in the global state so the NavigationBar, which is not a child of this component, can also use it
} catch (err) {
const isCommonError = err instanceof LogNotFoundError;
if (!isCommonError) {
captureException(err);
}
this.setState(err, null);
}
}
handleRefresh() {
// noinspection JSIgnoredPromiseFromCall
this.loadReport(this.props.reportCode, true);
}
renderError(error) {
return handleApiError(error, () => {
this.resetState();
this.props.history.push(makeAnalyzerUrl());
});
}
renderLoading() {
return <ActivityIndicator text={i18n._(t`Pulling report info...`)} />;
}
render() {
const error = this.state.error;
if (error) {
return this.renderError(error);
}
const report = this.state.report;
if (!report) {
return this.renderLoading();
}
return (
<>
{/* TODO: Refactor the DocumentTitle away */}
<DocumentTitle title={report.title} />
{this.props.children(report, this.handleRefresh)}
</>
);
}
}
const mapStateToProps = state => ({
reportCode: getReportCode(state),
});
export default compose(
withRouter,
connect(mapStateToProps, {
setReport,
})
)(ReportLoader);
|
packages/material-ui-icons/src/LeakRemove.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M10 3H8c0 .37-.04.72-.12 1.06l1.59 1.59C9.81 4.84 10 3.94 10 3zM3 4.27l2.84 2.84C5.03 7.67 4.06 8 3 8v2c1.61 0 3.09-.55 4.27-1.46L8.7 9.97C7.14 11.24 5.16 12 3 12v2c2.71 0 5.19-.99 7.11-2.62l2.5 2.5C10.99 15.81 10 18.29 10 21h2c0-2.16.76-4.14 2.03-5.69l1.43 1.43C14.55 17.91 14 19.39 14 21h2c0-1.06.33-2.03.89-2.84L19.73 21 21 19.73 4.27 3 3 4.27zM14 3h-2c0 1.5-.37 2.91-1.02 4.16l1.46 1.46C13.42 6.98 14 5.06 14 3zm5.94 13.12c.34-.08.69-.12 1.06-.12v-2c-.94 0-1.84.19-2.66.52l1.6 1.6zm-4.56-4.56l1.46 1.46C18.09 12.37 19.5 12 21 12v-2c-2.06 0-3.98.58-5.62 1.56z" /></g>
, 'LeakRemove');
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.