path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
actor-apps/app-web/src/app/components/activity/GroupProfile.react.js | gaolichuang/actor-platform | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
import { assign } from 'lodash';
import React from 'react';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import classnames from 'classnames';
import ActorClient from 'utils/ActorClient';
import confirm from 'utils/confirm'
import DialogActionCreators from 'actions/DialogActionCreators';
import GroupProfileActionCreators from 'actions/GroupProfileActionCreators';
import InviteUserActions from 'actions/InviteUserActions';
import EditGroupActionCreators from 'actions/EditGroupActionCreators';
import LoginStore from 'stores/LoginStore';
import PeerStore from 'stores/PeerStore';
import DialogStore from 'stores/DialogStore';
import GroupStore from 'stores/GroupStore';
import AvatarItem from 'components/common/AvatarItem.react';
import InviteUser from 'components/modals/InviteUser.react';
import InviteByLink from 'components/modals/invite-user/InviteByLink.react';
import GroupProfileMembers from 'components/activity/GroupProfileMembers.react';
import Fold from 'components/common/Fold.React';
import EditGroup from 'components/modals/EditGroup.react';
const getStateFromStores = (groupId) => {
const thisPeer = PeerStore.getGroupPeer(groupId);
return {
thisPeer: thisPeer,
isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer),
integrationToken: GroupStore.getIntegrationToken()
};
};
let _prevGroupId;
@ReactMixin.decorate(IntlMixin)
class GroupProfile extends React.Component {
static propTypes = {
group: React.PropTypes.object.isRequired
};
constructor(props) {
super(props);
const myId = LoginStore.getMyId();
this.state = assign({
isMoreDropdownOpen: false
}, getStateFromStores(props.group.id));
if (props.group.members.length > 0 && myId === props.group.adminId) {
GroupProfileActionCreators.getIntegrationToken(props.group.id);
}
DialogStore.addNotificationsListener(this.onChange);
GroupStore.addChangeListener(this.onChange);
}
componentWillUnmount() {
DialogStore.removeNotificationsListener(this.onChange);
GroupStore.removeChangeListener(this.onChange);
}
componentWillReceiveProps(newProps) {
const myId = LoginStore.getMyId();
// FIXME!!!
setTimeout(() => {
this.setState(getStateFromStores(newProps.group.id));
if (newProps.group.id !== _prevGroupId && newProps.group.members.length > 0 && myId === newProps.group.adminId) {
GroupProfileActionCreators.getIntegrationToken(newProps.group.id);
_prevGroupId = newProps.group.id;
}
}, 0);
}
onAddMemberClick = group => {
InviteUserActions.show(group);
};
onLeaveGroupClick = gid => {
confirm('Do you really want to leave this conversation?').then(
() => DialogActionCreators.leaveGroup(gid),
() => {}
);
};
onNotificationChange = event => {
const { thisPeer } = this.state;
DialogActionCreators.changeNotificationsEnabled(thisPeer, event.target.checked);
};
onChange = () => {
this.setState(getStateFromStores(this.props.group.id));
};
selectToken = (event) => {
event.target.select();
};
toggleMoreDropdown = () => {
const { isMoreDropdownOpen } = this.state;
if (!isMoreDropdownOpen) {
this.setState({isMoreDropdownOpen: true});
document.addEventListener('click', this.closeMoreDropdown, false);
} else {
this.closeMoreDropdown();
}
};
closeMoreDropdown = () => {
this.setState({isMoreDropdownOpen: false});
document.removeEventListener('click', this.closeMoreDropdown, false);
};
onClearGroupClick = (gid) => {
confirm('Do you really want to clear this conversation?').then(
() => {
const peer = ActorClient.getGroupPeer(gid);
DialogActionCreators.clearChat(peer)
},
() => {}
);
};
onDeleteGroupClick = (gid) => {
confirm('Do you really want to delete this conversation?').then(
() => {
const peer = ActorClient.getGroupPeer(gid);
DialogActionCreators.deleteChat(peer);
},
() => {}
);
};
onEditGroupClick = (gid) => {
EditGroupActionCreators.show(gid)
};
render() {
const { group } = this.props;
const {
isNotificationsEnabled,
integrationToken,
isMoreDropdownOpen
} = this.state;
const myId = LoginStore.getMyId();
const admin = GroupProfileActionCreators.getUser(group.adminId);
const isMember = DialogStore.isGroupMember(group);
let adminControls;
if (group.adminId === myId) {
adminControls = [
<li className="dropdown__menu__item hide">
<i className="material-icons">photo_camera</i>
<FormattedMessage message={this.getIntlMessage('setGroupPhoto')}/>
</li>
,
<li className="dropdown__menu__item hide">
<svg className="icon icon--dropdown"
dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#integration"/>'}}/>
<FormattedMessage message={this.getIntlMessage('addIntegration')}/>
</li>
,
<li className="dropdown__menu__item" onClick={() => this.onEditGroupClick(group.id)}>
<i className="material-icons">mode_edit</i>
<FormattedMessage message={this.getIntlMessage('editGroup')}/>
</li>
];
}
const members = <FormattedMessage message={this.getIntlMessage('members')} numMembers={group.members.length}/>;
const dropdownClassNames = classnames('dropdown', {
'dropdown--opened': isMoreDropdownOpen
});
const iconElement = (
<svg className="icon icon--green"
dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#members"/>'}}/>
);
const groupMeta = [
<header>
<AvatarItem image={group.bigAvatar}
placeholder={group.placeholder}
size="large"
title={group.name}/>
<h3 className="group_profile__meta__title">{group.name}</h3>
<div className="group_profile__meta__created">
<FormattedMessage admin={admin.name} message={this.getIntlMessage('createdBy')}/>
</div>
</header>
,
group.about ? <div className="group_profile__meta__description">{group.about}</div> : null
];
const token = (group.adminId === myId) ? (
<li className="profile__list__item group_profile__integration no-p">
<Fold icon="power" iconClassName="icon--pink" title="Integration Token">
<div className="info info--light">
If you have programming chops, or know someone who does,
this integration token allow the most flexibility and communication
with your own systems.
<a href="https://actor.readme.io/docs/simple-integration" target="_blank">Learn how to integrate</a>
</div>
<textarea className="token" onClick={this.selectToken} readOnly row="3" value={integrationToken}/>
</Fold>
</li>
) : null;
if (isMember) {
return (
<div className="activity__body group_profile">
<ul className="profile__list">
<li className="profile__list__item group_profile__meta">
{groupMeta}
<footer className="row">
<div className="col-xs">
<button className="button button--flat button--wide"
onClick={() => this.onAddMemberClick(group)}>
<i className="material-icons">person_add</i>
<FormattedMessage message={this.getIntlMessage('addPeople')}/>
</button>
</div>
<div style={{width: 10}}/>
<div className="col-xs">
<div className={dropdownClassNames}>
<button className="dropdown__button button button--flat button--wide"
onClick={this.toggleMoreDropdown}>
<i className="material-icons">more_horiz</i>
<FormattedMessage message={this.getIntlMessage('more')}/>
</button>
<ul className="dropdown__menu dropdown__menu--right">
{adminControls}
<li className="dropdown__menu__item dropdown__menu__item--light"
onClick={() => this.onLeaveGroupClick(group.id)}>
<FormattedMessage message={this.getIntlMessage('leaveGroup')}/>
</li>
<li className="dropdown__menu__item dropdown__menu__item--light"
onClick={() => this.onClearGroupClick(group.id)}>
<FormattedMessage message={this.getIntlMessage('clearGroup')}/>
</li>
<li className="dropdown__menu__item dropdown__menu__item--light"
onClick={() => this.onDeleteGroupClick(group.id)}>
<FormattedMessage message={this.getIntlMessage('deleteGroup')}/>
</li>
</ul>
</div>
</div>
</footer>
</li>
<li className="profile__list__item group_profile__media no-p hide">
<Fold icon="attach_file" iconClassName="icon--gray" title={this.getIntlMessage('sharedMedia')}>
<ul>
<li><a>230 Shared Photos and Videos</a></li>
<li><a>49 Shared Links</a></li>
<li><a>49 Shared Files</a></li>
</ul>
</Fold>
</li>
<li className="profile__list__item group_profile__notifications no-p">
<label htmlFor="notifications">
<i className="material-icons icon icon--squash">notifications_none</i>
<FormattedMessage message={this.getIntlMessage('notifications')}/>
<div className="switch pull-right">
<input checked={isNotificationsEnabled}
id="notifications"
onChange={this.onNotificationChange}
type="checkbox"/>
<label htmlFor="notifications"></label>
</div>
</label>
</li>
<li className="profile__list__item group_profile__members no-p">
<Fold iconElement={iconElement}
title={members}>
<GroupProfileMembers groupId={group.id} members={group.members}/>
</Fold>
</li>
{token}
</ul>
<InviteUser/>
<InviteByLink/>
<EditGroup/>
</div>
);
} else {
return (
<div className="activity__body group_profile">
<ul className="profile__list">
<li className="profile__list__item group_profile__meta">
{groupMeta}
</li>
</ul>
</div>
);
}
}
}
export default GroupProfile;
|
modules/dreamview/frontend/src/components/PNCMonitor/LatencyMonitor.js | xiaoxq/apollo | import React from 'react';
import { inject, observer } from 'mobx-react';
import setting from 'store/config/LatencyGraph.yml';
import ScatterGraph, { generateScatterGraph } from 'components/PNCMonitor/ScatterGraph';
@inject('store') @observer
export default class LatencyMonitor extends React.Component {
render() {
const { lastUpdatedTime, data } = this.props.store.latency;
if (!data) {
return null;
}
const graphs = {};
Object.keys(data).forEach((moduleName) => {
graphs[moduleName] = data[moduleName];
});
return generateScatterGraph(setting, graphs);
}
}
|
react-boilerplate/internals/templates/containers/App/index.js | Sakuyakun/Yorha-Experiment | /**
*
* App.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import HomePage from 'containers/HomePage/Loadable';
import NotFoundPage from 'containers/NotFoundPage/Loadable';
export default function App() {
return (
<div>
<Switch>
<Route exact path="/" component={HomePage} />
<Route component={NotFoundPage} />
</Switch>
</div>
);
}
|
public/src/admin/components/ConfigurationsList.js | SLedunois/Shiva | import React, { Component } from 'react';
class ConfigurationsList extends Component {
render() {
return (
<div className="menu col-9 centered-item">
<h1>Configurations List</h1>
</div>
);
}
}
export default ConfigurationsList;
|
src/icons/GlyphPencil.js | ipfs/webui | import React from 'react'
const GlyphPencil = props => (
<svg viewBox='0 0 100 100' {...props}>
<path d='M23.2 60.5l-4.38 16.33a3.61 3.61 0 0 0 .93 3.42 3.53 3.53 0 0 0 2.53 1 3.94 3.94 0 0 0 .89-.11l16.31-4.36z' />
<path d='M22.28 81.41a3.67 3.67 0 0 1-2.62-1.07 3.75 3.75 0 0 1-1-3.54l4.37-16.34.11-.12.11.08 16.41 16.39-.11.11L23.2 81.3a3.56 3.56 0 0 1-.92.11zm1-20.67l-4.34 16.12a3.49 3.49 0 0 0 .9 3.3 3.39 3.39 0 0 0 2.44 1 3.55 3.55 0 0 0 .86-.1l16.11-4.31zm56.01-33.85l-6.18-6.18a6.92 6.92 0 0 0-5.21-2A7.78 7.78 0 0 0 62.67 21L27.26 56.45l16.29 16.3L79 37.33a7.78 7.78 0 0 0 2.32-5.23 6.88 6.88 0 0 0-2.03-5.21z' />
<path d='M43.55 72.93l-.09-.09-16.38-16.39.09-.09L62.58 21a8 8 0 0 1 5.31-2.36 7 7 0 0 1 5.3 2l6.19 6.19a7 7 0 0 1 2 5.3 8 8 0 0 1-2.36 5.31zM27.44 56.45l16.11 16.12 35.32-35.33a7.69 7.69 0 0 0 2.29-5.14 6.75 6.75 0 0 0-2-5.12L73 20.79a6.86 6.86 0 0 0-5.12-1.95 7.73 7.73 0 0 0-5.14 2.28z' />
</svg>
)
export default GlyphPencil
|
pnpm-offline/.pnpm-store-offline/1/registry.npmjs.org/react-bootstrap/0.31.0/es/InputGroupAddon.js | Akkuma/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 { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var InputGroupAddon = function (_React$Component) {
_inherits(InputGroupAddon, _React$Component);
function InputGroupAddon() {
_classCallCheck(this, InputGroupAddon);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
InputGroupAddon.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 InputGroupAddon;
}(React.Component);
export default bsClass('input-group-addon', InputGroupAddon); |
examples/planout-example/isomorphic/variations/layer_2_bucket_C/components/footer.js | yahoo/mendel | /* Copyright 2015, Yahoo Inc.
Copyrights licensed under the MIT License.
Contributed by Shalom Volchok <shalom@digitaloptgroup.com>
See the accompanying LICENSE file for terms. */
import React from 'react';
const style = {
margin: "20px 0",
padding: "20px",
backgroundColor: "#884EA0"
}
export default () => {
return (
<div style={style}>
<b>footer.js</b><br/>
variations/layer_2_bucket_C/components/footer.js
</div>
);
}
|
packages/react-scripts/fixtures/kitchensink/src/features/webpack/UnknownExtInclusion.js | kst404/e8e-react-scripts | import React from 'react'
import aFileWithExtUnknown from './assets/aFileWithExt.unknown'
const text = aFileWithExtUnknown.includes('base64')
? atob(aFileWithExtUnknown.split('base64,')[1]).trim()
: aFileWithExtUnknown
export default () => (
<p id="feature-unknown-ext-inclusion">{text}.</p>
)
|
frontend/src/System/Logs/Logs.js | geogolem/Radarr | import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import Switch from 'Components/Router/Switch';
import LogFilesConnector from './Files/LogFilesConnector';
import UpdateLogFilesConnector from './Updates/UpdateLogFilesConnector';
class Logs extends Component {
//
// Render
render() {
return (
<Switch>
<Route
exact={true}
path="/system/logs/files"
component={LogFilesConnector}
/>
<Route
path="/system/logs/files/update"
component={UpdateLogFilesConnector}
/>
</Switch>
);
}
}
export default Logs;
|
src/renderer/views/molecules/Corner/index.js | airtoxin/youtubar | import React from 'react';
import styles from './index.css';
export default () => (
<img
className={`${styles.flow} ${styles.curl}`}
src="page-curl.svg"
role="presentation"
/>
);
|
app/component/WebViewPlayer/index.js | andy-shi88/MusicProgramador | import React, { Component } from 'react';
import {
StyleSheet,
Text,
TextInput,
Button,
View,
WebView,
AsyncStorage,
ToastAndroid
} from 'react-native';
import GetTime from '../../service/GetTime';
export default class WebViewPlayer extends Component {
constructor(props) {
super(props);
this.state = {
playlist_url: ''
}
}
componentDidMount() {
const { navigate } = this.props.navigation;
AsyncStorage.getItem(GetTime(), (err, val) => {
if (!val) {
navigate('Home')
ToastAndroid.showWithGravity('Your playlist in this time is empty', ToastAndroid.SHORT, ToastAndroid.CENTER);
} else {
AsyncStorage.getItem(val, (err, val) => {
console.log("==============val=============", val);
this.setState({
playlist_url: val
})
})
}
});
}
render() {
return(
<WebView
source={{uri: this.state.playlist_url}}
/>
);
}
}
|
packages/react-error-overlay/src/components/Footer.js | ro-savage/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* @flow */
import React from 'react';
import { darkGray } from '../styles';
const footerStyle = {
fontFamily: 'sans-serif',
color: darkGray,
marginTop: '0.5rem',
flex: '0 0 auto',
};
type FooterPropsType = {|
line1: string,
line2?: string,
|};
function Footer(props: FooterPropsType) {
return (
<div style={footerStyle}>
{props.line1}
<br />
{props.line2}
</div>
);
}
export default Footer;
|
imports/ui/pages/holidays/NewHoliday.js | KyneSilverhide/team-manager | import React from 'react';
import HolidayEditor from '../../components/holidays/HolidayEditor.js';
const NewHoliday = ({ developer }) => (
<div className="NewTeam">
<h4 className="page-header">{`${developer.firstname} ${developer.lastname}`} : Ajout d'un congé</h4>
<HolidayEditor developer={developer}/>
</div>
);
NewHoliday.propTypes = {
developer: React.PropTypes.object,
};
export default NewHoliday;
|
src/containers/LMap/index.js | Guseff/services-on-map-demo | import React, { Component } from 'react';
import { Map, TileLayer } from 'react-leaflet';
import LMarker from '../LMarker';
import './style.css';
class LMap extends Component {
constructor() {
super();
this.onMapClick = this.onMapClick.bind(this);
}
onMapClick(e) {
if (this.props.loggedUser) {
this.props.closeLoginMenu();
this.props.clickOnMap(e.latlng);
return;
}
this.props.showNotLogin();
}
render() {
const position = this.props.userCoords;
const { markers, showAccept, showAcceptForm, showNotLogin, loggedUser } = this.props;
return (
<Map center={position} zoom={13} onClick={this.onMapClick}>
<TileLayer
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
{markers.map(
(marker, index) => {
if (marker.status !==3 || (!!loggedUser && loggedUser._id === marker.author_id)) {
return (
<LMarker
key={index}
marker={marker}
showAccept={showAccept}
showAcceptForm={showAcceptForm}
showNotLogin={showNotLogin}
loggedUser={loggedUser}
/>
)
}
return null;
}
)}
</Map>
);
}
}
export default LMap;
|
packages/react-art/src/ReactART.js | rricard/react | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import ReactVersion from 'shared/ReactVersion';
import {LegacyRoot} from 'shared/ReactRootTags';
import {
createContainer,
updateContainer,
injectIntoDevTools,
} from 'react-reconciler/inline.art';
import Transform from 'art/core/transform';
import Mode from 'art/modes/current';
import FastNoSideEffects from 'art/modes/fast-noSideEffects';
import {TYPES, childrenAsString} from './ReactARTInternals';
Mode.setCurrent(
// Change to 'art/modes/dom' for easier debugging via SVG
FastNoSideEffects,
);
/** Declarative fill-type objects; API design not finalized */
const slice = Array.prototype.slice;
class LinearGradient {
constructor(stops, x1, y1, x2, y2) {
this._args = slice.call(arguments);
}
applyFill(node) {
node.fillLinear.apply(node, this._args);
}
}
class RadialGradient {
constructor(stops, fx, fy, rx, ry, cx, cy) {
this._args = slice.call(arguments);
}
applyFill(node) {
node.fillRadial.apply(node, this._args);
}
}
class Pattern {
constructor(url, width, height, left, top) {
this._args = slice.call(arguments);
}
applyFill(node) {
node.fillImage.apply(node, this._args);
}
}
/** React Components */
class Surface extends React.Component {
componentDidMount() {
const {height, width} = this.props;
this._surface = Mode.Surface(+width, +height, this._tagRef);
this._mountNode = createContainer(this._surface, LegacyRoot, false, null);
updateContainer(this.props.children, this._mountNode, this);
}
componentDidUpdate(prevProps, prevState) {
const props = this.props;
if (props.height !== prevProps.height || props.width !== prevProps.width) {
this._surface.resize(+props.width, +props.height);
}
updateContainer(this.props.children, this._mountNode, this);
if (this._surface.render) {
this._surface.render();
}
}
componentWillUnmount() {
updateContainer(null, this._mountNode, this);
}
render() {
// This is going to be a placeholder because we don't know what it will
// actually resolve to because ART may render canvas, vml or svg tags here.
// We only allow a subset of properties since others might conflict with
// ART's properties.
const props = this.props;
// TODO: ART's Canvas Mode overrides surface title and cursor
const Tag = Mode.Surface.tagName;
return (
<Tag
ref={ref => (this._tagRef = ref)}
accessKey={props.accessKey}
className={props.className}
draggable={props.draggable}
role={props.role}
style={props.style}
tabIndex={props.tabIndex}
title={props.title}
/>
);
}
}
class Text extends React.Component {
constructor(props) {
super(props);
// We allow reading these props. Ideally we could expose the Text node as
// ref directly.
['height', 'width', 'x', 'y'].forEach(key => {
Object.defineProperty(this, key, {
get: function() {
return this._text ? this._text[key] : undefined;
},
});
});
}
render() {
// This means you can't have children that render into strings...
const T = TYPES.TEXT;
return (
<T {...this.props} ref={t => (this._text = t)}>
{childrenAsString(this.props.children)}
</T>
);
}
}
injectIntoDevTools({
findFiberByHostInstance: () => null,
bundleType: __DEV__ ? 1 : 0,
version: ReactVersion,
rendererPackageName: 'react-art',
});
/** API */
export const ClippingRectangle = TYPES.CLIPPING_RECTANGLE;
export const Group = TYPES.GROUP;
export const Shape = TYPES.SHAPE;
export const Path = Mode.Path;
export {LinearGradient, Pattern, RadialGradient, Surface, Text, Transform};
|
src/components/drawer.js | rdenadai/mockingbird | import { css } from '../css';
import React, { Component } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
const icons = {
home: `${css.fontAwesome.fa} ${css.fontAwesome['fa-home']}`,
add_podcast: `${css.fontAwesome.fa} ${css.fontAwesome['fa-plus-square']}`,
};
class AppDrawer extends Component {
constructor(props) {
super(props);
this.state = { open: false };
}
onTouchTapHandleDrawerToggle = () => this.setState({open: !this.state.open});
render() {
const messages = this.props.messages;
return (
<div>
<AppBar
title={messages.title}
onLeftIconButtonTouchTap={this.onTouchTapHandleDrawerToggle.bind(this)} />
<Drawer
docked={false}
open={this.state.open}
onRequestChange={(open) => this.setState({open})}>
<AppBar title={messages.title} />
<div>
<Link to="/" style={{ textDecoration: 'none' }}>
<MenuItem><li className={icons.home} /> {messages.menu_home}</MenuItem>
</Link>
<Link to="/app/add/" style={{ textDecoration: 'none' }}>
<MenuItem><li className={icons.add_podcast} /> {messages.menu_add_podcast}</MenuItem>
</Link>
</div>
</Drawer>
</div>
);
}
}
AppDrawer.propTypes = {
messages: React.PropTypes.object
};
function mapStateToProps(state) {
return { messages: state.messages };
}
export default connect(mapStateToProps)(AppDrawer);
|
web-ui/src/login/page.js | pixelated/pixelated-user-agent | /*
* Copyright (c) 2017 ThoughtWorks, Inc.
*
* Pixelated 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.
*
* Pixelated 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 Pixelated. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react';
import { translate } from 'react-i18next';
import InputField from 'src/common/input_field/input_field';
import SubmitButton from 'src/common/submit_button/submit_button';
import AuthError from 'src/login/error/auth_error';
import GenericError from 'src/login/error/generic_error';
import Welcome from 'src/login/about/welcome';
import './page.scss';
const errorMessage = (t, authError) => {
if (authError) return <AuthError />;
return <div />;
};
const rightPanel = (t, error) => {
if (error) return <GenericError />;
return <Welcome />;
};
export const Page = ({ t, authError, error }) => (
<div className='login'>
<img
className={error ? 'logo small-logo' : 'logo'}
src='/public/images/logo-orange.svg'
alt='Pixelated logo'
/>
{rightPanel(t, error)}
<form className='standard' id='login_form' action='/login' method='post' noValidate>
{errorMessage(t, authError)}
<InputField name='username' label={t('login.email')} autoFocus />
<InputField type='password' name='password' label={t('login.password')} />
<SubmitButton buttonText={t('login.submit')} />
</form>
</div>
);
Page.propTypes = {
t: React.PropTypes.func.isRequired,
authError: React.PropTypes.bool,
error: React.PropTypes.bool
};
export default translate('', { wait: true })(Page);
|
client/src/app/views/forgot.js | jhuntoo/starhackit | import React from 'react';
import _ from 'lodash';
import LinkedStateMixin from 'react-addons-linked-state-mixin';
import cx from 'classnames';
import RaisedButton from 'material-ui/lib/raised-button';
import DocTitle from 'components/docTitle';
import authActions from 'actions/auth';
import ValidateEmail from 'services/validateEmail';
import ValidateRequiredField from 'services/validateRequiredField';
export default React.createClass( {
mixins: [
LinkedStateMixin,
],
getInitialState() {
return {
step: 'SendPasswordResetEmail',
errors: {}
};
},
render() {
return (
<div id="forgot">
<DocTitle
title="Forgot password"
/>
<legend>Password Reset</legend>
{ this.renderSendPasswordResetEmail()}
{ this.renderCheckEmail() }
</div>
);
},
renderSendPasswordResetEmail() {
if ( this.state.step != 'SendPasswordResetEmail' ) {
return;
}
return (
<div className="panel panel-primary">
<div className="panel-heading">Send Reset Email</div>
<div className="panel-body">
<p><strong>Enter the email address used when you registered with username and password. </strong></p>
<p>You'll be sent a reset code to change your password.</p>
<div className="form-inline">
<div className={ this.formClassNames( 'email' ) }>
<label>Email Address</label>
<input className="form-control"
type="text"
valueLink={ this.linkState( 'email' ) }
/>
{ this.renderErrorsFor( 'email' ) }
</div>
</div>
<div className="spacer">
<RaisedButton onClick={ this.requestReset } label='Send Reset Email'/>
</div>
</div>
</div>
);
},
renderCheckEmail() {
if ( this.state.step != 'CheckEmail' ) {
return;
}
return (
<div className="panel panel-primary animate bounceIn">
<div className="panel-heading">Step 2 - Check Email</div>
<div className="panel-body">
<p><strong>An email has been sent containing your reset link. Click on this link to proceed.</strong></p>
<p>Please also check your spam folder just in case the reset email ended up there.</p>
<p>This page can be safely closed.</p>
</div>
</div>
);
},
renderErrorsFor( field ) {
if ( this.state.errors[ field ] ) {
return (
<span className="label label-danger animate bounceIn">{ this.state.errors[ field ]}</span>
);
}
},
requestReset() {
this.resetErrors();
validateEmail.call( this )
.with( this )
.then( requestReset )
.then( setNextStep )
.catch( errors );
function validateEmail() {
return validateExists.call( this )
.then( validateFormat.bind( this ) );
function validateFormat() {
return new ValidateEmail( this.email() )
.execute();
}
function validateExists() {
return new ValidateRequiredField( 'email', this.email() )
.execute();
}
}
function requestReset() {
return authActions.requestPasswordReset( this.email() );
}
function setNextStep( ) {
this.setState( {
step: 'CheckEmail'
} );
}
function errors( e ) {
if ( e.name === 'CheckitError' ) {
this.setState( {
errors: e.toJSON()
} );
} else {
let error = e.responseJSON;
let message;
message = error.message;
this.setState( {
errors: {
email: message
}
} );
}
}
},
email() {
return _.trim( this.state.email );
},
code() {
return _.trim( this.state.code );
},
password() {
return _.trim( this.state.password );
},
resetErrors() {
this.setState( {
errors: {}
} );
},
formClassNames( field ) {
return cx( 'form-group', {
'has-error': this.state.errors[ field ]
} );
}
} );
|
src/QAApp.js | arunchaganty/briefly | import React, { Component } from 'react';
import {Label, Glyphicon, Panel, Well} from 'react-bootstrap';
import update from 'immutability-helper';
import Experiment from './Experiment.js'
import QAPrompt from './QAPrompt.js'
import SegmentList from './SegmentList';
import './QAApp.css';
const BONUS_VALUE = '0.75';
class App extends Experiment {
constructor(props) {
super(props);
this.handleAnswersChanged = this.handleAnswersChanged.bind(this);
}
title() {
return (<p>Check answers to commonly asked questions</p>);
}
subtitle() {
return null; //(<p><b>Correct grammatical errors, remove repeated text, etc.</b></p>);
}
instructionsVersion() {
return '20180124';
}
instructions() {
return (<InstructionContents
bonus={BONUS_VALUE}
isFirstTime={this.state.firstView}
editable={!this.state.instructionsComplete}
onValueChanged={(val) => this.setState({instructionsComplete: val})}
/>);
}
initState(props) {
let state = super.initState(props);
state = update(state, {
output: {$merge: {
response: QAPrompt.initialValue(props.contents.passages),
PayBonus: state.firstView ? BONUS_VALUE : 0,
}},
});
if (props._output) {
state = update(state, {
output: {$merge: props._output},
canSubmit: {$set: this._canSubmit(props._output.response)},
});
}
return state;
}
_canSubmit(response) {
return !response.plausibility || response.passages.every((_,i) => QAPrompt.getStatus(response, i) === "complete");
}
handleAnswersChanged(evt) {
const valueChange = evt;
this.setState(state => {
state = update(state, {output: {response: QAPrompt.handleValueChanged(state.output.response, valueChange)}});
const canSubmit = this._canSubmit(state.output.response);
if (state.canSubmit !== canSubmit) {
state = update(state, {canSubmit: {$set: canSubmit}});
}
return state;
});
}
renderContents() {
return (<Panel id="content">
<Panel.Heading><Panel.Title><b>Please evaluate the <u>answer</u> to the following question</b></Panel.Title></Panel.Heading>
<Panel.Body>
<QAPrompt
query={this.props.contents.query}
answer={this.props.contents.answer}
passages={this.props.contents.passages}
value={this.state.output.response}
onValueChanged={this.handleAnswersChanged}
/>
</Panel.Body>
</Panel>);
}
}
App.defaultProps = {
contents: {
'query': 'who said the quote by any means necessary',
'query_id': 18482,
'query_type': 'person',
'answers': ['Malcolm X'],
'answer': 'Malcolm X',
'passages': [{'is_selected': 0,
'passage_text': "How meaningful were such charges when they came from whites who brought Malcolm's ancestors to America in chains, then beat and lynched them with impunity? Faced with such crimes, he felt black Americans were entitled to secure their rights by any means necessary -- up to and including the use of violence.",
'url': 'http://www.pbs.org/wgbh/amex/malcolmx/sfeature/sf_means.html'},
{'is_selected': 0,
'passage_text': 'Malcolm X’s life changed dramatically in the first six months of 1964. On March 8, he left the Nation of Islam. In May he toured West Africa and made a pilgrimage to Mecca, returning as El Hajj Malik El-Shabazz. While in Ghana in May, he decided to form the Organization of Afro-American Unity (OAAU).',
'url': 'http://www.blackpast.org/1964-malcolm-x-s-speech-founding-rally-organization-afro-american-unity'},
{'is_selected': 0,
'passage_text': 'By any means necessary is a translation of a phrase used by the French intellectual Jean-Paul Sartre in his play Dirty Hands. It entered the popular civil rights culture through a speech given by Malcolm X at the Organization of Afro-American Unity Founding Rally on June 28, 1964.',
'url': 'https://en.wikipedia.org/wiki/By_any_means_necessary'},
{'is_selected': 0,
'passage_text': "Unknown quotes. On my grind, I'm out to get it by any means necessary. 3 up, 3 down. favorite. Malcolm X quotes. God quotes. The Negro revolution is controlled by foxy white liberals, by the Government itself. But the Black Revolution is controlled only by God.",
'url': 'http://www.searchquotes.com/search/Malcolm_X_By_Any_Means_Necessary/'},
{'is_selected': 0,
'passage_text': "1 of 5 stars 2 of 5 stars 3 of 5 stars 4 of 5 stars 5 of 5 stars. By Any Means Necessary Quotes (showing 1-1 of 1). “You're not to be so blind with patriotism that you can't face reality. Wrong is wrong, no matter who does it or says it.”. ― Malcolm X, By Any Means Necessary.",
'url': 'http://www.goodreads.com/work/quotes/180979-by-any-means-necessary'},
{'is_selected': 1,
'passage_text': '“By any means necessary.”. Malcolm X quotes (American black militant leader who articulated concepts of race pride and black nationalism in the early 1960s, 1925-1965).',
'url': 'http://thinkexist.com/quotation/by-any-means-necessary/557539.html'},
{'is_selected': 0,
'passage_text': "There's a popular saying often repeated by Christians. It has found new life on Facebook and Twitter. Maybe you have even uttered these words, commonly at tributed to Francis of Assisi: Preach the gospel. Use words if necessary..",
'url': 'http://www.christianpost.com/news/preach-the-gospel-and-since-its-necessary-use-words-77231/'}],
},
estimatedTime: 120,
reward: 0.40,
}
/***
* Renders a document within a div.
*/
class Example extends Component {
constructor(props) {
super(props);
this.state = (this.props.editable) ? QAPrompt.initialValue(props.passages)
: {
plausibility: this.props.expected.plausibility,
passages: this.props.expected.passages || [],
selections: this.props.expected.selections || [],
confirmations: this.props.expected.confirmations || [],
idx: 0,
};
this.handleValueChanged = this.handleValueChanged.bind(this);
}
shouldComponentUpdate(nextProps, nextState) {
return (this.props !== nextProps) || (this.state !== nextState);
}
handleValueChanged(evt) {
const valueChange = evt;
// Check here -- don't let them change if this is incorrect?
if (this.props.editable || valueChange.moveTo !== undefined) {
this.setState(state => update(state, QAPrompt.handleValueChanged(state, valueChange)),
() => {
let status = this.checkAnswer()[0];
let ret = (status === "correct") ? true : (status === "wrong") ? false : undefined;
this.props.onChanged(ret);
}
);
}
}
checkAnswer() {
const S = this.state;
const E = this.props.expected;
if (S.plausibility === undefined) {
return ["incomplete", undefined];
} else if (S.plausibility !== E.plausibility) {
return ["wrong", undefined];
} else if (S.passages.length > 0) { // passage-based checks.
// Incorrect passage judgement.
let idx;
idx = S.passages.findIndex((p,i) => p !== undefined && p !== E.passages[i]);
if (idx > -1) {
return ["wrong-passage", idx]; // say things are false early.
}
idx = S.selections.findIndex((p,i) => p !== undefined && S.passages[i] !== undefined && E.selections[i].length > 0 && p.length === 0)
if (idx > -1) {
return ["missing-highlight", idx];
}
idx = S.selections.findIndex((p,i) => p !== undefined && S.passages[i] !== undefined && E.selections[i].length > 0 && SegmentList.jaccard(p, E.selections[i]) < 0.01);
if (idx > -1) {
return ["wrong-highlight", idx];
}
idx = S.selections.findIndex((p,i) => p !== undefined && S.passages[i] !== undefined && E.selections[i].length > 0 && SegmentList.jaccard(p, E.selections[i]) < 0.3);
if (idx > -1) {
return ["poor-highlight", idx];
}
idx = S.passages.findIndex((p,i) => p !== undefined && S.confirmations[i] !== E.confirmations[i]);
if (idx > -1) {
return ["missing-confirmation", idx]; // say things are false early.
}
idx = S.passages.findIndex(p => p === undefined);
if (idx > -1) {
return ["incomplete", idx];
}
}
return ["correct", undefined];
}
renderWell(status, idx) {
// TODO: Report which should be fixed.
const bsStyle = (status === "incomplete") ? "primary" : (status === "correct") ? "success" : "danger";
let idxIndicator = (idx !== undefined) ? "passage number " + (idx+1) : "your plausibility response"
const well =
(status === "correct") ? (<span><b>That's right!</b> {this.props.successPrompt}</span>)
: (status === "wrong") ? (<span><b>Hmm... something doesn't seem quite right with your plausibility response.</b> {this.props.wrongPrompt}</span>)
: (status === "wrong-passage") ? (<span><b>Hmm... something doesn't seem quite right with how you rated {idxIndicator}.</b> {this.props.wrongPrompt}</span>)
: (status === "wrong-highlight") ? (<span><b>Hmm... something doesn't seem quite right with your highlights for {idxIndicator}.</b> {this.props.wrongPrompt}</span>)
: (status === "poor-highlight") ? (<span><b>Hmm... the highlighted region for {idxIndicator} could be improved.</b></span>)
: (status === "missing-highlight") ? (<span><b>Please highlight a region in the text for {idxIndicator} that justifies your response.</b></span>)
: (status === "missing-confirmation") ? (<span><b>Please confirm your response for {idxIndicator} to continue.</b></span>)
: undefined;
return well && (<Well bsStyle={bsStyle}>{well}</Well>);
}
render() {
const [status, idx] = this.checkAnswer();
const bsStyle = (status === "incomplete") ? "primary" : (status === "correct") ? "success" : "danger";
return (
<Panel bsStyle={bsStyle}>
<Panel.Heading><Panel.Title>{this.props.title} </Panel.Title></Panel.Heading>
<Panel.Body>
<p>{this.props.leadUp}</p>
<QAPrompt
query={this.props.query}
answer={this.props.answer}
passages={this.props.passages}
value={this.state}
onValueChanged={this.handleValueChanged}
/>
{this.renderWell(status, idx)}
</Panel.Body>
</Panel>
);
}
}
Example.defaultProps = {
id: "#example",
title: "#. Description of example.",
query: "where are the submandibular lymph nodes located",
answer: "below the jaw",
passages: [],
selections: [],
expected: {plausibility: true},
editable: true,
onChanged: () => {},
successPrompt: "",
wrongPrompt: "",
}
class InstructionContents extends Component {
constructor(props) {
super(props);
this.state = this.initState(props);
this.handleValueChanged = this.handleValueChanged.bind(this);
}
INSTRUCTION_KEY = {
"plausibility-1": true,
"plausibility-2": true,
"plausibility-3": true,
"plausibility-4": true,
"plausibility-5": true,
"judgement-1": true,
"judgement-2": true,
"judgement-3": true,
};
initState(props) {
if (props.isFirstTime) {
return {};
} else {
return this.INSTRUCTION_KEY;
}
}
handleValueChanged(update_) {
this.setState(update_, () => Object.keys(this.INSTRUCTION_KEY).every(k => this.state[k]) && this.props.onValueChanged(true));
}
render() {
let lede = (this.props.isFirstTime)
? (<p>
<b>Before you proceed with the HIT, you must complete the tutorial below</b> (you only need to do this once though!).
The tutorial should take about <i>5 minutes to complete</i> and you will get <b>a (one-time) ${this.props.bonus} bonus</b> for completing it.
</p>)
: undefined;
return (<div>
<h3>Updates <Label bsStyle="primary">NEW</Label></h3>
<ul>
<li> <b>We've made it easier to pass the tutorial</b> and <b>added more specific feedback</b> to help guide you to the right answer this time. </li>
<li>As you complete more HITs, <b>we will compare your work with those of your peers</b> and <b>notify you if we find that it disagrees a lot</b>.</li>
<li><b>The most common mistake is reporting an answer to be not plausible when it is, so please read carefully!</b> </li>
</ul>
{lede}
<h3>General instructions</h3>
<p>
We'd like you to read a <dfn>response</dfn> that was given to a question
asked online and judge if (a) it could be a <b>plausible</b> answer to
the question and (b) if one of several excerpts provide <b>evidence that it is a correct answer</b>.
</p>
<h3>Judging question plausibility</h3>
<p>
Sometimes <b>questions asked online are not staightforward</b>, so
we'd first like you to <b>identify if you can understand the
question</b>; a question like "<i>cost
starwars toy</i>" isn't grammatical, but it's pretty evident
what is being asked.
On the other hand, "<i>green eggs and ham</i>" is more ambiguous
but makes sense given the answer "<i>A children's book written by
Dr. Seuss and first published in 1960</i>".
Most questions are reasonable.
</p>
<Example
title="1. Judging question plausibility"
query="where are the submandibular lymph nodes located"
answer="below the jaw"
passages={[]}
expected={({plausibility:true, passages:[]})}
onChanged={(evt) => this.handleValueChanged({"plausibility-1": evt})}
editable={this.props.editable}
/>
<Example
title="2. Judging question plausibility"
query="psyllium husk fiber"
answer="Psyllium is a soluble fiber used primarily as a gentle bulk-forming laxative in products such as Metamucil."
passages={[]}
expected={({plausibility:true, passages:[]})}
onChanged={(evt) => this.handleValueChanged({"plausibility-2": evt})}
editable={this.props.editable}
successPrompt="Even though this question doesn't have a question word, it seems to be someone asking for the definition or explanation of what 'psyllium husk fiber' is."
/>
<Example
title="3. Judging question plausibility"
query="metatarsal what causes"
answer="The metatarsal bones, or metatarsus are a group of five long bones in the foot, located between the tarsal bones of the hind- and mid-foot and the phalanges of the toes."
passages={[]}
expected={({plausibility:false, passages:[]})}
onChanged={(evt) => this.handleValueChanged({"plausibility-3": evt})}
editable={this.props.editable}
successPrompt="It's very unclear to use what this question even means because metatarsal is a type of bone and can't obviously cause anything."
/>
<h3>Judging answer plausibility</h3>
<p>
We'd then like you to <b>check if the response even makes sense for the question</b>.
For example, for the question <i>"who said the quote by any means necessary"</i>,
<i>Malcom X</i> or <i>King Louis XVII</i> are both plausible
answers, while <i>the pancreatic tissue</i> or <i>the Sun</i> are
not. Now, try these examples:
</p>
<Example
title="4. Judging answer plausibility"
query="where are the submandibular lymph nodes located"
answer="It is responsible for lymphatic drainage of the tongue, submaxillary (salivary) gland, lips, mouth, and conjunctiva."
passages={[]}
expected={({plausibility:false, passages:[]})}
onChanged={(evt) => this.handleValueChanged({"plausibility-4": evt})}
editable={this.props.editable}
successPrompt="The answer seems to explain what these lymph nodes do, but not where they are."
/>
<Example
title="5. Judging answer plausibility"
query="can you use a deactivated sim card again"
answer="Once a SIM card retires, it can not be used again."
passages={[]}
expected={({plausibility:true, passages:[]})}
onChanged={(evt) => this.handleValueChanged({"plausibility-5": evt})}
editable={this.props.editable}
successPrompt="Even though this is not a 'yes/no' response, it clearly answers the question."
/>
<h3>Evaluating evidence for the response <Label bsStyle="primary">IMPORTANT: PLEASE READ!</Label></h3>
<p>
If the response is a plausible answer, we would like you to
check whether or not it is a <i>correct answer</i> according to
a few excerpted paragraphs.</p>
<ol>
<li>
For each paragraph presented, first <b>read the paragraph</b> and
indicate if the paragraph provides evidence that the response is correct (<Glyphicon glyph="ok" />),
incorrect (<Glyphicon glyph="remove" />), or that the paragraph simply
isn't sufficient to tell us either which way (<Glyphicon glyph="minus" />).
<b>You only need to use commonsense knowledge and information contained
within the question, answer or paragraph. You do not need
to search online for further inormation.</b>
</li>
<li>
If the paragraph provides evidence that the response is either
correct (<Glyphicon glyph="ok" />) or incorrect (<Glyphicon
glyph="remove" />), <b>highlight the regions of the text that you think justifies your decision</b>.
<i>You can but do not have to highlight regions if the response is neutral (<Glyphicon
glyph="minus" />)</i>.
The highlighted regions don't need to be exact, but should help us understand why you are making your decision.
</li>
<li>
<b>To remove a highlight, simply click on it.</b>
</li>
<li>
If you judge the response to be correct (or incorrect), you will have to
<b>confirm that the response is an answer (or not an answer)
<u>for the question</u> according to your selected evidence</b>
</li>
<li>
<b>Use the buttons on the lower right to move through the
paragraphs.</b> You will need to make a decision on each paragraph
to complete the task.
</li>
</ol>
<p>
Review the different paragraphs below by clicking
on the icons in the lower right corner.
</p>
<Example
title="Evaluating evidence (Example)"
query="who said the quote by any means necessary"
answer="Malcom X"
passages={[
{"passage_text": "It entered the popular culture through a speech given by Malcolm X in the last year of his life. \"We declare our right on this earth to be a man, ..., in this day, which we intend to bring into existence by any means necessary.\""},
{"passage_text": "Though commonly attributed to Malcom X, the quote \"By any means necessary\" actually comes from a speech by Martin Luther King Jr. (Note: this is a fictional example.)"},
{"passage_text": "Malcolm X’s life changed dramatically in the first six months of 1964. In May he toured West Africa and made a pilgrimage to Mecca, returning as El Hajj Malik El-Shabazz."},
]}
expected={({plausibility:true, passages: [1, -1, 0], selections:[[[0, 66],[97,228]],[[40,130]],[]], confirmations: [true, true, undefined]})}
editable={false}
/>
<p>
Now you try; if you made a mistake, simply click on the icons in the lower right corner to go back and correct your answer.
</p>
<Example
title="6. Evaluating evidence"
query="where are the submandibular lymph nodes located"
answer="below the jaw"
passages={[
{"passage_text": "When these lymph nodes enlarge through infection, you may have a red, painful swelling in the area of the parotid or submandibular glands. Lymph nodes also enlarge due to tumors and inflammation."},
{"passage_text": "Submandibular lymph nodes are glands that are a part of the immune system and are located below the jaw. Submandibular lymph nodes consist of lymphatic tissues enclosed by a fibrous capsule."},
{"passage_text": "Secondary infection of salivary glands from adjacent lymph nodes also occurs. These lymph nodes are the glands in the upper neck which often become tender during a common sore throat. Many of these lymph nodes are actually located on, within, and deep in the substance of the parotid gland, near the submandibular glands."},
]}
expected={({plausibility:true, passages: [0, 1, 1], selections:[[],[[0,104]],[[78,128]]], confirmations: [undefined, true, true]})}
onChanged={(evt) => this.handleValueChanged({"judgement-1": evt})}
editable={this.props.editable}
successPrompt={<span>Note how "These lymph nodes are glands in the upper neck" was also considered to be correct because it's very close to being <u>below the jaw</u>. That said, an answer like "above the hip" should <b>not</b> be rated correct as it is not specific enough and should instead be rated as neutral.</span>}
/>
<Example
title="7. Evaluating evidence"
query="can you use a deactivated sim card again"
answer="yes"
passages={[
{"passage_text": "I got the same question, how can I have my prepaid sim card reactivated. I haven't used or recharged this sim card for about more than six months. I just bought a new mobile phone and when I turned it on it said the sim card needs to be activated. I hope I can use this sim card again. Thank you."},
{"passage_text": "What is BAN? When I try to activate an used SIM, but deactivated, on the SAME account, it works."},
{"passage_text": "Once a SIM card is deactivated it is dead. You will have to get a new SIM."},
]}
expected={({plausibility:true, passages: [0, 1, -1], selections:[[],[[14,98]],[[0,42]]], confirmations: [undefined, true, true]})}
onChanged={(evt) => this.handleValueChanged({"judgement-2": evt})}
editable={this.props.editable}
/>
<Example
title="8. Evaluating evidence (numerical answers don't have to be exact, but close enough)"
query="how much do electricians charge"
answer="$40 to $100 an hour"
passages={[
{"passage_text": "Although there are still a few low-cost areas where electricians work for $30-$50 an hour, typically they charge $50-$100 an hour or more depending on local rates and their qualifications."},
{"passage_text": "Electricians typically charge between $65 and $110 an hour depending on their location and the type of work they do."},
{"passage_text": "I haven't found a good electrician who charges less than $150 an hour."},
]}
expected={({plausibility:true, passages: [1, 1, -1], selections:[[[52, 129]],[[0,58]],[[0, 70]]], confirmations: [true, true, true]})}
onChanged={(evt) => this.handleValueChanged({"judgement-3": evt})}
editable={this.props.editable}
/>
</div>);
}
}
InstructionContents.defaultProps = {
bonus: 0.50,
isFirstTime: false,
editable: false,
onValueChanged: () => {},
}
export default App;
|
src/client/SongCard.js | davekennewell/soundcloud | import React from 'react';
import styles from './songCard.css';
import mockSongs from './constants'
class SongCard extends React.Component {
constructor(props) {
super(props);
}
render() {
// console.log('SongCard props:', this.props);
const { artwork_url, title, user } = this.props;
const { avatar_url } = user;
return (
<div className={styles.songCard}>
<img src={artwork_url} className={styles.songImage}/>
<img src={avatar_url} className={styles.artist_img}/>
<div className={styles.title}>{title}</div>
</div>
);
}
}
export default SongCard; |
client/dev/components/button.js | tetondan/ReactReduxToDo | import React from 'react';
const Button = (props) => {
const selectedButtonStyle = {
background: "#b3e5d1",
textDecoration: "none",
cursor: "default"
};
if(props.type) {
return <button onClick={props.clickHandler.bind(this, props.type)} style={props.selected === props.type ? selectedButtonStyle : null}>{props.type}</button>;
} else {
return <button onClick={props.clickHandler}>{props.title}</button>;
}
};
export default Button; |
src/server.js | magnusbae/fluffy-beat | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import 'babel-core/polyfill';
import path from 'path';
import express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import Router from './routes';
import Html from './components/Html';
const server = global.server = express();
server.set('port', (process.env.PORT || 5000));
server.use(express.static(path.join(__dirname, 'public')));
//
// Register API middleware
// -----------------------------------------------------------------------------
server.use('/api/content', require('./api/content'));
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
try {
let statusCode = 200;
const data = { title: '', description: '', css: '', body: '' };
const css = [];
const context = {
onInsertCss: value => css.push(value),
onSetTitle: value => data.title = value,
onSetMeta: (key, value) => data[key] = value,
onPageNotFound: () => statusCode = 404,
};
await Router.dispatch({ path: req.path, context }, (state, component) => {
data.body = ReactDOM.renderToString(component);
data.css = css.join('');
});
const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
res.status(statusCode).send('<!doctype html>\n' + html);
} catch (err) {
next(err);
}
});
//
// Launch the server
// -----------------------------------------------------------------------------
server.listen(server.get('port'), () => {
/* eslint-disable no-console */
console.log('The server is running at http://localhost:' + server.get('port'));
if (process.send) {
process.send('online');
}
});
|
src/components/views/items/CarouselUserView.js | planlodge/soundmix | import React from 'react';
import Moment from 'react-moment';
import OwlCarousel from 'react-owl-carousel';
// Using "Stateless Functional Components"
export default function (props) {
//console.log("Ps", props);
return (
<OwlCarousel
items={6}
autoplaySpeed={300}
lazyLoad={true}
rewind={true}
navText={['<i class="material-icons">skip_previous</i>','<i class="material-icons">skip_next</i>']}
nav
responsive={
{
"0": {items: 1},
"600": {items: 3},
"1000": {items: 5}
}
}
autoplay={true}
autoplayHoverPause={true}>
{props.list.map((item, i) => {
return (
<div key={i} className="col s12">
<div className="item card hoverable carouselCard">
<div className="card-image">
<a href={"/user/" + item.username}>
<img src={item.pictures.large} alt={item.name}/>
</a>
<span className="card-title">{item.name}</span>
<a href={"/user/" + item.username}
className="btn-floating halfway-fab waves-effect waves-light deep-purple darken-1"><i
className="material-icons">info</i></a>
</div>
<div className="card-content">
{(() => {
if (item.listen_time !== undefined) {
return <p>Listened <Moment fromNow>{item.listen_time}</Moment></p>
} else {
return <p>
<a href={"/user/" + item.username}> {item.username} </a>
</p>
}
})()}
</div>
</div>
</div>
);
})}
</OwlCarousel>
);
} |
src/Crosswords/UI/MatrixFormRow.js | minkiele/crosswords | import React from 'react';
import MatrixFormCell from './MatrixFormCell';
export default class MatrixFormRow extends React.Component {
render () {
let cells = [];
for(let col = 0; col < this.props.cols; col += 1) {
cells.push(
<MatrixFormCell key={col.toString()} row={this.props.row} col={col} matrixCol={this.props.matrixRow[col]} definitions={this.props.definitions} eventManager={this.props.eventManager} />
);
}
return (
<tr>
{cells}
</tr>
);
}
}
MatrixFormRow.propTypes = {
cols: React.PropTypes.number.isRequired,
row: React.PropTypes.number.isRequired,
matrixRow: React.PropTypes.array.isRequired,
definitions: React.PropTypes.object.isRequired,
eventManager: React.PropTypes.object.isRequired
};
|
src/components/FullUser.js | AliaksandrZahorski/contacts | import React from 'react'
import { connect } from 'react-redux'
import { deleteUser, editUser } from '../actions'
let FullUser = ({id, text, additionalText, dispatch }) => (
<div>
<p className="currentUser name">Name: {text}</p>
<p className="currentUser data">Data: {additionalText}</p>
<button className="delete" onClick={() => dispatch(deleteUser( id ))}>
deleteUser
</button>
<button onClick={() => dispatch(editUser( id ))}>
editUser
</button>
</div>
)
FullUser = connect()(FullUser)
export default FullUser
|
client/views/setupWizard/SideBar.js | Sing-Li/Rocket.Chat | import { Box, Margins, Scrollable } from '@rocket.chat/fuselage';
import { useMediaQuery } from '@rocket.chat/fuselage-hooks';
import React from 'react';
import { useTranslation } from '../../contexts/TranslationContext';
import Logo from '../../components/basic/Logo';
import './SideBar.css';
function SideBar({
logoSrc = 'images/logo/logo.svg',
currentStep = 1,
steps = [],
}) {
const t = useTranslation();
const small = useMediaQuery('(max-width: 760px)');
return <Box
is='aside'
className='SetupWizard__SideBar'
flexGrow={0}
flexShrink={1}
flexBasis={small ? 'auto' : '350px'}
maxHeight='sh'
display='flex'
flexDirection='column'
flexWrap='nowrap'
style={{ overflow: 'hidden' }}
>
<Box
is='header'
marginBlockStart={small ? 'x16' : 'x32'}
marginBlockEnd={small ? 'none' : 'x32'}
marginInline='x24'
display='flex'
flexDirection='row'
flexWrap='wrap'
alignItems='center'
>
<Logo
src={logoSrc}
width='auto'
height='x24'
margin='x4'
/>
<Box
is='span'
margin='x4'
paddingBlock='x4'
paddingInline='x8'
color='alternative'
fontScale='micro'
style={{
whiteSpace: 'nowrap',
textTransform: 'uppercase',
backgroundColor: 'var(--color-dark, #2f343d)',
borderRadius: '9999px',
}}
>
{t('Setup_Wizard')}
</Box>
</Box>
{!small && <Scrollable>
<Box
flexGrow={1}
marginBlockEnd='x16'
paddingInline='x32'
>
<Margins blockEnd='x16'>
<Box is='h2' fontScale='h1' color='default'>{t('Setup_Wizard')}</Box>
<Box is='p' color='hint' fontScale='p1'>{t('Setup_Wizard_Info')}</Box>
</Margins>
<Box is='ol'>
{steps.map(({ step, title }) =>
<Box
key={step}
is='li'
className={[
'SetupWizard__SideBar-step',
step < currentStep && 'SetupWizard__SideBar-step--past',
].filter(Boolean).join(' ')}
data-number={step}
marginBlock='x32'
marginInline='neg-x8'
display='flex'
alignItems='center'
fontScale='p2'
color={(step === currentStep && 'primary')
|| (step < currentStep && 'default')
|| 'disabled'}
style={{ position: 'relative' }}
>
{title}
</Box>,
)}
</Box>
</Box>
</Scrollable>}
</Box>;
}
export default SideBar;
|
node_modules/react-slick/src/inner-slider.js | hong1012/FreePay | 'use strict';
import React from 'react';
import EventHandlersMixin from './mixins/event-handlers';
import HelpersMixin from './mixins/helpers';
import initialState from './initial-state';
import defaultProps from './default-props';
import classnames from 'classnames';
import assign from 'object-assign';
import {Track} from './track';
import {Dots} from './dots';
import {PrevArrow, NextArrow} from './arrows';
export var InnerSlider = React.createClass({
mixins: [HelpersMixin, EventHandlersMixin],
list: null,
track: null,
listRefHandler: function (ref) {
this.list = ref;
},
trackRefHandler: function (ref) {
this.track = ref;
},
getInitialState: function () {
return Object.assign({}, initialState, {
currentSlide: this.props.initialSlide
});
},
getDefaultProps: function () {
return defaultProps;
},
componentWillMount: function () {
if (this.props.init) {
this.props.init();
}
this.setState({
mounted: true
});
var lazyLoadedList = [];
for (var i = 0; i < React.Children.count(this.props.children); i++) {
if (i >= this.state.currentSlide && i < this.state.currentSlide + this.props.slidesToShow) {
lazyLoadedList.push(i);
}
}
if (this.props.lazyLoad && this.state.lazyLoadedList.length === 0) {
this.setState({
lazyLoadedList: lazyLoadedList
});
}
},
componentDidMount: function componentDidMount() {
// Hack for autoplay -- Inspect Later
this.initialize(this.props);
this.adaptHeight();
// To support server-side rendering
if (!window) {
return
}
if (window.addEventListener) {
window.addEventListener('resize', this.onWindowResized);
} else {
window.attachEvent('onresize', this.onWindowResized);
}
},
componentWillUnmount: function componentWillUnmount() {
if (this.animationEndCallback) {
clearTimeout(this.animationEndCallback);
}
if (window.addEventListener) {
window.removeEventListener('resize', this.onWindowResized);
} else {
window.detachEvent('onresize', this.onWindowResized);
}
if (this.state.autoPlayTimer) {
clearInterval(this.state.autoPlayTimer);
}
},
componentWillReceiveProps: function(nextProps) {
if (this.props.slickGoTo != nextProps.slickGoTo) {
if (process.env.NODE_ENV !== 'production') {
console.warn('react-slick deprecation warning: slickGoTo prop is deprecated and it will be removed in next release. Use slickGoTo method instead')
}
this.changeSlide({
message: 'index',
index: nextProps.slickGoTo,
currentSlide: this.state.currentSlide
});
} else if (this.state.currentSlide >= nextProps.children.length) {
this.update(nextProps);
this.changeSlide({
message: 'index',
index: nextProps.children.length - nextProps.slidesToShow,
currentSlide: this.state.currentSlide
});
} else {
this.update(nextProps);
}
},
componentDidUpdate: function () {
this.adaptHeight();
},
onWindowResized: function () {
this.update(this.props);
// animating state should be cleared while resizing, otherwise autoplay stops working
this.setState({
animating: false
});
clearTimeout(this.animationEndCallback);
delete this.animationEndCallback;
},
slickPrev: function () {
this.changeSlide({message: 'previous'});
},
slickNext: function () {
this.changeSlide({message: 'next'});
},
slickGoTo: function (slide) {
typeof slide === 'number' && this.changeSlide({
message: 'index',
index: slide,
currentSlide: this.state.currentSlide
});
},
render: function () {
var className = classnames('slick-initialized', 'slick-slider', this.props.className, {
'slick-vertical': this.props.vertical,
});
var trackProps = {
fade: this.props.fade,
cssEase: this.props.cssEase,
speed: this.props.speed,
infinite: this.props.infinite,
centerMode: this.props.centerMode,
focusOnSelect: this.props.focusOnSelect ? this.selectHandler : null,
currentSlide: this.state.currentSlide,
lazyLoad: this.props.lazyLoad,
lazyLoadedList: this.state.lazyLoadedList,
rtl: this.props.rtl,
slideWidth: this.state.slideWidth,
slidesToShow: this.props.slidesToShow,
slidesToScroll: this.props.slidesToScroll,
slideCount: this.state.slideCount,
trackStyle: this.state.trackStyle,
variableWidth: this.props.variableWidth
};
var dots;
if (this.props.dots === true && this.state.slideCount >= this.props.slidesToShow) {
var dotProps = {
dotsClass: this.props.dotsClass,
slideCount: this.state.slideCount,
slidesToShow: this.props.slidesToShow,
currentSlide: this.state.currentSlide,
slidesToScroll: this.props.slidesToScroll,
clickHandler: this.changeSlide,
children: this.props.children,
customPaging: this.props.customPaging
};
dots = (<Dots {...dotProps} />);
}
var prevArrow, nextArrow;
var arrowProps = {
infinite: this.props.infinite,
centerMode: this.props.centerMode,
currentSlide: this.state.currentSlide,
slideCount: this.state.slideCount,
slidesToShow: this.props.slidesToShow,
prevArrow: this.props.prevArrow,
nextArrow: this.props.nextArrow,
clickHandler: this.changeSlide
};
if (this.props.arrows) {
prevArrow = (<PrevArrow {...arrowProps} />);
nextArrow = (<NextArrow {...arrowProps} />);
}
var verticalHeightStyle = null;
if (this.props.vertical) {
verticalHeightStyle = {
height: this.state.listHeight,
};
}
var centerPaddingStyle = null;
if (this.props.vertical === false) {
if (this.props.centerMode === true) {
centerPaddingStyle = {
padding: ('0px ' + this.props.centerPadding)
};
}
} else {
if (this.props.centerMode === true) {
centerPaddingStyle = {
padding: (this.props.centerPadding + ' 0px')
};
}
}
const listStyle = assign({}, verticalHeightStyle, centerPaddingStyle);
return (
<div className={className} onMouseEnter={this.onInnerSliderEnter} onMouseLeave={this.onInnerSliderLeave}>
{prevArrow}
<div
ref={this.listRefHandler}
className="slick-list"
style={listStyle}
onMouseDown={this.swipeStart}
onMouseMove={this.state.dragging ? this.swipeMove: null}
onMouseUp={this.swipeEnd}
onMouseLeave={this.state.dragging ? this.swipeEnd: null}
onTouchStart={this.swipeStart}
onTouchMove={this.state.dragging ? this.swipeMove: null}
onTouchEnd={this.swipeEnd}
onTouchCancel={this.state.dragging ? this.swipeEnd: null}
onKeyDown={this.props.accessibility ? this.keyHandler : null}>
<Track ref={this.trackRefHandler} {...trackProps}>
{this.props.children}
</Track>
</div>
{nextArrow}
{dots}
</div>
);
}
});
|
docs/server.js | justinanastos/react-bootstrap | /* eslint no-console: 0 */
import 'colors';
import React from 'react';
import express from 'express';
import path from 'path';
import Router from 'react-router';
import routes from './src/Routes';
import httpProxy from 'http-proxy';
import metadata from './generate-metadata';
import ip from 'ip';
const development = process.env.NODE_ENV !== 'production';
const port = process.env.PORT || 4000;
let app = express();
if (development) {
let proxy = httpProxy.createProxyServer();
let webpackPort = process.env.WEBPACK_DEV_PORT;
let target = `http://${ip.address()}:${webpackPort}`;
app.get('/assets/*', function (req, res) {
proxy.web(req, res, { target });
});
proxy.on('error', function(e) {
console.log('Could not connect to webpack proxy'.red);
console.log(e.toString().red);
});
console.log('Prop data generation started:'.green);
metadata().then( props => {
console.log('Prop data generation finished:'.green);
app.use(function renderApp(req, res) {
res.header('Access-Control-Allow-Origin', target);
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
Router.run(routes, req.url, Handler => {
let html = React.renderToString(<Handler assetBaseUrl={target} propData={props}/>);
res.send('<!doctype html>' + html);
});
});
});
} else {
app.use(express.static(path.join(__dirname, '../docs-built')));
}
app.listen(port, function () {
console.log(`Server started at:`);
console.log(`- http://localhost:${port}`);
console.log(`- http://${ip.address()}:${port}`);
});
|
frontend/src/components/NotFound.js | OpenCollective/opencollective-website | import React, { Component } from 'react';
export default class NotFound extends Component {
render() {
return (
<div id="content-404">
<a href='https://opencollective.com/'> <img src='/public/images/LogoLargeTransparent.png' /></a>
<p><b>Error 404: We can't find that page.</b></p>
<p>Try our <a href='https://opencollective.com/'>homepage</a>, <a href='https://opencollective.com/faq'>FAQ</a> or <a href='https://medium.com/open-collective'>blog</a>. </p>
<p>Or chat with us on our <a href='https://slack.opencollective.com/'>Slack channel</a>.</p>
<img src='/public/images/404.gif' />
</div>
);
}
} |
app/config/feature/Feature.js | stefanKuijers/aw-fullstack-app | // @flow
import React, { Component } from 'react';
import { remote } from 'electron';
import {Card, CardHeader, CardText} from 'material-ui/Card';
import {List, ListItem} from 'material-ui/List';
import Subheader from 'material-ui/Subheader';
import Toggle from 'material-ui/Toggle';
import Avatar from 'material-ui/Avatar';
import TextField from 'material-ui/TextField';
import AddIcon from 'material-ui/svg-icons/content/add';
import InfoIcon from 'material-ui/svg-icons/action/info';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import Popover from 'material-ui/Popover/Popover';
import Divider from 'material-ui/Divider';
import IconButton from 'material-ui/IconButton';
import styles from './Feature.css';
import { globsExplenation, helpStyles } from '../../helpCenter/HelpCenter';
const dialog = remote.dialog;
const iconButtonElement = (
<IconButton touch={true}>
<MoreVertIcon/>
</IconButton>
);
class Feature extends Component {
constructor(props) {
super(props);
this.globRefs = [];
this.state = {
globPopoverOpen: false,
globHeader: undefined
};
}
toggleGlobPopover = (e) => {
this.state.globPopoverOpen = !this.state.globPopoverOpen;
this.state.globHeader = e.currentTarget;
this.setState(this.state);
}
openDirectorySelect(key, property, index, updateCallback) {
if (property === 'globs') return;
dialog.showOpenDialog({
properties: ['openDirectory']
}, (paths) => {
if (paths && paths.length) {
const path = (paths[0]+'\\').replace(this.props.data.rootFolder, '');
updateCallback(key, property, path, index)
}
});
}
handleGlobEnter(el, actions, configId, key) {
actions.addGlob(configId, key);
setTimeout(() => {
this.globRefs[this.globRefs.length-1].focus();
},300);
}
printState(flag) {
return flag ? "enabled":"disabled";
};
moveGlob(configId, key, index, newIndex) {
if (newIndex >= 0 && newIndex < this.props.data.options.globs.length) {
this.props.actions.moveGlob(configId, key, index, newIndex);
}
}
createInputListItem(
configId, index, actions, key, property, value, hintText = 'relative/path/to/files/**/*'
) {
return (
<ListItem
key={index}
className={styles.listItem}
rightIconButton={ (property != 'globs') ? null :
<IconMenu
iconButtonElement={iconButtonElement}
anchorOrigin={{horizontal: 'right', vertical: 'top'}}
targetOrigin={{horizontal: 'right', vertical: 'top'}}
>
<MenuItem onTouchTap={() => {this.moveGlob(configId, key, index, index-1)}}>Move Up</MenuItem>
<MenuItem onTouchTap={() => {this.moveGlob(configId, key, index, index+1)}}>Move Down</MenuItem>
<Divider />
<MenuItem onTouchTap={() => {actions.removeGlob(configId, key, index)}}>Delete</MenuItem>
</IconMenu>
}
>
<TextField
onTouchTap={() => {this.openDirectorySelect(key, property, index, actions.updateProperty)}}
onChange={(e, val) => { actions.updateProperty(key, property, val, index) }}
onKeyDown={(e, el) => {if (property === 'globs' && e.keyCode === 13) this.handleGlobEnter(el, actions, configId, key) }}
ref={(textField) => {if (property === 'globs') {
this.globRefs.push(textField);
} }}
value={value}
style={{width: '100%'}}
hintText={hintText}
hintStyle={{color: 'rgba(180,180,180,0.5)'}}
/>
</ListItem>
);
}
createInputListItems(configId, globs, key, property, actions) {
if (globs) {
return globs.map((glob, index) => {
return (this.createInputListItem(configId, index, actions, key, property, glob));
});
}
}
renderContent(configId, key, options, actions) {
console.log('Render feature content', options);
if (key !== 'dependencyManagement') {
return(
<CardText
expandable={true}
className={styles.cardText}
>
<List>
{((key !== 'watch') ? this.createInputListItem(
configId, 'outputDir', actions, key, 'outputDir', options.outputDir, 'Output Folder'
) : null)}
{((key === 'sass') ? this.createInputListItem(
configId, 'fontsDir', actions, key, 'fontsDir', options.fontsDir, 'Path to Font Folder'
) : null)}
</List>
<List>
<Subheader
className={helpStyles.subHeader}
onTouchTap={this.toggleGlobPopover}
>Globs <InfoIcon/></Subheader>
{this.createInputListItems(configId, options.globs, key, 'globs', actions)}
<ListItem
key="addNew"
onTouchTap={() => {actions.addGlob(configId, key)}}
leftAvatar={<Avatar icon={<AddIcon/>} />}
primaryText="Add new glob"
/>
</List>
<Popover
open={this.state.globPopoverOpen}
anchorEl={this.state.globHeader}
onRequestClose={this.toggleGlobPopover}
className={helpStyles.popover}
zDepth={4}
>{globsExplenation}</Popover>
</CardText>
);
}
}
render() {
const options = this.props.data.options || {};
const data = this.props.data || {};
const actions = this.props.actions;
const imgUrl = `./config/feature/${data.key}_logo.png`;
return (
<Card className="section" expanded={options.enabled}>
<CardHeader
title={data.title}
subtitle={this.printState(options.enabled)}
avatar={<Avatar style={{backgroundColor: '#fac415'}} src={imgUrl} />}
>
<Toggle
className={styles.toggle}
toggled={options.enabled}
onTouchTap={() => {actions.updateProperty(data.key, 'enabled', !options.enabled)}}
/>
</CardHeader>
{this.renderContent(data.configId, data.key, options, actions)}
</Card>
);
}
}
export default Feature;
|
src/components/LayoutFullScreen/LayoutFullScreen.js | cineindustria/site | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './LayoutFullScreen.css';
import HeaderFullScreen from '../HeaderFullScreen';
import Footer from '../Footer';
class LayoutFullScreen extends React.Component {
static propTypes = {
children: PropTypes.node.isRequired,
};
render() {
return (
<div>
<HeaderFullScreen />
{this.props.children}
<Footer />
</div>
);
}
}
export default withStyles(s)(LayoutFullScreen);
|
client/src/components/Message/index.js | ultranaut/react-chat | import React from 'react';
import './Message.scss';
const Message = (props) => {
return (
<div className="comment">
<div className="user">{props.user}</div>
<div className="copy">{props.message}</div>
</div>
);
};
export default Message;
|
src/svg-icons/action/add-shopping-cart.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAddShoppingCart = (props) => (
<SvgIcon {...props}>
<path d="M11 9h2V6h3V4h-3V1h-2v3H8v2h3v3zm-4 9c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zm10 0c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2zm-9.83-3.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.86-7.01L19.42 4h-.01l-1.1 2-2.76 5H8.53l-.13-.27L6.16 6l-.95-2-.94-2H1v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.13 0-.25-.11-.25-.25z"/>
</SvgIcon>
);
ActionAddShoppingCart = pure(ActionAddShoppingCart);
ActionAddShoppingCart.displayName = 'ActionAddShoppingCart';
ActionAddShoppingCart.muiName = 'SvgIcon';
export default ActionAddShoppingCart;
|
src/components/CvHeader/CvHeader.js | lkostrowski/cv | import React from 'react';
import PropTypes from 'prop-types';
import styled from "styled-components"
import colors from '../../utils/colors';
const Header = styled.header`
background: ${colors.dark};
color: ${colors.light};
padding: 1rem;
box-shadow: inset 0 0 0 4px ${colors.dark}, inset 0 0 0 6px ${colors.light};
`;
const Name = styled.h1`
margin:0;
text-transform: uppercase;
font-size: 24px;
`;
const Title = styled.h2`
margin: 0;
text-transform: uppercase;
font-size: 16px;
`;
const CvHeader = ({name, title}) => (
<Header>
<Name>{name}</Name>
<Title>{title}</Title>
</Header>
)
;
CvHeader.propTypes = {
name: PropTypes.string,
title: PropTypes.string,
};
export default CvHeader;
|
demo17/main.js | tangjingjing/try-react | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
// wrong!
// <App count="1"/>,
// right!
// <App count={1}/>,
<App/>,
document.getElementById('app')
)
|
webapp-src/src/Admin/UserMod.js | babelouest/glewlwyd | import React, { Component } from 'react';
import i18next from 'i18next';
import messageDispatcher from '../lib/MessageDispatcher';
import apiManager from '../lib/APIManager';
class UserMod extends Component {
constructor(props) {
super(props);
this.state = {
config: props.config,
mods: props.mods,
curMod: {},
types: props.types,
loggedIn: props.loggedIn
}
this.addMod = this.addMod.bind(this);
this.editMod = this.editMod.bind(this);
this.deleteMod = this.deleteMod.bind(this);
this.switchModStatus = this.switchModStatus.bind(this);
}
componentWillReceiveProps(nextProps) {
this.setState({
mods: nextProps.mods,
types: nextProps.types,
loggedIn: nextProps.loggedIn
});
}
addMod(e) {
messageDispatcher.sendMessage('App', {type: "add", role: "userMod"});
}
editMod(e, mod, index) {
messageDispatcher.sendMessage('App', {type: "edit", role: "userMod", mod: mod, index: index});
}
deleteMod(e, mod) {
messageDispatcher.sendMessage('App', {type: "delete", role: "userMod", mod: mod});
}
moveModUp(e, mod, previousMod) {
mod.order_rank--;
previousMod.order_rank++;
messageDispatcher.sendMessage('App', {type: "swap", role: "userMod", mod: mod, previousMod: previousMod});
}
switchModStatus(mod) {
var action = (mod.enabled?"disable":"enable");
apiManager.glewlwydRequest("/mod/user/" + encodeURIComponent(mod.name) + "/" + action + "/", "PUT")
.then(() => {
messageDispatcher.sendMessage('Notification', {type: "success", message: i18next.t("admin.success-api-edit-mod")});
})
.fail((err) => {
messageDispatcher.sendMessage('Notification', {type: "danger", message: i18next.t("admin.error-api-edit-mod")});
if (err.status === 400) {
messageDispatcher.sendMessage('Notification', {type: "danger", message: JSON.stringify(err.responseJSON)});
}
})
.always(() => {
messageDispatcher.sendMessage('App', {type: "refresh", role: "userMod", mod: mod});
});
}
render() {
var mods = [];
this.state.mods.forEach((mod, index) => {
var module = "", buttonUp = "", switchButton = "", buttonUpSmall, switchButtonSmall;
this.state.types.forEach((type) => {
if (mod.module === type.name) {
module = type.display_name;
}
});
if (index) {
buttonUp =
<button type="button" className="btn btn-secondary" onClick={(e) => this.moveModUp(e, mod, this.state.mods[index - 1])} title={i18next.t("admin.move-up")}>
<i className="fas fa-sort-up"></i>
</button>;
buttonUpSmall = <a className="dropdown-item" href="#" onClick={(e) => moveModUp(e, mod, this.state.mods[index - 1])} alt={i18next.t("admin.move-up")}>
<i className="fas fa-sort-up btn-icon"></i>
{i18next.t("admin.move-up")}
</a>
}
if (mod.enabled) {
switchButton = <button type="button" className="btn btn-secondary" onClick={(e) => this.switchModStatus(mod)} title={i18next.t("admin.switch-off")}>
<i className="fas fa-toggle-on"></i>
</button>;
switchButtonSmall = <a className="dropdown-item" href="#" onClick={(e) => this.switchModStatus(mod)} alt={i18next.t("admin.switch-off")}>
<i className="fas fa-toggle-on btn-icon"></i>
{i18next.t("admin.switch-off")}
</a>
} else {
switchButton = <button type="button" className="btn btn-secondary" onClick={(e) => this.switchModStatus(mod)} title={i18next.t("admin.switch-on")}>
<i className="fas fa-toggle-off"></i>
</button>;
switchButtonSmall = <a className="dropdown-item" href="#" onClick={(e) => this.switchModStatus(mod)} alt={i18next.t("admin.switch-on")}>
<i className="fas fa-toggle-off btn-icon"></i>
{i18next.t("admin.switch-on")}
</a>
}
mods.push(<tr key={index} className={(!mod.enabled?"table-danger":"")}>
<td className="d-none d-lg-table-cell">{mod.order_rank}</td>
<td>{module}</td>
<td>{mod.name}</td>
<td className="d-none d-lg-table-cell">{mod.display_name||""}</td>
<td className="d-none d-lg-table-cell">{(mod.readonly?i18next.t("yes"):i18next.t("no"))}</td>
<td className="d-none d-lg-table-cell">{(mod.enabled?i18next.t("yes"):i18next.t("no"))}</td>
<td>
<div className="btn-group d-none d-lg-table-cell" role="group">
{switchButton}
<button type="button" className="btn btn-secondary" onClick={(e) => this.editMod(e, mod, index)} title={i18next.t("admin.edit")}>
<i className="fas fa-edit"></i>
</button>
<button type="button" className="btn btn-secondary" onClick={(e) => this.deleteMod(e, mod)} title={i18next.t("admin.delete")}>
<i className="fas fa-trash"></i>
</button>
{buttonUp}
</div>
<div className="dropdown d-block d-lg-none">
<button className="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuNav" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i className="fas fa-chevron-circle-down"></i>
</button>
<div className="dropdown-menu" aria-labelledby="dropdownMenuNav">
{switchButtonSmall}
<a className="dropdown-item" href="#" onClick={(e) => this.editMod(e, mod, index)} alt={i18next.t("admin.edit")}>
<i className="fas fa-edit btn-icon"></i>
{i18next.t("admin.edit")}
</a>
<a className="dropdown-item" href="#" onClick={(e) => this.deleteMod(e, mod)} alt={i18next.t("admin.delete")}>
<i className="fas fa-trash btn-icon"></i>
{i18next.t("admin.delete")}
</a>
{buttonUpSmall}
</div>
</div>
</td>
</tr>);
});
return (
<table className="table table-responsive table-striped">
<thead>
<tr>
<th colSpan="5">
<h4>{i18next.t("admin.user-mod-list-title")}</h4>
</th>
<th colSpan="1">
<div className="btn-group" role="group">
<button disabled={!this.state.loggedIn} type="button" className="btn btn-secondary" onClick={(e) => this.addMod(e)} title={i18next.t("admin.add")}>
<i className="fas fa-plus"></i>
</button>
</div>
</th>
</tr>
<tr>
<th className="d-none d-lg-table-cell">
{i18next.t("admin.order")}
</th>
<th>
{i18next.t("admin.type")}
</th>
<th>
{i18next.t("admin.name")}
</th>
<th className="d-none d-lg-table-cell">
{i18next.t("admin.display-name")}
</th>
<th className="d-none d-lg-table-cell">
{i18next.t("admin.readonly")}
</th>
<th className="d-none d-lg-table-cell">
{i18next.t("admin.enabled")}
</th>
<th>
</th>
</tr>
</thead>
<tbody>
{mods}
</tbody>
</table>
);
}
}
export default UserMod;
|
search-filter-map/test/test_helper.js | murielg/react-redux | import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
src/svg-icons/image/wb-incandescent.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageWbIncandescent = (props) => (
<SvgIcon {...props}>
<path d="M3.55 18.54l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8zM11 22.45h2V19.5h-2v2.95zM4 10.5H1v2h3v-2zm11-4.19V1.5H9v4.81C7.21 7.35 6 9.28 6 11.5c0 3.31 2.69 6 6 6s6-2.69 6-6c0-2.22-1.21-4.15-3-5.19zm5 4.19v2h3v-2h-3zm-2.76 7.66l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4z"/>
</SvgIcon>
);
ImageWbIncandescent = pure(ImageWbIncandescent);
ImageWbIncandescent.displayName = 'ImageWbIncandescent';
ImageWbIncandescent.muiName = 'SvgIcon';
export default ImageWbIncandescent;
|
examples/antd-mobile-demo/src/routes/IndexPage.js | zjxpcyc/xrc-form | import React from 'react';
import { connect } from 'dva';
import { List, InputItem, Button, Modal } from 'antd-mobile';
import { createForm } from 'rc-form';
import FormBody from '../../../../xrc-form/lib';
import styles from './IndexPage.css';
const UserLogIn = createForm()((props) => {
const handleSubmit = (e) => {
e.preventDefault();
props.form.validateFields((err, values) => {
if (err) {
return false;
}
console.log('=============form data==============');
console.log(JSON.stringify(values));
console.log('====================================');
Modal.alert(
'登录消息',
`登录成功, 您的登录信息: ${JSON.stringify(values)}`,
);
});
};
const items = [
{
name: 'user',
element: <InputItem>用户名</InputItem>,
options: {
rules: [{
required: true,
message: '请填写用户名',
}],
},
},
{
name: 'password',
element: <InputItem type="password">密码</InputItem>,
options: {
rules: [{
required: true,
message: '请填写密码',
}],
},
},
{
name: 'token',
element: null,
options: {
initialValue: Math.random().toString(36).substr(2),
},
},
{
element: <Button type="primary" onClick={handleSubmit}>登录</Button>,
},
];
const formProps = {
items,
form: props.form,
};
return (
<List>
<FormBody {...formProps} />
</List>
);
});
function IndexPage() {
return (
<div className={styles.normal}>
<h1 className={styles.title}>antd-mobile demo</h1>
<UserLogIn />
</div>
);
}
IndexPage.propTypes = {
};
export default connect()(IndexPage);
|
app/components/game.js | BAMason/HI | import { browserHistory } from 'react-router';
import React from 'react';
import Counter from './counter';
import Display from './display';
import Keyboard from './keyboard';
import Lost from './lose';
import Win from './win';
export default class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
'answerKey': ``,
'currentWord': null,
'triesLeft': 6,
'lettersLeft': 0,
'result': ``,
};
this.getInput = this.getInput.bind(this);
this.getWord = this.getWord.bind(this);
this.formatKey = this.formatKey.bind(this);
this.checkProgress = this.checkProgress.bind(this);
this.again = this.again.bind(this);
}
formatKey(word) {
const key = [];
const capA = 65;
const capZ = 90;
let letters = word.length;
for (let i = 0; i < word.length; i++) {
const code = word.charCodeAt(i);
if (code < capA || code > capZ) {
key.push(word[i]);
letters--;
}
else { key.push(`_`); }
}
this.setState({
'answerKey': key,
'lettersLeft': letters,
});
}
getWord() {
$.ajax({
'data': {
'api_key': process.env.WORDNIK_KEY,
'excludePartOfSpeech': `noun-plural,noun-posessive,proper-noun,` +
`proper-noun-plural,proper-noun-posessive`,
'hasDictionaryDef': true,
'includePartOfSpeech': `noun,adjective,verb,adverb`,
// 'minLength': 12,
'maxLength': 12,
'minCorpusCount': 100,
'minDictionaryCount': 10,
},
'url': `http://api.wordnik.com:80/v4/words.json/randomWord`,
})
.done((data) => {
$.ajax({
'data': {
'api_key': process.env.WORDNIK_KEY,
'includeRelated': false,
'includeTags': false,
'limit': 1,
'sourceDictionary': `webster,century,wiktionary,ahd`,
'useCanonical': false,
},
'url': `http://api.wordnik.com:80/v4/word.json/${data.word}/definitions`,
})
.done((details) => {
const detail = details[0];
const newWord = {
'attribution': detail.attributionText,
'definition': detail.text,
'partOfSpeech': detail.partOfSpeech,
'word': detail.word.toUpperCase(),
};
this.setState({ 'currentWord': newWord }, () => { this.formatKey(newWord.word); });
});
});
}
componentWillMount() {
this.getWord();
}
checkProgress() {
const tries = this.state.triesLeft;
const letters = this.state.lettersLeft;
if (tries <= 0 && letters > 0) {
this.setState({ 'result': `lost` });
}
if (letters <= 0) {
if (this.props.mp) { this.props.scored(); }
this.setState({ 'result': `won` });
}
}
getInput() {
const guess = event.target.innerHTML;
const chime = document.getElementById(`chime`);
const buzzer = document.getElementById(`buzzer`);
const word = this.state.currentWord.word;
const key = this.state.answerKey;
let tries = this.state.triesLeft;
let letters = this.state.lettersLeft;
let match = false;
for (let i = 0; i < word.length; i++) {
if (guess === word[i]) {
key[i] = guess;
letters--;
match = true;
}
}
$(event.target).addClass(`chosen`);
if (match) {
chime.play();
}
else {
buzzer.play();
--tries;
}
this.setState({
'answerKey': key,
'lettersLeft': letters,
'triesLeft': tries,
}, () => { this.checkProgress(); });
}
again() {
this.setState({
'answerKey': ``,
'currentWord': null,
'triesLeft': 6,
'lettersLeft': 0,
'result': ``,
});
this.getWord();
}
render() {
const result = this.state.result;
if (result === `won`) { return <Win word={this.state.currentWord} again={this.again}/>; }
if (result === `lost`) { return <Lost word={this.state.currentWord} again={this.again}/>; }
return <div>
<Counter value={this.state.triesLeft}/>
<Display value={this.state.answerKey}/>
<Keyboard onClick={this.getInput} />
</div>;
}
}
|
assets/javascripts/kitten/karl/pages/kissbankers-modal/stories.js | KissKissBankBank/kitten | import React from 'react'
import KissbankersModal from './index'
export default {
title: 'pages/KissbankersPage',
component: KissbankersModal,
}
export const Default = () => <KissbankersModal />
|
Realization/frontend/czechidm-core/src/content/exportimport/ExportImportDetail.js | bcvsolutions/CzechIdMng | import React from 'react';
import { connect } from 'react-redux';
//
import { Basic, Advanced, Utils, Managers, Domain } from 'czechidm-core';
import { ExportImportManager, ImportLogManager } from '../../redux';
import ExportImportTypeEnum from '../../enums/ExportImportTypeEnum';
import ConceptRoleRequestOperationEnum from '../../enums/ConceptRoleRequestOperationEnum';
import OperationStateEnum from '../../enums/OperationStateEnum';
const manager = new ExportImportManager();
const longRunningTaskManager = new Managers.LongRunningTaskManager();
const importLogManager = new ImportLogManager();
/**
* Detail of export-imports
*
* @author Vít Švanda
*
*/
export class ExportImportDetail extends Advanced.AbstractTableContent {
constructor(props, context) {
super(props, context);
this.state = {
...this.state,
report: null,
activeKey: 1,
longRunningTask: null
};
}
/**
* "Shorcut" for localization
*/
getContentKey() {
return 'content.export-imports';
}
/**
* Base manager for this agenda (used in `AbstractTableContent`)
*/
getManager() {
return manager;
}
componentDidMount() {
super.componentDidMount();
}
/**
* Submit filter action
*/
useLogFilter(event) {
if (event) {
event.preventDefault();
}
this.refs.table_import_log.useFilterForm(this.refs.logFilterForm);
}
/**
* Cancel filter action
*/
cancelLogFilter(event) {
if (event) {
event.preventDefault();
}
this.refs.table_import_log.cancelFilter(this.refs.logFilterForm);
}
_onChangeSelectTabs(activeKey) {
this.setState({activeKey});
}
/**
* Method get last string of split string by dot.
* Used for get niceLabel for type entity.
*/
_getType(name) {
return Utils.Ui.getSimpleJavaType(name);
}
render() {
const {
showLoading,
detail,
longRunningTask,
} = this.props;
const { activeKey } = this.state;
let isImport = false;
if (detail.entity && detail.entity.type) {
isImport = detail.entity.type === 'IMPORT';
}
const tableImportLogforceSearchParameters = new Domain.SearchParameters()
.setFilter('batchId', detail.entity ? detail.entity.id : Domain.SearchParameters.BLANK_UUID);
return (
<Basic.Div showLoading={showLoading}>
<Basic.Tabs activeKey={ activeKey } onSelect={ this._onChangeSelectTabs.bind(this) }>
<Basic.Tab
eventKey={ 1 }
title={this.i18n('content.export-imports.detail.tab')}
className="bordered">
<Basic.Panel className="no-border">
<Basic.AbstractForm
ref="form"
data={detail.entity}
readOnly={ !Utils.Entity.isNew(detail.entity) }
className="panel-body">
<Basic.EnumLabel
ref="type"
enum={ ExportImportTypeEnum }
style={{marginRight: '5px'}}/>
<Basic.TextField
ref="name"
readOnly
label={ this.i18n('entity.ExportImport.name.label') }/>
<Basic.Div rendered={longRunningTask}>
<Basic.Row>
<Basic.Col lg={ 6 }>
<Basic.LabelWrapper label={this.i18n('entity.LongRunningTask.counter')}>
{ longRunningTaskManager.getProcessedCount(longRunningTask) }
</Basic.LabelWrapper>
</Basic.Col>
<Basic.Col lg={ 6 }>
<Basic.Div rendered={longRunningTask && longRunningTask.taskStarted}>
<Basic.LabelWrapper label={this.i18n('entity.LongRunningTask.duration')}>
<Basic.TimeDuration
start={longRunningTask ? longRunningTask.taskStarted : null}
end={longRunningTask ? longRunningTask.modified : null}
humanized/>
</Basic.LabelWrapper>
</Basic.Div>
</Basic.Col>
</Basic.Row>
<Advanced.OperationResult value={ longRunningTask ? longRunningTask.result : null} face="full"/>
</Basic.Div>
</Basic.AbstractForm>
</Basic.Panel>
</Basic.Tab>
<Basic.Tab
eventKey={2}
rendered={isImport}
title={this.i18n('content.export-imports.treeLogs.name')}
className="bordered">
<Advanced.Tree
manager={ importLogManager }
forceSearchParameters={ tableImportLogforceSearchParameters }
className="panel-body"
header={ null }
onChange={ () => false }
nodeStyle={{ paddingLeft: 0 }}
nodeIconClassName={ null }
nodeContent={ ({ node }) => {
const operation = node.operation;
return (
<span>
<Basic.EnumValue
value={operation}
enum={ ConceptRoleRequestOperationEnum }
style={{marginRight: '5px'}}/>
<Advanced.EntityInfo
entityType={ this._getType(node.type) }
entityIdentifier={ node.dto ? node.dto.id : null}
showTree={false}
showLink={operation === 'UPDATE'}
face="popover"
entity={ node.dto }
showEntityType
showIcon/>
</span>
);
}}
/>
</Basic.Tab>
<Basic.Tab
eventKey={3}
rendered={isImport}
title={this.i18n('content.export-imports.tableLogs.name')}
className="bordered">
<Advanced.Table
ref="table_import_log"
uiKey="table-import-log"
filterOpened
manager={ importLogManager }
rowClass={ ({rowIndex, data}) => { return Utils.Ui.getRowClass(data[rowIndex]); } }
forceSearchParameters={ tableImportLogforceSearchParameters }
filter={
<Advanced.Filter onSubmit={this.useLogFilter.bind(this)}>
<Basic.AbstractForm ref="logFilterForm">
<Basic.Row>
<Basic.Col lg={ 8 }>
<Advanced.Filter.TextField
ref="text"
placeholder={this.i18n('filter.textLog.placeholder')}/>
</Basic.Col>
<Basic.Col lg={ 4 } className="text-right">
<Advanced.Filter.FilterButtons cancelFilter={this.cancelLogFilter.bind(this)}/>
</Basic.Col>
</Basic.Row>
<Basic.Row className="last">
<Basic.Col lg={ 6 }>
<Advanced.Filter.EnumSelectBox
ref="operation"
placeholder={this.i18n('filter.operation.placeholder')}
enum={ ConceptRoleRequestOperationEnum }/>
</Basic.Col>
<Basic.Col lg={ 6 }>
<Advanced.Filter.EnumSelectBox
ref="operationState"
placeholder={this.i18n('filter.operationState.placeholder')}
enum={OperationStateEnum}/>
</Basic.Col>
</Basic.Row>
</Basic.AbstractForm>
</Advanced.Filter>
}
>
<Advanced.Column
property="id"
header={ this.i18n('content.export-imports.ImportDescriptor.dto') }
cell={
/* eslint-disable react/no-multi-comp */
({ rowIndex, data }) => {
const value = data[rowIndex];
if (!value) {
return null;
}
const operation = value.operation;
return (
<Advanced.EntityInfo
entityType={ this._getType(value.type) }
entityIdentifier={ value.dto ? value.dto.id : null}
face="popover"
entity={ value.dto }
showEntityType
showLink={operation === 'UPDATE'}
showIcon/>
);
}
}/>
<Advanced.Column
property="operation"
face="enum"
enumClass={ConceptRoleRequestOperationEnum}
sort
header={ this.i18n('content.export-imports.ImportDescriptor.operation') }
width={ 100 }/>
<Advanced.Column
property="type"
header={ this.i18n('content.export-imports.ImportDescriptor.type') }
sort
cell={
({ data, rowIndex }) => {
return this._getType(data[rowIndex].type);
}
}/>
<Advanced.Column
property="result"
header={ this.i18n('content.export-imports.ImportDescriptor.result') }
sort
sortProperty="result.state"
cell={
({ data, rowIndex }) => {
return <Advanced.OperationResult value={ data[rowIndex].result }/>;
}
}/>
</Advanced.Table>
</Basic.Tab>
</Basic.Tabs>
</Basic.Div>
);
}
}
function select(state, component) {
return {
_searchParameters: Utils.Ui.getSearchParameters(state, component.uiKey), // persisted filter state in redux,
showLoading: Utils.Ui.isShowLoading(state, `${component.uiKey}-detail`)
};
}
export default connect(select, null, null, { forwardRef: true })(ExportImportDetail);
|
bandicoot/dashboard_src/public/js/timescale_brush.js | yvesalexandre/bandicoot | import React from 'react'
import d3 from 'd3'
import ReactDOM from 'react-dom'
export default class TimeScaleBrush extends React.Component {
constructor(props) {
super(props)
this.chart = null
this.chart_id = "chart_" + props.id
this.svg = null
this.brush = null
this.intervals = {}
this.updateBrush.bind(this)
}
updateBrush(new_extent) {
this.svg.select(".brush").transition()
.duration(250)
.call(this.brush.extent(new_extent))
.call(this.brush.event);
this.props.onBrush(new_extent);
}
updateNamedBrush(name) {
this.updateBrush(this.intervals[name])
}
componentDidMount() {
let el = ReactDOM.findDOMNode(this)
let margin = {top: 5, right: 20, bottom: 20, left: 0},
width = el.offsetWidth - margin.left - margin.right,
height = 80 - margin.top - margin.bottom;
let svg = d3.select(el).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
this.svg = svg
svg.append("rect")
.attr("class", "grid-background")
.attr("width", width)
.attr("height", height)
let small_interval = d3.time.month,
large_interval = d3.time.year
if(this.props.timescale.length < 52 * 7) {
small_interval = d3.time.week
large_interval = d3.time.month
}
let timescale_by_chunk = this.props.timescale.map(small_interval)
let min_max = d3.extent(timescale_by_chunk) // First and last
this.intervals = {
'all': [null, null],
'last_week': [d3.time.week.offset(min_max[1], -1), min_max[1]],
'last_month': [d3.time.month.offset(min_max[1], -1), min_max[1]]
}
let x = d3.time.scale()
.domain(min_max)
.range([0, width])
let brush = d3.svg.brush()
.x(x)
.extent([null, null])
.on("brushend", brushended)
this.brush = brush
let onBrush = this.props.onBrush
function brushended() {
if (!d3.event.sourceEvent) return; // only transition after input
let extent0 = brush.extent(),
extent1 = extent0.map(small_interval.round);
// if empty when rounded, use floor & ceil instead
if (extent1[0] >= extent1[1]) {
extent1[0] = small_interval.floor(extent0[0]);
extent1[1] = small_interval.ceil(extent0[1]);
}
d3.select(this).transition()
.duration(250)
.call(brush.extent(extent1))
.call(brush.event);
if(onBrush) onBrush(extent1)
}
// Ticks by week
svg.append("g")
.attr("class", "x grid")
.attr("transform", "translate(0," + height + ")")
.call(d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(small_interval)
.tickSize(-height)
.tickFormat(""))
// X axis with months
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(large_interval)
.tickPadding(0))
.selectAll("text")
.attr("x", 6)
.style("text-anchor", null);
// Selector brush
svg.append("g")
.attr("class", "brush")
.call(brush)
.call(brush.event)
.selectAll("rect")
.attr("height", height)
}
render() {
return (<div id={this.chart_id}></div>);
}
}
|
docs/app/Examples/views/Feed/Content/FeedExampleIconLabel.js | mohammed88/Semantic-UI-React | import React from 'react'
import { Feed, Icon } from 'semantic-ui-react'
const FeedExampleIconLabel = () => (
<Feed>
<Feed.Event>
<Feed.Label>
<Icon name='pencil' />
</Feed.Label>
<Feed.Content>
<Feed.Date>Today</Feed.Date>
<Feed.Summary>
You posted on your friend <a>Stevie Feliciano's</a> wall.
</Feed.Summary>
</Feed.Content>
</Feed.Event>
</Feed>
)
export default FeedExampleIconLabel
|
docs/app/Examples/elements/Reveal/Content/index.js | vageeshb/Semantic-UI-React | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const RevealContentExamples = () => (
<ExampleSection title='Content'>
<ComponentExample
title='Visible Content'
description='A reveal may contain content that is visible before interaction.'
examplePath='elements/Reveal/Content/RevealExampleVisible'
/>
<ComponentExample
title='Hidden Content'
description='A reveal may contain content that is hidden before user interaction.'
examplePath='elements/Reveal/Content/RevealExampleHidden'
/>
</ExampleSection>
)
export default RevealContentExamples
|
src/components/views/delegatesList/components/delegate-list/DelegateCard.js | LiskHunt/LiskHunt | import React, { Component } from 'react';
import { goDelegateProfile } from '../../../../router/routes';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { bindActionCreators } from 'redux';
import ProfilePicture from "./ProfilePicture";
import Information from "./Information";
class DelegateCard extends Component {
render() {
const { delegate } = this.props;
let image_url = delegate.img_url
? delegate.img_url
: delegate.delegate_img_url ? delegate.delegate_img_url : '';
return (
<div className="column is-4">
<a key={this.props.delegate.name} className="delegate-card"
onClick={() => this.props.goDelegateProfile(this.props.delegate.name)}
>
<article className="media">
<div className="media-left">
<ProfilePicture url={image_url} />
</div>
<div className="media-content">
<Information delegate={delegate} />
</div>
<div className="media-right">{this.props.index}</div>
</article>
</a>
</div>
);
}
}
const mapStateToProps = state => ({});
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
goDelegateProfile: name => push(goDelegateProfile + name),
},
dispatch,
);
export default connect(mapStateToProps, mapDispatchToProps)(DelegateCard);
|
spec/javascripts/jsx/gradezilla/default_gradebook/components/GradebookFilterSpec.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 GradebookFilter from 'jsx/gradezilla/default_gradebook/components/GradebookFilter';
function defaultProps () {
return {
items: [
{ id: '1', name: 'Module 1', position: 2 },
{ id: '2', name: 'Module 2', position: 1 },
],
onSelect: () => {},
selectedItemId: '0',
}
}
QUnit.module('Gradebook Filter - basic functionality', {
setup () {
const props = defaultProps();
this.wrapper = mount(<GradebookFilter {...props} />);
},
teardown () {
this.wrapper.unmount();
}
});
test('renders a Select component', function () {
strictEqual(this.wrapper.find('Select').length, 1);
});
test('disables the underlying select component if specified by props', function () {
const props = { ...defaultProps(), disabled: true };
this.wrapper = mount(<GradebookFilter {...props} />);
strictEqual(this.wrapper.find('select').nodes[0].disabled, true)
});
test('renders a screenreader-friendly label', function () {
strictEqual(this.wrapper.find('ScreenReaderContent').at(1).text(), 'Item Filter');
});
test('the Select component has three options', function () {
strictEqual(this.wrapper.find('option').length, 3);
});
test('the options are in the same order as they were sent in', function () {
const actualOptionIds = this.wrapper.find('option').map(opt => opt.node.value);
const expectedOptionIds = ['0', '1', '2'];
deepEqual(actualOptionIds, expectedOptionIds);
});
test('the options are displayed in the same order as they were sent in', function () {
const actualOptionIds = this.wrapper.find('option').map(opt => opt.text());
const expectedOptionIds = ['All Items', 'Module 1', 'Module 2'];
deepEqual(actualOptionIds, expectedOptionIds);
});
test('selecting an option calls the onSelect prop', function () {
const props = { ...defaultProps(), onSelect: this.stub() };
this.wrapper = mount(<GradebookFilter {...props} />);
this.wrapper.find('select').simulate('change', { target: { value: '2' }});
strictEqual(props.onSelect.callCount, 1);
});
test('selecting an option calls the onSelect prop with the module id', function () {
const props = { ...defaultProps(), onSelect: this.stub() };
this.wrapper = mount(<GradebookFilter {...props} />);
this.wrapper.find('select').simulate('change', { target: { value: '2' }});
strictEqual(props.onSelect.firstCall.args[0], '2');
});
test('selecting an option while the control is disabled does not call the onSelect prop', function () {
const props = { ...defaultProps(), onSelect: this.stub(), disabled: true };
this.wrapper = mount(<GradebookFilter {...props} />);
this.wrapper.find('select').simulate('change', { target: { value: '2' }});
strictEqual(props.onSelect.callCount, 0);
});
|
website/src/components/examples/EventDelegation.js | atomiks/tippyjs | import React from 'react';
import Tippy from '../Tippy';
import {Button} from '../Framework';
function EventDelegation() {
return (
<Tippy target=".child" ignoreAttributes={false}>
<div id="parent">
<Button className="child" data-tippy-content="Tooltip 1">
One
</Button>
<Button
className="child"
data-tippy-content="Tooltip 2"
data-tippy-arrow="true"
>
Two
</Button>
<Button
className="child"
data-tippy-content="Tooltip 3"
data-tippy-theme="light"
>
Three
</Button>
</div>
</Tippy>
);
}
export default EventDelegation;
|
app/src/components/LandingTiles.js | mlang12/gameswipe | import React, { Component } from 'react';
import Gametile from './Gametile.js';
class LandingTiles extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="row">
{this.props.results.map(function(result) {
return <Gametile cn={"gameTileImg"} key={result.id} result={result}/>;
})}
</div>
);
}
}
export default LandingTiles; |
src/routes.js | Lebedancer/reactFull | import React from 'react';
import { Route, IndexRoute} from 'react-router';
import App from './components/App';
import HomePage from './components/home/HomePage';
import AboutPage from './components/about/AboutPage';
import CoursesPage from './components/course/CoursesPage';
import ManageCoursePage from './components/course/ManageCoursePage';
export default (
<Route path="/" component={App}>
<IndexRoute component={HomePage} />
<Route path="courses" component={CoursesPage} />
<Route path="course" component={ManageCoursePage} />
<Route path="course/:id" component={ManageCoursePage} />
<Route path="about" component={AboutPage} />
</Route>
); |
client/modules/Intl/IntlWrapper.js | XuHaoJun/tiamat | import React from 'react';
import PropTypes from 'prop-types';
import { IntlProvider } from 'react-intl';
import { connect } from 'react-redux';
export function IntlWrapper(props) {
return <IntlProvider {...props.intl}>{props.children}</IntlProvider>;
}
IntlWrapper.propTypes = {
children: PropTypes.element.isRequired,
intl: PropTypes.object.isRequired,
};
// Retrieve data from store as props
function mapStateToProps(store) {
return { intl: store.intl };
}
export default connect(mapStateToProps)(IntlWrapper);
|
src/parser/hunter/beastmastery/modules/features/SpellsAndTalents.js | fyruna/WoWAnalyzer | import React from 'react';
import StatisticsListBox from 'interface/others/StatisticsListBox';
import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER';
import Analyzer from 'parser/core/Analyzer';
import ChimaeraShot from 'parser/hunter/beastmastery/modules/talents/ChimaeraShot';
import Stampede from 'parser/hunter/beastmastery/modules/talents/Stampede';
import KillerInstinct from 'parser/hunter/beastmastery/modules/talents/KillerInstinct';
import AspectOfTheBeast from 'parser/hunter/beastmastery/modules/talents/AspectOfTheBeast';
import BarbedShot from '../spells/BarbedShot';
import BeastCleave from '../spells/BeastCleave';
class SpellsAndTalents extends Analyzer {
static dependencies = {
beastCleave: BeastCleave,
barbedShot: BarbedShot,
killerInstinct: KillerInstinct,
chimaeraShot: ChimaeraShot,
stampede: Stampede,
aspectOfTheBeast: AspectOfTheBeast,
};
constructor(...args) {
super(...args);
// Deactivate this module if none of the underlying modules are active.
this.active = Object.keys(this.constructor.dependencies)
.map(key => this[key])
.some(dependency => dependency.active);
}
statistic() {
return (
<StatisticsListBox
position={STATISTIC_ORDER.CORE(12)}
title="Spells and Talents"
tooltip="This provides an overview of the damage contributions of various spells and talents. This isn't meant as a way to 1:1 evaluate talents, as some talents bring other strengths to the table than pure damage."
>
{this.barbedShot.active && this.barbedShot.subStatistic()}
{this.beastCleave.active && this.beastCleave.subStatistic()}
{this.killerInstinct.active && this.killerInstinct.subStatistic()}
{this.chimaeraShot.active && this.chimaeraShot.subStatistic()}
{this.stampede.active && this.stampede.subStatistic()}
{this.aspectOfTheBeast.active && this.aspectOfTheBeast.subStatistic()}
</StatisticsListBox>
);
}
}
export default SpellsAndTalents;
|
src/routes/index.js | jonkemp/universal-react-todo-app | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import IndexPage from '../components/indexPage';
const routes = (
<Route path="/">
<IndexRoute component={IndexPage}/>
</Route>
);
export default routes;
|
thingmenn-frontend/src/widgets/partybadge/index.js | baering/thingmenn | import React from 'react'
import PropTypes from 'prop-types'
import './styles.css'
const PartyBadge = ({ party, className }) => {
return (
<div
className={`PartyBadge ${className}`}
data-party={party}
style={{
backgroundImage: `url(/images/parties/${party}.svg)`,
}}
></div>
)
}
PartyBadge.propTypes = {
party: PropTypes.number,
className: PropTypes.string,
}
export default PartyBadge
|
src/components/PersonModal/PersonModal.js | rlesniak/tind3r.com | // @flow
import 'rodal/lib/rodal.css';
import React, { Component } from 'react';
import Rodal from 'rodal';
import PersonView from 'components/PersonView';
import './PersonModal.scss';
type PropsType = {
location: Object,
history: Object,
person: Object,
}
class PersonModal extends Component {
props: PropsType;
back = (e) => {
const { history } = this.props;
e.stopPropagation();
history.goBack();
};
handleActionClick = () => {
const { history } = this.props;
history.goBack();
}
render() {
return (
<div className="person-modal">
<Rodal
visible
onClose={this.back}
height={570}
width={830}
>
<PersonView
person={this.props.location.state.person}
onActionClick={this.handleActionClick}
/>
</Rodal>
</div>
);
}
}
export default PersonModal;
|
src/svg-icons/hardware/keyboard-tab.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareKeyboardTab = (props) => (
<SvgIcon {...props}>
<path d="M11.59 7.41L15.17 11H1v2h14.17l-3.59 3.59L13 18l6-6-6-6-1.41 1.41zM20 6v12h2V6h-2z"/>
</SvgIcon>
);
HardwareKeyboardTab = pure(HardwareKeyboardTab);
HardwareKeyboardTab.displayName = 'HardwareKeyboardTab';
HardwareKeyboardTab.muiName = 'SvgIcon';
export default HardwareKeyboardTab;
|
zanata-editor/src/app/components/Button/story.js | Halcom/zanata-server | import React from 'react'
import { storiesOf, action } from '@kadira/storybook'
import Button from '.'
/*
* See .storybook/README.md for info on the component storybook.
*/
storiesOf('Button', module)
.add('plain', () => (
<Button title="Click should trigger onClick action"
onClick={action('onClick')}>
Unstyled button. Pretty plain. Should be used with some styles.
</Button>
))
.add('plain (disabled)', () => (
<Button title="Should not dispatch onClick action"
onClick={action('onClick')}
disabled>
Plain disabled button. Click event should <strong>not</strong> be fired.
</Button>
))
.add('colour styles', () => (
<ul>
<li>
<Button title="Click should trigger onClick action"
onClick={action('onClick')}
className="Button Button--primary">
Button Button--primary
</Button>
</li>
<li>
<Button title="Click should trigger onClick action"
onClick={action('onClick')}
className="Button Button--success">
Button Button--success
</Button>
</li>
<li>
<Button title="Click should trigger onClick action"
onClick={action('onClick')}
className="Button Button--unsure">
Button Button--unsure
</Button>
</li>
<li>
<Button title="Click should trigger onClick action"
onClick={action('onClick')}
className="Button Button--neutral">
Button Button--neutral
</Button>
</li>
</ul>
))
.add('rounded and styled', () => (
<Button title="Styles from suggestion panel button"
onClick={action('onClick')}
className="Button Button--small u-rounded Button--primary">
Button Button--small u-rounded Button--primary
</Button>
))
// TODO add more variety of styles. See if there is a stylesheet to compare to
|
client/App.js | eantler/simmeme-client | /**
* Root Component
*/
import React from 'react';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router';
import IntlWrapper from './modules/Intl/IntlWrapper';
// Import Routes
import routes from './routes';
// Base stylesheet
require('./main.css');
export default function App(props) {
return (
<Provider store={props.store}>
<IntlWrapper>
<Router history={browserHistory}>
{ routes }
</Router>
</IntlWrapper>
</Provider>
);
}
App.propTypes = {
store: React.PropTypes.object.isRequired,
};
|
src/routes/error/index.js | tarixgit/test | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import ErrorPage from './ErrorPage';
export default {
path: '/error',
action({ error }) {
return {
title: error.name,
description: error.message,
component: <ErrorPage error={error} />,
status: error.status || 500,
};
},
};
|
ui/js/pages/newsletter/Newsletter.js | ericsoderberg/pbc-web | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import moment from 'moment-timezone';
import { loadItem, unloadItem, postNewsletterSend } from '../../actions';
import ItemHeader from '../../components/ItemHeader';
import Button from '../../components/Button';
import Loading from '../../components/Loading';
import NewsletterContents from './NewsletterContents';
const READY = 'ready';
const SENT = 'sent';
const ERROR = 'error';
class Newsletter extends Component {
constructor() {
super();
this._onSend = this._onSend.bind(this);
this.state = { sendState: 'ready' };
}
componentDidMount() {
const { dispatch, id } = this.props;
dispatch(loadItem('newsletters', id, { populate: true }));
}
componentWillReceiveProps(nextProps) {
const { dispatch, id, newsletter } = nextProps;
if (id !== this.props.id) {
dispatch(loadItem('newsletters', id, { populate: true }));
} else if (newsletter) {
document.title = newsletter.name;
}
}
componentWillUnmount() {
const { dispatch, id } = this.props;
dispatch(unloadItem('newsletters', id));
}
_onSend(event) {
const { id } = this.props;
const { address } = this.state;
event.preventDefault();
postNewsletterSend(id, address)
.then(() => this.setState({ sendState: SENT }))
.catch(() => this.setState({ sendState: ERROR }));
}
render() {
const { newsletter } = this.props;
const { sendState } = this.state;
let title;
let sendControl;
let contents;
if (newsletter) {
title = `${newsletter.name} - ${moment(newsletter.date).format('MMMM Do YYYY')}`;
let button;
if (sendState === READY) {
button = <Button label="Send" secondary={true} type="submit" />;
} else if (sendState === SENT) {
button = <span className="newsletter-send__state secondary">sent</span>;
} else if (sendState === ERROR) {
button = <span className="newsletter-send__state error">uh-oh</span>;
}
sendControl = (
<div className="newsletter-header">
<form className="newsletter-send"
action={`/newsletters/${newsletter._id}/send`}
onSubmit={this._onSend}>
<input placeholder="email address"
name="address"
type="text"
onChange={event =>
this.setState({ address: event.target.value, sendState: READY })} />
{button}
</form>
</div>
);
contents = <NewsletterContents item={newsletter} reload={false} />;
} else {
contents = <Loading />;
}
return (
<main>
<ItemHeader category="newsletters" title={title} item={newsletter} />
{sendControl}
{contents}
</main>
);
}
}
Newsletter.propTypes = {
dispatch: PropTypes.func.isRequired,
id: PropTypes.string.isRequired,
newsletter: PropTypes.object,
};
Newsletter.defaultProps = {
newsletter: undefined,
};
const select = (state, props) => {
const id = props.match.params.id;
return {
id,
notFound: state.notFound[id],
newsletter: state[id],
session: state.session,
};
};
export default connect(select)(Newsletter);
|
src/components/HorizontalRail.js | mjangir/react-scrollify | import React from 'react';
import ReactDOM from 'react-dom';
import _ from '../helpers';
import HorizontalBar from './HorizontalBar';
class HorizontalRail extends React.Component {
constructor(props) {
super(props);
this.handleOnClick = this.handleOnClick.bind(this);
this.updateScrollAndGeometry = this.updateScrollAndGeometry.bind(this);
}
componentDidMount() {
}
handleOnClick(e) {
const {
horizontalBarLeft,
containerWidth
} = this.props;
const positionLeft = e.pageX - window.pageXOffset - ReactDOM.findDOMNode(this).getBoundingClientRect().left;
const direction = positionLeft > horizontalBarLeft ? 1 : -1;
const newLeft = ReactDOM.findDOMNode(this).parentNode.scrollLeft + direction * containerWidth;
this.updateScrollAndGeometry(newLeft);
e.stopPropagation();
}
updateScrollAndGeometry(newLeft) {
// this.props.updateContainerScroll('left', newLeft);
// this.props.updateGeometry();
}
render() {
const style = {
width : this.props.horizontalRailWidth + 'px',
left : this.props.horizontalRailLeft + 'px',
};
if(this.props.isHorizontalBarUsingBottom) {
style['bottom'] = this.props.horizontalRailBottom + 'px';
} else {
style['top'] = this.props.horizontalRailTop + 'px';
}
return (
<div
className="ps-scrollbar-x-rail"
style={style}
onClick={this.handleOnClick}
>
<HorizontalBar {...this.props}/>
</div>
);
}
}
export default HorizontalRail;
|
app/components/Store/Icons/PlusIcon.js | VineRelay/VineRelayStore | import React from 'react';
import Icon from 'react-icon-base';
const PlusIcon = (props) => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m35.9 16.4v4.3q0 0.9-0.6 1.5t-1.5 0.7h-9.3v9.2q0 0.9-0.6 1.6t-1.5 0.6h-4.3q-0.9 0-1.5-0.6t-0.7-1.6v-9.2h-9.3q-0.9 0-1.5-0.7t-0.6-1.5v-4.3q0-0.9 0.6-1.5t1.5-0.6h9.3v-9.3q0-0.9 0.7-1.5t1.5-0.6h4.3q0.9 0 1.5 0.6t0.6 1.5v9.3h9.3q0.9 0 1.5 0.6t0.6 1.5z" /></g>
</Icon>
);
export default PlusIcon;
|
src/js/main.js | mnm1001/draggable-homepage | import '../styles/bootstrap.min.css'
import '../styles/styles.scss'
import React from 'react'
import ReactDOM from 'react-dom'
import { Router, browserHistory } from 'react-router'
import routes from './routes'
const rootElement = document.getElementById('app')
const ComponentEl = <Router history={browserHistory} routes={routes} />
// Render the React application to the DOM
ReactDOM.render(
ComponentEl,
rootElement
)
|
src/svg-icons/communication/no-sim.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationNoSim = (props) => (
<SvgIcon {...props}>
<path d="M18.99 5c0-1.1-.89-2-1.99-2h-7L7.66 5.34 19 16.68 18.99 5zM3.65 3.88L2.38 5.15 5 7.77V19c0 1.1.9 2 2 2h10.01c.35 0 .67-.1.96-.26l1.88 1.88 1.27-1.27L3.65 3.88z"/>
</SvgIcon>
);
CommunicationNoSim = pure(CommunicationNoSim);
CommunicationNoSim.displayName = 'CommunicationNoSim';
CommunicationNoSim.muiName = 'SvgIcon';
export default CommunicationNoSim;
|
examples/js/footer/footer-table.js | prajapati-parth/react-bootstrap-table | /* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(70);
export default class FooterTable extends React.Component {
constructor(props) {
super(props);
}
render() {
const footerData = [
[
{
label: 'Total',
target: 0
},
{
label: 'Total value',
target: 2,
align: 'right',
formatter: (tableData) => {
let label = 0;
for (let i = 0, tableDataLen = tableData.length; i < tableDataLen; i++) {
label += tableData[i].price;
}
return (
<strong>{ label }</strong>
);
}
}
]
];
return (
<div>
<BootstrapTable
data={ products }
footerData={ footerData }
showFooter
pagination>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
</div>
);
}
}
|
packages/wix-style-react/src/MessageBox/docs/AnnouncementExamples/Standard.js | wix/wix-style-react | /* eslint-disable react/prop-types */
import React from 'react';
import { MessageBoxMarketerialLayout } from 'wix-style-react';
export default () => (
<MessageBoxMarketerialLayout
title="Looking good! Your site is on Google"
content="All of your pages are indexed and now come up as separate search results on Google. This is great for your visibility!"
confirmText="Button"
imageUrl="https://static.wixstatic.com/media/9ab0d1_8f1d1bd00e6c4bcd8764e1cae938f872~mv1.png"
theme="blue"
primaryButtonLabel="Button"
secondaryButtonLabel="Secondary action"
dataHook="announcement-standard"
onClose={() => undefined}
/>
);
|
rallyboard-v2/client/src/RaBreadcrumb.js | tylerjw/rallyscores | import React, { Component } from 'react';
import {
Breadcrumb
} from 'semantic-ui-react';
import { Link } from 'react-router-dom';
class RaBreadcrumb extends Component {
render() {
const { year, code } = this.props;
return (
<Breadcrumb size='big'>
<Breadcrumb.Section link as={Link} to="/">Home</Breadcrumb.Section>
<Breadcrumb.Divider icon='right chevron' />
<Breadcrumb.Section active>Rally America - {year} {code}</Breadcrumb.Section>
</Breadcrumb>
);
}
}
export default RaBreadcrumb;
|
Harddisk Browser/Flat-UI-master/ReactJS Browser/src/client/app/js/components/TVShow.js | tomjose92/Fun-Projects | import React from 'react';
import Radium,{StyleRoot} from 'radium';
import {connect} from 'react-redux';
import Header from './common/Header';
import Link from './common/Link';
import {TVSHOW_ONLINE_URL, TVSHOW_LOCAL_URL} from '../constants/apis';
import Gap from './common/Gap';
import {Images, ImagePosition} from '../constants/images';
import TVShowModal from './TVShowModal';
import UpcomingEpisodes from './UpcomingEpisodes';
import {blurImage, extractTVShowsFromURL} from 'utils';
import { fetchTVShowsData,
fetchTVShowInfo,
setCurrentTVShow,
setTVShowData,
removeTVShow} from '../actions/tvshow';
import { getTVShowData,
isFetchingTVShow,
getTVShowStatus,
getTVShowsInfo,
getTVShows} from 'selectors';
import isEmpty from 'lodash/isEmpty';
import ActionsPanel from './ActionsPanel';
@Radium
class TVShow extends React.Component {
constructor(){
super();
document.body.className="mediaBG";
this.state = {
records:[],
error:false,
interval:2000,
search: false,
addShow: false,
isInit: true
};
this.setTVShowsState = this.setTVShowsState.bind(this);
}
fetchTVShowData(isLocal=true){
console.log('fetchTVShowData');
console.log('Accessing',isLocal?'local':'online');
let data = extractTVShowsFromURL();
let url = isLocal?TVSHOW_LOCAL_URL: TVSHOW_ONLINE_URL;
let {isInit} = this.state;
if(data.length>0)
{
this.props.setTVShowData(data);
}
else
{
this.props.fetchTVShowsData({url, isLocal, isInit});
}
!isInit && this.setState({
isInit: true
});
}
componentWillMount() {
let {tvShows} = this.props;
if(isEmpty(tvShows)){
this.fetchTVShowData(false);
}
else
{
let {records} = this.state;
if(isEmpty(records))
{
this.setState({
records: tvShows,
isInit: true
});
}
}
}
shouldComponentUpdate( nextProps){
return nextProps;
}
closeModal(){
this.setState({
tvShow:{},
open: false
});
}
showModal(tvShow,index){
let {records: tvShows} = this.state;
let {tvShowsInfo} = this.props;
let {tv_show_name} = tvShow;
if(!tvShowsInfo[tv_show_name])
{
this.props.fetchTVShowInfo(tv_show_name);
}
else
{
this.props.setCurrentTVShow(tv_show_name);
}
if(index!=undefined)
{
tvShow.prev = tvShows[index-1];
tvShow.next = tvShows[index+1];
tvShow.index = index;
}
this.setState({
tvShow,
open: true
});
blurImage(false);
}
setTVShowsState(tvShows){
this.setState({
records: tvShows
});
}
render() {
let self=this,
{error, open, tvShow, records: tvShows} = this.state;
let {isLocal, isLoading, tvShowsInfo} = this.props;
let TVShowImages = isEmpty(tvShows)? null : tvShows.map(function(tvShow,i){
let {tv_show_name, tv_show_tag, episode} = tvShow;
let title = tv_show_name;
if(episode)
{
let {season, number, name, date} = episode;
title += ` : S${season}E${number} ${name} (${date})`;
}
let showInfo = tvShowsInfo && tvShowsInfo[tv_show_name];
let image = showInfo && showInfo.image && showInfo.image.medium;
return (
<span className='tvShow' title={title} style={styles.imageBox} key={"tvShow"+i}>
<div style={styles.close} onClick={()=>self.props.removeTVShow(tv_show_name)}>✕</div>
<a onClick={()=>self.showModal(tvShow, i)}>
{false ?
<img className='tvshow' key={"image"+i} style={Object.assign({},styles.image,Images[tv_show_tag], ImagePosition[tv_show_tag])}/>
:<img className='tvshow' key={"image"+i} style={styles.image} src={image}/>
}
</a>
</span>
)
});
return (
<StyleRoot>
<nav>
<Header isLocal={isLocal} loading={isLoading} error={error} onRefresh={()=>this.fetchTVShowData(false)} app="TVShows"/>
</nav>
{!isLoading &&
<div style={styles.outerContainer}>
<ActionsPanel callback={this.setTVShowsState} />
<UpcomingEpisodes
callback={this.setTVShowsState}
showModal={(tvShow)=>this.showModal(tvShow)}/>
<div style={styles.container}>
{open && <TVShowModal tvShow={tvShow} navShow={(tvShow,index)=>this.showModal(tvShow,index)} callback={()=>this.closeModal()} />}
{TVShowImages}
</div>
</div>}
</StyleRoot>
);
}
componentDidMount() {
/*let self=this;
let {records} = this.state;
if(isEmpty(records))
{
setTimeout(function(){
self.fetchTVShowData(false);
},this.state.interval);
}*/
}
componentDidUpdate(prevProps, prevState)
{
let {tvShows} = this.props;
let {tvShows: oldTVShows} = prevProps;
if(tvShows!=oldTVShows)
{
this.setState({records: tvShows});
}
}
};
const styles={
outerContainer:{
textAlign: 'center',
width:'100%'
},
container:{
position: 'absolute',
top: '140px',
left: '-20px',
right: '0px',
textAlign: 'center',
'@media screen and (min-width: 1600px)':{
left: '20px',
right: '50px',
},
},
image:{
height: '300px',
width: '250px',
cursor: 'pointer',
paddingBottom: '20px',
backgroundRepeat: 'no-repeat',
backgroundClip : 'content-box',
backgroundSize : '1275px 1420px'
},
imageBox: {
paddingLeft: '20px',
position: 'relative',
width: '270px',
height: '300px',
display: 'inline-block'
},
close:{
background: '#56544D',
color: '#CEC9BE',
cursor: 'pointer',
fontFamily: 'times new roman',
fontSize: '20px',
lineHeight: '30px',
fontWeight: 'bold',
padding: '0px',
position: 'absolute',
right: '0px',
top: '0px',
width: '30px',
height: '30px',
textAlign: 'center',
textShadow: 'none',
zIndex: '10',
opacity: '0.7'
}
}
const mapStateToProps = (state) =>{
let tvShows = getTVShowData(state);
let isLoading = isFetchingTVShow(state);
let isLocal = getTVShowStatus(state);
let tvShowsInfo = getTVShowsInfo(state);
return {
tvShows,
isLoading,
isLocal,
tvShowsInfo
};
};
export default connect(
mapStateToProps,
{
fetchTVShowsData,
fetchTVShowInfo,
setCurrentTVShow,
setTVShowData,
removeTVShow,
}
)(TVShow); |
src/pages/post_edit.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 { connect } from 'react-redux';
import _ from 'lodash';
import NotFound from './not-found'
import Header from '../components/header';
import Footer from '../components/footer';
import {API_HOST} from '../config';
import ApiClient from '../api/client'
import { addPost } from '../actions';
import { URL_NAMES, getUrl } from '../utils/urlGenerator';
import {EditPost} from '../components/post'
import TagsEditor from '../components/post/tags-editor';
import Sidebar from '../components/sidebar';
import SidebarAlt from '../components/sidebarAlt';
import { defaultSelector } from '../selectors';
import { ActionsTrigger } from '../triggers';
class PostEditPage extends React.Component {
constructor (props) {
super(props);
this.submitHandler = this.submitHandler.bind(this);
this.removeHandler = this.removeHandler.bind(this);
}
static async fetchData(params, store, client) {
let postInfo = client.postInfo(params.uuid);
const noScoolsLoaded = store.getState().get('schools').isEmpty();
let schoolsPromise;
if (noScoolsLoaded) {
let trigger = new ActionsTrigger(client, store.dispatch);
schoolsPromise = trigger.loadSchools();
}
store.dispatch(addPost(await postInfo));
if (noScoolsLoaded) {
await schoolsPromise;
}
}
removeHandler(event) {
event.preventDefault();
if (confirm(`Are you sure you want to delete this post and all it's comments? There is no undo.`)) {
const client = new ApiClient(API_HOST);
const triggers = new ActionsTrigger(client, this.props.dispatch);
triggers.deletePost(this.props.params.uuid)
.then(() => {
this.props.history.pushState(null, '/');
}).catch(e => {
// FIXME: "failed to delete post" should be reported to user
console.error(e); // eslint-disable-line no-console
});
}
}
submitHandler(event) {
event.preventDefault();
let form = event.target;
const client = new ApiClient(API_HOST);
const triggers = new ActionsTrigger(client, this.props.dispatch);
triggers.updatePost(
this.props.params.uuid,
{
text: form.text.value,
tags: this.editor.getTags(),
schools: this.editor.getSchools()
}
)
.then((result) => {
this.props.history.pushState(null, getUrl(URL_NAMES.POST, { uuid: result.id }));
});
}
render() {
const post_uuid = this.props.params.uuid;
if (!(post_uuid in this.props.posts)) {
// not loaded yet
return <script/>
}
const current_post = this.props.posts[post_uuid];
if (current_post === false) {
return <NotFound/>
}
if (current_post.user_id != this.props.current_user.id) {
return <script/>;
}
return (
<div>
<Header is_logged_in={this.props.is_logged_in} current_user={this.props.current_user} />
<div className="page__container">
<div className="page__body">
<Sidebar current_user={this.props.current_user}/>
<div className="page__content">
<div className="box box-post box-space_bottom">
<form onSubmit={this.submitHandler} action="" method="post">
<input type="hidden" name="id" value={current_post.id} />
<div className="box__body">
<EditPost post={current_post}/>
<TagsEditor
autocompleteSchools={_.values(this.props.schools)}
autocompleteTags={[{name: 'TestTagOne'}, {name: 'TestTagTwo'}]}
ref={(editor) => this.editor = editor}
schools={current_post.schools}
tags={current_post.labels}
/>
<div className="layout__row">
<div className="layout layout__grid layout-align_right">
<button className="button button-red" type="button" onClick={this.removeHandler}><span className="fa fa-trash-o"></span></button>
<button className="button button-wide button-green" type="submit">Save</button>
</div>
</div>
</div>
</form>
</div>
</div>
<SidebarAlt />
</div>
</div>
<Footer/>
</div>
)
}
}
export default connect(defaultSelector)(PostEditPage);
|
app/containers/ForgotPassword/ForgotPasswordForm.js | danielmoraes/invoices-web-client | import React from 'react'
import { Form } from 'components'
import { User } from 'api/entity-schema'
const formLayout = [
[ 'email' ]
]
const formOptions = {
focus: 'email',
hideLabels: true,
fieldOptions: {
email: {}
}
}
// inject schema to field options
Object.keys(formOptions.fieldOptions).forEach((field) => {
formOptions.fieldOptions[field].schema = User[field]
})
const ForgotPasswordForm = (props) => (
<Form layout={formLayout} options={formOptions} {...props} />
)
export default ForgotPasswordForm
|
assets/javascripts/kitten/components/graphics/illustrations/lightbulb-illustration.js | KissKissBankBank/kitten | import React from 'react'
import PropTypes from 'prop-types'
import { checkDeprecatedSizes } from '../../../helpers/utils/deprecated'
export const LightbulbIllustration = ({ size, ...props }) => {
checkDeprecatedSizes(size)
if (size === 'small') {
return (
<svg width={24} height={33} viewBox="0 0 24 33" {...props}>
<g fill="none" fillRule="evenodd">
<path
d="M12.171.5c6.446 0 11.671 5.225 11.671 11.671 0 4.76-2.85 8.855-6.937 10.671l-1.02 1.53H8.458l-1.021-1.53C3.35 21.026.5 16.932.5 12.172.5 5.724 5.725.5 12.171.5z"
fill="#FFEBDF"
/>
<path
d="M12.171 4.479a.796.796 0 110 1.591 6.1 6.1 0 00-6.1 6.101.796.796 0 11-1.592 0A7.692 7.692 0 0112.17 4.48z"
fill="#FFF"
fillRule="nonzero"
/>
<path
d="M9.29 15.979l.073.061 2.278 2.277v3.934a.53.53 0 01-1.053.095l-.008-.095v-3.494L8.612 16.79a.53.53 0 01-.061-.677l.06-.073a.53.53 0 01.678-.061zm6.44.061a.53.53 0 01.06.677l-.06.073-1.968 1.967v3.494a.53.53 0 01-.435.522l-.095.008a.53.53 0 01-.522-.435l-.008-.095v-3.934l2.277-2.277a.53.53 0 01.75 0z"
fill="#222"
fillRule="nonzero"
/>
<path
d="M9.519 30.739a1.061 1.061 0 01-1.061-1.061V24.37h7.427v5.308c0 .586-.475 1.06-1.061 1.06h-1.061v.531a1.592 1.592 0 01-3.183 0v-.53H9.519z"
fill="#00B3FD"
/>
<path
d="M15.885 28.086v1.061H8.458v-1.06h7.427zm0-2.122v1.061H8.458v-1.06h7.427z"
fill="#FFF"
/>
</g>
</svg>
)
}
return (
<svg width={62} height={70} viewBox="0 0 62 70" {...props}>
<g fill="none" fillRule="evenodd">
<path
d="M31 9c12.15 0 22 9.85 22 22 0 8.973-5.372 16.691-13.075 20.114L38 54H24l-1.924-2.885C14.372 47.692 9 39.973 9 31 9 18.85 18.85 9 31 9zM7.983 43.134l1 1.732-4.33 2.5-1-1.732 4.33-2.5zm46.034 0l4.33 2.5-1 1.732-4.33-2.5 1-1.732zM62 30v2h-5v-2h5zM5 30v2H0v-2h5zm52.347-15.366l1 1.732-4.33 2.5-1-1.732 4.33-2.5zm-52.694 0l4.33 2.5-1 1.732-4.33-2.5 1-1.732zm40.981-10.98l1.732 1-2.5 4.33-1.732-1 2.5-4.33zm-29.268 0l2.5 4.33-1.732 1-2.5-4.33 1.732-1zM32 0v5h-2V0h2z"
fill="#FFEBDE"
/>
<path
d="M31 16.5a1.5 1.5 0 010 3c-6.351 0-11.5 5.149-11.5 11.5a1.5 1.5 0 01-3 0c0-8.008 6.492-14.5 14.5-14.5z"
fill="#FFF"
fillRule="nonzero"
/>
<path
d="M25.613 38.21l.094.083L30 42.586V50a1 1 0 01-1.993.117L28 50v-6.585l-3.707-3.708a1 1 0 01-.083-1.32l.083-.094a1 1 0 011.32-.083zm12.094.083a1 1 0 01.083 1.32l-.083.094L34 43.414V50a1 1 0 01-.883.993L33 51a1 1 0 01-.993-.883L32 50v-7.414l4.293-4.293a1 1 0 011.414 0z"
fill="#222"
fillRule="nonzero"
/>
<path
d="M26 66a2 2 0 01-2-2v-1h14v1a2 2 0 01-2 2h-2v1a3 3 0 01-6 0v-1h-2zm12-7v2H24v-2h14zm0-5v3H24v-3h14z"
fill="#00B3FD"
/>
<path fill="#FFF" d="M24 57h14v2H24zM24 61h14v2H24z" />
</g>
</svg>
)
}
LightbulbIllustration.propTypes = {
size: PropTypes.oneOf(['small', 'medium', null, undefined]),
}
|
src/pages/blog/index.js | saschajullmann/gatsby-starter-gatsbythemes | /* eslint-disable */
import React from 'react';
import { graphql } from 'gatsby';
import Link from 'gatsby-link';
import { Box } from '../../components/Layout';
import colors from '../../utils/colors';
import PageWrapper from '../../components/PageWrapper';
import { css } from 'react-emotion';
const listStyle = css`
list-style-type: none;
margin: 0;
padding: 0;
`;
const BlogIndex = ({ data }) => {
const { edges: posts } = data.allMarkdownRemark;
return (
<PageWrapper>
<Box bg={colors.primary}>
<Box
width={[1, 1, 1 / 2]}
m={['3.5rem 0 0 0', '3.5rem 0 0 0', '3.5rem auto 0 auto']}
px={[3, 3, 0]}
color={colors.secondary}
>
<h1>Blog</h1>
<ul className={listStyle}>
{posts
.filter(post => post.node.frontmatter.title.length > 0)
.map(({ node: post }, index) => {
return (
<li key={post.id}>
<Link to={post.fields.slug}>
<h3>{post.frontmatter.title}</h3>
</Link>
<p>{post.excerpt}</p>
</li>
);
})}
</ul>
</Box>
</Box>
</PageWrapper>
);
};
export const query = graphql`
query BlogQuery {
allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) {
edges {
node {
excerpt(pruneLength: 250)
id
frontmatter {
title
date(formatString: "MMMM DD, YYYY")
}
fields {
slug
}
}
}
}
}
`;
/* eslint-enable */
export default BlogIndex;
|
router_tutorial/04-nested-routes/modules/App.js | Muzietto/react-playground | import React from 'react'
import { Link } from 'react-router'
export default React.createClass({
render() {
return (
<div>
<h1>React Router 04</h1>
<ul role="nav">
<li><Link to="/about" activeStyle={{color:'red'}}>About</Link></li>
<li><Link to="/repos" activeClassName="active">Repos</Link></li>
<li><Link to="/outsidez" activeClassName="active">Outside</Link></li>
</ul>
{/* children of the ROUTE!!! */}
{ this.props.children }
</div>
)
}
})
|
src/templates/not-found-template.js | Chogyuwon/chogyuwon.github.io | import React from 'react';
import { graphql } from 'gatsby';
import Sidebar from '../components/Sidebar';
import Layout from '../components/Layout';
import Page from '../components/Page';
const NotFoundTemplate = ({ data }) => {
const {
title,
subtitle
} = data.site.siteMetadata;
return (
<Layout title={`Not Found - ${title}`} description={subtitle}>
<Sidebar />
<Page title="NOT FOUND">
<p>You just hit a route that doesn't exist... the sadness.</p>
</Page>
</Layout>
);
};
export const query = graphql`
query NotFoundQuery {
site {
siteMetadata {
title
subtitle
}
}
}
`;
export default NotFoundTemplate;
|
src/components/TooltipIcon/TooltipIcon-story.js | joshblack/carbon-components-react | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { storiesOf } from '@storybook/react';
import Filter16 from '@carbon/icons-react/lib/filter/16';
import { withKnobs, select, text } from '@storybook/addon-knobs';
import TooltipIcon from '../TooltipIcon';
const directions = {
'Bottom (bottom)': 'bottom',
'Top (top)': 'top',
};
const props = () => ({
direction: select('Tooltip direction (direction)', directions, 'bottom'),
tooltipText: text('Tooltip content (tooltipText)', 'Filter'),
});
storiesOf('TooltipIcon', module)
.addDecorator(withKnobs)
.add(
'default',
() => (
<TooltipIcon {...props()}>
<Filter16 />
</TooltipIcon>
),
{
info: {
text: `
Tooltip Icon
`,
},
}
);
|
components/BtnContainer/BtnContainer.js | NGMarmaduke/bloom | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import cx from 'classnames';
import css from './BtnContainer.css';
export default class BtnContainer extends Component {
static propTypes = {
className: PropTypes.string,
children: PropTypes.node.isRequired,
type: PropTypes.oneOf(['submit', 'button', 'reset', 'menu']),
};
static defaultProps = {
type: 'button',
};
render() {
const { className, type, children, ...rest } = this.props;
const classes = cx(css.root, className);
return (
<button
className={ classes }
type={ type }
{ ...rest }
>
{ children }
</button>
);
}
}
|
src/docs/examples/Label/ExampleRequired.js | dryzhkov/ps-react-dr | import React from 'react';
import Label from 'ps-react/Label';
/** Required label */
export default function ExampleRequired() {
return <Label htmlFor="test" label="test" required />
} |
src/components/Bottom/Bottom.js | golotiuk/Good_luck | import React, { Component } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from '../App/App.scss';
import Feedback from './Feedback/Feedback';
import Footer from './Footer/Footer';
class Bottom extends Component {
render() {
return (
<div className={s.fee}>
<Feedback />
<Footer />
</div>
);
}
}
export default withStyles(Bottom, s);
|
PheidippidesDesktop/pheidippidesdesktop_web/src/App.js | Arcite/Pheidippides | import React, { Component } from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Header from './components/Header';
import ChartWrapper from './components/Chart';
export default class App extends Component {
render() {
return (
<MuiThemeProvider>
<div>
<Header />
<ChartWrapper />
</div>
</MuiThemeProvider>
);
}
} |
packages/docs/components/Examples/video/CustomAddVideoVideoEditor/index.js | nikgraf/draft-js-plugin-editor | import React, { Component } from 'react';
import { EditorState } from 'draft-js';
import Editor from '@draft-js-plugins/editor';
import createVideoPlugin from '@draft-js-plugins/video';
import VideoAdd from './VideoAdd';
import editorStyles from './editorStyles.module.css';
const videoPlugin = createVideoPlugin();
const plugins = [videoPlugin];
export default class CustomVideoEditor extends Component {
state = {
editorState: EditorState.createEmpty(),
};
onChange = (editorState) => {
this.setState({
editorState,
});
};
focus = () => {
this.editor.focus();
};
render() {
return (
<div>
<div className={editorStyles.editor} onClick={this.focus}>
<Editor
editorState={this.state.editorState}
onChange={this.onChange}
plugins={plugins}
ref={(element) => {
this.editor = element;
}}
/>
</div>
<VideoAdd
editorState={this.state.editorState}
onChange={this.onChange}
modifier={videoPlugin.addVideo}
/>
</div>
);
}
}
|
uis/mp-next/src/components/AudiosGridList.js | andrew-hai/bdgt | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { withStyles } from 'material-ui/styles';
import GridList, { GridListTile, GridListTileBar } from 'material-ui/GridList';
import IconButton from 'material-ui/IconButton';
import PlayCircleOutline from 'material-ui-icons/PlayCircleOutline';
import PauseCircleOutline from 'material-ui-icons/PauseCircleOutline';
import {
play,
pause,
playById
} from '../actions/index'
const styles = theme => ({
container: {
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-around',
overflow: 'hidden',
background: theme.palette.background.paper,
},
gridList: {
paddingTop: 0
},
textRight: {
textAlign: 'right'
},
button: {
color: 'white'
}
});
class AudiosGridList extends React.Component {
playById = (index) => {
const { dispatch } = this.props;
dispatch(playById(index));
};
play = () => {
const { dispatch } = this.props;
dispatch(play());
};
pause = () => {
const { dispatch } = this.props;
dispatch(pause());
};
render() {
const { audios, audioId, playing } = this.props;
const { classes } = this.props;
const cols = (audios.length >= 5) ? 5 : audios.length;
return (
<div className={classes.container}>
<GridList cellHeight={180} className={classes.gridList} cols={cols}>
{audios.map((audio, i) => (
<GridListTile key={audio.id}>
<img src={audio.img} alt={audio.title} />
<GridListTileBar
title={audio.title}
subtitle={<span>by: {audio.artist}</span>}
actionIcon={
<span>
{ (audioId === audio.id && !playing) &&
<IconButton onClick={this.play} className={classes.button}>
<PlayCircleOutline />
</IconButton>
}
{ (audioId === audio.id && playing) &&
<IconButton onClick={this.pause} className={classes.button}>
<PauseCircleOutline />
</IconButton>
}
{ (audioId !== audio.id) &&
<IconButton onClick={() => this.playById(audio.id)} className={classes.button}>
<PlayCircleOutline />
</IconButton>
}
</span>
}
/>
</GridListTile>
))}
</GridList>
</div>
)
}
}
AudiosGridList.defaultProps = {
audios: [],
playing: false
};
AudiosGridList.propTypes = {
audios: PropTypes.array.isRequired,
classes: PropTypes.object.isRequired
}
function mapStateToProps(state) {
return state.playerData;
}
export default connect(mapStateToProps)(
withStyles(styles)(AudiosGridList)
)
|
server/middleware/reactMiddleware.js | Art404/twitter-boiler404 | import {RouterContext, match} from 'react-router'
import {Provider} from 'react-redux'
import React from 'react'
import configureStore from '../../client/store/configureStore'
import {createLocation} from 'history'
import {setClient} from '../../client/actions/AppActions'
import {renderToString} from 'react-dom/server'
import routes from '../../client/routes'
import MobileDetect from 'mobile-detect'
function hydrateInitialStore (req) {
const md = new MobileDetect(req.headers['user-agent'])
const agent = md.mobile() ? 'mobile' : 'desktop'
req.cookies = req.cookies || {}
const cookie = req.cookies[process.env.COOKIE_NAME]
return (dispatch) => Promise.all([dispatch(setClient({cookie, agent}))])
}
export default function reactMiddleware (req, res) {
const location = createLocation(req.url)
match({routes, location}, (error, redirectLocation, renderProps) => {
if (error) return res.status(500).send(error.message)
if (redirectLocation) return res.redirect(302, redirectLocation.pathname + redirectLocation.search)
if (!renderProps) return res.redirect(302, '/')
const assets = require('../../build/assets.json')
const store = configureStore()
return store.dispatch(hydrateInitialStore(req)).then(() => {
const initialState = JSON.stringify(store.getState())
let content
try {
content = renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
)
} catch(e) {
console.log('ERROR RENDERING APP', e)
process.exit()
}
return res.render('index', {content, assets, initialState})
})
})
}
|
project/react-ant-multi-pages/src/pages/index/containers/PureSaga/Item/index.js | FFF-team/generator-earth | import React from 'react'
import moment from 'moment'
import { DatePicker, Button, Form, Input, Col } from 'antd'
import BaseContainer from 'ROOT_SOURCE/base/BaseContainer'
import request from 'ROOT_SOURCE/utils/request'
import { mapMoment } from 'ROOT_SOURCE/utils/fieldFormatter'
import Rules from 'ROOT_SOURCE/utils/validateRules'
const FormItem = Form.Item
export default Form.create()(class extends BaseContainer {
/**
* 提交表单
*/
submitForm = (e) => {
e && e.preventDefault()
const { form } = this.props
form.validateFieldsAndScroll(async (err, values) => {
if (err) {
return;
}
// 提交表单最好新起一个事务,不受其他事务影响
await this.sleep()
let _formData = { ...form.getFieldsValue() }
// _formData里的一些值需要适配
_formData = mapMoment(_formData, 'YYYY-MM-DD HH:mm:ss')
// action
await request.post('/asset/updateAsset', _formData)
//await this.props.updateForm(_formData)
// 提交后返回list页
this.props.history.push(`${this.context.CONTAINER_ROUTE_PREFIX}/list`)
})
}
constructor(props) {
super(props);
this.state = {};
}
async componentDidMount() {
let { data } = await request.get('/asset/viewAsset', {id: this.props.match.params.id /*itemId*/})
this.setState(data)
}
render() {
let { form, formData } = this.props
let { getFieldDecorator } = form
const { id, assetName, contract, contractDate, contacts, contactsPhone } = this.state
return (
<div className="ui-background">
<Form layout="inline" onSubmit={this.submitForm}>
{getFieldDecorator('id', { initialValue: id===undefined ? '' : +id})(
<Input type="hidden" />
)}
<FormItem label="资产方名称">
{getFieldDecorator('assetName', {
rules: [{ required: true }],
initialValue: assetName || ''
})(<Input disabled />)}
</FormItem>
<FormItem label="签约主体">
{getFieldDecorator('contract', {
rules: [{ required: true }],
initialValue: contract || ''
})(<Input disabled />)}
</FormItem>
<FormItem label="签约时间">
{getFieldDecorator('contractDate', {
rules: [{ type: 'object', required: true }],
initialValue: contractDate && moment(contractDate)
})(<DatePicker showTime format='YYYY年MM月DD HH:mm:ss' style={{ width: '100%' }} />)}
</FormItem>
<FormItem label="联系人">
{getFieldDecorator('contacts', { initialValue: contacts || ''
})(<Input />)}
</FormItem>
<FormItem label="联系电话" hasFeedback>
{getFieldDecorator('contactsPhone', {
rules: [{ pattern: Rules.phone, message: '无效' }],
initialValue: contactsPhone || ''
})(<Input maxLength="11" />)}
</FormItem>
<FormItem>
<Button type="primary" htmlType="submit"> 提交 </Button>
</FormItem>
<FormItem>
<Button type="primary" onClick={e=>window.history.back()}> 取消/返回 </Button>
</FormItem>
</Form>
</div>
)
}
}) |
src/shared/containers/404/NotFoundPage.js | Mike1Q84/react-ssr-simple | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Helmet } from "react-helmet";
import t from './_lang.json';
export class NotFoundPage extends Component {
render() {
let { lang } = this.props;
return (
<div className="not-found">
<Helmet>
<title>{t[lang.id].title}</title>
</Helmet>
<h1 className="not-found__title">{t[lang.id].title}</h1>
</div>
)
}
}
NotFoundPage.propTypes = {
lang: PropTypes.object.isRequired
};
function mapStateToProps(state) {
return {
lang: state.lang
};
}
export default connect(mapStateToProps)(NotFoundPage);
|
src/components/charts/PieChartCust.js | sateez/salestracker | import React from 'react';
import {Pie} from 'react-chartjs-2';
class PieChartCust extends React.Component{
constructor(props, context) {
super(props, context);
}
render() {
let chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(231,233,237)'
};
const pieData = {
labels: [
'June',
'July',
'August',
'September',
'October',
'November'
],
datasets: [{
data: this.props.myLast6MonthRevenue,
backgroundColor: [
chartColors.red,
chartColors.orange,
chartColors.yellow,
chartColors.green,
chartColors.blue,
chartColors.purple
],
hoverBackgroundColor: [
chartColors.red,
chartColors.orange,
chartColors.yellow,
chartColors.green,
chartColors.blue,
chartColors.purple
]
}]
};
return (
<div className='pie-chart-container'>
<h2>Revenue of the model for past 6 months</h2>
<Pie data={pieData} />
</div>
)
}
}
export default PieChartCust;
|
src/svg-icons/communication/message.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationMessage = (props) => (
<SvgIcon {...props}>
<path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/>
</SvgIcon>
);
CommunicationMessage = pure(CommunicationMessage);
CommunicationMessage.displayName = 'CommunicationMessage';
CommunicationMessage.muiName = 'SvgIcon';
export default CommunicationMessage;
|
src/views/icons/MenuIndicatorIcon.js | physiii/home-gateway | import React from 'react';
import IconBase from './IconBase.js';
export const MenuIndicatorIcon = (props) => (
<IconBase {...props} viewBox="7 10 10 5">
<path d="M7 10l5 5 5-5z" />
</IconBase>
);
export default MenuIndicatorIcon;
|
stories/index.js | ringmath/gene-lab | import React from 'react'
import { storiesOf, action } from '@kadira/storybook'
import GeneLab from '../src'
storiesOf('GeneLab', module)
.addWithInfo('Basic', 'added Description', () => (
<GeneLab />
), { inline: true })
.add('Basic', () => (
<GeneLab />
))
|
smsgw/static/js/applications/add.react.js | VojtechBartos/smsgw | 'use strict';
import React from 'react';
import {List} from 'immutable';
import {create} from './actions';
import Component from '../components/component.react';
import Subheader from '../components/subheader.react';
import FlashMessages from '../components/flashmessages.react';
import Form from './form.react';
class Add extends Component {
onFormSubmit(e) {
e.preventDefault();
const form = this.refs.applicationForm;
if (form.isValid())
create(form.getData()).then(() => {
this.redirectOnSuccess();
});
}
redirectOnSuccess() {
this.props.router.transitionTo('applications');
}
render() {
const messages = this.props.flashMessages;
return (
<div>
<Subheader backTitle="Applications"
backRoute="applications"
router={this.props.router}>
<h1>Add application</h1>
</Subheader>
<div id="context">
<FlashMessages messages={messages} />
<Form onSubmit={e => this.onFormSubmit(e)}
ref="applicationForm"
pending={create.pending} />
</div>
</div>
);
}
}
Add.propTypes = {
router: React.PropTypes.func,
flashMessages: React.PropTypes.instanceOf(List).isRequired
};
export default Add;
|
src/svg-icons/action/alarm-off.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAlarmOff = (props) => (
<SvgIcon {...props}>
<path d="M12 6c3.87 0 7 3.13 7 7 0 .84-.16 1.65-.43 2.4l1.52 1.52c.58-1.19.91-2.51.91-3.92 0-4.97-4.03-9-9-9-1.41 0-2.73.33-3.92.91L9.6 6.43C10.35 6.16 11.16 6 12 6zm10-.28l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM2.92 2.29L1.65 3.57 2.98 4.9l-1.11.93 1.42 1.42 1.11-.94.8.8C3.83 8.69 3 10.75 3 13c0 4.97 4.02 9 9 9 2.25 0 4.31-.83 5.89-2.2l2.2 2.2 1.27-1.27L3.89 3.27l-.97-.98zm13.55 16.1C15.26 19.39 13.7 20 12 20c-3.87 0-7-3.13-7-7 0-1.7.61-3.26 1.61-4.47l9.86 9.86zM8.02 3.28L6.6 1.86l-.86.71 1.42 1.42.86-.71z"/>
</SvgIcon>
);
ActionAlarmOff = pure(ActionAlarmOff);
ActionAlarmOff.displayName = 'ActionAlarmOff';
ActionAlarmOff.muiName = 'SvgIcon';
export default ActionAlarmOff;
|
docs/public/static/examples/v36.0.0/map-view.js | exponent/exponent | import React from 'react';
import MapView from 'react-native-maps';
import { StyleSheet, View, Dimensions } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<MapView style={styles.mapStyle} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
mapStyle: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
},
});
|
src/containers/BooksList/Page.js | LifeSourceUA/lifesource.ua | import React, { Component } from 'react';
import Helmet from 'react-helmet';
import Meta from './Meta';
// import * as Book from 'components/Book';
import * as Common from 'components/Common';
import breadcrumbs from './Mock/Breadcrumbs.json';
import headerMenuItems from './Mock/HeaderMenu.json';
class BooksListPage extends Component {
render = () => {
return (
<div>
<Helmet { ...Meta() }/>
<Common.Header items={ headerMenuItems }/>
<Common.List type={ 'book' }/>
<Common.Breadcrumbs breadcrumbs={ breadcrumbs }/>
<Common.Contacts/>
<Common.Footer/>
</div>
);
}
}
export default BooksListPage;
|
src/routes.js | safe-steps/Frontend | import React from 'react';
import {IndexRoute, Route} from 'react-router';
import Layout from './components/layout/Layout.jsx';
import Home from './components/home/Home.jsx';
import ScenarioList from './components/scenarios/ScenarioList.jsx';
import ScenarioPage from './components/scenarios/ScenarioPage.jsx';
import ScenarioEditorPage from './components/scenarios/ScenarioEditorPage.jsx';
import SafetyPlan from './components/safetyPlan/SafetyPlan.jsx';
import Training from './components/Training/Training.jsx';
export default () => {
return (
<Route path="/" component={Layout}>
{ /* Home (main) route */ }
<IndexRoute component={Home}/>
{ /* Routes */ }
<Route path="/home" component={Home}/>
<Route path="/scenariolist" component={ScenarioList}/>
<Route path="/scenarios/:id" component={ScenarioPage}/>
<Route path="/scenarioeditor" component={ScenarioEditorPage}/>
<Route path="/safetyplan" component={SafetyPlan}/>
<Route path="/training" component={Training}/>
{ /* Catch all route */ }
{ /* <Route path="*" component={NotFound} status={404} /> */ }
</Route>
);
};
|
src/Parser/Druid/Restoration/Modules/Features/Checklist.js | hasseboulen/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import Wrapper from 'common/Wrapper';
import SpellLink from 'common/SpellLink';
import { formatPercentage } from 'common/format';
import CoreChecklist, { Rule, Requirement } from 'Parser/Core/Modules/Features/Checklist';
import { PreparationRule } from 'Parser/Core/Modules/Features/Checklist/Rules';
import { GenericCastEfficiencyRequirement } from 'Parser/Core/Modules/Features/Checklist/Requirements';
import CastEfficiency from 'Parser/Core/Modules/CastEfficiency';
import Combatants from 'Parser/Core/Modules/Combatants';
import LegendaryUpgradeChecker from 'Parser/Core/Modules/Items/LegendaryUpgradeChecker';
import LegendaryCountChecker from 'Parser/Core/Modules/Items/LegendaryCountChecker';
import PrePotion from 'Parser/Core/Modules/Items/PrePotion';
import EnchantChecker from 'Parser/Core/Modules/Items/EnchantChecker';
import ManaValues from 'Parser/Core/Modules/ManaValues';
import AlwaysBeCasting from './AlwaysBeCasting';
import Clearcasting from './Clearcasting';
import Efflorescence from './Efflorescence';
import Innervate from './Innervate';
import Lifebloom from './Lifebloom';
import NaturesEssence from './NaturesEssence';
import WildGrowth from './WildGrowth';
import Cultivation from '../Talents/Cultivation';
import SpringBlossoms from '../Talents/SpringBlossoms';
import TreeOfLife from '../Talents/TreeOfLife';
class Checklist extends CoreChecklist {
static dependencies = {
castEfficiency: CastEfficiency,
combatants: Combatants,
alwaysBeCasting: AlwaysBeCasting,
clearcasting: Clearcasting,
efflorescence: Efflorescence,
innervate: Innervate,
lifebloom: Lifebloom,
manaValues: ManaValues,
naturesEssence: NaturesEssence,
wildGrowth: WildGrowth,
cultivation: Cultivation,
springBlossoms: SpringBlossoms,
treeOfLife: TreeOfLife,
legendaryUpgradeChecker: LegendaryUpgradeChecker,
legendaryCountChecker: LegendaryCountChecker,
prePotion: PrePotion,
enchantChecker: EnchantChecker,
};
rules = [
new Rule({
name: 'Stay active throughout the fight',
description: <Wrapper>While constantly casting heals will quickly run you out of mana, you should still try to always be doing something throughout the fight. You can reduce your downtime while saving mana by spamming <SpellLink id={SPELLS.SOLAR_WRATH.id} /> on the boss when there is nothing serious to heal. If you safely healed through the entire fight and still had high non-healing time, your raid team is probably bringing too many healers.</Wrapper>,
requirements: () => {
return [
new Requirement({
name: 'Non healing time',
check: () => this.alwaysBeCasting.nonHealingTimeSuggestionThresholds,
}),
new Requirement({
name: 'Downtime',
check: () => this.alwaysBeCasting.downtimeSuggestionThresholds,
}),
];
},
}),
new Rule({
name: <Wrapper>Use <SpellLink id={SPELLS.WILD_GROWTH.id} icon /> effectively</Wrapper>,
description: <Wrapper>Effective use of <SpellLink id={SPELLS.WILD_GROWTH.id} /> is incredibly important to your healing performance. It provides not only the directly applied HoT, but also procs <SpellLink id={SPELLS.NATURES_ESSENCE_DRUID.id} /> and <SpellLink id={SPELLS.DREAMWALKER.id} />. When more than 3 raiders are wounded, it is probably the most efficienct and effective spell you can cast. Try to time your <SpellLink id={SPELLS.WILD_GROWTH.id} /> cast to land just after a boss ability in order to keep raiders healthy even through heavy AoE.</Wrapper>,
requirements: () => {
return [
new Requirement({
name: <Wrapper><SpellLink id={SPELLS.WILD_GROWTH.id} icon /> / <SpellLink id={SPELLS.REJUVENATION.id} icon /> ratio</Wrapper>,
check: () => this.wildGrowth.suggestionThresholds,
tooltip: `This is your ratio of Wild Growth casts to Rejuvenation casts. If this number is too low, it probably indicates you were missing good opportunities to cast Wild Growth.`,
}),
new Requirement({
name: <Wrapper>Low target <SpellLink id={SPELLS.WILD_GROWTH.id} icon /> casts</Wrapper>,
check: () => this.naturesEssence.suggestionThresholds,
tooltip: `This is your percent of Wild Growth casts that hit too few wounded targets. Low target casts happen either by casting it when almost all the raid was full health, or casting it on an isolated target. Remember that Wild Growth can only apply to players within 30 yds of the primary target, so if you use it on a target far away from the rest of the raid your cast will not be effective.`,
}),
];
},
}),
new Rule({
name: 'Use your healing cooldowns',
description: <Wrapper>Your cooldowns can be a big contributor to healing throughput when used frequently throughout the fight. When used early and often they can contribute a lot of healing for very little mana. Try to plan your major cooldowns (<SpellLink id={SPELLS.TRANQUILITY_CAST.id} /> and <SpellLink id={SPELLS.ESSENCE_OF_GHANIR.id} />) around big damage boss abilities, like the Transition Phase on Imonar or Fusillade on Antoran High Command. The below percentages represent the percentage of time you kept each spell on cooldown.</Wrapper>,
requirements: () => {
const combatant = this.combatants.selected;
return [
new GenericCastEfficiencyRequirement({
spell: SPELLS.CENARION_WARD_TALENT,
when: combatant.hasTalent(SPELLS.CENARION_WARD_TALENT.id),
}),
new GenericCastEfficiencyRequirement({
spell: SPELLS.FLOURISH_TALENT,
when: combatant.hasTalent(SPELLS.FLOURISH_TALENT.id),
}),
new GenericCastEfficiencyRequirement({
spell: SPELLS.VELENS_FUTURE_SIGHT_BUFF,
when: combatant.hasTrinket(ITEMS.VELENS_FUTURE_SIGHT.id),
}),
new GenericCastEfficiencyRequirement({
spell: SPELLS.ESSENCE_OF_GHANIR,
}),
new GenericCastEfficiencyRequirement({
spell: SPELLS.INCARNATION_TREE_OF_LIFE_TALENT,
when: combatant.hasTalent(SPELLS.INCARNATION_TREE_OF_LIFE_TALENT.id),
}),
new GenericCastEfficiencyRequirement({
spell: SPELLS.TRANQUILITY_CAST,
}),
new GenericCastEfficiencyRequirement({
spell: SPELLS.INNERVATE,
}),
];
},
}),
new Rule({
name: <Wrapper>Keep <SpellLink id={SPELLS.LIFEBLOOM_HOT_HEAL.id} icon /> and <SpellLink id={SPELLS.EFFLORESCENCE_CAST.id} icon /> active</Wrapper>,
description: <Wrapper>Maintaining uptime on these two important spells will improve your mana efficiency and overall throughput. It is good to keep <SpellLink id={SPELLS.LIFEBLOOM_HOT_HEAL.id} /> constantly active on a tank. While its throughput is comparable to a <SpellLink id={SPELLS.REJUVENATION.id} />, it also provides a constant chance to proc <SpellLink id={SPELLS.CLEARCASTING_BUFF.id} />. <SpellLink id={SPELLS.EFFLORESCENCE_CAST.id} /> is very mana efficient when it can tick over its full duration. Place it where raiders are liable to be and refresh it as soon as it expires.</Wrapper>,
requirements: () => {
const combatant = this.combatants.selected;
return [
new Requirement({
name: <Wrapper><SpellLink id={SPELLS.LIFEBLOOM_HOT_HEAL.id} icon /> uptime</Wrapper>,
check: () => this.lifebloom.suggestionThresholds,
when: !combatant.hasWaist(ITEMS.THE_DARK_TITANS_ADVICE.id),
}),
new Requirement({
name: <Wrapper><SpellLink id={SPELLS.LIFEBLOOM_HOT_HEAL.id} icon /> uptime</Wrapper>,
tooltip: `This requirement is more stringent because you have The Dark Titans Advice equipped`,
check: () => this.lifebloom.suggestionThresholds,
when: combatant.hasWaist(ITEMS.THE_DARK_TITANS_ADVICE.id),
}),
new Requirement({
name: <Wrapper><SpellLink id={SPELLS.EFFLORESCENCE_CAST.id} icon /> uptime</Wrapper>,
check: () => this.efflorescence.suggestionThresholds,
}),
];
},
}),
new Rule({
name: 'Manage your mana',
description: <Wrapper>Casting on targets who don't need healing or recklessly using inefficienct heals can result in running out of mana well before an encounter ends. Adapt your spell use to the situation, and as a rule of thumb try and keep your current mana percentage just above the bosses health percentage.</Wrapper>,
requirements: () => {
return [
new Requirement({
name: <Wrapper>Mana saved during <SpellLink id={SPELLS.INNERVATE.id} icon /></Wrapper>,
check: () => this.innervate.averageManaSavedSuggestionThresholds,
tooltip: `All spells cost no mana during Innervate, so take care to chain cast for its duration. Typically this means casting a Wild Growth, refreshing Efflorescence, and spamming Rejuvenation. It's also fine to Regrowth a target that is in immediate danger of dying.`,
}),
new Requirement({
name: <Wrapper>Use your <SpellLink id={SPELLS.CLEARCASTING_BUFF.id} icon /> procs</Wrapper>,
check: () => this.clearcasting.clearcastingUtilSuggestionThresholds,
tooltip: `This is the percentage of Clearcasting procs that you used. Regrowth is normally very expensive, but it's completely free with a Clearcasting proc. Use your procs in a timely fashion for a lot of free healing.`,
}),
new Requirement({
name: <Wrapper>Don't overuse <SpellLink id={SPELLS.REGROWTH.id} icon /></Wrapper>,
check: () => this.clearcasting.nonCCRegrowthsSuggestionThresholds,
tooltip: `This is the number of no-clearcasting Regrowths you cast per minute. Regrowth is very mana inefficient, and should only be used in emergency situations (and when you've already expended Swiftmend). Usually, you should rely on other healers in your raid to triage.`,
}),
new Requirement({
name: 'Mana remaining at fight end',
check: () => this.manaValues.suggestionThresholds,
tooltip: `Try to spend your mana at roughly the same rate the boss is dying. Having too much mana left at fight end could mean you were too conservative with your spell casts. If your mana is in good shape but there isn't much to heal, consider mixing Moonfire and Sunfire into your DPS rotation, which will burn some mana for extra DPS contribution.`,
}),
];
},
}),
new Rule({
name: 'Use your defensive / emergency spells',
description: <Wrapper>Restoration Druids unfortunately do not have many tools to deal with burst damage, but you should take care to use the ones you have. Swiftmend is a fairly inefficient spell, and should only be used in an emergency. The below percentages represent the percentage of time you kept each spell on cooldown.</Wrapper>,
requirements: () => {
return [
new GenericCastEfficiencyRequirement({
spell: SPELLS.SWIFTMEND,
}),
new GenericCastEfficiencyRequirement({
spell: SPELLS.IRONBARK,
}),
new GenericCastEfficiencyRequirement({
spell: SPELLS.BARKSKIN,
}),
];
},
}),
new Rule({
name: 'Pick the right tools for the fight',
description: <Wrapper>Different talent choices can be more or less effective depending on the fight. Listed below you will see how much throughput some talents were providing.</Wrapper>,
requirements: () => {
return [
new Requirement({
name: <Wrapper><SpellLink id={SPELLS.CULTIVATION.id} icon /> throughput</Wrapper>,
check: () => this.cultivation.suggestionThresholds,
tooltip: `This is the percent of your total healing that Cultivation contributed. Below around ${formatPercentage(this.cultivation.suggestionThresholds.isLessThan.average, 0)}%, you either had too many healers in this fight, or the fight is better for Tree of Life`,
when: this.cultivation.active,
}),
new Requirement({
name: <Wrapper><SpellLink id={SPELLS.SPRING_BLOSSOMS.id} icon /> throughput</Wrapper>,
check: () => this.springBlossoms.suggestionThresholds,
tooltip: `This is the percent of your total healing that Spring Blossoms contributed. Below around ${formatPercentage(this.springBlossoms.suggestionThresholds.isLessThan.average, 0)}%, you either weren't doing a good job with Efflorescence placement or you would have been better off picking Germination`,
when: this.springBlossoms.active,
}),
new Requirement({
name: <Wrapper><SpellLink id={SPELLS.INCARNATION_TREE_OF_LIFE_TALENT.id} icon /> throughput</Wrapper>,
check: () => this.treeOfLife.suggestionThresholds,
tooltip: `This is the percent of your total healing that Tree of Life contributed. Below around ${formatPercentage(this.treeOfLife.suggestionThresholds.isLessThan.average, 0)}%, you either didn't pick good times to use ToL or you would have been better off picking Cultivation`,
when: this.treeOfLife.hasTol,
}),
];
},
}),
new PreparationRule(),
];
}
export default Checklist;
|
packages/react-server-examples/redux-basic/pages/counter-app/index.js | emecell/react-server | import React from 'react'
import { RootElement } from 'react-server'
import { RootProvider } from 'react-server-redux'
import Counter from '../../components/Counter'
import store from '../store'
export default class CounterPage {
getElements() {
return [
<RootProvider store={store}>
<RootElement key={0}>
<Counter
value={store.getState()}
onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
/>
</RootElement>
<RootElement key={1}>
<Counter
value={store.getState()}
onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
/>
</RootElement>
</RootProvider>,
]
}
getMetaTags() {
return [
{charset: 'utf8'},
{'http-equiv': 'x-ua-compatible', 'content': 'ie=edge'},
{name: 'viewport', content: 'width=device-width, initial-scale=1'},
{name: 'description', content: 'Redux Counter app, powered by React Server'},
{name: 'generator', content: 'React Server'},
]
}
}
|
src/Parser/Core/Modules/Items/Legion/AmalgamsSeventhSpine.js | hasseboulen/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import ItemManaGained from 'Main/ItemManaGained';
/**
* Amalgam's Seventh Spine -
* Equip: Your direct healing spells apply and refresh Fragile Echo for 6 sec. When Fragile Echo expires, it restores 3840 mana to you.
*/
class AmalgamsSeventhSpine extends Analyzer {
static dependencies = {
combatants: Combatants,
};
manaGained = 0;
procs = 0;
applications = 0;
refreshes = 0;
on_initialized() {
this.active = this.combatants.selected.hasTrinket(ITEMS.AMALGAMS_SEVENTH_SPINE.id);
}
on_toPlayer_energize(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.FRAGILE_ECHO_ENERGIZE.id) {
return;
}
this.manaGained += event.resourceChange;
this.procs += 1;
}
on_byPlayer_applybuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.FRAGILE_ECHO_BUFF.id) {
return;
}
this.applications += 1;
}
on_byPlayer_refreshbuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.FRAGILE_ECHO_BUFF.id) {
return;
}
this.refreshes += 1;
}
item() {
return {
item: ITEMS.AMALGAMS_SEVENTH_SPINE,
result: (
<dfn data-tip={`The buff expired and restored mana ${this.procs} times and was refreshed ${this.refreshes} times. (refreshing delays the buff expiration and is an inefficient use of this trinket).`}>
<ItemManaGained amount={this.manaGained} />
</dfn>
),
};
}
// TODO: Suggest upon refreshing often to not do that
}
export default AmalgamsSeventhSpine;
|
src/components/CreateButton/index.js | cantonjs/re-admin | import React, { Component } from 'react';
import PropTypes from 'utils/PropTypes';
import { isFunction } from 'utils/fp';
import localize from 'hocs/localize';
import ContextButton from 'components/ContextButton';
@localize('CreateButton')
export default class CreateButton extends Component {
static propTypes = {
localeStore: PropTypes.object.isRequired,
table: PropTypes.string,
label: PropTypes.stringOrFunc,
title: PropTypes.stringOrFunc,
save: PropTypes.stringOrFunc,
};
_handleClick = (ev, actions) => {
ev.preventDefault();
const { props } = this;
const { create, getData } = actions;
const { title, label, table, save, localeStore } = props;
if (save || title || table) {
const getTitle = title || localeStore.localizeProp(label, 'label');
const params = {
title: isFunction(getTitle) ? getTitle(getData()) : getTitle,
save,
};
if (table) params.table = table;
create(params);
} else create();
};
render() {
const { title, table, save, localeStore, ...other } = this.props;
return (
<ContextButton
onClick={this._handleClick}
{...localeStore.localize(other)}
/>
);
}
}
|
react-flux-mui/js/material-ui/src/svg-icons/device/storage.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceStorage = (props) => (
<SvgIcon {...props}>
<path d="M2 20h20v-4H2v4zm2-3h2v2H4v-2zM2 4v4h20V4H2zm4 3H4V5h2v2zm-4 7h20v-4H2v4zm2-3h2v2H4v-2z"/>
</SvgIcon>
);
DeviceStorage = pure(DeviceStorage);
DeviceStorage.displayName = 'DeviceStorage';
DeviceStorage.muiName = 'SvgIcon';
export default DeviceStorage;
|
docs/src/components/Components/Buttons.js | abouthiroppy/scuba | import React from 'react';
import { Button } from '../../../../src';
import generateCodeTemplate from './generateCodeTemplate';
import generateTableTemplate from './generateTableTemplate';
import styles from './style';
const sampleCode = `import {Button} from 'scuba';
<div>
<Button>BUTTON</Button>
<Button backgroundColor="none">BUTTON</Button>
<Button disabled>DISABLED</Button>
<Button clear>CLEAR</Button>
</div>
`;
const Buttons = () => (
<div>
<h2 id="buttons">Buttons</h2>
<div className={styles.buttons}>
<Button>BUTTON</Button>
<Button backgroundColor="none">BUTTON</Button>
<Button disabled>DISABLED</Button>
<Button clear>CLEAR</Button>
</div>
{generateCodeTemplate(sampleCode)}
<h3>Properties</h3>
<h4>Button</h4>
{generateTableTemplate([
{
name : 'className',
type : 'string',
default: ''
},
{
name : 'style',
type : 'Object',
default: ''
},
{
name : 'children',
type : 'React.Element<*>',
default: ''
},
{
name : 'width',
type : 'number | string',
default: 'auto'
},
{
name : 'backgroundColor',
type : 'none | string',
default: 'a theme\'s color'
},
{
name : 'disabled',
type : 'boolean',
default: 'false'
},
{
name : 'clear',
type : 'boolean',
default: 'false'
},
{
name : 'onClick',
type : 'Function',
default: ''
}
])}
</div>
);
export default Buttons;
|
Skins/VetoccitanT3/ReactSrc/node_modules/react-router/esm/react-router.js | ENG-SYSTEMS/Kob-Eye | import _inheritsLoose from '@babel/runtime/helpers/esm/inheritsLoose';
import React from 'react';
import PropTypes from 'prop-types';
import { createMemoryHistory, createLocation, locationsAreEqual, createPath } from 'history';
import warning from 'tiny-warning';
import createContext from 'mini-create-react-context';
import invariant from 'tiny-invariant';
import _extends from '@babel/runtime/helpers/esm/extends';
import pathToRegexp from 'path-to-regexp';
import { isValidElementType } from 'react-is';
import _objectWithoutPropertiesLoose from '@babel/runtime/helpers/esm/objectWithoutPropertiesLoose';
import hoistStatics from 'hoist-non-react-statics';
// TODO: Replace with React.createContext once we can assume React 16+
var createNamedContext = function createNamedContext(name) {
var context = createContext();
context.displayName = name;
return context;
};
var historyContext =
/*#__PURE__*/
createNamedContext("Router-History");
// TODO: Replace with React.createContext once we can assume React 16+
var createNamedContext$1 = function createNamedContext(name) {
var context = createContext();
context.displayName = name;
return context;
};
var context =
/*#__PURE__*/
createNamedContext$1("Router");
/**
* The public API for putting history on context.
*/
var Router =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Router, _React$Component);
Router.computeRootMatch = function computeRootMatch(pathname) {
return {
path: "/",
url: "/",
params: {},
isExact: pathname === "/"
};
};
function Router(props) {
var _this;
_this = _React$Component.call(this, props) || this;
_this.state = {
location: props.history.location
}; // This is a bit of a hack. We have to start listening for location
// changes here in the constructor in case there are any <Redirect>s
// on the initial render. If there are, they will replace/push when
// they mount and since cDM fires in children before parents, we may
// get a new location before the <Router> is mounted.
_this._isMounted = false;
_this._pendingLocation = null;
if (!props.staticContext) {
_this.unlisten = props.history.listen(function (location) {
if (_this._isMounted) {
_this.setState({
location: location
});
} else {
_this._pendingLocation = location;
}
});
}
return _this;
}
var _proto = Router.prototype;
_proto.componentDidMount = function componentDidMount() {
this._isMounted = true;
if (this._pendingLocation) {
this.setState({
location: this._pendingLocation
});
}
};
_proto.componentWillUnmount = function componentWillUnmount() {
if (this.unlisten) this.unlisten();
};
_proto.render = function render() {
return React.createElement(context.Provider, {
value: {
history: this.props.history,
location: this.state.location,
match: Router.computeRootMatch(this.state.location.pathname),
staticContext: this.props.staticContext
}
}, React.createElement(historyContext.Provider, {
children: this.props.children || null,
value: this.props.history
}));
};
return Router;
}(React.Component);
if (process.env.NODE_ENV !== "production") {
Router.propTypes = {
children: PropTypes.node,
history: PropTypes.object.isRequired,
staticContext: PropTypes.object
};
Router.prototype.componentDidUpdate = function (prevProps) {
process.env.NODE_ENV !== "production" ? warning(prevProps.history === this.props.history, "You cannot change <Router history>") : void 0;
};
}
/**
* The public API for a <Router> that stores location in memory.
*/
var MemoryRouter =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(MemoryRouter, _React$Component);
function MemoryRouter() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.history = createMemoryHistory(_this.props);
return _this;
}
var _proto = MemoryRouter.prototype;
_proto.render = function render() {
return React.createElement(Router, {
history: this.history,
children: this.props.children
});
};
return MemoryRouter;
}(React.Component);
if (process.env.NODE_ENV !== "production") {
MemoryRouter.propTypes = {
initialEntries: PropTypes.array,
initialIndex: PropTypes.number,
getUserConfirmation: PropTypes.func,
keyLength: PropTypes.number,
children: PropTypes.node
};
MemoryRouter.prototype.componentDidMount = function () {
process.env.NODE_ENV !== "production" ? warning(!this.props.history, "<MemoryRouter> ignores the history prop. To use a custom history, " + "use `import { Router }` instead of `import { MemoryRouter as Router }`.") : void 0;
};
}
var Lifecycle =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Lifecycle, _React$Component);
function Lifecycle() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Lifecycle.prototype;
_proto.componentDidMount = function componentDidMount() {
if (this.props.onMount) this.props.onMount.call(this, this);
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
if (this.props.onUpdate) this.props.onUpdate.call(this, this, prevProps);
};
_proto.componentWillUnmount = function componentWillUnmount() {
if (this.props.onUnmount) this.props.onUnmount.call(this, this);
};
_proto.render = function render() {
return null;
};
return Lifecycle;
}(React.Component);
/**
* The public API for prompting the user before navigating away from a screen.
*/
function Prompt(_ref) {
var message = _ref.message,
_ref$when = _ref.when,
when = _ref$when === void 0 ? true : _ref$when;
return React.createElement(context.Consumer, null, function (context) {
!context ? process.env.NODE_ENV !== "production" ? invariant(false, "You should not use <Prompt> outside a <Router>") : invariant(false) : void 0;
if (!when || context.staticContext) return null;
var method = context.history.block;
return React.createElement(Lifecycle, {
onMount: function onMount(self) {
self.release = method(message);
},
onUpdate: function onUpdate(self, prevProps) {
if (prevProps.message !== message) {
self.release();
self.release = method(message);
}
},
onUnmount: function onUnmount(self) {
self.release();
},
message: message
});
});
}
if (process.env.NODE_ENV !== "production") {
var messageType = PropTypes.oneOfType([PropTypes.func, PropTypes.string]);
Prompt.propTypes = {
when: PropTypes.bool,
message: messageType.isRequired
};
}
var cache = {};
var cacheLimit = 10000;
var cacheCount = 0;
function compilePath(path) {
if (cache[path]) return cache[path];
var generator = pathToRegexp.compile(path);
if (cacheCount < cacheLimit) {
cache[path] = generator;
cacheCount++;
}
return generator;
}
/**
* Public API for generating a URL pathname from a path and parameters.
*/
function generatePath(path, params) {
if (path === void 0) {
path = "/";
}
if (params === void 0) {
params = {};
}
return path === "/" ? path : compilePath(path)(params, {
pretty: true
});
}
/**
* The public API for navigating programmatically with a component.
*/
function Redirect(_ref) {
var computedMatch = _ref.computedMatch,
to = _ref.to,
_ref$push = _ref.push,
push = _ref$push === void 0 ? false : _ref$push;
return React.createElement(context.Consumer, null, function (context) {
!context ? process.env.NODE_ENV !== "production" ? invariant(false, "You should not use <Redirect> outside a <Router>") : invariant(false) : void 0;
var history = context.history,
staticContext = context.staticContext;
var method = push ? history.push : history.replace;
var location = createLocation(computedMatch ? typeof to === "string" ? generatePath(to, computedMatch.params) : _extends({}, to, {
pathname: generatePath(to.pathname, computedMatch.params)
}) : to); // When rendering in a static context,
// set the new location immediately.
if (staticContext) {
method(location);
return null;
}
return React.createElement(Lifecycle, {
onMount: function onMount() {
method(location);
},
onUpdate: function onUpdate(self, prevProps) {
var prevLocation = createLocation(prevProps.to);
if (!locationsAreEqual(prevLocation, _extends({}, location, {
key: prevLocation.key
}))) {
method(location);
}
},
to: to
});
});
}
if (process.env.NODE_ENV !== "production") {
Redirect.propTypes = {
push: PropTypes.bool,
from: PropTypes.string,
to: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired
};
}
var cache$1 = {};
var cacheLimit$1 = 10000;
var cacheCount$1 = 0;
function compilePath$1(path, options) {
var cacheKey = "" + options.end + options.strict + options.sensitive;
var pathCache = cache$1[cacheKey] || (cache$1[cacheKey] = {});
if (pathCache[path]) return pathCache[path];
var keys = [];
var regexp = pathToRegexp(path, keys, options);
var result = {
regexp: regexp,
keys: keys
};
if (cacheCount$1 < cacheLimit$1) {
pathCache[path] = result;
cacheCount$1++;
}
return result;
}
/**
* Public API for matching a URL pathname to a path.
*/
function matchPath(pathname, options) {
if (options === void 0) {
options = {};
}
if (typeof options === "string" || Array.isArray(options)) {
options = {
path: options
};
}
var _options = options,
path = _options.path,
_options$exact = _options.exact,
exact = _options$exact === void 0 ? false : _options$exact,
_options$strict = _options.strict,
strict = _options$strict === void 0 ? false : _options$strict,
_options$sensitive = _options.sensitive,
sensitive = _options$sensitive === void 0 ? false : _options$sensitive;
var paths = [].concat(path);
return paths.reduce(function (matched, path) {
if (!path && path !== "") return null;
if (matched) return matched;
var _compilePath = compilePath$1(path, {
end: exact,
strict: strict,
sensitive: sensitive
}),
regexp = _compilePath.regexp,
keys = _compilePath.keys;
var match = regexp.exec(pathname);
if (!match) return null;
var url = match[0],
values = match.slice(1);
var isExact = pathname === url;
if (exact && !isExact) return null;
return {
path: path,
// the path used to match
url: path === "/" && url === "" ? "/" : url,
// the matched portion of the URL
isExact: isExact,
// whether or not we matched exactly
params: keys.reduce(function (memo, key, index) {
memo[key.name] = values[index];
return memo;
}, {})
};
}, null);
}
function isEmptyChildren(children) {
return React.Children.count(children) === 0;
}
function evalChildrenDev(children, props, path) {
var value = children(props);
process.env.NODE_ENV !== "production" ? warning(value !== undefined, "You returned `undefined` from the `children` function of " + ("<Route" + (path ? " path=\"" + path + "\"" : "") + ">, but you ") + "should have returned a React element or `null`") : void 0;
return value || null;
}
/**
* The public API for matching a single path and rendering.
*/
var Route =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Route, _React$Component);
function Route() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Route.prototype;
_proto.render = function render() {
var _this = this;
return React.createElement(context.Consumer, null, function (context$1) {
!context$1 ? process.env.NODE_ENV !== "production" ? invariant(false, "You should not use <Route> outside a <Router>") : invariant(false) : void 0;
var location = _this.props.location || context$1.location;
var match = _this.props.computedMatch ? _this.props.computedMatch // <Switch> already computed the match for us
: _this.props.path ? matchPath(location.pathname, _this.props) : context$1.match;
var props = _extends({}, context$1, {
location: location,
match: match
});
var _this$props = _this.props,
children = _this$props.children,
component = _this$props.component,
render = _this$props.render; // Preact uses an empty array as children by
// default, so use null if that's the case.
if (Array.isArray(children) && children.length === 0) {
children = null;
}
return React.createElement(context.Provider, {
value: props
}, props.match ? children ? typeof children === "function" ? process.env.NODE_ENV !== "production" ? evalChildrenDev(children, props, _this.props.path) : children(props) : children : component ? React.createElement(component, props) : render ? render(props) : null : typeof children === "function" ? process.env.NODE_ENV !== "production" ? evalChildrenDev(children, props, _this.props.path) : children(props) : null);
});
};
return Route;
}(React.Component);
if (process.env.NODE_ENV !== "production") {
Route.propTypes = {
children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
component: function component(props, propName) {
if (props[propName] && !isValidElementType(props[propName])) {
return new Error("Invalid prop 'component' supplied to 'Route': the prop is not a valid React component");
}
},
exact: PropTypes.bool,
location: PropTypes.object,
path: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
render: PropTypes.func,
sensitive: PropTypes.bool,
strict: PropTypes.bool
};
Route.prototype.componentDidMount = function () {
process.env.NODE_ENV !== "production" ? warning(!(this.props.children && !isEmptyChildren(this.props.children) && this.props.component), "You should not use <Route component> and <Route children> in the same route; <Route component> will be ignored") : void 0;
process.env.NODE_ENV !== "production" ? warning(!(this.props.children && !isEmptyChildren(this.props.children) && this.props.render), "You should not use <Route render> and <Route children> in the same route; <Route render> will be ignored") : void 0;
process.env.NODE_ENV !== "production" ? warning(!(this.props.component && this.props.render), "You should not use <Route component> and <Route render> in the same route; <Route render> will be ignored") : void 0;
};
Route.prototype.componentDidUpdate = function (prevProps) {
process.env.NODE_ENV !== "production" ? warning(!(this.props.location && !prevProps.location), '<Route> elements should not change from uncontrolled to controlled (or vice versa). You initially used no "location" prop and then provided one on a subsequent render.') : void 0;
process.env.NODE_ENV !== "production" ? warning(!(!this.props.location && prevProps.location), '<Route> elements should not change from controlled to uncontrolled (or vice versa). You provided a "location" prop initially but omitted it on a subsequent render.') : void 0;
};
}
function addLeadingSlash(path) {
return path.charAt(0) === "/" ? path : "/" + path;
}
function addBasename(basename, location) {
if (!basename) return location;
return _extends({}, location, {
pathname: addLeadingSlash(basename) + location.pathname
});
}
function stripBasename(basename, location) {
if (!basename) return location;
var base = addLeadingSlash(basename);
if (location.pathname.indexOf(base) !== 0) return location;
return _extends({}, location, {
pathname: location.pathname.substr(base.length)
});
}
function createURL(location) {
return typeof location === "string" ? location : createPath(location);
}
function staticHandler(methodName) {
return function () {
process.env.NODE_ENV !== "production" ? invariant(false, "You cannot %s with <StaticRouter>", methodName) : invariant(false) ;
};
}
function noop() {}
/**
* The public top-level API for a "static" <Router>, so-called because it
* can't actually change the current location. Instead, it just records
* location changes in a context object. Useful mainly in testing and
* server-rendering scenarios.
*/
var StaticRouter =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(StaticRouter, _React$Component);
function StaticRouter() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.handlePush = function (location) {
return _this.navigateTo(location, "PUSH");
};
_this.handleReplace = function (location) {
return _this.navigateTo(location, "REPLACE");
};
_this.handleListen = function () {
return noop;
};
_this.handleBlock = function () {
return noop;
};
return _this;
}
var _proto = StaticRouter.prototype;
_proto.navigateTo = function navigateTo(location, action) {
var _this$props = this.props,
_this$props$basename = _this$props.basename,
basename = _this$props$basename === void 0 ? "" : _this$props$basename,
_this$props$context = _this$props.context,
context = _this$props$context === void 0 ? {} : _this$props$context;
context.action = action;
context.location = addBasename(basename, createLocation(location));
context.url = createURL(context.location);
};
_proto.render = function render() {
var _this$props2 = this.props,
_this$props2$basename = _this$props2.basename,
basename = _this$props2$basename === void 0 ? "" : _this$props2$basename,
_this$props2$context = _this$props2.context,
context = _this$props2$context === void 0 ? {} : _this$props2$context,
_this$props2$location = _this$props2.location,
location = _this$props2$location === void 0 ? "/" : _this$props2$location,
rest = _objectWithoutPropertiesLoose(_this$props2, ["basename", "context", "location"]);
var history = {
createHref: function createHref(path) {
return addLeadingSlash(basename + createURL(path));
},
action: "POP",
location: stripBasename(basename, createLocation(location)),
push: this.handlePush,
replace: this.handleReplace,
go: staticHandler("go"),
goBack: staticHandler("goBack"),
goForward: staticHandler("goForward"),
listen: this.handleListen,
block: this.handleBlock
};
return React.createElement(Router, _extends({}, rest, {
history: history,
staticContext: context
}));
};
return StaticRouter;
}(React.Component);
if (process.env.NODE_ENV !== "production") {
StaticRouter.propTypes = {
basename: PropTypes.string,
context: PropTypes.object,
location: PropTypes.oneOfType([PropTypes.string, PropTypes.object])
};
StaticRouter.prototype.componentDidMount = function () {
process.env.NODE_ENV !== "production" ? warning(!this.props.history, "<StaticRouter> ignores the history prop. To use a custom history, " + "use `import { Router }` instead of `import { StaticRouter as Router }`.") : void 0;
};
}
/**
* The public API for rendering the first <Route> that matches.
*/
var Switch =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Switch, _React$Component);
function Switch() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Switch.prototype;
_proto.render = function render() {
var _this = this;
return React.createElement(context.Consumer, null, function (context) {
!context ? process.env.NODE_ENV !== "production" ? invariant(false, "You should not use <Switch> outside a <Router>") : invariant(false) : void 0;
var location = _this.props.location || context.location;
var element, match; // We use React.Children.forEach instead of React.Children.toArray().find()
// here because toArray adds keys to all child elements and we do not want
// to trigger an unmount/remount for two <Route>s that render the same
// component at different URLs.
React.Children.forEach(_this.props.children, function (child) {
if (match == null && React.isValidElement(child)) {
element = child;
var path = child.props.path || child.props.from;
match = path ? matchPath(location.pathname, _extends({}, child.props, {
path: path
})) : context.match;
}
});
return match ? React.cloneElement(element, {
location: location,
computedMatch: match
}) : null;
});
};
return Switch;
}(React.Component);
if (process.env.NODE_ENV !== "production") {
Switch.propTypes = {
children: PropTypes.node,
location: PropTypes.object
};
Switch.prototype.componentDidUpdate = function (prevProps) {
process.env.NODE_ENV !== "production" ? warning(!(this.props.location && !prevProps.location), '<Switch> elements should not change from uncontrolled to controlled (or vice versa). You initially used no "location" prop and then provided one on a subsequent render.') : void 0;
process.env.NODE_ENV !== "production" ? warning(!(!this.props.location && prevProps.location), '<Switch> elements should not change from controlled to uncontrolled (or vice versa). You provided a "location" prop initially but omitted it on a subsequent render.') : void 0;
};
}
/**
* A public higher-order component to access the imperative API
*/
function withRouter(Component) {
var displayName = "withRouter(" + (Component.displayName || Component.name) + ")";
var C = function C(props) {
var wrappedComponentRef = props.wrappedComponentRef,
remainingProps = _objectWithoutPropertiesLoose(props, ["wrappedComponentRef"]);
return React.createElement(context.Consumer, null, function (context) {
!context ? process.env.NODE_ENV !== "production" ? invariant(false, "You should not use <" + displayName + " /> outside a <Router>") : invariant(false) : void 0;
return React.createElement(Component, _extends({}, remainingProps, context, {
ref: wrappedComponentRef
}));
});
};
C.displayName = displayName;
C.WrappedComponent = Component;
if (process.env.NODE_ENV !== "production") {
C.propTypes = {
wrappedComponentRef: PropTypes.oneOfType([PropTypes.string, PropTypes.func, PropTypes.object])
};
}
return hoistStatics(C, Component);
}
var useContext = React.useContext;
function useHistory() {
if (process.env.NODE_ENV !== "production") {
!(typeof useContext === "function") ? process.env.NODE_ENV !== "production" ? invariant(false, "You must use React >= 16.8 in order to use useHistory()") : invariant(false) : void 0;
}
return useContext(historyContext);
}
function useLocation() {
if (process.env.NODE_ENV !== "production") {
!(typeof useContext === "function") ? process.env.NODE_ENV !== "production" ? invariant(false, "You must use React >= 16.8 in order to use useLocation()") : invariant(false) : void 0;
}
return useContext(context).location;
}
function useParams() {
if (process.env.NODE_ENV !== "production") {
!(typeof useContext === "function") ? process.env.NODE_ENV !== "production" ? invariant(false, "You must use React >= 16.8 in order to use useParams()") : invariant(false) : void 0;
}
var match = useContext(context).match;
return match ? match.params : {};
}
function useRouteMatch(path) {
if (process.env.NODE_ENV !== "production") {
!(typeof useContext === "function") ? process.env.NODE_ENV !== "production" ? invariant(false, "You must use React >= 16.8 in order to use useRouteMatch()") : invariant(false) : void 0;
}
var location = useLocation();
var match = useContext(context).match;
return path ? matchPath(location.pathname, path) : match;
}
if (process.env.NODE_ENV !== "production") {
if (typeof window !== "undefined") {
var global = window;
var key = "__react_router_build__";
var buildNames = {
cjs: "CommonJS",
esm: "ES modules",
umd: "UMD"
};
if (global[key] && global[key] !== "esm") {
var initialBuildName = buildNames[global[key]];
var secondaryBuildName = buildNames["esm"]; // TODO: Add link to article that explains in detail how to avoid
// loading 2 different builds.
throw new Error("You are loading the " + secondaryBuildName + " build of React Router " + ("on a page that is already running the " + initialBuildName + " ") + "build, so things won't work right.");
}
global[key] = "esm";
}
}
export { MemoryRouter, Prompt, Redirect, Route, Router, StaticRouter, Switch, historyContext as __HistoryContext, context as __RouterContext, generatePath, matchPath, useHistory, useLocation, useParams, useRouteMatch, withRouter };
//# sourceMappingURL=react-router.js.map
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.