path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
app/common/components/AuthenticationManager.js
|
BitLooter/Stuffr-frontend
|
import React from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import log from 'loglevel'
import LoginDialog from './LoginDialog'
import RegisterDialog from './RegisterDialog'
import PasswordResetDialog from './PasswordResetDialog'
const MODE_LOGIN = Symbol('MODE_LOGIN')
const MODE_REGISTER = Symbol('MODE_REGISTER')
const MODE_PWRESET = Symbol('MODE_PWRESET')
const reduxWrapper = connect(
function mapStateToProps (state) {
return {
authenticated: state.auth.authenticated
}
}
)
class AuthenticationManagerComponent extends React.Component {
static propTypes = {
children: PropTypes.node.isRequired,
authenticated: PropTypes.bool.isRequired,
onLogin: PropTypes.func.isRequired,
onRegister: PropTypes.func
}
constructor (props) {
super(props)
this.state = {
mode: MODE_LOGIN
}
}
switchMode (mode) {
log.info(`Authentication mode switching to ${String(mode)}`)
this.setState({mode})
}
render () {
// onRegister is optional
const handleRegister = this.props.onRegister || this.props.onLogin
let component
// TODO: Password reset mode
if (this.props.authenticated) {
// Rest of the UI is only rendered if user is authenticated
component = <div>{this.props.children}</div>
} else if (this.state.mode === MODE_LOGIN) {
// TODO: Allow to disable user register button
component = <LoginDialog
onLogin={this.props.onLogin}
handleSwitchToRegister={() => this.switchMode(MODE_REGISTER)}
handleSwitchToPWReset={() => this.switchMode(MODE_PWRESET)} />
} else if (this.state.mode === MODE_REGISTER) {
component = <RegisterDialog
onRegister={handleRegister}
handleSwitchToLogin={() => this.switchMode(MODE_LOGIN)} />
} else if (this.state.mode === MODE_PWRESET) {
component = <PasswordResetDialog
handleSwitchToLogin={() => this.switchMode(MODE_LOGIN)} />
} else {
log.error(`AuthenticationManager: Unknown mode ${this.state.mode}`)
}
return component
}
}
const AuthenticationManager = reduxWrapper(AuthenticationManagerComponent)
export default AuthenticationManager
|
third_party/prometheus_ui/base/web/ui/node_modules/reactstrap/src/__tests__/ModalBody.spec.js
|
GoogleCloudPlatform/prometheus-engine
|
import React from 'react';
import { shallow } from 'enzyme';
import { ModalBody } from '../';
describe('ModalBody', () => {
it('should render with "modal-body" class', () => {
const wrapper = shallow(<ModalBody>Yo!</ModalBody>);
expect(wrapper.text()).toBe('Yo!');
expect(wrapper.hasClass('modal-body')).toBe(true);
});
it('should render additional classes', () => {
const wrapper = shallow(<ModalBody className="other">Yo!</ModalBody>);
expect(wrapper.hasClass('other')).toBe(true);
expect(wrapper.hasClass('modal-body')).toBe(true);
});
it('should render custom tag', () => {
const wrapper = shallow(<ModalBody tag="main">Yo!</ModalBody>);
expect(wrapper.text()).toBe('Yo!');
expect(wrapper.hasClass('modal-body')).toBe(true);
expect(wrapper.type()).toBe('main');
});
});
|
src/index.js
|
nebgnahz/marry-guess
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
src/index.js
|
mitchallen/react-card-grey
|
/*
Module: @mitchallen/react-card-grey
Author: Mitch Allen
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
// import { withRouter } from 'react-router-dom';
import Paper from 'material-ui/Paper';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
const paperStyle = {
height: 300,
width: 300,
margin: 20,
textAlign: 'center',
display: 'inline-block',
backgroundColor: 'rgba(0, 0, 0, 0.5)'
};
// const CardGrey = ({ children, ...props }) => (
const CardGrey = ({ children }) => (
<div>
<MuiThemeProvider>
<Paper style={paperStyle} zDepth={5}>
{children}
</Paper>
</MuiThemeProvider>
</div>
);
CardGrey.propTypes = {
children: PropTypes.object
};
export default CardGrey;
|
node_modules/antd/es/anchor/index.js
|
prodigalyijun/demo-by-antd
|
import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import addEventListener from 'rc-util/es/Dom/addEventListener';
import AnchorLink from './AnchorLink';
import Affix from '../affix';
import AnchorHelper, { getDefaultTarget } from './anchorHelper';
var Anchor = function (_React$Component) {
_inherits(Anchor, _React$Component);
function Anchor(props) {
_classCallCheck(this, Anchor);
var _this = _possibleConstructorReturn(this, (Anchor.__proto__ || Object.getPrototypeOf(Anchor)).call(this, props));
_this.handleScroll = function () {
_this.setState({
activeAnchor: _this.anchorHelper.getCurrentAnchor(_this.props.offsetTop, _this.props.bounds)
});
};
_this.updateInk = function () {
var activeAnchor = _this.anchorHelper.getCurrentActiveAnchor();
if (activeAnchor) {
_this.refs.ink.style.top = activeAnchor.offsetTop + activeAnchor.clientHeight / 2 - 4.5 + 'px';
}
};
_this.clickAnchorLink = function (href, component) {
_this._avoidInk = true;
_this.refs.ink.style.top = component.offsetTop + component.clientHeight / 2 - 4.5 + 'px';
_this.anchorHelper.scrollTo(href, _this.props.offsetTop, getDefaultTarget, function () {
_this._avoidInk = false;
});
};
_this.renderAnchorLink = function (child) {
var href = child.props.href;
var type = child.type;
if (type.__ANT_ANCHOR_LINK && href) {
_this.anchorHelper.addLink(href);
return React.cloneElement(child, {
onClick: _this.clickAnchorLink,
prefixCls: _this.props.prefixCls,
bounds: _this.props.bounds,
affix: _this.props.affix || _this.props.showInkInFixed,
offsetTop: _this.props.offsetTop
});
}
return child;
};
_this.state = {
activeAnchor: null,
animated: true
};
_this.anchorHelper = new AnchorHelper();
return _this;
}
_createClass(Anchor, [{
key: 'getChildContext',
value: function getChildContext() {
return {
anchorHelper: this.anchorHelper
};
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this.handleScroll();
this.updateInk();
this.scrollEvent = addEventListener((this.props.target || getDefaultTarget)(), 'scroll', this.handleScroll);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
if (this.scrollEvent) {
this.scrollEvent.remove();
}
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
if (!this._avoidInk) {
this.updateInk();
}
}
}, {
key: 'render',
value: function render() {
var _classNames;
var _props = this.props,
prefixCls = _props.prefixCls,
offsetTop = _props.offsetTop,
style = _props.style,
_props$className = _props.className,
className = _props$className === undefined ? '' : _props$className,
affix = _props.affix,
showInkInFixed = _props.showInkInFixed;
var _state = this.state,
activeAnchor = _state.activeAnchor,
animated = _state.animated;
var inkClass = classNames((_classNames = {}, _defineProperty(_classNames, prefixCls + '-ink-ball', true), _defineProperty(_classNames, 'animated', animated), _defineProperty(_classNames, 'visible', !!activeAnchor), _classNames));
var wrapperClass = classNames(_defineProperty({}, prefixCls + '-wrapper', true), className);
var anchorClass = classNames(prefixCls, {
'fixed': !affix && !showInkInFixed
});
var anchorContent = React.createElement(
'div',
{ className: wrapperClass, style: style },
React.createElement(
'div',
{ className: anchorClass },
React.createElement(
'div',
{ className: prefixCls + '-ink' },
React.createElement('span', { className: inkClass, ref: 'ink' })
),
React.Children.toArray(this.props.children).map(this.renderAnchorLink)
)
);
return !affix ? anchorContent : React.createElement(
Affix,
{ offsetTop: offsetTop },
anchorContent
);
}
}]);
return Anchor;
}(React.Component);
export default Anchor;
Anchor.Link = AnchorLink;
Anchor.defaultProps = {
prefixCls: 'ant-anchor',
affix: true,
showInkInFixed: false
};
Anchor.childContextTypes = {
anchorHelper: PropTypes.any
};
|
src/svg-icons/social/group-add.js
|
rscnt/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialGroupAdd = (props) => (
<SvgIcon {...props}>
<path d="M8 10H5V7H3v3H0v2h3v3h2v-3h3v-2zm10 1c1.66 0 2.99-1.34 2.99-3S19.66 5 18 5c-.32 0-.63.05-.91.14.57.81.9 1.79.9 2.86s-.34 2.04-.9 2.86c.28.09.59.14.91.14zm-5 0c1.66 0 2.99-1.34 2.99-3S14.66 5 13 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm6.62 2.16c.83.73 1.38 1.66 1.38 2.84v2h3v-2c0-1.54-2.37-2.49-4.38-2.84zM13 13c-2 0-6 1-6 3v2h12v-2c0-2-4-3-6-3z"/>
</SvgIcon>
);
SocialGroupAdd = pure(SocialGroupAdd);
SocialGroupAdd.displayName = 'SocialGroupAdd';
export default SocialGroupAdd;
|
modules/__tests__/Redirect-test.js
|
cold-brew-coding/react-router
|
/*eslint-env mocha */
import expect from 'expect'
import React from 'react'
import createHistory from 'history/lib/createMemoryHistory'
import Redirect from '../Redirect'
import Router from '../Router'
import Route from '../Route'
describe('A <Redirect>', function () {
let node
beforeEach(function () {
node = document.createElement('div')
})
afterEach(function () {
React.unmountComponentAtNode(node)
})
it('works', function (done) {
React.render((
<Router history={createHistory('/notes/5')}>
<Route path="/messages/:id" />
<Redirect from="/notes/:id" to="/messages/:id" />
</Router>
), node, function () {
expect(this.state.location.pathname).toEqual('/messages/5')
done()
})
})
})
|
src/encoded/static/components/anno_viz.js
|
T2DREAM/t2dream-portal
|
import React from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import _ from 'underscore';
import moment from 'moment';
import globals from './globals';
import { Panel, PanelHeading, TabPanel, TabPanelPane } from '../libs/bootstrap/panel';
import { Modal, ModalHeader, ModalBody, ModalFooter } from '../libs/bootstrap/modal';
import { auditDecor, auditsDisplayed, AuditIcon } from './audit';
import StatusLabel from './statuslabel';
import { requestFiles, DownloadableAccession, BrowserSelector } from './objectutils';
import { Graph, JsonGraph } from './graph';
import { qcModalContent, qcIdToDisplay } from './quality_metric';
import { softwareVersionList } from './software';
import { FetchedData, Param } from './fetched';
import { collapseIcon } from '../libs/svg-icons';
import { SortTablePanel, SortTable } from './sorttable';
var button = require('../libs/bootstrap/button');
export const FileGallery = createReactClass({
propTypes: {
context: PropTypes.object, // Dataset object whose annotations we're rendering
},
contextTypes: {
session: PropTypes.object, // Login information
location_href: PropTypes.string, // URL of this variant search page, including query string stuff
},
render: function () {
const { context } = this.props;
return (
<FetchedData ignoreErrors>
<Param name="schemas" url="/profiles/" />
<FileGalleryRenderer context={context} session={this.context.session} />
</FetchedData>
);
},
});
export function assembleGraph(context, session, infoNodeId, query, regions, viz) {
// Create an empty graph architecture that we fill in next.
const jsonGraph = new JsonGraph(context.accession);
const queryNodeId = query;
const queryNodeLabel = query;
const fileCssClass = `pipeline-node-file${infoNodeId === queryNodeId ? ' active' : ''}`;
jsonGraph.addNode(queryNodeId, queryNodeLabel, {
cssClass: fileCssClass,
type: 'Viz',
shape: 'rect',
cornerRadius: 16,
});
Object.keys(viz).forEach((vizId) => {
const annotations = viz[vizId];
const annotationNodeId = annotations['id'];
const annotationNodeLabel = annotations['id'];
const regionNodeId = annotations['value'];
const regionNodeLabel = annotations['value'];
jsonGraph.addNode(annotationNodeId, annotationNodeLabel, {
cssClass: fileCssClass,
type: 'Viz',
shape: 'rect',
cornerRadius: 16,
});
jsonGraph.addNode(regionNodeId, regionNodeLabel, {
cssClass: fileCssClass,
type: 'Viz',
shape: 'rect',
cornerRadius: 16,
});
jsonGraph.addEdge(queryNodeId, annotationNodeId);
jsonGraph.addEdge(annotationNodeId, regionNodeId);
});
return { graph: jsonGraph };
}
// Function to render the variant annotation graph, and it gets called after the viz results i.e. annotation type, state and biosample
const FileGalleryRenderer = createReactClass({
propTypes: {
context: PropTypes.object, // Dataset whose files we're rendering
hideGraph: PropTypes.bool, // T to hide graph display
},
contextTypes: {
session: PropTypes.object,
session_properties: PropTypes.object,
location_href: PropTypes.string,
},
getInitialState: function () {
return {
infoNodeId: '', // @id of node whose info panel is open
infoModalOpen: false, // True if info modal is open
relatedFiles: [],
};
},
// Called from child components when the selected node changes.
setInfoNodeId: function (nodeId) {
this.setState({ infoNodeId: nodeId });
},
setInfoNodeVisible: function (visible) {
this.setState({ infoNodeVisible: visible });
},
render: function () {
const { context, schemas, hideGraph } = this.props;
let jsonGraph;
const query = context['query'];
const regions = context['regions'];
const viz = context['viz'];
const loggedIn = this.context.session && this.context.session['auth.userid'];
// Build node graph of the files and analysis steps with this experiment
if ( regions && regions.length ) {
const { graph } = assembleGraph(context, this.context.session, this.state.infoNodeId, query, regions, viz);
jsonGraph = graph;
return (
<Panel>
{/* Display the strip of filgering controls */}
{!hideGraph ?
<FileGraph
context={context}
items={regions}
graph={jsonGraph}
query={query}
viz={viz}
session={this.context.session}
infoNodeId={this.state.infoNodeId}
setInfoNodeId={this.setInfoNodeId}
infoNodeVisible={this.state.infoNodeVisible}
setInfoNodeVisible={this.setInfoNodeVisible}
sessionProperties={this.context.session_properties}
forceRedraw
/>
: null}
</Panel>
);
}
else {
return <div className="browser-error"> No results available for selection</div>;
}
}
});
const CollapsingTitle = createReactClass({
propTypes: {
title: PropTypes.string.isRequired, // Title to display in the title bar
handleCollapse: PropTypes.func.isRequired, // Function to call to handle click in collapse button
collapsed: PropTypes.bool, // T if the panel this is over has been collapsed
},
render: function () {
const { title, handleCollapse, collapsed } = this.props;
return (
<div className="collapsing-title">
<button className="collapsing-title-trigger pull-left" data-trigger onClick={handleCollapse}>{collapseIcon(collapsed, 'collapsing-title-icon')}</button>
<h4>{title}</h4>
</div>
);
},
});
const FileGraphComponent = createReactClass({
propTypes: {
items: PropTypes.array, // Array of annotation information we're graphing
graph: PropTypes.object, // JsonGraph object generated from files
setInfoNodeId: PropTypes.func, // Function to call to set the currently selected node ID
setInfoNodeVisible: PropTypes.func, // Function to call to set the visibility of the node's modal
infoNodeId: PropTypes.string, // ID of selected node in graph
infoNodeVisible: PropTypes.bool, // True if node's modal is vibible
session: PropTypes.object, // Current user's login information
sessionProperties: PropTypes.object, // True if logged in user is an admin
},
getInitialState: function () {
return {
infoModalOpen: false, // Graph information modal open
};
},
// Render metadata if a graph node is selected.
// jsonGraph: JSON graph data.
// infoNodeId: ID of the selected node
detailNodes: function (jsonGraph, infoNodeId, session, sessionProperties) {
let meta;
// Find data matching selected node, if any
if (infoNodeId) {
if (infoNodeId.indexOf('qc:') >= 0) {
// QC subnode.
const subnode = jsonGraph.getSubnode(infoNodeId);
if (subnode) {
meta = qcDetailsView(subnode, this.props.schemas);
meta.type = subnode['@type'][0];
}
} else if (infoNodeId.indexOf('coalesced:') >= 0) {
// Coalesced contributing files.
const node = jsonGraph.getNode(infoNodeId);
if (node) {
const currCoalescedFiles = this.state.coalescedFiles;
if (currCoalescedFiles[node.metadata.contributing]) {
// We have the requested coalesced files in the cache, so just display
// them.
node.metadata.coalescedFiles = currCoalescedFiles[node.metadata.contributing];
meta = coalescedDetailsView(node);
meta.type = 'File';
} else if (!this.contributingRequestOutstanding) {
// We don't have the requested coalesced files in the cache, so we have to
// request them from the DB.
this.contributingRequestOutstanding = true;
requestFiles(node.metadata.ref).then((contributingFiles) => {
this.contributingRequestOutstanding = false;
currCoalescedFiles[node.metadata.contributing] = contributingFiles;
this.setState({ coalescedFiles: currCoalescedFiles });
}).catch(() => {
this.contributingRequestOutstanding = false;
currCoalescedFiles[node.metadata.contributing] = [];
this.setState({ coalescedFiles: currCoalescedFiles });
});
}
}
} else {
// A regular or contributing file.
const node = jsonGraph.getNode(infoNodeId);
if (node) {
if (node.metadata.contributing) {
// This is a contributing file, and its @id is in
// node.metadata.contributing. See if the file is in the cache.
const currContributing = this.state.contributingFiles;
if (currContributing[node.metadata.contributing]) {
// We have this file's object in the cache, so just display it.
node.metadata.ref = currContributing[node.metadata.contributing];
meta = globals.graph_detail.lookup(node)(node, this.handleNodeClick, this.props.auditIndicators, this.props.auditDetail, session, sessionProperties);
meta.type = node['@type'][0];
} else if (!this.contributingRequestOutstanding) {
// We don't have this file's object in the cache, so request it from
// the DB.
this.contributingRequestOutstanding = true;
requestFiles([node.metadata.contributing]).then((contributingFile) => {
this.contributingRequestOutstanding = false;
currContributing[node.metadata.contributing] = contributingFile[0];
this.setState({ contributingFiles: currContributing });
}).catch(() => {
this.contributingRequestOutstanding = false;
currContributing[node.metadata.contributing] = {};
this.setState({ contributingFiles: currContributing });
});
}
} else {
// Regular File data in the node from when we generated the graph. Just
// display the file data from there.
meta = globals.graph_detail.lookup(node)(node, this.handleNodeClick, this.props.auditIndicators, this.props.auditDetail, session, sessionProperties);
meta.type = node['@type'][0];
}
}
}
}
return meta;
},
handleCollapse: function () {
// Handle click on panel collapse icon
this.setState({ collapsed: !this.state.collapsed });
},
closeModal: function () {
// Called when user wants to close modal somehow
this.props.setInfoNodeVisible(false);
},
render: function () {
const { session, sessionProperties, items, graph, infoNodeId, infoNodeVisible } = this.props;
const files = items;
const modalTypeMap = {
File: 'file',
Step: 'analysis-step',
Viz: 'viz',
QualityMetric: 'quality-metric',
};
// If we have a graph, or if we have a selected assembly/annotation, draw the graph panel
const goodGraph = graph && Object.keys(graph).length;
const loggedIn = this.context.session && this.context.session['auth.userid'];
if (goodGraph){
const meta = this.detailNodes(graph, infoNodeId, session, sessionProperties);
const modalClass = meta ? `graph-modal-${modalTypeMap[meta.type]}` : '';
return (
<div>
<Graph graph={graph} nodeClickHandler={this.handleNodeClick} nodeMouseenterHandler={this.handleHoverIn} nodeMouseleaveHandler={this.handleHoverOut} noDefaultClasses forceRedraw />
{meta && infoNodeVisible ?
<Modal closeModal={this.closeModal}>
<ModalHeader closeModal={this.closeModal} addCss={modalClass}>
{meta ? meta.header : null}
</ModalHeader>
<ModalBody>
{meta ? meta.body : null}
</ModalBody>
<ModalFooter closeModal={<button className="btn btn-info" onClick={this.closeModal}>Close</button>} />
</Modal>
: null}
</div>
);
return null;
}
},
});
const FileGraph = auditDecor(FileGraphComponent);
// Display the metadata of the selected file in the graph
const FileDetailView = function (node, qcClick, auditIndicators, auditDetail, session, sessionProperties) {
// The node is for a file
const selectedFile = node.metadata.ref;
let body = null;
let header = null;
const loggedIn = !!(session && session['auth.userid']);
const adminUser = !!(sessionProperties && sessionProperties.admin);
if (selectedFile && Object.keys(selectedFile).length) {
let contributingAccession;
if (node.metadata.contributing) {
const accessionStart = selectedFile.dataset.indexOf('/', 1) + 1;
const accessionEnd = selectedFile.dataset.indexOf('/', accessionStart) - accessionStart;
contributingAccession = selectedFile.dataset.substr(accessionStart, accessionEnd);
}
const dateString = !!selectedFile.date_created && moment.utc(selectedFile.date_created).format('YYYY-MM-DD');
header = (
<div className="details-view-info">
<h4>{selectedFile.file_type} <a href={selectedFile['@id']}>{selectedFile.title}</a></h4>
</div>
);
body = (
<div>
<dl className="key-value">
{selectedFile.output_type ?
<div data-test="output">
<dt>Output</dt>
<dd>{selectedFile.output_type}</dd>
</div>
: null}
</dl>
</div>
);
} else {
header = (
<div className="details-view-info">
<h4>Unknown</h4>
</div>
);
body = <p className="browser-error">No information available</p>;
}
return { header: header, body: body };
};
globals.graph_detail.register(FileDetailView, 'File');
|
src/Footer.js
|
leeppolis/bookmarks
|
import React, { Component } from 'react';
class Footer extends Component {
render() {
return (
<div className="body-wrapper">
<footer>
<small>
© <a href="https://simonelippolis.com">Simone Lippolis</a>. All opinions are mine.
</small>
</footer>
</div>
);
}
}
export default Footer;
|
app/javascript/mastodon/features/getting_started/index.js
|
ikuradon/mastodon
|
import React from 'react';
import Column from '../ui/components/column';
import ColumnLink from '../ui/components/column_link';
import ColumnSubheading from '../ui/components/column_subheading';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { me, profile_directory, showTrends } from '../../initial_state';
import { fetchFollowRequests } from 'mastodon/actions/accounts';
import { List as ImmutableList } from 'immutable';
import NavigationContainer from '../compose/containers/navigation_container';
import Icon from 'mastodon/components/icon';
import LinkFooter from 'mastodon/features/ui/components/link_footer';
import TrendsContainer from './containers/trends_container';
const messages = defineMessages({
home_timeline: { id: 'tabs_bar.home', defaultMessage: 'Home' },
notifications: { id: 'tabs_bar.notifications', defaultMessage: 'Notifications' },
public_timeline: { id: 'navigation_bar.public_timeline', defaultMessage: 'Federated timeline' },
settings_subheading: { id: 'column_subheading.settings', defaultMessage: 'Settings' },
community_timeline: { id: 'navigation_bar.community_timeline', defaultMessage: 'Local timeline' },
direct: { id: 'navigation_bar.direct', defaultMessage: 'Direct messages' },
bookmarks: { id: 'navigation_bar.bookmarks', defaultMessage: 'Bookmarks' },
preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' },
follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' },
favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' },
blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' },
domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Hidden domains' },
mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' },
pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned toots' },
lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' },
discover: { id: 'navigation_bar.discover', defaultMessage: 'Discover' },
personal: { id: 'navigation_bar.personal', defaultMessage: 'Personal' },
security: { id: 'navigation_bar.security', defaultMessage: 'Security' },
menu: { id: 'getting_started.heading', defaultMessage: 'Getting started' },
profile_directory: { id: 'getting_started.directory', defaultMessage: 'Profile directory' },
});
const mapStateToProps = state => ({
myAccount: state.getIn(['accounts', me]),
columns: state.getIn(['settings', 'columns']),
unreadFollowRequests: state.getIn(['user_lists', 'follow_requests', 'items'], ImmutableList()).size,
});
const mapDispatchToProps = dispatch => ({
fetchFollowRequests: () => dispatch(fetchFollowRequests()),
});
const badgeDisplay = (number, limit) => {
if (number === 0) {
return undefined;
} else if (limit && number >= limit) {
return `${limit}+`;
} else {
return number;
}
};
const NAVIGATION_PANEL_BREAKPOINT = 600 + (285 * 2) + (10 * 2);
export default @connect(mapStateToProps, mapDispatchToProps)
@injectIntl
class GettingStarted extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
intl: PropTypes.object.isRequired,
myAccount: ImmutablePropTypes.map.isRequired,
columns: ImmutablePropTypes.list,
multiColumn: PropTypes.bool,
fetchFollowRequests: PropTypes.func.isRequired,
unreadFollowRequests: PropTypes.number,
unreadNotifications: PropTypes.number,
};
componentDidMount () {
const { fetchFollowRequests, multiColumn } = this.props;
if (!multiColumn && window.innerWidth >= NAVIGATION_PANEL_BREAKPOINT) {
this.context.router.history.replace('/home');
return;
}
fetchFollowRequests();
}
render () {
const { intl, myAccount, columns, multiColumn, unreadFollowRequests } = this.props;
const navItems = [];
let height = (multiColumn) ? 0 : 60;
if (multiColumn) {
navItems.push(
<ColumnSubheading key='header-discover' text={intl.formatMessage(messages.discover)} />,
<ColumnLink key='community_timeline' icon='users' text={intl.formatMessage(messages.community_timeline)} to='/public/local' />,
<ColumnLink key='public_timeline' icon='globe' text={intl.formatMessage(messages.public_timeline)} to='/public' />,
);
height += 34 + 48*2;
if (profile_directory) {
navItems.push(
<ColumnLink key='directory' icon='address-book' text={intl.formatMessage(messages.profile_directory)} to='/directory' />,
);
height += 48;
}
navItems.push(
<ColumnSubheading key='header-personal' text={intl.formatMessage(messages.personal)} />,
);
height += 34;
} else if (profile_directory) {
navItems.push(
<ColumnLink key='directory' icon='address-book' text={intl.formatMessage(messages.profile_directory)} to='/directory' />,
);
height += 48;
}
if (multiColumn && !columns.find(item => item.get('id') === 'HOME')) {
navItems.push(
<ColumnLink key='home' icon='home' text={intl.formatMessage(messages.home_timeline)} to='/home' />,
);
height += 48;
}
navItems.push(
<ColumnLink key='direct' icon='envelope' text={intl.formatMessage(messages.direct)} to='/conversations' />,
<ColumnLink key='bookmark' icon='bookmark' text={intl.formatMessage(messages.bookmarks)} to='/bookmarks' />,
<ColumnLink key='favourites' icon='star' text={intl.formatMessage(messages.favourites)} to='/favourites' />,
<ColumnLink key='lists' icon='list-ul' text={intl.formatMessage(messages.lists)} to='/lists' />,
);
height += 48*4;
if (myAccount.get('locked') || unreadFollowRequests > 0) {
navItems.push(<ColumnLink key='follow_requests' icon='user-plus' text={intl.formatMessage(messages.follow_requests)} badge={badgeDisplay(unreadFollowRequests, 40)} to='/follow_requests' />);
height += 48;
}
if (!multiColumn) {
navItems.push(
<ColumnSubheading key='header-settings' text={intl.formatMessage(messages.settings_subheading)} />,
<ColumnLink key='preferences' icon='gears' text={intl.formatMessage(messages.preferences)} href='/settings/preferences' />,
);
height += 34 + 48;
}
return (
<Column bindToDocument={!multiColumn} label={intl.formatMessage(messages.menu)}>
{multiColumn && <div className='column-header__wrapper'>
<h1 className='column-header'>
<button>
<Icon id='bars' className='column-header__icon' fixedWidth />
<FormattedMessage id='getting_started.heading' defaultMessage='Getting started' />
</button>
</h1>
</div>}
<div className='getting-started'>
<div className='getting-started__wrapper' style={{ height }}>
{!multiColumn && <NavigationContainer />}
{navItems}
</div>
{!multiColumn && <div className='flex-spacer' />}
<LinkFooter withHotkeys={multiColumn} />
</div>
{multiColumn && showTrends && <TrendsContainer />}
</Column>
);
}
}
|
src/parser/core/tests/snapshotTest.js
|
sMteX/WoWAnalyzer
|
import React from 'react';
import PropTypes from 'prop-types';
import renderer from 'react-test-renderer';
import { i18n } from 'interface/RootLocalizationProvider';
import { loadLog, parseLog } from './log-tools';
class ParserContextProvider extends React.PureComponent {
static propTypes = {
parser: PropTypes.object,
children: PropTypes.node,
};
static childContextTypes = {
parser: PropTypes.object,
};
getChildContext() {
return {
parser: this.props.parser,
};
}
render() {
return this.props.children;
}
}
function renderWithParser(output, parser) {
return renderer.create(<ParserContextProvider parser={parser}>{output}</ParserContextProvider>).toJSON();
}
export function statistic(analyzer, parser=null) {
const stat = analyzer.statistic({ i18n });
return renderWithParser(stat, parser);
}
export function tab(analyzer, parser=null) {
const tab = analyzer.tab().render();
return renderWithParser(tab, parser);
}
/**
* Perform a test using the Jest snapshot tool (https://jestjs.io/docs/en/snapshot-testing#snapshot-testing-with-jest).
*
* This is a consistency test, testing only that the output of the given
* function (default: statistic()) matches the snapshotted value. See
* the docs linked above for information on how to update a snapshot.
*
* Honestly no longer sure this deserves its own function.
*
* @param {object} parserClass - CombatLogParser class. Uninstantiated
* @param {object} moduleClass - Analyzer or other module. Uninstantiated
* @param {string} key - Log identifier
* @param {function} propFn - Function returning serializable output to be tested for consistency. Optional.
*/
export default function snapshotTest(parserClass, moduleClass, key, propFn = statistic, suppressLog = true, suppressWarn = true) {
return () => {
return loadLog(key).then(log => {
const parser = parseLog(parserClass, log, suppressLog, suppressWarn);
expectSnapshot(parser, moduleClass, propFn);
});
};
}
export function expectSnapshot(parser, moduleClass, propFn = statistic) {
const result = propFn(parser.getModule(moduleClass), parser);
expect(result).toMatchSnapshot();
}
|
src/components/sortable_list/sortable_list.js
|
thinktopography/reframe
|
import PropTypes from 'prop-types'
import React from 'react'
import Item from './item'
import _ from 'lodash'
class SortableList extends React.Component {
render() {
const { items } = this.props
return (
<div className="reframe-sortable-list">
{ items.map((item, index) => (
<Item key={`item_${index}`} { ...this._getItem(item, index) } />
))}
</div>
)
}
componentDidMount() {
if(this.props.defaultValue) this._handleSet()
}
componentDidUpdate(prevProps) {
const { defaultValue, items, onUpdate } = this.props
if(!_.isEqual(prevProps.items, items)) onUpdate(items)
if(!_.isEqual(prevProps.defaultValue, defaultValue)) this._handleSet()
}
_getItem(item, index) {
const { onMove, onToggle } = this.props
return {
label: item.label,
checked: item.checked,
index,
onMove: onMove.bind(this),
onToggle: onToggle.bind(this)
}
}
_handleSet() {
const { defaultValue, onSet } = this.props
onSet(defaultValue.map(item => ({
...item,
checked: item.checked !== false
})))
}
}
export default SortableList
|
src/routes/Editor/components/EmailsTab.js
|
peksi/ilmomasiina
|
import React from 'react';
import PropTypes from 'prop-types';
import { Textarea } from 'formsy-react-components';
class EmailsTab extends React.Component {
static propTypes = {
onDataChange: PropTypes.func.isRequired,
event: PropTypes.object,
};
render() {
return (
<div>
<Textarea
rows={10}
name="verificationEmail"
value={this.props.event.verification}
label="Vahvistusviesti sähköpostiin"
onChange={this.props.onDataChange}
/>
</div>
);
}
}
export default EmailsTab;
|
docs/src/examples/elements/Step/Variations/StepExampleSizeBig.js
|
Semantic-Org/Semantic-UI-React
|
import React from 'react'
import { Icon, Step } from 'semantic-ui-react'
const StepExampleSizeBig = () => (
<Step.Group size='big'>
<Step>
<Icon name='truck' />
<Step.Content>
<Step.Title>Shipping</Step.Title>
</Step.Content>
</Step>
<Step active>
<Icon name='payment' />
<Step.Content>
<Step.Title>Billing</Step.Title>
</Step.Content>
</Step>
</Step.Group>
)
export default StepExampleSizeBig
|
src/Divider/Divider.js
|
IsenrichO/mui-with-arrows
|
import React from 'react';
import PropTypes from 'prop-types';
const Divider = (props, context) => {
const {
inset,
style,
...other
} = props;
const {
baseTheme,
prepareStyles,
} = context.muiTheme;
const styles = {
root: {
margin: 0,
marginTop: -1,
marginLeft: inset ? 72 : 0,
height: 1,
border: 'none',
backgroundColor: baseTheme.palette.borderColor,
},
};
return (
<hr {...other} style={prepareStyles(Object.assign(styles.root, style))} />
);
};
Divider.muiName = 'Divider';
Divider.propTypes = {
/**
* If true, the `Divider` will be indented.
*/
inset: PropTypes.bool,
/**
* Override the inline-styles of the root element.
*/
style: PropTypes.object,
};
Divider.defaultProps = {
inset: false,
};
Divider.contextTypes = {
muiTheme: PropTypes.object.isRequired,
};
export default Divider;
|
spec/components/layout.js
|
rahultaglr/taglr-toolbox
|
import React from 'react';
import { AppBar, Checkbox, Dropdown, IconButton, RadioGroup, RadioButton } from '../../components';
import { Layout, NavDrawer, Panel, Sidebar } from '../../components';
const dummyText = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.';
const drawerItems = dummyText.split(/\s/).map(function (word, index) {
return (<li key={index}>{word}</li>);
});
const sidebarWidths = [
{ value: 4, label: '4 incr' },
{ value: 5, label: '5 incr' },
{ value: 6, label: '6 incr' },
{ value: 7, label: '7 incr' },
{ value: 8, label: '8 incr' },
{ value: 9, label: '9 incr' },
{ value: 10, label: '10 incr' },
{ value: 25, label: '25%'},
{ value: 33, label: '33%'},
{ value: 50, label: '50%'},
{ value: 66, label: '66%'},
{ value: 75, label: '75%'}
];
class LayoutTest extends React.Component {
state = {
permanentAt: 'lg',
drawerOpen: false,
drawerPinned: false,
sidebarPinned: false,
sidebarWidth: 5,
loremIpsums: 1
};
toggleDrawer = (event) => {
event.stopPropagation();
this.setState({ drawerOpen: !this.state.drawerOpen });
};
toggleDrawerPinned = () => {
this.setState({ drawerPinned: !this.state.drawerPinned });
};
changeDrawerPermanentAt = (value) => {
this.setState({ permanentAt: value });
};
toggleSidebar = (value) => {
this.setState({ sidebarPinned: (value === true) });
};
changeSidebarWidth = (value) => {
this.setState({ sidebarWidth: value });
};
fewer = (event) => {
event.preventDefault();
this.setState({ loremIpsums: Math.max(0, this.state.loremIpsums - 1) });
};
more = (event) => {
event.preventDefault();
this.setState({ loremIpsums: this.state.loremIpsums + 1 });
};
render () {
const rng = Array.from(new Array(this.state.loremIpsums), (x, i) => i);
return (
<section>
<h5>Layout</h5>
<div style={{ width: '100%', height: '60rem', margin: '1.8rem 0' }}>
<Layout>
<NavDrawer active={this.state.drawerOpen} pinned={this.state.drawerPinned} permanentAt={this.state.permanentAt} onOverlayClick={this.toggleDrawer}>
<AppBar title='Drawer'/>
<ul style={{ listStyle: 'none', overflowY: 'auto', flex: 1, padding: '1.6rem' }}>
{drawerItems}
</ul>
</NavDrawer>
<Panel>
<AppBar leftIcon='menu' onLeftIconClick={this.toggleDrawer}/>
<div style={{ flex: 1, overflowY: 'auto' }}>
<div style={{ display: 'flex', flexDirection: 'row' }}>
<section style={{ margin: '1.8rem'}}>
<h5>NavDrawer State</h5>
<p>Drawer becomes permanent when window is....</p>
<RadioGroup name='permanentAt' value={this.state.permanentAt} onChange={this.changeDrawerPermanentAt}>
<RadioButton label='Small' value='sm'/>
<RadioButton label='Medium' value='md' />
<RadioButton label='Large' value='lg' />
<RadioButton label='Extra Large' value='xl' />
<RadioButton label='Never' value={undefined} />
</RadioGroup>
<Checkbox label='Pin drawer' checked={this.state.drawerPinned} onChange={this.toggleDrawerPinned} />
</section>
<section style={{ margin: '1.8rem'}}>
<h5>Sidebar State</h5>
<RadioGroup name='sidebarPinned' value={this.state.sidebarPinned} onChange={this.toggleSidebar}>
<RadioButton label='Pinned' value />
<RadioButton label='Unpinned' value={false} />
</RadioGroup>
<h5>Sidebar Width</h5>
<Dropdown
auto
onChange={this.changeSidebarWidth}
source={sidebarWidths}
value={this.state.sidebarWidth}
/>
</section>
</div>
<section style={{ margin: '1.8rem' }}>
<h5>Scrollable Content</h5>
<p>
The center pane should scroll independently from
the sides. Show
[<a href='#' onClick={this.fewer}>-</a>]
{`${this.state.loremIpsums}`}
[<a href='#' onClick={this.more}>+</a>] paragraph(s) below this one.
</p>
{rng.map((x, i) => <p key={i}>{dummyText}</p>)}
</section>
</div>
</Panel>
<Sidebar pinned={this.state.sidebarPinned} width={Number(this.state.sidebarWidth)}>
<div><IconButton icon='close' onClick={this.toggleSidebar}/></div>
<div style={{ flex: 1, margin: '1.8rem' }}>
<h5>Sidebar</h5>
<p>
Sidebar content should be secondary to the main content on a page.
</p>
<p>
The width of the sidebar can be set either in <em>increments</em>
(where 1 increment = height of the app bar) or in percentages.
</p>
<p>
As per the spec, the right sidebar expands to cover the entire
screen at small screen sizes.
</p>
</div>
</Sidebar>
</Layout>
</div>
</section>
);
}
}
export default LayoutTest;
|
app/components/HomeComponents/TransactionTable.js
|
hlynn93/basic_ims
|
import React, { Component } from 'react';
import { Table, Icon, Button, Container } from 'semantic-ui-react';
class TransactionTable extends Component {
props: {
transactions: [],
items: [],
onDelete: () => void,
onOrder: () => void
}
render() {
const { transactions, items, onOrder, onDelete } = this.props;
const entries = transactions.map((t, index) => (
<Table.Row key={index}>
<Table.Cell textAlign="center">{index}</Table.Cell>
<Table.Cell textAlign="center">{items.find(item => item.id === t.itemId).title}</Table.Cell>
<Table.Cell textAlign="center">{t.quantity}</Table.Cell>
<Table.Cell textAlign="center">{t.price}</Table.Cell>
<Table.Cell textAlign="center">
<Icon
size="large"
color="red"
name="remove"
onClick={onDelete.bind(null, index)}
/>
</Table.Cell>
</Table.Row>
));
return (
<div>
<Table singleLine>
<Table.Header>
<Table.Row>
<Table.HeaderCell collapsing textAlign="center">ID</Table.HeaderCell>
<Table.HeaderCell textAlign="center">Name</Table.HeaderCell>
<Table.HeaderCell textAlign="center">Quantity</Table.HeaderCell>
<Table.HeaderCell textAlign="center">Price</Table.HeaderCell>
<Table.HeaderCell textAlign="center">Remove</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{entries}
</Table.Body>
</Table>
<Container fluid>
<Button
floated="right"
color="green"
onClick={onOrder}
disabled={transactions.length < 1}
>
<Icon name="add to cart" /> Order
</Button>
</Container>
</div>
);
}
}
export default TransactionTable;
|
javascript/containers/current-stock-page.js
|
kdoran/moriana-react
|
import React from 'react'
import { connect } from 'react-redux'
import { getItems } from 'store/items'
import h from 'utils/helpers'
import {buildStockCardHref} from 'components/stockcard-link'
const CurrentStockPage = class extends React.Component {
state = { activeFilter: 'all', displayedItems: null }
componentDidMount = () => {
const { dbName, currentLocationName } = this.props.route
this.props.getItems(dbName, currentLocationName)
}
filterOnClick = (event) => {
event.preventDefault()
const {filter} = event.target.dataset
const {items} = this.props
let displayedItems
switch (filter) {
case 'all':
displayedItems = items
break
case 'positive':
displayedItems = items.filter(i => i.value > 0)
break
case 'zero':
displayedItems = items.filter(i => i.value === 0)
break
case 'quality':
displayedItems = items.filter(i => i.value < 0)
break
}
this.setState({ activeFilter: filter, displayedItems })
}
stockLinkClicked = (event) => {
const {item, category} = event.currentTarget.dataset
window.location.href = buildStockCardHref(this.props.route.dbName, {item, category})
}
render () {
const filters = [
{ name: 'All', key: 'all' },
{ name: 'By Positive', key: 'positive' },
{ name: 'By Zero', key: 'zero' },
{ name: 'By Data Quality', key: 'quality' }
]
const { items, loading } = this.props
const { currentLocationName } = this.props.route
let { activeFilter, displayedItems } = this.state
displayedItems = displayedItems || items
if (loading && items.length === 0) return (<div className='loader' />)
return (
<div className='current-stock-page'>
<h5>Current Stock at {currentLocationName}</h5>
<div className='pull-right'>
{filters.map((filter, i) => {
const classes = (filter.key === activeFilter) ? 'disabled-link' : ''
return (
<a
href='#'
key={i}
onClick={this.filterOnClick}
data-filter={filter.key}
className={classes}>
{filter.name}
</a>
)
})}
</div>
<table>
<thead>
<tr>
<th>Item</th>
<th>Category</th>
<th>Total Value</th>
</tr>
</thead>
<tbody>
{displayedItems.map((row, i) => (
<tr key={i} data-item={row.item} data-category={row.category} onClick={this.stockLinkClicked}>
<td>{row.item}</td>
<td>{row.category}</td>
<td>{h.num(row.value)}</td>
</tr>
))}
</tbody>
</table>
{!displayedItems.length && (<div className='text-center'>No items</div>)}
</div>
)
}
}
export default connect(
state => state.items,
{ getItems }
)(CurrentStockPage)
|
src/components/category_frequency_all.js
|
xuan6/admin_dashboard_local_dev
|
import React from 'react';
import ReactDOM from 'react-dom';
var SimpleTooltipStyle = require('react-d3-tooltip').SimpleTooltip;
var BarTooltip = require('react-d3-tooltip').BarTooltip;
//category by frequency
const CategoryFreAll = ({data}) => {
//activity trend by departments
var generalChartData = data;
var width = 800,
height = 500,
title = "Value",
chartSeries = [
{
field:'count',
name:'Appreciation Count',
color:'#A4D0EF'
}];
var x = function(d) {
return d.category;
},
xScale = "ordinal",
xLabel = "Values",
yLabel = "Counts",
yTicks = d3.format("d");//round to decimal int
return(
<BarTooltip
title= {title}
data= {generalChartData}
width= {width}
height= {height}
chartSeries = {chartSeries}
x= {x}
xScale= {xScale}
xLabel = {xLabel}
yLabel = {yLabel}
yTicks = {yTicks}
showXGrid= {false}
>
<SimpleTooltipStyle/>
</BarTooltip>
)
};
export default CategoryFreAll;
|
test/PagerSpec.js
|
nickuraltsev/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Pager from '../src/Pager';
import PageItem from '../src/PageItem';
describe('Pager', () => {
it('Should output a unordered list as root element with class "pager"', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Pager/>
);
assert.equal(React.findDOMNode(instance).nodeName, 'UL');
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'pager'));
});
it('Should allow "PageItem" as child element', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Pager>
<PageItem href="#">Top</PageItem>
</Pager>
);
assert.equal(React.findDOMNode(instance).children.length, 1);
assert.equal(React.findDOMNode(instance).children[0].nodeName, 'LI');
});
it('Should allow multiple "PageItem" as child elements', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Pager>
<PageItem previous href="#">Previous</PageItem>
<PageItem disabled href="#">Top</PageItem>
<PageItem next href="#">Next</PageItem>
</Pager>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'previous'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'disabled'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'next'));
});
it('Should call "onSelect" when item is clicked', (done) => {
function handleSelect(key, href) {
assert.equal(key, 2);
assert.equal(href, '#next');
done();
}
let instance = ReactTestUtils.renderIntoDocument(
<Pager onSelect={handleSelect}>
<PageItem eventKey={1} href="#prev">Previous</PageItem>
<PageItem eventKey={2} href="#next">Next</PageItem>
</Pager>
);
let items = ReactTestUtils.scryRenderedComponentsWithType(instance, PageItem);
ReactTestUtils.Simulate.click(
ReactTestUtils.findRenderedDOMComponentWithTag(items[1], 'a')
);
});
});
|
test/PopoverSpec.js
|
HorizonXP/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Popover from '../src/Popover';
describe('Popover', function () {
it('Should output a popover title and content', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Popover title="Popover title">
<strong>Popover Content</strong>
</Popover>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'popover-title'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'popover-content'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong'));
});
});
|
src/components/SideMenu/index.js
|
PalmasLab/palmasplay
|
import React from 'react'
import styles from './styles.css'
const MenuSection = ({title, icon, children}) => (
<ul>
<li className={styles.title}><strong>{title}</strong><i className={`fa fa-${icon}`}></i></li>
{children}
</ul>
)
export const SideMenu = () => (
<div className={styles.sideMenu}>
<MenuSection title="Menu">
<a href="#"><li><i className="fa fa-youtube-play"></i>What to watch</li></a>
<a href="#"><li><i className="fa fa-user"></i>My Channel</li></a>
<a href="#"><li><i className="fa fa-clock-o"></i>History</li></a>
<a href="#"><li><i className="fa fa-play-circle-o"></i>Watch later</li></a>
</MenuSection>
<MenuSection title="Playlists" icon="cog">
<a href="#"><li><i className="fa fa-heart-o"></i>Liked Videos</li></a>
<a href="#"><li><i className="fa fa-indent"></i>My Music</li></a>
<a href="#"><li><i className="fa fa-indent"></i>Eminem</li></a>
<a href="#"><li><i className="fa fa-indent"></i>David Guetta</li></a>
</MenuSection>
<MenuSection title="Playlists2" icon="heart">
<a href="#"><li><i className="fa fa-heart-o"></i>Liked Videos</li></a>
<a href="#"><li><i className="fa fa-indent"></i>My Music</li></a>
<a href="#"><li><i className="fa fa-indent"></i>Eminem</li></a>
<a href="#"><li><i className="fa fa-indent"></i>David Guetta</li></a>
</MenuSection>
</div>
)
|
src/components/numeric-input.js
|
bhongy/react-components
|
/**
* A thin wrapper around HTMLInputElement that state as number type
* rather than string - avoid ad-hoc string/number handling at use sites.
* Handles precision and trailing period. See unit tests for the detail spec.
*
* TODO: handle formatting (could be tricky with change event value)
*
* @flow
*/
import React, { Component } from 'react';
import { omit } from 'lodash';
type Props = {
initialValue?: ?number,
onChange?: (obj: { value: ?number, name?: string }) => void,
precision?: number,
};
export type State = {
inputValue: string,
value: ?number,
};
function handleInitialValue(value: ?number): State {
if (typeof value === 'number' && Number.isFinite(value)) {
return {
value,
inputValue: value.toString(),
};
}
return {
value: null,
inputValue: '',
};
}
export function truncateInputValueToPrecision(inputValue: string, precision?: number): string {
if (typeof precision !== 'number' || precision % 1 !== 0 || precision < 0) {
// handle invalid `precision` param
// ? should throw instead ?
return inputValue;
}
const [integer, decimals]: Array<string> = inputValue.split('.');
if (precision === 0 || typeof decimals === 'undefined') {
return integer;
}
return [integer, decimals.slice(0, precision)].join('.');
}
class NumericInput extends Component<Props, State> {
constructor(props: Props): void {
super(props);
this.state = handleInitialValue(props.initialValue);
}
handleChange = (event: SyntheticInputEvent<HTMLInputElement>): void => {
// create a copy of "name" value because React synthetic event is re-used
// hence we cannot rely on the reference like `event.currentTarget.name`
const { name, value: inputValue } = event.currentTarget;
// bail early (do not change state) if input is invalid
if (Number.isNaN(+inputValue)) {
return;
}
// transformations assume that the inputValue can be safely converted
// to float and without multiple periods (e.g. "01a" or "01.10.")
// keep this after the "bail" check
const newState: State = this.handlePrecision(inputValue);
// do not `setState` if the new inputValue is the same as the current inputValue
// after calling `this.handlePrecision` with the new inputValue
if (newState === this.state) {
return;
}
this.setState(newState, (): void => {
const { onChange } = this.props;
if (typeof onChange === 'function') {
onChange({ value: this.state.value, name });
}
});
};
handlePrecision = (inputValue: string): State => {
const truncated: string = truncateInputValueToPrecision(inputValue, this.props.precision);
if (this.state.inputValue === truncated) {
return this.state;
}
return truncated === ''
? { value: null, inputValue: '' }
: { value: +truncated, inputValue: truncated };
};
render() {
const passThroughProps = omit(this.props, 'initialValue');
return (
<input {...passThroughProps} onChange={this.handleChange} value={this.state.inputValue} />
);
}
}
export default NumericInput;
|
pages/blog/test-article-one.js
|
fmarcos83/mdocs
|
/**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import React, { Component } from 'react';
export default class extends Component {
render() {
return (
<div>
<h1>Test Article 1</h1>
<p>Coming soon.</p>
</div>
);
}
}
|
js/jqwidgets/demos/react/app/chart/dashboard/app.js
|
luissancheza/sice
|
import React from 'react';
import ReactDOM from 'react-dom';
import JqxChart from '../../../jqwidgets-react/react_jqxchart.js';
class App extends React.Component {
render() {
let data1 =
[
{ text: 'Used', value: 55 },
{ text: 'Available', value: 9 }
];
let data2 =
[
{ text: 'Used', value: 37 },
{ text: 'Available', value: 63 }
];
let data3 =
[
{ text: 'Used', value: 89.3 },
{ text: 'Available', value: 166.7 }
];
let data4 =
[
{ text: 'Used', value: 47 },
{ text: 'Available', value: 53 }
];
let data5 =
[
{ hour: 0, latency: 235, requests: 3500 },
{ hour: 1, latency: 231, requests: 3400 },
{ hour: 2, latency: 217, requests: 3350 },
{ hour: 3, latency: 215, requests: 3260 },
{ hour: 4, latency: 225, requests: 3320 },
{ hour: 5, latency: 235, requests: 3400 },
{ hour: 6, latency: 239, requests: 3550 },
{ hour: 7, latency: 255, requests: 4100 },
{ hour: 8, latency: 251, requests: 4200 },
{ hour: 9, latency: 259, requests: 4500 },
{ hour: 10, latency: 265, requests: 4560 },
{ hour: 11, latency: 257, requests: 4500 },
{ hour: 12, latency: 265, requests: 4490 },
{ hour: 13, latency: 261, requests: 4400 },
{ hour: 14, latency: 258, requests: 4350 },
{ hour: 15, latency: 257, requests: 4340 },
{ hour: 16, latency: 255, requests: 4200 },
{ hour: 17, latency: 245, requests: 4050 },
{ hour: 18, latency: 241, requests: 4020 },
{ hour: 19, latency: 239, requests: 3900 },
{ hour: 20, latency: 237, requests: 3810 },
{ hour: 21, latency: 236, requests: 3720 },
{ hour: 22, latency: 235, requests: 3610 },
{ hour: 23, latency: 239, requests: 3550 },
];
let padding = { left: 5, top: 5, right: 5, bottom: 5 };
let titlePadding = { left: 5, top: 5, right: 5, bottom: 5 };
let seriesGroups =
[
{
type: 'donut',
useGradientColors: false,
series:
[
{
showLabels: false,
enableSelection: true,
displayText: 'text',
dataField: 'value',
labelRadius: 120,
initialAngle: 90,
radius: 60,
innerRadius: 50,
centerOffset: 0
}
]
}
];
let counter = 0;
let drawBefore = (renderer, rect) => {
let value;
if (counter === 0) {
value = data1[0].value;
} else if (counter === 1) {
value = data2[0].value;
} else if (counter === 2) {
value = data3[0].value;
} else if (counter === 3) {
value = data4[0].value;
}
let sz = renderer.measureText(value, 0, { 'class': 'chart-inner-text' });
renderer.text(
value,
rect.x + (rect.width - sz.width) / 2,
rect.y + rect.height / 2,
0,
0,
0,
{ 'class': 'chart-inner-text' }
);
counter++;
};
let xAxis =
{
dataField: 'hour',
displayText: 'Hour',
};
let latencyThreshold = 260;
let seriesGroups2 =
[
{
type: 'column',
valueAxis:
{
title: { text: 'Request Latency [ms]<br>' },
position: 'left'
},
toolTipFormatSettings: { sufix: ' ms' },
series:
[
{
dataField: 'latency',
displayText: 'Request latency',
colorFunction: (value, itemIndex, serie, group) => {
return (value > latencyThreshold) ? '#CC1133' : '#55CC55';
}
}
],
bands:
[
{
minValue: latencyThreshold,
maxValue: latencyThreshold,
lineWidth: 1,
color: 'red'
}
]
},
{
type: 'spline',
valueAxis:
{
title: { text: 'Get Requests per second' },
position: 'right'
},
toolTipFormatSettings: { sufix: ' req/s' },
series:
[
{
dataField: 'requests',
displayText: 'Get requests',
lineColor: '#343F9B',
lineWidth: 2
}
]
},
];
return (
<div>
<JqxChart ref='myChart1' style={{ width: 400, height: 180, float: 'left' }}
title={'Cluster capacity'} description={''} colorScheme={'scheme05'}
showLegend={false} enableAnimations={true} padding={padding} showToolTips={true}
titlePadding={titlePadding} source={data1} backgroundColor={'#FAFAFA'}
seriesGroups={seriesGroups} drawBefore={drawBefore}
/>
<JqxChart ref='myChart2' style={{ width: 400, height: 180, float: 'left' }}
title={'Avg. CPU %'} description={''} colorScheme={'scheme05'}
showLegend={false} enableAnimations={true} padding={padding} showToolTips={true}
titlePadding={titlePadding} source={data2} backgroundColor={'#FAFAFA'}
seriesGroups={seriesGroups} drawBefore={drawBefore}
/>
<JqxChart ref='myChart3' style={{ width: 400, height: 180, float: 'left' }}
title={'Storage capacity [TB]'} description={''} colorScheme={'scheme05'}
showLegend={false} enableAnimations={true} padding={padding} showToolTips={true}
titlePadding={titlePadding} source={data3} backgroundColor={'#FAFAFA'}
seriesGroups={seriesGroups} drawBefore={drawBefore}
/>
<JqxChart ref='myChart4' style={{ width: 400, height: 180, float: 'left' }}
title={'Network utilization %'} description={''} colorScheme={'scheme05'}
showLegend={false} enableAnimations={true} padding={padding} showToolTips={true}
titlePadding={titlePadding} source={data4} backgroundColor={'#FAFAFA'}
seriesGroups={seriesGroups} drawBefore={drawBefore}
/>
<JqxChart style={{ width: 800, height: 300 }}
title={'Get request per second & response latencies'} description={'(Aggregated values for the last 24h)'}
showLegend={false} enableAnimations={true} padding={padding} backgroundColor={'#FAFAFA'}
titlePadding={titlePadding} source={data5} xAxis={xAxis} showBorderLine={true}
seriesGroups={seriesGroups2} colorScheme={'scheme05'}
/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
app/boards/motec-d153/components/warnings.js
|
fermio/motorsport-display
|
import React from 'react';
import _ from 'lodash';
import { EngineWarnings } from '../../constants';
const Warnings = React.createClass({
propTypes: {
warnings: React.PropTypes.array
},
getDefaultProps: function() {
return {
warnings: []
}
},
shouldComponentUpdate: function(nextProps, nextState) {
return this.props.warnings != nextProps.warnings;
},
render: function() {
let warnings = [];
if (_.indexOf(this.props.warnings, EngineWarnings.PIT_SPEED_LIMITER) != -1) {
warnings.push(
<div key="pit-speed-limiter" id="pit-speed-limiter" className="column">
Pit Speed Limiter
</div>
);
}
if (_.indexOf(this.props.warnings, EngineWarnings.REV_LIMITER_ACTIVE) != -1) {
warnings.push(
<div key="rev-limiter" id="rev-limiter" className="column">
Rev Limiter Active
</div>
);
}
if (_.indexOf(this.props.warnings, EngineWarnings.WATER_TEMP_WARNING) != -1) {
warnings.push(
<div key="water-temp" id="water-temp" className="column">
Engine Hot
</div>
);
}
if (_.indexOf(this.props.warnings, EngineWarnings.FUEL_PRESSURE_WARNING) != -1) {
warnings.push(
<div key="fuel-pressure" id="fuel-pressure" className="column">
Fuel Pressure Low
</div>
);
}
if (_.indexOf(this.props.warnings, EngineWarnings.OIL_PRESSURE_WARNING) != -1) {
warnings.push(
<div key="oil-pressure" id="oil-pressure" className="column">
Oil Pressue Low
</div>
);
}
if (_.indexOf(this.props.warnings, EngineWarnings.ENGINE_STALLED) != -1) {
warnings.push(
<div key="engine-stalled" id="engine-stalled" className="column">
Engine Stalled
</div>
);
}
return (
<div id="engine-warnings" className="row">
{warnings}
</div>
);
}
});
export default Warnings;
|
packages/@lyra/vision/src/containers/LoadingContainer.js
|
VegaPublish/vega-studio
|
import React from 'react'
import PropTypes from 'prop-types'
import request from '../util/request'
// Yeah, inheritance and all that. Deal with it.
class LoadingContainer extends React.PureComponent {
constructor() {
super()
if (!this.getSubscriptions) {
throw new Error(
`${
this.constructor.name
} extended LoadingContainer but did not define a getSubscriptions() method`
)
}
this.subscriptions = []
this.state = {}
}
componentDidMount() {
const subs = this.getSubscriptions()
const stateKeys = (this.stateKeys = Object.keys(subs))
this.subscriptions = stateKeys.reduce((target, key) => {
target.push(request(this, subs[key], key))
return target
}, [])
}
hasAllData() {
return (
this.stateKeys &&
this.stateKeys.every(key => this.state[key] !== undefined)
)
}
componentWillUnmount() {
while (this.subscriptions.length) {
this.subscriptions.pop().unsubscribe()
}
}
}
LoadingContainer.contextTypes = {
client: PropTypes.shape({fetch: PropTypes.func}).isRequired
}
export default LoadingContainer
|
webapp/app/components/Spinner/index.js
|
EIP-SAM/SAM-Solution-Node-js
|
//
// Spinner components to display during ajax requests
// Props:
// color: optional, choose the spinner's color
// size: optional, choose the spinner's size
// className: optional, add your own css here, to center the component etc...
// Example:
// import Spinner from 'components/Spinner';
// ...
// <Spinner color="#ff0000" size={200} className={styles.newStyleSpinner} />
//
import React from 'react';
import styles from './styles.css';
/* eslint-disable react/prefer-stateless-function */
export default class Spinner extends React.Component {
static defaultProps = {
color: '#3498db',
size: 120,
className: '',
}
render() {
const width = 16 * (this.props.size / 120);
const newStyle = {
borderTopColor: this.props.color,
width: this.props.size,
height: this.props.size,
borderWidth: width,
borderTopWidth: width,
};
return (
<div className={[styles.spinner, this.props.className].join(' ')} style={newStyle} />
);
}
}
Spinner.propTypes = {
color: React.PropTypes.string,
size: React.PropTypes.number,
className: React.PropTypes.string,
};
|
node_modules/enzyme/test/ReactWrapper-spec.js
|
PanJ/SimplerCityGlide
|
import { describeWithDOM, describeIf } from './_helpers';
import React from 'react';
import { expect } from 'chai';
import {
mount,
render,
ReactWrapper,
} from '../src/';
import sinon from 'sinon';
import { REACT013 } from '../src/version';
describeWithDOM('mount', () => {
describe('context', () => {
const context = { name: 'foo' };
it('can pass in context', () => {
const SimpleComponent = React.createClass({
contextTypes: {
name: React.PropTypes.string,
},
render() {
return <div>{this.context.name}</div>;
},
});
const wrapper = mount(<SimpleComponent />, { context });
expect(wrapper.text()).to.equal('foo');
});
it('can pass context to the child of mounted component', () => {
const SimpleComponent = React.createClass({
contextTypes: {
name: React.PropTypes.string,
},
render() {
return <div>{this.context.name}</div>;
},
});
const ComplexComponent = React.createClass({
render() {
return <div><SimpleComponent /></div>;
},
});
const childContextTypes = {
name: React.PropTypes.string.isRequired,
};
const wrapper = mount(<ComplexComponent />, { context, childContextTypes });
expect(wrapper.find(SimpleComponent)).to.have.length(1);
});
it('should not throw if context is passed in but contextTypes is missing', () => {
const SimpleComponent = React.createClass({
render() {
return <div>{this.context.name}</div>;
},
});
expect(() => mount(<SimpleComponent />, { context })).to.not.throw(Error);
});
it('is instrospectable through context API', () => {
const SimpleComponent = React.createClass({
contextTypes: {
name: React.PropTypes.string,
},
render() {
return <div>{this.context.name}</div>;
},
});
const wrapper = mount(<SimpleComponent />, { context });
expect(wrapper.context().name).to.equal(context.name);
expect(wrapper.context('name')).to.equal(context.name);
});
describeIf(!REACT013, 'stateless components', () => {
it('works with stateless components', () => {
const Foo = ({ foo }) => (
<div>
<div className="bar">bar</div>
<div className="qoo">{foo}</div>
</div>
);
Foo.contextTypes = {
_: React.PropTypes.string,
};
const wrapper = mount(<Foo foo="qux" />, {
context: {
_: 'foo',
},
});
expect(wrapper.context('_')).to.equal('foo');
});
});
});
describeIf(!REACT013, 'stateless components', () => {
it('works with stateless components', () => {
const Foo = ({ foo }) => (
<div>
<div className="bar">bar</div>
<div className="qoo">{foo}</div>
</div>
);
const wrapper = mount(<Foo foo="qux" />);
expect(wrapper.type()).to.equal(Foo);
expect(wrapper.find('.bar')).to.have.length(1);
expect(wrapper.find('.qoo').text()).to.equal('qux');
});
it('supports findDOMNode with stateless components', () => {
const Foo = ({ foo }) => (
<div>{foo}</div>
);
const wrapper = mount(<Foo foo="qux" />);
expect(wrapper.text()).to.equal('qux');
});
it('works with nested stateless', () => {
const TestItem = () => (
<div className="item">1</div>
);
const Test = () => (
<div className="box">
<TestItem test="123" />
<TestItem />
<TestItem />
</div>
);
const wrapper = mount(<Test />);
const children = wrapper.find('.box').children();
expect(children).to.have.length(3);
expect(children.at(0).props().test).to.equal('123');
expect(wrapper.find(TestItem)).to.have.length(3);
expect(wrapper.find(TestItem).first().props().test).to.equal('123');
});
});
describe('.contains(node)', () => {
it('should allow matches on the root node', () => {
const a = <div className="foo" />;
const b = <div className="foo" />;
const c = <div className="bar" />;
expect(mount(a).contains(b)).to.equal(true);
expect(mount(a).contains(c)).to.equal(false);
});
it('should allow matches on a nested node', () => {
const wrapper = mount(
<div>
<div className="foo" />
</div>
);
const b = <div className="foo" />;
expect(wrapper.contains(b)).to.equal(true);
});
it('should match composite components', () => {
class Foo extends React.Component {
render() { return <div />; }
}
const wrapper = mount(
<div>
<Foo />
</div>
);
const b = <Foo />;
expect(wrapper.contains(b)).to.equal(true);
});
it('should do something with arrays of nodes', () => {
const wrapper = mount(
<div>
<span>Hello</span>
<div>Goodbye</div>
<span>More</span>
</div>
);
const fails = [
<span>wrong</span>,
<div>Goodbye</div>,
];
const passes1 = [
<span>Hello</span>,
<div>Goodbye</div>,
];
const passes2 = [
<div>Goodbye</div>,
<span>More</span>,
];
expect(wrapper.contains(fails)).to.equal(false);
expect(wrapper.contains(passes1)).to.equal(true);
expect(wrapper.contains(passes2)).to.equal(true);
});
});
describe('.find(selector)', () => {
it('should find an element based on a class name', () => {
const wrapper = mount(
<div>
<input className="foo" />
</div>
);
expect(wrapper.find('.foo').type()).to.equal('input');
});
it('should find an element based on a tag name', () => {
const wrapper = mount(
<div>
<input className="foo" />
</div>
);
expect(wrapper.find('input').props().className).to.equal('foo');
});
it('should find a component based on a constructor', () => {
class Foo extends React.Component {
render() { return <div />; }
}
const wrapper = mount(
<div>
<Foo className="foo" />
</div>
);
expect(wrapper.find(Foo).type()).to.equal(Foo);
});
it('should find a component based on a component displayName', () => {
class Foo extends React.Component {
render() { return <div />; }
}
const wrapper = mount(
<div>
<Foo className="foo" />
</div>
);
expect(wrapper.find('Foo').type()).to.equal(Foo);
});
it('should find component based on a react prop', () => {
const wrapper = mount(
<div>
<span htmlFor="foo" />
</div>
);
expect(wrapper.find('[htmlFor="foo"]')).to.have.length(1);
expect(wrapper.find('[htmlFor]')).to.have.length(1);
});
it('should compound tag and prop selector', () => {
const wrapper = mount(
<div>
<span htmlFor="foo" />
</div>
);
expect(wrapper.find('span[htmlFor="foo"]')).to.have.length(1);
expect(wrapper.find('span[htmlFor]')).to.have.length(1);
});
it('should support data prop selectors', () => {
const wrapper = mount(
<div>
<span data-foo="bar" />
</div>
);
expect(wrapper.find('[data-foo="bar"]')).to.have.length(1);
expect(wrapper.find('[data-foo]')).to.have.length(1);
});
it('should find components with multiple matching props', () => {
const onChange = () => ({});
const wrapper = mount(
<div>
<span htmlFor="foo" onChange={onChange} preserveAspectRatio="xMaxYMax" />
</div>
);
expect(wrapper.find('span[htmlFor="foo"][onChange]')).to.have.length(1);
expect(wrapper.find('span[htmlFor="foo"][preserveAspectRatio="xMaxYMax"]')).to.have.length(1);
});
it('should not find property when undefined', () => {
const wrapper = mount(
<div>
<span data-foo={undefined} />
</div>
);
expect(wrapper.find('[data-foo]')).to.have.length(0);
});
it('should support boolean and numeric values for matching props', () => {
const wrapper = mount(
<div>
<span value={1} />
<a value={false} />
</div>
);
expect(wrapper.find('span[value=1]')).to.have.length(1);
expect(wrapper.find('span[value=2]')).to.have.length(0);
expect(wrapper.find('a[value=false]')).to.have.length(1);
expect(wrapper.find('a[value=true]')).to.have.length(0);
});
it('should not find key or ref via property selector', () => {
class Foo extends React.Component {
render() {
const arrayOfComponents = [<div key="1" />, <div key="2" />];
return (
<div>
<div ref="foo" />
{arrayOfComponents}
</div>
);
}
}
const wrapper = mount(<Foo />);
expect(wrapper.find('div[ref="foo"]')).to.have.length(0);
expect(wrapper.find('div[key="1"]')).to.have.length(0);
expect(wrapper.find('[ref]')).to.have.length(0);
expect(wrapper.find('[key]')).to.have.length(0);
});
it('should find multiple elements based on a class name', () => {
const wrapper = mount(
<div>
<input className="foo" />
<button className="foo" />
</div>
);
expect(wrapper.find('.foo').length).to.equal(2);
});
it('should find multiple elements based on a tag name', () => {
const wrapper = mount(
<div>
<input className="foo" />
<input />
<button />
</div>
);
expect(wrapper.find('input').length).to.equal(2);
expect(wrapper.find('button').length).to.equal(1);
});
it('should find multiple elements based on a constructor', () => {
const wrapper = mount(
<div>
<input className="foo" />
<input />
<button />
</div>
);
expect(wrapper.find('input').length).to.equal(2);
expect(wrapper.find('button').length).to.equal(1);
});
it('should support object property selectors', () => {
const wrapper = mount(
<div>
<input data-test="ref" className="foo" type="text" />
<input data-test="ref" type="text" />
<button data-test="ref" prop={undefined} />
<span data-test="ref" prop={null} />
<div data-test="ref" prop={123} />
<input data-test="ref" prop={false} />
<a data-test="ref" prop />
</div>
);
expect(wrapper.find({ a: 1 })).to.have.length(0);
expect(wrapper.find({ 'data-test': 'ref' })).to.have.length(7);
expect(wrapper.find({ className: 'foo' })).to.have.length(1);
expect(wrapper.find({ prop: undefined })).to.have.length(1);
expect(wrapper.find({ prop: null })).to.have.length(1);
expect(wrapper.find({ prop: 123 })).to.have.length(1);
expect(wrapper.find({ prop: false })).to.have.length(1);
expect(wrapper.find({ prop: true })).to.have.length(1);
});
it('should support complex and nested object property selectors', () => {
const testFunction = () => ({});
const wrapper = mount(
<div>
<span more={[{ id: 1 }]} data-test="ref" prop onChange={testFunction} />
<a more={[{ id: 1 }]} data-test="ref" />
<div more={{ item: { id: 1 } }} data-test="ref" />
<input style={{ height: 20 }} data-test="ref" />
</div>
);
expect(wrapper.find({ 'data-test': 'ref' })).to.have.length(4);
expect(wrapper.find({ more: { a: 1 } })).to.have.length(0);
expect(wrapper.find({ more: [{ id: 1 }] })).to.have.length(2);
expect(wrapper.find({ more: { item: { id: 1 } } })).to.have.length(1);
expect(wrapper.find({ style: { height: 20 } })).to.have.length(1);
expect(wrapper
.find({ more: [{ id: 1 }], 'data-test': 'ref', prop: true, onChange: testFunction })
).to.have.length(1);
});
it('should throw when given empty object, null, or an array', () => {
const wrapper = mount(
<div>
<input className="foo" type="text" />
</div>
);
expect(() => wrapper.find({})).to.throw(Error);
expect(() => wrapper.find([])).to.throw(Error);
expect(() => wrapper.find(null)).to.throw(Error);
});
});
describe('.findWhere(predicate)', () => {
it('should return all elements for a truthy test', () => {
const wrapper = mount(
<div>
<input className="foo" />
<input />
</div>
);
expect(wrapper.findWhere(() => true).length).to.equal(3);
});
it('should return no elements for a falsy test', () => {
const wrapper = mount(
<div>
<input className="foo" />
<input />
</div>
);
expect(wrapper.findWhere(() => false).length).to.equal(0);
});
it('should call the predicate with the wrapped node as the first argument', () => {
const wrapper = mount(
<div>
<div className="foo bar" />
<div className="foo baz" />
<div className="foo bux" />
</div>
);
const stub = sinon.stub();
stub.returns(true);
const spy = sinon.spy(stub);
wrapper.findWhere(spy);
expect(spy.callCount).to.equal(4);
expect(spy.args[0][0]).to.be.instanceOf(ReactWrapper);
expect(spy.args[1][0]).to.be.instanceOf(ReactWrapper);
expect(spy.args[2][0]).to.be.instanceOf(ReactWrapper);
expect(spy.args[3][0]).to.be.instanceOf(ReactWrapper);
expect(spy.args[1][0].hasClass('bar')).to.equal(true);
expect(spy.args[2][0].hasClass('baz')).to.equal(true);
expect(spy.args[3][0].hasClass('bux')).to.equal(true);
});
describeIf(!REACT013, 'stateless functional components', () => {
it('finds nodes', () => {
const SFC = function SFC({ selector }) {
return (
<div>
<span data-foo={selector} />
<i data-foo={selector} />
</div>
);
};
const selector = 'blah';
const wrapper = mount(<SFC selector={selector} />);
const foundSpan = wrapper.findWhere(n => (
n.type() === 'span' && n.props()['data-foo'] === selector
));
expect(foundSpan.type()).to.equal('span');
const foundNotSpan = wrapper.findWhere(n => (
n.type() !== 'span' && n.props()['data-foo'] === selector
));
expect(foundNotSpan.type()).to.equal('i');
});
it('finds nodes when conditionally rendered', () => {
const SFC = function SFC({ selector }) {
return (
<div>
<span data-foo={selector} />
{selector === 'baz' ? <i data-foo={selector} /> : null}
</div>
);
};
const selector = 'blah';
const wrapper = mount(<SFC selector={selector} />);
const foundSpan = wrapper.findWhere(n => (
n.type() === 'span' && n.props()['data-foo'] === selector
));
expect(foundSpan.type()).to.equal('span');
const foundNotSpan = wrapper.findWhere(n => (
n.type() !== 'span' && n.props()['data-foo'] === selector
));
expect(foundNotSpan).to.have.length(0);
});
it('should return props object when props() is called', () => {
const SFC = function SFC({ data }) {
return (
<div data-foo={data}>Test SFC</div>
);
};
const content = 'blah';
const wrapper = mount(<SFC data={content} />);
expect(wrapper.props()).to.deep.equal({ data: content });
});
it('should return shallow rendered string when debug() is called', () => {
const SFC = function SFC({ data }) {
return (
<div data-foo={data}>Test SFC</div>
);
};
const content = 'blah';
const wrapper = mount(<SFC data={content} />);
expect(wrapper.debug()).to.equal(
`<SFC data="${content}">
<div data-foo="${content}">
Test SFC
</div>
</SFC>`
);
});
});
it('should not pass in null or false nodes', () => {
const wrapper = mount(
<div>
<div className="foo bar" />
{null}
{false}
</div>
);
const stub = sinon.stub();
stub.returns(true);
const spy = sinon.spy(stub);
wrapper.findWhere(spy);
expect(spy.callCount).to.equal(2);
});
});
describe('.setProps(newProps)', () => {
it('should set props for a component multiple times', () => {
class Foo extends React.Component {
render() {
return (
<div className={this.props.id}>
{this.props.id}
</div>
);
}
}
const wrapper = mount(<Foo id="foo" />);
expect(wrapper.find('.foo').length).to.equal(1);
wrapper.setProps({ id: 'bar', foo: 'bla' });
expect(wrapper.find('.bar').length).to.equal(1);
});
it('should call componentWillReceiveProps for new renders', () => {
const spy = sinon.spy();
class Foo extends React.Component {
constructor(props) {
super(props);
this.componentWillReceiveProps = spy;
}
render() {
return (
<div className={this.props.id}>
{this.props.id}
</div>
);
}
}
const nextProps = { id: 'bar', foo: 'bla' };
const wrapper = mount(<Foo id="foo" />);
expect(spy.calledOnce).to.equal(false);
wrapper.setProps(nextProps);
expect(spy.calledOnce).to.equal(true);
expect(spy.calledWith(nextProps)).to.equal(true);
});
it('should merge newProps with oldProps', () => {
class Foo extends React.Component {
render() {
return (
<div {...this.props} />
);
}
}
const wrapper = mount(<Foo a="a" b="b" />);
expect(wrapper.props().a).to.equal('a');
expect(wrapper.props().b).to.equal('b');
wrapper.setProps({ b: 'c', d: 'e' });
expect(wrapper.props().a).to.equal('a');
expect(wrapper.props().b).to.equal('c');
expect(wrapper.props().d).to.equal('e');
});
it('should throw if an exception occurs during render', () => {
class Trainwreck extends React.Component {
render() {
const { user } = this.props;
return (
<div>
{user.name.givenName}
</div>
);
}
}
const validUser = {
name: {
givenName: 'Brian',
},
};
const wrapper = mount(<Trainwreck user={validUser} />);
const setInvalidProps = () => {
wrapper.setProps({
user: {},
});
};
expect(setInvalidProps).to.throw();
});
});
describe('.setContext(newContext)', () => {
const SimpleComponent = React.createClass({
contextTypes: {
name: React.PropTypes.string,
},
render() {
return <div>{this.context.name}</div>;
},
});
it('should set context for a component multiple times', () => {
const context = { name: 'foo' };
const wrapper = mount(<SimpleComponent />, { context });
expect(wrapper.text()).to.equal('foo');
wrapper.setContext({ name: 'bar' });
expect(wrapper.text()).to.equal('bar');
wrapper.setContext({ name: 'baz' });
expect(wrapper.text()).to.equal('baz');
});
it('should throw if it is called when shallow didnt include context', () => {
const wrapper = mount(<SimpleComponent />);
expect(() => wrapper.setContext({ name: 'bar' })).to.throw(Error);
});
});
describe('.mount()', () => {
it('should call componentWillUnmount()', () => {
const willMount = sinon.spy();
const didMount = sinon.spy();
const willUnmount = sinon.spy();
class Foo extends React.Component {
constructor(props) {
super(props);
this.componentWillUnmount = willUnmount;
this.componentWillMount = willMount;
this.componentDidMount = didMount;
}
render() {
return (
<div className={this.props.id}>
{this.props.id}
</div>
);
}
}
const wrapper = mount(<Foo id="foo" />);
expect(willMount.callCount).to.equal(1);
expect(didMount.callCount).to.equal(1);
expect(willUnmount.callCount).to.equal(0);
wrapper.unmount();
expect(willMount.callCount).to.equal(1);
expect(didMount.callCount).to.equal(1);
expect(willUnmount.callCount).to.equal(1);
wrapper.mount();
expect(willMount.callCount).to.equal(2);
expect(didMount.callCount).to.equal(2);
expect(willUnmount.callCount).to.equal(1);
});
});
describe('.unmount()', () => {
it('should call componentWillUnmount()', () => {
const spy = sinon.spy();
class Foo extends React.Component {
constructor(props) {
super(props);
this.componentWillUnmount = spy;
}
render() {
return (
<div className={this.props.id}>
{this.props.id}
</div>
);
}
}
const wrapper = mount(<Foo id="foo" />);
expect(spy.calledOnce).to.equal(false);
wrapper.unmount();
expect(spy.calledOnce).to.equal(true);
});
});
describe('.simulate(eventName, data)', () => {
it('should simulate events', () => {
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
this.incrementCount = this.incrementCount.bind(this);
}
incrementCount() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<a
className={`clicks-${this.state.count}`}
onClick={this.incrementCount}
>
foo
</a>
);
}
}
const wrapper = mount(<Foo />);
expect(wrapper.find('.clicks-0').length).to.equal(1);
wrapper.simulate('click');
expect(wrapper.find('.clicks-1').length).to.equal(1);
});
it('should pass in event data', () => {
const spy = sinon.spy();
class Foo extends React.Component {
render() {
return (
<a onClick={spy}>foo</a>
);
}
}
const wrapper = mount(<Foo />);
wrapper.simulate('click', { someSpecialData: 'foo' });
expect(spy.calledOnce).to.equal(true);
expect(spy.args[0][0].someSpecialData).to.equal('foo');
});
it('should throw a descriptive error for invalid events', () => {
const wrapper = mount(<div>foo</div>);
expect(wrapper.simulate.bind(wrapper, 'invalidEvent'))
.to.throw(TypeError, "ReactWrapper::simulate() event 'invalidEvent' does not exist");
});
describe('Normalizing JS event names', () => {
it('should convert lowercase events to React camelcase', () => {
const spy = sinon.spy();
const clickSpy = sinon.spy();
class Foo extends React.Component {
render() {
return (
<a onClick={clickSpy} onDoubleClick={spy}>foo</a>
);
}
}
const wrapper = mount(<Foo />);
wrapper.simulate('dblclick');
expect(spy.calledOnce).to.equal(true);
wrapper.simulate('click');
expect(clickSpy.calledOnce).to.equal(true);
});
describeIf(!REACT013, 'normalizing mouseenter', () => {
it('should convert lowercase events to React camelcase', () => {
const spy = sinon.spy();
class Foo extends React.Component {
render() {
return (
<a onMouseEnter={spy}>foo</a>
);
}
}
const wrapper = mount(<Foo />);
wrapper.simulate('mouseenter');
expect(spy.calledOnce).to.equal(true);
});
});
});
});
describe('.setState(newState)', () => {
it('should set the state of the root node', () => {
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = { id: 'foo' };
}
render() {
return (
<div className={this.state.id} />
);
}
}
const wrapper = mount(<Foo />);
expect(wrapper.find('.foo').length).to.equal(1);
wrapper.setState({ id: 'bar' });
expect(wrapper.find('.bar').length).to.equal(1);
});
it('allows setState inside of componentDidMount', () => {
// NOTE: this test is a test to ensure that the following issue is
// fixed: https://github.com/airbnb/enzyme/issues/27
class MySharona extends React.Component {
constructor(props) {
super(props);
this.state = { mounted: false };
}
componentDidMount() {
this.setState({ mounted: true });
}
render() {
return <div>{this.state.mounted ? 'a' : 'b'}</div>;
}
}
const wrapper = mount(<MySharona />);
expect(wrapper.find('div').text()).to.equal('a');
});
});
describe('.is(selector)', () => {
it('should return true when selector matches current element', () => {
const wrapper = mount(<div className="foo bar baz" />);
expect(wrapper.is('.foo')).to.equal(true);
});
it('should allow for compound selectors', () => {
const wrapper = mount(<div className="foo bar baz" />);
expect(wrapper.is('.foo.bar')).to.equal(true);
});
it('should ignore insignificant whitespace', () => {
const className = `
foo
`;
const wrapper = mount(<div className={className} />);
expect(wrapper.is('.foo')).to.equal(true);
});
it('should handle all significant whitespace', () => {
const className = `foo
bar
baz`;
const wrapper = mount(<div className={className} />);
expect(wrapper.is('.foo.bar.baz')).to.equal(true);
});
it('should return false when selector does not match', () => {
const wrapper = mount(<div className="bar baz" />);
expect(wrapper.is('.foo')).to.equal(false);
});
});
describe('.not(selector)', () => {
it('filters to things not matching a selector', () => {
const wrapper = mount(
<div>
<div className="foo bar baz" />
<div className="foo" />
<div className="bar baz" />
<div className="baz" />
<div className="foo bar" />
</div>
);
expect(wrapper.find('.foo').not('.bar').length).to.equal(1);
expect(wrapper.find('.baz').not('.foo').length).to.equal(2);
expect(wrapper.find('.foo').not('div').length).to.equal(0);
});
});
describe('.filter(selector)', () => {
it('should return a new wrapper of just the nodes that matched the selector', () => {
const wrapper = mount(
<div>
<div className="foo bar baz" />
<div className="foo" />
<div className="bar baz">
<div className="foo bar baz" />
<div className="foo" />
</div>
<div className="baz" />
<div className="foo bar" />
</div>
);
expect(wrapper.find('.foo').filter('.bar').length).to.equal(3);
expect(wrapper.find('.bar').filter('.foo').length).to.equal(3);
expect(wrapper.find('.bar').filter('.bax').length).to.equal(0);
expect(wrapper.find('.foo').filter('.baz.bar').length).to.equal(2);
});
it('should only look in the current wrappers nodes, not their children', () => {
const wrapper = mount(
<div>
<div className="foo">
<div className="bar" />
</div>
<div className="foo bar" />
</div>
);
expect(wrapper.find('.foo').filter('.bar').length).to.equal(1);
});
});
describe('.filterWhere(predicate)', () => {
it('should filter only the nodes of the wrapper', () => {
const wrapper = mount(
<div>
<div className="foo bar" />
<div className="foo baz" />
<div className="foo bux" />
</div>
);
const stub = sinon.stub();
stub.onCall(0).returns(false);
stub.onCall(1).returns(true);
stub.onCall(2).returns(false);
const baz = wrapper.find('.foo').filterWhere(stub);
expect(baz.length).to.equal(1);
expect(baz.hasClass('baz')).to.equal(true);
});
it('should call the predicate with the wrapper as the first argument', () => {
const wrapper = mount(
<div>
<div className="foo bar" />
<div className="foo baz" />
<div className="foo bux" />
</div>
);
const stub = sinon.stub();
stub.returns(true);
const spy = sinon.spy(stub);
wrapper.find('.foo').filterWhere(spy);
expect(spy.callCount).to.equal(3);
expect(spy.args[0][0]).to.be.instanceOf(ReactWrapper);
expect(spy.args[1][0]).to.be.instanceOf(ReactWrapper);
expect(spy.args[2][0]).to.be.instanceOf(ReactWrapper);
expect(spy.args[0][0].hasClass('bar')).to.equal(true);
expect(spy.args[1][0].hasClass('baz')).to.equal(true);
expect(spy.args[2][0].hasClass('bux')).to.equal(true);
});
});
describe('.text()', () => {
const matchesRender = function matchesRender(node) {
const actual = mount(node).text();
const expected = render(node).text();
expect(expected).to.equal(actual);
};
it('should handle simple text nodes', () => {
const wrapper = mount(
<div>some text</div>
);
expect(wrapper.text()).to.equal('some text');
});
it('should handle nodes with mapped children', () => {
class Foo extends React.Component {
render() {
return (
<div>
{this.props.items.map(x => x)}
</div>
);
}
}
matchesRender(<Foo items={['abc', 'def', 'hij']} />);
matchesRender(
<Foo
items={[
<i key={1}>abc</i>,
<i key={2}>def</i>,
<i key={3}>hij</i>,
]}
/>
);
});
it('should render composite components smartly', () => {
class Foo extends React.Component {
render() { return <div>foo</div>; }
}
const wrapper = mount(
<div>
<Foo />
<div>test</div>
</div>
);
expect(wrapper.text()).to.equal('footest');
});
it('should handle html entities', () => {
matchesRender(<div>></div>);
});
});
describe('.props()', () => {
it('should return the props object', () => {
const fn = () => ({});
const wrapper = mount(
<div id="fooId" className="bax" onClick={fn} >
<div className="baz" />
<div className="foo" />
</div>
);
expect(wrapper.props().className).to.equal('bax');
expect(wrapper.props().onClick).to.equal(fn);
expect(wrapper.props().id).to.equal('fooId');
});
it('should be allowed to be used on an inner node', () => {
const fn = () => ({});
const wrapper = mount(
<div className="bax">
<div className="baz" onClick={fn} />
<div className="foo" id="fooId" />
</div>
);
expect(wrapper.find('.baz').props().onClick).to.equal(fn);
expect(wrapper.find('.foo').props().id).to.equal('fooId');
});
});
describe('.state(name)', () => {
it('should return the state object', () => {
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = { foo: 'foo' };
}
render() { return <div />; }
}
const wrapper = mount(<Foo />);
expect(wrapper.state()).to.eql({ foo: 'foo' });
});
it('should return the current state after state transitions', () => {
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = { foo: 'foo' };
}
render() { return <div />; }
}
const wrapper = mount(<Foo />);
wrapper.setState({ foo: 'bar' });
expect(wrapper.state()).to.eql({ foo: 'bar' });
});
it('should allow a state property name be passed in as an argument', () => {
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = { foo: 'foo' };
}
render() { return <div />; }
}
const wrapper = mount(<Foo />);
expect(wrapper.state('foo')).to.equal('foo');
});
});
describe('.children([selector])', () => {
it('should return empty wrapper for node with no children', () => {
const wrapper = mount(<div />);
expect(wrapper.children().length).to.equal(0);
});
it('should return the children nodes of the root', () => {
const wrapper = mount(
<div>
<div className="foo" />
<div className="bar" />
<div className="baz" />
</div>
);
expect(wrapper.children().length).to.equal(3);
expect(wrapper.children().at(0).hasClass('foo')).to.equal(true);
expect(wrapper.children().at(1).hasClass('bar')).to.equal(true);
expect(wrapper.children().at(2).hasClass('baz')).to.equal(true);
});
it('should not return any of the children of children', () => {
const wrapper = mount(
<div>
<div className="foo">
<div className="bar" />
</div>
<div className="baz" />
</div>
);
expect(wrapper.children().length).to.equal(2);
expect(wrapper.children().at(0).hasClass('foo')).to.equal(true);
expect(wrapper.children().at(1).hasClass('baz')).to.equal(true);
});
it('should handle mixed children with and without arrays', () => {
class Foo extends React.Component {
render() {
return (
<div>
<span className="foo"></span>
{this.props.items.map(x => x)}
</div>
);
}
}
const wrapper = mount(
<Foo
items={[
<i key={1} className="bar">abc</i>,
<i key={2} className="baz">def</i>,
]}
/>
);
expect(wrapper.children().length).to.equal(3);
expect(wrapper.children().at(0).hasClass('foo')).to.equal(true);
expect(wrapper.children().at(1).hasClass('bar')).to.equal(true);
expect(wrapper.children().at(2).hasClass('baz')).to.equal(true);
});
it('should optionally allow a selector to filter by', () => {
const wrapper = mount(
<div>
<div className="foo" />
<div className="bar bip" />
<div className="baz bip" />
</div>
);
const children = wrapper.children('.bip');
expect(children.length).to.equal(2);
expect(children.at(0).hasClass('bar')).to.equal(true);
expect(children.at(1).hasClass('baz')).to.equal(true);
});
});
describe('.childAt(index)', () => {
it('should get a wrapped node at the specified index', () => {
const wrapper = mount(
<div>
<div className="bar" />
<div className="baz" />
</div>
);
expect(wrapper.childAt(0).hasClass('bar')).to.equal(true);
expect(wrapper.childAt(1).hasClass('baz')).to.equal(true);
});
});
describe('.parents([selector])', () => {
it('should return an array of current nodes ancestors', () => {
const wrapper = mount(
<div className="bax">
<div className="foo">
<div className="bar">
<div className="baz" />
</div>
</div>
</div>
);
const parents = wrapper.find('.baz').parents();
expect(parents.length).to.equal(3);
expect(parents.at(0).hasClass('bar')).to.equal(true);
expect(parents.at(1).hasClass('foo')).to.equal(true);
expect(parents.at(2).hasClass('bax')).to.equal(true);
});
it('should work for non-leaf nodes as well', () => {
const wrapper = mount(
<div className="bax">
<div className="foo">
<div className="bar">
<div className="baz" />
</div>
</div>
</div>
);
const parents = wrapper.find('.bar').parents();
expect(parents.length).to.equal(2);
expect(parents.at(0).hasClass('foo')).to.equal(true);
expect(parents.at(1).hasClass('bax')).to.equal(true);
});
it('should optionally allow a selector', () => {
const wrapper = mount(
<div className="bax foo">
<div className="foo">
<div className="bar">
<div className="baz" />
</div>
</div>
</div>
);
const parents = wrapper.find('.baz').parents('.foo');
expect(parents.length).to.equal(2);
expect(parents.at(0).hasClass('foo')).to.equal(true);
expect(parents.at(1).hasClass('bax')).to.equal(true);
});
});
describe('.parent()', () => {
it('should return only the immediate parent of the node', () => {
const wrapper = mount(
<div className="bax">
<div className="foo">
<div className="bar">
<div className="baz" />
</div>
</div>
</div>
);
expect(wrapper.find('.baz').parent().hasClass('bar')).to.equal(true);
});
it('should work for multiple nodes', () => {
const wrapper = mount(
<div>
<div className="foo">
<div className="baz" />
</div>
<div className="bar">
<div className="baz" />
</div>
<div className="bax">
<div className="baz" />
</div>
</div>
);
const parents = wrapper.find('.baz').parent();
expect(parents).to.have.length(3);
expect(parents.at(0).hasClass('foo')).to.equal(true);
expect(parents.at(1).hasClass('bar')).to.equal(true);
expect(parents.at(2).hasClass('bax')).to.equal(true);
});
});
describe('.closest(selector)', () => {
it('should return the closest ancestor for a given selector', () => {
const wrapper = mount(
<div className="foo">
<div className="foo baz">
<div className="bax">
<div className="bar" />
</div>
</div>
</div>
);
const closestFoo = wrapper.find('.bar').closest('.foo');
expect(closestFoo.hasClass('baz')).to.equal(true);
expect(closestFoo.length).to.equal(1);
});
it('should only ever return a wrapper of a single node', () => {
const wrapper = mount(
<div className="bax">
<div className="foo">
<div className="bar">
<div className="baz" />
</div>
</div>
</div>
);
expect(wrapper.find('.baz').parent().hasClass('bar')).to.equal(true);
});
it('should return itself if matching', () => {
const wrapper = mount(
<div className="bax">
<div className="foo">
<div className="baz">
<div className="bux baz" />
</div>
</div>
</div>
);
expect(wrapper.find('.bux').closest('.baz').hasClass('bux')).to.equal(true);
});
});
describe('.hasClass(className)', () => {
it('should return whether or not node has a certain class', () => {
const wrapper = mount(
<div className="foo bar baz some-long-string FoOo" />
);
expect(wrapper.hasClass('foo')).to.equal(true);
expect(wrapper.hasClass('bar')).to.equal(true);
expect(wrapper.hasClass('baz')).to.equal(true);
expect(wrapper.hasClass('some-long-string')).to.equal(true);
expect(wrapper.hasClass('FoOo')).to.equal(true);
expect(wrapper.hasClass('doesnt-exist')).to.equal(false);
});
});
describe('.forEach(fn)', () => {
it('should call a function for each node in the wrapper', () => {
const wrapper = mount(
<div>
<div className="foo bax" />
<div className="foo bar" />
<div className="foo baz" />
</div>
);
const spy = sinon.spy();
wrapper.find('.foo').forEach(spy);
expect(spy.callCount).to.equal(3);
expect(spy.args[0][0]).to.be.instanceOf(ReactWrapper);
expect(spy.args[0][0].hasClass('bax')).to.equal(true);
expect(spy.args[1][0]).to.be.instanceOf(ReactWrapper);
expect(spy.args[1][0].hasClass('bar')).to.equal(true);
expect(spy.args[2][0]).to.be.instanceOf(ReactWrapper);
expect(spy.args[2][0].hasClass('baz')).to.equal(true);
});
});
describe('.map(fn)', () => {
it('should call a function with a wrapper for each node in the wrapper', () => {
const wrapper = mount(
<div>
<div className="foo bax" />
<div className="foo bar" />
<div className="foo baz" />
</div>
);
const spy = sinon.spy();
wrapper.find('.foo').map(spy);
expect(spy.callCount).to.equal(3);
expect(spy.args[0][0]).to.be.instanceOf(ReactWrapper);
expect(spy.args[0][0].hasClass('bax')).to.equal(true);
expect(spy.args[1][0]).to.be.instanceOf(ReactWrapper);
expect(spy.args[1][0].hasClass('bar')).to.equal(true);
expect(spy.args[2][0]).to.be.instanceOf(ReactWrapper);
expect(spy.args[2][0].hasClass('baz')).to.equal(true);
});
it('should return an array with the mapped values', () => {
const wrapper = mount(
<div>
<div className="foo bax" />
<div className="foo bar" />
<div className="foo baz" />
</div>
);
const result = wrapper.find('.foo').map(w => w.props().className);
expect(result).to.eql([
'foo bax',
'foo bar',
'foo baz',
]);
});
});
describe('.reduce(fn[, initialValue])', () => {
it('should call a function with a wrapper for each node in the wrapper', () => {
const wrapper = mount(
<div>
<div className="foo bax" />
<div className="foo bar" />
<div className="foo baz" />
</div>
);
const spy = sinon.spy(n => n + 1);
wrapper.find('.foo').reduce(spy, 0);
expect(spy.callCount).to.equal(3);
expect(spy.args[0][1]).to.be.instanceOf(ReactWrapper);
expect(spy.args[0][1].hasClass('bax')).to.equal(true);
expect(spy.args[1][1]).to.be.instanceOf(ReactWrapper);
expect(spy.args[1][1].hasClass('bar')).to.equal(true);
expect(spy.args[2][1]).to.be.instanceOf(ReactWrapper);
expect(spy.args[2][1].hasClass('baz')).to.equal(true);
});
it('should accumulate a value', () => {
const wrapper = mount(
<div>
<div id="bax" className="foo qoo" />
<div id="bar" className="foo boo" />
<div id="baz" className="foo hoo" />
</div>
);
const result = wrapper.find('.foo').reduce((obj, n) => {
obj[n.prop('id')] = n.prop('className');
return obj;
}, {});
expect(result).to.eql({
bax: 'foo qoo',
bar: 'foo boo',
baz: 'foo hoo',
});
});
});
describe('.reduceRight(fn[, initialValue])', () => {
it('should call a function with a wrapper for each node in the wrapper in reverse', () => {
const wrapper = mount(
<div>
<div className="foo bax" />
<div className="foo bar" />
<div className="foo baz" />
</div>
);
const spy = sinon.spy(n => n + 1);
wrapper.find('.foo').reduceRight(spy, 0);
expect(spy.callCount).to.equal(3);
expect(spy.args[0][1]).to.be.instanceOf(ReactWrapper);
expect(spy.args[0][1].hasClass('baz')).to.equal(true);
expect(spy.args[1][1]).to.be.instanceOf(ReactWrapper);
expect(spy.args[1][1].hasClass('bar')).to.equal(true);
expect(spy.args[2][1]).to.be.instanceOf(ReactWrapper);
expect(spy.args[2][1].hasClass('bax')).to.equal(true);
});
it('should accumulate a value', () => {
const wrapper = mount(
<div>
<div id="bax" className="foo qoo" />
<div id="bar" className="foo boo" />
<div id="baz" className="foo hoo" />
</div>
);
const result = wrapper.find('.foo').reduceRight((obj, n) => {
obj[n.prop('id')] = n.prop('className');
return obj;
}, {});
expect(result).to.eql({
bax: 'foo qoo',
bar: 'foo boo',
baz: 'foo hoo',
});
});
});
describe('.some(selector)', () => {
it('should return if a node matches a selector', () => {
const wrapper = mount(
<div>
<div className="foo qoo" />
<div className="foo boo" />
<div className="foo hoo" />
</div>
);
expect(wrapper.find('.foo').some('.qoo')).to.equal(true);
expect(wrapper.find('.foo').some('.foo')).to.equal(true);
expect(wrapper.find('.foo').some('.bar')).to.equal(false);
});
});
describe('.someWhere(predicate)', () => {
it('should return if a node matches a predicate', () => {
const wrapper = mount(
<div>
<div className="foo qoo" />
<div className="foo boo" />
<div className="foo hoo" />
</div>
);
expect(wrapper.find('.foo').someWhere(n => n.hasClass('qoo'))).to.equal(true);
expect(wrapper.find('.foo').someWhere(n => n.hasClass('foo'))).to.equal(true);
expect(wrapper.find('.foo').someWhere(n => n.hasClass('bar'))).to.equal(false);
});
});
describe('.every(selector)', () => {
it('should return if every node matches a selector', () => {
const wrapper = mount(
<div>
<div className="foo qoo" />
<div className="foo boo" />
<div className="foo hoo" />
</div>
);
expect(wrapper.find('.foo').every('.foo')).to.equal(true);
expect(wrapper.find('.foo').every('.qoo')).to.equal(false);
expect(wrapper.find('.foo').every('.bar')).to.equal(false);
});
});
describe('.everyWhere(predicate)', () => {
it('should return if every node matches a predicate', () => {
const wrapper = mount(
<div>
<div className="foo qoo" />
<div className="foo boo" />
<div className="foo hoo" />
</div>
);
expect(wrapper.find('.foo').everyWhere(n => n.hasClass('foo'))).to.equal(true);
expect(wrapper.find('.foo').everyWhere(n => n.hasClass('qoo'))).to.equal(false);
expect(wrapper.find('.foo').everyWhere(n => n.hasClass('bar'))).to.equal(false);
});
});
describe('.flatMap(fn)', () => {
it('should return a wrapper with the mapped and flattened nodes', () => {
const wrapper = mount(
<div>
<div className="foo">
<div className="bar" />
<div className="bar" />
</div>
<div className="foo">
<div className="baz" />
<div className="baz" />
</div>
<div className="foo">
<div className="bax" />
<div className="bax" />
</div>
</div>
);
const nodes = wrapper.find('.foo').flatMap(w => w.children().nodes);
expect(nodes.length).to.equal(6);
expect(nodes.at(0).hasClass('bar')).to.equal(true);
expect(nodes.at(1).hasClass('bar')).to.equal(true);
expect(nodes.at(2).hasClass('baz')).to.equal(true);
expect(nodes.at(3).hasClass('baz')).to.equal(true);
expect(nodes.at(4).hasClass('bax')).to.equal(true);
expect(nodes.at(5).hasClass('bax')).to.equal(true);
});
});
describe('.first()', () => {
it('should return the first node in the current set', () => {
const wrapper = mount(
<div>
<div className="bar baz" />
<div className="bar" />
<div className="bar" />
<div className="bar" />
</div>
);
expect(wrapper.find('.bar').first().hasClass('baz')).to.equal(true);
});
});
describe('.last()', () => {
it('should return the last node in the current set', () => {
const wrapper = mount(
<div>
<div className="bar" />
<div className="bar" />
<div className="bar" />
<div className="bar baz" />
</div>
);
expect(wrapper.find('.bar').last().hasClass('baz')).to.equal(true);
});
});
describe('.isEmpty()', () => {
it('should return true iff wrapper is empty', () => {
const wrapper = mount(
<div className="foo" />
);
expect(wrapper.find('.bar').isEmpty()).to.equal(true);
expect(wrapper.find('.foo').isEmpty()).to.equal(false);
});
});
describe('.at(index)', () => {
it('gets a wrapper of the node at the specified index', () => {
const wrapper = mount(
<div>
<div className="bar foo" />
<div className="bar bax" />
<div className="bar bux" />
<div className="bar baz" />
</div>
);
expect(wrapper.find('.bar').at(0).hasClass('foo')).to.equal(true);
expect(wrapper.find('.bar').at(1).hasClass('bax')).to.equal(true);
expect(wrapper.find('.bar').at(2).hasClass('bux')).to.equal(true);
expect(wrapper.find('.bar').at(3).hasClass('baz')).to.equal(true);
});
});
describe('.get(index)', () => {
it('gets the node at the specified index', () => {
const wrapper = mount(
<div>
<div className="bar foo" />
<div className="bar bax" />
<div className="bar bux" />
<div className="bar baz" />
</div>
);
expect(wrapper.find('.bar').get(0)).to.equal(wrapper.find('.foo').node);
expect(wrapper.find('.bar').get(1)).to.equal(wrapper.find('.bax').node);
expect(wrapper.find('.bar').get(2)).to.equal(wrapper.find('.bux').node);
expect(wrapper.find('.bar').get(3)).to.equal(wrapper.find('.baz').node);
});
});
describe('.ref(refName)', () => {
it('gets a wrapper of the node matching the provided refName', () => {
class Foo extends React.Component {
render() {
return (
<div>
<span ref="firstRef" amount={2}>First</span>
<span ref="secondRef" amount={4}>Second</span>
<span ref="thirdRef" amount={8}>Third</span>
</div>
);
}
}
const wrapper = mount(<Foo />);
expect(wrapper.ref('secondRef').prop('amount')).to.equal(4);
expect(wrapper.ref('secondRef').text()).to.equal('Second');
});
});
describe('.html()', () => {
it('should return html of straight DOM elements', () => {
const wrapper = mount(
<div className="test">
<span>Hello World!</span>
</div>
);
expect(wrapper.html()).to.equal(
'<div class="test"><span>Hello World!</span></div>'
);
});
it('should render out nested composite components', () => {
class Foo extends React.Component {
render() {
return (<div className="in-foo" />);
}
}
class Bar extends React.Component {
render() {
return (
<div className="in-bar">
<Foo />
</div>
);
}
}
const wrapper = mount(<Bar />);
expect(wrapper.html()).to.equal(
'<div class="in-bar"><div class="in-foo"></div></div>'
);
expect(wrapper.find(Foo).html()).to.equal(
'<div class="in-foo"></div>'
);
});
});
describe('.render()', () => {
it('should return a cheerio wrapper around the current node', () => {
class Foo extends React.Component {
render() {
return (<div className="in-foo" />);
}
}
class Bar extends React.Component {
render() {
return (
<div className="in-bar">
<Foo />
</div>
);
}
}
const wrapper = mount(<Bar />);
expect(wrapper.render().find('.in-foo')).to.have.length(1);
});
});
describe('.tap()', () => {
it('should call the passed function with current ShallowWrapper and returns itself', () => {
const spy = sinon.spy();
const wrapper = mount(
<ul>
<li>xxx</li>
<li>yyy</li>
<li>zzz</li>
</ul>
).find('li');
const result = wrapper.tap(spy);
expect(spy.calledWith(wrapper)).to.equal(true);
expect(result).to.equal(wrapper);
});
});
describe('attachTo option', () => {
it('should attach and stuff', () => {
class Foo extends React.Component {
render() {
return (<div className="in-foo" />);
}
}
const div = global.document.createElement('div');
global.document.body.appendChild(div);
expect(document.body.childNodes).to.have.length(1);
expect(div.childNodes).to.have.length(0);
const wrapper = mount(<Foo />, { attachTo: div });
expect(wrapper.find('.in-foo')).to.have.length(1);
expect(document.body.childNodes).to.have.length(1);
expect(div.childNodes).to.have.length(1);
wrapper.detach();
expect(document.body.childNodes).to.have.length(1);
expect(div.childNodes).to.have.length(0);
global.document.body.removeChild(div);
expect(document.body.childNodes).to.have.length(0);
expect(div.childNodes).to.have.length(0);
});
it('should allow for multiple attaches/detaches on same node', () => {
class Foo extends React.Component {
render() {
return (<div className="in-foo" />);
}
}
class Bar extends React.Component {
render() {
return (<section className="in-bar" />);
}
}
let wrapper;
const div = global.document.createElement('div');
global.document.body.appendChild(div);
expect(document.body.childNodes).to.have.length(1);
expect(div.childNodes).to.have.length(0);
wrapper = mount(<Foo />, { attachTo: div });
expect(wrapper.find('.in-foo')).to.have.length(1);
expect(document.body.childNodes).to.have.length(1);
expect(div.childNodes).to.have.length(1);
wrapper.detach();
wrapper = mount(<Bar />, { attachTo: div });
expect(wrapper.find('.in-bar')).to.have.length(1);
expect(document.body.childNodes).to.have.length(1);
expect(div.childNodes).to.have.length(1);
wrapper.detach();
expect(document.body.childNodes).to.have.length(1);
expect(div.childNodes).to.have.length(0);
global.document.body.removeChild(div);
expect(document.body.childNodes).to.have.length(0);
expect(div.childNodes).to.have.length(0);
});
it('will attach to the body successfully', () => {
class Bar extends React.Component {
render() {
return (<section className="in-bar" />);
}
}
const wrapper = mount(<Bar />, { attachTo: document.body });
expect(wrapper.find('.in-bar')).to.have.length(1);
expect(document.body.childNodes).to.have.length(1);
wrapper.detach();
expect(document.body.childNodes).to.have.length(0);
});
});
it('works with components that return null', () => {
class Foo extends React.Component {
render() {
return null;
}
}
const wrapper = mount(<Foo />);
expect(wrapper).to.have.length(1);
expect(wrapper.type()).to.equal(Foo);
expect(wrapper.html()).to.equal(null);
const rendered = wrapper.render();
expect(rendered.length).to.equal(0);
expect(rendered.html()).to.equal(null);
});
describe('.key()', () => {
it('should return the key of the node', () => {
const wrapper = mount(
<ul>
{['foo', 'bar'].map(s => <li key={s}>{s}</li>)}
</ul>
).find('li');
expect(wrapper.at(0).key()).to.equal('foo');
expect(wrapper.at(1).key()).to.equal('bar');
});
});
describe('.matchesElement(node)', () => {
it('should match on a root node that looks like the rendered one', () => {
const spy = sinon.spy();
const wrapper = mount(
<div>
<div onClick={spy} style={{ fontSize: 12, color: 'red' }}>Hello World</div>
</div>
).first();
expect(wrapper.matchesElement(<div><div>Hello World</div></div>)).to.equal(true);
expect(wrapper.matchesElement(
<div>
<div onClick={spy} style={{ fontSize: 12, color: 'red' }}>Hello World</div>
</div>
)).to.equal(true);
expect(wrapper.matchesElement(
<div>
<div onClick={spy}>Hello World</div>
</div>
)).to.equal(true);
expect(wrapper.matchesElement(
<div>
<div style={{ fontSize: 12, color: 'red' }}>Hello World</div>
</div>
)).to.equal(true);
expect(spy.callCount).to.equal(0);
});
it('should not match on a root node that doesn\'t looks like the rendered one', () => {
const spy = sinon.spy();
const spy2 = sinon.spy();
const wrapper = mount(
<div>
<div onClick={spy} style={{ fontSize: 12, color: 'red' }}>Hello World</div>
</div>
).first();
expect(wrapper.matchesElement(<div><div>Bonjour le monde</div></div>)).to.equal(false);
expect(wrapper.matchesElement(
<div>
<div onClick={spy} style={{ fontSize: 12, color: 'blue' }}>Hello World</div>
</div>
)).to.equal(false);
expect(wrapper.matchesElement(
<div>
<div onClick={spy2}>Hello World</div>
</div>
)).to.equal(false);
expect(wrapper.matchesElement(
<div>
<div style={{ fontSize: 13, color: 'red' }}>Hello World</div>
</div>
)).to.equal(false);
expect(spy.callCount).to.equal(0);
expect(spy2.callCount).to.equal(0);
});
});
describe('.containsMatchingElement(node)', () => {
it('should match a root node that looks like the rendered one', () => {
const spy1 = sinon.spy();
const spy2 = sinon.spy();
const wrapper = mount(
<div>
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Hello World</div>
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>
</div>
);
expect(wrapper.containsMatchingElement(
<div>
<div>Hello World</div>
<div>Goodbye World</div>
</div>
)).to.equal(true);
expect(wrapper.containsMatchingElement(
<div>
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Hello World</div>
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>
</div>
)).to.equal(true);
expect(wrapper.containsMatchingElement(
<div>
<div onClick={spy1}>Hello World</div>
<div style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>
</div>
)).to.equal(true);
expect(wrapper.containsMatchingElement(
<div>
<div style={{ fontSize: 12, color: 'red' }}>Hello World</div>
<div onClick={spy2}>Goodbye World</div>
</div>
)).to.equal(true);
expect(wrapper.containsMatchingElement(
<div>
<div>Hello World</div>
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>
</div>
)).to.equal(true);
expect(wrapper.containsMatchingElement(
<div>
<div>Hello World</div>
<div style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>
</div>
)).to.equal(true);
expect(spy1.callCount).to.equal(0);
expect(spy2.callCount).to.equal(0);
});
it('should match on a single node that looks like a rendered one', () => {
const spy1 = sinon.spy();
const spy2 = sinon.spy();
const wrapper = mount(
<div>
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Hello World</div>
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>
</div>
);
expect(wrapper.containsMatchingElement(
<div>Hello World</div>
)).to.equal(true);
expect(wrapper.containsMatchingElement(
<div>Goodbye World</div>
)).to.equal(true);
expect(wrapper.containsMatchingElement(
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Hello World</div>
)).to.equal(true);
expect(wrapper.containsMatchingElement(
<div style={{ fontSize: 12, color: 'red' }}>Hello World</div>
)).to.equal(true);
expect(wrapper.containsMatchingElement(
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>
)).to.equal(true);
expect(wrapper.containsMatchingElement(
<div onClick={spy2}>Goodbye World</div>
)).to.equal(true);
expect(spy1.callCount).to.equal(0);
expect(spy2.callCount).to.equal(0);
});
it('should not match on a single node that doesn\'t looks like a rendered one', () => {
const spy1 = sinon.spy();
const spy2 = sinon.spy();
const wrapper = mount(
<div>
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Hello World</div>
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>
</div>
);
expect(wrapper.containsMatchingElement(
<div>Bonjour le monde</div>
)).to.equal(false);
expect(wrapper.containsMatchingElement(
<div onClick={spy2}>Au revoir le monde</div>
)).to.equal(false);
});
});
describe('.containsAllMatchingElements(nodes)', () => {
it('should match on an array of nodes that all looks like one of rendered nodes', () => {
const spy1 = sinon.spy();
const spy2 = sinon.spy();
const wrapper = mount(
<div>
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Hello World</div>
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>
</div>
);
expect(wrapper.containsAllMatchingElements([
<div>Hello World</div>,
<div>Goodbye World</div>,
])).to.equal(true);
expect(wrapper.containsAllMatchingElements([
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Hello World</div>,
<div>Goodbye World</div>,
])).to.equal(true);
expect(wrapper.containsAllMatchingElements([
<div>Hello World</div>,
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>,
])).to.equal(true);
expect(wrapper.containsAllMatchingElements([
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Hello World</div>,
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>,
])).to.equal(true);
expect(wrapper.containsAllMatchingElements([
<div onClick={spy1}>Hello World</div>,
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>,
])).to.equal(true);
expect(wrapper.containsAllMatchingElements([
<div style={{ fontSize: 12, color: 'red' }}>Hello World</div>,
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>,
])).to.equal(true);
expect(wrapper.containsAllMatchingElements([
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Hello World</div>,
<div style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>,
])).to.equal(true);
expect(wrapper.containsAllMatchingElements([
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Hello World</div>,
<div onClick={spy2}>Goodbye World</div>,
])).to.equal(true);
expect(spy1.callCount).to.equal(0);
expect(spy2.callCount).to.equal(0);
});
it('should not match on nodes that doesn\'t all looks like one of rendered nodes', () => {
const spy1 = sinon.spy();
const spy2 = sinon.spy();
const wrapper = mount(
<div>
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Hello World</div>
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>
</div>
);
expect(wrapper.containsAllMatchingElements([
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Hello World</div>,
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Bonjour le monde</div>,
<div onClick={spy2}>Goodbye World</div>,
])).to.equal(false);
expect(spy1.callCount).to.equal(0);
expect(spy2.callCount).to.equal(0);
});
});
describe('.containsAnyMatchingElements(nodes)', () => {
it('should match on an array with at least one node that looks like a rendered nodes', () => {
const spy1 = sinon.spy();
const spy2 = sinon.spy();
const wrapper = mount(
<div>
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Hello World</div>
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>
</div>
);
expect(wrapper.containsAnyMatchingElements([
<div>Bonjour le monde</div>,
<div>Goodbye World</div>,
])).to.equal(true);
expect(wrapper.containsAnyMatchingElements([
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Bonjour le monde</div>,
<div>Goodbye World</div>,
])).to.equal(true);
expect(wrapper.containsAnyMatchingElements([
<div>Bonjour le monde</div>,
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>,
])).to.equal(true);
expect(wrapper.containsAnyMatchingElements([
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Bonjour le monde</div>,
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>,
])).to.equal(true);
expect(wrapper.containsAnyMatchingElements([
<div onClick={spy1}>Bonjour le monde</div>,
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>,
])).to.equal(true);
expect(wrapper.containsAnyMatchingElements([
<div style={{ fontSize: 12, color: 'red' }}>Bonjour le monde</div>,
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>,
])).to.equal(true);
expect(wrapper.containsAnyMatchingElements([
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Bonjour le monde</div>,
<div style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>,
])).to.equal(true);
expect(wrapper.containsAnyMatchingElements([
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Bonjour le monde</div>,
<div onClick={spy2}>Goodbye World</div>,
])).to.equal(true);
expect(spy1.callCount).to.equal(0);
expect(spy2.callCount).to.equal(0);
});
it('should not match on an array with no nodes that looks like a rendered nodes', () => {
const spy1 = sinon.spy();
const spy2 = sinon.spy();
const wrapper = mount(
<div>
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Hello World</div>
<div onClick={spy2} style={{ fontSize: 13, color: 'blue' }}>Goodbye World</div>
</div>
);
expect(wrapper.containsAnyMatchingElements([
<div onClick={spy1} style={{ fontSize: 12, color: 'red' }}>Bonjour le monde</div>,
<div onClick={spy2}>Au revoir le monde</div>,
])).to.equal(false);
expect(spy1.callCount).to.equal(0);
expect(spy2.callCount).to.equal(0);
});
});
describe('.name()', () => {
describe('node with displayName', () => {
it('should return the displayName of the node', () => {
class Foo extends React.Component {
render() { return <div />; }
}
Foo.displayName = 'CustomWrapper';
const wrapper = mount(<Foo />);
expect(wrapper.name()).to.equal('CustomWrapper');
});
describeIf(!REACT013, 'stateless function components', () => {
it('should return the name of the node', () => {
function SFC() {
return <div />;
}
SFC.displayName = 'CustomWrapper';
const wrapper = mount(<SFC />);
expect(wrapper.name()).to.equal('CustomWrapper');
});
});
describe('React.createClass', () => {
it('should return the name of the node', () => {
const Foo = React.createClass({
displayName: 'CustomWrapper',
render() {
return <div />;
},
});
const wrapper = mount(<Foo />);
expect(wrapper.name()).to.equal('CustomWrapper');
});
});
});
describe('node without displayName', () => {
it('should return the name of the node', () => {
class Foo extends React.Component {
render() { return <div />; }
}
const wrapper = mount(<Foo />);
expect(wrapper.name()).to.equal('Foo');
});
describeIf(!REACT013, 'stateless function components', () => {
it('should return the name of the node', () => {
function SFC() {
return <div />;
}
const wrapper = mount(<SFC />);
expect(wrapper.name()).to.equal('SFC');
});
});
describe('React.createClass', () => {
it('should return the name of the node', () => {
const Foo = React.createClass({
render() {
return <div />;
},
});
const wrapper = mount(<Foo />);
expect(wrapper.name()).to.equal('Foo');
});
});
});
describe('DOM node', () => {
it('should return the name of the node', () => {
const wrapper = mount(<div />);
expect(wrapper.name()).to.equal('div');
});
});
});
});
|
fields/types/datetime/DatetimeField.js
|
xyzteam2016/keystone
|
import DateInput from '../../components/DateInput';
import Field from '../Field';
import moment from 'moment';
import React from 'react';
import { Button, FormField, FormInput, FormNote, InputGroup } from 'elemental';
module.exports = Field.create({
displayName: 'DatetimeField',
statics: {
type: 'Datetime',
},
focusTargetRef: 'dateInput',
// default input formats
dateInputFormat: 'YYYY-MM-DD',
timeInputFormat: 'h:mm:ss a',
tzOffsetInputFormat: 'Z',
// parse formats (duplicated from lib/fieldTypes/datetime.js)
parseFormats: ['YYYY-MM-DD', 'YYYY-MM-DD h:m:s a', 'YYYY-MM-DD h:m a', 'YYYY-MM-DD H:m:s', 'YYYY-MM-DD H:m'],
getInitialState () {
return {
dateValue: this.props.value && this.moment(this.props.value).format(this.dateInputFormat),
timeValue: this.props.value && this.moment(this.props.value).format(this.timeInputFormat),
tzOffsetValue: this.props.value ? this.moment(this.props.value).format(this.tzOffsetInputFormat) : this.moment().format(this.tzOffsetInputFormat),
};
},
getDefaultProps () {
return {
formatString: 'Do MMM YYYY, h:mm:ss a',
};
},
moment () {
if (this.props.isUTC) return moment.utc.apply(moment, arguments);
else return moment.apply(undefined, arguments);
},
// TODO: Move isValid() so we can share with server-side code
isValid (value) {
return this.moment(value, this.parseFormats).isValid();
},
// TODO: Move format() so we can share with server-side code
format (value, format) {
format = format || this.dateInputFormat + ' ' + this.timeInputFormat;
return value ? this.moment(value).format(format) : '';
},
handleChange (dateValue, timeValue, tzOffsetValue) {
var value = dateValue + ' ' + timeValue;
var datetimeFormat = this.dateInputFormat + ' ' + this.timeInputFormat;
// if the change included a timezone offset, include that in the calculation (so NOW works correctly during DST changes)
if (typeof tzOffsetValue !== 'undefined') {
value += ' ' + tzOffsetValue;
datetimeFormat += ' ' + this.tzOffsetInputFormat;
}
// if not, calculate the timezone offset based on the date (respect different DST values)
else {
this.setState({ tzOffsetValue: this.moment(value, datetimeFormat).format(this.tzOffsetInputFormat) });
}
this.props.onChange({
path: this.props.path,
value: this.isValid(value) ? this.moment(value, datetimeFormat).toISOString() : null,
});
},
dateChanged ({ value }) {
this.setState({ dateValue: value });
this.handleChange(value, this.state.timeValue);
},
timeChanged (evt) {
this.setState({ timeValue: evt.target.value });
this.handleChange(this.state.dateValue, evt.target.value);
},
setNow () {
var dateValue = this.moment().format(this.dateInputFormat);
var timeValue = this.moment().format(this.timeInputFormat);
var tzOffsetValue = this.moment().format(this.tzOffsetInputFormat);
this.setState({
dateValue: dateValue,
timeValue: timeValue,
tzOffsetValue: tzOffsetValue,
});
this.handleChange(dateValue, timeValue, tzOffsetValue);
},
renderNote () {
if (!this.props.note) return null;
return <FormNote note={this.props.note} />;
},
renderUI () {
var input;
if (this.shouldRenderField()) {
input = (
<InputGroup>
<InputGroup.Section grow>
<DateInput ref="dateInput" name={this.props.paths.date} value={this.state.dateValue} format={this.dateInputFormat} onChange={this.dateChanged} />
</InputGroup.Section>
<InputGroup.Section grow>
<FormInput name={this.props.paths.time} value={this.state.timeValue} placeholder="HH:MM:SS am/pm" onChange={this.timeChanged} autoComplete="off" />
</InputGroup.Section>
<InputGroup.Section>
<Button onClick={this.setNow}>Now</Button>
</InputGroup.Section>
<input type="hidden" name={this.props.paths.tzOffset} value={this.state.tzOffsetValue} />
</InputGroup>
);
} else {
input = <FormInput noedit>{this.format(this.props.value, this.props.formatString)}</FormInput>;
}
return (
<FormField label={this.props.label} className="field-type-datetime" htmlFor={this.props.path}>
{input}
{this.renderNote()}
</FormField>
);
},
});
|
src/routes/mypolls/index.js
|
binyuace/vote
|
import React from 'react';
import Layout from '../../components/Layout';
async function action({ fetch, store }) {
const resp = await fetch('/api/polls', {
method: 'GET',
});
const data = await resp.json();
const state = store.getState();
if (!data) throw new Error('Failed to load the polls feed.');
const myPolls = data
.filter(arr => arr.creatorId === (state.user ? state.user.id : null))
.reverse()
.map(arr =>
<h1 key={arr._id}>
<a href={`/poll/${arr._id}`}>
{arr.title}
</a>
</h1>,
);
return {
chunks: ['about'],
title: 'My Polls',
component: (
<Layout>
{myPolls}
</Layout>
),
};
}
export default action;
|
node_modules/enzyme/src/ReactWrapper.js
|
aurimas-darguzis/react-intro
|
import React from 'react';
import cheerio from 'cheerio';
import { flatten, unique, compact } from 'underscore';
import createWrapperComponent from './ReactWrapperComponent';
import {
instHasClassName,
childrenOfInst,
parentsOfInst,
buildInstPredicate,
instEqual,
treeFilter,
getNode,
} from './MountedTraversal';
import {
renderWithOptions,
Simulate,
findDOMNode,
unmountComponentAtNode,
} from './react-compat';
import {
mapNativeEventNames,
containsChildrenSubArray,
propsOfNode,
typeOfNode,
} from './Utils';
import {
debugInsts,
} from './Debug';
/**
* Finds all nodes in the current wrapper nodes' render trees that match the provided predicate
* function.
*
* @param {ReactWrapper} wrapper
* @param {Function} predicate
* @returns {ReactWrapper}
*/
function findWhereUnwrapped(wrapper, predicate) {
return wrapper.flatMap(n => treeFilter(n.node, predicate));
}
/**
* Returns a new wrapper instance with only the nodes of the current wrapper instance that match
* the provided predicate function.
*
* @param {ReactWrapper} wrapper
* @param {Function} predicate
* @returns {ReactWrapper}
*/
function filterWhereUnwrapped(wrapper, predicate) {
return wrapper.wrap(compact(wrapper.nodes.filter(predicate)));
}
/**
* @class ReactWrapper
*/
export default class ReactWrapper {
constructor(nodes, root, options = {}) {
if (!global.window && !global.document) {
throw new Error(
`It looks like you called \`mount()\` without a jsdom document being loaded. ` +
`Make sure to only use \`mount()\` inside of a \`describeWithDOM(...)\` call. `
);
}
if (!root) {
const ReactWrapperComponent = createWrapperComponent(nodes, options);
this.component = renderWithOptions(
<ReactWrapperComponent
Component={nodes.type}
props={nodes.props}
context={options.context}
/>,
options);
this.root = this;
this.node = this.component.getWrappedComponent();
this.nodes = [this.node];
this.length = 1;
} else {
this.component = null;
this.root = root;
if (!Array.isArray(nodes)) {
this.node = nodes;
this.nodes = [nodes];
} else {
this.node = nodes[0];
this.nodes = nodes;
}
this.length = this.nodes.length;
}
this.options = options;
}
/**
* If the root component contained a ref, you can access it here
* and get a wrapper around it.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
*
* @param {String} refname
* @returns {ReactWrapper}
*/
ref(refname) {
if (this.root !== this) {
throw new Error('ReactWrapper::ref(refname) can only be called on the root');
}
return this.wrap(this.instance().refs[refname]);
}
/**
* Gets the instance of the component being rendered as the root node passed into `mount()`.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
*
* Example:
* ```
* const wrapper = mount(<MyComponent />);
* const inst = wrapper.instance();
* expect(inst).to.be.instanceOf(MyComponent);
* ```
* @returns {ReactComponent}
*/
instance() {
return this.component.getInstance();
}
/**
* Forces a re-render. Useful to run before checking the render output if something external
* may be updating the state of the component somewhere.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
*
* @returns {ReactWrapper}
*/
update() {
if (this.root !== this) {
// TODO(lmr): this requirement may not be necessary for the ReactWrapper
throw new Error('ReactWrapper::update() can only be called on the root');
}
this.single(() => {
this.component.forceUpdate();
});
return this;
}
/**
* A method that unmounts the component. This can be used to simulate a component going through
* and unmount/mount lifecycle.
*
* @returns {ReactWrapper}
*/
unmount() {
if (this.root !== this) {
throw new Error('ReactWrapper::unmount() can only be called on the root');
}
this.single(() => {
this.component.setState({ mount: false });
});
return this;
}
/**
* A method that re-mounts the component. This can be used to simulate a component going through
* an unmount/mount lifecycle.
*
* @returns {ReactWrapper}
*/
mount() {
if (this.root !== this) {
throw new Error('ReactWrapper::mount() can only be called on the root');
}
this.single(() => {
this.component.setState({ mount: true });
});
return this;
}
/**
* A method that sets the props of the root component, and re-renders. Useful for when you are
* wanting to test how the component behaves over time with changing props. Calling this, for
* instance, will call the `componentWillReceiveProps` lifecycle method.
*
* Similar to `setState`, this method accepts a props object and will merge it in with the already
* existing props.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
*
* @param {Object} props object
* @returns {ReactWrapper}
*/
setProps(props) {
if (this.root !== this) {
throw new Error('ReactWrapper::setProps() can only be called on the root');
}
this.component.setChildProps(props);
return this;
}
/**
* A method to invoke `setState` on the root component instance similar to how you might in the
* definition of the component, and re-renders. This method is useful for testing your component
* in hard to achieve states, however should be used sparingly. If possible, you should utilize
* your component's external API in order to get it into whatever state you want to test, in order
* to be as accurate of a test as possible. This is not always practical, however.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
*
* @param {Object} state to merge
* @returns {ReactWrapper}
*/
setState(state) {
if (this.root !== this) {
throw new Error('ReactWrapper::setState() can only be called on the root');
}
this.instance().setState(state);
return this;
}
/**
* A method that sets the context of the root component, and re-renders. Useful for when you are
* wanting to test how the component behaves over time with changing contexts.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
*
* @param {Object} context object
* @returns {ReactWrapper}
*/
setContext(context) {
if (this.root !== this) {
throw new Error('ReactWrapper::setContext() can only be called on the root');
}
if (!this.options.context) {
throw new Error(
'ShallowWrapper::setContext() can only be called on a wrapper that was originally passed ' +
'a context option'
);
}
this.component.setChildContext(context);
return this;
}
/**
* Whether or not a given react element exists in the mount render tree.
*
* Example:
* ```
* const wrapper = mount(<MyComponent />);
* expect(wrapper.contains(<div className="foo bar" />)).to.equal(true);
* ```
*
* @param {ReactElement|Array<ReactElement>} nodeOrNodes
* @returns {Boolean}
*/
contains(nodeOrNodes) {
const predicate = Array.isArray(nodeOrNodes)
? other => containsChildrenSubArray(instEqual, other, nodeOrNodes)
: other => instEqual(nodeOrNodes, other);
return findWhereUnwrapped(this, predicate).length > 0;
}
/**
* Finds every node in the render tree of the current wrapper that matches the provided selector.
*
* @param {String|Function} selector
* @returns {ReactWrapper}
*/
find(selector) {
const predicate = buildInstPredicate(selector);
return findWhereUnwrapped(this, predicate);
}
/**
* Returns whether or not current node matches a provided selector.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @param {String|Function} selector
* @returns {boolean}
*/
is(selector) {
const predicate = buildInstPredicate(selector);
return this.single(n => predicate(n));
}
/**
* Returns a new wrapper instance with only the nodes of the current wrapper instance that match
* the provided predicate function.
*
* @param {Function} predicate
* @returns {ReactWrapper}
*/
filterWhere(predicate) {
return filterWhereUnwrapped(this, n => predicate(this.wrap(n)));
}
/**
* Returns a new wrapper instance with only the nodes of the current wrapper instance that match
* the provided selector.
*
* @param {String|Function} selector
* @returns {ReactWrapper}
*/
filter(selector) {
const predicate = buildInstPredicate(selector);
return filterWhereUnwrapped(this, predicate);
}
/**
* Returns a new wrapper instance with only the nodes of the current wrapper that did not match
* the provided selector. Essentially the inverse of `filter`.
*
* @param {String|Function} selector
* @returns {ReactWrapper}
*/
not(selector) {
const predicate = buildInstPredicate(selector);
return filterWhereUnwrapped(this, n => !predicate(n));
}
/**
* Returns a string of the rendered text of the current render tree. This function should be
* looked at with skepticism if being used to test what the actual HTML output of the component
* will be. If that is what you would like to test, use enzyme's `render` function instead.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @returns {String}
*/
text() {
return this.single(n => findDOMNode(n).textContent);
}
/**
* Returns the HTML of the node.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @returns {String}
*/
html() {
return this.single(n => findDOMNode(n).outerHTML.replace(/\sdata-reactid+="[^"]+"/g, ''));
}
/**
* Returns the current node rendered to HTML and wrapped in a CheerioWrapper.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @returns {CheerioWrapper}
*/
render() {
return cheerio.load(this.html()).root();
}
/**
* Used to simulate events. Pass an eventname and (optionally) event arguments. This method of
* testing events should be met with some skepticism.
*
* @param {String} event
* @param {Array} args
* @returns {ReactWrapper}
*/
simulate(event, ...args) {
this.single(n => {
const mappedEvent = mapNativeEventNames(event);
const eventFn = Simulate[mappedEvent];
if (!eventFn) {
throw new TypeError(`ReactWrapper::simulate() event '${event}' does not exist`);
}
eventFn(findDOMNode(n), ...args);
});
return this;
}
/**
* Returns the props hash for the root node of the wrapper.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @returns {Object}
*/
props() {
return this.single(propsOfNode);
}
/**
* Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it
* will return just that value.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @param {String} name (optional)
* @returns {*}
*/
state(name) {
if (this.root !== this) {
throw new Error('ReactWrapper::state() can only be called on the root');
}
const _state = this.single(() => this.instance().state);
if (name !== undefined) {
return _state[name];
}
return _state;
}
/**
* Returns the context hash for the root node of the wrapper.
* Optionally pass in a prop name and it will return just that value.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @param {String} name (optional)
* @returns {*}
*/
context(name) {
if (this.root !== this) {
throw new Error('ReactWrapper::context() can only be called on the root');
}
const _context = this.single(() => this.instance().context);
if (name !== undefined) {
return _context[name];
}
return _context;
}
/**
* Returns a new wrapper with all of the children of the current wrapper.
*
* @param {String|Function} [selector]
* @returns {ReactWrapper}
*/
children(selector) {
const allChildren = this.flatMap(n => childrenOfInst(n.node));
return selector ? allChildren.filter(selector) : allChildren;
}
/**
* Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node
* in the current wrapper.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @param {String|Function} [selector]
* @returns {ReactWrapper}
*/
parents(selector) {
const allParents = this.wrap(this.single(n => parentsOfInst(n, this.root.node)));
return selector ? allParents.filter(selector) : allParents;
}
/**
* Returns a wrapper around the immediate parent of the current node.
*
* @returns {ReactWrapper}
*/
parent() {
return this.flatMap(n => [n.parents().get(0)]);
}
/**
*
* @param {String|Function} selector
* @returns {ReactWrapper}
*/
closest(selector) {
return this.is(selector) ? this : this.parents().filter(selector).first();
}
/**
* Returns the value of prop with the given name of the root node.
*
* @param {String} propName
* @returns {*}
*/
prop(propName) {
return this.props()[propName];
}
/**
* Returns the type of the root ndoe of this wrapper. If it's a composite component, this will be
* the component constructor. If it's native DOM node, it will be a string.
*
* @returns {String|Function}
*/
type() {
return this.single(n => typeOfNode(getNode(n)));
}
/**
* Returns whether or not the current root node has the given class name or not.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @param {String} className
* @returns {Boolean}
*/
hasClass(className) {
if (className && className.indexOf('.') !== -1) {
console.log(
'It looks like you\'re calling `ReactWrapper::hasClass()` with a CSS selector. ' +
'hasClass() expects a class name, not a CSS selector.'
);
}
return this.single(n => instHasClassName(n, className));
}
/**
* Iterates through each node of the current wrapper and executes the provided function with a
* wrapper around the corresponding node passed in as the first argument.
*
* @param {Function} fn
* @returns {ReactWrapper}
*/
forEach(fn) {
this.nodes.forEach((n, i) => fn.call(this, this.wrap(n), i));
return this;
}
/**
* Maps the current array of nodes to another array. Each node is passed in as a `ReactWrapper`
* to the map function.
*
* @param {Function} fn
* @returns {Array}
*/
map(fn) {
return this.nodes.map((n, i) => fn.call(this, this.wrap(n), i));
}
/**
* Reduces the current array of nodes to another array.
* Each node is passed in as a `ShallowWrapper` to the reducer function.
*
* @param {Function} fn - the reducer function
* @param {*} initialValue - the initial value
* @returns {*}
*/
reduce(fn, initialValue) {
return this.nodes.reduce(
(accum, n, i) => fn.call(this, accum, this.wrap(n), i),
initialValue
);
}
/**
* Reduces the current array of nodes to another array, from right to left. Each node is passed
* in as a `ShallowWrapper` to the reducer function.
*
* @param {Function} fn - the reducer function
* @param {*} initialValue - the initial value
* @returns {*}
*/
reduceRight(fn, initialValue) {
return this.nodes.reduceRight(
(accum, n, i) => fn.call(this, accum, this.wrap(n), i),
initialValue
);
}
/**
* Returns whether or not any of the nodes in the wrapper match the provided selector.
*
* @param {Function|String} selector
* @returns {Boolean}
*/
some(selector) {
const predicate = buildInstPredicate(selector);
return this.nodes.some(predicate);
}
/**
* Returns whether or not any of the nodes in the wrapper pass the provided predicate function.
*
* @param {Function} predicate
* @returns {Boolean}
*/
someWhere(predicate) {
return this.nodes.some((n, i) => predicate.call(this, this.wrap(n), i));
}
/**
* Returns whether or not all of the nodes in the wrapper match the provided selector.
*
* @param {Function|String} selector
* @returns {Boolean}
*/
every(selector) {
const predicate = buildInstPredicate(selector);
return this.nodes.every(predicate);
}
/**
* Returns whether or not any of the nodes in the wrapper pass the provided predicate function.
*
* @param {Function} predicate
* @returns {Boolean}
*/
everyWhere(predicate) {
return this.nodes.every((n, i) => predicate.call(this, this.wrap(n), i));
}
/**
* Utility method used to create new wrappers with a mapping function that returns an array of
* nodes in response to a single node wrapper. The returned wrapper is a single wrapper around
* all of the mapped nodes flattened (and de-duplicated).
*
* @param {Function} fn
* @returns {ReactWrapper}
*/
flatMap(fn) {
const nodes = this.nodes.map((n, i) => fn.call(this, this.wrap(n), i));
const flattened = flatten(nodes, true);
const uniques = unique(flattened);
return this.wrap(uniques);
}
/**
* Finds all nodes in the current wrapper nodes' render trees that match the provided predicate
* function.
*
* @param {Function} predicate
* @returns {ReactWrapper}
*/
findWhere(predicate) {
return findWhereUnwrapped(this, n => predicate(this.wrap(n)));
}
/**
* Returns the node at a given index of the current wrapper.
*
* @param {Number} index
* @returns {ReactElement}
*/
get(index) {
return this.nodes[index];
}
/**
* Returns a wrapper around the node at a given index of the current wrapper.
*
* @param {Number} index
* @returns {ReactWrapper}
*/
at(index) {
return this.wrap(this.nodes[index]);
}
/**
* Returns a wrapper around the first node of the current wrapper.
*
* @returns {ReactWrapper}
*/
first() {
return this.at(0);
}
/**
* Returns a wrapper around the last node of the current wrapper.
*
* @returns {ReactWrapper}
*/
last() {
return this.at(this.length - 1);
}
/**
* Returns true if the current wrapper has no nodes. False otherwise.
*
* @returns {boolean}
*/
isEmpty() {
return this.length === 0;
}
/**
* Utility method that throws an error if the current instance has a length other than one.
* This is primarily used to enforce that certain methods are only run on a wrapper when it is
* wrapping a single node.
*
* @param {Function} fn
* @returns {*}
*/
single(fn) {
if (this.length !== 1) {
throw new Error(
`This method is only meant to be run on single node. ${this.length} found instead.`
);
}
return fn.call(this, this.node);
}
/**
* Helpful utility method to create a new wrapper with the same root as the current wrapper, with
* any nodes passed in as the first parameter automatically wrapped.
*
* @param {ReactWrapper|ReactElement|Array<ReactElement>} node
* @returns {ReactWrapper}
*/
wrap(node) {
if (node instanceof ReactWrapper) {
return node;
}
return new ReactWrapper(node, this.root);
}
/**
* Returns an HTML-like string of the shallow render for debugging purposes.
*
* @returns {String}
*/
debug() {
return debugInsts(this.nodes);
}
/**
* Detaches the react tree from the DOM. Runs `ReactDOM.unmountComponentAtNode()` under the hood.
*
* This method will most commonly be used as a "cleanup" method if you decide to use the
* `attachTo` option in `mount(node, options)`.
*
* The method is intentionally not "fluent" (in that it doesn't return `this`) because you should
* not be doing anything with this wrapper after this method is called.
*/
detach() {
if (this.root !== this) {
throw new Error('ReactWrapper::detach() can only be called on the root');
}
if (!this.options.attachTo) {
throw new Error(
'ReactWrapper::detach() can only be called on when the `attachTo` option was passed into ' +
'`mount()`.'
);
}
unmountComponentAtNode(this.options.attachTo);
}
}
|
app/components/TagsForm/index.js
|
54vanya/ru-for-you-front
|
/**
*
* TagsInput
*
*/
import React from 'react';
import styled from 'styled-components';
import Input from 'components/Input';
import Button from 'components/Button';
const AddButtonWrapper = styled.div`
position:relative;
float: right;
input{
height:42px;
border-bottom-left-radius:0;
border-top-left-radius:0;
font-size:20px;
padding: 0 1em;
}
margin-left:-4px;
`;
const InputWrapper = styled.div`
overflow: hidden;
`;
const TagsForm = ({ value, onChange, onSubmitForm }) =>
(
<form onSubmit={onSubmitForm}>
<AddButtonWrapper>
<Button inputValue="GO" />
</AddButtonWrapper>
<InputWrapper>
<Input
id="username"
type="text"
value={value}
onChange={onChange}
/>
</InputWrapper>
</form>
)
;
TagsForm.propTypes = {
value: React.PropTypes.string,
onChange: React.PropTypes.func.isRequired,
onSubmitForm: React.PropTypes.func.isRequired,
};
export default TagsForm;
|
src/svg-icons/av/repeat.js
|
ichiohta/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvRepeat = (props) => (
<SvgIcon {...props}>
<path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z"/>
</SvgIcon>
);
AvRepeat = pure(AvRepeat);
AvRepeat.displayName = 'AvRepeat';
AvRepeat.muiName = 'SvgIcon';
export default AvRepeat;
|
docs/app/Examples/elements/Button/Groups/index.js
|
vageeshb/Semantic-UI-React
|
import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const ButtonGroupsExamples = () => (
<ExampleSection title='Groups'>
<ComponentExample
title='Group'
description='Buttons can exist together as a group.'
examplePath='elements/Button/Groups/ButtonExampleGroup'
/>
<ComponentExample
title='Icon Group'
description='Button groups can show groups of icons.'
examplePath='elements/Button/Groups/ButtonExampleGroupIcon'
/>
</ExampleSection>
)
export default ButtonGroupsExamples
|
vgdb-frontend/src/components/nav/NavItem.js
|
mattruston/idb
|
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import './NavItem.css';
/* Link or Text item on the nav */
class NavItem extends Component {
static defaultProps = {
bold: false
}
render() {
return (
/* Probably needs to be a router-link or something */
<Link className="nav-item" to={this.props.link}>
<div className={"nav-link " + (this.props.bold ? 'nav-link-bold' : '')}>
{this.props.text}
</div>
</Link>
);
}
}
export default NavItem;
|
addons/storyshots/stories/directly_required/Button.js
|
enjoylife/storybook
|
import PropTypes from 'prop-types';
import React from 'react';
const buttonStyles = {
border: '1px solid #eee',
borderRadius: 3,
backgroundColor: '#FFFFFF',
cursor: 'pointer',
fontSize: 15,
padding: '3px 10px',
margin: 10,
};
const Button = ({ children, onClick }) =>
<button style={buttonStyles} onClick={onClick}>
{children}
</button>;
Button.defaultProps = {
onClick: null,
};
Button.propTypes = {
children: PropTypes.string.isRequired,
onClick: PropTypes.func,
};
export default Button;
|
src/containers/Admin/Chats/Chats.js
|
EncontrAR/backoffice
|
import React, { Component } from 'react';
import ContactList from '../../../components/admin/conversations/contactList';
import chatActions from '../../../redux/chat/actions';
import { connect } from 'react-redux';
const {
indexAllConversations
} = chatActions;
class Chats extends Component {
render() {
return (
<ContactList
conversations={ this.props.conversations }
total_pages={ this.props.total_pages }
total_count={ this.props.total_count }
loadConversations={ (page, itemsPerPage) => { this.props.indexAllConversations(page, itemsPerPage) }}
/>
);
}
}
function mapStateToProps(state) {
const { conversations, total_pages, total_count } = state.Chat;
return {
conversations: conversations,
total_pages: total_pages,
total_count: total_count
};
}
export default connect(mapStateToProps, { indexAllConversations })(Chats);
|
src/js/components/App.js
|
MarcusWasTaken/ArmelloCards
|
import React from 'react'
import Deck from '../containers/Deck'
import DeckList from '../containers/DeckList'
import Filters from '../containers/Filters'
import 'css/app'
const App = () => (
<div className="app clearfix">
<div className="main">
<DeckList />
<Deck />
</div>
<aside className="aside">
<h1>Armello Cards</h1>
<Filters />
{/*<h5>Options</h5>*/}
</aside>
</div>
)
export default App
|
docs/src/pages/premium-themes/onepirate/modules/views/AppForm.js
|
lgollut/material-ui
|
import React from 'react';
import PropTypes from 'prop-types';
import Container from '@material-ui/core/Container';
import Box from '@material-ui/core/Box';
import { withStyles } from '@material-ui/core/styles';
import Paper from '../components/Paper';
const styles = (theme) => ({
root: {
display: 'flex',
backgroundImage: 'url(/static/onepirate/appCurvyLines.png)',
backgroundRepeat: 'no-repeat',
},
paper: {
padding: theme.spacing(4, 3),
[theme.breakpoints.up('md')]: {
padding: theme.spacing(8, 6),
},
},
});
function AppForm(props) {
const { children, classes } = props;
return (
<div className={classes.root}>
<Container maxWidth="sm">
<Box mt={7} mb={12}>
<Paper className={classes.paper}>{children}</Paper>
</Box>
</Container>
</div>
);
}
AppForm.propTypes = {
children: PropTypes.node.isRequired,
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(AppForm);
|
react/features/conference/components/native/ConferenceTimerDisplay.js
|
bgrozev/jitsi-meet
|
// @flow
import React from 'react';
import { Text } from 'react-native';
import styles from './styles';
/**
* Returns native element to be rendered.
*
* @param {string} timerValue - String to display as time.
*
* @returns {ReactElement}
*/
export default function renderConferenceTimer(timerValue: string) {
return (
<Text
numberOfLines = { 4 }
style = { styles.roomTimer }>
{ timerValue }
</Text>
);
}
|
app/components/Settings/ChannelSelector.js
|
TheCbac/MICA-Desktop
|
// @flow
/* **********************************************************
* File: ChannelSelector.js
*
* Brief: React component for choosing which of the sensor
* channels that are active.
*
* Authors: Craig Cheney
*
* 2017.09.12 CC - Document created
*
********************************************************* */
import React, { Component } from 'react';
import { Col, ButtonToolbar, Row } from 'react-bootstrap';
import ToggleButtonGroup from 'react-bootstrap/lib/ToggleButtonGroup';
import ToggleButton from 'react-bootstrap/lib/ToggleButton';
import micaSensorParams from '../../utils/mica/micaSensorParams';
import type { idType } from '../../types/paramTypes';
import type { setSensorChannelsActionT } from '../../types/actionTypes';
type propsType = {
/* parameters */
deviceId: idType,
sensorId: idType,
channels: channelsT,
/* Functions */
setSensorChannels: (
deviceId: idType,
sensorId: idType,
newChannels: number[]
) => setSensorChannelsActionT
};
type stateType = {
channels: number[]
};
/* Get the channels */
function channelIdsFromObj(Obj: channelsT): number[] {
const channelIds = Object.keys(Obj);
const valueArray = [];
for (let i = 0; i < channelIds.length; i++) {
const { active } = Obj[channelIds[i]];
if (active) {
valueArray.push(parseInt(channelIds[i], 10));
}
}
return valueArray;
}
export default class ChannelSelector extends Component<propsType, stateType> {
/* Constructor function */
constructor(props: propsType) {
super(props);
/* Set the default state */
this.state = {
channels: channelIdsFromObj(props.channels)
};
}
/* Return the channels that are available */
getChannels() {
const { channels } = this.props;
const channelIds = Object.keys(channels);
/* Create a button for each channel */
const buttonArray = [];
const numChan = channelIds.length;
for (let i = 0; i < numChan; i++) {
const id = channelIds[i];
/* Create the button */
buttonArray.push((
<ToggleButton key={i.toString()} value={parseInt(id, 10)}>
{channels[id].name}
</ToggleButton>
));
}
return buttonArray;
}
/* Control the state */
onChange = (channels: number[]): void => {
/* Update the state */
this.setState({ channels });
/* Update the stored channels */
const { deviceId, sensorId } = this.props;
/* Get the channels from the props */
this.props.setSensorChannels(deviceId, sensorId, channels);
}
/* At least one channel warning */
channelWarning() {
if (this.state.channels.length < 1) {
const warningText = {
color: 'red',
fontStyle: 'italic'
};
return (
<Col md={8} xs={8}>
<span style={warningText}>At least one channel must be active</span>
</Col>
);
}
}
/* Render function */
render() {
return (
<div>
<ButtonToolbar>
<Col md={4} xs={4}>
<label htmlFor='dataChannels'>Data Channels:</label>
</Col>
{this.channelWarning()}
<Row />
<Col md={12} xs={12}>
<ToggleButtonGroup
bsSize='small'
type='checkbox'
value={this.state.channels}
onChange={this.onChange}
>
{ this.getChannels() }
</ToggleButtonGroup>
</Col>
</ButtonToolbar>
</div>
);
}
}
/* [] - END OF FILE */
|
webapp/app/components/Tr/index.js
|
EIP-SAM/SAM-Solution-Node-js
|
//
// Component <tr></tr>
//
import React from 'react';
/* eslint-disable react/prefer-stateless-function */
export default class Tr extends React.Component {
render() {
const ComponentToRender = this.props.component;
let content = null;
content = this.props.items.map((item, index) => (
<ComponentToRender key={`item-${index}`} object={item} />
));
return (
<tr className={this.props.className}>{content}</tr>
);
}
}
Tr.propTypes = {
component: React.PropTypes.func.isRequired,
className: React.PropTypes.string,
items: React.PropTypes.arrayOf(React.PropTypes.any).isRequired,
};
|
app/js/components/header.js
|
pauloelias/simple-webpack-react
|
import React from 'react';
export default class Header extends React.Component {
render() {
return (
<div>
<p>This is the amazing <b>header</b>.</p>
</div>
)
};
}
|
react-router-webpack-code-splitting/src/app.js
|
LiuuY/code-splitting-demo
|
import React from 'react'
import {BrowserRouter, Link, Route} from 'react-router-dom'
// getComponent is a function that returns a promise for a component
// It will not be called until the first mount
function asyncComponent(getComponent) {
return class AsyncComponent extends React.Component {
static Component = null;
state = { Component: AsyncComponent.Component };
componentWillMount() {
if (!this.state.Component) {
getComponent().then(Component => {
AsyncComponent.Component = Component
this.setState({ Component })
})
}
}
render() {
const { Component } = this.state
if (Component) {
return <Component {...this.props} />
}
return null
}
}
}
const Module1 = asyncComponent(() =>
System.import('./module1').then(module => module.default)
)
const Module2 = asyncComponent(() =>
System.import('./module2').then(module => module.default)
)
const App = () =>
<BrowserRouter>
<div>
<Link to="/module1">module1</Link>
<br />
<Link to="/module2">module2</Link>
<h1>Welcome</h1>
<Route path="/" render={() => <div>Home</div>} />
<Route path="/module1" component={Module1} />
<Route path="/module2" component={Module2} />
</div>
</BrowserRouter>
export default App
|
js/components/loaders/ProgressBar.android.js
|
fahrulrizall/projectuts
|
import React, { Component } from 'react';
import ProgressBar from 'ProgressBarAndroid';
export default class SpinnerNB extends Component {
render() {
return (
<ProgressBar
{...this.prepareRootProps()}
styleAttr="Horizontal"
indeterminate={false}
progress={this.props.progress ? this.props.progress / 100 : 0.5}
color={getColor()}
/>
);
}
}
|
imports/components/Signup.js
|
adderpositive/chat-app
|
/*================================================
Signup
======
- is component for UI architecture
of sign up
@imports - react
================================================ */
// imports
import React from 'react';
const Signup = ({
name,
email,
password,
passwordRepeated,
setName,
setEmail,
setPassword,
setPasswordRepeated,
hangleSignup }) => {
return (
<div className="container log">
<h1>Sign Up</h1>
<div className="row">
<label htmlFor="name">Name:</label>
<input className="u-full-width" type="text" placeholder="Name" id="name" value={name} onChange={setName}/>
</div>
<div className="row">
<label htmlFor="email">E-mail:</label>
<input className="u-full-width" type="email" placeholder="Email" id="email" value={email} onChange={setEmail} required />
</div>
<div className="row">
<label htmlFor="password">Password:</label>
<input className="u-full-width" type="password" placeholder="Password" id="password" value={password} onChange={setPassword}/>
</div>
<div className="row">
<label htmlFor="passwordRepeat">Repeat password:</label>
<input className="u-full-width" type="password" placeholder="Repeat password" id="passwordRepeated" value={passwordRepeated} onChange={setPasswordRepeated}/>
</div>
<div className="row">
<button className="button button-primary u-full-width" onClick={hangleSignup}>Sign up</button>
</div>
</div>
)
}
// export
export default Signup;
|
packages/mineral-ui-icons/src/IconLineWeight.js
|
mineral-ui/mineral-ui
|
/* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconLineWeight(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M3 17h18v-2H3v2zm0 3h18v-1H3v1zm0-7h18v-3H3v3zm0-9v4h18V4H3z"/>
</g>
</Icon>
);
}
IconLineWeight.displayName = 'IconLineWeight';
IconLineWeight.category = 'action';
|
src/svg-icons/av/stop.js
|
andrejunges/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvStop = (props) => (
<SvgIcon {...props}>
<path d="M6 6h12v12H6z"/>
</SvgIcon>
);
AvStop = pure(AvStop);
AvStop.displayName = 'AvStop';
AvStop.muiName = 'SvgIcon';
export default AvStop;
|
src/client/components/TrippianListItemRoundWidget/TrippianListItemRoundWidget.js
|
trippian/trippian
|
import log from '../../log'
import React from 'react'
import {
Link
}
from 'react-router'
const TrippianListItemRoundWidget = ({
name = 'Amanda . Sydney', id, picture = 'lorempixel.com/200/200/people/'
}) => {
return (
<div className="popular-trippians-item text-center">
<Link to={`trippian/${id}`}>
<div className="circle-image">
<img src={picture} alt="" />
</div> <h4> {name} </h4>
</Link>
</div>
)
}
TrippianListItemRoundWidget
.displayName = 'TrippianListItemRoundWidget'
export default TrippianListItemRoundWidget
|
client/common/components/DropdownFilter.js
|
Haaarp/geo
|
import React from 'react';
import { SplitButton, MenuItem } from 'react-bootstrap';
/*
* Props:
* items: Array
* title: String
*/
const DropdownFilter = (props) => (
<div className="guide-dropdown-wrap">
<SplitButton title={props.title} pullLeft className="guide-dropdown-custom">
{props.items ? props.items.map((el, index) => <MenuItem eventKey="{index}">{el}</MenuItem>) : null}
</SplitButton>
</div>
);
export default DropdownFilter;
|
client/views/admin/settings/inputs/ActionSettingInput.js
|
VoiSmart/Rocket.Chat
|
import { Button, Field } from '@rocket.chat/fuselage';
import React from 'react';
import { useMethod } from '../../../../contexts/ServerContext';
import { useToastMessageDispatch } from '../../../../contexts/ToastMessagesContext';
import { useTranslation } from '../../../../contexts/TranslationContext';
function ActionSettingInput({ _id, actionText, value, disabled, sectionChanged }) {
const t = useTranslation();
const dispatchToastMessage = useToastMessageDispatch();
const actionMethod = useMethod(value);
const handleClick = async () => {
try {
const data = await actionMethod();
const args = [data.message].concat(data.params);
dispatchToastMessage({ type: 'success', message: t(...args) });
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
}
};
return (
<>
<Field.Row>
<Button
data-qa-setting-id={_id}
children={t(actionText)}
disabled={disabled || sectionChanged}
primary
onClick={handleClick}
/>
</Field.Row>
{sectionChanged && <Field.Hint>{t('Save_to_enable_this_action')}</Field.Hint>}
</>
);
}
export default ActionSettingInput;
|
src/components/search_bar.js
|
scepticulous/react-video-player
|
import React, { Component } from 'react';
// const SearchBar = () => {
// return <input />;
// };
class SearchBar extends Component{
constructor(props) {
super(props);
this.state = { term: '' };
}
render = () => {
return (
<div className="search-bar">
<input
value={this.state.term}
onChange={event => this.onInputChange(event.target.value) }
/>
</div>
);
}
onInputChange(term){
this.setState({term});
this.props.onSearchTermChange(term);
}
}
export default SearchBar;
|
src/index.js
|
vladpolonskiy/news-feed-react-redux
|
import React from 'react';
import ReactDOM from 'react-dom';
import store from './store';
import {Provider} from 'react-redux';
import {Router, browserHistory} from 'react-router';
import {routes} from './routes';
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory} routes={routes} />
</Provider>,
document.getElementById('root')
);
|
src/layouts/ErrorPage/index.js
|
IntellectionStudio/intellection.kz
|
import React from 'react';
import Page from 'layouts/Page';
import styles from './index.css';
const STATUS_CODE_NOT_FOUND = 404;
const ErrorPage = ({
error = STATUS_CODE_NOT_FOUND,
errorText = 'Page Not Found',
...restProps
}) => {
const pageProps = Page.pickPageProps(restProps);
return (
<Page
{...{
...pageProps,
head: {
...pageProps.head,
hero:
'https://farm8.staticflickr.com/7559/16101654539_bee5151340_k.jpg',
},
}}
>
<div className={styles.container}>
<div className={styles.oops}>{'😱 Oooops!'}</div>
<div className={styles.text}>
<p className={styles.title}>
<strong>{error}</strong> {errorText}
</p>
{error === STATUS_CODE_NOT_FOUND && (
<div>
{'It seems you found a broken link. '}
{'Sorry about that. '}
<br />
{'Do not hesitate to report this page 😁.'}
</div>
)}
</div>
</div>
</Page>
);
};
export default ErrorPage;
|
HomeScreen.js
|
bakin-bacon/app
|
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
} from 'react-native';
import * as Colors from './Colors';
export class HomeScreen extends Component {
static navigationOptions = {
title: "Bakin' Bacon",
};
render() {
return (
<View style={styles.container}>
<Text style={{ textAlign: 'center', color: Colors.primary }}>Home Bacon Screen</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: Colors.backgroundColor,
},
});
|
integration_tests/babel-plugin-jest-hoist/__tests__/integration-test.js
|
blainekasten/jest
|
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails oncall+jsinfra
*/
/* eslint-disable no-useless-concat */
'use strict';
import React from 'react';
import Unmocked from '../__test_modules__/Unmocked';
import Mocked from '../__test_modules__/Mocked';
import a from '../__test_modules__/a';
import b from '../__test_modules__/b';
import c from '../__test_modules__/c';
import d from '../__test_modules__/d';
import e from '../__test_modules__/e';
// These will all be hoisted above imports
jest.unmock('react');
jest.deepUnmock('../__test_modules__/Unmocked');
jest
.unmock('../__test_modules__/c')
.unmock('../__test_modules__/d');
jest.mock('../__test_modules__/e', () => {
if (!global.CALLS) {
global.CALLS = 0;
}
global.CALLS++;
return {
_isMock: true,
fn: () => {
// The `jest.mock` transform will allow require, built-ins and globals.
const path = require('path');
const array = new Array(3);
array[0] = path.sep;
return jest.fn(() => array);
},
};
});
// These will not be hoisted
jest.unmock('../__test_modules__/a').dontMock('../__test_modules__/b');
jest.unmock('../__test_modules__/' + 'c');
jest.dontMock('../__test_modules__/Mocked');
// This must not throw an error
const myObject = {mock: () => {}};
myObject.mock('apple', 27);
describe('babel-plugin-jest-hoist', () => {
it('does not throw during transform', () => {
const object = {};
object.__defineGetter__('foo', () => 'bar');
expect(object.foo).toEqual('bar');
});
it('hoists react unmock call before imports', () => {
expect(typeof React).toEqual('object');
expect(React.isValidElement.mock).toBe(undefined);
});
it('hoists unmocked modules before imports', () => {
expect(Unmocked._isMockFunction).toBe(undefined);
expect((new Unmocked()).isUnmocked).toEqual(true);
expect(c._isMockFunction).toBe(undefined);
expect(c()).toEqual('unmocked');
expect(d._isMockFunction).toBe(undefined);
expect(d()).toEqual('unmocked');
});
it('hoists mock call with 2 arguments', () => {
const path = require('path');
expect(e._isMock).toBe(true);
const mockFn = e.fn();
expect(mockFn()).toEqual([path.sep, undefined, undefined]);
});
it('only executes the module factories once', () => {
jest.resetModules();
global.CALLS = 0;
require('../__test_modules__/e');
expect(global.CALLS).toEqual(1);
require('../__test_modules__/e');
expect(global.CALLS).toEqual(1);
delete global.CALLS;
});
it('does not hoist dontMock calls before imports', () => {
expect(Mocked._isMockFunction).toBe(true);
expect((new Mocked()).isMocked).toEqual(undefined);
expect(a._isMockFunction).toBe(true);
expect(a()).toEqual(undefined);
expect(b._isMockFunction).toBe(true);
expect(b()).toEqual(undefined);
});
it('requires modules that also call jest.mock', () => {
require('../mock-file');
const mock = require('../banana');
expect(mock).toEqual('apple');
});
});
|
src/containers/About.js
|
u-wave/web
|
import React from 'react';
import UwaveContext from '../context/UwaveContext';
import Overlay from '../components/Overlay';
import About from '../components/About';
const {
useContext,
} = React;
function AboutContainer(props) {
const uwave = useContext(UwaveContext);
const component = uwave.getAboutPageComponent() ?? null;
return (
<Overlay direction="top">
<About
{...props}
hasAboutPage={!!component}
render={component}
/>
</Overlay>
);
}
export default AboutContainer;
|
app/components/Footer/index.js
|
jdelatorreitrs/react-boilerplate
|
import React from 'react';
import { FormattedMessage } from 'react-intl';
import A from 'components/A';
import LocaleToggle from 'containers/LocaleToggle';
import Wrapper from './Wrapper';
import messages from './messages';
function Footer() {
return (
<Wrapper>
<section>
<FormattedMessage {...messages.licenseMessage} />
</section>
<section>
<LocaleToggle />
</section>
<section>
<FormattedMessage
{...messages.authorMessage}
values={{
author: <A href="https://twitter.com/mxstbr">Max Stoiber</A>,
}}
/>
</section>
</Wrapper>
);
}
export default Footer;
|
test/ProgressBarSpec.js
|
bvasko/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import ProgressBar from '../src/ProgressBar';
import {shouldWarn} from './helpers';
const getProgressBarNode = wrapper => {
return React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(wrapper, 'progress-bar'));
};
describe('ProgressBar', () => {
it('Should output a progress bar with wrapper', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} />
);
assert.equal(React.findDOMNode(instance).nodeName, 'DIV');
assert.ok(React.findDOMNode(instance).className.match(/\bprogress\b/));
assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar\b/));
assert.equal(getProgressBarNode(instance).getAttribute('role'), 'progressbar');
});
it('Should have the default class', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} bsStyle='default' />
);
assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar-default\b/));
});
it('Should have the primary class', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} bsStyle='primary' />
);
assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar-primary\b/));
});
it('Should have the success class', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} bsStyle='success' />
);
assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar-success\b/));
});
it('Should have the warning class', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} bsStyle='warning' />
);
assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar-warning\b/));
});
it('Should default to min:0, max:100', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar now={5} />
);
let bar = getProgressBarNode(instance);
assert.equal(bar.getAttribute('aria-valuemin'), '0');
assert.equal(bar.getAttribute('aria-valuemax'), '100');
});
it('Should have 0% computed width', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} />
);
assert.equal(getProgressBarNode(instance).style.width, '0%');
});
it('Should have 10% computed width', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={1} />
);
assert.equal(getProgressBarNode(instance).style.width, '10%');
});
it('Should have 100% computed width', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={10} />
);
assert.equal(getProgressBarNode(instance).style.width, '100%');
});
it('Should have 50% computed width with non-zero min', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={1} max={11} now={6} />
);
assert.equal(getProgressBarNode(instance).style.width, '50%');
});
it('Should not have label', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={5} bsStyle='primary' />
);
assert.equal(React.findDOMNode(instance).innerText, '');
});
it('Should have label', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={5} bsStyle='primary'
label='min:%(min)s, max:%(max)s, now:%(now)s, percent:%(percent)s, bsStyle:%(bsStyle)s' />
);
assert.equal(React.findDOMNode(instance).innerText, 'min:0, max:10, now:5, percent:50, bsStyle:primary');
});
it('Should have screen reader only label', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={5} bsStyle='primary' srOnly
label='min:%(min)s, max:%(max)s, now:%(now)s, percent:%(percent)s, bsStyle:%(bsStyle)s' />
);
let srLabel = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'sr-only');
assert.equal(React.findDOMNode(srLabel).innerText, 'min:0, max:10, now:5, percent:50, bsStyle:primary');
});
it('Should have a label that is a React component', () => {
let customLabel = (
<strong className="special-label">My label</strong>
);
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={5} bsStyle='primary' label={customLabel} />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'special-label'));
});
it('Should have screen reader only label that wraps a React component', () => {
let customLabel = (
<strong className="special-label">My label</strong>
);
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={5} bsStyle='primary' label={customLabel} srOnly />
);
let srLabel = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'sr-only');
let component = ReactTestUtils.findRenderedDOMComponentWithClass(srLabel, 'special-label');
assert.ok(component);
});
it('Should show striped bar', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={1} max={11} now={6} striped />
);
assert.ok(React.findDOMNode(instance).firstChild.className.match(/\bprogress-bar-striped\b/));
});
it('Should show animated striped bar', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={1} max={11} now={6} active />
);
const barClassName = React.findDOMNode(instance).firstChild.className;
assert.ok(barClassName.match(/\bprogress-bar-striped\b/));
assert.ok(barClassName.match(/\bactive\b/));
});
it('Should show stacked bars', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar>
<ProgressBar key={1} now={50} />
<ProgressBar key={2} now={30} />
</ProgressBar>
);
let wrapper = React.findDOMNode(instance);
let bar1 = wrapper.firstChild;
let bar2 = wrapper.lastChild;
assert.ok(wrapper.className.match(/\bprogress\b/));
assert.ok(bar1.className.match(/\bprogress-bar\b/));
assert.equal(bar1.style.width, '50%');
assert.ok(bar2.className.match(/\bprogress-bar\b/));
assert.equal(bar2.style.width, '30%');
});
it('Should render active and striped children in stacked bar too', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar>
<ProgressBar active key={1} now={50} />
<ProgressBar striped key={2} now={30} />
</ProgressBar>
);
let wrapper = React.findDOMNode(instance);
let bar1 = wrapper.firstChild;
let bar2 = wrapper.lastChild;
assert.ok(wrapper.className.match(/\bprogress\b/));
assert.ok(bar1.className.match(/\bprogress-bar\b/));
assert.ok(bar1.className.match(/\bactive\b/));
assert.ok(bar1.className.match(/\bprogress-bar-striped\b/));
assert.ok(bar2.className.match(/\bprogress-bar\b/));
assert.ok(bar2.className.match(/\bprogress-bar-striped\b/));
assert.notOk(bar2.className.match(/\bactive\b/));
});
it('allows only ProgressBar in children', () => {
ReactTestUtils.renderIntoDocument(
<ProgressBar>
<ProgressBar key={1} />
<div />
<ProgressBar key={2} />
</ProgressBar>
);
shouldWarn('Failed propType');
});
});
|
examples/PopoverExample.js
|
instea/react-native-popup-menu
|
import {
Menu,
MenuProvider,
MenuOptions,
MenuTrigger,
renderers,
} from 'react-native-popup-menu';
import { Text, View, StyleSheet } from 'react-native';
import React from 'react';
const { Popover } = renderers
const MyPopover = () => (
<Menu renderer={Popover} rendererProps={{ preferredPlacement: 'bottom' }}>
<MenuTrigger style={styles.menuTrigger} >
<Text style={styles.triggerText}>{'\u263A'}</Text>
</MenuTrigger>
<MenuOptions style={styles.menuOptions}>
<Text style={styles.contentText}>Hello world!</Text>
</MenuOptions>
</Menu>
)
const Row = () => (
<View style={styles.row}>
<MyPopover />
<MyPopover />
<MyPopover />
<MyPopover />
<MyPopover />
<MyPopover />
</View>
)
const PopoverExample = () => (
<MenuProvider style={styles.container} customStyles={{ backdrop: styles.backdrop }}>
<Row />
<Row />
<Row />
<Row />
<Row />
<Row />
<Row />
<Row />
</MenuProvider>
);
const styles = StyleSheet.create({
container: {
padding: 10,
flexDirection: 'column',
justifyContent: 'space-between',
backgroundColor: 'rgba(0, 0, 0, 0.05)',
},
row: {
flexDirection: 'row',
justifyContent: 'space-between',
},
backdrop: {
},
menuOptions: {
padding: 50,
},
menuTrigger: {
padding: 5,
},
triggerText: {
fontSize: 20,
},
contentText: {
fontSize: 18,
},
})
export default PopoverExample;
|
src/plugins/position/components/TableEnhancer.js
|
joellanciaux/Griddle
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from '../../../utils/griddleConnect';
import compose from 'recompose/compose';
import mapProps from 'recompose/mapProps';
import getContext from 'recompose/getContext';
import { setScrollPosition } from '../actions';
const Table = OriginalComponent => compose(
getContext({
selectors: PropTypes.object,
}),
connect((state, props) => {
const { tableHeightSelector, tableWidthSelector, rowHeightSelector } = props.selectors;
return {
TableHeight: tableHeightSelector(state),
TableWidth: tableWidthSelector(state),
RowHeight: rowHeightSelector(state),
};
},
{
setScrollPosition,
}
),
mapProps((props) => {
const { selectors, ...restProps } = props;
return restProps;
})
)(class extends Component {
constructor(props, context) {
super(props, context);
this.state = { scrollTop: 0 };
}
render() {
const { TableHeight, TableWidth } = this.props;
const scrollStyle = {
'overflow': TableHeight && TableWidth ? 'scroll' : null,
'overflowY' : TableHeight && !TableWidth ? 'scroll' : null,
'overflowX' : !TableHeight && TableWidth ? 'scroll' : null,
'height': TableHeight ? TableHeight : null,
'width': TableWidth ? TableWidth : null,
'display': 'inline-block'
};
return (
<div ref={(ref) => this._scrollable = ref} style={scrollStyle} onScroll={this._scroll}>
<OriginalComponent {...this.props}/>
</div>
);
}
_scroll = () => {
const { setScrollPosition, RowHeight } = this.props;
const { scrollTop } = this.state;
if (this._scrollable && Math.abs(this._scrollable.scrollTop - scrollTop) >= RowHeight) {
setScrollPosition(
this._scrollable.scrollLeft,
this._scrollable.scrollWidth,
this._scrollable.clientWidth,
this._scrollable.scrollTop,
this._scrollable.scrollHeight,
this._scrollable.clientHeight
);
this.setState({ scrollTop: this._scrollable.scrollTop });
}
}
});
export default Table;
|
src/app/components/AudioEditor.js
|
skratchdot/audio-editor
|
import React, { Component } from 'react';
import { Row, Col, Jumbotron } from 'react-bootstrap';
import { connect } from 'react-redux';
import AudioPlayer from './AudioPlayer';
import WaveformAmplitude from './display/WaveformAmplitude';
import DisplayContainer from './DisplayContainer';
import DisplayMessage from './DisplayMessage';
import DisplayPlaybackPosition from './DisplayPlaybackPosition';
import MonoButtonGroup from './MonoButtonGroup';
import PlayBar from './PlayBar';
import PlaybackPositionSlider from './PlaybackPositionSlider';
import PlaybackRateBar from './PlaybackRateBar';
import PlaybackRateSlider from './PlaybackRateSlider';
import VolumeSlider from './VolumeSlider';
import ZoomBar from './ZoomBar';
import ZoomSlider from './ZoomSlider';
class AudioEditor extends Component {
render() {
const { buffer, mono, playbackType, playbackPosition, zoom } = this.props;
const audioPlayer = playbackType === 0 ? '' : <AudioPlayer />;
const zoomDisplay = [];
if (mono || buffer.length === 0) {
zoomDisplay.push(
<WaveformAmplitude
key="mono"
type="mono"
zoomLevel={1}
start={zoom.start}
end={zoom.end}
/>
);
} else {
for (let i = 0; i < buffer.numberOfChannels; i++) {
if (i > 0) {
zoomDisplay.push(
<div key={`spacer${i}`} style={{
height: 2,
backgroundColor: '#aaa'
}}> </div>
);
}
zoomDisplay.push(
<WaveformAmplitude
key={`channels.${i}`}
type={`channels.${i}`}
zoomLevel={1}
start={zoom.start}
end={zoom.end}
/>
);
}
}
return (
<div>
{audioPlayer}
<Row>
<Col md={6}>
<Jumbotron className="jumbo-control">
<PlayBar />
<VolumeSlider />
</Jumbotron>
</Col>
<Col md={6}>
<Jumbotron className="jumbo-control">
<PlaybackRateBar />
<PlaybackRateSlider />
</Jumbotron>
</Col>
</Row>
<Row>
<Col md={12}>
<DisplayContainer>
<div style={{
height: 200,
display: 'flex',
flexDirection: 'column'
}}>
{zoomDisplay}
</div>
<DisplayPlaybackPosition min={zoom.start} max={zoom.end} />
<DisplayMessage showExtended={true} />
</DisplayContainer>
<PlaybackPositionSlider min={zoom.start} max={zoom.end} />
<Row>
<Col md={6}>
<ZoomBar />
</Col>
<Col md={6} style={{display: 'flex', justifyContent: 'flex-end'}}>
<MonoButtonGroup />
</Col>
</Row>
</Col>
</Row>
<Row>
<Col md={12}>
<DisplayContainer>
<WaveformAmplitude
zoomLevel={1}
start={0}
end={buffer.length - 1}
type="mono"
height={50}
/>
<DisplayPlaybackPosition min={0} max={buffer.length - 1} />
<ZoomSlider />
<DisplayMessage />
</DisplayContainer>
<PlaybackPositionSlider min={0} max={buffer.length - 1} />
<Row>
<Col md={6}>
<small>Position: {Math.round(playbackPosition.position)}</small>
</Col>
<Col md={6}>
</Col>
</Row>
</Col>
</Row>
</div>
);
}
}
export default connect(function (state) {
return {
buffer: state.buffer,
mono: state.mono,
muted: state.muted,
playbackPosition: state.playbackPosition,
playbackType: state.playbackType,
volume: state.volume,
zoom: state.zoom
};
})(AudioEditor);
|
frontend/src/components/common/hoc/tableWithStateInUrl.js
|
unicef/un-partner-portal
|
// eslint-disable-next-line
import React, { Component } from 'react';
import R from 'ramda';
import PropTypes from 'prop-types';
import { browserHistory as history, withRouter } from 'react-router';
import { connect } from 'react-redux';
import {
updateOrder,
calculatePaginatedPage,
updatePageNumberSize,
updatePageNumber,
} from '../../../helpers/apiHelper';
class TableWithStateInUrl extends Component {
constructor(props) {
super(props);
this.state = { page: props.pageNumber || 1, page_size: props.pageSize || 10 };
this.changeSorting = this.changeSorting.bind(this);
this.changePageSize = this.changePageSize.bind(this);
this.changePageNumber = this.changePageNumber.bind(this);
// TODO - move default order to this component
}
componentWillReceiveProps(nextProps) {
const { pathName, query = {} } = nextProps;
if (!query.page || !query.page_size) {
history.push({
pathname: pathName,
query: R.merge(query, { page: this.state.page, page_size: this.state.page_size }),
});
}
}
changePageSize(pageSize) {
const { pageNumber, itemsCount, pathName, query } = this.props;
updatePageNumberSize(calculatePaginatedPage(pageNumber, pageSize, itemsCount),
pageSize, pathName, query);
}
changePageNumber(page) {
const { pathName, query } = this.props;
updatePageNumber(page, pathName, query);
}
changeSorting(sorting) {
const { pathName, query } = this.props;
if (sorting[0].columnName !== 'country_code' && sorting[0].columnName !== 'status') {
const order = sorting[0].columnName === 'specializations' ? 'specializations__name' : sorting[0].columnName;
this.setState({
sorting,
});
const direction = sorting[0].direction === 'desc' ? '-' : '';
updateOrder(order, direction, pathName, query);
}
}
render() {
const { component: WrappedComponent, pageSize, pageNumber, ...other } = this.props;
return (<WrappedComponent
{...other}
allowSorting
sorting={this.state.sorting}
changeSorting={this.changeSorting}
changePageSize={this.changePageSize}
changePageNumber={this.changePageNumber}
pageSize={pageSize}
pageNumber={pageNumber}
/>);
}
}
TableWithStateInUrl.propTypes = {
component: PropTypes.oneOfType([
PropTypes.element,
PropTypes.func,
]),
query: PropTypes.object,
pathName: PropTypes.string,
pageSize: PropTypes.number,
pageNumber: PropTypes.number,
itemsCount: PropTypes.number,
};
const mapStateToProps = (state, {
location: { pathname: pathName, query } = {},
}) => ({
pathName,
query,
pageSize: R.isNil(query.page_size) ? 0 : Number(query.page_size),
pageNumber: R.isNil(query.page) ? 1 : Number(query.page),
});
export default withRouter(connect(mapStateToProps, null)(TableWithStateInUrl));
|
admin/client/App/screens/Item/index.js
|
dvdcastro/keystone
|
/**
* Item View
*
* This is the item view, it is rendered when users visit a page of a specific
* item. This mainly renders the form to edit the item content in.
*/
import React from 'react';
import { Container, Spinner } from 'elemental';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import { listsByKey } from '../../../utils/lists';
import CreateForm from '../../shared/CreateForm';
import EditForm from './components/EditForm';
import EditFormHeader from './components/EditFormHeader';
import RelatedItemsList from './components/RelatedItemsList';
// import FlashMessages from '../../shared/FlashMessages';
import {
selectItem,
loadItemData,
} from './actions';
import {
selectList,
} from '../List/actions';
var ItemView = React.createClass({
displayName: 'ItemView',
contextTypes: {
router: React.PropTypes.object.isRequired,
},
getInitialState () {
return {
createIsOpen: false,
};
},
componentDidMount () {
// When we directly navigate to an item without coming from another client
// side routed page before, we need to select the list before initializing the item
this.props.dispatch(selectList(this.props.params.listId));
this.initializeItem(this.props.params.itemId);
},
componentWillReceiveProps (nextProps) {
// We've opened a new item from the client side routing, so initialize
// again with the new item id
if (nextProps.params.itemId !== this.props.params.itemId) {
this.props.dispatch(selectList(nextProps.params.listId));
this.initializeItem(nextProps.params.itemId);
}
},
// Initialize an item
initializeItem (itemId) {
this.props.dispatch(selectItem(itemId));
this.props.dispatch(loadItemData());
},
// Called when a new item is created
onCreate (item) {
// Hide the create form
this.setState({
createIsOpen: false,
});
// Redirect to newly created item path
const list = this.props.currentList;
this.context.router.push(`${Keystone.adminPath}/${list.path}/${item.id}`);
},
// Open and close the create new item modal
toggleCreate (visible) {
this.setState({
createIsOpen: visible,
});
},
// Render this items relationships
renderRelationships () {
const { relationships } = this.props.currentList;
const keys = Object.keys(relationships);
if (!keys.length) return;
return (
<div className="Relationships">
<Container>
<h2>Relationships</h2>
{keys.map(key => {
const relationship = relationships[key];
const refList = listsByKey[relationship.ref];
return (
<RelatedItemsList
key={relationship.path}
list={this.props.currentList}
refList={refList}
relatedItemId={this.props.params.itemId}
relationship={relationship}
/>
);
})}
</Container>
</div>
);
},
// Handle errors
handleError (error) {
const detail = error.detail;
if (detail) {
// Item not found
if (detail.name === 'CastError'
&& detail.path === '_id') {
return (
<Container>
<p>Item not found!</p>
<Link to={`${Keystone.adminPath}/${this.props.routeParams.listId}`}>
Go to list
</Link>
</Container>
);
}
}
if (error.message) {
// Server down + possibly other errors
if (error.message === 'Internal XMLHttpRequest Error') {
return (
<Container>
<p>We encountered some network problems, please try refreshing!</p>
</Container>
);
}
}
return (<p>Error!</p>);
},
render () {
// If we don't have any data yet, show the loading indicator
if (!this.props.ready) {
return (
<div className="centered-loading-indicator" data-screen-id="item">
<Spinner size="md" />
</div>
);
}
// When we have the data, render the item view with it
return (
<div data-screen-id="item">
{(this.props.error) ? this.handleError(this.props.error) : (
<div>
<Container>
<EditFormHeader
list={this.props.currentList}
data={this.props.data}
toggleCreate={this.toggleCreate}
/>
<CreateForm
list={this.props.currentList}
isOpen={this.state.createIsOpen}
onCancel={() => this.toggleCreate(false)}
onCreate={(item) => this.onCreate(item)}
/>
<EditForm
list={this.props.currentList}
data={this.props.data}
dispatch={this.props.dispatch}
router={this.context.router}
/>
</Container>
{this.renderRelationships()}
</div>
)}
</div>
);
},
});
module.exports = connect((state) => ({
data: state.item.data,
loading: state.item.loading,
ready: state.item.ready,
error: state.item.error,
currentList: state.lists.currentList,
}))(ItemView);
|
src/svg-icons/editor/mode-comment.js
|
tan-jerene/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorModeComment = (props) => (
<SvgIcon {...props}>
<path d="M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18z"/>
</SvgIcon>
);
EditorModeComment = pure(EditorModeComment);
EditorModeComment.displayName = 'EditorModeComment';
EditorModeComment.muiName = 'SvgIcon';
export default EditorModeComment;
|
packages/frint-react-server/src/renderToString.spec.js
|
Travix-International/frint
|
/* eslint-disable import/no-extraneous-dependencies, func-names, react/prop-types */
/* global describe, it */
import React from 'react';
import { expect } from 'chai';
import { createApp } from 'frint';
import { observe, streamProps, Region } from 'frint-react';
import renderToString from './renderToString';
describe('frint-react-server › renderToString', function () {
it('is a function', function () {
expect(renderToString).to.be.a('function');
});
it('returns HTML output of an App instance', function () {
function TestComponent() {
return (
<div>
<p>Hello World!</p>
</div>
);
}
const TestApp = createApp({
name: 'TestAppname',
providers: [
{
name: 'component',
useValue: TestComponent,
},
],
});
const app = new TestApp();
const html = renderToString(app);
expect(html).to.contain('>Hello World!</p></div>');
});
it('returns HTML output of an App instance, with observed props', function () {
function TestComponent({ name }) {
return (
<div>
<p>{name}</p>
</div>
);
}
const ObservedTestComponent = observe(function (app) {
const defaultProps = {
name: app.getName(),
};
return streamProps(defaultProps)
.get$();
})(TestComponent);
const TestApp = createApp({
name: 'TestAppName',
providers: [
{
name: 'component',
useValue: ObservedTestComponent,
},
],
});
const app = new TestApp();
const html = renderToString(app);
expect(html).to.contain('>TestAppName</p></div>');
});
it('returns HTML output of an App instance, with childs Apps', function () {
// root
function RootComponent() {
return (
<div>
<Region name="sidebar" />
</div>
);
}
const RootApp = createApp({
name: 'RootApp',
providers: [
{ name: 'component', useValue: RootComponent },
],
});
// apps
function App1Component() {
return <p>App 1</p>;
}
const App1 = createApp({
name: 'App1',
providers: [
{ name: 'component', useValue: App1Component },
],
});
function App2Component() {
return <p>App 2</p>;
}
const App2 = createApp({
name: 'App2',
providers: [
{ name: 'component', useValue: App2Component },
],
});
// render
const rootApp = new RootApp();
// register apps
rootApp.registerApp(App1, {
regions: ['sidebar'],
weight: 10,
});
rootApp.registerApp(App2, {
regions: ['sidebar2'],
weight: 10,
});
const string = renderToString(rootApp);
// verify
expect(string).to.include('>App 1</p>');
expect(string).not.to.include('>App 2</p>');
});
});
|
docs/src/app/pages/components/Modal/ExampleModalCustomTitle.js
|
GetAmbassador/react-ions
|
import React from 'react'
import Modal from 'react-ions/lib/components/Modal'
import Header from 'react-ions/lib/components/Modal/Header'
import Button from 'react-ions/lib/components/Button'
class ExampleModalCustomTitle extends React.Component {
constructor(props) {
super(props)
this.state = {
open: false
}
}
handleOpen = () => {
this.setState({open: true})
}
handleClose = () => {
this.setState({open: false})
}
handleSubmit = () => {
this.setState({open: false})
}
render() {
const actions = [
<Button onClick={this.handleClose} optClass="inverted">Cancel</Button>,
<Button onClick={this.handleSubmit}>Submit</Button>
]
return (
<div>
<Button onClick={this.handleOpen}>Open Modal</Button>
<Modal
title={
<Header handleClose={this.handleClose}>
<h1>Custom Title</h1>
</Header>
}
open={this.state.open}
onRequestClose={this.handleClose}
actions={actions}
closeOnAction={true}
>
<p>The actions in this window were passed in as an array of React objects.</p>
<p>This modal can only be closed by selecting one of the actions.</p>
</Modal>
</div>
)
}
}
export default ExampleModalCustomTitle
|
docs/app/Examples/addons/Radio/States/index.js
|
Rohanhacker/Semantic-UI-React
|
import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
import { Message } from 'semantic-ui-react'
const RadioStatesExamples = () => (
<ExampleSection title='States'>
<ComponentExample
title='Checked'
description='A radio can come pre-checked.'
examplePath='addons/Radio/States/RadioExampleChecked'
>
<Message>
Use{' '}
<a href='https://facebook.github.io/react/docs/forms.html#default-value' target='_blank'>
<code>defaultChecked</code>
</a>
{' '}as you normally would to set default form values.
</Message>
</ComponentExample>
<ComponentExample
title='Disabled'
description='Radios can be disabled.'
examplePath='addons/Radio/States/RadioExampleDisabled'
/>
<ComponentExample
title='Read Only'
description='Make the radio unable to be edited by the user.'
examplePath='addons/Radio/States/RadioExampleReadOnly'
/>
<ComponentExample
title='Remote Control'
description='You can trigger events remotely.'
examplePath='addons/Radio/States/RadioExampleRemoteControl'
/>
</ExampleSection>
)
export default RadioStatesExamples
|
src/app/components/menuComponents/SettingsMenuItems.js
|
preeminence/react-redux-skeleton
|
import React from 'react';
import Settings from 'material-ui/svg-icons/action/settings';
import MenuListItem from './MenuListItem';
import appActions from '../../appActions';
class SettingsMenuItems extends React.Component {
handleThemeChange() {
this.props.dispatch(appActions.themeChanged());
}
handleToggleSettingsClick() {
this.props.dispatch(appActions.toggleSettings());
}
render() {
const menuItems = [
<MenuListItem
key={1}
toggle
toggleText="Light Theme"
toggleValue={this.props.values.lightTheme}
onToggle={this.handleThemeChange.bind(this)}
/>,
];
return (
<div>
<MenuListItem
primaryText="Settings"
leftIcon={<Settings />}
open={this.props.values.settingsShow}
nestedItems={menuItems}
onClick={this.handleToggleSettingsClick.bind(this)}
/>
</div>);
}
}
export default SettingsMenuItems;
|
examples/draft-0-10-0/tex/js/components/TeXEditorExample.js
|
tonygentilcore/draft-js
|
/**
* Copyright (c) 2013-present, Facebook, Inc. All rights reserved.
*
* This file provided by Facebook is for non-commercial testing and evaluation
* purposes only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
'use strict';
import Draft from 'draft-js';
import {Map} from 'immutable';
import React from 'react';
import TeXBlock from './TeXBlock';
import {content} from '../data/content';
import {insertTeXBlock} from '../modifiers/insertTeXBlock';
import {removeTeXBlock} from '../modifiers/removeTeXBlock';
var {Editor, EditorState, RichUtils} = Draft;
export default class TeXEditorExample extends React.Component {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createWithContent(content),
liveTeXEdits: Map(),
};
this._blockRenderer = (block) => {
if (block.getType() === 'atomic') {
return {
component: TeXBlock,
editable: false,
props: {
onStartEdit: (blockKey) => {
var {liveTeXEdits} = this.state;
this.setState({liveTeXEdits: liveTeXEdits.set(blockKey, true)});
},
onFinishEdit: (blockKey, newContentState) => {
var {liveTeXEdits} = this.state;
this.setState({
liveTeXEdits: liveTeXEdits.remove(blockKey),
editorState:EditorState.createWithContent(newContentState),
});
},
onRemove: (blockKey) => this._removeTeX(blockKey),
},
};
}
return null;
};
this._focus = () => this.refs.editor.focus();
this._onChange = (editorState) => this.setState({editorState});
this._handleKeyCommand = command => {
var {editorState} = this.state;
var newState = RichUtils.handleKeyCommand(editorState, command);
if (newState) {
this._onChange(newState);
return true;
}
return false;
};
this._removeTeX = (blockKey) => {
var {editorState, liveTeXEdits} = this.state;
this.setState({
liveTeXEdits: liveTeXEdits.remove(blockKey),
editorState: removeTeXBlock(editorState, blockKey),
});
};
this._insertTeX = () => {
this.setState({
liveTeXEdits: Map(),
editorState: insertTeXBlock(this.state.editorState),
});
};
}
/**
* While editing TeX, set the Draft editor to read-only. This allows us to
* have a textarea within the DOM.
*/
render() {
return (
<div className="TexEditor-container">
<div className="TeXEditor-root">
<div className="TeXEditor-editor" onClick={this._focus}>
<Editor
blockRendererFn={this._blockRenderer}
editorState={this.state.editorState}
handleKeyCommand={this._handleKeyCommand}
onChange={this._onChange}
placeholder="Start a document..."
readOnly={this.state.liveTeXEdits.count()}
ref="editor"
spellCheck={true}
/>
</div>
</div>
<button onClick={this._insertTeX} className="TeXEditor-insert">
{'Insert new TeX'}
</button>
</div>
);
}
}
|
client/components/AltFooter/index.js
|
Elektro1776/Project_3
|
import React, { Component } from 'react';
import { Button } from 'react-toolbox/lib/button';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
class AltFooter extends Component {
constructor() {
super();
this.state = {
};
}
render() {
const styles = {
basic: {
width: '100vw',
background: '#545454',
height: '50px',
bottom: '0',
position: 'fixed',
color: 'white',
textAlign: 'center',
lineHeight: '44px',
},
};
return (
<div style={styles.basic}>
<p>ⒸCopyright 2017 uTile</p>
</div>
);
}
}
export default AltFooter;
|
test/app/components/TodoItem.spec.js
|
atixlabs/TrelloDescriptionChangelog
|
// /*import { expect } from 'chai';
// import sinon from 'sinon';
// import React from 'react';
// import TestUtils from 'react-addons-test-utils';
// import TodoItem from '../../../app/components/TodoItem';
// import style from '../../../app/components/TodoItem.css';
// import TodoTextInput from '../../../app/components/TodoTextInput';*/
// function setup(editing = false) {
// const props = {
// todo: {
// id: 0,
// text: 'Use Redux',
// completed: false
// },
// editTodo: sinon.spy(),
// deleteTodo: sinon.spy(),
// completeTodo: sinon.spy()
// };
// const renderer = TestUtils.createRenderer();
// renderer.render(<TodoItem {...props} />);
// let output = renderer.getRenderOutput();
// if (editing) {
// const label = output.props.children.props.children[1];
// label.props.onDoubleClick({});
// output = renderer.getRenderOutput();
// }
// return { props, output, renderer };
// }
// describe.skip('todoapp TodoItem component', () => {
// it('should render correctly', () => {
// const { output } = setup();
// expect(output.type).to.equal('li');
// expect(output.props.className).to.equal(style.normal);
// const div = output.props.children;
// expect(div.type).to.equal('div');
// expect(div.props.className).to.equal(style.view);
// const [input, label, button] = div.props.children;
// expect(input.type).to.equal('input');
// expect(input.props.checked).to.equal(false);
// expect(label.type).to.equal('label');
// expect(label.props.children).to.equal('Use Redux');
// expect(button.type).to.equal('button');
// expect(button.props.className).to.equal(style.destroy);
// });
// it('input onChange should call completeTodo', () => {
// const { output, props } = setup();
// const input = output.props.children.props.children[0];
// input.props.onChange({});
// expect(props.completeTodo.calledWith(0)).to.equal(true);
// });
// it('button onClick should call deleteTodo', () => {
// const { output, props } = setup();
// const button = output.props.children.props.children[2];
// button.props.onClick({});
// expect(props.deleteTodo.calledWith(0)).to.equal(true);
// });
// it('label onDoubleClick should put component in edit state', () => {
// const { output, renderer } = setup();
// const label = output.props.children.props.children[1];
// label.props.onDoubleClick({});
// const updated = renderer.getRenderOutput();
// expect(updated.type).to.equal('li');
// expect(updated.props.className).to.equal(style.editing);
// });
// it('edit state render', () => {
// const { output } = setup(true);
// expect(output.type).to.equal('li');
// expect(output.props.className).to.equal(style.editing);
// const input = output.props.children;
// expect(input.type).to.equal(TodoTextInput);
// expect(input.props.text).to.equal('Use Redux');
// expect(input.props.editing).to.equal(true);
// });
// it('TodoTextInput onSave should call editTodo', () => {
// const { output, props } = setup(true);
// output.props.children.props.onSave('Use Redux');
// expect(props.editTodo.calledWith(0, 'Use Redux')).to.equal(true);
// });
// it('TodoTextInput onSave should call deleteTodo if text is empty', () => {
// const { output, props } = setup(true);
// output.props.children.props.onSave('');
// expect(props.deleteTodo.calledWith(0)).to.equal(true);
// });
// it('TodoTextInput onSave should exit component from edit state', () => {
// const { output, renderer } = setup(true);
// output.props.children.props.onSave('Use Redux');
// const updated = renderer.getRenderOutput();
// expect(updated.type).to.equal('li');
// expect(updated.props.className).to.equal(style.normal);
// });
// });
|
src/browser/users/UsersPage.js
|
reedlaw/read-it
|
// @flow
import OnlineUsers from './OnlineUsers';
import React from 'react';
import linksMessages from '../../common/app/linksMessages';
import { Box, PageHeader } from '../../common/components';
import { Title } from '../components';
const UsersPage = () => (
<Box>
<Title message={linksMessages.users} />
<PageHeader heading="Users" description="Online users" />
<OnlineUsers />
</Box>
);
export default UsersPage;
|
src/toolbar/SearchField.js
|
prajapati-parth/react-bootstrap-table
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
class SearchField extends Component {
getValue() {
return ReactDOM.findDOMNode(this).value;
}
setValue(value) {
ReactDOM.findDOMNode(this).value = value;
}
render() {
const {
className,
defaultValue,
placeholder,
onKeyUp,
...rest
} = this.props;
return (
<input
className={ `form-control ${className}` }
type='text'
defaultValue={ defaultValue }
placeholder={ placeholder || SearchField.defaultProps.placeholder }
onKeyUp={ onKeyUp }
style={ { zIndex: 0 } }
{ ...rest }/>
);
}
}
SearchField.propTypes = {
className: PropTypes.string,
defaultValue: PropTypes.string,
placeholder: PropTypes.string,
onKeyUp: PropTypes.func
};
SearchField.defaultProps = {
className: '',
defaultValue: '',
placeholder: 'Search',
onKeyUp: undefined
};
export default SearchField;
|
src/app/components/blocks/_copyright.js
|
maullerz/eve-react
|
import React from 'react'
const _copyright = ({info}) => {
return <div className='row'>
<div className='col-md-12'>
<div className='grayback t-small'>
<div className="row">
<div className="col-md-9 col-first">
EVE Online and the EVE logo are the registered trademarks of CCP hf.
All rights are reserved worldwide.
All other trademarks are the property of their respective owners.
EVE Online, the EVE logo, EVE and all associated logos and designs are the intellectual property of CCP
hf.
All artwork, screenshots, characters, vehicles, storylines, world facts or other recognizable features
of the intellectual property relating to these trademarks are likewise the intellectual property of CCP
hf.
CCP hf. has granted permission to EVE-Prod to use EVE Online and all associated logos and designs for
promotional and information purposes on its website but does not endorse, and is not in any way affiliated
with,
EVE-Prod. CCP is in no way responsible for the content on or functioning of this website,
nor can it be liable for any damage arising from the use of this website.
</div>
<div className="col-md-3 col-last">
Version: <a target="_blank" href={info.repo_url}>{info.message}</a><br />
Online: <span className="txt-yellow">{info.eve_online}</span><br />
Latest Update: <span className="txt-lime">{info.updated_at}</span><br />
EVE Time: <span className="txt-lime">{info.eve_time}</span><br />
Have idea? <a target="_blank" href="https://github.com/mazahell/eve-react">Fork me on Github</a><br />
</div>
</div>
</div>
</div>
</div>
}
export default _copyright
|
electron/app/components/PlusButton.js
|
zindlerb/motif
|
import React from 'react';
import classname from 'classname';
function PlusButton(props) {
return (
<i
onClick={props.onClick}
className={classnames("fa fa-plus-circle", props.className)}
aria-hidden="true"
/>
);
}
export default PlusButton;
|
src/lib/plugins/hostname.js
|
Hyperline/hyperline
|
import os from 'os'
import React from 'react'
import Component from 'hyper/component'
import SvgIcon from '../utils/svg-icon'
class PluginIcon extends Component {
render() {
return (
<SvgIcon>
<g fill="none" fillRule="evenodd">
<g
className="hostname-icon"
transform="translate(1.000000, 1.000000)"
>
<path d="M2,0 L12,0 L12,8 L2,8 L2,0 Z M4,2 L10,2 L10,6 L4,6 L4,2 Z M5.5,11 L8.5,11 L8.5,14 L5.5,14 L5.5,11 Z M11,11 L14,11 L14,14 L11,14 L11,11 Z M0,11 L3,11 L3,14 L0,14 L0,11 Z M6.5,10 L7.5,10 L7.5,11 L6.5,11 L6.5,10 Z M12,10 L13,10 L13,11 L12,11 L12,10 Z M1,10 L2,10 L2,11 L1,11 L1,10 Z M1,9 L13,9 L13,10 L1,10 L1,9 Z M6.5,8 L7.5,8 L7.5,9 L6.5,9 L6.5,8 Z" />
</g>
</g>
<style jsx>{`
.hostname-icon {
fill: #fff;
}
`}</style>
</SvgIcon>
)
}
}
export default class HostName extends Component {
static displayName() {
return 'hostname'
}
render() {
const hostname = os.hostname()
const username = process.env.USER
return (
<div className="wrapper">
<PluginIcon /> <span>{username}@</span>
{hostname}
<style jsx>{`
.wrapper {
display: flex;
align-items: center;
}
`}</style>
</div>
)
}
}
|
tests/unit/autoComplete/autoComplete.handleItemMouseDown.spec.js
|
Travix-International/travix-ui-kit
|
import React from 'react';
import { shallow } from 'enzyme';
import AutoComplete from '../../../components/autoComplete/autoComplete';
import AutoCompleteItem from '../../../components/autoComplete/autoCompleteItem';
describe('AutoComplete: handleItemMouseDown', () => {
it('should call passed preventDefault', () => {
const e = {
preventDefault: jest.fn(),
};
const component = shallow(
<AutoComplete
name="autocomplete"
>
<AutoCompleteItem
value="value"
>
item
</AutoCompleteItem>
</AutoComplete>
);
component.instance().handleItemMouseDown(e);
expect(e.preventDefault).toBeCalled();
});
});
|
client/extensions/woocommerce/woocommerce-services/views/shipping-label/label-purchase-modal/packages-step/add-item.js
|
Automattic/woocommerce-services
|
/** @format */
/**
* External dependencies
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { localize } from 'i18n-calypso';
import { includes, size, some } from 'lodash';
import { CheckboxControl } from '@wordpress/components';
/**
* Internal dependencies
*/
import Dialog from 'components/dialog';
import FormLabel from 'components/forms/form-label';
import getPackageDescriptions from './get-package-descriptions';
import FormSectionHeading from 'components/forms/form-section-heading';
import {
closeAddItem,
setAddedItem,
addItems,
} from 'woocommerce/woocommerce-services/state/shipping-label/actions';
import { getShippingLabel } from 'woocommerce/woocommerce-services/state/shipping-label/selectors';
import { getAllPackageDefinitions } from 'woocommerce/woocommerce-services/state/packages/selectors';
const AddItemDialog = props => {
const {
siteId,
orderId,
showAddItemDialog,
addedItems,
openedPackageId,
selected,
all,
translate,
} = props;
if ( ! showAddItemDialog ) {
return null;
}
const packageLabels = getPackageDescriptions( selected, all, true );
const getPackageNameElement = pckgId => {
return <span className="packages-step__dialog-package-name">{ packageLabels[ pckgId ] }</span>;
};
const renderCheckbox = ( pckgId, itemIdx, item ) => {
const itemLabel = packageLabels[ pckgId ]
? translate( '%(item)s from {{pckg/}}', {
args: { item: item.name },
components: { pckg: getPackageNameElement( pckgId ) },
} )
: item;
const onChange = ( state ) => {
props.setAddedItem( orderId, siteId, pckgId, itemIdx, state );
}
return (
<FormLabel
key={ `${ pckgId }-${ itemIdx }` }
className="packages-step__dialog-package-option"
>
<CheckboxControl label={ itemLabel } className="form-label packages-step__dialog-package-option" checked={ includes( addedItems[ pckgId ], itemIdx ) } onChange={ onChange } />
</FormLabel>
);
};
const itemOptions = [];
Object.keys( selected ).forEach( pckgId => {
if ( pckgId === openedPackageId ) {
return;
}
let itemIdx = 0;
selected[ pckgId ].items.forEach( item => {
itemOptions.push( renderCheckbox( pckgId, itemIdx, item ) );
itemIdx++;
} );
} );
const onClose = () => props.closeAddItem( orderId, siteId );
const buttons = [
{ action: 'close', label: translate( 'Close' ), onClick: onClose },
{
action: 'add',
label: translate( 'Add' ),
isPrimary: true,
disabled: ! some( addedItems, size ),
onClick: () => props.addItems( orderId, siteId, openedPackageId ),
},
];
return (
<Dialog
isVisible={ showAddItemDialog }
isFullScreen={ false }
onClickOutside={ onClose }
onClose={ onClose }
buttons={ buttons }
additionalClassNames="wcc-root woocommerce packages-step__dialog"
>
<FormSectionHeading>{ translate( 'Add item' ) }</FormSectionHeading>
<div className="packages-step__dialog-body">
<p>
{ translate( 'Which items would you like to add to {{pckg/}}?', {
components: {
pckg: getPackageNameElement( openedPackageId ),
},
} ) }
</p>
{ itemOptions }
</div>
</Dialog>
);
};
AddItemDialog.propTypes = {
siteId: PropTypes.number.isRequired,
orderId: PropTypes.number.isRequired,
showAddItemDialog: PropTypes.bool.isRequired,
addedItems: PropTypes.object,
openedPackageId: PropTypes.string.isRequired,
selected: PropTypes.object.isRequired,
all: PropTypes.object.isRequired,
closeAddItem: PropTypes.func.isRequired,
setAddedItem: PropTypes.func.isRequired,
addItems: PropTypes.func.isRequired,
};
const mapStateToProps = ( state, { orderId, siteId } ) => {
const shippingLabel = getShippingLabel( state, orderId, siteId );
return {
showAddItemDialog: Boolean( shippingLabel.showAddItemDialog ),
addedItems: shippingLabel.addedItems,
openedPackageId: shippingLabel.openedPackageId,
selected: shippingLabel.form.packages.selected,
all: getAllPackageDefinitions( state, siteId ),
};
};
const mapDispatchToProps = dispatch => {
return bindActionCreators( { closeAddItem, setAddedItem, addItems }, dispatch );
};
export default connect(
mapStateToProps,
mapDispatchToProps
)( localize( AddItemDialog ) );
|
src/components/SettingsPage.js
|
guilhermehn/all-mangas-reader
|
import React from 'react'
import SettingsStore from '../stores/SettingsStore'
import SettingsAPI from '../apis/SettingsAPI'
import { SETTINGS_SECTIONS } from '../constants/SettingsConstants'
import SettingsHolder from './settings/SettingsHolder'
import MigrationNotice from './settings/MigrationNotice'
import SettingsContent from './settings/SettingsContent'
function getStateFromStores() {
return {
settings: SettingsStore.getSettings()
}
}
function dismissMigration() {
SettingsAPI.setOption('dismissMigration', true)
}
const SettingsPage = React.createClass({
getInitialState() {
return getStateFromStores()
},
componentDidMount() {
SettingsAPI.loadSettings()
SettingsStore.addChangeListener(this._onChange)
},
componentWillUnmount() {
SettingsStore.removeChangeListener(this._onChange)
},
_onChange() {
this.setState(getStateFromStores())
},
componentDidUpdate() {
// When changing the sync option, the user
// must be remembered about migrating the
// old data if not already migrated
},
getSettingsValue(key) {
return this.state.settings[key]
},
render() {
let settings = this.state.settings
if (Object.keys(settings).length === 0) {
// This should return a loader view
return (
<SettingsHolder>
<h3>Loading settings...</h3>
</SettingsHolder>
)
}
let shouldShowMigrationNotice = settings.syncData && !settings.dismissMigration
return (
<SettingsHolder>
{ shouldShowMigrationNotice && <MigrationNotice onDismiss={ dismissMigration } /> }
<SettingsContent sections={ SETTINGS_SECTIONS } settings={ settings } />
</SettingsHolder>
)
}
})
export default SettingsPage
|
services/web/src/index.js
|
ojedarob/tennis-buddy
|
import React from 'react'
import { render } from 'react-dom'
import { createStore, dispatch, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import logger from 'redux-logger'
import { Provider } from 'react-redux'
import App from './containers/App'
import reducer from './reducers/reducer'
const middleware = [ thunk, logger ]
const store = createStore(reducer, applyMiddleware(...middleware))
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
src/containers/Accounts/ResetPassword/Complete/index.js
|
westoncolemanl/tabbr-web
|
import React from 'react'
import Link from 'react-router-dom/Link'
import Card, {
CardActions,
CardContent
} from 'material-ui/Card'
import Typography from 'material-ui/Typography'
import Button from 'material-ui/Button'
import { CardLogoHeader } from 'components'
export default () =>
<Card
raised
>
<CardLogoHeader />
<CardContent>
<Typography
variant={'headline'}
gutterBottom
>
{'Password reset complete'}
</Typography>
</CardContent>
<CardActions
className={'flex flex-row justify-end'}
>
<Button
component={Link}
to={'/accounts/sign-in'}
children={'NEXT'}
color={'primary'}
variant={'raised'}
/>
</CardActions>
</Card>
|
examples/js/app.js
|
echaouchna/react-bootstrap-tab
|
import React from 'react';
import ReactDOM from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import { IndexRoute, Router, Route, hashHistory } from 'react-router';
import App from './components/App';
import Home from './components/Home';
import GettingStarted from './components/GettingStarted';
import PageNotFound from './components/PageNotFound';
import Basic from './basic/demo';
import Column from './column/demo';
import Sort from './sort/demo';
import ColumnFormat from './column-format/demo';
import ColumnFilter from './column-filter/demo';
import Selection from './selection/demo';
import Pagination from './pagination/demo';
import Manipulation from './manipulation/demo';
import CellEdit from './cell-edit/demo';
import Style from './style/demo';
import Advance from './advance/demo';
import Other from './others/demo';
import Complex from './complex/demo';
import Remote from './remote/demo';
import Expand from './expandRow/demo';
import Custom from './custom/demo';
import Span from './column-header-span/demo';
import KeyBoardNav from './keyboard-nav/demo';
const renderApp = () => {
ReactDOM.render(
<AppContainer>
<Router history={ hashHistory }>
<Route path='/' component={ App }>
<IndexRoute component={ Home } />
<Route path='getting-started' component={ GettingStarted }/>
<Route path='examples'>
<Route path='basic' component={ Basic } />
<Route path='column' component={ Column } />
<Route path='sort' component={ Sort } />
<Route path='column-format' component={ ColumnFormat } />
<Route path='column-filter' component={ ColumnFilter } />
<Route path='column-header-span' component={ Span } />
<Route path='selection' component={ Selection } />
<Route path='pagination' component={ Pagination } />
<Route path='manipulation' component={ Manipulation } />
<Route path='cell-edit' component={ CellEdit } />
<Route path='style' component={ Style } />
<Route path='advance' component={ Advance } />
<Route path='others' component={ Other } />
<Route path='complex' component={ Complex } />
<Route path='remote' component={ Remote } />
<Route path='custom' component={ Custom } />
<Route path='expandRow' component={ Expand } />
<Route path='keyboard-nav' component={ KeyBoardNav } />
</Route>
<Route path='*' component={ PageNotFound }/>
</Route>
</Router>
</AppContainer>, document.querySelector('#root'));
};
if (module.hot) {
module.hot.accept('./app', renderApp);
}
renderApp();
|
app/javascript/mastodon/components/status_content.js
|
Arukas/mastodon
|
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { isRtl } from '../rtl';
import { FormattedMessage } from 'react-intl';
import Permalink from './permalink';
import classnames from 'classnames';
export default class StatusContent extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
expanded: PropTypes.bool,
onExpandedToggle: PropTypes.func,
onClick: PropTypes.func,
};
state = {
hidden: true,
};
_updateStatusLinks () {
const node = this.node;
const links = node.querySelectorAll('a');
for (var i = 0; i < links.length; ++i) {
let link = links[i];
if (link.classList.contains('status-link')) {
continue;
}
link.classList.add('status-link');
let mention = this.props.status.get('mentions').find(item => link.href === item.get('url'));
if (mention) {
link.addEventListener('click', this.onMentionClick.bind(this, mention), false);
link.setAttribute('title', mention.get('acct'));
} else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) {
link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false);
} else {
link.setAttribute('title', link.href);
}
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener');
}
}
componentDidMount () {
this._updateStatusLinks();
}
componentDidUpdate () {
this._updateStatusLinks();
}
onMentionClick = (mention, e) => {
if (this.context.router && e.button === 0) {
e.preventDefault();
this.context.router.history.push(`/accounts/${mention.get('id')}`);
}
}
onHashtagClick = (hashtag, e) => {
hashtag = hashtag.replace(/^#/, '').toLowerCase();
if (this.context.router && e.button === 0) {
e.preventDefault();
this.context.router.history.push(`/timelines/tag/${hashtag}`);
}
}
handleMouseDown = (e) => {
this.startXY = [e.clientX, e.clientY];
}
handleMouseUp = (e) => {
if (!this.startXY) {
return;
}
const [ startX, startY ] = this.startXY;
const [ deltaX, deltaY ] = [Math.abs(e.clientX - startX), Math.abs(e.clientY - startY)];
if (e.target.localName === 'button' || e.target.localName === 'a' || (e.target.parentNode && (e.target.parentNode.localName === 'button' || e.target.parentNode.localName === 'a'))) {
return;
}
if (deltaX + deltaY < 5 && e.button === 0 && this.props.onClick) {
this.props.onClick();
}
this.startXY = null;
}
handleSpoilerClick = (e) => {
e.preventDefault();
if (this.props.onExpandedToggle) {
// The parent manages the state
this.props.onExpandedToggle();
} else {
this.setState({ hidden: !this.state.hidden });
}
}
setRef = (c) => {
this.node = c;
}
render () {
const { status } = this.props;
const hidden = this.props.onExpandedToggle ? !this.props.expanded : this.state.hidden;
const content = { __html: status.get('contentHtml') };
const spoilerContent = { __html: status.get('spoilerHtml') };
const directionStyle = { direction: 'ltr' };
const classNames = classnames('status__content', {
'status__content--with-action': this.props.onClick && this.context.router,
'status__content--with-spoiler': status.get('spoiler_text').length > 0,
});
if (isRtl(status.get('search_index'))) {
directionStyle.direction = 'rtl';
}
if (status.get('spoiler_text').length > 0) {
let mentionsPlaceholder = '';
const mentionLinks = status.get('mentions').map(item => (
<Permalink to={`/accounts/${item.get('id')}`} href={item.get('url')} key={item.get('id')} className='mention'>
@<span>{item.get('username')}</span>
</Permalink>
)).reduce((aggregate, item) => [...aggregate, item, ' '], []);
const toggleText = hidden ? <FormattedMessage id='status.show_more' defaultMessage='Show more' /> : <FormattedMessage id='status.show_less' defaultMessage='Show less' />;
if (hidden) {
mentionsPlaceholder = <div>{mentionLinks}</div>;
}
return (
<div className={classNames} ref={this.setRef} tabIndex='0' onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp}>
<p style={{ marginBottom: hidden && status.get('mentions').isEmpty() ? '0px' : null }}>
<span dangerouslySetInnerHTML={spoilerContent} />
{' '}
<button tabIndex='0' className='status__content__spoiler-link' onClick={this.handleSpoilerClick}>{toggleText}</button>
</p>
{mentionsPlaceholder}
<div tabIndex={!hidden ? 0 : null} className={`status__content__text ${!hidden ? 'status__content__text--visible' : ''}`} style={directionStyle} dangerouslySetInnerHTML={content} />
</div>
);
} else if (this.props.onClick) {
return (
<div
ref={this.setRef}
tabIndex='0'
className={classNames}
style={directionStyle}
onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMouseUp}
dangerouslySetInnerHTML={content}
/>
);
} else {
return (
<div
tabIndex='0'
ref={this.setRef}
className='status__content'
style={directionStyle}
dangerouslySetInnerHTML={content}
/>
);
}
}
}
|
client/src/MyJobsButton.js
|
roxroy/codeploy
|
import React, { Component } from 'react';
class MyJobsButton extends Component {
constructor(props) {
super(props);
this.viewJobs = this.viewJobs.bind(this);
}
viewJobs() {
this.props.closeResourceModal();
this.props.viewJobs();
}
render(){
return(
<div>
<button className="modal-button" onClick={this.viewJobs}>My Jobs</button>
</div>
);
}
}
module.exports = MyJobsButton;
|
src/templates/category-template.js
|
wall3/wall3.github.io
|
// @flow strict
import React from 'react';
import { graphql } from 'gatsby';
import Layout from '../components/Layout';
import Sidebar from '../components/Sidebar';
import Feed from '../components/Feed';
import Page from '../components/Page';
import Pagination from '../components/Pagination';
import { useSiteMetadata } from '../hooks';
import type { PageContext, AllMarkdownRemark } from '../types';
type Props = {
data: AllMarkdownRemark,
pageContext: PageContext
};
const CategoryTemplate = ({ data, pageContext }: Props) => {
const { title: siteTitle, subtitle: siteSubtitle } = useSiteMetadata();
const {
category,
currentPage,
prevPagePath,
nextPagePath,
hasPrevPage,
hasNextPage,
} = pageContext;
const { edges } = data.allMarkdownRemark;
const pageTitle = currentPage > 0 ? `${category} - Page ${currentPage} - ${siteTitle}` : `${category} - ${siteTitle}`;
return (
<Layout title={pageTitle} description={siteSubtitle}>
<Sidebar />
<Page title={category}>
<Feed edges={edges} />
<Pagination
prevPagePath={prevPagePath}
nextPagePath={nextPagePath}
hasPrevPage={hasPrevPage}
hasNextPage={hasNextPage}
/>
</Page>
</Layout>
);
};
export const query = graphql`
query CategoryPage($category: String, $postsLimit: Int!, $postsOffset: Int!) {
allMarkdownRemark(
limit: $postsLimit,
skip: $postsOffset,
filter: { frontmatter: { category: { eq: $category }, template: { eq: "post" }, draft: { ne: true } } },
sort: { order: DESC, fields: [frontmatter___date] }
){
edges {
node {
fields {
categorySlug
slug
}
frontmatter {
date
description
category
title
}
}
}
}
}
`;
export default CategoryTemplate;
|
src/controls/filefield/preview.js
|
thinktopography/reframe
|
import ImageFileToken from './image_file_token'
import PlainFileToken from './plain_file_token'
import PropTypes from 'prop-types'
import React from 'react'
import qs from 'qs'
class Preview extends React.Component {
static propTypes = {
file: PropTypes.object,
preview: PropTypes.string,
onRemove: PropTypes.func
}
render() {
const dpis = [1,2]
const { file } = this.props
const content_type = file.contentType || file.asset.content_type
const isImage = (content_type.split('/')[0] === 'image')
const type = isImage ? 'image' : 'plain'
return (
<div className={`reframe-filefield-token ${type}`}>
{ file.status === 'added' &&
<div className="reframe-filefield-progress">
<div className="ui green progress">
<div className="bar" style={{ width: 0 }} />
</div>
</div>
}
{ file.status === 'uploading' &&
<div className="reframe-filefield-progress">
<div className="ui green progress">
<div className="bar" style={{ width: `${file.progress}%`}}>
<div className="progress">{ file.progress }%</div>
</div>
</div>
</div>
}
<div className="reframe-filefield-remove" onClick={ this._handleRemove.bind(this) }>
{ isImage ? <i className="fa fa-fw fa-times-circle" /> : <i className="fa fa-fw fa-times" /> }
</div>
{ isImage ? <ImageFileToken { ...this._getImageFile() } /> : <PlainFileToken { ...this._getPlainFile() } /> }
</div>
)
}
_getImageFile() {
const { file, preview } = this.props
return {
file: file.asset,
preview
}
}
_getPlainFile() {
const { file } = this.props
const file_name = file.fileName || file.asset.file_name
const file_size = file.fileSize || file.asset.file_size
return {
file_name,
file_size
}
}
_handleRemove() {
this.props.onRemove()
}
}
export default Preview
|
addons/info/src/components/types/InstanceOf.js
|
rhalff/storybook
|
import React from 'react';
import { TypeInfo, getPropTypes } from './proptypes';
const InstanceOf = ({ propType }) => <span>{getPropTypes(propType)}</span>;
InstanceOf.propTypes = {
propType: TypeInfo.isRequired,
};
export default InstanceOf;
|
app/jsx/new_user_tutorial/ConfirmEndTutorialDialog.js
|
djbender/canvas-lms
|
/*
* Copyright (C) 2017 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import PropTypes from 'prop-types'
import I18n from 'i18n!new_user_tutorial'
import {Button} from '@instructure/ui-buttons'
import Modal from '../shared/components/InstuiModal'
import axios from 'axios'
const API_URL = '/api/v1/users/self/features/flags/new_user_tutorial_on_off'
export default function ConfirmEndTutorialDialog({isOpen, handleRequestClose}) {
return (
<Modal
open={isOpen}
size="small"
onDismiss={handleRequestClose}
label={I18n.t('End Course Set-up Tutorial')}
>
<Modal.Body>
{I18n.t(
'Turning off this tutorial will remove the tutorial tray from your view for all of your courses. It can be turned back on under Feature Options in your User Settings.'
)}
</Modal.Body>
<Modal.Footer>
<Button onClick={handleRequestClose}>{I18n.t('Cancel')}</Button>
<Button
onClick={() =>
axios.put(API_URL, {state: 'off'}).then(() => ConfirmEndTutorialDialog.onSuccess())
}
variant="primary"
>
{I18n.t('Okay')}
</Button>
</Modal.Footer>
</Modal>
)
}
ConfirmEndTutorialDialog.onSuccess = () => window.location.reload()
ConfirmEndTutorialDialog.propTypes = {
isOpen: PropTypes.bool,
handleRequestClose: PropTypes.func.isRequired
}
ConfirmEndTutorialDialog.defaultProps = {
isOpen: false
}
|
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
|
UKForeignOffice/ETD-prototype-upload
|
import React from 'react';
import { render } from 'react-dom';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
render(<HelloWorld />, document.getElementById('react-root'));
|
app/components/Options-bar.js
|
L-A/Little-Jekyll
|
import React, { Component } from 'react';
import Dispatcher from '../utils/front-end-dispatcher';
import SimpleButton from './simple-button'
var OptionsBar = React.createClass({
requestNewSite: function() {
Dispatcher.send('addSite');
},
createNewSite: function() {
Dispatcher.send('createSite');
},
render: function () {
return (
<div className="options-bar">
<SimpleButton onClick={this.createNewSite} className="btn-create" hintText="Create a new template site" />
<span className={this.props.hintAvailable ? "hint-text hint-available" : "hint-text"}>{this.props.hintText}</span>
<SimpleButton href="#" onClick={this.requestNewSite} className="btn-open" hintText="Open an existing Jekyll site" />
{/* <SimpleButton className="btn-settings" /> */}
</div>
);
}
})
module.exports = OptionsBar;
|
winearb/static/react/js/articles.js
|
REBradley/WineArb
|
import React from 'react';
import ReactDOM from 'react-dom';
import Col from 'react-bootstrap/lib/Col';
import Jumbotron from 'react-bootstrap/lib/Jumbotron';
import Image from 'react-bootstrap/lib/Image';
import Button from 'react-bootstrap/lib/Button';
import ButtonGroup from 'react-bootstrap/lib/ButtonGroup';
import Fade from 'react-bootstrap/lib/Fade';
import Title from "./components/title.js";
import { Username } from "./components/username.js";
import { Date } from "./components/date.js";
import Text from "./components/text.js";
import InnerHTML from "./components/innerhtml.js";
function CustomJTron(ShowWrappedComponent, ToggleWrappedComponent) {
return class FadeInJumbotronIvory extends React.Component {
constructor(props) {
super(props);
this.state = {isClicked: false};
this.handleClick = this.handleClick.bind(this);
}
handleClick () {
this.setState(prevState => ({
isClicked: !prevState.isClicked
}));
}
render() {
const isClicked = this.state.isClicked;
return(
<Col>
<div>
<Jumbotron style={{backgroundColor: '#FFFFF0', float: 'center', padding: 'none', border: 'outset black'}}>
<div className="JumbotronItem" style={{textAlign: 'center'}}>
<div>
<ShowWrappedComponent {...this.props} />
</div>
<ButtonGroup vertical block>
<Col md={6} mdOffset={3}>
<Button bsSize="xsmall" onClick={this.handleClick}>
{isClicked ? 'Close' : 'View Content'}
</Button>
</Col>
</ButtonGroup>
</div>
</Jumbotron>
</div>
<div>
<Fade in={isClicked} unmountOnExit={true} timeout={1000}>
<Jumbotron style={{backgroundColor: '#FFFFF0', float: 'center', padding: 'none', border: 'outset black', marginTop: '0px'}}>
<div className="JumbotronItem" style={{textAlign: 'center'}}>
<div>
{this.props.children}
<ToggleWrappedComponent {...this.props} />
</div>
</div>
</Jumbotron>
</Fade>
</div>
</Col>
);
}
}
};
const ArticleHeading = (props) => {
return(
<div>
<Image style={{ display: 'inline-block' }}src={props.image} responsive />
<Title main_title={props.main_title} sub_title={props.sub_title} />
<Username username={props.author} />
<Date date={props.date} />
</div>
);
};
const Article = CustomJTron(ArticleHeading, InnerHTML);
export { Article, CustomJTron };
|
src/main.js
|
dontexpectanythingsensible/password-checker
|
import React from 'react';
import ReactDOM from 'react-dom';
import createStore from './store/createStore';
import AppContainer from './containers/AppContainer';
import * as OfflinePluginRuntime from 'offline-plugin/runtime';
OfflinePluginRuntime.install();
// ========================================================
// Store Instantiation
// ========================================================
const initialState = window.___INITIAL_STATE__;
const store = createStore(initialState);
// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('root');
let render = () => {
const routes = require('./routes/index').default(store);
ReactDOM.render(
<AppContainer store={ store } 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) {
console.error(error);
renderError(error);
}
};
// Setup hot module replacement
module.hot.accept('./routes/index', () =>
setImmediate(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE);
render();
})
);
}
}
// ========================================================
// Go!
// ========================================================
render();
|
tests/client/core/components/TestLoginPage.js
|
mstriemer/usetopscore-widgets
|
import React from 'react';
import { renderIntoDocument } from 'react-addons-test-utils';
import { findDOMNode } from 'react-dom';
import config from 'config';
import LoginPage from 'core/components/LoginPage';
describe('<LoginPage />', () => {
function render(props = {}) {
return findDOMNode(renderIntoDocument(<LoginPage {...props} />));
}
it('has a header', () => {
const root = render();
assert.equal(root.querySelector('h1').textContent, 'Login Required');
});
it('has a default message', () => {
const root = render();
assert.equal(
root.querySelector('.login-message').textContent,
'You must be logged in to access this page.');
});
it('can accept a message', () => {
const root = render({message: 'My custom login message.'});
assert.equal(
root.querySelector('.login-message').textContent,
'My custom login message.');
});
it('has a button to the login URL', () => {
const root = render();
const loginLink = root.querySelector('a');
assert.equal(loginLink.href, config.get('startLoginUrl'));
assert.equal(loginLink.textContent, 'Login');
});
});
|
client/src/universal/routes/async.js
|
mariocoski/express-typescript-react-redux-universal
|
import React from 'react';
import Loadable from 'react-loadable';
function loadAsync(loader){
return Loadable({
loader,
loading: ()=>(<div>Loading...</div>)
});
}
export const Home = loadAsync(() => import('universal/containers/pages/HomeContainer.jsx'));
export const Todos = loadAsync(() => import('universal/containers/pages/TodosContainer.jsx'));
export const NotFound = loadAsync(() => import('universal/containers/pages/NotFoundContainer.jsx'));
export const Login = loadAsync(() => import('universal/containers/auth/LoginContainer.jsx'));
export const Register = loadAsync(() => import('universal/containers/auth/RegistrationContainer.jsx'));
export const Dashboard = loadAsync(() => import('universal/containers/dashboard/DashboardContainer.jsx'));
|
src/Card/__tests__/CardMedia-test.js
|
Graf009/react-mdl
|
/* eslint-env mocha */
import expect from 'expect';
import React from 'react';
import { render } from '../../__tests__/render';
import { CardMedia } from '../';
describe('Card', () => {
describe('CardMedia', () => {
it('should render a div with the card media css class', () => {
const output = render(<CardMedia />);
expect(output.type).toBe('div');
expect(output.props.className).toInclude('mdl-card__media');
});
it('should allow custom css classes', () => {
const output = render(<CardMedia className="my-media" />);
expect(output.props.className)
.toInclude('mdl-card__media')
.toInclude('my-media');
});
it('should render with the children', () => {
const element = (
<CardMedia>
<img src="test.png" />
</CardMedia>
);
const output = render(element);
expect(output.props.children)
.toEqual(<img src="test.png" />);
});
});
});
|
app/jsx/courses/ModulesHomePage.js
|
djbender/canvas-lms
|
/*
* Copyright (C) 2017 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import PropTypes from 'prop-types'
import {IconModuleSolid, IconUploadLine} from '@instructure/ui-icons'
import I18n from 'i18n!modules_home_page'
export default class ModulesHomePage extends React.Component {
static propTypes = {
onCreateButtonClick: PropTypes.func
}
static defaultProps = {
onCreateButtonClick: () => {}
}
render() {
const importURL = window.ENV.CONTEXT_URL_ROOT + '/content_migrations'
return (
<ul className="ic-EmptyStateList">
<li className="ic-EmptyStateList__Item">
<div className="ic-EmptyStateList__BillboardWrapper">
<button
type="button"
className="ic-EmptyStateButton"
onClick={this.props.onCreateButtonClick}
>
<IconModuleSolid className="ic-EmptyStateButton__SVG" />
<span className="ic-EmptyStateButton__Text">{I18n.t('Create a new Module')}</span>
</button>
</div>
</li>
<li className="ic-EmptyStateList__Item">
<div className="ic-EmptyStateList__BillboardWrapper">
<a href={importURL} className="ic-EmptyStateButton">
<IconUploadLine className="ic-EmptyStateButton__SVG" />
<span className="ic-EmptyStateButton__Text">{I18n.t('Add existing content')}</span>
</a>
</div>
</li>
</ul>
)
}
}
|
src/pwa.js
|
tpphu/react-pwa
|
import React from 'react';
import ReactDOM from 'react-dom/server';
import Html from './helpers/Html';
export default function () {
return `<!doctype html>${ReactDOM.renderToStaticMarkup(<Html />)}`;
}
|
demo/components/switch/PagerOptions.js
|
ctco/rosemary-ui
|
import React from 'react';
import OptionsTable from '../../helper/OptionsTable';
import {MonthPager, Pager} from '../../../src';
export default () => {
let propDescription = {
onPrevBtnClick: {
values: 'function',
description: 'Is called when a left btn is clicked'
},
onNextBtnClick: {
values: 'function',
description: 'Is called when a right btn is clicked'
},
value: {
values: 'any',
description: 'value will be displayed'
},
prevBtnIcon: {
values: 'string',
description: 'icon name'
},
nextBtnIcon: {
values: 'string',
description: 'icon name'
}
};
return (
<div>
<h2>Pager</h2>
<OptionsTable component={Pager} propDescription={propDescription}/>
<br/>
<h2>MonthPager</h2>
<OptionsTable component={MonthPager} propDescription={propDescription}/>
</div>
);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.