path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
src/svg-icons/hardware/laptop-windows.js
|
skarnecki/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareLaptopWindows = (props) => (
<SvgIcon {...props}>
<path d="M20 18v-1c1.1 0 1.99-.9 1.99-2L22 5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2v1H0v2h24v-2h-4zM4 5h16v10H4V5z"/>
</SvgIcon>
);
HardwareLaptopWindows = pure(HardwareLaptopWindows);
HardwareLaptopWindows.displayName = 'HardwareLaptopWindows';
export default HardwareLaptopWindows;
|
actor-apps/app-web/src/app/components/sidebar/ContactsSectionItem.react.js
|
voidException/actor-platform
|
import React from 'react';
import ReactMixin from 'react-mixin';
import addons from 'react/addons';
import DialogActionCreators from 'actions/DialogActionCreators';
import AvatarItem from 'components/common/AvatarItem.react';
const {addons: { PureRenderMixin }} = addons;
@ReactMixin.decorate(PureRenderMixin)
class ContactsSectionItem extends React.Component {
static propTypes = {
contact: React.PropTypes.object
};
constructor(props) {
super(props);
}
openNewPrivateCoversation = () => {
DialogActionCreators.selectDialogPeerUser(this.props.contact.uid);
}
render() {
const contact = this.props.contact;
return (
<li className="sidebar__list__item row" onClick={this.openNewPrivateCoversation}>
<AvatarItem image={contact.avatar}
placeholder={contact.placeholder}
size="small"
title={contact.name}/>
<div className="col-xs">
<span className="title">
{contact.name}
</span>
</div>
</li>
);
}
}
export default ContactsSectionItem;
|
src/cms/preview-templates/page-preview.js
|
wall3/wall3.github.io
|
// @flow strict
import React from 'react';
import type { Entry, WidgetFor } from '../../types';
type Props = {
entry: Entry,
widgetFor: WidgetFor
};
const PagePreview = ({ entry, widgetFor }: Props) => {
const body = widgetFor('body');
const title = entry.getIn(['data', 'title']);
return (
<div className="page">
<h1 className="page__title">{title}</h1>
<div className="page__body">{ body }</div>
</div>
);
};
export default PagePreview;
|
core/src/plugins/gui.ajax/res/js/ui/Workspaces/search/components/FileSizePanel.js
|
huzergackl/pydio-core
|
/*
* Copyright 2007-2017 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
* This file is part of Pydio.
*
* Pydio 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.
*
* Pydio 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 Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
import React from 'react';
const {PydioContextConsumer} = require('pydio').requireLib('boot')
import {TextField} from 'material-ui';
class SearchFileSizePanel extends React.Component {
constructor(props) {
super(props)
this.state = {
from:false,
to: null
}
}
onChange() {
this.setState({
from: this.refs.from.getValue() || 0,
to: this.refs.to.getValue() || 1099511627776
})
}
componentWillUpdate(nextProps, nextState) {
if (nextState === this.state) return
const {from, to} = nextState
this.props.onChange({
ajxp_bytesize: (from && to) ? '['+from+' TO '+to+']' : null
})
}
render() {
const {inputStyle, getMessage, ...props} = this.props
return (
<div>
<TextField
ref="from"
style={inputStyle}
hintText={getMessage(504)}
floatingLabelFixed={true}
floatingLabelText={getMessage(613)}
onChange={this.onChange.bind(this)}
/>
<TextField
ref="to"
style={inputStyle}
hintText={getMessage(504)}
floatingLabelFixed={true}
floatingLabelText={getMessage(614)}
onChange={this.onChange.bind(this)}
/>
</div>
);
}
}
SearchFileSizePanel = PydioContextConsumer(SearchFileSizePanel)
export default SearchFileSizePanel
|
cm19/ReactJS/your-first-react-app-exercises-master/exercise-11/complete/App.js
|
Brandon-J-Campbell/codemash
|
import React, { Component } from 'react';
import Exercise from './Exercise';
import styles from './App.css';
import classNames from 'classnames';
class App extends Component {
render() {
return (
<div className={styles.app}>
<header className={styles.appHeader}>
<h1 className={styles.appTitle}>Exercise 11</h1>
<h2 className={classNames(styles.subTitle, styles.emphasize)}>CSS Modules</h2>
</header>
<div className={styles.exercise}>
<Exercise />
</div>
</div>
);
}
}
export default App;
|
examples/react-native/index.ios.js
|
natew/rxdb
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import {
AppRegistry,
} from 'react-native';
import React, { Component } from 'react';
import App from './src'
AppRegistry.registerComponent('reactNative', () => App);
|
app/components/ProgressBar.js
|
AngelGallegosE/Osiris
|
import React from 'react';
class ProgressBar extends React.Component {
render() {
return (
<div id="MainProgressBarContainer">
<progress id="progressBar" value={this.props.value} max="100" className={this.props.value===0?'hidden':''}></progress>
</div>
);
}
}
ProgressBar.propTypes = {
value: React.PropTypes.number
};
export default ProgressBar;
|
src/server.js
|
brecht/react-redux-universal-hot-example
|
import Express from 'express';
import React from 'react';
import Location from 'react-router/lib/Location';
import config from './config';
import favicon from 'serve-favicon';
import compression from 'compression';
import httpProxy from 'http-proxy';
import path from 'path';
import createStore from './redux/create';
import api from './api/api';
import ApiClient from './ApiClient';
import universalRouter from './universalRouter';
import Html from './Html';
import PrettyError from 'pretty-error';
const pretty = new PrettyError();
const app = new Express();
const proxy = httpProxy.createProxyServer({
target: 'http://localhost:' + config.apiPort
});
app.use(compression());
app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico')));
let webpackStats;
if (!__DEVELOPMENT__) {
webpackStats = require('../webpack-stats.json');
}
app.use(require('serve-static')(path.join(__dirname, '..', 'static')));
// Proxy to API server
app.use('/api', (req, res) => {
proxy.web(req, res);
});
app.use((req, res) => {
if (__DEVELOPMENT__) {
webpackStats = require('../webpack-stats.json');
// Do not cache webpack stats: the script file would change since
// hot module replacement is enabled in the development env
delete require.cache[require.resolve('../webpack-stats.json')];
}
const client = new ApiClient(req);
const store = createStore(client);
const location = new Location(req.path, req.query);
if (__DISABLE_SSR__) {
res.send('<!doctype html>\n' +
React.renderToString(<Html webpackStats={webpackStats} component={<div/>} store={store}/>));
} else {
universalRouter(location, undefined, store)
.then(({component, transition, isRedirect}) => {
if (isRedirect) {
res.redirect(transition.redirectInfo.pathname);
return;
}
res.send('<!doctype html>\n' +
React.renderToString(<Html webpackStats={webpackStats} component={component} store={store}/>));
})
.catch((error) => {
console.error('ROUTER ERROR:', pretty.render(error));
res.status(500).send({error: error.stack});
});
}
});
if (config.port) {
app.listen(config.port, (err) => {
if (err) {
console.error(err);
} else {
api().then(() => {
console.info('==> ✅ Server is listening');
console.info('==> 🌎 %s running on port %s, API on port %s', config.app.name, config.port, config.apiPort);
console.info('----------\n==> 💻 Open http://localhost:%s in a browser to view the app.', config.port);
});
}
});
} else {
console.error('==> ERROR: No PORT environment variable has been specified');
}
|
test/integration/image-component/default/pages/style-inheritance.js
|
azukaru/next.js
|
import React from 'react'
import Image from 'next/image'
import style from '../style.module.css'
const Page = () => {
return (
<div id="main-container" className={style.mainContainer}>
<h1>Image Style Inheritance</h1>
<Image
id="img-fixed"
layout="fixed"
src="/test.jpg"
width="400"
height="400"
/>
<Image
id="img-intrinsic"
layout="intrinsic"
src="/test.jpg"
width="400"
height="400"
/>
<div style={{ position: 'relative', width: '200px', height: '200px' }}>
<Image id="img-fill" layout="fill" src="/test.jpg" objectFit="cover" />
</div>
<Image
id="img-responsive"
layout="responsive"
src="/test.jpg"
width="400"
height="400"
/>
<footer>Footer</footer>
</div>
)
}
export default Page
|
frontend/src/components/dir-view-mode/dir-column-view.js
|
miurahr/seahub
|
import React from 'react';
import PropTypes from 'prop-types';
import DirColumnNav from './dir-column-nav';
import DirColumnFile from './dir-column-file';
import DirListView from './dir-list-view';
const propTypes = {
path: PropTypes.string.isRequired,
repoID: PropTypes.string.isRequired,
// repoinfo
currentRepoInfo: PropTypes.object.isRequired,
repoPermission: PropTypes.bool.isRequired,
enableDirPrivateShare: PropTypes.bool.isRequired,
userPerm: PropTypes.string,
isGroupOwnedRepo: PropTypes.bool.isRequired,
// tree
isTreeDataLoading: PropTypes.bool.isRequired,
treeData: PropTypes.object.isRequired,
currentNode: PropTypes.object,
onNodeClick: PropTypes.func.isRequired,
onNodeCollapse: PropTypes.func.isRequired,
onNodeExpanded: PropTypes.func.isRequired,
onRenameNode: PropTypes.func.isRequired,
onDeleteNode: PropTypes.func.isRequired,
onAddFileNode: PropTypes.func.isRequired,
onAddFolderNode: PropTypes.func.isRequired,
// file
isViewFile: PropTypes.bool.isRequired,
isFileLoading: PropTypes.bool.isRequired,
isFileLoadedErr: PropTypes.bool.isRequired,
hash: PropTypes.string,
isDraft: PropTypes.bool.isRequired,
hasDraft: PropTypes.bool.isRequired,
goDraftPage: PropTypes.func.isRequired,
filePermission: PropTypes.string,
content: PropTypes.string,
lastModified: PropTypes.string,
latestContributor: PropTypes.string,
onLinkClick: PropTypes.func.isRequired,
// repo content
isRepoInfoBarShow: PropTypes.bool.isRequired,
draftCounts: PropTypes.number.isRequired,
usedRepoTags: PropTypes.array.isRequired,
readmeMarkdown: PropTypes.object,
updateUsedRepoTags: PropTypes.func.isRequired,
// list
isDirentListLoading: PropTypes.bool.isRequired,
direntList: PropTypes.array.isRequired,
sortBy: PropTypes.string.isRequired,
sortOrder: PropTypes.string.isRequired,
sortItems: PropTypes.func.isRequired,
onAddFolder: PropTypes.func.isRequired,
onAddFile: PropTypes.func.isRequired,
updateDirent: PropTypes.func.isRequired,
onItemClick: PropTypes.func.isRequired,
onItemSelected: PropTypes.func.isRequired,
onItemDelete: PropTypes.func.isRequired,
onItemRename: PropTypes.func.isRequired,
onItemMove: PropTypes.func.isRequired,
onItemCopy: PropTypes.func.isRequired,
onDirentClick: PropTypes.func.isRequired,
isAllItemSelected: PropTypes.bool.isRequired,
onAllItemSelected: PropTypes.func.isRequired,
selectedDirentList: PropTypes.array.isRequired,
onItemsMove: PropTypes.func.isRequired,
onItemsCopy: PropTypes.func.isRequired,
onItemsDelete: PropTypes.func.isRequired,
onFileTagChanged: PropTypes.func,
showDirentDetail: PropTypes.func.isRequired,
};
class DirColumnView extends React.Component {
constructor(props) {
super(props);
this.state = {
inResizing: false,
navRate: 0.25,
};
this.containerWidth = null;
}
onResizeMouseUp = () => {
if (this.state.inResizing) {
this.setState({
inResizing: false
});
}
this.setCookie('navRate', this.state.navRate);
}
onResizeMouseDown = () => {
this.containerWidth = this.refs.viewModeContainer.clientWidth;
this.setState({
inResizing: true
});
};
onResizeMouseMove = (e) => {
let sizeNavWidth = this.containerWidth / 0.78 * 0.22 + 3;
let rate = (e.nativeEvent.clientX - sizeNavWidth) / this.containerWidth;
if (rate < 0.1) {
this.setState({
inResizing: false,
navRate: 0.12,
});
}
else if (rate > 0.4) {
this.setState({
inResizing: false,
navRate: 0.38,
});
}
else {
this.setState({
navRate: rate
});
}
};
setCookie = (name, value) => {
let cookie = name + '=' + value + ';';
document.cookie = cookie;
}
getCookie = (cookiename) => {
let name = cookiename + '=';
let cookie = document.cookie.split(';');
for (let i = 0, len = cookie.length; i < len; i++) {
let c = cookie[i].trim();
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length) * 1;
}
}
return '';
}
componentWillMount() {
let rate = this.getCookie('navRate');
if (rate) {
this.setState({
navRate: rate,
});
}
}
render() {
const onResizeMove = this.state.inResizing ? this.onResizeMouseMove : null;
const select = this.state.inResizing ? 'none' : '';
const mainFlex = '1 0 ' + (1 - this.state.navRate - 0.05) * 100 + '%';
return (
<div className="dir-colunm-view" onMouseMove={onResizeMove} onMouseUp={this.onResizeMouseUp} ref="viewModeContainer">
<DirColumnNav
currentPath={this.props.path}
repoPermission={this.props.repoPermission}
isTreeDataLoading={this.props.isTreeDataLoading}
treeData={this.props.treeData}
currentNode={this.props.currentNode}
onNodeClick={this.props.onNodeClick}
onNodeCollapse={this.props.onNodeCollapse}
onNodeExpanded={this.props.onNodeExpanded}
onAddFolderNode={this.props.onAddFolderNode}
onAddFileNode={this.props.onAddFileNode}
onRenameNode={this.props.onRenameNode}
onDeleteNode={this.props.onDeleteNode}
repoID={this.props.repoID}
navRate={this.state.navRate}
inResizing={this.state.inResizing}
currentRepoInfo={this.props.currentRepoInfo}
onItemMove={this.props.onItemMove}
onItemCopy={this.props.onItemCopy}
selectedDirentList={this.props.selectedDirentList}
onItemsMove={this.props.onItemsMove}
/>
<div className="dir-content-resize" onMouseDown={this.onResizeMouseDown}></div>
<div className="dir-content-main" style={{userSelect: select, flex: mainFlex}}>
{this.props.isViewFile ? (
<DirColumnFile
path={this.props.path}
repoID={this.props.repoID}
hash={this.props.hash}
isDraft={this.props.isDraft}
hasDraft={this.props.hasDraft}
goDraftPage={this.props.goDraftPage}
isFileLoading={this.props.isFileLoading}
isFileLoadedErr={this.props.isFileLoadedErr}
filePermission={this.props.filePermission}
content={this.props.content}
lastModified={this.props.lastModified}
latestContributor={this.props.latestContributor}
onLinkClick={this.props.onLinkClick}
/>
) : (
<DirListView
path={this.props.path}
repoID={this.props.repoID}
currentRepoInfo={this.props.currentRepoInfo}
isGroupOwnedRepo={this.props.isGroupOwnedRepo}
userPerm={this.props.userPerm}
enableDirPrivateShare={this.props.enableDirPrivateShare}
isRepoInfoBarShow={this.props.isRepoInfoBarShow}
usedRepoTags={this.props.usedRepoTags}
readmeMarkdown={this.props.readmeMarkdown}
draftCounts={this.props.draftCounts}
updateUsedRepoTags={this.props.updateUsedRepoTags}
isDirentListLoading={this.props.isDirentListLoading}
direntList={this.props.direntList}
sortBy={this.props.sortBy}
sortOrder={this.props.sortOrder}
sortItems={this.props.sortItems}
onAddFolder={this.props.onAddFolder}
onAddFile={this.props.onAddFile}
onItemClick={this.props.onItemClick}
onItemSelected={this.props.onItemSelected}
onItemDelete={this.props.onItemDelete}
onItemRename={this.props.onItemRename}
onItemMove={this.props.onItemMove}
onItemCopy={this.props.onItemCopy}
onDirentClick={this.props.onDirentClick}
updateDirent={this.props.updateDirent}
isAllItemSelected={this.props.isAllItemSelected}
onAllItemSelected={this.props.onAllItemSelected}
selectedDirentList={this.props.selectedDirentList}
onItemsMove={this.props.onItemsMove}
onItemsCopy={this.props.onItemsCopy}
onItemsDelete={this.props.onItemsDelete}
onFileTagChanged={this.props.onFileTagChanged}
showDirentDetail={this.props.showDirentDetail}
/>
)}
</div>
</div>
);
}
}
DirColumnView.propTypes = propTypes;
export default DirColumnView;
|
app/javascript/mastodon/features/account_timeline/index.js
|
sylph-sin-tyaku/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { fetchAccount } from '../../actions/accounts';
import { expandAccountFeaturedTimeline, expandAccountTimeline } from '../../actions/timelines';
import StatusList from '../../components/status_list';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import HeaderContainer from './containers/header_container';
import ColumnBackButton from '../../components/column_back_button';
import { List as ImmutableList } from 'immutable';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { FormattedMessage } from 'react-intl';
import { fetchAccountIdentityProofs } from '../../actions/identity_proofs';
import MissingIndicator from 'mastodon/components/missing_indicator';
const emptyList = ImmutableList();
const mapStateToProps = (state, { params: { accountId }, withReplies = false }) => {
const path = withReplies ? `${accountId}:with_replies` : accountId;
return {
isAccount: !!state.getIn(['accounts', accountId]),
statusIds: state.getIn(['timelines', `account:${path}`, 'items'], emptyList),
featuredStatusIds: withReplies ? ImmutableList() : state.getIn(['timelines', `account:${accountId}:pinned`, 'items'], emptyList),
isLoading: state.getIn(['timelines', `account:${path}`, 'isLoading']),
hasMore: state.getIn(['timelines', `account:${path}`, 'hasMore']),
blockedBy: state.getIn(['relationships', accountId, 'blocked_by'], false),
};
};
export default @connect(mapStateToProps)
class AccountTimeline extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
statusIds: ImmutablePropTypes.list,
featuredStatusIds: ImmutablePropTypes.list,
isLoading: PropTypes.bool,
hasMore: PropTypes.bool,
withReplies: PropTypes.bool,
blockedBy: PropTypes.bool,
isAccount: PropTypes.bool,
multiColumn: PropTypes.bool,
};
componentWillMount () {
const { params: { accountId }, withReplies } = this.props;
this.props.dispatch(fetchAccount(accountId));
this.props.dispatch(fetchAccountIdentityProofs(accountId));
if (!withReplies) {
this.props.dispatch(expandAccountFeaturedTimeline(accountId));
}
this.props.dispatch(expandAccountTimeline(accountId, { withReplies }));
}
componentWillReceiveProps (nextProps) {
if ((nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) || nextProps.withReplies !== this.props.withReplies) {
this.props.dispatch(fetchAccount(nextProps.params.accountId));
this.props.dispatch(fetchAccountIdentityProofs(nextProps.params.accountId));
if (!nextProps.withReplies) {
this.props.dispatch(expandAccountFeaturedTimeline(nextProps.params.accountId));
}
this.props.dispatch(expandAccountTimeline(nextProps.params.accountId, { withReplies: nextProps.params.withReplies }));
}
}
handleLoadMore = maxId => {
this.props.dispatch(expandAccountTimeline(this.props.params.accountId, { maxId, withReplies: this.props.withReplies }));
}
render () {
const { shouldUpdateScroll, statusIds, featuredStatusIds, isLoading, hasMore, blockedBy, isAccount, multiColumn } = this.props;
if (!isAccount) {
return (
<Column>
<ColumnBackButton multiColumn={multiColumn} />
<MissingIndicator />
</Column>
);
}
if (!statusIds && isLoading) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
const emptyMessage = blockedBy ? <FormattedMessage id='empty_column.account_unavailable' defaultMessage='Profile unavailable' /> : <FormattedMessage id='empty_column.account_timeline' defaultMessage='No toots here!' />;
return (
<Column>
<ColumnBackButton multiColumn={multiColumn} />
<StatusList
prepend={<HeaderContainer accountId={this.props.params.accountId} />}
alwaysPrepend
scrollKey='account_timeline'
statusIds={blockedBy ? emptyList : statusIds}
featuredStatusIds={featuredStatusIds}
isLoading={isLoading}
hasMore={hasMore}
onLoadMore={this.handleLoadMore}
shouldUpdateScroll={shouldUpdateScroll}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
/>
</Column>
);
}
}
|
src/web/solutions/SolveError/SolutionForm.js
|
whybug/whybug-server
|
import React from 'react';
export var SolutionForm = React.createClass({
propTypes: {
solution: React.PropTypes.object,
onChange: React.PropTypes.func,
onSave: React.PropTypes.func
},
render() {
var solution = this.props.solution || {};
return form({},
div({className: 'w-row'},
div({className: 'w-col w-col-9'},
MarkdownTextarea({
id: 'description',
onSave: this.props.onSave,
saving: this.props.saving,
//spinner: Spinner,
rows: 6,
required: "required",
className: "w-input field textarea markdown-body",
placeholder: 'How to solve this error?',
autoFocus: true,
buttonText: 'Create'
}),
this.props.error ? div({}, "Unable to save solution. ", this.props.error.message) : ""
),
div({className: 'w-col w-col-3'},
TextInput({
text: 'Level',
name: 'level',
onChange: this.props.onChange('level'),
values: solution
}),
TextInput({
text: 'Language',
name: 'programminglanguage',
onChange: this.props.onChange('programminglanguage'),
values: solution
}),
TextInput({
text: 'Language version',
name: 'programminglanguage_version',
onChange: this.props.onChange('programminglanguage_version'),
values: solution
}),
TextInput({
text: 'Operating system',
name: 'os',
onChange: this.props.onChange('os'),
values: solution
})
)
)
);
}
});
|
test/regressions/site/src/tests/Divider/InsetDivider.js
|
und3fined/material-ui
|
// @flow weak
import React from 'react';
import Divider from 'material-ui/Divider';
export default function InsetDivider() {
return (
<div style={{ padding: 2, width: 100 }}>
<Divider inset />
</div>
);
}
|
shared/components/Comment.js
|
AndrewGibson27/react-webpack-express-isomorphic-boilerplate
|
import React, { Component } from 'react';
const Comment = ({ body }) => (
<p>{body}</p>
);
export default Comment;
|
src/parser/warrior/arms/modules/core/Execute/MortalStrike.js
|
sMteX/WoWAnalyzer
|
import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import { formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import Abilities from 'parser/core/modules/Abilities';
import calculateMaxCasts from 'parser/core/calculateMaxCasts';
import Events from 'parser/core/Events';
import ExecuteRange from './ExecuteRange';
class MortalStrikeAnalyzer extends Analyzer {
static dependencies = {
abilities: Abilities,
executeRange: ExecuteRange,
};
mortalStrikesOutsideExecuteRange = 0;
mortalStrikesInExecuteRange = 0;
constructor(...args) {
super(...args);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.MORTAL_STRIKE), this._onMortalStrikeCast);
}
_onMortalStrikeCast(event) {
if (this.executeRange.isTargetInExecuteRange(event)) {
this.mortalStrikesInExecuteRange += 1;
event.meta = event.meta || {};
event.meta.isInefficientCast = true;
event.meta.inefficientCastReason = 'This Mortal Strike was used on a target in Execute range.';
} else {
this.mortalStrikesOutsideExecuteRange += 1;
}
}
get goodMortalStrikeThresholds() {
const cd = this.abilities.getAbility(SPELLS.MORTAL_STRIKE.id).cooldown;
const max = calculateMaxCasts(cd, this.owner.fightDuration - this.executeRange.executionPhaseDuration());
const maxCast = this.mortalStrikesOutsideExecuteRange / max > 1 ? this.mortalStrikesOutsideExecuteRange : max;
return {
actual: this.mortalStrikesOutsideExecuteRange / maxCast,
isLessThan: {
minor: 0.9,
average: 0.8,
major: 0.7,
},
style: 'percentage',
};
}
get badMortalStrikeThresholds() {
const cd = this.abilities.getAbility(SPELLS.MORTAL_STRIKE.id).cooldown;
const max = calculateMaxCasts(cd, this.executeRange.executionPhaseDuration());
const maxCast = this.mortalStrikesInExecuteRange / max > 1 ? this.mortalStrikesInExecuteRange : max;
return {
actual: this.mortalStrikesInExecuteRange / maxCast,
isGreaterThan: {
minor: 0,
average: 0.05,
major: 0.1,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.badMortalStrikeThresholds).addSuggestion((suggest, actual, recommended) => {
return suggest(<>Try to avoid using <SpellLink id={SPELLS.MORTAL_STRIKE.id} icon /> on a target in <SpellLink id={SPELLS.EXECUTE.id} icon /> range, as <SpellLink id={SPELLS.MORTAL_STRIKE.id} /> is less rage efficient than <SpellLink id={SPELLS.EXECUTE.id} />.</>)
.icon(SPELLS.MORTAL_STRIKE.icon)
.actual(`Mortal Strike was cast ${this.mortalStrikesInExecuteRange} times accounting for ${formatPercentage(actual)}% of the total possible casts of Mortal Strike during a time a target was in execute range.`)
.recommended(`${formatPercentage(recommended)}% is recommended`);
});
when(this.goodMortalStrikeThresholds).addSuggestion((suggest, actual, recommended) => {
return suggest(<>Try to cast <SpellLink id={SPELLS.MORTAL_STRIKE.id} icon /> more often when the target is outside execute range.</>)
.icon(SPELLS.MORTAL_STRIKE.icon)
.actual(`Mortal Strike was used ${formatPercentage(actual)}% of the time on a target outside execute range.`)
.recommended(`${formatPercentage(recommended)}% is recommended`);
});
}
}
export default MortalStrikeAnalyzer;
|
packages/icons/src/md/maps/Navigation.js
|
suitejs/suitejs
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdNavigation(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<polygon points="24 5 9 41.59 10.41 43 24 37 37.59 43 39 41.59" />
</IconBase>
);
}
export default MdNavigation;
|
RNApp/node_modules/react-native/local-cli/generator/templates/index.android.js
|
abhaytalreja/react-native-telescope
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class <%= name %> extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('<%= name %>', () => <%= name %>);
|
src/main.js
|
daveham/ilgmrdx
|
import React from 'react';
import ReactDOM from 'react-dom';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import { useRouterHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import createStore from 'store/createStore';
import Root from 'containers/Root';
// Browser History Setup
const browserHistory = useRouterHistory(createBrowserHistory)({
basename : __BASENAME__
});
// Store and History Instantiation
// Create redux store and sync with react-router-redux. We have installed the
// react-router-redux reducer under the routerKey "router" in src/routes/index.js,
// so we need to provide a custom `selectLocationState` to inform
// react-router-redux of its location.
const initialState = window.___INITIAL_STATE__;
const store = createStore(initialState, browserHistory);
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState : (state) => state.router
});
// Render Setup
const MOUNT_NODE = document.getElementById('root');
let render = () => {
const routes = require('./routes/index').default(store);
ReactDOM.render(
<Root
store={store}
history={history}
routes={routes}
/>,
MOUNT_NODE
);
};
// This code is excluded from production bundle
if (__DEV__) {
if (module.hot) {
// Development render functions
const renderApp = render;
const renderError = (error) => {
const RedBox = require('redbox-react').default;
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE);
};
// Wrap render in try/catch
render = () => {
try {
renderApp();
} catch (error) {
renderError(error);
}
};
// Setup hot module replacement
module.hot.accept('./routes/index', () => {
setTimeout(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE);
render();
});
});
}
}
render();
|
analysis/deathknightblood/src/CONFIG.js
|
anom0ly/WoWAnalyzer
|
import SPELLS from 'common/SPELLS';
import { Yajinni, joshinator } from 'CONTRIBUTORS';
import SPECS from 'game/SPECS';
import { SpellLink } from 'interface';
import React from 'react';
import CHANGELOG from './CHANGELOG';
export default {
// The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion.
contributors: [Yajinni, joshinator],
// The WoW client patch this spec was last updated.
patchCompatibility: '9.0.5',
isPartial: false,
// Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more.
// If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component.
description: (
<>
Blood depends a lot on using his runes and how they're used in order to perform well.
<br />
Overusing <SpellLink id={SPELLS.MARROWREND.id} /> for example reduces the amount of runic
power you can generate, directly affecting the amount of{' '}
<SpellLink id={SPELLS.DEATH_STRIKE.id} />
's.
<br />
<br />
Not only the amount of <SpellLink id={SPELLS.DEATH_STRIKE.id} />
's are important, timing is aswell. Make sure to check them in the 'Death Strike Timing'-tab
below.
<br />
The rest of this analyzer focuses a lot on maximizing your damage output, buff uptimes,
cooldown usage and more or less usefull statistics.
<br />
Your best defensive rotation is also your best offensive one, so optimizing your output means
you'll optimize your survivability aswell.
<br />
<br />
If you find any issues or have something you'd like to see added, open an issue on{' '}
<a href="https://github.com/WoWAnalyzer/WoWAnalyzer/issues/new">GitHub</a>, contact us on{' '}
<a href="https://discord.gg/AxphPxU">Discord</a> or DM us on Discord.
<br />
<br />
Make sure to check out the <a href="https://goo.gl/qjTtNY">Death Knight Class Discord</a> if
you need more specific advice or a more detailed guide than the ones available on{' '}
<a href="https://www.icy-veins.com/wow/blood-death-knight-pve-tank-guide">Icy-Veins</a> and{' '}
<a href="http://www.wowhead.com/blood-death-knight-guide">wowhead</a>.
</>
),
// A recent example report to see interesting parts of the spec. Will be shown on the homepage.
exampleReport: "/report/mx1BaMV7PyL4FnKz/10-Mythic+Artificer+Xy'mox+-+Kill+(5:53)/Tombo/standard",
// Don't change anything below this line;
// The current spec identifier. This is the only place (in code) that specifies which spec this parser is about.
spec: SPECS.BLOOD_DEATH_KNIGHT,
// The contents of your changelog.
changelog: CHANGELOG,
// The CombatLogParser class for your spec.
parser: () =>
import('./CombatLogParser' /* webpackChunkName: "BloodDeathKnight" */).then(
(exports) => exports.default,
),
// The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code.
path: __dirname,
};
|
packages/example-universal-react-app/src/index.js
|
raymondsze/create-react-scripts
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
source/patterns/01-molecules/messages/alert/__tests__/alert.spec.js
|
apparena/patterns
|
/* eslint-env mocha */
import React from 'react';
import {shallow, configure} from 'enzyme';
import Alert from '../index';
import Adapter from 'enzyme-adapter-react-16';
configure({adapter: new Adapter()});
test('DUMMY', () => {
const wrapper = shallow(
<Alert type="danger">
Hello world!
</Alert>
);
expect(true).toBe(true);
});
/*
test('alerts with custom text', (t) => {
const wrapbuttper = shallow(
<Alert type="danger">
Hello world!
</Alert>
);
t.is(wrapper.find('Alert').length === 1, true);
//t.is(wrapper.contains('Hello World!'), true);
t.is(wrapper.find('.alert-danger').length, 1);
});
test('respects the type', (t) => {
const wrapper = shallow(
<Alert type="info">
Hello world!
</Alert>
);
t.is(wrapper.find('.alert-info').length, 1);
});
test('allows me to insert custom classes as a string', (t) => {
const wrapper = shallow(
<Alert type="info" classNames="custom-class-1 custom-class-2">
Hello world!
</Alert>
);
t.is(wrapper.find('.custom-class-1').length, 1);
t.is(wrapper.find('.custom-class-2').length, 1);
});
test('is dismissable at will', (t) => {
const wrapper = shallow(
<Alert type="danger" dismissible>
Hello world!
</Alert>
);
t.is(wrapper.find('button').length, 1);
t.is(wrapper.find('.alert-danger').length, 1);
});
test('is not dismissable by default', (t) => {
const wrapper = shallow(
<Alert type="danger">
Hello world!
</Alert>
);
t.is(wrapper.find('button').length, 0);
t.is(wrapper.find('.alert-danger').length, 1);
});*/
|
packages/components/src/List/Toolbar/ItemsNumber/ItemsNumber.component.js
|
Talend/ui
|
import React from 'react';
import PropTypes from 'prop-types';
import getDefaultT from '../../../translate';
function ItemsNumber({ id, totalItems, selected, label, labelSelected, t }) {
return (
<div className="tc-items-number" id={id}>
{selected
? labelSelected ||
t('LIST_TOOLBAR_NUMBER_OF_SELECTED_ITEMS', {
defaultValue: '{{count}}/{{total}} items',
count: selected,
total: totalItems,
})
: label ||
t('LIST_TOOLBAR_TOTAL_NUMBER_OF_ITEMS', {
defaultValue: '{{count}} items',
count: totalItems,
})}
</div>
);
}
ItemsNumber.propTypes = {
id: PropTypes.string,
selected: PropTypes.number,
totalItems: PropTypes.number,
label: PropTypes.string,
labelSelected: PropTypes.string,
t: PropTypes.func,
};
ItemsNumber.defaultProps = {
t: getDefaultT(),
};
export default ItemsNumber;
|
src/components/relativeLink/index.js
|
LiskHQ/lisk-nano
|
import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { withRouter } from 'react-router';
import buttonStyle from 'react-toolbox/lib/button/theme.css';
import offlineStyle from '../offlineWrapper/offlineWrapper.css';
import dialogs from '../dialog/dialogs';
const RelativeLink = ({
location, to, children, className, raised, neutral, primary, flat, disableWhenOffline,
}) => {
let style = '';
if (raised !== undefined) style += `${buttonStyle.raised} `;
if (neutral !== undefined) style += `${buttonStyle.neutral} `;
if (flat !== undefined) style += `${buttonStyle.flat} `;
if (primary !== undefined) style += `${buttonStyle.primary} `;
if (disableWhenOffline !== undefined) style += `${offlineStyle.disableWhenOffline} `;
if (style !== '') style += ` ${buttonStyle.button}`;
const dialogNames = Object.keys(dialogs());
let pathname = location.pathname;
dialogNames.forEach((dialog) => {
pathname = pathname.replace(`/${dialog}`, '');
});
const path = `${pathname}/${to}`.replace('//', '/');
return (
<Link className={`${className} ${style}`} to={path}>{ children }</Link>
);
};
const mapStateToProps = state => ({
dialog: state.dialog,
});
export default withRouter(connect(mapStateToProps)(RelativeLink));
|
client/src/components/StreamField/blocks/FieldBlock.js
|
torchbox/wagtail
|
/* global $ */
import { escapeHtml as h } from '../../../utils/text';
import ReactDOM from 'react-dom';
import React from 'react';
import Icon from '../../Icon/Icon';
export class FieldBlock {
constructor(
blockDef,
placeholder,
prefix,
initialState,
initialError,
parentCapabilities,
) {
this.blockDef = blockDef;
this.type = blockDef.name;
const dom = $(`
<div class="${h(this.blockDef.meta.classname)}">
<div class="field-content">
<div class="input">
<div data-streamfield-widget></div>
<span></span>
</div>
</div>
</div>
`);
$(placeholder).replaceWith(dom);
const widgetElement = dom.find('[data-streamfield-widget]').get(0);
this.element = dom[0];
this.parentCapabilities = parentCapabilities || new Map();
this.prefix = prefix;
try {
this.widget = this.blockDef.widget.render(
widgetElement,
prefix,
prefix,
initialState,
this.parentCapabilities,
);
} catch (e) {
// eslint-disable-next-line no-console
console.error(e);
this.setError([
{
messages: [
'This widget failed to render, please check the console for details',
],
},
]);
return;
}
this.idForLabel = this.widget.idForLabel;
if (this.blockDef.meta.helpText) {
const helpElement = document.createElement('p');
helpElement.classList.add('help');
helpElement.innerHTML = this.blockDef.meta.helpText; // unescaped, as per Django conventions
this.element.querySelector('.field-content').appendChild(helpElement);
}
if (window.comments && this.blockDef.meta.showAddCommentButton) {
const fieldCommentControlElement = document.createElement('div');
fieldCommentControlElement.classList.add('field-comment-control');
this.element.appendChild(fieldCommentControlElement);
const addCommentButtonElement = document.createElement('button');
addCommentButtonElement.type = 'button';
addCommentButtonElement.setAttribute(
'aria-label',
blockDef.meta.strings.ADD_COMMENT,
);
addCommentButtonElement.setAttribute('data-comment-add', '');
addCommentButtonElement.classList.add('button');
addCommentButtonElement.classList.add('button-secondary');
addCommentButtonElement.classList.add('button-small');
addCommentButtonElement.classList.add('u-hidden');
ReactDOM.render(
<>
<Icon name="comment-add" className="icon-default" />
<Icon name="comment-add-reversed" className="icon-reversed" />
</>,
addCommentButtonElement,
);
fieldCommentControlElement.appendChild(addCommentButtonElement);
window.comments.initAddCommentButton(addCommentButtonElement);
}
if (initialError) {
this.setError(initialError);
}
}
setCapabilityOptions(capability, options) {
Object.assign(this.parentCapabilities.get(capability), options);
if (this.widget && this.widget.setCapabilityOptions) {
this.widget.setCapabilityOptions(capability, options);
}
}
setState(state) {
if (this.widget) {
this.widget.setState(state);
}
}
setError(errorList) {
this.element
.querySelectorAll(':scope > .field-content > .error-message')
.forEach((element) => element.remove());
if (errorList) {
this.element.classList.add('error');
const errorElement = document.createElement('p');
errorElement.classList.add('error-message');
errorElement.innerHTML = errorList
.map((error) => `<span>${h(error.messages[0])}</span>`)
.join('');
this.element.querySelector('.field-content').appendChild(errorElement);
} else {
this.element.classList.remove('error');
}
}
getState() {
return this.widget.getState();
}
getValue() {
return this.widget.getValue();
}
getTextLabel(opts) {
if (this.widget.getTextLabel) {
return this.widget.getTextLabel(opts);
}
return null;
}
focus(opts) {
if (this.widget) {
this.widget.focus(opts);
}
}
}
export class FieldBlockDefinition {
constructor(name, widget, meta) {
this.name = name;
this.widget = widget;
this.meta = meta;
}
render(placeholder, prefix, initialState, initialError, parentCapabilities) {
return new FieldBlock(
this,
placeholder,
prefix,
initialState,
initialError,
parentCapabilities,
);
}
}
|
server/prerenderer.js
|
firegoby/react-ecosystem-aurora
|
import React from 'react'
import Router from 'react-router'
import Flux from '../app/flux.js'
import routes from '../app/routes.js'
import performRouteHandlerStaticMethod from '../app/shared/performRouteHandlerStaticMethod'
export default function (req, res) {
const flux = new Flux()
// let's just assume `npm run build` has been run at least once
const hash = require('../public/build/stats.json').hash
const router = Router.create({
routes: routes,
location: req.url,
onError: error => {
throw error
},
onAbort: abortReason => {
const error = new Error()
if (abortReason.constructor.name === 'Redirect') {
console.log('redirect causing abort')
const { to, params, query } = abortReason
console.log(to, params, query)
const url = router.makePath(to, params, query)
error.redirect = url
}
throw error
}
})
router.run(function (Handler, state) {
async function run() {
await performRouteHandlerStaticMethod(state.routes, 'routerWillRunOnServer', state, flux)
React.withContext(
{ flux },
() => {
let appString = React.renderToString(<Handler />)
res.render('index', { production: true, appString: appString, hash: hash })
}
)
}
run().catch(error => {
throw error
})
})
}
|
modules/IndexLink.js
|
littlefoot32/react-router
|
import React from 'react'
import Link from './Link'
var IndexLink = React.createClass({
render() {
return <Link {...this.props} onlyActiveOnIndex={true} />
}
})
export default IndexLink
|
src/parser/monk/brewmaster/modules/core/MasteryValue.js
|
sMteX/WoWAnalyzer
|
import React from 'react';
import SPELLS from 'common/SPELLS';
import HIT_TYPES from 'game/HIT_TYPES';
import Analyzer from 'parser/core/Analyzer';
import StatTracker from 'parser/shared/modules/StatTracker';
import LazyLoadStatisticBox from 'interface/others/LazyLoadStatisticBox';
import SpellIcon from 'common/SpellIcon';
import { formatNumber, formatPercentage } from 'common/format';
import OneVariableBinomialChart from 'interface/others/charts/OneVariableBinomialChart';
import DamageTaken from './DamageTaken';
import GiftOfTheOx from '../spells/GiftOfTheOx';
// coefficients to calculate dodge chance from agility
const MONK_DODGE_COEFFS = {
base_dodge: 3,
base_agi: 1468,
// names of individual coefficients are taken from ancient lore, err,
// formulae
P: 452.27,
D: 80,
v: 0.01,
h: 1.06382978723,
};
function _clampProb(prob) {
if (prob > 1.0) {
return 1.0;
} else if (prob < 0.0) {
return 0.0;
} else {
return prob;
}
}
/**
* This class represents the Markov Chain with which the Mastery stacks
* are modeled. The transition probabilities are defined by two
* potential operations:
*
* 1. Guaranteed Addition: from using an ability that generates a stack
* 100% of the time (e.g. BoS, BoF). The probability of having i stacks
* afterward is equal to the probability of having i-1 stacks before
* (the probability of having 0 stacks afterward is 0).
*
* 2. Attack: The probability of having i > 0 stacks afterward is equal to
* the probability of being hit with i - 1 stacks. The probability of
* having 0 stacks afterward is the sum of the probabilities of dodging
* with each number of stacks. Note that there is a natural cap on the
* number of stacks you can reach, since after that point every hit will
* be a dodge.
*
* The expected number of stacks you have is just the sum of the indices
* weighted by the values.
*/
class StackMarkovChain {
_stackProbs = [1.0];
_assertSum() {
const sum = this._stackProbs.reduce((sum, p) => p + sum, 0);
if (Math.abs(sum - 1.0) > 1e-6) {
const err = new Error('probabilities do not sum to 1 in StackMarkovChain');
err.data = {
sum: sum,
probs: this._stackProbs,
};
console.log(err.data);
throw err;
}
}
// add a stack with guaranteed probability
guaranteeStack() {
this._stackProbs.unshift(0.0);
this._assertSum();
}
processAttack(baseDodgeProb, masteryValue) {
this._stackProbs.push(0);
const n = this._stackProbs.length - 1;
// probability of ending at 0 stacks. initial
let zeroProb = 0;
// didn't dodge, gain a stack
for (let stacks = n - 1; stacks >= 0; stacks--) {
const prob = _clampProb(baseDodgeProb + masteryValue * stacks);
zeroProb += prob * this._stackProbs[stacks]; // dodge -> go to 0
const hitProb = 1 - prob;
this._stackProbs[stacks + 1] = hitProb * this._stackProbs[stacks]; // hit -> go to stacks + 1
}
// did dodge, reset stacks
this._stackProbs[0] = zeroProb;
this._assertSum();
}
get expected() {
return this._stackProbs.reduce((sum, prob, index) => sum + prob * index, 0);
}
}
export function baseDodge(agility, dodge_rating = 0) {
const base = MONK_DODGE_COEFFS.base_dodge + MONK_DODGE_COEFFS.base_agi / MONK_DODGE_COEFFS.P;
const chance = (agility - MONK_DODGE_COEFFS.base_agi) / MONK_DODGE_COEFFS.P + dodge_rating / MONK_DODGE_COEFFS.D;
// the x / (x + k) formula is commonly used by the wow team to
// implement diminishing returns
return (base + chance / (chance * MONK_DODGE_COEFFS.v + MONK_DODGE_COEFFS.h)) / 100;
}
/**
* Estimate the expected value of mastery on this fight. The *actual*
* estimated value is subject to greater variance.
* On the other hand, the expected value averages over all
* possible outcomes and gives a better sense of how valuable mastery is
* if you were to do this fight again. This values more stable over
* repeated attempts or kills and reflects the value of mastery (and the
* execution of the rotation) more closely than how well-favored you
* were on this particular attempt.
*
* We calculate the expected value by applying the Markov Chain above to
* the timeline to calculate the expected number of stacks at each
* dodgeable event. This is then combined with information about the
* expected damage of each dodged hit (dodge events have amount: 0,
* absorbed: 0, etc.) to provide a best-guess estimate of the damage
* you'll mitigate on average. The actual estimate (shown in the
* tooltip) may be over or under this, but is unlikely to be far from
* it.
*
* This madness was authored by emallson. If you need further explanation of
* the theory behind it, find me on discord.
*/
class MasteryValue extends Analyzer {
static dependencies = {
dmg: DamageTaken,
stats: StatTracker,
gotox: GiftOfTheOx,
};
_loaded = false;
_dodgeableSpells = {};
_timeline = [];
_hitCounts = {};
_dodgeCounts = {};
dodgePenalty(_source) {
return 0.045; // 1.5% per level, bosses are three levels over players. not sure how to get trash levels yet -- may not matter
}
// returns the current chance to dodge a damage event assuming the
// event is dodgeable
dodgeChance(masteryStacks, masteryRating, agility, sourceID, timestamp = null) {
const masteryPercentage = this.stats.masteryPercentage(masteryRating, true);
return _clampProb(masteryPercentage * masteryStacks + baseDodge(agility) - this.dodgePenalty(sourceID));
}
on_byPlayer_cast(event) {
if (this._stacksApplied(event) > 0) {
this._timeline.push(event);
}
}
on_toPlayer_damage(event) {
event._masteryRating = this.stats.currentMasteryRating;
event._agility = this.stats.currentAgilityRating;
if (event.hitType === HIT_TYPES.DODGE) {
this._addDodge(event);
} else {
this._addHit(event);
}
}
_addDodge(event) {
const spellId = event.ability.guid;
this._dodgeableSpells[spellId] = true;
if (this._dodgeCounts[spellId] === undefined) {
this._dodgeCounts[spellId] = 0;
}
this._dodgeCounts[spellId] += 1;
this._timeline.push(event);
}
_addHit(event) {
const spellId = event.ability.guid;
if (this._hitCounts[spellId] === undefined) {
this._hitCounts[spellId] = 0;
}
this._hitCounts[spellId] += 1;
this._timeline.push(event);
}
// returns true of the event represents a cast that applies a stack of
// mastery
_stacksApplied(event) {
if(event.ability.guid !== SPELLS.BLACKOUT_STRIKE.id) {
return 0;
}
let stacks = 1;
// account for elusive footwork
if(this.selectedCombatant.hasTrait(SPELLS.ELUSIVE_FOOTWORK.id) && event.hitType === HIT_TYPES.CRIT) {
stacks += 1;
}
return stacks;
}
meanHitByAbility(spellId) {
if (this._hitCounts[spellId] !== undefined) {
return (this.dmg.byAbility(spellId).effective + this.dmg.staggeredByAbility(spellId)) / this._hitCounts[spellId];
}
return 0;
}
// events that either (a) add a stack or (b) can be dodged according
// to the data we have
get relevantTimeline() {
return this._timeline.filter(event => event.type === 'cast' || this._dodgeableSpells[event.ability.guid]);
}
_expectedValues = {
expectedDamageMitigated: 0,
estimatedDamageMitigated: 0,
meanExpectedDodge: 0,
noMasteryExpectedDamageMitigated: 0,
noMasteryMeanExpectedDodge: 0,
noAgiExpectedDamageMitigated: 0,
};
_calculateExpectedValues() {
// expected damage mitigated according to the markov chain
let expectedDamageMitigated = 0;
let noMasteryExpectedDamageMitigated = 0;
let noAgiExpectedDamageMitigated = 0;
// estimate of the damage that was actually dodged in this log
let estimatedDamageMitigated = 0;
// average dodge % across each event that could be dodged
let meanExpectedDodge = 0;
let noMasteryMeanExpectedDodge = 0;
let dodgeableEvents = 0;
const stacks = new StackMarkovChain(); // mutating a const object irks me to no end
const noMasteryStacks = new StackMarkovChain();
const noAgiStacks = new StackMarkovChain();
// timeline replay is expensive, compute several things here and
// provide individual getters for each of the values
this.relevantTimeline.forEach(event => {
if (event.type === 'cast') {
const eventStacks = this._stacksApplied(event);
for(let i = 0; i < eventStacks; i++) {
stacks.guaranteeStack();
noMasteryStacks.guaranteeStack();
noAgiStacks.guaranteeStack();
}
} else if (event.type === 'damage') {
const noMasteryDodgeChance = this.dodgeChance(noMasteryStacks.expected, 0, event._agility, event.sourceID, event.timestamp);
const noAgiDodgeChance = this.dodgeChance(noAgiStacks.expected, event._masteryRating,
MONK_DODGE_COEFFS.base_agi, event.sourceID, event.timestamp);
const expectedDodgeChance = this.dodgeChance(stacks.expected, event._masteryRating, event._agility, event.sourceID, event.timestamp);
const baseDodgeChance = this.dodgeChance(0, 0, event._agility, event.sourceID, event.timestamp);
const noAgiBaseDodgeChance = this.dodgeChance(0, 0, MONK_DODGE_COEFFS.base_agi, event.sourceID, event.timestamp);
const damage = (event.amount + event.absorbed) || this.meanHitByAbility(event.ability.guid);
expectedDamageMitigated += expectedDodgeChance * damage;
noMasteryExpectedDamageMitigated += noMasteryDodgeChance * damage;
noAgiExpectedDamageMitigated += noAgiDodgeChance * damage;
estimatedDamageMitigated += (event.hitType === HIT_TYPES.DODGE) * damage;
meanExpectedDodge += expectedDodgeChance;
noMasteryMeanExpectedDodge += noMasteryDodgeChance;
dodgeableEvents += 1;
stacks.processAttack(baseDodgeChance, this.stats.masteryPercentage(event._masteryRating, true));
noAgiStacks.processAttack(noAgiBaseDodgeChance, this.stats.masteryPercentage(event._masteryRating, true));
noMasteryStacks.processAttack(baseDodgeChance, this.stats.masteryPercentage(0, true));
}
});
meanExpectedDodge /= dodgeableEvents;
noMasteryMeanExpectedDodge /= dodgeableEvents;
return {
expectedDamageMitigated,
estimatedDamageMitigated,
meanExpectedDodge,
noMasteryExpectedDamageMitigated,
noMasteryMeanExpectedDodge,
noAgiExpectedDamageMitigated,
};
}
get expectedMitigation() {
return this._expectedValues.expectedDamageMitigated;
}
get expectedMeanDodge() {
return this._expectedValues.meanExpectedDodge;
}
get noMasteryExpectedMeanDodge() {
return this._expectedValues.noMasteryMeanExpectedDodge;
}
get totalDodges() {
return Object.keys(this._dodgeableSpells).reduce((sum, spellId) => sum + this._dodgeCounts[spellId], 0);
}
get totalDodgeableHits() {
return Object.keys(this._dodgeableSpells).reduce((sum, spellId) => sum + (this._hitCounts[spellId] || 0), 0)
+ this.totalDodges;
}
get actualDodgeRate() {
return this.totalDodges / this.totalDodgeableHits;
}
get estimatedActualMitigation() {
return this._expectedValues.estimatedDamageMitigated;
}
get averageMasteryRating() {
return this.relevantTimeline.reduce((sum, event) => {
if (event.type === 'damage') {
return event._masteryRating + sum;
} else {
return sum;
}
}, 0) / this.relevantTimeline.filter(event => event.type === 'damage').length;
}
get noMasteryExpectedMitigation() {
return this._expectedValues.noMasteryExpectedDamageMitigated;
}
get noAgiExpectedDamageMitigated() {
return this._expectedValues.noAgiExpectedDamageMitigated;
}
get expectedMitigationPerSecond() {
return this.expectedMitigation / this.owner.fightDuration * 1000;
}
get noMasteryExpectedMitigationPerSecond() {
return this.noMasteryExpectedMitigation / this.owner.fightDuration * 1000;
}
get totalMasteryHealing() {
return this.gotox.masteryBonusHealing;
}
get plot() {
// not the most efficient, but close enough and pretty safe
function binom(n, k) {
if(k > n) {
return null;
}
if(k === 0) {
return 1;
}
return n / k * binom(n-1, k-1);
}
// pmf of the binomial distribution with n = totalDodgeableHits and
// p = expectedMeanDodge
const dodge_prob = (i) => binom(this.totalDodgeableHits, i) * Math.pow(this.expectedMeanDodge, i) * Math.pow(1 - this.expectedMeanDodge, this.totalDodgeableHits - i);
// probability of having dodge exactly k of the n incoming hits
// assuming the expected mean dodge % is the true mean dodge %
const dodge_probs = Array.from({length: this.totalDodgeableHits}, (_x, i) => {
return { x: i, y: dodge_prob(i) };
});
const actualDodge = {
x: this.totalDodges,
y: dodge_prob(this.totalDodges),
};
return (
<OneVariableBinomialChart
probabilities={dodge_probs}
actualEvent={actualDodge}
yDomain={[0, 0.4]}
xAxis={{
title: 'Dodge %',
tickFormat: (value) => `${formatPercentage(value / this.totalDodgeableHits, 0)}%`,
}}
tooltip={(point) => `Actual Dodge: ${formatPercentage(point.x / this.totalDodgeableHits, 2)}%`}
/>
);
}
load() {
this._loaded = true;
this._expectedValues = this._calculateExpectedValues();
return Promise.resolve(this._expectedValues);
}
statistic() {
return (
<LazyLoadStatisticBox
loader={this.load.bind(this)}
icon={<SpellIcon id={SPELLS.MASTERY_ELUSIVE_BRAWLER.id} />}
value={`${formatNumber(this.expectedMitigationPerSecond - this.noMasteryExpectedMitigationPerSecond)} DTPS`}
label="Expected Mitigation by Mastery"
tooltip={this._loaded ? (
<>
On average, you would dodge about <strong>{formatNumber(this.expectedMitigation)}</strong> damage on this fight. This value was increased by about <strong>{formatNumber(this.expectedMitigation - this.noMasteryExpectedMitigation)}</strong> due to Mastery.
You had an average expected dodge chance of <strong>{formatPercentage(this.expectedMeanDodge)}%</strong> and actually dodged about <strong>{formatNumber(this.estimatedActualMitigation)}</strong> damage with an overall rate of <strong>{formatPercentage(this.actualDodgeRate)}%</strong>.
This amounts to an expected reduction of <strong>{formatNumber((this.expectedMitigationPerSecond - this.noMasteryExpectedMitigationPerSecond) / this.averageMasteryRating)} DTPS per 1 Mastery</strong> <em>on this fight</em>.<br /><br />
<em>Technical Information:</em><br />
<strong>Estimated Actual Damage</strong> is calculated by calculating the average damage per hit of an ability, then multiplying that by the number of times you dodged each ability.<br />
<strong>Expected</strong> values are calculated by computing the expected number of mastery stacks each time you <em>could</em> dodge an ability.<br />
An ability is considered <strong>dodgeable</strong> if you dodged it at least once.
</>
) : null}
>
<div style={{padding: '8px'}}>
{this._loaded ? this.plot : null}
<p>Likelihood of dodging <em>exactly</em> as much as you did with your level of Mastery.</p>
</div>
</LazyLoadStatisticBox>
);
}
}
export default MasteryValue;
|
src/js/components/AccordionPanel.js
|
kylebyerly-hp/grommet
|
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Header from './Header';
import Button from './Button';
import ListItem from './ListItem';
import CaretNextIcon from './icons/base/CaretNext';
import Collapsible from './Collapsible';
import CSSClassnames from '../utils/CSSClassnames';
import Intl from '../utils/Intl';
const CLASS_ROOT = CSSClassnames.ACCORDION_PANEL;
export default class AccordionPanel extends Component {
constructor() {
super();
this._onClickTab = this._onClickTab.bind(this);
}
_onClickTab (event) {
const { onChange } = this.props;
if (event) {
event.preventDefault();
}
onChange();
}
render () {
const {
a11yTitle, active, animate, className, children, heading, pad
} = this.props;
const { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
className,
{
[`${CLASS_ROOT}--active`]: active
}
);
const tabContentTitle = Intl.getMessage(intl, 'Tab Contents', {
activeTitle: a11yTitle || heading
});
return (
<div>
<ListItem className={classes} direction='column' pad='none'
aria-expanded={active} aria-selected={active} role='tab'
aria-label={a11yTitle || heading}>
<Button fill={true} plain={true} onClick={this._onClickTab}>
<Header pad={pad} direction='row'
justify='between' align='center' responsive={false}
className={`${CLASS_ROOT}__header`}>
{heading}
<CaretNextIcon
className={`${CLASS_ROOT}__control`} />
</Header>
</Button>
</ListItem>
<Collapsible aria-label={tabContentTitle} role='tabpanel'
active={active} animate={animate} pad={pad}>
{children}
</Collapsible>
</div>
);
}
}
AccordionPanel.propTypes = {
a11yTitle: PropTypes.string,
active: PropTypes.bool, // set by Accordion
animate: PropTypes.bool,
heading: PropTypes.node.isRequired,
onChange: PropTypes.func,
pad: Header.propTypes.pad
};
AccordionPanel.contextTypes = {
intl: PropTypes.object
};
|
local-cli/templates/HelloNavigation/components/ListItem.js
|
makadaw/react-native
|
'use strict';
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
TouchableHighlight,
TouchableNativeFeedback,
View,
} from 'react-native';
/**
* Renders the right type of Touchable for the list item, based on platform.
*/
const Touchable = ({onPress, children}) => {
const child = React.Children.only(children);
if (Platform.OS === 'android') {
return (
<TouchableNativeFeedback onPress={onPress}>
{child}
</TouchableNativeFeedback>
);
} else {
return (
<TouchableHighlight onPress={onPress} underlayColor="#ddd">
{child}
</TouchableHighlight>
);
}
}
const ListItem = ({label, onPress}) => (
<Touchable onPress={onPress}>
<View style={styles.item}>
<Text style={styles.label}>{label}</Text>
</View>
</Touchable>
);
const styles = StyleSheet.create({
item: {
height: 48,
justifyContent: 'center',
paddingLeft: 12,
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: '#ddd',
},
label: {
fontSize: 16,
}
});
export default ListItem;
|
packages/starter-scripts/fixtures/kitchensink/src/features/webpack/ScssModulesInclusion.js
|
chungchiehlun/create-starter-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.
*/
import React from 'react';
import styles from './assets/scss-styles.module.scss';
import indexStyles from './assets/index.module.scss';
export default () => (
<div>
<p className={styles.scssModulesInclusion}>SCSS Modules are working!</p>
<p className={indexStyles.scssModulesIndexInclusion}>
SCSS Modules with index are working!
</p>
</div>
);
|
components/navbar/DropDownMenu.js
|
telemark/portalen
|
import React from 'react'
import { Icon } from '../styles'
export default class extends React.Component {
constructor (props) {
super(props)
this.state = {
isOpen: false
}
this.handleOutsideClick = this.handleOutsideClick.bind(this)
this.handleClick = this.handleClick.bind(this)
}
handleClick () {
this.state.isOpen
? document.removeEventListener('click', this.handleOutsideClick, false)
: document.addEventListener('click', this.handleOutsideClick, false)
this.setState(prevState => ({ isOpen: !prevState.isOpen }))
}
handleOutsideClick (e) {
if (this.node.contains(e.target)) {
return
}
this.handleClick()
}
render () {
return (
<div className='menu' ref={node => { this.node = node }}>
<a onClick={this.handleClick}><Icon name='more_vert' /></a>
{
this.state.isOpen &&
<div className='menu-content'>
{this.props.children}
</div>
}
<style jsx>
{`
.menu {
position: relative;
cursor: pointer;
}
.menu-content {
display: inline-block;
position: absolute;
background-color: #f9f9f9;
min-width: 130px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
right: 0;
line-height: 30px;
top: 40px;
text-align: center;
border-radius: 2px;
}
`}
</style>
</div>
)
}
}
|
src/files/explore-form/FilesExploreForm.stories.js
|
ipfs/webui
|
import React from 'react'
import { storiesOf } from '@storybook/react'
import { action } from '@storybook/addon-actions'
import { checkA11y } from '@storybook/addon-a11y'
import i18n from '../../i18n-decorator'
import FilesExploreForm from './FilesExploreForm'
storiesOf('Files', module)
.addDecorator(checkA11y)
.addDecorator(i18n)
.add('Explore Form', () => (
<div className='ma3 pa3 bg-snow-muted mw6'>
<FilesExploreForm onBrowse={action('Browse')} onInspect={action('Inspect')} />
</div>
))
|
src/svg-icons/av/high-quality.js
|
nathanmarks/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvHighQuality = (props) => (
<SvgIcon {...props}>
<path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 11H9.5v-2h-2v2H6V9h1.5v2.5h2V9H11v6zm7-1c0 .55-.45 1-1 1h-.75v1.5h-1.5V15H14c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1v4zm-3.5-.5h2v-3h-2v3z"/>
</SvgIcon>
);
AvHighQuality = pure(AvHighQuality);
AvHighQuality.displayName = 'AvHighQuality';
AvHighQuality.muiName = 'SvgIcon';
export default AvHighQuality;
|
client/components/ReactHotLoader.js
|
KCPSoftware/KCPS-React-Starterkit
|
/* eslint-disable global-require */
/* eslint-disable import/no-extraneous-dependencies */
import React from 'react';
// We create this wrapper so that we only import react-hot-loader for a
// development build. Small savings. :)
const ReactHotLoader = process.env.NODE_ENV === 'development'
? require('react-hot-loader').AppContainer
: ({ children }) => React.Children.only(children);
export default ReactHotLoader;
|
src/icons/IosListOutline.js
|
fbfeix/react-icons
|
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosListOutline extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<g>
<path d="M432,80v352H80V80H432 M448,64H64v384h384V64L448,64z"></path>
<g>
<rect x="192" y="152" width="192" height="16"></rect>
</g>
<g>
<rect x="192" y="248" width="192" height="16"></rect>
</g>
<g>
<rect x="192" y="344" width="192" height="16"></rect>
</g>
</g>
<circle cx="144" cy="160" r="16"></circle>
<circle cx="144" cy="256" r="16"></circle>
<circle cx="144" cy="352" r="16"></circle>
</g>
</g>;
} return <IconBase>
<g>
<g>
<path d="M432,80v352H80V80H432 M448,64H64v384h384V64L448,64z"></path>
<g>
<rect x="192" y="152" width="192" height="16"></rect>
</g>
<g>
<rect x="192" y="248" width="192" height="16"></rect>
</g>
<g>
<rect x="192" y="344" width="192" height="16"></rect>
</g>
</g>
<circle cx="144" cy="160" r="16"></circle>
<circle cx="144" cy="256" r="16"></circle>
<circle cx="144" cy="352" r="16"></circle>
</g>
</IconBase>;
}
};IosListOutline.defaultProps = {bare: false}
|
src/elements/List/ListHeader.js
|
aabustamante/Semantic-UI-React
|
import cx from 'classnames'
import _ from 'lodash'
import PropTypes from 'prop-types'
import React from 'react'
import {
createShorthandFactory,
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
/**
* A list item can contain a header.
*/
function ListHeader(props) {
const { children, className, content } = props
const classes = cx('header', className)
const rest = getUnhandledProps(ListHeader, props)
const ElementType = getElementType(ListHeader, props)
return (
<ElementType {...rest} className={classes}>
{_.isNil(children) ? content : children}
</ElementType>
)
}
ListHeader._meta = {
name: 'ListHeader',
parent: 'List',
type: META.TYPES.ELEMENT,
}
ListHeader.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
}
ListHeader.create = createShorthandFactory(ListHeader, content => ({ content }))
export default ListHeader
|
src/routes.js
|
Rosita13/react-redux
|
/* eslint-disable */
import React from 'react';
import { IndexRoute, Route } from 'react-router';
import { routerActions } from 'react-router-redux';
import { UserAuthWrapper } from 'redux-auth-wrapper';
import { App, Home, NotFound } from 'containers';
import getRoutesUtils from 'utils/routes';
// eslint-disable-next-line import/no-dynamic-require
if (typeof System.import === 'undefined') System.import = module => Promise.resolve(require(module));
export default store => {
const {
injectReducerAndRender,
permissionsComponent
} = getRoutesUtils(store);
/* Permissions */
const isAuthenticated = UserAuthWrapper({
authSelector: state => state.auth.user,
redirectAction: routerActions.replace,
wrapperDisplayName: 'UserIsAuthenticated'
});
const isNotAuthenticated = UserAuthWrapper({
authSelector: state => state.auth.user,
redirectAction: routerActions.replace,
wrapperDisplayName: 'UserIsNotAuthenticated',
predicate: user => !user,
failureRedirectPath: '/',
allowRedirectBack: false
});
/**
* Please keep routes in alphabetical order
*/
return (
<Route path="/" component={App}>
{/* Home (main) route */}
<IndexRoute component={Home} />
{/* Routes requiring login */}
{/*
You can also protect a route like this:
<Route path="protected-route" {...permissionsComponent(isAuthenticated)(Component)}>
*/}
<Route {...permissionsComponent(isAuthenticated)() }>
<Route path="loginSuccess" getComponent={() => System.import('./containers/LoginSuccess/LoginSuccess')} />
<Route
path="chatFeathers"
getComponent={() => injectReducerAndRender(
{ chat: System.import('./redux/modules/chat') },
System.import('./containers/ChatFeathers/ChatFeathers')
)}
/>
/>
</Route>
{/* Routes disallow login */}
<Route {...permissionsComponent(isNotAuthenticated)() }>
<Route path="register" getComponent={() => System.import('./containers/Register/Register')} />
</Route>
{/* Routes */}
{/*<Route path="login" getComponent={() => System.import('./containers/Login/Login')} /> */}
<Route path="about" getComponent={() => System.import('./containers/About/About')} />
<Route path="profile" getComponent={() => System.import('./containers/profile/profile')} />
<Route path="cooperations" getComponent={() => System.import('./containers/Cooperations/Cooperations')} />
<Route path="cooperation/:slug" getComponent={() => System.import('./containers/Cooperation/Cooperation')} />
<Route
path="cooperation/:slug/edit"
getComponent={() => System.import('./containers/CooperationEdit/CooperationEdit')} />
<Route
path="cooperation-create"
getComponent={() => System.import('./containers/CooperationCreate/CooperationCreate')} />
<Route path="cooperation" getComponent={() => System.import('./containers/Cooperation/Cooperation')} />
<Route
path="survey"
getComponent={() => injectReducerAndRender(
{ survey: System.import('./redux/modules/survey') },
System.import('./containers/Survey/Survey')
)}
/>
/>
<Route
path="widgets"
getComponent={() => injectReducerAndRender(
{ widgets: System.import('./redux/modules/widgets') },
System.import('./containers/Widgets/Widgets')
)}
/>
/>
<Route path="chat" getComponent={() => System.import('./containers/Chat/Chat')} />
{/* Catch all route */}
<Route path="*" component={NotFound} status={404} />
</Route>
);
};
|
app/javascript/components/FieldShape/FieldShape.js
|
SumOfUs/Champaign
|
import React, { Component } from 'react';
import { map, pick } from 'lodash';
import SweetInput from '../SweetInput/SweetInput';
import SelectCountry from '../SelectCountry/SelectCountry';
import SweetSelect from '../SweetSelect/SweetSelect';
import Checkbox from '../Checkbox/Checkbox';
export default class FieldShape extends Component {
checkboxToggle(event) {
const checked = event.currentTarget.checked;
this.props.onChange && this.props.onChange(checked ? '1' : '0');
}
fieldProps() {
const { field, value } = this.props;
return {
name: field.name,
label: field.label,
disabled: field.disabled,
required: field.required,
value: value,
errorMessage: this.props.errorMessage,
onChange: this.props.onChange,
};
}
errorMessage(fieldProps) {
if (fieldProps.errorMessage)
return <span className="error-msg">{fieldProps.errorMessage}</span>;
}
renderParagraph(fieldProps) {
return (
<div>
<textarea
name={fieldProps.name}
value={fieldProps.value}
placeholder={fieldProps.label}
onChange={e =>
fieldProps.onChange && fieldProps.onChange(e.currentTarget.value)
}
className={fieldProps.errorMessage ? 'has-error' : ''}
maxLength="9999"
/>
{this.errorMessage(fieldProps)}
</div>
);
}
renderCheckbox(fieldProps) {
fieldProps.value = (fieldProps.value || '0').toString();
const checked =
fieldProps.value === '1' ||
fieldProps.value === 'checked' ||
fieldProps.value === 'true';
return (
<div>
<Checkbox checked={checked} onChange={this.checkboxToggle.bind(this)}>
{fieldProps.label}
</Checkbox>
{this.errorMessage(fieldProps)}
</div>
);
}
renderChoice(fieldProps) {
const { field } = this.props;
return (
<div className="radio-container">
<div className="form__instruction">{fieldProps.label}</div>
{field.choices &&
field.choices.map(choice => (
<label key={choice.id} htmlFor={choice.id}>
<input
id={choice.id}
name={fieldProps.name}
type="radio"
value={choice.value}
checked={choice.value === fieldProps.value}
onChange={event =>
this.props.onChange &&
this.props.onChange(event.currentTarget.value)
}
/>
{choice.label}
</label>
))}
{this.errorMessage(fieldProps)}
</div>
);
}
renderField(type) {
const fieldProps = this.fieldProps();
const {
field: { default_value, name, choices },
} = this.props;
switch (type) {
case 'email':
return <SweetInput type="email" {...fieldProps} />;
case 'phone':
case 'numeric':
return <SweetInput type="tel" {...fieldProps} />;
case 'country':
return <SelectCountry {...fieldProps} />;
case 'dropdown':
case 'select':
return (
<SweetSelect
{...fieldProps}
options={map(choices, c => pick(c, 'value', 'label'))}
/>
);
case 'hidden':
return <input type="hidden" name={name} value={default_value} />;
case 'checkbox':
return this.renderCheckbox(fieldProps);
case 'choice':
return this.renderChoice(fieldProps);
case 'instruction':
return <div className="form__instruction">{fieldProps.label}</div>;
case 'paragraph':
return this.renderParagraph(fieldProps);
case 'text':
case 'postal':
default:
return <SweetInput type="text" {...fieldProps} />;
}
}
render() {
return (
<div
key={this.props.field.name}
className={`MemberDetailsForm-field form__group action-form__field-container ${this
.props.className || ''}`}
>
{this.renderField(this.props.field.data_type)}
</div>
);
}
}
|
client/app/containers/LocaleToggle/index.js
|
KamillaKhabibrakhmanova/postcardsforchange-api
|
/*
*
* LanguageToggle
*
*/
import React from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import Toggle from 'components/Toggle';
import Wrapper from './Wrapper';
import messages from './messages';
import { appLocales } from '../../i18n';
import { changeLocale } from '../LanguageProvider/actions';
import { makeSelectLocale } from '../LanguageProvider/selectors';
export class LocaleToggle extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<Wrapper>
<Toggle value={this.props.locale} values={appLocales} messages={messages} onToggle={this.props.onLocaleToggle} />
</Wrapper>
);
}
}
LocaleToggle.propTypes = {
onLocaleToggle: React.PropTypes.func,
locale: React.PropTypes.string,
};
const mapStateToProps = createSelector(
makeSelectLocale(),
(locale) => ({ locale })
);
export function mapDispatchToProps(dispatch) {
return {
onLocaleToggle: (evt) => dispatch(changeLocale(evt.target.value)),
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(LocaleToggle);
|
src/components/table/TableQuickInput.js
|
metasfresh/metasfresh-webui-frontend
|
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import cx from 'classnames';
import { getLayout, patchRequest } from '../../api';
import { addNotification } from '../../actions/AppActions';
import { completeRequest, createInstance } from '../../actions/GenericActions';
import { parseToDisplay } from '../../utils/documentListHelper';
import RawWidget from '../widget/RawWidget';
class TableQuickInput extends Component {
// promise with patching for queuing form submission after patch is done
patchPromise;
constructor(props) {
super(props);
this.state = {
layout: null,
data: null,
id: null,
editedField: 0,
inProgress: false,
};
}
componentDidMount() {
this.initQuickInput();
}
componentDidUpdate() {
const { data, layout, editedField } = this.state;
if (data && layout) {
for (let i = 0; i < layout.length; i++) {
const item = layout[i].fields.map((elem) => data[elem.field] || -1);
if (!item[0].value) {
if (editedField !== i) {
this.setState(
{
editedField: i,
},
() => {
if (this.rawWidgets) {
let curWidget = this.rawWidgets[i];
if (curWidget && curWidget.focus) {
curWidget.focus();
}
}
}
);
}
break;
}
}
}
}
initQuickInput = () => {
const { dispatch, docType, docId, tabId, closeBatchEntry } = this.props;
const { layout } = this.state;
this.setState(
{
data: null,
},
() => {
createInstance('window', docType, docId, tabId, 'quickInput')
.then((instance) => {
this.setState({
data: parseToDisplay(instance.data.fieldsByName),
id: instance.data.id,
editedField: 0,
});
})
.catch((err) => {
if (err.response.status === 404) {
dispatch(
addNotification(
'Batch entry error',
'Batch entry is not available.',
5000,
'error'
)
);
closeBatchEntry();
}
});
!layout &&
getLayout('window', docType, tabId, 'quickInput', docId).then(
(layout) => {
this.setState({
layout: layout.data.elements,
});
}
);
}
);
};
handleChange = (field, value) => {
this.setState((prevState) => ({
data: Object.assign({}, prevState.data, {
[field]: Object.assign({}, prevState.data[field], {
value,
}),
}),
}));
};
handlePatch = (prop, value, callback) => {
const { docType, docId, tabId } = this.props;
const { id } = this.state;
this.setState(
{
inProgress: true,
},
() => {
this.patchPromise = new Promise((resolve) => {
patchRequest({
entity: 'window',
docType,
docId,
tabId,
property: prop,
value,
subentity: 'quickInput',
subentityId: id,
}).then((response) => {
const fields = response.data[0] && response.data[0].fieldsByName;
fields &&
Object.keys(fields).map((fieldName) => {
this.setState(
(prevState) => ({
data: Object.assign({}, prevState.data, {
[fieldName]: Object.assign(
{},
prevState.data[fieldName],
fields[fieldName]
),
}),
inProgress: false,
}),
() => {
if (callback) {
callback();
}
resolve();
}
);
});
});
});
}
);
};
renderFields = (layout, data, dataId, attributeType, quickInputId) => {
const { tabId, docType, forceHeight } = this.props;
const { inProgress } = this.state;
this.rawWidgets = [];
const layoutFieldsAmt = layout ? layout.length : 2;
const stylingLayout = [
{
formGroup: cx(`col-12`, {
'col-lg-5': layoutFieldsAmt === 2,
'col-xl-6': layoutFieldsAmt === 2,
'col-lg-4': layoutFieldsAmt === 3,
'col-xl-5': layoutFieldsAmt === 3,
}),
label: `col-12 col-lg-3 quickInput-label`,
field: `col-12 col-lg-9`,
},
{
formGroup: `col-12 col-lg-3 col-xl-3`,
label: `col-12 col-sm-4 col-lg-5 col-xl-4`,
field: `col-12 col-sm-8 col-lg-7 col-xl-8`,
},
{
formGroup: `col-12 col-lg-3 col-xl-2`,
label: `col-12 col-sm-9 col-lg-7`,
field: `col-12 col-sm-3 col-lg-5`,
},
];
if (data && layout) {
return layout.map((item, idx) => {
const widgetData = item.fields.map((elem) => data[elem.field] || -1);
const lastFormField = idx === layout.length - 1;
return (
<RawWidget
ref={(c) => {
if (c) {
this.rawWidgets.push(c);
}
}}
fieldFormGroupClass={stylingLayout[idx].formGroup}
fieldLabelClass={stylingLayout[idx].label}
fieldInputClass={stylingLayout[idx].field}
inProgress={inProgress}
entity={attributeType}
subentity="quickInput"
subentityId={quickInputId}
tabId={tabId}
windowType={docType}
widgetType={item.widgetType}
fields={item.fields}
dataId={dataId}
widgetData={widgetData}
gridAlign={item.gridAlign}
forceFullWidth={widgetData.length > 1}
forceHeight={forceHeight}
key={idx}
lastFormField={lastFormField}
caption={item.caption}
handlePatch={this.handlePatch}
handleChange={this.handleChange}
type="secondary"
autoFocus={idx === 0}
initialFocus={idx === 0}
/>
);
});
}
};
onSubmit = (e) => {
const { dispatch, docType, docId, tabId } = this.props;
const { id, data } = this.state;
e.preventDefault();
document.activeElement.blur();
if (!this.validateForm(data)) {
return dispatch(
addNotification(
'Error',
'Mandatory fields are not filled!',
5000,
'error'
)
);
}
return this.patchPromise
.then(() => {
return completeRequest(
'window',
docType,
docId,
tabId,
null,
'quickInput',
id
);
})
.then(() => {
this.initQuickInput();
});
};
validateForm = (data) => {
return !Object.keys(data).filter(
(key) => data[key].mandatory && !data[key].value
).length;
};
render() {
const { docId } = this.props;
const { data, layout, id } = this.state;
return (
<form
onSubmit={this.onSubmit}
className="row quick-input-container"
ref={(c) => (this.form = c)}
>
{this.renderFields(layout, data, docId, 'window', id)}
<div className="col-sm-12 col-md-3 col-lg-2 hint">
{`(Press 'Enter' to add)`}
</div>
<button type="submit" className="hidden-up" />
</form>
);
}
}
TableQuickInput.propTypes = {
dispatch: PropTypes.func.isRequired,
closeBatchEntry: PropTypes.func,
forceHeight: PropTypes.number,
docType: PropTypes.any,
docId: PropTypes.string,
tabId: PropTypes.string,
};
export default connect()(TableQuickInput);
|
client/modules/App/__tests__/Components/Header.spec.js
|
GTDev87/stylizer
|
import React from 'react';
import test from 'ava';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import { FormattedMessage } from 'react-intl';
import { Header } from '../../components/Header/Header';
import { intl } from '../../../../util/react-intl-test-helper';
const intlProp = { ...intl, enabledLanguages: ['en', 'fr'] };
test('renders the header properly', t => {
const router = {
isActive: sinon.stub().returns(true),
};
const wrapper = shallow(
<Header switchLanguage={() => {}} intl={intlProp} toggleAddPost={() => {}} />,
{
context: {
router,
intl,
},
}
);
t.truthy(wrapper.find('Link').first().containsMatchingElement(<FormattedMessage id="siteTitle" />));
t.is(wrapper.find('a').length, 1);
});
test('doesn\'t add post in pages other than home', t => {
const router = {
isActive: sinon.stub().returns(false),
};
const wrapper = shallow(
<Header switchLanguage={() => {}} intl={intlProp} toggleAddPost={() => {}} />,
{
context: {
router,
intl,
},
}
);
t.is(wrapper.find('a').length, 0);
});
test('toggleAddPost called properly', t => {
const router = {
isActive: sinon.stub().returns(true),
};
const toggleAddPost = sinon.spy();
const wrapper = shallow(
<Header switchLanguage={() => {}} intl={intlProp} toggleAddPost={toggleAddPost} />,
{
context: {
router,
intl,
},
}
);
wrapper.find('a').first().simulate('click');
t.truthy(toggleAddPost.calledOnce);
});
|
src/svg-icons/action/settings-overscan.js
|
ruifortes/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsOverscan = (props) => (
<SvgIcon {...props}>
<path d="M12.01 5.5L10 8h4l-1.99-2.5zM18 10v4l2.5-1.99L18 10zM6 10l-2.5 2.01L6 14v-4zm8 6h-4l2.01 2.5L14 16zm7-13H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16.01H3V4.99h18v14.02z"/>
</SvgIcon>
);
ActionSettingsOverscan = pure(ActionSettingsOverscan);
ActionSettingsOverscan.displayName = 'ActionSettingsOverscan';
ActionSettingsOverscan.muiName = 'SvgIcon';
export default ActionSettingsOverscan;
|
src/index.js
|
erdgabios/react-youtube-search
|
import _ from 'lodash';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail';
// Put here your youtube-api-search key
const API_KEY = '';
class App extends Component {
constructor(props){
super(props);
this.state = {
videos: [],
selectedVideo: null
};
this.videoSearch('surfboards');
}
videoSearch(term) {
YTSearch({key: API_KEY, term: term}, (videos) => {
this.setState({
videos: videos,
selectedVideo: videos[0]
});
});
}
render() {
const videoSearch = _.debounce((term) => { this.videoSearch(term) }, 300);
return (
<div>
<SearchBar onSearchTermChange={videoSearch} />
<VideoDetail video={this.state.selectedVideo} />
<VideoList
onVideoSelect={selectedVideo => this.setState({selectedVideo}) }
videos={this.state.videos} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container'));
|
src/components/subjects/BookSubjectIndex.js
|
great-design-and-systems/cataloguing-app
|
import { BookSubjectList } from './BookSubjectList';
import PropTypes from 'prop-types';
import React from 'react';
export const BookSubjectIndex = ({ removeSubject, managedBook, subjects }) => {
return (<div className="subjects">
<BookSubjectList
removeSubject={removeSubject}
subjects={subjects}
managedBook={managedBook} />
</div>);
};
BookSubjectIndex.propTypes = {
removeSubject: PropTypes.func.isRequired,
managedBook: PropTypes.object.isRequired,
subjects: PropTypes.array.isRequired
};
|
app/App.js
|
munir7/react
|
import React from 'react';
import Router from 'react-router';
import routes from './config/routes';
Router.run(routes, (Root, state) => {
React.render(<Root {...state} />, document.getElementById('app'));
});
|
packages/frontend/tests/components/common/Link/index.spec.js
|
ks888/LambStatus
|
import React from 'react'
import { Link as ReactRouterLink } from 'react-router'
import Link from 'components/common/Link'
import { shallow } from 'enzyme'
describe('Link', () => {
const generateProps = () => {
return {
link: 'https://github.com',
text: 'github'
}
}
it('should render the link', () => {
const props = generateProps()
const link = shallow(<Link {...props} />)
assert(link.find(ReactRouterLink).prop('to') === props.link)
assert(link.find(ReactRouterLink).contains(props.text))
})
})
|
src/Input.js
|
collinwu/react-bootstrap
|
import React from 'react';
import InputBase from './InputBase';
import * as FormControls from './FormControls';
import deprecationWarning from './utils/deprecationWarning';
class Input extends InputBase {
render() {
if (this.props.type === 'static') {
deprecationWarning('Input type=static', 'StaticText');
return <FormControls.Static {...this.props} />;
}
return super.render();
}
}
Input.propTypes = {
type: React.PropTypes.string
};
export default Input;
|
benchmarks/src/index.js
|
rofrischmann/fela
|
import App from './app/App'
import impl from './impl'
import Tree from './cases/Tree'
import SierpinskiTriangle from './cases/SierpinskiTriangle'
import React from 'react'
import ReactDOM from 'react-dom'
const implementations = impl
const packageNames = Object.keys(implementations)
const createTestBlock = (fn) => {
return packageNames.reduce((testSetups, packageName) => {
const { name, components, version } = implementations[packageName]
const {
Component,
getComponentProps,
sampleCount,
Provider,
benchmarkType,
} = fn(components)
testSetups[packageName] = {
Component,
getComponentProps,
sampleCount,
Provider,
benchmarkType,
version,
name,
}
return testSetups
}, {})
}
const tests = {
'Mount deep tree': createTestBlock((components) => ({
benchmarkType: 'mount',
Component: Tree,
getComponentProps: () => ({
breadth: 2,
components,
depth: 7,
id: 0,
wrap: 1,
}),
Provider: components.Provider,
sampleCount: 200,
})),
'Mount wide tree': createTestBlock((components) => ({
benchmarkType: 'mount',
Component: Tree,
getComponentProps: () => ({
breadth: 6,
components,
depth: 3,
id: 0,
wrap: 2,
}),
Provider: components.Provider,
sampleCount: 200,
})),
'Update dynamic styles': createTestBlock((components) => ({
benchmarkType: 'update',
Component: SierpinskiTriangle,
getComponentProps: ({ cycle }) => {
return { components, s: 200, renderCount: cycle, x: 0, y: 0 }
},
Provider: components.Provider,
sampleCount: 300,
})),
}
ReactDOM.render(<App tests={tests} />, document.querySelector('.root'))
|
src/ElevationCatalog.js
|
material-components/material-components-web-catalog
|
import React, { Component } from 'react';
import ComponentCatalogPanel from './ComponentCatalogPanel.js';
import './styles/ElevationCatalog.scss';
const MAX_ELEVATION_LEVELS = 24;
const ElevationCatalog = () => {
const description = 'Elevation is the relative depth, or distance, between two surfaces along the z-axis.';
return (
<ComponentCatalogPanel
hero={<ElevationHero />}
title='Elevation'
description={description}
designLink='https://material.io/go/design-elevation'
docsLink='https://material.io/components/web/catalog/elevation/'
sourceLink='https://github.com/material-components/material-components-web/tree/master/packages/mdc-elevation'
demos={<ElevationDemos />}
/>
);
};
export class ElevationHero extends Component {
render() {
return (
<div className='elevation-hero'>
<div className='elevation-demo-surface mdc-elevation--z0'>
Flat 0dp
</div>
<div className='elevation-demo-surface mdc-elevation--z8'>
Raised 8dp
</div>
<div className='elevation-demo-surface mdc-elevation--z16'>
Raised 16dp
</div>
</div>
);
}
}
class ElevationDemos extends Component {
render() {
return (
<div className='elevation-demo-container'>
{this.getElevationDemos()}
</div>
);
}
getElevationDemos() {
let demos = [];
for(let x = 0; x <= MAX_ELEVATION_LEVELS; x++) {
demos.push(
<div key={'elevation' + x} className={'elevation-demo-surface mdc-elevation--z' + x}>
{x}dp
</div>);
}
return demos;
}
}
export default ElevationCatalog;
|
assets/js/components/Item.js
|
scottocorp/react-todos
|
import React from 'react';
var createReactClass = require('create-react-class');
const Item = createReactClass({
handleOnChange(e) {
const content = e.target.value;
this.props.updateTodo(this.props.todo.id, content);
},
handleKeyUp(e) {
if (e.keyCode == 13) {
this.close(e.target.value);
}
},
handleOnBlur(e) {
this.close(e.target.value);
},
close(value) {
if (!value) {
this.props.removeTodo(this.props.todo.id)
} else {
this.props.viewTodo(this.props.todo.id)
}
},
componentDidUpdate() {
if (this.props.todo.editing){
this.refs.input.focus();
}
},
render() {
const { todo, i } = this.props;
var style = (todo.editing) ? "editing" : "";
style = (todo.completed) ? style + " completed" : style;
style = style.trim();
return (
<li className={style} onDoubleClick={this.props.editTodo.bind(null, todo.id)} >
<div className="view">
<input className="toggle" checked={ todo.completed } type="checkbox" onClick={this.props.toggleComplete.bind(null, todo.id)} />
<label>{ todo.content }</label>
<button className="destroy" onClick={this.props.removeTodo.bind(null, todo.id)}></button>
</div>
<input type="text" name="content" className="edit" ref="input" value={ todo.content } onChange={this.handleOnChange} onKeyUp={this.handleKeyUp} onBlur={this.handleOnBlur} />
</li>
)
}
});
export default Item;
|
src/svg-icons/notification/confirmation-number.js
|
mmrtnz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationConfirmationNumber = (props) => (
<SvgIcon {...props}>
<path d="M22 10V6c0-1.11-.9-2-2-2H4c-1.1 0-1.99.89-1.99 2v4c1.1 0 1.99.9 1.99 2s-.89 2-2 2v4c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-4c-1.1 0-2-.9-2-2s.9-2 2-2zm-9 7.5h-2v-2h2v2zm0-4.5h-2v-2h2v2zm0-4.5h-2v-2h2v2z"/>
</SvgIcon>
);
NotificationConfirmationNumber = pure(NotificationConfirmationNumber);
NotificationConfirmationNumber.displayName = 'NotificationConfirmationNumber';
NotificationConfirmationNumber.muiName = 'SvgIcon';
export default NotificationConfirmationNumber;
|
js/components/Nav.react.js
|
Karaja-Naji/frontEndMusic
|
/**
*
* Nav.react.js
*
* This component renders the navigation bar
*
*/
import React, { Component } from 'react';
import { Link } from 'react-router';
import { logout } from '../actions/AppActions';
import LoadingButton from './LoadingButton.react';
class Nav extends Component {
render() {
// Render either the Log In and register buttons, or the logout button
// based on the current authentication state.
const navButtons = this.props.loggedIn ? (
<div>
<Link to="/dashboard" className="btn btn--dash btn--nav">Dashboard</Link>
{this.props.currentlySending ? (
<LoadingButton className="btn--nav" />
) : (
<a href="#" className="btn btn--login btn--nav" onClick={::this._logout}>Logout</a>
)}
</div>
) : (
<div>
<Link to="/register" className="btn btn--login btn--nav">Register</Link>
<Link to="/login" className="btn btn--login btn--nav">Login</Link>
</div>
);
return(
<div className="nav">
<div className="nav__wrapper">
<Link to="/" className="nav__logo-wrapper"><h1 className="nav__logo">Login Flow</h1></Link>
<Link to="/blogs" className="btn btn--login btn--nav">Blogs</Link>
<Link to="/products" className="btn btn--login btn--nav">Products</Link>
{ navButtons }
</div>
</div>
);
}
_logout() {
this.props.dispatch(logout());
}
}
Nav.propTypes = {
loggedIn: React.PropTypes.bool.isRequired,
currentlySending: React.PropTypes.bool.isRequired
}
export default Nav;
|
client/node_modules/uu5g03/doc/main/client/src/data/source/uu5-forms-slider.js
|
UnicornCollege/ucl.itkpd.configurator
|
import React from 'react';
import Environment from '../environment/environment.js';
import {BaseMixin, ElementaryMixin, ContentMixin, Tools} from './../common/common.js';
import {Glyphicon, Slider} from './../bricks/bricks.js';
import InputMixin from './input-mixin.js';
import Number from './number.js';
import './slider.less';
export default React.createClass({
mixins: [
BaseMixin,
ElementaryMixin,
ContentMixin,
InputMixin
],
statics: {
tagName: 'UU5.Forms.Slider',
classNames: {
main: 'uu5-forms-slider',
inputGroup: 'uu5-forms-slider-input-group',
slider: 'uu5-forms-slider-slider',
number: 'uu5-forms-slider-number'
}
},
propTypes: {
colorSchema: React.PropTypes.oneOf(Environment.colorSchema),
// TODO
//position: React.PropTypes.oneOf(['horizontal', 'vertical']),
min: React.PropTypes.number,
max: React.PropTypes.number,
step: React.PropTypes.number,
value: React.PropTypes.number,
onChange: React.PropTypes.func,
onChanged: React.PropTypes.func
},
// Setting defaults
getDefaultProps: function () {
return {
colorSchema: 'primary',
//position: 'horizontal',
min: 0,
max: 10,
step: 1,
value: null,
onChanged: null
};
},
componentWillMount: function () {
this.setState({ value: typeof this.props.value === 'number' ? this.props.value : this.props.min });
},
// Interface
// Overriding Functions
setValue_: function (value, setStateCallback, options) {
options = options || {};
options.feedback = options.feedback || 'initial';
options.message = options.message || '';
options.value = value;
this.setState(options, setStateCallback);
return this;
},
// Component Specific Helpers
// _onChange: function (e) {
// if (!this.isDisabled()) {
// var value = !this.getValue();
// var newState = this._validateValue(value);
//
// if (newState) {
// this.setState(newState);
// } else {
// if (this.props.onChange) {
// this.props.onChange({ value: value, input: this, event: e });
// } else {
// this.setState({ value: value });
// }
// }
// }
// return this;
// },
_getMainAttrs: function () {
return this.getInputMainAttrs();
},
_getInputGroupAttrs: function () {
return {
className: this.getClassName().inputGroup
};
},
_getSliderProps: function () {
return {
name: this.getName(),
className: this.getClassName().slider,
colorSchema: this.props.colorSchema,
//position: 'horizontal',
min: this.props.min,
max: this.props.max,
step: this.props.step,
value: this.getValue() === null ? this.props.min : this.getValue(),
content: this.getContent(),
onChange: this._onChange,
onChanged: this.props.onChanged,
disabled: this.isDisabled()
};
},
_getNumberProps: function () {
var value = this.getValue();
value = value > this.props.max ?
this.props.max :
(value < this.props.min) ? this.props.min : value;
return {
className: this.getClassName().number,
min: this.props.min,
max: this.props.max,
value: this.getValue(),
onChange: this._onChange,
onBlur: function (opt) {
if (this.getValue() < this.props.min) {
opt.component.setValue(this.props.min);
} else if (this.getValue() > this.props.max) {
opt.component.setValue(this.props.max);
}
}.bind(this),
disabled: this.isDisabled(),
onChangeFeedback: this._onChangeNumberFeedback
};
},
_getOnChanged: function (value, e) {
var onChanged;
if (typeof this.props.onChanged === 'function') {
var slider = this;
onChanged = function () {
slider.props.onChanged({ value: value, component: slider, event: e });
};
}
return onChanged;
},
_onChange: function (opt) {
if (!this.isDisabled()) {
if (typeof this.props.onChange == 'function') {
this.props.onChange(Tools.merge({}, opt, { component: this }));
} else {
this.setFeedback('initial', '', opt.value, this._getOnChanged(opt.value, opt.event));
}
}
return this;
},
_onChangeNumberFeedback: function (opt) {
this.setValue(opt.value ? +opt.value : null, opt.callback);
//this.setFeedback(opt.feedback, opt.message, opt.value ? +opt.value : null, opt.callback);
return this;
},
// Render
render: function () {
return (
<div {...this._getMainAttrs()}>
{this.getLabelChild()}
<div {...this.getInputWrapperAttrs()}>
<div {...this._getInputGroupAttrs()}>
<Slider {...this._getSliderProps()}>
{this.props.children && React.Children.toArray(this.props.children)}
</Slider>
<Number {...this._getNumberProps()} />
</div>
{this.getMessageChild()}
</div>
</div>
);
}
});
|
packages/editor/src/components/Controls/FontFamily/FontFamilyLayout.js
|
boldr/boldr
|
/* eslint-disable react/no-array-index-key */
/* @flow */
import React from 'react';
import type { Node } from 'react';
import cn from 'classnames';
import { Dropdown, DropdownOption } from '../../Dropdown';
import type { FontFamilyConfig } from '../../../core/config';
export type Props = {
expanded: boolean,
onExpandEvent: Function,
doExpand: Function,
doCollapse: Function,
onChange: Function,
config: FontFamilyConfig,
currentState: any,
};
type State = {
defaultFontFamily: string,
};
class FontFamilyLayout extends React.Component<Props, State> {
state = {
defaultFontFamily: undefined,
};
componentDidMount(): void {
const editorElm = document.getElementsByClassName('DraftEditor-root');
if (editorElm && editorElm.length > 0) {
const styles = window.getComputedStyle(editorElm[0]);
const defaultFontFamily = styles.getPropertyValue('font-family');
this.setDefaultFam(defaultFontFamily);
}
}
setDefaultFam = defaultFont => {
this.setState({
defaultFontFamily: defaultFont,
});
};
props: Props;
render(): Node {
const { defaultFontFamily } = this.state;
const {
config: { options, title },
onChange,
expanded,
doCollapse,
onExpandEvent,
doExpand,
} = this.props;
let { currentState: { fontFamily: currentFontFamily } } = this.props;
currentFontFamily =
currentFontFamily ||
(options &&
defaultFontFamily &&
options.some(opt => opt.toLowerCase() === defaultFontFamily.toLowerCase()) &&
defaultFontFamily);
return (
<div className={cn('be-ctrl__group')} aria-label="be-fontfamily-control">
<Dropdown
onChange={onChange}
expanded={expanded}
doExpand={doExpand}
ariaLabel="be-dropdown-fontfamily-control"
doCollapse={doCollapse}
onExpandEvent={onExpandEvent}
title={title}>
<span className={cn('be-fontfamily__ph')}>{currentFontFamily || 'Font Family'}</span>
{options.map((family, index) => (
<DropdownOption active={currentFontFamily === family} value={family} key={index}>
{family}
</DropdownOption>
))}
</Dropdown>
</div>
);
}
}
export default FontFamilyLayout;
|
docs/app/Examples/modules/Accordion/Usage/AccordionExamplePanelsPropWithCustomTitleAndContent.js
|
aabustamante/Semantic-UI-React
|
import React from 'react'
import { Accordion, Label, Message } from 'semantic-ui-react'
import faker from 'faker'
import _ from 'lodash'
const panels = _.times(3, i => ({
key: `panel-${i}`,
title: <Label color='blue' content={faker.lorem.sentence()} />,
content: (
<Message
info
header={faker.lorem.sentence()}
content={faker.lorem.paragraph()}
/>
),
}))
const AccordionExamplePanelsPropWithCustomTitleAndContent = () => (
<Accordion panels={panels} />
)
export default AccordionExamplePanelsPropWithCustomTitleAndContent
|
node_modules/npm/docs/src/components/DocLinks.js
|
giovannic/giovannic.github.com
|
import React from 'react'
import styled from 'styled-components'
import {StaticQuery, graphql} from 'gatsby'
import {Flex} from 'rebass'
import {SidebarLink} from './links'
import Accordion from './Accordion'
const LinkDesc = styled.span`
font-size: 11px;
line-height: 1.5;
text-transform: lowercase;
display: block;
font-weight: 400;
color: ${(props) => props.theme.colors.darkGray};
`
const DocLinks = ({data}) => {
const linkInfo = data.allMarkdownRemark.nodes
const sections = ['cli-commands', 'configuring-npm', 'using-npm']
let sortedData = {}
sections.map((section) => (
sortedData[section] = linkInfo.filter(function (item) {
return item.frontmatter.section === section
})
))
return sections.map((section, index) => (
<Accordion key={index} section={section}>
{sortedData[section].map((linkData, index) => {
const title = section === 'cli-commands'
? linkData.frontmatter.title.replace(/(npm-)+([a-zA-Z\\.-]*)/, 'npm $2')
: linkData.frontmatter.title
return (
<Flex flexDirection='column' key={index}>
<SidebarLink
to={`${linkData.fields.slug}`}
activeClassName='active-sidebar-link'
>
{title}
<LinkDesc>{linkData.frontmatter.description}</LinkDesc>
</SidebarLink>
</Flex>
)
})
}
</Accordion>
))
}
export default props => (
<StaticQuery
query={graphql`
query sortedLinkData {
allMarkdownRemark(sort: {fields: frontmatter___title}) {
nodes {
fields {
slug
}
frontmatter {
description
section
title
}
}
}
}
`}
render={data => <DocLinks data={data} {...props} />}
/>
)
|
app/components/shared/filtersControl.js
|
nypl-registry/browse
|
import React from 'react'
import { Link } from 'react-router'
import { stringify } from 'qs'
const FiltersControl = React.createClass({
propTypes () {
return {
}
},
queryStringWithoutFilter (field, value) {
// copy query & filters:
var newQuery = Object.assign({}, this.props.query)
newQuery.filters = Object.assign({}, this.props.query.filters)
// If filter is an array of values:
if (typeof newQuery.filters[field] === 'object') {
// Remove value from array:
newQuery.filters[field] = newQuery.filters[field].filter((otherValue) => otherValue !== value)
// Remove field entirely if array empty:
if (newQuery.filters[field].length === 0) delete newQuery.filters[field]
} else {
// Remove field entirely
delete newQuery.filters[field]
}
return newQuery
},
render () {
var links = []
Object.keys(this.props.query.filters).forEach((field, fieldIndex) => {
// var query = Object.assign({ filters: {} }, this.props.query)
var values = []
if ((typeof this.props.query.filters[field]) === 'object') values = this.props.query.filters[field]
else values = [this.props.query.filters[field]]
values.forEach((v, i) => {
var newQuery = this.queryStringWithoutFilter(field, v)
var url = [this.props.basePath, '?', stringify(newQuery)].join('')
links.push(<li key={[fieldIndex, i].join('-')}><Link to={url}><span className='nypl-icon-circle-x'/>{field}: {v}</Link></li>)
})
})
return (
<ul className='filters-control'>
{links}
</ul>
)
}
})
export default FiltersControl
|
app/components/__tests__/CodeBttns-test.js
|
andrewmoon1/moon.codes
|
/* eslint no-unused-vars: 0 */ // since fetch is needed but not used
import React from 'react';
import { polyfill } from 'es6-promise';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import ReactTestUtils from 'react-dom/test-utils';
import { shallow, mount } from 'enzyme';
import { CodeBttns } from '../CodeBttns';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
function setup(authenticated, edit) {
const props = {
newArea: jasmine.createSpy('newArea'),
message: jasmine.createSpy('message'),
update: jasmine.createSpy('edit'),
submit: jasmine.createSpy('edit'),
authenticated: authenticated || false,
code: {
areas: [
'textArea',
'codeMirror',
],
savedAreas: {
'text-0': 'Enter Description Here',
'mirror-1': 'Enter Your Code'
},
title: 'Enter Title Here',
edit: edit || ''
},
router: {
push: () => {},
}
}
const enzymeWrapper = mount(<CodeBttns {...props} />)
return {
props,
enzymeWrapper
}
}
describe('<CodeBttns />', () => {
it('should render self', () => {
const { enzymeWrapper } = setup();
expect(enzymeWrapper.find('CodeBttns')).toBeDefined();
expect(enzymeWrapper.find('#areaBttn').text()).toEqual('Insert Text Area');
expect(enzymeWrapper.find('#submitBttn')).toBeDefined();
expect(enzymeWrapper.find('#mirrorBttn').text()).toEqual('Insert Code Mirror');
});
describe('Textarea Button', () => {
it('should call newArea with textArea', () => {
const { enzymeWrapper, props } = setup();
const areaBttn = enzymeWrapper.find('#areaBttn');
areaBttn.simulate('click');
expect(props.newArea).toHaveBeenCalledWith('textArea');
});
});
describe('Mirror Button', () => {
it('should call newArea with codeMirror', () => {
const { enzymeWrapper, props } = setup();
const mirrorBttn = enzymeWrapper.find('#mirrorBttn');
mirrorBttn.simulate('click');
expect(props.newArea).toHaveBeenCalledWith('codeMirror');
});
});
describe('Submit Button', () => {
it('should call message if not authenticated', () => {
const { enzymeWrapper, props } = setup(false);
const submit = enzymeWrapper.find('#submitBttn');
const msg = 'Enter Title Here was not saved, you are not authorized';
submit.simulate('click');
expect(props.message).toHaveBeenCalledWith(msg);
});
it('should call submit if authenticated and not editing code', () => {
const { enzymeWrapper, props } = setup(true);
const submit = enzymeWrapper.find('#submitBttn');
submit.simulate('click');
expect(props.submit).toHaveBeenCalledWith(props.code);
});
it('should call update if authenticated and editing code', () => {
const { enzymeWrapper, props } = setup(true, 'Enter Title Here');
const submit = enzymeWrapper.find('#submitBttn');
submit.simulate('click');
expect(props.update).toHaveBeenCalledWith(props.code);
});
});
});
|
admin/client/components/PopoutBody.js
|
nickhsine/keystone
|
import React from 'react';
import blacklist from 'blacklist';
import classnames from 'classnames';
var PopoutBody = React.createClass({
displayName: 'PopoutBody',
propTypes: {
children: React.PropTypes.node.isRequired,
className: React.PropTypes.string,
scrollable: React.PropTypes.bool,
},
render () {
let className = classnames('Popout__body', {
'Popout__scrollable-area': this.props.scrollable,
}, this.props.className);
let props = blacklist(this.props, 'className', 'scrollable');
return <div className={className} {...props} />;
},
});
module.exports = PopoutBody;
|
examples/todomvc/containers/App.js
|
bloodyowl/redux-devtools
|
import React, { Component } from 'react';
import TodoApp from './TodoApp';
import { createStore, combineReducers, compose } from 'redux';
import { devTools, persistState } from 'redux-devtools';
import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react';
import { Provider } from 'react-redux';
import * as reducers from '../reducers';
const finalCreateStore = compose(
devTools(),
persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)),
createStore
);
const reducer = combineReducers(reducers);
const store = finalCreateStore(reducer);
export default class App extends Component {
render() {
return (
<div>
<Provider store={store}>
{() => <TodoApp /> }
</Provider>
<DebugPanel top right bottom>
<DevTools store={store}
monitor={LogMonitor} />
</DebugPanel>
</div>
);
}
}
|
hello_world/src/components/Geocities.react.js
|
rpearce/react-form-steps-example
|
import React, { Component } from 'react';
class Geocities extends Component {
render() {
return (
<div>
<div style={ { textAlign: 'center', marginTop: '50px' } }>
<img src="http://www.wonder-tonic.com/geocitiesizer/images/genie.gif" />
<img src="http://www.wonder-tonic.com/geocitiesizer/images/dancingbaby.gif" />
</div>
<marquee>
<h1>Welcome to the Internet</h1>
</marquee>
<marquee>
<h2>I will be your guide</h2>
</marquee>
<div style={ { textAlign: 'center', fontSize: '24px' } }>
@RobertWPearce<br /><br />
The Iron Yard.com
</div>
<div dangerouslySetInnerHTML={ this.nyanCat() }></div>
</div>
);
}
nyanCat() {
return { __html: '<marquee direction="right"><img src="https://38.media.tumblr.com/8210fd413c5ce209678ef82d65731443/tumblr_mjphnqLpNy1s5jjtzo1_400.gif" /></marquee>' };
}
}
export default Geocities;
|
node_modules/react-bootstrap/es/utils/ValidComponentChildren.js
|
acalabano/get-committed
|
// TODO: This module should be ElementChildren, and should use named exports.
import React from 'react';
/**
* Iterates through children that are typically specified as `props.children`,
* but only maps over children that are "valid components".
*
* The mapFunction provided index will be normalised to the components mapped,
* so an invalid component would not increase the index.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func.
* @param {*} context Context for func.
* @return {object} Object containing the ordered map of results.
*/
function map(children, func, context) {
var index = 0;
return React.Children.map(children, function (child) {
if (!React.isValidElement(child)) {
return child;
}
return func.call(context, child, index++);
});
}
/**
* Iterates through children that are "valid components".
*
* The provided forEachFunc(child, index) will be called for each
* leaf child with the index reflecting the position relative to "valid components".
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func.
* @param {*} context Context for context.
*/
function forEach(children, func, context) {
var index = 0;
React.Children.forEach(children, function (child) {
if (!React.isValidElement(child)) {
return;
}
func.call(context, child, index++);
});
}
/**
* Count the number of "valid components" in the Children container.
*
* @param {?*} children Children tree container.
* @returns {number}
*/
function count(children) {
var result = 0;
React.Children.forEach(children, function (child) {
if (!React.isValidElement(child)) {
return;
}
++result;
});
return result;
}
/**
* Finds children that are typically specified as `props.children`,
* but only iterates over children that are "valid components".
*
* The provided forEachFunc(child, index) will be called for each
* leaf child with the index reflecting the position relative to "valid components".
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func.
* @param {*} context Context for func.
* @returns {array} of children that meet the func return statement
*/
function filter(children, func, context) {
var index = 0;
var result = [];
React.Children.forEach(children, function (child) {
if (!React.isValidElement(child)) {
return;
}
if (func.call(context, child, index++)) {
result.push(child);
}
});
return result;
}
function find(children, func, context) {
var index = 0;
var result = undefined;
React.Children.forEach(children, function (child) {
if (result) {
return;
}
if (!React.isValidElement(child)) {
return;
}
if (func.call(context, child, index++)) {
result = child;
}
});
return result;
}
function every(children, func, context) {
var index = 0;
var result = true;
React.Children.forEach(children, function (child) {
if (!result) {
return;
}
if (!React.isValidElement(child)) {
return;
}
if (!func.call(context, child, index++)) {
result = false;
}
});
return result;
}
function some(children, func, context) {
var index = 0;
var result = false;
React.Children.forEach(children, function (child) {
if (result) {
return;
}
if (!React.isValidElement(child)) {
return;
}
if (func.call(context, child, index++)) {
result = true;
}
});
return result;
}
function toArray(children) {
var result = [];
React.Children.forEach(children, function (child) {
if (!React.isValidElement(child)) {
return;
}
result.push(child);
});
return result;
}
export default {
map: map,
forEach: forEach,
count: count,
find: find,
filter: filter,
every: every,
some: some,
toArray: toArray
};
|
src/routes/admin/index.js
|
zsu13579/whatsgoinontonight
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Layout from '../../components/Layout';
const title = 'Admin Page';
const isAdmin = false;
export default {
path: '/admin',
async action() {
if (!isAdmin) {
return { redirect: '/login' };
}
const Admin = await require.ensure([], require => require('./Admin').default, 'admin');
return {
title,
chunk: 'admin',
component: <Layout><Admin title={title} /></Layout>,
};
},
};
|
app/static/src/diagnostic/TestTypeResultForm_modules/PolymerisationDegreeTestForm.js
|
vsilent/Vision
|
import React from 'react';
import FormControl from 'react-bootstrap/lib/FormControl';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import Button from 'react-bootstrap/lib/Button';
import Panel from 'react-bootstrap/lib/Panel';
import {findDOMNode} from 'react-dom';
import {hashHistory} from 'react-router';
import {Link} from 'react-router';
import HelpBlock from 'react-bootstrap/lib/HelpBlock';
import {NotificationContainer, NotificationManager} from 'react-notifications';
const TextField = React.createClass({
render: function() {
var label = (this.props.label != null) ? this.props.label: "";
var name = (this.props.name != null) ? this.props.name: "";
var value = (this.props.value != null) ? this.props.value: "";
return (
<FormGroup validationState={this.props.errors[name] ? 'error' : null}>
<FormControl type="text"
placeholder={label}
name={name}
value={value}
data-type={this.props["data-type"]}
data-len={this.props["data-len"]}
/>
<HelpBlock className="warning">{this.props.errors[name]}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
);
}
});
const CheckBox = React.createClass({
render: function () {
var name = (this.props.name != null) ? this.props.name : "";
return (
<Checkbox name={name}>
<span className="glyphicon glyphicon-menu-left">
</span>
</Checkbox>
);
}
});
var PolymerisationDegreeTestForm = React.createClass({
getInitialState: function () {
return {
loading: false,
errors: {},
fields: [
'phase_a1', 'phase_a2', 'phase_a3', 'phase_b1', 'phase_b2',
'phase_b3', 'phase_c1', 'phase_c2', 'phase_c3',
'lead_a', 'lead_b', 'lead_c', 'lead_n',
'winding'
]
}
},
componentDidMount: function () {
var source = '/api/v1.0/' + this.props.tableName + '/?test_result_id=' + this.props.testResultId;
this.serverRequest = $.authorizedGet(source, function (result) {
var res = (result['result']);
if (res.length > 0) {
var fields = this.state.fields;
fields.push('id');
var data = res[0];
var state = {};
for (var i = 0; i < fields.length; i++) {
var key = fields[i];
if (data.hasOwnProperty(key)) {
state[key] = data[key];
}
}
this.setState(state);
}
}.bind(this), 'json');
},
_create: function () {
var fields = this.state.fields;
var data = {test_result_id: this.props.testResultId};
var url = '/api/v1.0/' + this.props.tableName + '/';
for (var i = 0; i < fields.length; i++) {
var key = fields[i];
data[key] = this.state[key];
}
if ('id' in this.state) {
url += this.state['id'];
delete data.id;
}
return $.authorizedAjax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
beforeSend: function () {
this.setState({loading: true});
}.bind(this)
})
},
_onSubmit: function (e) {
e.preventDefault();
// Do not propagate the submit event of the main form
e.stopPropagation();
if (!this.is_valid()){
NotificationManager.error('Please correct the errors');
e.stopPropagation();
return false;
}
var xhr = this._create();
xhr.done(this._onSuccess)
.fail(this._onError)
.always(this.hideLoading)
},
hideLoading: function () {
this.setState({loading: false});
},
_onSuccess: function (data) {
// this.setState(this.getInitialState());
NotificationManager.success('Test values have been saved successfully.');
if ($.isNumeric(data.result)) {
this.setState({id: data.result});
}
},
_onError: function (data) {
var message = "Failed to create";
var res = data.responseJSON;
if (res.message) {
message = data.responseJSON.message;
}
if (res.error) {
// We get list of errors
if (data.status >= 500) {
message = res.error.join(". ");
} else if (res.error instanceof Object){
// We get object of errors with field names as key
for (var field in res.error) {
var errorMessage = res.error[field];
if (Array.isArray(errorMessage)) {
errorMessage = errorMessage.join(". ");
}
res.error[field] = errorMessage;
}
this.setState({
errors: res.error
});
} else {
message = res.error;
}
}
NotificationManager.error(message);
},
_onChange: function (e) {
var state = {};
if (e.target.type == 'checkbox') {
state[e.target.name] = e.target.checked;
} else if (e.target.type == 'select-one') {
state[e.target.name] = e.target.value;
} else {
state[e.target.name] = e.target.value;
}
var errors = this._validate(e);
state = this._updateFieldErrors(e.target.name, state, errors);
this.setState(state);
},
_validate: function (e) {
var errors = [];
var error;
error = this._validateFieldType(e.target.value, e.target.getAttribute("data-type"));
if (error){
errors.push(error);
}
error = this._validateFieldLength(e.target.value, e.target.getAttribute("data-len"));
if (error){
errors.push(error);
}
return errors;
},
_validateFieldType: function (value, type){
var error = "";
if (type != undefined && value){
var typePatterns = {
"float": /^(-|\+?)[0-9]+(\.)?[0-9]*$/
};
if (!typePatterns[type].test(value)){
error = "Invalid " + type + " value";
}
}
return error;
},
_validateFieldLength: function (value, length){
var error = "";
if (value && length){
if (value.length > length){
error = "Value should be maximum " + length + " characters long"
}
}
return error;
},
_updateFieldErrors: function (fieldName, state, errors){
// Clear existing errors related to the current field as it has been edited
state.errors = this.state.errors;
delete state.errors[fieldName];
// Update errors with new ones, if present
if (Object.keys(errors).length){
state.errors[fieldName] = errors.join(". ");
}
return state;
},
is_valid: function () {
return (Object.keys(this.state.errors).length <= 0);
},
_formGroupClass: function (field) {
var className = "form-group ";
if (field) {
className += " has-error"
}
return className;
},
render: function () {
return (
<div className="form-container">
<form method="post" action="#" onSubmit={this._onSubmit} onChange={this._onChange}>
<div className="row">
<div className="col-md-3 col-md-offset-3">
<Panel header="Primary">
</Panel>
</div>
<div className="col-md-3">
<Panel header="Secondary">
</Panel>
</div>
<div className="col-md-3">
<Panel header="Connection">
</Panel>
</div>
</div>
<div className="row">
<div className="col-md-2 col-md-offset-1">
<b>Phase A</b>
</div>
<div className="col-md-3">
<TextField label="phase_a1" name="phase_a1" value={this.state.phase_a1}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label="phase_a2" name="phase_a2" value={this.state.phase_a2}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label="phase_a3" name="phase_a3" value={this.state.phase_a3}
errors={this.state.errors} data-type="float"/>
</div>
</div>
<div className="row">
<div className="col-md-2 col-md-offset-1">
<b>Phase B</b>
</div>
<div className="col-md-3">
<TextField label="phase_b1" name="phase_b1" value={this.state.phase_b1}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label="phase_b2" name="phase_b2" value={this.state.phase_b2}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label="phase_b3" name="phase_b3" value={this.state.phase_b3}
errors={this.state.errors} data-type="float"/>
</div>
</div>
<div className="row">
<div className="col-md-2 col-md-offset-1">
<b>Phase C</b>
</div>
<div className="col-md-3">
<TextField label="phase_c1" name="phase_c1" value={this.state.phase_c1}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label="phase_c2" name="phase_c2" value={this.state.phase_c2}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label="phase_c3" name="phase_c3" value={this.state.phase_c3}
errors={this.state.errors} data-type="float"/>
</div>
</div>
<div className="row">
<div className="col-md-12 ">
<Panel header="Lead & Winding">
</Panel>
</div>
</div>
<div className="row">
<div className="col-md-1">
<b>Lead A</b>
</div>
<div className="col-md-2">
<TextField label="lead_a" name="lead_a" value={this.state.lead_a}
errors={this.state.errors} data-type="float" data-len="4"/>
</div>
<div className="col-md-1">
<b>Lead B</b>
</div>
<div className="col-md-2">
<TextField label="lead_b" name="lead_b" value={this.state.lead_b}
errors={this.state.errors} data-type="float" data-len="4"/>
</div>
<div className="col-md-1">
<b>Lead C</b>
</div>
<div className="col-md-2">
<TextField label="lead_c" name="lead_c" value={this.state.lead_c}
errors={this.state.errors} data-type="float" data-len="4"/>
</div>
<div className="col-md-1">
<b>Lead N</b>
</div>
<div className="col-md-2">
<TextField label="lead_n" name="lead_n" value={this.state.lead_n}
errors={this.state.errors} data-type="float" data-len="4"/>
</div>
</div>
<div className="row">
<div className="col-md-3 pull-right">
<b>Winding</b>
<TextField label="winding" name="winding" value={this.state.winding}
errors={this.state.errors} data-type="float" data-len="4"/>
</div>
</div>
<div className="row">
<div className="col-md-12 ">
<Button bsStyle="success"
className="pull-right"
type="submit">Save</Button>
<Button bsStyle="danger"
className="pull-right margin-right-xs"
onClick={this.props.handleClose}
>Cancel</Button>
</div>
</div>
</form>
</div>
);
}
});
export default PolymerisationDegreeTestForm;
|
examples/real-world/containers/DevTools.js
|
javascriptjedi/redux-select
|
import React from 'react'
import { createDevTools } from 'redux-devtools'
import LogMonitor from 'redux-devtools-log-monitor'
import DockMonitor from 'redux-devtools-dock-monitor'
export default createDevTools(
<DockMonitor toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-w">
<LogMonitor />
</DockMonitor>
)
|
client/src/components/dataset/index.js
|
OpenChemistry/materialsdatabank
|
import React, { Component } from 'react';
import Button from '@material-ui/core/Button';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import IconButton from '@material-ui/core/IconButton';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableRow from '@material-ui/core/TableRow';
import Typography from '@material-ui/core/Typography';
import EditIcon from '@material-ui/icons/Edit';
import DoneIcon from '@material-ui/icons/Done';
import DownloadIcon from '@material-ui/icons/CloudDownload';
import DeleteIcon from '@material-ui/icons/Delete';
import PropTypes from 'prop-types';
import { connect } from 'react-redux'
import _ from 'lodash'
import selectors from '../../redux/selectors';
import { symbols } from '../../elements'
import StructureContainer from '../../containers/structure'
import { approveDataSet } from '../../redux/ducks/upload';
import { setProgress } from '../../redux/ducks/app';
import { deleteDataset } from '../../redux/ducks/datasets';
import PageHead from '../page-head';
import PageBody from '../page-body';
import ValidateTable from './validate';
import EditToggle from './editToggle';
import {
generalInformationFields,
dataCollectionFields,
reconstructionFields
} from '../deposit/fields'
import './index.css'
import { CardActions } from '@material-ui/core';
import { push } from 'connected-react-router';
import moment from 'moment';
const tableLabelStyle = {
fontSize: '18px',
color: '#9E9E9E'
}
const tableStyle = {
fontSize: '18px'
}
const curatorCardStyle = {
marginTop: '2rem'
}
class Dataset extends Component {
constructor(props) {
super(props);
this.state = {
approving: false,
reconstructionMenu: {
anchor: null,
open: false
},
structureMenu: {
anchor: null,
open: false
},
projectionMenu: {
anchor: null,
open: false
},
}
}
approve = () => {
this.props.dispatch(setProgress(true));
this.props.dispatch(approveDataSet(this.props._id));
this.setState({
approving: true
})
}
edit = () => {
this.props.dispatch(push(`/dataset/${this.props._id}/edit`));
}
remove = () => {
new Promise((resolve, reject) => {
this.props.dispatch(deleteDataset(this.props.dataset._id, resolve, reject));
}).then((dataSet) =>{
this.props.dispatch(push('/search'));
})
}
componentWillReceiveProps = (nextProps) => {
if (nextProps.public && this.state.approving) {
this.props.dispatch(setProgress(false));
this.setState({
approving: false
});
}
}
handleClick = (key, anchor) => {
this.setState({[key]: {anchor: anchor}});
};
handleClose = () => {
this.setState(
{
reconstructionMenu:{anchor: null},
structureMenu: {anchor: null},
projectionMenu: {anchor: null}
}
);
};
render = () => {
const species = this.props.atomicSpecies.map((an) => symbols[an]).join(', ');
const authors = this.props.authors.join(' and ');
const mdbId = this.props.mdbId;
const deposited = this.props.deposited;
const released = this.props.released;
const validation = this.props.validation;
let r1 = 'N/A';
if (!_.isNil(validation)) {
r1 = this.props.validation.r1;
}
let isPublic = this.props.public;
let {
structure, reconstruction, projection, title,
isCurator, doi, _id, editable, isOwner
} = this.props;
editable = _.isNil(editable) ? false : editable;
let numberOfAtoms = -1;
let structureUrl = '';
if (!_.isNil(structure)) {
structureUrl = `${window.location.origin}/api/v1/mdb/datasets/_/structures/${structure._id}`;
numberOfAtoms = structure.numberOfAtoms;
}
let reconEmdUrl = '';
let reconTiffUrl = '';
if (!_.isNil(reconstruction)) {
reconEmdUrl = `${window.location.origin}/api/v1/mdb/datasets/_/reconstructions/${reconstruction._id}/emd?updated=${this.props.updated}`
reconTiffUrl = `${window.location.origin}/api/v1/mdb/datasets/_/reconstructions/${reconstruction._id}/tiff?updated=${this.props.updated}`
}
let projEmdUrl = '';
let projTiffUrl = '';
if (!_.isNil(projection)) {
projEmdUrl = `${window.location.origin}/api/v1/mdb/datasets/_/projections/${projection._id}/emd?updated=${this.props.updated}`
projTiffUrl = `${window.location.origin}/api/v1/mdb/datasets/_/projections/${projection._id}/tiff?updated=${this.props.updated}`
}
// Prepare report data
let jsonReportData = null;
if (!_.isNil(projection) && !_.isNil(reconstruction)) {
// Filter the ones we want
const dataSetProps = _.pick(this.props, Object.keys(generalInformationFields()));
const projectionProps = _.pick(projection, Object.keys(dataCollectionFields()));
const reconstructionProps = _.pick(reconstruction, Object.keys(reconstructionFields()));
// Combine and encode
const data = {...dataSetProps, ...projectionProps, ...reconstructionProps};
const jsonReport = encodeURIComponent(JSON.stringify(data, null, 2));
jsonReportData = `text/json;charset=utf-8, ${jsonReport}`;
}
return (
<div>
<PageHead>
<Typography color="inherit" gutterBottom variant="display1">
{title}
</Typography>
<Typography variant="subheading" paragraph color="inherit">
{authors}
</Typography>
</PageHead>
<PageBody>
<Card>
<CardContent>
<Table>
<TableBody>
<TableRow>
<TableCell style={{...tableLabelStyle}}>
MDB ID
</TableCell>
<TableCell style={{...tableStyle}}>
{mdbId}
</TableCell>
</TableRow>
<TableRow>
<TableCell style={{...tableLabelStyle}}>
Name of the structure
</TableCell>
<TableCell style={{...tableStyle}}>
{title}
</TableCell>
</TableRow>
<TableRow>
<TableCell style={{...tableLabelStyle}}>
Total number of atoms
</TableCell>
{ numberOfAtoms !== -1 &&
<TableCell style={{...tableStyle}}>
{numberOfAtoms}
</TableCell>
}
</TableRow>
<TableRow>
<TableCell style={{...tableLabelStyle}}>
R<sub>1</sub> factor
</TableCell>
<TableCell style={{...tableStyle}}>
{r1}
</TableCell>
</TableRow>
<TableRow>
<TableCell style={{...tableLabelStyle}}>
Atomic Species
</TableCell>
<TableCell style={{...tableStyle}}>
{species}
</TableCell>
</TableRow>
<TableRow>
<TableCell style={{...tableLabelStyle}}>
DOI
</TableCell>
<TableCell style={{...tableStyle}}>
{_.isNil(doi) ? (
'N/A'
) : (
<a href={`https://dx.doi.org/${doi}`}>
{doi}
</a>
)}
</TableCell>
</TableRow>
<TableRow>
<TableCell style={{...tableLabelStyle}}>
Deposition author(s)
</TableCell>
<TableCell style={{...tableStyle}}>
{authors}
</TableCell>
</TableRow>
<TableRow>
<TableCell style={{...tableLabelStyle}}>
Deposited
</TableCell>
<TableCell style={{...tableStyle}}>
{_.isNil(deposited) ? (
'N/A'
) : (
moment(deposited).calendar()
)}
</TableCell>
</TableRow>
<TableRow>
<TableCell style={{...tableLabelStyle}}>
Released
</TableCell>
<TableCell style={{...tableStyle}}>
{_.isNil(released) ? (
'N/A'
) : (
moment(released).calendar()
)}
</TableCell>
</TableRow>
{ ( !_.isNil(projection) &&
(!_.isNil(projection.tiffFileId) ||
!_.isNil(projection.emdFileId))
) &&
<TableRow>
<TableCell style={{...tableLabelStyle}}>
Tilt series file
</TableCell>
<TableCell style={{...tableStyle}}>
<IconButton
aria-label="More"
aria-owns={this.state.projectionMenu.anchor ? 'projection-menu' : null}
aria-haspopup="true"
onClick={(e) => {this.handleClick('projectionMenu', e.currentTarget)}}
>
<DownloadIcon />
</IconButton>
<Menu
id="projection-menu"
anchorEl={this.state.projectionMenu.anchor}
open={Boolean(this.state.projectionMenu.anchor)}
onClose={this.handleClose}
>
{ !_.isNil(projection.tiffFileId) &&
<MenuItem
value="tiff"
onClick={this.handleClose}
>
<a href={projTiffUrl}>TIFF</a>
</MenuItem>
}
{ !_.isNil(projection.emdFileId) &&
<MenuItem
value="emd"
onClick={this.handleClose}
>
<a href={projEmdUrl}>EMD</a>
</MenuItem>
}
</Menu>
</TableCell>
</TableRow>
}
{ ( !_.isNil(reconstruction) &&
(!_.isNil(reconstruction.tiffFileId) ||
!_.isNil(reconstruction.emdFileId))
) &&
<TableRow>
<TableCell style={{...tableLabelStyle}}>
3D reconstruction file
</TableCell>
<TableCell style={{...tableStyle}}>
<IconButton
aria-label="More"
aria-owns={this.state.reconstructionMenu.anchor ? 'reconstruction-menu' : null}
aria-haspopup="true"
onClick={(e) => {this.handleClick('reconstructionMenu', e.currentTarget)}}
>
<DownloadIcon />
</IconButton>
<Menu
id="reconstruction-menu"
anchorEl={this.state.reconstructionMenu.anchor}
open={Boolean(this.state.reconstructionMenu.anchor)}
onClose={this.handleClose}
>
{ !_.isNil(reconstruction.tiffFileId) &&
<MenuItem
value="tiff"
onClick={this.handleClose}
>
<a href={reconTiffUrl}>TIFF</a>
</MenuItem>
}
{ !_.isNil(reconstruction.emdFileId) &&
<MenuItem
value="emd"
onClick={this.handleClose}
>
<a href={reconEmdUrl}>EMD</a>
</MenuItem>
}
</Menu>
</TableCell>
</TableRow>
}
<TableRow>
<TableCell style={{...tableLabelStyle}}>
3D atomic structure file
</TableCell>
<TableCell style={{...tableStyle}}>
<IconButton
aria-label="More"
aria-owns={this.state.structureMenu.anchor ? 'structure-menu' : null}
aria-haspopup="true"
onClick={(e) => {this.handleClick('structureMenu', e.currentTarget)}}
>
<DownloadIcon />
</IconButton>
<Menu
id="structure-menu"
anchorEl={this.state.structureMenu.anchor}
open={Boolean(this.state.structureMenu.anchor)}
onClose={this.handleClose}
>
<MenuItem
value="xyz"
onClick={this.handleClose}
>
<a href={`${structureUrl}/xyz?updated=${this.props.updated}`}>XYZ</a>
</MenuItem>
<MenuItem
value="cjson"
onClick={this.handleClose}
>
<a href={`${structureUrl}/cjson?updated=${this.props.updated}`}>CJSON</a>
</MenuItem>
<MenuItem
value="cml"
onClick={this.handleClose}
>
<a href={`${structureUrl}/cml?updated=${this.props.updated}`}>CML</a>
</MenuItem>
</Menu>
</TableCell>
</TableRow>
<TableRow>
<TableCell style={{...tableLabelStyle}}>
Full report (MatData)
</TableCell>
<TableCell style={{...tableStyle}}>
<a href={`data:' + ${jsonReportData}`} download={`${mdbId}.json`}>
<IconButton>
<DownloadIcon />
</IconButton>
</a>
</TableCell>
</TableRow>
</TableBody>
</Table>
<div style={{width: '100%', height: '30rem'}}>
<StructureContainer _id={_id}/>
</div>
{ !isPublic &&
<Typography color="textSecondary" style={{flexGrow: 1}}>* This dataset is awaiting approval.</Typography>
}
</CardContent>
{ (isCurator || isOwner) &&
<CardActions style={{display: 'flex'}}>
<div style={{marginLeft: 'auto'}}>
<Button
variant="contained"
color="primary"
disabled={!editable && !isCurator}
onClick={() => this.edit()}
>
<EditIcon/>
Edit
</Button>
<Button
style={{marginLeft: '0.5rem'}}
variant="contained"
color="secondary"
disabled={!editable && !isCurator}
onClick={() => this.remove()}
>
<DeleteIcon/>
Delete
</Button>
</div>
</CardActions>
}
</Card>
{ isCurator &&
<div style={curatorCardStyle}>
<Card>
<CardContent>
<ValidateTable _id={_id} />
<EditToggle _id={_id} />
</CardContent>
<CardActions style={{display: 'flex'}}>
{ !isPublic &&
<Button
style={{marginLeft: 'auto'}}
variant="contained"
color="primary"
disabled={this.state.approving}
onClick={() => this.approve()}
>
<DoneIcon/>
Approve
</Button>
}
</CardActions>
</Card>
</div>
}
</PageBody>
</div>
);
}
}
Dataset.propTypes = {
_id: PropTypes.string,
userId: PropTypes.string,
title: PropTypes.string,
authors: PropTypes.array,
imageFileId: PropTypes.string,
doi: PropTypes.string,
isCurator: PropTypes.bool,
public: PropTypes.bool,
reconstruction:PropTypes.object,
projection:PropTypes.object,
isOwner: PropTypes.bool
}
Dataset.defaultProps = {
title: '',
userId: null,
authors: [],
imageFileId: null,
atomicSpecies: [],
doi: null,
isCurator: false,
public: false,
reconstruction: {},
projection: {},
isOwner: false
}
function mapStateToProps(state, ownProps) {
let props = {};
if (!_.isNull(ownProps._id)) {
let structures = selectors.structures.getStructuresById(state);
if (_.has(structures, ownProps._id)) {
// For now we only have a single structure, so just pick the first.
const structure = structures[ownProps._id][0];
props = {
structure,
public: structure.public
}
}
let reconstructions = selectors.reconstructions.getReconstructionsById(state);
if (_.has(reconstructions, ownProps._id)) {
// For now we only have a single reconstruction, so just pick the first.
const reconstruction = reconstructions[ownProps._id][0];
props = {...props,
reconstruction
}
if (_.has(reconstruction, 'emdFileId')) {
props['emdFileId'] = reconstruction.emdFileId
}
if (_.has(reconstruction, 'tiffFileId')) {
props['tiffFileId'] = reconstruction.tiffFileId
}
}
let projections = selectors.projections.getProjectionsById(state);
if (_.has(projections, ownProps._id)) {
// For now we only have a single projection, so just pick the first.
const projection = projections[ownProps._id][0];
props = {...props,
projection
}
if (_.has(projection, 'emdFileId')) {
props['emdFileId'] = projection.emdFileId
}
if (_.has(projection, 'tiffFileId')) {
props['tiffFileId'] = projection.tiffFileId
}
}
const dataset = selectors.datasets.getDatasetById(state, ownProps._id);
props['dataset'] = dataset;
}
const me = selectors.girder.getMe(state);
const curatorGroup = selectors.girder.getCuratorGroup(state);
if (!_.isNil(curatorGroup)) {
if (!_.isNil(me)) {
props['isCurator'] = _.includes(me.groups, curatorGroup['_id'])
}
}
if (!_.isNil(me)) {
if (me._id === ownProps.userId) {
props['isOwner'] = true;
}
}
return props;
}
export default connect(mapStateToProps)(Dataset)
|
docs/app/Examples/collections/Table/States/TableExampleWarningShorthand.js
|
vageeshb/Semantic-UI-React
|
import React from 'react'
import { Table } from 'semantic-ui-react'
const tableData = [
{ name: undefined, status: undefined, notes: undefined },
{ name: 'Jimmy', status: 'Requires Action', notes: undefined },
{ name: 'Jamie', status: undefined, notes: 'Hostile' },
{ name: 'Jill', status: undefined, notes: undefined },
]
const headerRow = [
'Name',
'Status',
'Notes',
]
const renderBodyRow = ({ name, status, notes }) => ({
warning: !!(status && status.match('Requires Action')),
cells: [
name || 'No name specified',
status
? { icon: 'attention', content: status }
: 'Unknown',
notes
? { icon: 'attention', content: notes, warning: true }
: 'None',
],
})
const TableExampleWarningShorthand = () => (
<Table
celled
headerRow={headerRow}
renderBodyRow={renderBodyRow}
tableData={tableData}
/>
)
export default TableExampleWarningShorthand
|
classic/src/scenes/mailboxes/src/Scenes/BookmarkScene/BookmarkEditScene/BookmarkEditScene.js
|
wavebox/waveboxapp
|
import React from 'react'
import shallowCompare from 'react-addons-shallow-compare'
import { RouterDialog, RouterDialogStateProvider } from 'wbui/RouterDialog'
import BookmarkEditSceneContent from './BookmarkEditSceneContent'
class BookmarkEditScene extends React.Component {
/* **************************************************************************/
// User Interaction
/* **************************************************************************/
/**
* Closes the modal
*/
handleClose = () => {
window.location.hash = '/'
}
/* **************************************************************************/
// Rendering
/* **************************************************************************/
shouldComponentUpdate (nextProps, nextState) {
return shallowCompare(this, nextProps, nextState)
}
render () {
const { routeName } = this.props
return (
<RouterDialog
routeName={routeName}
disableEnforceFocus
onClose={this.handleClose}>
<RouterDialogStateProvider routeName={routeName} Component={BookmarkEditSceneContent} />
</RouterDialog>
)
}
}
export default BookmarkEditScene
|
test/components/SlideListEditorComponentTest.js
|
C3-TKO/gaiyo
|
/*eslint-env node, mocha */
/*global expect */
/*eslint no-console: 0*/
'use strict';
import React from 'react';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import { mountWithIntl, shallowWithIntl } from 'helpers/intl-enzyme-test-helper.js';
import configureStore from 'redux-mock-store';
import { Provider } from 'react-redux';
import * as SyncStates from '../../src/constants/SyncStates.js'
import SlideListEditorComponent from 'components//SlideListEditorComponent.js';
describe('SlideListEditorComponent', () => {
let wrapper;
const mockStore = configureStore();
const store = mockStore({
slides: [],
settings: {
remoteDbUrl: undefined,
remoteDbUser: undefined,
remoteDbPassword: undefined,
syncMode: 1,
enabled: false
},
syncState: {
status: SyncStates.NOT_CONNECTED
}
});
beforeEach(() => {
wrapper = mountWithIntl(
<Provider store={store}>
<SlideListEditorComponent />
</Provider>
);
});
it('should have its component name as default className for the containing div', () => {
expect(wrapper.find('div.slidelisteditor-component')).to.have.length(1);
});
});
|
src/js/main.js
|
goadapp/goad-site
|
import React from 'react';
import ReactDOM from 'react-dom';
import Downloads from './components/downloads.jsx';
var smoothScroll = require('smoothscroll');
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
window.React = React;
window.ReactDOM = ReactDOM;
const binaries = [
{
os: "macOS",
architecture: 64,
url: "https://github.com/gophergala2016/goad/releases/download/v1.3.0/goad-gopher-gala-osx-x86-64.zip"
},
{
os: "Linux",
architecture: 32,
url: "https://github.com/gophergala2016/goad/releases/download/v1.3.0/goad-gopher-gala-linux-x86.zip"
},
{
os: "Linux",
architecture: 64,
url: "https://github.com/gophergala2016/goad/releases/download/v1.3.0/goad-gopher-gala-linux-x86-64.zip"
},
{
os: "Windows",
architecture: 32,
url: "https://github.com/gophergala2016/goad/releases/download/v1.3.0/goad-gopher-gala-windows-x86.zip"
},
{
os: "Windows",
architecture: 64,
url: "https://github.com/gophergala2016/goad/releases/download/v1.3.0/goad-gopher-gala-windows-x86-64.zip"
},
];
ReactDOM.render(<Downloads binaries={binaries} />, document.getElementById("downloads"));
ready(function(){
var tryEl = document.getElementById("try-link");
var tryDestination = document.getElementById("demo");
tryEl.addEventListener("click", event => {
event.preventDefault()
smoothScroll(tryDestination)
})
var installEl = document.getElementById("install-link");
var installDestination = document.getElementById("install");
installEl.addEventListener("click", event => {
event.preventDefault()
smoothScroll(installDestination)
})
})
|
openex-front/src/private/components/exercises/injects/InjectPopover.js
|
Luatix/OpenEx
|
import React, { Component } from 'react';
import * as PropTypes from 'prop-types';
import { connect } from 'react-redux';
import * as R from 'ramda';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogActions from '@mui/material/DialogActions';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import Slide from '@mui/material/Slide';
import { MoreVert } from '@mui/icons-material';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import Alert from '@mui/material/Alert';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableRow from '@mui/material/TableRow';
import TableCell from '@mui/material/TableCell';
import withStyles from '@mui/styles/withStyles';
import {
updateInject,
deleteInject,
tryInject,
updateInjectActivation,
injectDone,
} from '../../../../actions/Inject';
import InjectForm from './InjectForm';
import inject18n from '../../../../components/i18n';
import { splitDuration } from '../../../../utils/Time';
import { isExerciseReadOnly } from '../../../../utils/Exercise';
import { tagsConverter } from '../../../../actions/Schema';
const Transition = React.forwardRef((props, ref) => (
<Slide direction="up" ref={ref} {...props} />
));
Transition.displayName = 'TransitionSlide';
const styles = () => ({
tableHeader: {
borderBottom: '1px solid rgba(255, 255, 255, 0.15)',
},
tableCell: {
borderTop: '1px solid rgba(255, 255, 255, 0.15)',
borderBottom: '1px solid rgba(255, 255, 255, 0.15)',
},
});
class InjectPopover extends Component {
constructor(props) {
super(props);
this.state = {
openDelete: false,
openEdit: false,
openPopover: false,
openTry: false,
openCopy: false,
openEnable: false,
openDisable: false,
openDone: false,
openResult: false,
injectResult: null,
};
}
handlePopoverOpen(event) {
event.stopPropagation();
this.setState({ anchorEl: event.currentTarget });
}
handlePopoverClose() {
this.setState({ anchorEl: null });
}
handleOpenEdit() {
this.setState({ openEdit: true });
this.handlePopoverClose();
}
handleCloseEdit() {
this.setState({ openEdit: false });
}
onSubmitEdit(data) {
const inputValues = R.pipe(
R.assoc(
'inject_depends_duration',
data.inject_depends_duration_days * 3600 * 24
+ data.inject_depends_duration_hours * 3600
+ data.inject_depends_duration_minutes * 60,
),
R.assoc('inject_contract', data.inject_contract.id),
R.assoc('inject_tags', R.pluck('id', data.inject_tags)),
R.dissoc('inject_depends_duration_days'),
R.dissoc('inject_depends_duration_hours'),
R.dissoc('inject_depends_duration_minutes'),
)(data);
return this.props
.updateInject(
this.props.exerciseId,
this.props.inject.inject_id,
inputValues,
)
.then(() => this.handleCloseEdit());
}
handleOpenDelete() {
this.setState({ openDelete: true });
this.handlePopoverClose();
}
handleCloseDelete() {
this.setState({ openDelete: false });
}
submitDelete() {
this.props.deleteInject(this.props.exerciseId, this.props.inject.inject_id);
this.handleCloseDelete();
}
handleOpenTry() {
this.setState({
openTry: true,
});
this.handlePopoverClose();
}
handleCloseTry() {
this.setState({
openTry: false,
});
}
handleCloseResult() {
this.setState({
openResult: false,
injectResult: null,
});
}
submitTry() {
this.props.tryInject(this.props.inject.inject_id).then((payload) => {
this.setState({ injectResult: payload, openResult: true });
});
this.handleCloseTry();
}
handleOpenEnable() {
this.setState({
openEnable: true,
});
this.handlePopoverClose();
}
handleCloseEnable() {
this.setState({
openEnable: false,
});
}
submitEnable() {
this.props.updateInjectActivation(
this.props.exerciseId,
this.props.inject.inject_id,
{ inject_enabled: true },
);
this.handleCloseEnable();
}
handleOpenDisable() {
this.setState({
openDisable: true,
});
this.handlePopoverClose();
}
handleCloseDisable() {
this.setState({
openDisable: false,
});
}
submitDisable() {
this.props.updateInjectActivation(
this.props.exerciseId,
this.props.inject.inject_id,
{ inject_enabled: false },
);
this.handleCloseDisable();
}
handleOpenDone() {
this.setState({
openDone: true,
});
this.handlePopoverClose();
}
handleCloseDone() {
this.setState({
openDone: false,
});
}
submitDone() {
this.props.injectDone(
this.props.exercise.exercise_id,
this.props.inject.inject_id,
);
this.handleCloseDone();
}
handleOpenEditContent() {
this.props.setSelectedInject(this.props.inject.inject_id);
this.handlePopoverClose();
}
render() {
const {
t,
inject,
injectTypesMap,
exercise,
setSelectedInject,
tagsMap,
isDisabled,
classes,
} = this.props;
const injectTags = tagsConverter(inject.inject_tags, tagsMap);
const duration = splitDuration(inject.inject_depends_duration || 0);
const initialValues = R.pipe(
R.assoc('inject_tags', injectTags),
R.pick([
'inject_title',
'inject_contract',
'inject_description',
'inject_tags',
'inject_content',
'inject_audiences',
'inject_all_audiences',
'inject_country',
'inject_city',
]),
R.assoc('inject_depends_duration_days', duration.days),
R.assoc('inject_depends_duration_hours', duration.hours),
R.assoc('inject_depends_duration_minutes', duration.minutes),
)(inject);
return (
<div>
<IconButton
onClick={this.handlePopoverOpen.bind(this)}
aria-haspopup="true"
size="large"
>
<MoreVert />
</IconButton>
<Menu
anchorEl={this.state.anchorEl}
open={Boolean(this.state.anchorEl)}
onClose={this.handlePopoverClose.bind(this)}
>
<MenuItem
onClick={this.handleOpenEdit.bind(this)}
disabled={isExerciseReadOnly(exercise) || isDisabled}
>
{t('Update')}
</MenuItem>
{setSelectedInject && (
<MenuItem
onClick={this.handleOpenEditContent.bind(this)}
disabled={isExerciseReadOnly(exercise) || isDisabled}
>
{t('Manage content')}
</MenuItem>
)}
{!inject.inject_status && (
<MenuItem
onClick={this.handleOpenDone.bind(this)}
disabled={isExerciseReadOnly(exercise) || isDisabled}
>
{t('Mark as done')}
</MenuItem>
)}
{inject.inject_type !== 'openex_manual' && (
<MenuItem
onClick={this.handleOpenTry.bind(this)}
disabled={isExerciseReadOnly(exercise) || isDisabled}
>
{t('Try the inject')}
</MenuItem>
)}
{inject.inject_enabled ? (
<MenuItem
onClick={this.handleOpenDisable.bind(this)}
disabled={isExerciseReadOnly(exercise) || isDisabled}
>
{t('Disable')}
</MenuItem>
) : (
<MenuItem
onClick={this.handleOpenEnable.bind(this)}
disabled={isExerciseReadOnly(exercise) || isDisabled}
>
{t('Enable')}
</MenuItem>
)}
<MenuItem
onClick={this.handleOpenDelete.bind(this)}
disabled={isExerciseReadOnly(exercise)}
>
{t('Delete')}
</MenuItem>
</Menu>
<Dialog
open={this.state.openDelete}
TransitionComponent={Transition}
onClose={this.handleCloseDelete.bind(this)}
PaperProps={{ elevation: 1 }}
>
<DialogContent>
<DialogContentText>
{t('Do you want to delete this inject?')}
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={this.handleCloseDelete.bind(this)}>
{t('Cancel')}
</Button>
<Button color="secondary" onClick={this.submitDelete.bind(this)}>
{t('Delete')}
</Button>
</DialogActions>
</Dialog>
<Dialog
TransitionComponent={Transition}
open={this.state.openEdit}
onClose={this.handleCloseEdit.bind(this)}
fullWidth={true}
maxWidth="md"
PaperProps={{ elevation: 1 }}
>
<DialogTitle>{t('Update the inject')}</DialogTitle>
<DialogContent>
<InjectForm
initialValues={initialValues}
editing={true}
injectTypesMap={injectTypesMap}
onSubmit={this.onSubmitEdit.bind(this)}
handleClose={this.handleCloseEdit.bind(this)}
/>
</DialogContent>
</Dialog>
<Dialog
TransitionComponent={Transition}
open={this.state.openTry}
onClose={this.handleCloseTry.bind(this)}
PaperProps={{ elevation: 1 }}
>
<DialogContent>
<DialogContentText>
<p>{t('Do you want to try this inject?')}</p>
<Alert severity="info">
{t('The inject will only be sent to you.')}
</Alert>
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={this.handleCloseTry.bind(this)}>
{t('Cancel')}
</Button>
<Button color="secondary" onClick={this.submitTry.bind(this)}>
{t('Try')}
</Button>
</DialogActions>
</Dialog>
<Dialog
TransitionComponent={Transition}
open={this.state.openEnable}
onClose={this.handleCloseEnable.bind(this)}
PaperProps={{ elevation: 1 }}
>
<DialogContent>
<DialogContentText>
{t('Do you want to enable this inject?')}
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={this.handleCloseEnable.bind(this)}>
{t('Cancel')}
</Button>
<Button color="secondary" onClick={this.submitEnable.bind(this)}>
{t('Enable')}
</Button>
</DialogActions>
</Dialog>
<Dialog
TransitionComponent={Transition}
open={this.state.openDisable}
onClose={this.handleCloseDisable.bind(this)}
PaperProps={{ elevation: 1 }}
>
<DialogContent>
<DialogContentText>
{t('Do you want to disable this inject?')}
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={this.handleCloseDisable.bind(this)}>
{t('Cancel')}
</Button>
<Button color="secondary" onClick={this.submitDisable.bind(this)}>
{t('Disable')}
</Button>
</DialogActions>
</Dialog>
<Dialog
TransitionComponent={Transition}
open={this.state.openDone}
onClose={this.handleCloseDone.bind(this)}
PaperProps={{ elevation: 1 }}
>
<DialogContent>
<DialogContentText>
{t('Do you want to mark this inject as done?')}
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={this.handleCloseDone.bind(this)}>
{t('Cancel')}
</Button>
<Button color="secondary" onClick={this.submitDone.bind(this)}>
{t('Mark')}
</Button>
</DialogActions>
</Dialog>
<Dialog
open={this.state.openResult}
TransitionComponent={Transition}
onClose={this.handleCloseResult.bind(this)}
fullWidth={true}
maxWidth="md"
PaperProps={{ elevation: 1 }}
>
<DialogContent>
<Table selectable={false} size="small">
<TableBody displayRowCheckbox={false}>
{this.state.injectResult
&& Object.entries(this.state.injectResult.status_reporting).map(
([key, value]) => {
if (key === 'execution_traces') {
return (
<TableRow key={key}>
<TableCell classes={{ root: classes.tableCell }}>
{key}
</TableCell>
<TableCell classes={{ root: classes.tableCell }}>
<Table selectable={false} size="small" key={key}>
<TableBody displayRowCheckbox={false}>
{value.map((trace) => (
<TableRow key={trace.trace_identifier}>
<TableCell
classes={{ root: classes.tableCell }}
>
{trace.trace_message}
</TableCell>
<TableCell
classes={{ root: classes.tableCell }}
>
{trace.trace_status}
</TableCell>
<TableCell
classes={{ root: classes.tableCell }}
>
{trace.trace_time}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableCell>
</TableRow>
);
}
return (
<TableRow key={key}>
<TableCell classes={{ root: classes.tableCell }}>
{key}
</TableCell>
<TableCell classes={{ root: classes.tableCell }}>
{value}
</TableCell>
</TableRow>
);
},
)}
</TableBody>
</Table>
</DialogContent>
<DialogActions>
<Button onClick={this.handleCloseResult.bind(this)}>
{t('Close')}
</Button>
</DialogActions>
</Dialog>
</div>
);
}
}
InjectPopover.propTypes = {
t: PropTypes.func,
exerciseId: PropTypes.string,
exercise: PropTypes.object,
tagsMap: PropTypes.object,
inject: PropTypes.object,
updateInject: PropTypes.func,
deleteInject: PropTypes.func,
injectTypesMap: PropTypes.object,
updateInjectActivation: PropTypes.func,
injectDone: PropTypes.func,
setSelectedInject: PropTypes.func,
isDisabled: PropTypes.bool,
};
export default R.compose(
connect(null, {
updateInject,
deleteInject,
tryInject,
updateInjectActivation,
injectDone,
}),
inject18n,
withStyles(styles),
)(InjectPopover);
|
tests/react/useLayoutEffect_hook.js
|
mroch/flow
|
// @flow
import React from 'react';
{
React.useLayoutEffect(); // Error: function requires another argument.
}
{
// Ok variants without cleanup functions
React.useLayoutEffect(() => {});
React.useLayoutEffect(() => {}, []);
React.useLayoutEffect(() => {}, [1, 2, 3]);
// Ok variants with cleanup functions
React.useLayoutEffect(() => () => {});
React.useLayoutEffect(() => () => {}, []);
React.useLayoutEffect(() => () => {}, [1, 2, 3]);
}
{
React.useLayoutEffect(1); // Error: number is incompatible with function type
React.useLayoutEffect(() => {}, 1); // Error: number is incompatible with function react-only array
React.useLayoutEffect(async () => {}) // Error: promise is incompatible with function return type
React.useLayoutEffect(() => () => 123) // Error: cleanup function should not return a value
}
|
components/Home/FeaturedOn/index.js
|
parkerproject/conceptionarts
|
import React from 'react';
export default() => (
<div className="featured_on">
<div className="container">
<div className="row-eq-height featured_on_resp">
<div className="featured_on_title col-xl-2 col-lg-3 col-md-4 col-sm-12">
<span>
As featured on:
</span>
</div>
<div className="featured_on_img col-xl-10 col-lg-9 col-md-8 col-sm-12">
<img src="/static/img/brand.jpg" alt="" />
</div>
</div>
</div>
</div>
);
|
fiveRows/__tests__/index.android.js
|
chngws/User-Interface
|
import 'react-native';
import React from 'react';
import Index from '../index.android.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
step7-flux/node_modules/react-router/modules/IndexRedirect.js
|
jintoppy/react-training
|
import React from 'react'
import warning from './routerWarning'
import invariant from 'invariant'
import Redirect from './Redirect'
import { falsy } from './PropTypes'
const { string, object } = React.PropTypes
/**
* An <IndexRedirect> is used to redirect from an indexRoute.
*/
const IndexRedirect = React.createClass({
statics: {
createRouteFromReactElement(element, parentRoute) {
/* istanbul ignore else: sanity check */
if (parentRoute) {
parentRoute.indexRoute = Redirect.createRouteFromReactElement(element)
} else {
warning(
false,
'An <IndexRedirect> does not make sense at the root of your route config'
)
}
}
},
propTypes: {
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
/* istanbul ignore next: sanity check */
render() {
invariant(
false,
'<IndexRedirect> elements are for router configuration only and should not be rendered'
)
}
})
export default IndexRedirect
|
app/components/Theme/Theme.js
|
zchen9/DonutTab
|
import React from 'react';
require('./Theme.scss');
const LIGHT_ICON = (
<span className="theme-icon theme-light">
<i className="fa fa-sun-o"></i>
</span>
);
const DARK_ICON = (
<span className="theme-icon theme-dark">
<i className="fa fa-moon-o"></i>
</span>
);
const LIGHT_STYLE = {
background: 'linear-gradient(to bottom, rgba(255, 255, 255, .15) 0, rgba(255, 255, 255, .3), rgba(255, 255, 255, .15) 100%)'
}
const DARK_STYLE = {
background: 'linear-gradient(to bottom, rgba(0, 0, 0, .35) 0, rgba(0, 0, 0, .1), rgba(0, 0, 0, .35) 100%)'
}
export default class Theme extends React.Component {
constructor(props) {
super(props);
this.state = {
isDark: JSON.parse(localStorage.getItem('curIsDark')) ? true : false
}
}
handleClick(ev) {
var isDark = this.state.isDark;
// change icon
this.setState({
isDark: !isDark
});
// set local
localStorage.setItem('curIsDark', !isDark);
this.props.onChangeTheme(!isDark);
}
render() {
var isDark = this.state.isDark,
themeStyle = isDark ? DARK_STYLE : LIGHT_STYLE,
themeIcon = isDark ? DARK_ICON : LIGHT_ICON;
return (
<div className="theme-container" style={themeStyle}>
<div onClick={this.handleClick.bind(this)}>{themeIcon}</div>
</div>
);
}
}
|
src/components/ImagePicker/ImagePicker.js
|
ahthamrin/kbri-admin2
|
import React from 'react'
import { IndexLink, Link } from 'react-router'
console.log('ImagePicker')
var thisUpCanvas = document.createElement('canvas')
var thisUpImage = new Image()
class ImagePicker extends React.Component {
constructor(props) {
super(props);
console.log('ImagePicker:constructor');
}
renderValidation() {
// TODO: change materialize CSS code
for (var elemId in this.dataset) {
try {
let elem = document.querySelector('label[for='+elemId+']').dataset;
if (this.dataset[elemId].error) {
elem.error = this.dataset[elemId].error;
document.getElementById(elemId).classList.add('invalid')
document.getElementById(elemId).classList.remove('valid')
}
else {
delete elem.error ;
document.getElementById(elemId).classList.add('valid')
document.getElementById(elemId).classList.remove('invalid')
}
// console.log('elem', elemId, this.dataset[elemId]);
}
catch(e) {}
}
}
componentDidMount() {
console.log('ImagePicker:componentDidMount');
}
componentDidUpdate() {
}
state = {
dialogOpen : null,
}
handleOpenDialog = (name) => {
this.setState({dialogOpen: name});
}
handleCloseDialog = () => {
this.setState({dialogOpen: null});
}
handleFiles = (e) => {
// console.log('handleFiles', e.target.files);
const files = [];
for (let i = 0; i < e.target.files.length; i++) {
// Convert to Array.
files.push(e.target.files[i]);
}
// Build Promise List, each promise resolved by FileReader.onload.
Promise.all(files.map(file => new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = (ref) => {
// Resolve both the FileReader result and its original file.
resolve(ref.target.result);
};
// Read the file with format based on this.props.as.
switch ((this.props.as || 'url').toLowerCase()) {
case 'binary': {
reader.readAsBinaryString(file);
break;
}
case 'buffer': {
reader.readAsArrayBuffer(file);
break;
}
case 'text': {
reader.readAsText(file);
break;
}
case 'url': {
reader.readAsDataURL(file);
break;
}
}
})))
.then(zippedResults => {
// Run the callback after all files have been read.
console.log('res', zippedResults);
const MAX_SIZE = 800;
var upImage = thisUpImage //new Image();
var upCanvas = thisUpCanvas // document.createElement('canvas');
var ctx = upCanvas.getContext('2d');
upImage.onload = () => {
// Make a smaller image from input
// console.log('drawImage', upImage.width, upImage.height, zippedResults[0].length);
const hwRatio = upImage.height/upImage.width;
const maxDimRatio = MAX_SIZE/Math.max(upImage.height, upImage.width);
upCanvas.height = upImage.height;
upCanvas.width = upImage.width;
if (maxDimRatio < 1) {
upCanvas.height = maxDimRatio*upImage.height;
upCanvas.width = maxDimRatio*upImage.width;
}
// console.log('drawImage', upImage.width, upImage.height, zippedResults[0].length);
ctx.drawImage(upImage, 0, 0, upCanvas.width, upCanvas.height);
var dataUrl = upCanvas.toDataURL('image/jpeg', 0.9)
ctx.clearRect(0, 0, upCanvas.width, upCanvas.height)
upCanvas.height = 1
upCanvas.width = 1
upImage.src = null;
zippedResults[0] = ''
zippedResults = null
// this.props.onChange(null, dataUrl);
this.props.onChange({target:{value:dataUrl}});
}
upImage.src = zippedResults[0];
});
}
render() {
return (
<div style={{display:'inline-block'}}>
<label className='active'>{this.props.label}</label>
<div className='btn' style={{overflow:'hidden',position:'relative'}}>
<span><i className='material-icons'>add_a_photo</i></span>
<input name={'fileinput-'+this.props.name} type='file' accept='image/*;capture=camera' onChange={this.handleFiles}
style={{display:'block', cursor: 'inherit', position: 'absolute', opacity: 0, top:0, bottom:0, left:0, right:0}}/>
</div>
</div>
)
}
}
// <label className='active'>{this.props.label}</label>
// <div className='btn' >
// <span>Unggah<i className='material-icons'>add_a_photo</i></span>
// <input type='file' accept='image/*;capture=camera' onChange={this.handleFiles} style={{position: 'absolute', opacity:1, top:0, bottom:0, left:0, right:0}}/>
// </div>
export default ImagePicker
|
ui/src/components/PostImage.js
|
nateinaction/nateanddanielle.love
|
import React from 'react';
import PropTypes from 'prop-types';
import LinearProgress from '@material-ui/core/LinearProgress';
import CardMedia from '@material-ui/core/CardMedia';
import './PostImage.css';
const srcSize = (imageType, maxWidth, imageDetails) => {
// Apparently GIFs are no longer animated after WP scales them so we always serve full size
let response = {
featured: imageDetails.sizes.full.source_url,
src: imageDetails.sizes.full.source_url,
};
if (imageType !== 'image/gif') {
// find available sizes for a given image
const availableSizes = [200, 400, 600, 800, 1200, 1400, 1600, 1800, 2000].filter(size => (typeof imageDetails.sizes[size] !== 'undefined'));
// grab the size of the featured image and deliver other sizes to srcset
const featuredSize = availableSizes.find(size => maxWidth <= size) || 'full';
const srcset = availableSizes.map(size => `${imageDetails.sizes[size].source_url} ${size}w`);
// create response
response = {
featured: imageDetails.sizes[featuredSize].source_url,
src: imageDetails.sizes.full.source_url,
srcset,
};
}
return response;
};
const PostImage = (props) => {
// if fetching show loading bar
if (props.media.fetching) {
return (
<LinearProgress className="fetching" />
);
}
// else get image object and return
const media = {
type: props.media.mime_type,
maxWidth: props.width,
details: props.media.media_details,
};
const image = srcSize(media.type, media.maxWidth, media.details);
return (
<div>
<CardMedia
title={props.media.alt_text}
src={image.featured}
component="img"
/>
</div>
);
};
PostImage.propTypes = {
media: PropTypes.shape({
fetching: PropTypes.bool,
alt_text: PropTypes.string,
media_details: PropTypes.object,
mime_type: PropTypes.string,
}).isRequired,
width: PropTypes.number,
};
PostImage.defaultProps = {
width: 0,
};
export default PostImage;
|
node_modules/rc-dialog/es/Modal.js
|
yhx0634/foodshopfront
|
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import { View, Modal, Animated, TouchableWithoutFeedback, StyleSheet, Dimensions, Easing } from 'react-native';
var styles = StyleSheet.create({
wrap: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0)'
},
mask: {
backgroundColor: 'black',
opacity: .5
},
content: {
backgroundColor: 'white'
},
absolute: {
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0
}
});
var screen = Dimensions.get('window');
var RCModal = function (_React$Component) {
_inherits(RCModal, _React$Component);
function RCModal(props) {
_classCallCheck(this, RCModal);
var _this = _possibleConstructorReturn(this, (RCModal.__proto__ || Object.getPrototypeOf(RCModal)).call(this, props));
_this.animateMask = function (visible) {
_this.stopMaskAnim();
_this.state.opacity.setValue(_this.getOpacity(!visible));
_this.animMask = Animated.timing(_this.state.opacity, {
toValue: _this.getOpacity(visible),
duration: _this.props.animationDuration
});
_this.animMask.start(function () {
_this.animMask = null;
});
};
_this.stopMaskAnim = function () {
if (_this.animMask) {
_this.animMask.stop();
_this.animMask = null;
}
};
_this.stopDialogAnim = function () {
if (_this.animDialog) {
_this.animDialog.stop();
_this.animDialog = null;
}
};
_this.animateDialog = function (visible) {
_this.stopDialogAnim();
_this.animateMask(visible);
var animationType = _this.props.animationType;
if (animationType !== 'none') {
if (animationType === 'slide-up' || animationType === 'slide-down') {
_this.state.position.setValue(_this.getPosition(!visible));
_this.animDialog = Animated.timing(_this.state.position, {
toValue: _this.getPosition(visible),
duration: _this.props.animationDuration,
easing: visible ? Easing.elastic(0.8) : undefined
});
} else if (animationType === 'fade') {
_this.animDialog = Animated.parallel([Animated.timing(_this.state.opacity, {
toValue: _this.getOpacity(visible),
duration: _this.props.animationDuration,
easing: visible ? Easing.elastic(0.8) : undefined
}), Animated.spring(_this.state.scale, {
toValue: _this.getScale(visible),
duration: _this.props.animationDuration,
easing: visible ? Easing.elastic(0.8) : undefined
})]);
}
_this.animDialog.start(function () {
_this.animDialog = null;
if (!visible) {
_this.setState({
modalVisible: false
});
}
_this.props.onAnimationEnd(visible);
});
} else {
if (!visible) {
_this.setState({
modalVisible: false
});
}
}
};
_this.close = function () {
_this.animateDialog(false);
};
_this.onMaskClose = function () {
if (_this.props.maskClosable) {
_this.props.onClose();
}
};
_this.getPosition = function (visible) {
if (visible) {
return 0;
}
return _this.props.animationType === 'slide-down' ? -screen.height : screen.height;
};
_this.getScale = function (visible) {
return visible ? 1 : 1.05;
};
_this.getOpacity = function (visible) {
return visible ? 1 : 0;
};
var visible = props.visible;
_this.state = {
position: new Animated.Value(_this.getPosition(visible)),
scale: new Animated.Value(_this.getScale(visible)),
opacity: new Animated.Value(_this.getOpacity(visible)),
modalVisible: visible
};
return _this;
}
_createClass(RCModal, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (this.shouldComponentUpdate(nextProps)) {
this.setState({
modalVisible: true
});
}
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
if (this.props.visible || this.props.visible !== nextProps.visible) {
return true;
}
if (nextState) {
if (nextState.modalVisible !== this.state.modalVisible) {
return true;
}
}
return false;
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
if (this.props.animateAppear && this.props.animationType !== 'none') {
this.componentDidUpdate({});
}
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps) {
var props = this.props;
if (prevProps.visible !== props.visible) {
this.animateDialog(props.visible);
}
}
}, {
key: 'render',
value: function render() {
var props = this.props;
if (!this.state.modalVisible) {
return null;
}
var animationStyleMap = {
none: {},
'slide-up': { transform: [{ translateY: this.state.position }] },
'slide-down': { transform: [{ translateY: this.state.position }] },
fade: { transform: [{ scale: this.state.scale }], opacity: this.state.opacity }
};
return React.createElement(Modal, { visible: true, transparent: true, onRequestClose: this.props.onClose, supportedOrientations: ['portrait', 'landscape'] }, React.createElement(View, { style: [styles.wrap, props.wrapStyle] }, React.createElement(TouchableWithoutFeedback, { onPress: this.onMaskClose }, React.createElement(Animated.View, { style: [styles.absolute, { opacity: this.state.opacity }] }, React.createElement(View, { style: [styles.absolute, props.maskStyle] }))), React.createElement(Animated.View, { style: [styles.content, props.style, animationStyleMap[props.animationType]] }, this.props.children)));
}
}]);
return RCModal;
}(React.Component);
export default RCModal;
RCModal.defaultProps = {
wrapStyle: styles.wrap,
maskStyle: styles.mask,
animationType: 'slide-up',
animateAppear: false,
animationDuration: 300,
visible: false,
maskClosable: true,
onClose: function onClose() {},
onAnimationEnd: function onAnimationEnd(_visible) {}
};
|
client/my-sites/invites/utils.js
|
mmmavis/mofo-calypso
|
/**
* Internal dependencies
*/
import React from 'react';
import get from 'lodash/object/get'
/**
* Internal dependencies
*/
import i18n from 'lib/mixins/i18n';
export default {
acceptedNotice( invite, displayOnNextPage = true ) {
let takeATour = (
<p className="invite-message__intro">
{
i18n.translate(
'Since you\'re new, you might like to {{docsLink}}take a tour{{/docsLink}}.',
{ components: { docsLink: <a href="https://learn.wordpress.com/" target="_blank" /> } }
)
}
</p>
);
let site = (
<a href={ get( invite, 'site.URL' ) } className="invite-accept__notice-site-link">
{ get( invite, 'site.title' ) }
</a>
);
switch ( get( invite, 'role' ) ) {
case 'follower':
return [
i18n.translate(
'You are now following {{site/}}', {
components: { site }
}
),
{
button: i18n.translate( 'Visit Site' ),
href: get( invite, 'site.URL' ),
displayOnNextPage
}
];
break;
case 'viewer':
return [
i18n.translate(
'You are now a viewer of: {{site/}}', {
components: { site }
}
),
{
button: i18n.translate( 'Visit Site' ),
href: get( invite, 'site.URL' ),
displayOnNextPage
}
];
break;
case 'administrator':
return [
<div>
<h3 className="invite-message__title">
{ i18n.translate( 'You\'re now an Administrator of: {{site/}}', {
components: { site }
} ) }
</h3>
<p className="invite-message__intro">
{ i18n.translate( 'This is your site dashboard where you will be able to manage all aspects of %(site)s', {
args: { site: get( invite, 'site.title' ) }
} ) }
</p>
{ takeATour }
</div>,
{ displayOnNextPage }
];
break;
case 'editor':
return [
<div>
<h3 className="invite-message__title">
{ i18n.translate( 'You\'re now an Editor of: {{site/}}', {
components: { site }
} ) }
</h3>
<p className="invite-message__intro">
{ i18n.translate( 'This is your site dashboard where you can publish and manage your own posts and the posts of others, as well as upload media.' ) }
</p>
{ takeATour }
</div>,
{ displayOnNextPage }
];
break;
case 'author':
return [
<div>
<h3 className="invite-message__title">
{ i18n.translate( 'You\'re now an Author of: {{site/}}', {
components: { site }
} ) }
</h3>
<p className="invite-message__intro">
{ i18n.translate( 'This is your site dashboard where you can publish and edit your own posts as well as upload media.' ) }
</p>
{ takeATour }
</div>,
{ displayOnNextPage }
];
break;
case 'contributor':
return [
<div>
<h3 className="invite-message__title">
{ i18n.translate( 'You\'re now a Contributor of: {{site/}}', {
components: { site }
} ) }
</h3>
<p className="invite-message__intro">
{ i18n.translate( 'This is your site dashboard where you can write and manage your own posts.' ) }
</p>
{ takeATour }
</div>,
{ displayOnNextPage }
];
break;
case 'subscriber':
return [
i18n.translate( 'You\'re now a Subscriber of: {{site/}}', {
components: { site }
} ),
{ displayOnNextPage }
];
break;
}
},
getRedirectAfterAccept( invite ) {
switch ( invite.role ) {
case 'viewer':
case 'follower':
return '/';
break;
default:
return '/posts/' + invite.site.ID;
}
}
};
|
app/javascript/mastodon/features/compose/components/poll_button.js
|
dunn/mastodon
|
import React from 'react';
import IconButton from '../../../components/icon_button';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl } from 'react-intl';
const messages = defineMessages({
add_poll: { id: 'poll_button.add_poll', defaultMessage: 'Add a poll' },
remove_poll: { id: 'poll_button.remove_poll', defaultMessage: 'Remove poll' },
});
const iconStyle = {
height: null,
lineHeight: '27px',
};
export default
@injectIntl
class PollButton extends React.PureComponent {
static propTypes = {
disabled: PropTypes.bool,
unavailable: PropTypes.bool,
active: PropTypes.bool,
onClick: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleClick = () => {
this.props.onClick();
}
render () {
const { intl, active, unavailable, disabled } = this.props;
if (unavailable) {
return null;
}
return (
<div className='compose-form__poll-button'>
<IconButton
icon='tasks'
title={intl.formatMessage(active ? messages.remove_poll : messages.add_poll)}
disabled={disabled}
onClick={this.handleClick}
className={`compose-form__poll-button-icon ${active ? 'active' : ''}`}
size={18}
inverted
style={iconStyle}
/>
</div>
);
}
}
|
src/components/users/UserAvatar.js
|
secretin/secretin-app
|
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import User from 'models/User';
const COLORS = [
'emerland',
'nephritis',
'belize-hole',
'wisteria',
'midnight-blue',
'sun-flower',
'pumpkin',
'pomegranate',
'silver',
'asbestos',
];
function getInitials(fullName) {
const names = fullName.split(' ');
if (names.length > 1) {
return `${names[0][0]}${names[1][0]}`.toUpperCase();
}
return fullName.substring(0, 2).toUpperCase();
}
function getAvatarColor(fullName) {
const colorIndex = fullName
.split('')
.reduce((sum, letter) => sum + letter.charCodeAt(), 0);
return COLORS[colorIndex % COLORS.length];
}
const propTypes = {
user: PropTypes.instanceOf(User),
size: PropTypes.oneOf(['base', 'large']),
};
const defaultProps = {
size: 'base',
};
function UserAvatar({ user, size }) {
const color = getAvatarColor(user.username);
const className = classNames(
'user-avatar',
`user-avatar--color-${color}`,
`user-avatar--size-${size}`
);
return (
<div className={className} title={user.username}>
{getInitials(user.username)}
</div>
);
}
UserAvatar.propTypes = propTypes;
UserAvatar.defaultProps = defaultProps;
export default UserAvatar;
|
src/components/Forms/__tests__/TextFieldHint.spec.js
|
instacart/Snacks
|
import React from 'react'
import renderer from 'react-test-renderer'
import { StyleRoot } from '@instacart/radium'
import TextFieldHint from '../TextFieldHint'
it('renders TextFieldHint correctly', () => {
const tree = renderer
.create(
<StyleRoot>
<div>
<TextFieldHint text="Text field hint text" show />
</div>
</StyleRoot>
)
.toJSON()
expect(tree).toMatchSnapshot()
})
it('renders TextFieldHint when show is false', () => {
const tree = renderer
.create(
<StyleRoot>
<div>
<TextFieldHint text="Text field hint text" show={false} />
</div>
</StyleRoot>
)
.toJSON()
expect(tree).toMatchSnapshot()
})
it('renders TextFieldHint when disabled', () => {
const tree = renderer
.create(
<StyleRoot>
<div>
<TextFieldHint text="Text field hint text" show disabled />
</div>
</StyleRoot>
)
.toJSON()
expect(tree).toMatchSnapshot()
})
|
src/browser/extension/popup/index.js
|
UrgBenri/UrgBenriWeb
|
import React from 'react';
import { render } from 'react-dom';
import Root from 'app/containers/Root';
chrome.runtime.getBackgroundPage(background => {
const { store, unsubscribe } = background.getStore();
render(
<Root store={store} />,
document.getElementById('root')
);
addEventListener('unload', unsubscribe, true);
});
|
src/js/components/icons/base/Camera.js
|
kylebyerly-hp/grommet
|
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-camera`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'camera');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M1,21 L1,7 L6,7 L8,3 L16,3 L18,7 L23,7 L23,21 L1,21 Z M12,18 C14.7614237,18 17,15.7614237 17,13 C17,10.2385763 14.7614237,8 12,8 C9.23857625,8 7,10.2385763 7,13 C7,15.7614237 9.23857625,18 12,18 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Camera';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
docs/src/app/components/pages/components/Menu/ExampleSimple.js
|
manchesergit/material-ui
|
import React from 'react';
import Paper from 'material-ui/Paper';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
const style = {
display: 'inline-block',
margin: '16px 32px 16px 0',
};
const MenuExampleSimple = () => (
<div>
<Paper style={style}>
<Menu>
<MenuItem primaryText="Maps" />
<MenuItem primaryText="Books" />
<MenuItem primaryText="Flights" />
<MenuItem primaryText="Apps" />
</Menu>
</Paper>
<Paper style={style}>
<Menu>
<MenuItem primaryText="Refresh" />
<MenuItem primaryText="Help & feedback" />
<MenuItem primaryText="Settings" />
<MenuItem primaryText="Sign out" />
</Menu>
</Paper>
</div>
);
export default MenuExampleSimple;
|
src/widgets/Anchor.js
|
xiaofan2406/react-starter-kit
|
import React from 'react';
import PropTypes from 'prop-types';
const Anchor = ({ href, children, ...rest }) => (
<a rel="noopener noreferrer" target="_blank" href={href} {...rest}>
{children}
</a>
);
Anchor.propTypes = {
href: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
};
export default Anchor;
|
ui/components/loading.js
|
danjac/podbaby
|
import React from 'react';
import Icon from './icon';
export default function () {
return (
<div className="text-center" style={{ marginTop: 50 }}>
<h1 style={{ fontFamily: 'GoodDog' }}><Icon icon="spinner" spin /> loading...</h1>
</div>
);
}
|
test/tabInactive-test.js
|
OnsenUI/react-onsenui
|
/* global describe it assert */
import React from 'react';
import ReactDOM from 'react-dom';
import {TabInactive} from '../dist/react-onsenui.js';
import TestUtils from 'react/lib/ReactTestUtils';
import rendersToComponent from './testUtil.js';
describe('TabInactive', function() {
rendersToComponent(
<TabInactive />,
'ons-tab-inactive'
);
});
|
src/js/pages/ResetPasswordPage.js
|
MichaelFKogan/project3
|
import React from 'react';
import DocumentTitle from 'react-document-title';
import { ResetPasswordForm } from 'react-stormpath';
export default class ResetPasswordPage extends React.Component {
render() {
return (
<DocumentTitle title={`Login`}>
<div className="container">
<div className="row">
<div className="col-xs-12">
<h3>Forgot Password</h3>
<hr />
</div>
</div>
<ResetPasswordForm />
</div>
</DocumentTitle>
);
}
}
|
app/javascript/mastodon/features/notifications/index.js
|
Toootim/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import { expandNotifications, scrollTopNotifications } from '../../actions/notifications';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import NotificationContainer from './containers/notification_container';
import { ScrollContainer } from 'react-router-scroll';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ColumnSettingsContainer from './containers/column_settings_container';
import { createSelector } from 'reselect';
import Immutable from 'immutable';
import LoadMore from '../../components/load_more';
import { debounce } from 'lodash';
const messages = defineMessages({
title: { id: 'column.notifications', defaultMessage: 'Notifications' },
});
const getNotifications = createSelector([
state => Immutable.List(state.getIn(['settings', 'notifications', 'shows']).filter(item => !item).keys()),
state => state.getIn(['notifications', 'items']),
], (excludedTypes, notifications) => notifications.filterNot(item => excludedTypes.includes(item.get('type'))));
const mapStateToProps = state => ({
notifications: getNotifications(state),
isLoading: state.getIn(['notifications', 'isLoading'], true),
isUnread: state.getIn(['notifications', 'unread']) > 0,
hasMore: !!state.getIn(['notifications', 'next']),
});
@connect(mapStateToProps)
@injectIntl
export default class Notifications extends React.PureComponent {
static propTypes = {
columnId: PropTypes.string,
notifications: ImmutablePropTypes.list.isRequired,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
intl: PropTypes.object.isRequired,
isLoading: PropTypes.bool,
isUnread: PropTypes.bool,
multiColumn: PropTypes.bool,
hasMore: PropTypes.bool,
};
static defaultProps = {
trackScroll: true,
};
dispatchExpandNotifications = debounce(() => {
this.props.dispatch(expandNotifications());
}, 300, { leading: true });
dispatchScrollToTop = debounce((top) => {
this.props.dispatch(scrollTopNotifications(top));
}, 100);
handleScroll = (e) => {
const { scrollTop, scrollHeight, clientHeight } = e.target;
const offset = scrollHeight - scrollTop - clientHeight;
this._oldScrollPosition = scrollHeight - scrollTop;
if (250 > offset && this.props.hasMore && !this.props.isLoading) {
this.dispatchExpandNotifications();
}
if (scrollTop < 100) {
this.dispatchScrollToTop(true);
} else {
this.dispatchScrollToTop(false);
}
}
componentDidUpdate (prevProps) {
if (this.node.scrollTop > 0 && (prevProps.notifications.size < this.props.notifications.size && prevProps.notifications.first() !== this.props.notifications.first() && !!this._oldScrollPosition)) {
this.node.scrollTop = this.node.scrollHeight - this._oldScrollPosition;
}
}
handleLoadMore = (e) => {
e.preventDefault();
this.dispatchExpandNotifications();
}
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('NOTIFICATIONS', {}));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
setRef = (c) => {
this.node = c;
}
setColumnRef = c => {
this.column = c;
}
render () {
const { intl, notifications, shouldUpdateScroll, isLoading, isUnread, columnId, multiColumn, hasMore } = this.props;
const pinned = !!columnId;
let loadMore = '';
let scrollableArea = '';
let unread = '';
let scrollContainer = '';
if (!isLoading && notifications.size > 0 && hasMore) {
loadMore = <LoadMore onClick={this.handleLoadMore} />;
}
if (isUnread) {
unread = <div className='notifications__unread-indicator' />;
}
if (isLoading && this.scrollableArea) {
scrollableArea = this.scrollableArea;
} else if (notifications.size > 0) {
scrollableArea = (
<div className='scrollable' onScroll={this.handleScroll} ref={this.setRef}>
{unread}
<div>
{notifications.map(item => <NotificationContainer key={item.get('id')} notification={item} accountId={item.get('account')} />)}
{loadMore}
</div>
</div>
);
} else {
scrollableArea = (
<div className='empty-column-indicator' ref={this.setRef}>
<FormattedMessage id='empty_column.notifications' defaultMessage="You don't have any notifications yet. Interact with others to start the conversation." />
</div>
);
}
if (pinned) {
scrollContainer = scrollableArea;
} else {
scrollContainer = (
<ScrollContainer scrollKey={`notifications-${columnId}`} shouldUpdateScroll={shouldUpdateScroll}>
{scrollableArea}
</ScrollContainer>
);
}
this.scrollableArea = scrollableArea;
return (
<Column ref={this.setColumnRef}>
<ColumnHeader
icon='bell'
active={isUnread}
title={intl.formatMessage(messages.title)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
>
<ColumnSettingsContainer />
</ColumnHeader>
{scrollContainer}
</Column>
);
}
}
|
src/SvgIcon/SvgIcon.spec.js
|
rhaedes/material-ui
|
/* eslint-env mocha */
import React from 'react';
import sinon from 'sinon';
import {shallow} from 'enzyme';
import {assert} from 'chai';
import SvgIcon from './SvgIcon';
import getMuiTheme from '../styles/getMuiTheme';
describe('<SvgIcon />', () => {
const muiTheme = getMuiTheme();
const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});
const path = <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" />;
it('renders children by default', () => {
const wrapper = shallowWithContext(
<SvgIcon>{path}</SvgIcon>
);
assert.ok(wrapper.contains(path), 'should contain the children');
});
it('renders children and color', () => {
const wrapper = shallowWithContext(
<SvgIcon color="red">{path}</SvgIcon>
);
assert.ok(wrapper.contains(path), 'should contain the children');
assert.equal(wrapper.node.props.style.fill, 'red', 'should have color set to red');
});
it('renders children and hoverColor when mouseEnter', () => {
const onMouseEnter = sinon.spy();
const wrapper = shallowWithContext(
<SvgIcon
className="material-icons"
color="red"
hoverColor="green"
onMouseEnter={onMouseEnter}
>
{path}
</SvgIcon>
);
assert.ok(wrapper.contains(path), 'should contain the children');
assert.equal(wrapper.node.props.style.fill, 'red', 'should have color set to red');
wrapper.simulate('mouseEnter');
assert.equal(wrapper.node.props.style.fill, 'green', 'should have color set to green after hover');
assert.equal(onMouseEnter.calledOnce, true,
'should have called onMouseEnter callback function');
});
it('renders children and call onMouseEnter callback', () => {
const onMouseEnter = sinon.spy();
const wrapper = shallowWithContext(
<SvgIcon onMouseEnter={onMouseEnter} hoverColor="green">{path}</SvgIcon>
);
assert.ok(wrapper.contains(path), 'should contain the children');
wrapper.simulate('mouseEnter');
assert.equal(onMouseEnter.calledOnce, true,
'should have called onMouseEnter callback function');
});
it('renders children and call onMouseEnter callback even when hoverColor is not set', () => {
const onMouseEnter = sinon.spy();
const wrapper = shallowWithContext(
<SvgIcon onMouseEnter={onMouseEnter}>{path}</SvgIcon>
);
assert.ok(wrapper.contains(path), 'should contain the children');
wrapper.simulate('mouseEnter');
assert.equal(onMouseEnter.calledOnce, true,
'should have called onMouseEnter callback function');
});
it('renders children and call onMouseLeave callback', () => {
const onMouseLeave = sinon.spy();
const wrapper = shallowWithContext(
<SvgIcon onMouseLeave={onMouseLeave} hoverColor="green">{path}</SvgIcon>
);
assert.ok(wrapper.contains(path), 'should contain the children');
wrapper.simulate('mouseLeave');
assert.equal(onMouseLeave.calledOnce, true,
'should have called onMouseLeave callback function');
});
it('renders children and call onMouseLeave callback even when hoverColor is not set', () => {
const onMouseLeave = sinon.spy();
const wrapper = shallowWithContext(
<SvgIcon onMouseLeave={onMouseLeave}>{path}</SvgIcon>
);
assert.ok(wrapper.contains(path), 'should contain the children');
wrapper.simulate('mouseLeave');
assert.equal(onMouseLeave.calledOnce, true,
'should have called onMouseLeave callback function');
});
it('renders children and overwrite styles', () => {
const style = {
backgroundColor: 'red',
};
const wrapper = shallowWithContext(
<SvgIcon style={style}>{path}</SvgIcon>
);
assert.equal(wrapper.get(0).props.style.backgroundColor, style.backgroundColor,
'should have backgroundColor to red');
});
});
|
client/src/signup/Form.js
|
petertrotman/adventurelookup
|
import React from 'react';
import { connect } from 'react-redux';
import { signupEmail } from './actions';
@connect(
state => ({ signup: state.signup }),
dispatch => ({ submitEmail: (email, validity) => (
dispatch(signupEmail(email, validity))
) }),
)
class SignupForm extends React.Component {
constructor(props) {
super(props);
this.state = { email: this.props.signup.email, validity: {} };
this.changeHandler = this.changeHandler.bind(this);
this.clickHandler = this.clickHandler.bind(this);
}
changeHandler(e) {
e.preventDefault();
this.setState({
email: e.target.value,
validity: e.target.validity,
});
}
clickHandler(e) {
e.preventDefault();
this.props.submitEmail(this.state.email, this.state.validity);
}
render() {
return (
<div className="signup-form">
<form>
<input
type="email"
value={this.state.email || ''}
onChange={this.changeHandler}
/>
<button
type="submit"
onClick={this.clickHandler}
>
Sign Up
</button>
</form>
<div>
{ this.props.signup.isValid
? null
: <span className="warning">Not a valid e-mail address.</span>
}
{ this.props.signup.completed
? <span className="success">You have successfully signed up!</span>
: null
}
</div>
</div>
);
}
}
SignupForm.propTypes = {
signup: React.PropTypes.object,
submitEmail: React.PropTypes.func,
};
export default SignupForm;
|
client/src/containers/FileListPage.js
|
RiddleMan/giant-privacy-spy
|
import React, { Component } from 'react';
import Paper from 'material-ui/Paper';
import { GridList } from 'material-ui/GridList';
import { GridFilePreview } from '../components/layout';
import { connect } from 'react-redux';
import { routeActions } from 'react-router-redux';
import { clear, getNextUnboxed, setGeoHash } from '../actions/list';
import { findDOMNode } from 'react-dom';
import CircularProgress from 'material-ui/CircularProgress';
/* eslint-disable */
const styles = {
gridList: {
overflowY: 'scroll'
},
};
/* eslint-enable */
class FileListPage extends Component {
constructor(props) {
super(props);
this.onResize = this.onResize.bind(this);
this.onScroll = this.onScroll.bind(this);
this.state = {
columnsCount: this.noOfColumns
};
this.onFileSelect = this.onFileSelect.bind(this);
}
onFileSelect(file) {
this.props.goToFile(file._id);
}
onScroll() {
const { getNextUnboxed } = this.props;
if(this.scroller.scrollTop + this.scroller.offsetHeight >= this.scroller.scrollHeight - 50)
getNextUnboxed();
}
onResize() {
if(this.state.columnsCount !== this.noOfColumns)
this.setState({
columnsCount: this.noOfColumns
});
}
get noOfColumns() {
if(window.matchMedia('(min-width: 1200px)').matches)
return 5;
if(window.matchMedia('(min-width: 768px)').matches)
return 4;
if(window.matchMedia('(min-width: 480px)').matches)
return 3;
return 2;
}
componentDidMount() {
const { setGeoHash, params: { id }, getNextUnboxed } = this.props;
setGeoHash(id);
getNextUnboxed();
window.addEventListener('resize', this.onResize);
this.scroller.addEventListener('wheel', this.onScroll);
}
componentWillUpdate(nextProps) {
if(nextProps.params.id !== this.props.params.id) {
const { setGeoHash, clear, getNextUnboxed } = this.props;
const { params: { id } } = nextProps;
clear();
setGeoHash(id);
getNextUnboxed();
}
}
componentWillUnmount() {
const { clear } = this.props;
clear();
window.removeEventListener('resize', this.onResize);
if(this.scroller)
this.scroller.removeEventListener('wheel', this.onScroll);
}
shouldComponentUpdate(nextProps) {
return this.props.list.isFetching !== nextProps.list.isFetching ||
this.props.list.files !== nextProps.list.files
|| this.props.params.id !== nextProps.params.id;
}
render() {
const { list } = this.props;
const { isFetching } = list;
const { columnsCount } = this.state;
return (
<Paper className='mainPage__overlay'>
<GridList
ref={(r) => this.scroller = findDOMNode(r)}
cols={columnsCount}
cellHeight={200}
style={styles.gridList}>
{list.files.map(file =>
<GridFilePreview
onSelect={this.onFileSelect}
key={file.fileId}
file={file}
{...file}/>)}
</GridList>
{ isFetching && <CircularProgress
style={{
position: 'fixed',
bottom: 10,
left: '50%',
transform: 'translateX(-50%)'
}}
size={50}/> }
</Paper>);
}
}
const mapStateToProps = (state) => {
const { list } = state;
return {
list
};
};
export default connect(mapStateToProps, {
setGeoHash,
getNextUnboxed,
clear,
goToFile: (fileId) => routeActions.push(`/file/${fileId}`)
})(FileListPage);
|
test/Scrollbars/hideTracks.js
|
malte-wessel/react-custom-scrollbars
|
import { Scrollbars } from 'react-custom-scrollbars';
import { render, unmountComponentAtNode } from 'react-dom';
import React from 'react';
export default function createTests(scrollbarWidth) {
describe('hide tracks', () => {
let node;
beforeEach(() => {
node = document.createElement('div');
document.body.appendChild(node);
});
afterEach(() => {
unmountComponentAtNode(node);
document.body.removeChild(node);
});
describe('when native scrollbars have a width', () => {
if (!scrollbarWidth) return;
describe('when content is greater than wrapper', () => {
it('should show tracks', done => {
render((
<Scrollbars
hideTracksWhenNotNeeded
style={{ width: 100, height: 100 }}>
<div style={{ width: 200, height: 200 }}/>
</Scrollbars>
), node, function callback() {
setTimeout(() => {
const { trackHorizontal, trackVertical } = this;
expect(trackHorizontal.style.visibility).toEqual('visible');
expect(trackVertical.style.visibility).toEqual('visible');
done();
}, 100);
});
});
});
describe('when content is smaller than wrapper', () => {
it('should hide tracks', done => {
render((
<Scrollbars
hideTracksWhenNotNeeded
style={{ width: 100, height: 100 }}>
<div style={{ width: 50, height: 50 }}/>
</Scrollbars>
), node, function callback() {
setTimeout(() => {
const { trackHorizontal, trackVertical } = this;
expect(trackHorizontal.style.visibility).toEqual('hidden');
expect(trackVertical.style.visibility).toEqual('hidden');
done();
}, 100);
});
});
});
});
});
}
|
frontend/src/DiscoverMovie/DiscoverMovieFooterLabel.js
|
geogolem/Radarr
|
import PropTypes from 'prop-types';
import React from 'react';
import SpinnerIcon from 'Components/SpinnerIcon';
import { icons } from 'Helpers/Props';
import styles from './DiscoverMovieFooterLabel.css';
function DiscoverMovieFooterLabel(props) {
const {
className,
label,
isSaving
} = props;
return (
<div className={className}>
{label}
{
isSaving &&
<SpinnerIcon
className={styles.savingIcon}
name={icons.SPINNER}
isSpinning={true}
/>
}
</div>
);
}
DiscoverMovieFooterLabel.propTypes = {
className: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
isSaving: PropTypes.bool.isRequired
};
DiscoverMovieFooterLabel.defaultProps = {
className: styles.label
};
export default DiscoverMovieFooterLabel;
|
app/components/resources/resourcePage.js
|
nypl-registry/browse
|
import React from 'react'
import ReactDOM from 'react-dom'
import { Link } from 'react-router'
import { connect } from 'react-redux'
import { resourceOverview, resourceByOwi } from '../../utils.js'
require('core-js/fn/object/entries')
import HeaderNav from '../shared/header_nav.js'
import Hero from '../shared/hero.js'
import Footer from '../shared/footer.js'
import { fetchResourceIfNeeded } from '../../actions'
const ResourcePage = React.createClass({
componentDidMount: function () {
const { dispatch, params } = this.props
dispatch(fetchResourceIfNeeded(params.id))
/* var self = this
resourceOverview(this.props.params.id, function (results) {
self.setState({data: results.data})
})
*/
},
shouldComponentUpdate: function (nextProps, nextState) {
return true
},
componentDidUpdate () {
ReactDOM.findDOMNode(this).scrollIntoView()
},
componentWillReceiveProps: function (nextProps) {
/* resourceOverview(nextProps.params.id, function (results) {
this.setState({data: results.data})
}.bind(this))
*/
},
renderEntry (entry) {
// counter++
var d = entry
// console.log('entry: ', entry)
var key = entry[0]
var values = entry[1]
if (key === '@context') return null
if (!Array.isArray(values)) values = [values]
entry.push([])
values.forEach((v) => {
if (v['@id'] && v['@id'].search('terms:') > -1) {
v = v['prefLabel']
}
if (typeof v === 'object') {
v['@id'] = v['@id'].replace(':', '/')
v['@id'] = v['@id'].replace('resourcetypes/', 'http://id.loc.gov/vocabulary/resourceTypes/')
v['@id'] = v['@id'].replace('language/', 'http://id.loc.gov/vocabulary/languages/')
v['@id'] = v['@id'].replace('res/', '/resources/')
if (v.title) v.prefLabel = v.title
if (!v.filename) v.filename = []
if (d[0].search('roles:') === -1) {
if (v.filename.length > 0) {
v.filename.forEach((c) => {
d[2].push(<Link to={v['@id']}><img src={`http://images.nypl.org/index.php?t=t&id=${c}`}/></Link>)
})
} else {
if (v['@id'].search('vocabulary/resourceTypes') > -1 || v['@id'].search('vocabulary/languages') > -1) {
d[2].push(<a href={`${v['@id']}`}>{v.prefLabel}</a>)
} else {
d[2].push(<Link to={v['@id']}>{v.prefLabel}</Link>)
}
}
} else {
d[0] = v.note
d[2].push(<Link to={v['@id']}>{v.prefLabel}</Link>)
}
} else {
if (d[0] === 'idBnum') {
if (this.state.data.suppressed) {
d[2].push(<span key={`link-${v}`}>{v} (SUPPRESSED)</span>)
} else {
d[2].push(<a key={`link-${v}`} href={`http://catalog.nypl.org/record=${v}`}>{v}</a>)
}
} else if (d[0] === 'idMssColl') {
d[2].push(<a key={`link-${v}`} href={`http://archives.nypl.org/${v}`}>{v}</a>)
} else if (d[0] === 'idMss') {
d[2].push(<a key={`link-${v}`} href={`http://archives.nypl.org/detail/${v}`}>{v}</a>)
} else if (d[0] === 'idOclc' || d[0] === 'idOclcExact') {
d[2].push(<a key={`link-${v}`} href={`http://worldcat.org/oclc/${v}`}>{v}</a>)
} else if (d[0] === 'idOwi') {
d[2].push(<a key={`link-${v}`} href={`http://classify.oclc.org/classify2/ClassifyDemo?owi=${v}`}>{v}</a>)
d[2].push(<OWILinks id={this.props.params.id} owi={v} />)
} else if (d[0] === 'idLccCoarse') {
d[2].push(<a key={`link-${v}`} href={`http://billi.nypl.org/classmark/${v}`}>{v}</a>)
} else if (d[0] === 'idMmsDb') {
if (this.state.data['@type'].indexOf('nypl:Item') > -1) {
d[2].push(<a key={`link-${v}`} href={`http://metadata.nypl.org/items/show/${v}`}>{v}</a>)
}
if (this.state.data['@type'].indexOf('nypl:Collection') > -1) {
d[2].push(<a key={`link-${v}`} href={`http://metadata.nypl.org/collection/${v}`}>{v}</a>)
}
} else {
d[2].push(<span key={`span-${v.toString()}`}>{v.toString()}<br/><br/></span>)
}
}
})
return (
<div key={key} className='resource-item-fields'>
<div key={key} style={(d[1].length === 0) ? { color: 'lightgrey' } : {}} className='resource-item-fields-label'>{d[0]}</div>
{d[2].map((v, ind) => { return <div key={`${key}.${ind}`} className='resource-item-fields-value'>{v}</div> })}
</div>
)
},
render () {
if (this.props.isFetching) {
return (
<div>
<HeaderNav title='data.nypl / Resources' link='/' />
<Hero
image={false}
textUpper=''
textMiddle='Loading...'
textLower='' />
</div>
)
} else {
// console.log(this.state.data.idBnum[0], '$%^&#$')
var textMiddle = ''
var textLower = ''
var imageUrl = {}
var textMiddleClass = 'agent-hero-middle-text'
var textLowerClass = 'agent-hero-lower-text'
if (this.props.item) {
// imageUrl = this.state.data.agent.depiction
textMiddle = this.props.item.title[0]
imageUrl = false
imageUrl = (this.props.item && this.props.item.idBnum && this.props.item.idBnum[0]) ? { idBnum: this.props.item.idBnum[0] } : false
// textLower = <span>{this.state.data.agent.description}</span>
// if (this.state.data.agent.name) if (this.state.data.agent.topFiveRoles.length>0){
// textLower = <span>{this.state.data.agent.description}<br/>{this.state.data.agent.topFiveRoles.join(", ")}</span>
// }
// console.log()
}
var entries = this.props.item ? Object.entries(this.props.item).map(this.renderEntry) : null
return (
<div>
<HeaderNav title='data.nypl / Resources' link='/' />
<Hero
textMiddleClass={textMiddleClass}
textLowerClass={textLowerClass}
image={{ url: imageUrl, title: '', link: '' }}
textUpper=''
textMiddle={textMiddle}
textLower={textLower} />
<div className='container'>
<div className='row'>
<div className='three columns'>
<div>
</div>
</div>
<div className='seven columns'>
<div>
{entries}
</div>
</div>
<div className='two columns resource-data-links'>
<a href={`/resources/${this.props.params.id}/jsonld`}>JSON-LD</a>
<br/>
<br/>
<a href={`/resources/${this.props.params.id}/nt`}>N-Triples</a>
</div>
</div>
</div>
<Footer />
</div>
)
}
}
})
const OWILinks = React.createClass({
componentDidMount: function () {
var self = this
if (this.props.owi) {
resourceByOwi(this.props.owi, function (results) {
self.setState({data: results.data})
})
}
},
shouldComponentUpdate: function (nextProps, nextState) {
return true
},
componentWillReceiveProps: function (nextProps) {
if (this.props.owi) {
resourceByOwi(nextProps.owi, function (results) {
this.setState({data: results.data})
}.bind(this))
}
},
render () {
var id = this.props.id
var hasRelated = false
var realtedEd = this.state.data.itemListElement.map((owi) => {
if (parseInt(id) === parseInt(owi.result['@id'].replace('res:', ''))) return <span/>
if (owi.result && owi.result.dateStart && owi.result.title) {
hasRelated = true
return <span key={owi.result['@id']}><Link to={owi.result['@id'].replace('res:', 'resources/')}> ({owi.result.dateStart}) {owi.result.title} </Link><br/></span>
} else if (owi.result && owi.result.title) {
hasRelated = true
return <span key={owi.result['@id']}><Link to={owi.result['@id'].replace('res:', 'resources/')}> {owi.result.title} </Link><br/></span>
} else {
return <span key={owi.result['@id']} />
}
})
if (hasRelated) {
return (
<div className='resource-owi-box'>
<span>Related Editions:</span>
<br/>
{realtedEd}
</div>
)
} else {
return (
<span/>
)
}
}
})
function mapStateToProps (state) {
const { resource } = state
const {
uri,
isFetching,
item
} = resource || {
isFetching: true,
item: null
}
return {
uri,
item,
isFetching
}
}
export default connect(mapStateToProps)(ResourcePage)
|
browser/modules/layerTree/controls/SelectControl.js
|
mapcentia/vidi
|
/*
* @author Alexander Shumilov
* @copyright 2013-2019 MapCentia ApS
* @license http://www.gnu.org/licenses/#AGPL GNU AFFERO GENERAL PUBLIC LICENSE 3
*/
import React from 'react';
import PropTypes from 'prop-types';
/**
* Select control component
*/
class SelectControl extends React.Component {
constructor(props) {
super(props);
}
render() {
let options = [];
options.push(<option key={`option_null`} value="">{__(`Select`)}</option>)
this.props.restriction.map((option, index) => {
options.push(<option key={`option_${index}`} value={option.value}>{option.alias}</option>)
});
return (<select id={this.props.id} value={this.props.value} className="form-control" onChange={(event) => { this.props.onChange(event.target.value) }}>
{options}
</select>);
}
}
SelectControl.propTypes = {
id: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
restriction: PropTypes.array.isRequired,
onChange: PropTypes.func.isRequired,
};
export { SelectControl };
|
src/js/Components/BackgroundPane/ImageBackgroundView.js
|
mattgordils/DropSplash
|
import React, { Component } from 'react';
import Button from 'Components/Common/Button';
import PlusIcon from 'assets/icons/plus-icon';
import InlineSVG from 'svg-inline-react/lib';
import ColorPicker from 'Components/Common/ColorPicker/ColorPicker';
import 'sass/components/common/inputs';
export default class App extends Component {
render () {
return (
<div className="has-button" key="view1">
<div className="content pane-padded">
<div className="ds-empty-content light">Upload Image</div>
<input type="file" className="hidden" />
</div>
<div className="pane-view-actions">
<Button
buttonClass="medium hollow"
label="Add Color Overlay"
clickEvent={this.props.clickHandler}
/>
</div>
</div>
);
}
}
|
docs/app/Examples/elements/Image/Variations/ImageAvatarExample.js
|
jcarbo/stardust
|
import React from 'react'
import { Image } from 'stardust'
const src = 'http://semantic-ui.com/images/wireframe/square-image.png'
const ImageAvatarExample = () => (
<div>
<Image src={src} avatar />
<span>Username</span>
</div>
)
export default ImageAvatarExample
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.