path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
fields/types/cloudinaryimage/CloudinaryImageFilter.js
|
nickhsine/keystone
|
import React from 'react';
import { SegmentedControl } from 'elemental';
var PasswordFilter = React.createClass({
getInitialState () {
return {
checked: this.props.value || true,
};
},
toggleChecked (checked) {
this.setState({
checked: checked,
});
},
renderToggle () {
let options = [
{ label: 'Is Set', value: true },
{ label: 'Is NOT Set', value: false },
];
return <SegmentedControl equalWidthSegments options={options} value={this.state.checked} onChange={this.toggleChecked} />;
},
render () {
return this.renderToggle();
},
});
module.exports = PasswordFilter;
|
client/src/components/UtilComponents/NotFound.js
|
codefordenver/Circular
|
import React from 'react';
import { Link } from 'react-router';
const NotFound = () => (
<div className="not-found-container">
<div>
<h1>You seem to have gotten lost...</h1>
</div>
<div>
<i className="fa fa-4x fa-recycle loading-spinner slow-spin" />
</div>
<div>
<Link className="home-section-link" to="/">
Go back to Home Page
</Link>
</div>
</div>
);
export default NotFound;
|
examples/huge-apps/routes/Profile/components/Profile.js
|
Dodelkin/react-router
|
import React from 'react'
class Profile extends React.Component {
render() {
return (
<div>
<h2>Profile</h2>
</div>
)
}
}
export default Profile
|
src/modules/keywords/components/KeywordCommentList/KeywordCommentList.js
|
CtrHellenicStudies/Commentary
|
import React from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import moment from 'moment';
import { compose } from 'react-apollo';
// components
import AvatarIcon from '../../../users/components/AvatarIcon';
// lib
import createRevisionMarkup from '../../../../lib/createRevisionMarkup';
// graphql
import commentersQuery from '../../../commenters/graphql/queries/list';
const KeywordCommentList = (props) => {
const { keywordComments } = props;
if (!keywordComments || !keywordComments.length) {
return (
<div className="comment-outer has-discussion">
<div className="no-results">
This tag has no comments associated with it yet.
</div>
</div>
);
}
return (
<div className="comment-outer has-discussion">
{props.keywordComments.map((comment, i) => {
const selectedRevision = comment.revisions[comment.revisions.length - 1];
const updated = selectedRevision.updated;
const format = 'D MMMM YYYY';
return (
<article
key={comment._id}
className="comment commentary-comment paper-shadow "
>
<div className="comment-upper">
<div className="comment-upper-left">
<h2 className="comment-title" style={{margin: 0, padding: 0}}><Link to={`/commentary?_id=${comment._id}`}>{selectedRevision.title}</Link></h2>
</div>
<div className="comment-upper-right">
{comment.commenters.map((commenter, _i) => {
const commenterRecord = props.commentersQuery.loading ? {} : props.commentersQuery.commenters.find(x =>
x.slug === commenter.slug);
if (!commenterRecord) {
return null;
}
return (
<div
key={_i}
className="comment-author"
>
<div className="comment-author-text">
<Link to={`/commenters/${commenterRecord.slug}`}>
<span className="comment-author-name" style={{margin: 0, textAlign: 'right'}}>{commenterRecord.name}</span>
</Link>
<span className="comment-date" style={{margin: 0, textAlign: 'right'}}>
{moment(updated).format(format)}
</span>
</div>
<div className="comment-author-image-wrap paper-shadow">
<Link to={`/commenters/${commenterRecord.slug}`}>
<AvatarIcon
avatar={
(commenterRecord && commenterRecord.avatar) ?
commenterRecord.avatar.src
: null
}
/>
</Link>
</div>
</div>
);
})}
</div>
</div>
<div className="comment-lower">
<div
className="comment-body"
dangerouslySetInnerHTML={createRevisionMarkup(selectedRevision.text)}
/>
</div>
</article>
);
})}
</div>
);
};
KeywordCommentList.propTypes = {
keywordComments: PropTypes.array,
};
export default compose(
commentersQuery
)(KeywordCommentList);
|
packages/material-ui-icons/src/LocalDining.js
|
AndriusBil/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let LocalDining = props =>
<SvgIcon {...props}>
<path d="M8.1 13.34l2.83-2.83L3.91 3.5c-1.56 1.56-1.56 4.09 0 5.66l4.19 4.18zm6.78-1.81c1.53.71 3.68.21 5.27-1.38 1.91-1.91 2.28-4.65.81-6.12-1.46-1.46-4.2-1.1-6.12.81-1.59 1.59-2.09 3.74-1.38 5.27L3.7 19.87l1.41 1.41L12 14.41l6.88 6.88 1.41-1.41L13.41 13l1.47-1.47z" />
</SvgIcon>;
LocalDining = pure(LocalDining);
LocalDining.muiName = 'SvgIcon';
export default LocalDining;
|
src/Components/RichEditor/index.js
|
sqhtiamo/zaro
|
import React, { Component } from 'react';
import { PropTypes } from 'prop-types';
import Loading from '../Loading';
class RichEditor extends Component {
static genStyle(tags = []) {
const res = {};
const styles = [
'color', 'font-size', 'font-family', 'position', 'display', 'font-weight', 'cursor',
'letter-spacing', 'line-height', 'vertical-align', 'text-align',
'width', 'height',
'padding', 'padding-top', 'padding-left', 'padding-right', 'padding-bottom',
'margin', 'margin-top', 'margin-left', 'margin-right', 'margin-bottom',
'border', 'border-top', 'border-left', 'border-right', 'border-bottom', 'border-collapse', 'border-color', 'border-collapse',
'background', 'background-color', 'word-break',
'list-style-type'
];
for (let i = 0; i < tags.length; i++) {
res[tags[i]] = styles;
}
return res;
}
static genAttr(tags = []) {
const res = {};
const attrs = [
'src', 'alt', 'width', 'height', 'title', 'color',
'class', 'align', 'valign', 'size', 'bgColor', 'cols',
'rows', 'colspan', 'rowspan', 'align', 'size', 'cellpadding',
'cellspacing', 'border', 'nowrap'
];
for (let i = 0; i < tags.length; i++) {
res[tags[i]] = attrs;
}
return res;
}
constructor(props) {
super(props);
this.state = {
isFull: false,
isLoading: true,
};
this.showModal = this.showModal.bind(this);
this.hideModal = this.hideModal.bind(this);
this.htmlTags = [
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'b',
'strong', 'i', 'em', 'ul', 'ol', 'li', 'font',
'br', 'p', 'sub', 'sup', 'del', 'hr',
'table', 'th', 'tr', 'thead', 'tbody', 'td', 'colgroup', 'col',
'div', 'pre', 'dl', 'dt', 'dd', 'a', 'span', 'code', 'blockquote',
'header', 'footer', 'nav', 'aside', 'section', 'figure', 'time', 'cite',
];
}
componentDidMount() {
const { editorOnload } = this.props;
require.ensure([], (require) => {
window.jquery = require('jquery/dist/jquery');
this.Simditor = require('simditor');
this.style = require('./simditor.css');
this.setState({
isLoading: false
});
this.initEditor();
// 确保已经载入
setTimeout(() => {
editorOnload();
});
});
}
componentWillUnmount() {
this.editor.destroy();
}
getContent() {
return this.editor.getValue();
}
setContent(v) {
this.editor.setValue(v);
}
initEditor() {
const textbox = this.textarea;
this.editor = new this.Simditor({
textarea: window.jquery(textbox),
upload: false,
toolbarFloat: false,
toolbar: [
'title',
'bold',
'italic',
'underline',
'strikethrough',
'fontScale',
'color',
'ol',
'ul',
'blockquote',
// 'code',
'table',
// 'link',
'hr',
'indent',
'outdent',
'alignment'
],
allowedTags: this.htmlTags,
allowedAttributes: RichEditor.genAttr(this.htmlTags),
allowedStyles: RichEditor.genStyle(this.htmlTags)
});
this.editor.on('valuechanged', () => {
this.props.change(this.getContent());
});
}
showModal() {
this.setState({
isFull: true
});
document.body.style.overflow = 'hidden';
// 编辑器全屏
window.jquery('.simditor').addClass('full');
}
hideModal() {
this.setState({
isFull: false
});
document.body.style.overflow = 'auto';
window.jquery('.simditor').removeClass('full');
}
render() {
const { isFull, isLoading } = this.state;
if (isLoading) {
return (
<Loading />
);
}
return (
<div>
<div
onClick={this.hideModal}
className={isFull ? 'full editor-modal' : 'editor-modal'}
/>
<textarea
ref={(item) => {
this.textarea = item;
}}
/>
</div>
);
}
}
RichEditor.propTypes = {
change: PropTypes.func,
editorOnload: PropTypes.func,
};
RichEditor.defaultProps = {
change: () => {},
editorOnload: () => {}
};
export default RichEditor;
|
app/javascript/mastodon/features/compose/components/upload_progress.js
|
hugogameiro/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import Motion from '../../ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import { FormattedMessage } from 'react-intl';
export default class UploadProgress extends React.PureComponent {
static propTypes = {
active: PropTypes.bool,
progress: PropTypes.number,
};
render () {
const { active, progress } = this.props;
if (!active) {
return null;
}
return (
<div className='upload-progress'>
<div className='upload-progress__icon'>
<i className='fa fa-upload' />
</div>
<div className='upload-progress__message'>
<FormattedMessage id='upload_progress.label' defaultMessage='Uploading...' />
<div className='upload-progress__backdrop'>
<Motion defaultStyle={{ width: 0 }} style={{ width: spring(progress) }}>
{({ width }) =>
<div className='upload-progress__tracker' style={{ width: `${width}%` }} />
}
</Motion>
</div>
</div>
</div>
);
}
}
|
app/javascript/mastodon/features/explore/results.js
|
koba-lab/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { FormattedMessage } from 'react-intl';
import { connect } from 'react-redux';
import { expandSearch } from 'mastodon/actions/search';
import Account from 'mastodon/containers/account_container';
import Status from 'mastodon/containers/status_container';
import { ImmutableHashtag as Hashtag } from 'mastodon/components/hashtag';
import { List as ImmutableList } from 'immutable';
import LoadMore from 'mastodon/components/load_more';
import LoadingIndicator from 'mastodon/components/loading_indicator';
const mapStateToProps = state => ({
isLoading: state.getIn(['search', 'isLoading']),
results: state.getIn(['search', 'results']),
});
const appendLoadMore = (id, list, onLoadMore) => {
if (list.size >= 5) {
return list.push(<LoadMore key={`${id}-load-more`} visible onClick={onLoadMore} />);
} else {
return list;
}
};
const renderAccounts = (results, onLoadMore) => appendLoadMore('accounts', results.get('accounts', ImmutableList()).map(item => (
<Account key={`account-${item}`} id={item} />
)), onLoadMore);
const renderHashtags = (results, onLoadMore) => appendLoadMore('hashtags', results.get('hashtags', ImmutableList()).map(item => (
<Hashtag key={`tag-${item.get('name')}`} hashtag={item} />
)), onLoadMore);
const renderStatuses = (results, onLoadMore) => appendLoadMore('statuses', results.get('statuses', ImmutableList()).map(item => (
<Status key={`status-${item}`} id={item} />
)), onLoadMore);
export default @connect(mapStateToProps)
class Results extends React.PureComponent {
static propTypes = {
results: ImmutablePropTypes.map,
isLoading: PropTypes.bool,
multiColumn: PropTypes.bool,
dispatch: PropTypes.func.isRequired,
};
state = {
type: 'all',
};
handleSelectAll = () => this.setState({ type: 'all' });
handleSelectAccounts = () => this.setState({ type: 'accounts' });
handleSelectHashtags = () => this.setState({ type: 'hashtags' });
handleSelectStatuses = () => this.setState({ type: 'statuses' });
handleLoadMoreAccounts = () => this.loadMore('accounts');
handleLoadMoreStatuses = () => this.loadMore('statuses');
handleLoadMoreHashtags = () => this.loadMore('hashtags');
loadMore (type) {
const { dispatch } = this.props;
dispatch(expandSearch(type));
}
render () {
const { isLoading, results } = this.props;
const { type } = this.state;
let filteredResults = ImmutableList();
if (!isLoading) {
switch(type) {
case 'all':
filteredResults = filteredResults.concat(renderAccounts(results, this.handleLoadMoreAccounts), renderHashtags(results, this.handleLoadMoreHashtags), renderStatuses(results, this.handleLoadMoreStatuses));
break;
case 'accounts':
filteredResults = filteredResults.concat(renderAccounts(results, this.handleLoadMoreAccounts));
break;
case 'hashtags':
filteredResults = filteredResults.concat(renderHashtags(results, this.handleLoadMoreHashtags));
break;
case 'statuses':
filteredResults = filteredResults.concat(renderStatuses(results, this.handleLoadMoreStatuses));
break;
}
if (filteredResults.size === 0) {
filteredResults = (
<div className='empty-column-indicator'>
<FormattedMessage id='search_results.nothing_found' defaultMessage='Could not find anything for these search terms' />
</div>
);
}
}
return (
<React.Fragment>
<div className='account__section-headline'>
<button onClick={this.handleSelectAll} className={type === 'all' && 'active'}><FormattedMessage id='search_results.all' defaultMessage='All' /></button>
<button onClick={this.handleSelectAccounts} className={type === 'accounts' && 'active'}><FormattedMessage id='search_results.accounts' defaultMessage='People' /></button>
<button onClick={this.handleSelectHashtags} className={type === 'hashtags' && 'active'}><FormattedMessage id='search_results.hashtags' defaultMessage='Hashtags' /></button>
<button onClick={this.handleSelectStatuses} className={type === 'statuses' && 'active'}><FormattedMessage id='search_results.statuses' defaultMessage='Toots' /></button>
</div>
<div className='explore__search-results'>
{isLoading ? <LoadingIndicator /> : filteredResults}
</div>
</React.Fragment>
);
}
}
|
app/javascript/mastodon/features/ui/components/columns_area.js
|
pfm-eyesightjp/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl } from 'react-intl';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ReactSwipeableViews from 'react-swipeable-views';
import { links, getIndex, getLink } from './tabs_bar';
import BundleContainer from '../containers/bundle_container';
import ColumnLoading from './column_loading';
import BundleColumnError from './bundle_column_error';
import { Compose, Notifications, HomeTimeline, CommunityTimeline, PublicTimeline, HashtagTimeline, FavouritedStatuses } from '../../ui/util/async-components';
import detectPassiveEvents from 'detect-passive-events';
import { scrollRight } from '../../../scroll';
const componentMap = {
'COMPOSE': Compose,
'HOME': HomeTimeline,
'NOTIFICATIONS': Notifications,
'PUBLIC': PublicTimeline,
'COMMUNITY': CommunityTimeline,
'HASHTAG': HashtagTimeline,
'FAVOURITES': FavouritedStatuses,
};
@component => injectIntl(component, { withRef: true })
export default class ColumnsArea extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
intl: PropTypes.object.isRequired,
columns: ImmutablePropTypes.list.isRequired,
singleColumn: PropTypes.bool,
children: PropTypes.node,
};
state = {
shouldAnimate: false,
}
componentWillReceiveProps() {
this.setState({ shouldAnimate: false });
}
componentDidMount() {
if (!this.props.singleColumn) {
this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false);
}
this.lastIndex = getIndex(this.context.router.history.location.pathname);
this.setState({ shouldAnimate: true });
}
componentWillUpdate(nextProps) {
if (this.props.singleColumn !== nextProps.singleColumn && nextProps.singleColumn) {
this.node.removeEventListener('wheel', this.handleWheel);
}
}
componentDidUpdate(prevProps) {
if (this.props.singleColumn !== prevProps.singleColumn && !this.props.singleColumn) {
this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false);
}
this.lastIndex = getIndex(this.context.router.history.location.pathname);
this.setState({ shouldAnimate: true });
}
componentWillUnmount () {
if (!this.props.singleColumn) {
this.node.removeEventListener('wheel', this.handleWheel);
}
}
handleChildrenContentChange() {
if (!this.props.singleColumn) {
scrollRight(this.node, this.node.scrollWidth - window.innerWidth);
}
}
handleSwipe = (index) => {
this.pendingIndex = index;
const nextLinkTranslationId = links[index].props['data-preview-title-id'];
const currentLinkSelector = '.tabs-bar__link.active';
const nextLinkSelector = `.tabs-bar__link[data-preview-title-id="${nextLinkTranslationId}"]`;
// HACK: Remove the active class from the current link and set it to the next one
// React-router does this for us, but too late, feeling laggy.
document.querySelector(currentLinkSelector).classList.remove('active');
document.querySelector(nextLinkSelector).classList.add('active');
}
handleAnimationEnd = () => {
if (typeof this.pendingIndex === 'number') {
this.context.router.history.push(getLink(this.pendingIndex));
this.pendingIndex = null;
}
}
handleWheel = () => {
if (typeof this._interruptScrollAnimation !== 'function') {
return;
}
this._interruptScrollAnimation();
}
setRef = (node) => {
this.node = node;
}
renderView = (link, index) => {
const columnIndex = getIndex(this.context.router.history.location.pathname);
const title = this.props.intl.formatMessage({ id: link.props['data-preview-title-id'] });
const icon = link.props['data-preview-icon'];
const view = (index === columnIndex) ?
React.cloneElement(this.props.children) :
<ColumnLoading title={title} icon={icon} />;
return (
<div className='columns-area' key={index}>
{view}
</div>
);
}
renderLoading = () => {
return <ColumnLoading />;
}
renderError = (props) => {
return <BundleColumnError {...props} />;
}
render () {
const { columns, children, singleColumn } = this.props;
const { shouldAnimate } = this.state;
const columnIndex = getIndex(this.context.router.history.location.pathname);
this.pendingIndex = null;
if (singleColumn) {
return columnIndex !== -1 ? (
<ReactSwipeableViews index={columnIndex} onChangeIndex={this.handleSwipe} onTransitionEnd={this.handleAnimationEnd} animateTransitions={shouldAnimate} springConfig={{ duration: '400ms', delay: '0s', easeFunction: 'ease' }} style={{ height: '100%' }}>
{links.map(this.renderView)}
</ReactSwipeableViews>
) : <div className='columns-area'>{children}</div>;
}
return (
<div className='columns-area' ref={this.setRef}>
{columns.map(column => {
const params = column.get('params', null) === null ? null : column.get('params').toJS();
return (
<BundleContainer key={column.get('uuid')} fetchComponent={componentMap[column.get('id')]} loading={this.renderLoading} error={this.renderError}>
{SpecificComponent => <SpecificComponent columnId={column.get('uuid')} params={params} multiColumn />}
</BundleContainer>
);
})}
{React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))}
</div>
);
}
}
|
fields/types/Field.js
|
davibe/keystone
|
import _ from 'underscore';
import classnames from 'classnames';
import evalDependsOn from '../utils/evalDependsOn.js';
import React from 'react';
import { Button, FormField, FormInput, FormNote } from 'elemental';
function validateSpec(spec) {
if (!spec) spec = {};
if (!_.isObject(spec.supports)) {
spec.supports = {};
}
if (!spec.focusTargetRef) {
spec.focusTargetRef = 'focusTarget';
}
return spec;
}
var Base = module.exports.Base = {
getInitialState () {
return {};
},
getDefaultProps () {
return {
inputProps: {},
labelProps: {},
valueProps: {},
size: 'full'
};
},
valueChanged (event) {
this.props.onChange({
path: this.props.path,
value: event.target.value
});
},
shouldCollapse () {
return this.props.collapse && !this.props.value;
},
shouldRenderField () {
if (!this.props.noedit) return true;
if (this.props.mode === 'create' && this.props.initial) return true;
return false;
},
focus () {
if (!this.refs[this.spec.focusTargetRef]) return;
this.refs[this.spec.focusTargetRef].getDOMNode().focus();
},
renderNote () {
if (!this.props.note) return null;
return <FormNote note={this.props.note} />;
},
renderField () {
var props = _.extend(this.props.inputProps, {
autoComplete: 'off',
name: this.props.path,
onChange: this.valueChanged,
ref: 'focusTarget',
value: this.props.value
});
return <FormInput {...props} />;
},
renderValue () {
return <FormInput noedit>{this.props.value}</FormInput>;
},
renderUI () {
var wrapperClassName = classnames(
('field-type-' + this.props.type),
this.props.className
);
return (
<FormField label={this.props.label} className={wrapperClassName} htmlFor={this.props.path}>
<div className={'FormField__inner field-size-' + this.props.size}>
{this.shouldRenderField() ? this.renderField() : this.renderValue()}
</div>
{this.renderNote()}
</FormField>
);
}
};
var Mixins = module.exports.Mixins = {
Collapse: {
componentWillMount () {
this.setState({
isCollapsed: this.shouldCollapse()
});
},
componentDidUpdate (prevProps, prevState) {
if (prevState.isCollapsed && !this.state.isCollapsed) {
this.focus();
}
},
uncollapse () {
this.setState({
isCollapsed: false
});
},
renderCollapse () {
if (!this.shouldRenderField()) return null;
return (
<FormField>
<Button type="link" className="collapsed-field-label" onClick={this.uncollapse}>+ Add {this.props.label.toLowerCase()}</Button>
</FormField>
);
}
}
};
module.exports.create = function(spec) {
spec = validateSpec(spec);
var excludeBaseMethods = [];
var field = {
spec: spec,
displayName: spec.displayName,
mixins: [Mixins.Collapse],
render () {
if (!evalDependsOn(this.props.dependsOn, this.props.values)) {
return null;
}
if (this.state.isCollapsed) {
return this.renderCollapse();
}
return this.renderUI();
}
};
if (spec.mixins) {
_.each(spec.mixins, function(mixin) {
_.each(mixin, function(method, name) {
if (Base[name]) excludeBaseMethods.push(name);
});
});
}
_.extend(field, _.omit(Base, excludeBaseMethods));
_.extend(field, _.omit(spec, 'mixins'));
if (_.isArray(spec.mixins)) {
field.mixins = field.mixins.concat(spec.mixins);
}
return React.createClass(field);
};
|
examples/todomvc/containers/Root.dev.js
|
alexkuz/redux-devtools
|
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import TodoApp from './TodoApp';
import DevTools from './DevTools';
export default class Root extends Component {
render() {
const { store } = this.props;
return (
<Provider store={store}>
<div>
<TodoApp />
<DevTools />
</div>
</Provider>
);
}
}
|
example/src/screens/types/Notification.js
|
junedomingo/react-native-navigation
|
import React from 'react';
import {StyleSheet, View, Text, Dimensions, Button} from 'react-native';
class Notification extends React.Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>In-App Notification</Text>
<Text style={styles.content}>You have 10 unread notifications!</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
height: 100,
backgroundColor: '#ff505c',
padding: 16,
margin: 10,
},
title: {
fontSize: 18,
textAlign: 'center',
},
content: {
textAlign: 'center',
marginTop: 10,
},
});
export default Notification;
|
src/TextField/TextFieldHint.js
|
ichiohta/material-ui
|
import React from 'react';
import PropTypes from 'prop-types';
import transitions from '../styles/transitions';
function getStyles(props) {
const {
muiTheme: {
textField: {
hintColor,
},
},
show,
} = props;
return {
root: {
position: 'absolute',
opacity: show ? 1 : 0,
color: hintColor,
transition: transitions.easeOut(),
bottom: 12,
},
};
}
const TextFieldHint = (props) => {
const {
muiTheme: {
prepareStyles,
},
style,
text,
} = props;
const styles = getStyles(props);
return (
<div style={prepareStyles(Object.assign(styles.root, style))}>
{text}
</div>
);
};
TextFieldHint.propTypes = {
/**
* @ignore
* The material-ui theme applied to this component.
*/
muiTheme: PropTypes.object.isRequired,
/**
* True if the hint text should be visible.
*/
show: PropTypes.bool,
/**
* Override the inline-styles of the root element.
*/
style: PropTypes.object,
/**
* The hint text displayed.
*/
text: PropTypes.node,
};
TextFieldHint.defaultProps = {
show: true,
};
export default TextFieldHint;
|
src/svg-icons/social/people.js
|
jacklam718/react-svg-iconx
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialPeople = (props) => (
<SvgIcon {...props}>
<path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/>
</SvgIcon>
);
SocialPeople = pure(SocialPeople);
SocialPeople.displayName = 'SocialPeople';
SocialPeople.muiName = 'SvgIcon';
export default SocialPeople;
|
src/components/item/view/ItemActionPanel.js
|
katima-g33k/blu-react-desktop
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { ActionPanel } from '../../general';
import i18n from '../../../lib/i18n';
import StatusButton from '../../../containers/StatusButtonContainer';
export default class ItemActionPanel extends Component {
static propTypes = {
canDelete: PropTypes.bool.isRequired,
handleDelete: PropTypes.func.isRequired,
handleReserve: PropTypes.func.isRequired,
handleUpdateStorage: PropTypes.func.isRequired,
modify: PropTypes.func.isRequired,
userIsAdmin: PropTypes.bool.isRequired,
};
userActions = [
{
label: i18n('ItemView.actions.modify'),
onClick: this.props.modify,
},
{
customComponent: (<StatusButton />),
},
{
label: i18n('ItemView.actions.storage'),
onClick: this.props.handleUpdateStorage,
},
{
label: i18n('ItemView.actions.reserve'),
onClick: this.props.handleReserve,
},
];
adminActions = [{
disabled: this.props.canDelete,
label: i18n('ItemView.actions.delete'),
onClick: this.props.handleDelete,
style: 'danger',
}];
actions = [
...this.userActions,
...(this.props.userIsAdmin ? this.adminActions : []),
];
render() {
return (<ActionPanel actions={this.actions} />);
}
}
|
Neos.Media.Browser/packages/neos-media-browser/src/Variants/Variants.js
|
daniellienert/neos-development-collection
|
import React from 'react';
import Variant from './Variant';
export default class Variants extends React.PureComponent {
render() {
const {variants, onRequestCrop} = this.props;
const renderedVariants = variants.map((variantInformation) => <Variant onRequestCrop={onRequestCrop} key={variantInformation.persistenceIdentifier} {...variantInformation} />);
return (
<ul className="neos-thumbnails asset-list">
{renderedVariants}
</ul>
)
}
}
|
client/src/transforms/TreeDropdownField/moveTreeDropdownField.js
|
open-sausages/silverstripe-asset-admin
|
import React from 'react';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { findTreeByPath } from 'components/TreeDropdownField/TreeDropdownField';
/**
* Enables a treepdropdown field to have individually disabled items
*/
const disabledTreeDropdownField = (TreeDropdownField) => (props) => {
/* eslint-disable react/prop-types */
const { disabledIDs } = props;
const find = props.findTreeByPath || findTreeByPath;
/* eslint-enable react/prop-types */
const newProps = {
...props,
findTreeByPath(tree, visible) {
const visibleTree = find(tree, visible);
const pathDisabled = visible.some(id => disabledIDs.includes(id));
return visibleTree ? {
...visibleTree,
children: visibleTree.children.map(child => ({
...child,
disabled: pathDisabled || disabledIDs.includes(child.id),
})),
} : null;
},
};
return <TreeDropdownField {...newProps} />;
};
/*
* Ensure selected files can't also be selected as move target
*/
const moveTreeDropdownField = compose(
connect(
state => ({
disabledIDs: state.assetAdmin.gallery.selectedFiles,
})
),
disabledTreeDropdownField
);
export { disabledTreeDropdownField };
export default moveTreeDropdownField;
|
node_modules/@material-ui/core/es/internal/svg-icons/CheckBoxOutlineBlank.js
|
pcclarke/civ-techs
|
import React from 'react';
import createSvgIcon from './createSvgIcon';
/**
* @ignore - internal component.
*/
export default createSvgIcon(React.createElement("path", {
d: "M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"
}), 'CheckBoxOutlineBlank');
|
demo/src/index.js
|
insin/react-octicon
|
import React from 'react'
import {render} from 'react-dom'
import Demo from './Demo'
render(<Demo/>, document.querySelector('#demo'))
|
projects/react-redux/sample/app/src/index.js
|
stanleygomes/stanleygomes.github.io
|
import React from 'react';
import { render } from 'react-dom';
import router from './utils/router';
import '../styles/styles.scss';
const rootElement = document.getElementById('app');
render(router, rootElement);
|
test/DropdownButtonSpec.js
|
egauci/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import ReactDOM from 'react-dom';
import DropdownButton from '../src/DropdownButton';
import DropdownMenu from '../src/DropdownMenu';
import MenuItem from '../src/MenuItem';
describe('DropdownButton', () => {
const simpleDropdown = (
<DropdownButton title='Simple Dropdown' id='test-id'>
<MenuItem>Item 1</MenuItem>
<MenuItem>Item 2</MenuItem>
<MenuItem>Item 3</MenuItem>
<MenuItem>Item 4</MenuItem>
</DropdownButton>
);
it('renders title prop', () => {
const instance = ReactTestUtils.renderIntoDocument(simpleDropdown);
const buttonNode = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON');
buttonNode.innerText.should.match(/Simple Dropdown/);
});
it('renders dropdown toggle button', () => {
const instance = ReactTestUtils.renderIntoDocument(simpleDropdown);
const buttonNode = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON');
buttonNode.tagName.should.equal('BUTTON');
buttonNode.className.should.match(/\bbtn[ $]/);
buttonNode.className.should.match(/\bbtn-default\b/);
buttonNode.className.should.match(/\bdropdown-toggle\b/);
buttonNode.getAttribute('type').should.equal('button');
buttonNode.getAttribute('aria-expanded').should.equal('false');
buttonNode.getAttribute('id').should.be.ok;
});
it('renders single MenuItem child', () => {
const instance = ReactTestUtils.renderIntoDocument(
<DropdownButton title='Single child' id='test-id'>
<MenuItem>Item 1</MenuItem>
</DropdownButton>
);
const menuNode = ReactDOM.findDOMNode(
ReactTestUtils.findRenderedComponentWithType(instance, DropdownMenu));
expect(menuNode.children.length).to.equal(1);
});
it('forwards pullRight to menu', () => {
const instance = ReactTestUtils.renderIntoDocument(
<DropdownButton pullRight title='blah' id='test-id'>
<MenuItem>Item 1</MenuItem>
</DropdownButton>
);
const menu = ReactTestUtils.findRenderedComponentWithType(instance, DropdownMenu);
menu.props.pullRight.should.be.true;
});
it('renders bsSize', () => {
const instance = ReactTestUtils.renderIntoDocument(
<DropdownButton title='blah' bsSize='small' id='test-id'>
<MenuItem>Item 1</MenuItem>
</DropdownButton>
);
const node = ReactDOM.findDOMNode(instance);
node.className.should.match(/\bbtn-group-sm\b/);
});
it('renders bsStyle', () => {
const instance = ReactTestUtils.renderIntoDocument(
<DropdownButton title='blah' bsStyle='success' id='test-id'>
<MenuItem>Item 1</MenuItem>
</DropdownButton>
);
const buttonNode = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON');
buttonNode.className.should.match(/\bbtn-success\b/);
});
it('forwards onSelect handler to MenuItems', (done) => {
const selectedEvents = [];
const onSelect = (event, eventKey) => {
selectedEvents.push(eventKey);
if (selectedEvents.length === 4) {
selectedEvents.should.eql(['1', '2', '3', '4']);
done();
}
};
const instance = ReactTestUtils.renderIntoDocument(
<DropdownButton title='Simple Dropdown' onSelect={onSelect} id='test-id'>
<MenuItem eventKey='1'>Item 1</MenuItem>
<MenuItem eventKey='2'>Item 2</MenuItem>
<MenuItem eventKey='3'>Item 3</MenuItem>
<MenuItem eventKey='4'>Item 4</MenuItem>
</DropdownButton>
);
const menuItems = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'A');
menuItems.forEach(item => {
ReactTestUtils.Simulate.click(item);
});
});
it('closes when child MenuItem is selected', () => {
const instance = ReactTestUtils.renderIntoDocument(
<DropdownButton title='Simple Dropdown' id='test-id'>
<MenuItem eventKey='1'>Item 1</MenuItem>
</DropdownButton>
);
const node = ReactDOM.findDOMNode(instance);
const buttonNode = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON');
ReactTestUtils.Simulate.click(buttonNode);
node.className.should.match(/\bopen\b/);
const menuItem = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A');
ReactTestUtils.Simulate.click(menuItem);
node.className.should.not.match(/\bopen\b/);
});
it('does not close when onToggle is controlled', () => {
const handleSelect = () => {};
const instance = ReactTestUtils.renderIntoDocument(
<DropdownButton title='Simple Dropdown' open={true} onToggle={handleSelect} id='test-id'>
<MenuItem eventKey='1'>Item 1</MenuItem>
</DropdownButton>
);
const node = ReactDOM.findDOMNode(instance);
const buttonNode = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON');
const menuItem = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A');
ReactTestUtils.Simulate.click(buttonNode);
node.className.should.match(/\bopen\b/);
ReactTestUtils.Simulate.click(menuItem);
node.className.should.match(/\bopen\b/);
});
it('Should pass props to button', () => {
const instance = ReactTestUtils.renderIntoDocument(
<DropdownButton title="Title" bsStyle="primary" id="testId" disabled>
<MenuItem eventKey="1">MenuItem 1 content</MenuItem>
<MenuItem eventKey="2">MenuItem 2 content</MenuItem>
</DropdownButton>
);
const buttonNode = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON');
assert.ok(buttonNode.className.match(/\bbtn-primary\b/));
assert.equal(buttonNode.getAttribute('id'), 'testId');
assert.ok(buttonNode.disabled);
});
});
|
src/components/ControlPanel/ControlPanel.js
|
bocasfx/Q
|
import React from 'react';
import './ControlPanel.css';
import SelectorPanel from './SelectorPanel';
import EditorPanel from './EditorPanel';
import config from '../../config/config';
class ControlPanel extends React.Component {
constructor(props) {
super(props);
this.style = {
width: config.controlPanel.width,
};
}
render() {
return (
<div className="control-panel-container" style={this.style}>
<SelectorPanel />
<EditorPanel />
</div>
);
}
}
export default ControlPanel;
|
src/svg-icons/content/add-circle.js
|
ichiohta/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentAddCircle = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11h-4v4h-2v-4H7v-2h4V7h2v4h4v2z"/>
</SvgIcon>
);
ContentAddCircle = pure(ContentAddCircle);
ContentAddCircle.displayName = 'ContentAddCircle';
ContentAddCircle.muiName = 'SvgIcon';
export default ContentAddCircle;
|
docs/src/examples/elements/Header/Types/HeaderExampleContent.js
|
Semantic-Org/Semantic-UI-React
|
import React from 'react'
import { Header } from 'semantic-ui-react'
const HeaderExampleContent = () => (
<div>
<Header size='huge'>Huge Header</Header>
<Header size='large'>Large Header</Header>
<Header size='medium'>Medium Header</Header>
<Header size='small'>Small Header</Header>
<Header size='tiny'>Tiny Header</Header>
</div>
)
export default HeaderExampleContent
|
react/features/screen-share/components/ShareAudioDialog.js
|
gpolitis/jitsi-meet
|
// @flow
import { Checkbox } from '@atlaskit/checkbox';
import React, { Component } from 'react';
import type { Dispatch } from 'redux';
import { Dialog } from '../../base/dialog';
import { translate } from '../../base/i18n';
import { connect } from '../../base/redux';
import {
updateSettings,
shouldHideShareAudioHelper
} from '../../base/settings';
import { toggleScreensharing } from '../../base/tracks';
/**
* The type of the React {@code Component} props of {@link ShareAudioDialog}.
*/
export type Props = {
/**
* The redux {@code dispatch} function.
*/
dispatch: Dispatch<any>,
/**
* Boolean stored in local storage that determines whether or not the dialog will be displayed again.
*/
_shouldHideShareAudioHelper: boolean,
/**
* Invoked to obtain translated strings.
*/
t: Function
};
/**
* Component that displays the audio screen share helper dialog.
*/
class ShareAudioDialog extends Component<Props> {
/**
* Instantiates a new component.
*
* @inheritdoc
*/
constructor(props) {
super(props);
this._onContinue = this._onContinue.bind(this);
this._onSelectHideShareAudioHelper = this._onSelectHideShareAudioHelper.bind(this);
}
_onContinue: () => boolean;
/**
* Continue the normal screen sharing flow when the user clicks continue.
*
* @returns {boolean}
*/
_onContinue() {
// Pass undefined as the first parameter so the underlying logic decides weather or not to stop screen sharing.
this.props.dispatch(toggleScreensharing(undefined, true));
return true;
}
_onSelectHideShareAudioHelper: (Object) => void;
/**
* Callback invoked when the hide audio helper checkbox has been selected. This setting will be persisted in
* the local storage, thus the dialog won't be displayed again.
*
* @param {Object} e - The key event to handle.
* @returns {void}
*/
_onSelectHideShareAudioHelper({ target: { checked } }) {
this.props.dispatch(updateSettings({ hideShareAudioHelper: checked }));
}
/**
* Implements {@Component#render}.
*
* @inheritdoc
*/
render() {
const { t } = this.props;
return (
<Dialog
hideCancelButton = { false }
okKey = { t('dialog.shareAudio') }
onSubmit = { this._onContinue }
titleKey = { t('dialog.shareAudioTitle') }
width = { 'medium' } >
<div className = 'share-audio-dialog'>
<img
className = 'share-audio-animation'
src = 'images/share-audio.gif' />
<Checkbox
isChecked = { this.props._shouldHideShareAudioHelper }
label = { t('dialog.hideShareAudioHelper') }
name = 'hide-share-audio-helper'
// eslint-disable-next-line react/jsx-no-bind
onChange = { this._onSelectHideShareAudioHelper } />
</div>
</Dialog>
);
}
}
/**
* Maps part of the Redux state to the props of this component.
*
* @param {Object} state - The Redux state.
* @private
* @returns {Props}
*/
function _mapStateToProps(state: Object): $Shape<Props> {
return {
_shouldHideShareAudioHelper: shouldHideShareAudioHelper(state)
};
}
export default translate(connect(_mapStateToProps)(ShareAudioDialog));
|
docs/app/Examples/views/Card/Content/CardExampleHeaderCard.js
|
Rohanhacker/Semantic-UI-React
|
import React from 'react'
import { Card } from 'semantic-ui-react'
const CardExampleHeaderCard = () => (
<Card.Group>
<Card>
<Card.Content>
<Card.Header>Matthew Harris</Card.Header>
<Card.Meta>Co-Worker</Card.Meta>
<Card.Description>Matthew is a pianist living in Nashville.</Card.Description>
</Card.Content>
</Card>
<Card>
<Card.Content>
<Card.Header content='Jake Smith' />
<Card.Meta content='Musicians' />
<Card.Description content='Jake is a drummer living in New York.' />
</Card.Content>
</Card>
<Card>
<Card.Content
header='Elliot Baker'
meta='Friend'
description='Elliot is a music producer living in Chicago.'
/>
</Card>
<Card
header='Jenny Hess'
meta='Friend'
description='Jenny is a student studying Media Management at the New School'
/>
</Card.Group>
)
export default CardExampleHeaderCard
|
Console/app/node_modules/antd/es/input-number/index.js
|
RisenEsports/RisenEsports.github.io
|
import _extends from 'babel-runtime/helpers/extends';
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';
var __rest = this && this.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]];
}return t;
};
import React from 'react';
import classNames from 'classnames';
import RcInputNumber from 'rc-input-number';
var InputNumber = function (_React$Component) {
_inherits(InputNumber, _React$Component);
function InputNumber() {
_classCallCheck(this, InputNumber);
return _possibleConstructorReturn(this, (InputNumber.__proto__ || Object.getPrototypeOf(InputNumber)).apply(this, arguments));
}
_createClass(InputNumber, [{
key: 'render',
value: function render() {
var _classNames;
var _a = this.props,
className = _a.className,
size = _a.size,
others = __rest(_a, ["className", "size"]);
var inputNumberClass = classNames((_classNames = {}, _defineProperty(_classNames, this.props.prefixCls + '-lg', size === 'large'), _defineProperty(_classNames, this.props.prefixCls + '-sm', size === 'small'), _classNames), className);
return React.createElement(RcInputNumber, _extends({ className: inputNumberClass }, others));
}
}]);
return InputNumber;
}(React.Component);
export default InputNumber;
InputNumber.defaultProps = {
prefixCls: 'ant-input-number',
step: 1
};
|
src/components/Navbar/Navbar.js
|
uiruson/chorongi
|
/*
* React.js Starter Kit
* Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
'use strict';
import React from 'react';
var Navbar = React.createClass({
render() {
return (
/* jshint ignore:start */
<div className="navbar-top" role="navigation">
<div className="container">
<a className="navbar-brand row" href="/">
<img src={require('./logo-small.png')} width="38" height="38" alt="React" />
<span>React.js Starter Kit</span>
</a>
</div>
</div>
/* jshint ignore:end */
);
}
});
module.exports = Navbar;
|
src/Input.js
|
buildo/rc-datepicker
|
import React from 'react';
import cx from 'classnames';
import { props } from 'tcomb-react';
import t from 'tcomb';
import View from 'react-flexview';
import skinnable from './utils/skinnable';
import pure from './utils/pure';
@pure
@skinnable()
@props({
value: t.maybe(t.String),
onInputChange: t.Function,
iconClearClassName: t.String,
iconClassName: t.String,
hasValue: t.Boolean,
active: t.Boolean,
small: t.Boolean,
onButtonClick: t.maybe(t.Function),
onInputClick: t.maybe(t.Function),
onInputClear: t.maybe(t.Function),
onInputKeyUp: t.Function
}, { strict: false })
export default class Input extends React.Component {
getLocals(props) {
const {
value,
iconClearClassName,
iconClassName,
hasValue,
active,
small,
onButtonClick,
onInputClick,
onInputChange,
onInputClear,
onInputKeyUp,
...inputProps
} = props;
return {
className: cx('react-datepicker-input', {
'is-open': active,
'has-value': hasValue,
'is-small': small
}),
inputButtonProps: onButtonClick && {
onButtonClick, iconClassName,
className: cx('input-button', { active })
},
clearButtonProps: onInputClear && hasValue && {
onInputClear, iconClearClassName
},
inputProps: {
value,
onChange: onInputChange,
onClick: onInputClick,
onKeyUp: onInputKeyUp,
...inputProps
}
};
}
templateInputButton({ className, onButtonClick, iconClassName }) {
return (
<View shrink={false} className={className} onClick={onButtonClick}>
<i className={iconClassName} />
</View>
);
}
templateClearButton({ onInputClear, iconClearClassName }) {
return (
<View shrink={false} className='clear-button' onClick={onInputClear}>
<i className={iconClearClassName} />
</View>
);
}
template({ className, inputButtonProps, clearButtonProps, inputProps }) {
return (
<div className={className}>
<input {...inputProps} />
<View className='button-wrapper' vAlignContent='center'>
{clearButtonProps && this.templateClearButton(clearButtonProps)}
{inputButtonProps && this.templateInputButton(inputButtonProps)}
</View>
</div>
);
}
}
|
docs/src/Routes.js
|
SSLcom/Bootsharp
|
import React from 'react';
import { IndexRoute, Route } from 'react-router';
import ComponentsPage from './ComponentsPage';
import NotFoundPage from './NotFoundPage';
import Root from './Root';
export default (
<Route path="/" component={Root}>
<IndexRoute component={ComponentsPage} />
<Route path="components.html" component={ComponentsPage} />
<Route path="*" component={NotFoundPage} />
</Route>
);
|
__tests__/index.android.js
|
zhuifeng740643787/gougouApp
|
import 'react-native';
import React from 'react';
import Index from '../index.android.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
src/logo.js
|
coma/spotify
|
import React from 'react';
import style from './logo.css';
class Logo extends React.Component {
render () {
return (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 45 40" className={ style.main }>
<path className={ style.a } d="M45,25c0,9.32 -10.074,15 -22.5,15c-12.426,0 -22.5,-5.68 -22.5,-15c0,-9.32 10.074,-18.75 22.5,-18.75c12.426,0 22.5,9.43 22.5,18.75"/>
<path className={ style.b } d="M39.694,13.345c1.71,-1.375 2.806,-3.482 2.806,-5.845c0,-4.142 -3.358,-7.5 -7.5,-7.5c-3.576,0 -6.563,2.506 -7.313,5.856c-1.611,-0.604 -3.355,-0.948 -5.187,-0.948c-1.831,0 -3.576,0.344 -5.186,0.948c-0.752,-3.35 -3.738,-5.856 -7.314,-5.856c-4.141,0 -7.5,3.358 -7.5,7.5c0,2.363 1.097,4.47 2.806,5.845c-3.306,3.35 -5.306,7.511 -5.306,11.655c0,9.32 10.074,1.25 22.5,1.25c12.427,0 22.5,8.07 22.5,-1.25c0,-4.144 -1.999,-8.305 -5.306,-11.655"/>
<path className={ style.c } d="M13.75,6.875c0,2.416 -1.959,4.375 -4.375,4.375c-2.416,0 -4.375,-1.959 -4.375,-4.375c0,-2.416 1.959,-4.375 4.375,-4.375c2.416,0 4.375,1.959 4.375,4.375"/>
<path className={ style.d } d="M11.25,6.875c0,1.036 -0.839,1.875 -1.875,1.875c-1.036,0 -1.875,-0.839 -1.875,-1.875c0,-1.036 0.839,-1.875 1.875,-1.875c1.036,0 1.875,0.839 1.875,1.875"/>
<path className={ style.c } d="M40,6.875c0,2.416 -1.958,4.375 -4.375,4.375c-2.418,0 -4.375,-1.959 -4.375,-4.375c0,-2.416 1.957,-4.375 4.375,-4.375c2.417,0 4.375,1.959 4.375,4.375"/>
<path className={ style.d } d="M37.5,6.875c0,1.036 -0.84,1.875 -1.875,1.875c-1.035,0 -1.875,-0.839 -1.875,-1.875c0,-1.036 0.84,-1.875 1.875,-1.875c1.035,0 1.875,0.839 1.875,1.875"/>
<path className={ style.e } d="M18.75,22.5c0,0.691 -0.56,1.25 -1.25,1.25c-0.69,0 -1.25,-0.559 -1.25,-1.25c0,-0.691 0.56,-1.25 1.25,-1.25c0.69,0 1.25,0.559 1.25,1.25"/>
<path className={ style.e } d="M28.75,22.5c0,0.691 -0.559,1.25 -1.25,1.25c-0.691,0 -1.25,-0.559 -1.25,-1.25c0,-0.691 0.559,-1.25 1.25,-1.25c0.691,0 1.25,0.559 1.25,1.25"/>
</svg>
);
}
}
export default Logo;
|
app/javascript/mastodon/features/compose/containers/warning_container.js
|
WitchesTown/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import Warning from '../components/warning';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { me } from '../../../initial_state';
const APPROX_HASHTAG_RE = /(?:^|[^\/\)\w])#(\w*[a-zA-Z·]\w*)/i;
const mapStateToProps = state => ({
needsLockWarning: state.getIn(['compose', 'privacy']) === 'private' && !state.getIn(['accounts', me, 'locked']),
hashtagWarning: state.getIn(['compose', 'privacy']) !== 'public' && APPROX_HASHTAG_RE.test(state.getIn(['compose', 'text'])),
});
const WarningWrapper = ({ needsLockWarning, hashtagWarning }) => {
if (needsLockWarning) {
return <Warning message={<FormattedMessage id='compose_form.lock_disclaimer' defaultMessage='Your account is not {locked}. Anyone can follow you to view your follower-only posts.' values={{ locked: <a href='/settings/profile'><FormattedMessage id='compose_form.lock_disclaimer.lock' defaultMessage='locked' /></a> }} />} />;
}
if (hashtagWarning) {
return <Warning message={<FormattedMessage id='compose_form.hashtag_warning' defaultMessage="This toot won't be listed under any hashtag as it is unlisted. Only public toots can be searched by hashtag." />} />;
}
return null;
};
WarningWrapper.propTypes = {
needsLockWarning: PropTypes.bool,
hashtagWarning: PropTypes.bool,
};
export default connect(mapStateToProps)(WarningWrapper);
|
src/containers/SearchFormContainer.js
|
blwoosky/DigCSS-Theme-v4-Redesign
|
import React, { Component } from 'react';
import SearchForm from "./../components/SearchForm";
import { Link,browserHistory } from 'react-router';
import { connect } from "react-redux";
import { search } from "./../actions";
export default class SearchFormContainer extends Component {
constructor(props) {
super(props);
this.onInputChange = this.onInputChange.bind(this);
this.onSearch = this.onSearch.bind(this);
this.state = {
keyword: ""
}
}
onInputChange(e) {
this.setState({
keyword: e.target.value
});
//console.log(this.state.keyword);
}
onSearch(e) {
e.preventDefault();
this.props.setOpened(false);
this.setState({
keyword: ""
});
browserHistory.push(`/search/${this.state.keyword}`);
}
render() {
return (
<SearchForm keyword={this.state.keyword} {...this.props} {...this}/>
)
}
}
//function mapStateToProps(store) {
// return {
// list: store.search.list,
// pageNum: store.search.pageNum,
// totalPages: store.search.totalPages
// };
//}
export default connect(null, {search})(SearchFormContainer);
|
src/Fade.js
|
mengmenglv/react-bootstrap
|
import React from 'react';
import Transition from 'react-overlays/lib/Transition';
import CustomPropTypes from './utils/CustomPropTypes';
import deprecationWarning from './utils/deprecationWarning';
class Fade extends React.Component {
render() {
let timeout = this.props.timeout || this.props.duration;
return (
<Transition
{...this.props}
timeout={timeout}
className="fade"
enteredClassName="in"
enteringClassName="in"
>
{this.props.children}
</Transition>
);
}
}
// Explicitly copied from Transition for doc generation.
// TODO: Remove duplication once #977 is resolved.
Fade.propTypes = {
/**
* Show the component; triggers the fade in or fade out animation
*/
in: React.PropTypes.bool,
/**
* Unmount the component (remove it from the DOM) when it is faded out
*/
unmountOnExit: React.PropTypes.bool,
/**
* Run the fade in animation when the component mounts, if it is initially
* shown
*/
transitionAppear: React.PropTypes.bool,
/**
* Duration of the fade animation in milliseconds, to ensure that finishing
* callbacks are fired even if the original browser transition end events are
* canceled
*/
timeout: React.PropTypes.number,
/**
* duration
* @private
*/
duration: CustomPropTypes.all([
React.PropTypes.number,
(props)=> {
if (props.duration != null) {
deprecationWarning('Fade `duration`', 'the `timeout` prop');
}
return null;
}
]),
/**
* Callback fired before the component fades in
*/
onEnter: React.PropTypes.func,
/**
* Callback fired after the component starts to fade in
*/
onEntering: React.PropTypes.func,
/**
* Callback fired after the has component faded in
*/
onEntered: React.PropTypes.func,
/**
* Callback fired before the component fades out
*/
onExit: React.PropTypes.func,
/**
* Callback fired after the component starts to fade out
*/
onExiting: React.PropTypes.func,
/**
* Callback fired after the component has faded out
*/
onExited: React.PropTypes.func
};
Fade.defaultProps = {
in: false,
timeout: 300,
unmountOnExit: false,
transitionAppear: false
};
export default Fade;
|
src/routes.js
|
ProjectSunday/rooibus
|
import React from 'react'
import { Route, IndexRoute } from 'react-router'
import About from './components/about'
import Root from './components/root'
import FriendMap from './components/friend-map'
import Session from './components/session'
export default (
<Route path="/" component={Root}>
<IndexRoute component={FriendMap} />
<Route path="/about" component={About} />
<Route path="/:mapId" component={Session} />
</Route>
)
|
src/components/Copy/spec.js
|
hasibsahibzada/quran.com-frontend
|
import React from 'react';
import { shallow } from 'enzyme';
import Copy from './index';
const text = 'Some text';
let wrapper;
describe('<Copy />', () => {
beforeEach(() => {
wrapper = shallow(<Copy text={text} />);
});
it('should render', () => {
expect(wrapper).to.be.ok; // eslint-disable-line
});
});
|
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/components/Apis/Listing/MoreMenu.js
|
Minoli/carbon-apimgt
|
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Button from 'material-ui/Button';
import Grow from 'material-ui/transitions/Grow';
import Paper from 'material-ui/Paper';
import { withStyles } from 'material-ui/styles';
import { Manager, Target, Popper } from 'react-popper';
import ClickAwayListener from 'material-ui/utils/ClickAwayListener';
import MoreHoriz from '@material-ui/icons/MoreHoriz';
import List, {ListItem, ListItemText} from 'material-ui/List';
import {Link} from 'react-router-dom'
const styles = {
root: {
display: 'flex',
zIndex: 1202,
position: 'absolute',
marginTop: -20,
left: 190,
},
popperClose: {
pointerEvents: 'none',
},
moreButton: {
backgroundColor: '#4c4c4c',
minWidth: 55,
minHeight: 20,
color: '#fff',
padding: 0,
}
};
class MoreMenu extends React.Component {
state = {
open: false,
};
handleClick = () => {
this.setState({ open: true });
};
handleClose = () => {
this.setState({ open: false });
};
render() {
const { classes } = this.props;
const { open } = this.state;
const tabs = [
"overview",
"lifecycle",
"endpoints",
"resources",
"scopes",
"documents",
"permission",
"mediation",
"scripting",
"subscriptions",
"security"
];
return (
<div className={classes.root}>
<Manager>
<Target>
<Button
aria-owns={open ? 'menu-list' : null}
aria-haspopup="true"
onClick={this.handleClick}
className={classes.moreButton}
variant="raised"
>
<MoreHoriz />
</Button>
</Target>
<Popper
placement="bottom-start"
eventsEnabled={open}
className={classNames({ [classes.popperClose]: !open })}
>
<ClickAwayListener onClickAway={this.handleClose}>
<Grow in={open} id="menu-list" style={{ transformOrigin: '0 0 0' }}>
<Paper>
<List>
{tabs.map(tab =>
(<ListItem key={tab}>
<Link name={tab} to={"/apis/" + this.props.api_uuid + "/" + tab}>
<ListItemText primary={tab}/></Link>
</ListItem>)
)}
</List>
</Paper>
</Grow>
</ClickAwayListener>
</Popper>
</Manager>
</div>
);
}
}
MoreMenu.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(MoreMenu);
|
app/javascript/mastodon/components/status_content.js
|
tootcafe/mastodon
|
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import Permalink from './permalink';
import classnames from 'classnames';
import PollContainer from 'mastodon/containers/poll_container';
import Icon from 'mastodon/components/icon';
import { autoPlayGif } from 'mastodon/initial_state';
const MAX_HEIGHT = 642; // 20px * 32 (+ 2px padding at the top)
export default class StatusContent extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
expanded: PropTypes.bool,
showThread: PropTypes.bool,
onExpandedToggle: PropTypes.func,
onClick: PropTypes.func,
collapsable: PropTypes.bool,
onCollapsedToggle: PropTypes.func,
};
state = {
hidden: true,
};
_updateStatusLinks () {
const node = this.node;
if (!node) {
return;
}
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.classList.add('unhandled-link');
}
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer');
}
if (this.props.status.get('collapsed', null) === null) {
let collapsed =
this.props.collapsable
&& this.props.onClick
&& node.clientHeight > MAX_HEIGHT
&& this.props.status.get('spoiler_text').length === 0;
if(this.props.onCollapsedToggle) this.props.onCollapsedToggle(collapsed);
this.props.status.set('collapsed', collapsed);
}
}
handleMouseEnter = ({ currentTarget }) => {
if (autoPlayGif) {
return;
}
const emojis = currentTarget.querySelectorAll('.custom-emoji');
for (var i = 0; i < emojis.length; i++) {
let emoji = emojis[i];
emoji.src = emoji.getAttribute('data-original');
}
}
handleMouseLeave = ({ currentTarget }) => {
if (autoPlayGif) {
return;
}
const emojis = currentTarget.querySelectorAll('.custom-emoji');
for (var i = 0; i < emojis.length; i++) {
let emoji = emojis[i];
emoji.src = emoji.getAttribute('data-static');
}
}
componentDidMount () {
this._updateStatusLinks();
}
componentDidUpdate () {
this._updateStatusLinks();
}
onMentionClick = (mention, e) => {
if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(`/accounts/${mention.get('id')}`);
}
}
onHashtagClick = (hashtag, e) => {
hashtag = hashtag.replace(/^#/, '');
if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
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)];
let element = e.target;
while (element) {
if (element.localName === 'button' || element.localName === 'a' || element.localName === 'label') {
return;
}
element = element.parentNode;
}
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 renderReadMore = this.props.onClick && status.get('collapsed');
const renderViewThread = this.props.showThread && status.get('in_reply_to_id') && status.get('in_reply_to_account_id') === status.getIn(['account', 'id']);
const content = { __html: status.get('contentHtml') };
const spoilerContent = { __html: status.get('spoilerHtml') };
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,
'status__content--collapsed': renderReadMore,
});
const showThreadButton = (
<button className='status__content__read-more-button' onClick={this.props.onClick}>
<FormattedMessage id='status.show_thread' defaultMessage='Show thread' />
</button>
);
const readMoreButton = (
<button className='status__content__read-more-button' onClick={this.props.onClick} key='read-more'>
<FormattedMessage id='status.read_more' defaultMessage='Read more' /><Icon id='angle-right' fixedWidth />
</button>
);
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} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>
<p style={{ marginBottom: hidden && status.get('mentions').isEmpty() ? '0px' : null }}>
<span dangerouslySetInnerHTML={spoilerContent} className='translate' />
{' '}
<button tabIndex='0' className={`status__content__spoiler-link ${hidden ? 'status__content__spoiler-link--show-more' : 'status__content__spoiler-link--show-less'}`} onClick={this.handleSpoilerClick}>{toggleText}</button>
</p>
{mentionsPlaceholder}
<div tabIndex={!hidden ? 0 : null} className={`status__content__text ${!hidden ? 'status__content__text--visible' : ''} translate`} dangerouslySetInnerHTML={content} />
{!hidden && !!status.get('poll') && <PollContainer pollId={status.get('poll')} />}
{renderViewThread && showThreadButton}
</div>
);
} else if (this.props.onClick) {
const output = [
<div className={classNames} ref={this.setRef} tabIndex='0' onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} key='status-content' onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>
<div className='status__content__text status__content__text--visible translate' dangerouslySetInnerHTML={content} />
{!!status.get('poll') && <PollContainer pollId={status.get('poll')} />}
{renderViewThread && showThreadButton}
</div>,
];
if (renderReadMore) {
output.push(readMoreButton);
}
return output;
} else {
return (
<div className={classNames} ref={this.setRef} tabIndex='0' onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>
<div className='status__content__text status__content__text--visible translate' dangerouslySetInnerHTML={content} />
{!!status.get('poll') && <PollContainer pollId={status.get('poll')} />}
{renderViewThread && showThreadButton}
</div>
);
}
}
}
|
__tests__/index.android.js
|
TrungSpy/React-Native-SampleProject
|
import 'react-native';
import React from 'react';
import Index from '../index.android.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
generators/app/templates/app/test/static/js/components/form.spec.js
|
TFarla/generator-phoenix-react
|
import React from 'react';
import Chai, {expect} from 'chai';
import sinon from 'sinon';
import {mount} from 'enzyme';
import sinonChai from 'sinon-chai';
import Form from '<%= atomName %>/components/form';
Chai.use(sinonChai);
describe('Form', () => {
it('submits a message', () => {
const handleSubmit = sinon.spy();
const wrapper = mount(
<Form handleSubmit={handleSubmit} />
);
const message = 'Hello, my name is Bob!';
const {node} = wrapper.find('input');
node.value = message;
wrapper.find('form').simulate('submit');
expect(handleSubmit).to.have.been.calledWith(message);
expect(node.value).to.equal('');
});
});
|
src/components/pages/PatientsSummary/patients-summary.config.js
|
PulseTile/PulseTile-React
|
import React from 'react';
import { get } from 'lodash';
import { themePatientSummaryConfig } from '../../theme/config/plugins';
import {
allergiesPrevImage,
problemsPrevImage,
contactsPrevImage,
medicationsPrevImage,
} from './ImageSources';
import { themeConfigs } from '../../../themes.config';
import { isPluginVisible, rangePlugins } from '../../../utils/themeSettings-helper';
const problemsTitle = get(themeConfigs.patientsSummaryTitles, 'diagnoses', 'Problems / Diagnosis');
const contactsTitle = get(themeConfigs.patientsSummaryTitles, 'contacts', 'Contacts');
const allergiesTitle = get(themeConfigs.patientsSummaryTitles, 'allergies', 'Allergies');
const medicationsTitle = get(themeConfigs.patientsSummaryTitles, 'medications', 'Medications');
const corePatientsSummaryConfig = [
{
key: 'problems',
panelId: 'summary-panel-problems',
title: problemsTitle,
emptyMessage: 'No information available',
state: 'diagnoses',
titleCheckboxes: problemsTitle,
nameCheckboxes: 'problems',
imgPreview: problemsPrevImage,
isDefaultSelected: true,
}, {
key: 'contacts',
panelId: 'summary-panel-contacts',
title: contactsTitle,
emptyMessage: 'No information available',
titleCheckboxes: contactsTitle,
state: 'contacts',
nameCheckboxes: 'contacts',
imgPreview: contactsPrevImage,
isDefaultSelected: true,
}, {
key: 'allergies',
panelId: 'summary-panel-allergies',
title: allergiesTitle,
emptyMessage: 'No information available',
titleCheckboxes: allergiesTitle,
state: 'allergies',
nameCheckboxes: 'allergies',
imgPreview: allergiesPrevImage,
isDefaultSelected: true,
}, {
key: 'medications',
panelId: 'summary-panel-medications',
title: medicationsTitle,
emptyMessage: 'No information available',
titleCheckboxes: medicationsTitle,
state: 'medications',
nameCheckboxes: 'medications',
imgPreview: medicationsPrevImage,
isDefaultSelected: true,
},
];
/**
* This constant returns list of pattient summary plugins, excluded corePluginsToHide (themes settings)
*
* @return {array}
*/
const filterPatientsSummaryConfig = corePatientsSummaryConfig.filter(item => {
const hiddenCorePlugins = get(themeConfigs, 'corePluginsToHide', []);
return isPluginVisible(hiddenCorePlugins, item.state);
});
const totalSummaryConfig = filterPatientsSummaryConfig.concat(themePatientSummaryConfig);
export const patientsSummaryConfig = rangePlugins(totalSummaryConfig);
export const defaultViewOfBoardsSelected = {
full: true,
preview: false,
list: false,
};
|
node_modules/react-bootstrap/es/Table.js
|
xuan6/admin_dashboard_local_dev
|
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
striped: PropTypes.bool,
bordered: PropTypes.bool,
condensed: PropTypes.bool,
hover: PropTypes.bool,
responsive: PropTypes.bool
};
var defaultProps = {
bordered: false,
condensed: false,
hover: false,
responsive: false,
striped: false
};
var Table = function (_React$Component) {
_inherits(Table, _React$Component);
function Table() {
_classCallCheck(this, Table);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Table.prototype.render = function render() {
var _extends2;
var _props = this.props,
striped = _props.striped,
bordered = _props.bordered,
condensed = _props.condensed,
hover = _props.hover,
responsive = _props.responsive,
className = _props.className,
props = _objectWithoutProperties(_props, ['striped', 'bordered', 'condensed', 'hover', 'responsive', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, 'striped')] = striped, _extends2[prefix(bsProps, 'bordered')] = bordered, _extends2[prefix(bsProps, 'condensed')] = condensed, _extends2[prefix(bsProps, 'hover')] = hover, _extends2));
var table = React.createElement('table', _extends({}, elementProps, {
className: classNames(className, classes)
}));
if (responsive) {
return React.createElement(
'div',
{ className: prefix(bsProps, 'responsive') },
table
);
}
return table;
};
return Table;
}(React.Component);
Table.propTypes = propTypes;
Table.defaultProps = defaultProps;
export default bsClass('table', Table);
|
developers.diem.com/src/pages/index.js
|
libra/libra
|
import React from 'react';
import {Redirect} from '@docusaurus/router';
import useBaseUrl from '@docusaurus/useBaseUrl';
function Home() {
return <Redirect to={useBaseUrl('/docs/welcome-to-diem/')} />;
}
export default Home;
|
lib/Card.js
|
robbiegreiner/weathrly
|
import React from 'react';
const Card = ({
time,
condition,
img,
temp,
}) => {
return (
<div className='card'>
<p className='time'>{time}</p>
<div className='card-condition'>
<p>{condition}</p>
</div>
<div className='img-background'>
<img src={img} alt={condition}/>
</div>
<p className='temp'>{temp}</p>
</div>
);
};
export default Card;
|
src/containers/layout/List/List.js
|
max-gram/react-saga-universal
|
import React from 'react'
import PropTypes from 'prop-types'
import { Grid, Row } from 'react-flexbox-grid'
import css from './List.css'
const List = ({children, className}) => {
return (
<section className={className ? className : css.section}>
<Grid fluid>
<Row middle="xs" className={css.row}>
{children}
</Row>
</Grid>
</section>
)
}
List.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string,
}
export default List
|
docs/Documentation/DatePickerPage.js
|
reactivers/react-mcw
|
/**
* Created by muratguney on 29/03/2017.
*/
import React from 'react';
import {Card, IconButton,CardHeader,DatePicker,Table, TableRow, TableHeaderColumn, TableHeader, TableRowColumn, TableBody} from '../../lib';
import Highlight from 'react-highlight.js'
export default class ChipPage extends React.Component {
state = {dialog: false, open: false};
render() {
let document = `
<div>
<DatePicker/>
<DatePicker value="Fri Apr 30 2027 23:47:26 GMT+0300 (+03)"/>
<DatePicker value="Fri Apr 30 2017 23:47:26 GMT+0300 (+03)" open={this.state.open} onClose={this.closeDatepicker} />
<IconButton onClick={this.openDatePicker} iconName={"date_range"}/>
</div>
`;
return (
<Card style={{padding: 8}}>
<CardHeader title="DatePicker"/>
<div style={{margin: "0 auto"}}>
<DatePicker/>
<div style={{padding: 16}}></div>
<DatePicker value="Fri Apr 30 2027 23:47:26 GMT+0300 (+03)"/>
<div style={{padding: 16}}></div>
<DatePicker value="Fri Apr 30 2017 23:47:26 GMT+0300 (+03)" open={this.state.open}
onClose={() => this.setState({open: false})}/>
<IconButton onClick={() => this.setState({open: true})} iconName={"date_range"}/>
</div>
<Highlight language="javascript">{document}</Highlight>
<CardHeader title="Datepicker properties"/>
<Table>
<TableHeader>
<TableRow>
<TableHeaderColumn>Props</TableHeaderColumn>
<TableHeaderColumn>Type</TableHeaderColumn>
<TableHeaderColumn>Description</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody>
<TableRow>
<TableRowColumn>open</TableRowColumn>
<TableRowColumn>Boolean</TableRowColumn>
<TableRowColumn>If true, dialog opens as dialog and shows cancel and ok buttons.</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>value</TableRowColumn>
<TableRowColumn>Date</TableRowColumn>
<TableRowColumn>You can send a date as string.</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>onClose</TableRowColumn>
<TableRowColumn>Function</TableRowColumn>
<TableRowColumn>Fire when dialog close.</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>onChange</TableRowColumn>
<TableRowColumn>Function</TableRowColumn>
<TableRowColumn>Gets value of date.</TableRowColumn>
</TableRow>
</TableBody>
</Table>
</Card>
)
}
}
|
blueocean-material-icons/src/js/components/svg-icons/image/wb-sunny.js
|
jenkinsci/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const ImageWbSunny = (props) => (
<SvgIcon {...props}>
<path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/>
</SvgIcon>
);
ImageWbSunny.displayName = 'ImageWbSunny';
ImageWbSunny.muiName = 'SvgIcon';
export default ImageWbSunny;
|
tp-3/juan-pablo-gonzalez/src/components/Root.js
|
solp/sovos-reactivo-2017
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import App from './App';
import { BrowserRouter as Router } from 'react-router-dom';
export default class Root extends Component {
render() {
return (
<Router>
<App />
</Router>
);
}
}
Root.propTypes = {
history: PropTypes.object
};
|
src/containers/LandingPage/AboutPidc/index.js
|
westoncolemanl/tabbr-web
|
import React from 'react'
import Body from './Body'
export default () => {
window.scrollTo(0, 0)
return (
<div>
<Body />
</div>
)
}
|
app/components/EarningsTableFooter/index.js
|
projectcashmere/web-server
|
/**
*
* EarningsTableFooter
*
*/
import React from 'react';
import styled from 'styled-components';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
const Table = styled.table`
background-color: grey;
color: white;
height: 40px;
margin: 5px;
margin-bottom: 20px;
width: 100%;
`;
function EarningsTableFooter(props) {
return (
<div>
<Table>
<tbody>
<tr className='row'>
<td className='col-sm-6'>TOTAL</td>
<td className='col-sm-2'>{props.roomIncomeTotal}</td>
<td className='col-sm-2'>{props.addIncomeTotal}</td>
<td className='col-sm-2'>{props.roomIncomeTotal + props.addIncomeTotal}</td>
</tr>
</tbody>
</Table>
</div>
);
}
EarningsTableFooter.propTypes = {
};
export default EarningsTableFooter;
|
packages/react/src/components/ErrorBoundary/ErrorBoundary.js
|
carbon-design-system/carbon-components
|
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import { ErrorBoundaryContext } from './ErrorBoundaryContext';
/**
* React introduced additional lifecycle methods in v16 for capturing errors
* that occur in a specific sub-tree of components. This component helps to
* consolidate some of the duplication that occurs when using these lifecycle
* methods across a codebase. In addition, it allows you to specify the fallback
* UI to display when an error occurs in the sub-tree through the `fallback`
* prop.
*
* This component roughly follows the React.js docs example code for these
* methods. In addition, it takes advantage of an `ErrorBoundaryContext` so that
* consumers can specify their own logic for logging errors. For example,
* reporting an error in the UI to an external service for every `ErrorBoundary`
* used.
*
* Reference:
* https://reactjs.org/docs/error-boundaries.html#introducing-error-boundaries
*/
export default class ErrorBoundary extends React.Component {
static propTypes = {
children: PropTypes.node,
fallback: PropTypes.node,
};
static contextType = ErrorBoundaryContext;
static getDerivedStateFromError() {
return {
hasError: true,
};
}
state = {
hasError: false,
};
componentDidCatch(error, info) {
this.context.log(error, info);
}
componentDidUpdate(prevProps) {
if (prevProps.children !== this.props.children) {
this.setState({ hasError: false });
}
}
render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}
|
app/jsx/external_apps/components/AppDetails.js
|
djbender/canvas-lms
|
/*
* Copyright (C) 2014 - 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 I18n from 'i18n!external_tools'
import React from 'react'
import PropTypes from 'prop-types'
import page from 'page'
import Header from './Header'
import AddApp from './AddApp'
import 'compiled/jquery.rails_flash_notifications'
export default class AppDetails extends React.Component {
static propTypes = {
store: PropTypes.object.isRequired,
baseUrl: PropTypes.string.isRequired,
shortName: PropTypes.string.isRequired
}
state = {
app: null
}
componentDidMount() {
const app = this.props.store.findAppByShortName(this.props.shortName)
if (app) {
this.setState({app})
} else {
page('/')
}
}
handleToolInstalled = () => {
const app = this.state.app
app.is_installed = true
this.setState({app})
this.props.store.flagAppAsInstalled(app.short_name)
this.props.store.setState({filter: 'installed', filterText: ''})
$.flashMessage(I18n.t('The app was added successfully'))
page('/')
}
alreadyInstalled = () => {
if (this.state.app.is_installed) {
return <div className="gray-box-centered">{I18n.t('Installed')}</div>
}
}
render() {
if (!this.state.app) {
return <img src="/images/ajax-loader-linear.gif" />
}
return (
<div className="AppDetails">
<Header>
<a
href={`${this.props.baseUrl}/configurations`}
className="btn view_tools_link lm pull-right"
>
{I18n.t('View App Configurations')}
</a>
<a href={this.props.baseUrl} className="btn view_tools_link lm pull-right">
{I18n.t('View App Center')}
</a>
</Header>
<div className="app_full">
<table className="individual-app">
<tbody>
<tr>
<td className="individual-app-left" valign="top">
<div className="app">
<img className="img-polaroid" src={this.state.app.banner_image_url} />
{this.alreadyInstalled()}
</div>
<AddApp
ref="addAppButton"
app={this.state.app}
handleToolInstalled={this.handleToolInstalled}
/>
<a href={this.props.baseUrl} className="app_cancel">
« {I18n.t('Back to App Center')}
</a>
</td>
<td className="individual-app-right" valign="top">
<h2 ref="appName">{this.state.app.name}</h2>
<p
ref="appDescription"
dangerouslySetInnerHTML={{__html: this.state.app.description}}
/>
</td>
</tr>
</tbody>
</table>
</div>
</div>
)
}
}
|
src/icons/index.stories.js
|
resmio/mantecao
|
import React from 'react'
import { storiesOf } from '@storybook/react'
import AddIcon from './AddIcon'
import ArrivedIcon from './ArrivedIcon'
import ArrowIcon from './ArrowIcon'
import BlankIcon from './BlankIcon'
import BookIcon from './BookIcon'
import BookingIcon from './BookingIcon'
import CalendarIcon from './CalendarIcon'
import CheckIcon from './CheckIcon'
import CloseIcon from './CloseIcon'
import CreditIcon from './CreditIcon'
import DotDotDotIcon from './DotDotDotIcon'
import EditIcon from './EditIcon'
import EmailIcon from './EmailIcon'
import ErrorIcon from './ErrorIcon'
import EyeClosedIcon from './EyeClosedIcon'
import FinishedIcon from './FinishedIcon'
import GuestIcon from './GuestIcon'
import GuestsIcon from './GuestsIcon'
import InfoIcon from './InfoIcon'
import LockedIcon from './LockedIcon'
import NoteIcon from './NoteIcon'
import PhoneIcon from './PhoneIcon'
import ScheduledIcon from './ScheduledIcon'
import SeatedIcon from './SeatedIcon'
import SettingsIcon from './SettingsIcon'
import SuccessIcon from './SuccessIcon'
import ThumbIcon from './ThumbIcon'
import TicketIcon from './TicketIcon'
import TrashIcon from './TrashIcon'
import UpgradeIcon from './UpgradeIcon'
import WalkInIcon from './WalkInIcon'
import WarningIcon from './WarningIcon'
storiesOf('32 Icons', module).add('all icons', () =>
<div style={{ display: 'flex', flexWrap: 'wrap' }}>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>AddIcon</p>
<AddIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>ArrivedIcon</p>
<ArrivedIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>ArrowIcon</p>
<ArrowIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>BlankIcon</p>
<BlankIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>BookIcon</p>
<BookIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>BookingIcon</p>
<BookingIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>CalendarIcon</p>
<CalendarIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>CheckIcon</p>
<CheckIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>CloseIcon</p>
<CloseIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>CreditIcon</p>
<CreditIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>DotDotDotIcon</p>
<DotDotDotIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>EditIcon</p>
<EditIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>EmailIcon</p>
<EmailIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>ErrorIcon</p>
<ErrorIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>EyeClosedIcon</p>
<EyeClosedIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>FinishedIcon</p>
<FinishedIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>GuestIcon</p>
<GuestIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>GuestsIcon</p>
<GuestsIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>InfoIcon</p>
<InfoIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>LockedIcon</p>
<LockedIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>NoteIcon</p>
<NoteIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>PhoneIcon</p>
<PhoneIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>ScheduledIcon</p>
<ScheduledIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>SeatedIcon</p>
<SeatedIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>SettingsIcon</p>
<SettingsIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>SuccessIcon</p>
<SuccessIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>ThumbIcon</p>
<ThumbIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>TicketIcon</p>
<TicketIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>TrashIcon</p>
<TrashIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>UpgradeIcon</p>
<UpgradeIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>WalkInIcon</p>
<WalkInIcon large />
</div>
<div style={{ textAlign: 'center', flex: '1 1', padding: '10px' }}>
<p>WarningIcon</p>
<WarningIcon large />
</div>
</div>
)
|
src/components/shell/Shell.js
|
ipfs/webui
|
import React from 'react'
import classNames from 'classnames'
const Shell = ({
title = 'Shell',
children,
className
}) => {
return (
<div className={classNames('br1 overflow-hidden', className)}>
<div className='f7 mb0 sans-serif ttu tracked charcoal pv1 pl2 bg-black-20'>{ title }</div>
<div className='bg-black-70 snow pa2 f7 lh-copy monospace nowrap overflow-x-auto'>
{children}
</div>
</div>
)
}
export default Shell
|
examples/with-clerk/pages/index.js
|
zeit/next.js
|
import React from 'react'
import Head from 'next/head'
import Link from 'next/link'
import styles from '../styles/Home.module.css'
import { SignedIn, SignedOut } from '@clerk/nextjs'
const ClerkFeatures = () => (
<Link href="/user">
<a className={styles.cardContent}>
<img src="/icons/layout.svg" />
<div>
<h3>Explore features provided by Clerk</h3>
<p>
Interact with the user button, user profile, and more to preview what
your users will see
</p>
</div>
<div className={styles.arrow}>
<img src="/icons/arrow-right.svg" />
</div>
</a>
</Link>
)
const SignupLink = () => (
<Link href="/sign-up">
<a className={styles.cardContent}>
<img src="/icons/user-plus.svg" />
<div>
<h3>Sign up for an account</h3>
<p>
Sign up and sign in to explore all the features provided by Clerk
out-of-the-box
</p>
</div>
<div className={styles.arrow}>
<img src="/icons/arrow-right.svg" />
</div>
</a>
</Link>
)
const apiSample = `import { withSession } from '@clerk/nextjs/api'
export default withSession((req, res) => {
res.statusCode = 200
if (req.session) {
res.json({ id: req.session.userId })
} else {
res.json({ id: null })
}
})`
// Main component using <SignedIn> & <SignedOut>.
//
// The SignedIn and SignedOut components are used to control rendering depending
// on whether or not a visitor is signed in.
//
// https://docs.clerk.dev/frontend/react/signedin-and-signedout
const Main = () => (
<main className={styles.main}>
<h1 className={styles.title}>Welcome to your new app</h1>
<p className={styles.description}>Sign up for an account to get started</p>
<div className={styles.cards}>
<div className={styles.card}>
<SignedIn>
<ClerkFeatures />
</SignedIn>
<SignedOut>
<SignupLink />
</SignedOut>
</div>
<div className={styles.card}>
<Link href="https://dashboard.clerk.dev">
<a target="_blank" rel="noreferrer" className={styles.cardContent}>
<img src="/icons/settings.svg" />
<div>
<h3>Configure settings for your app</h3>
<p>
Visit Clerk to manage instances and configure settings for user
management, theme, and more
</p>
</div>
<div className={styles.arrow}>
<img src="/icons/arrow-right.svg" />
</div>
</a>
</Link>
</div>
</div>
<APIRequest />
<div className={styles.links}>
<Link href="https://docs.clerk.dev">
<a target="_blank" rel="noreferrer" className={styles.link}>
<span className={styles.linkText}>Read Clerk documentation</span>
</a>
</Link>
<Link href="https://nextjs.org/docs">
<a target="_blank" rel="noreferrer" className={styles.link}>
<span className={styles.linkText}>Read NextJS documentation</span>
</a>
</Link>
</div>
</main>
)
const APIRequest = () => {
React.useEffect(() => {
if (window.Prism) {
window.Prism.highlightAll()
}
})
const [response, setResponse] = React.useState(
'// Click above to run the request'
)
const makeRequest = async () => {
setResponse('// Loading...')
try {
const res = await fetch('/api/getAuthenticatedUserId')
const body = await res.json()
setResponse(JSON.stringify(body, null, ' '))
} catch (e) {
setResponse(
'// There was an error with the request. Please contact support@clerk.dev'
)
}
}
return (
<div className={styles.backend}>
<h2>API request example</h2>
<div className={styles.card}>
<button
target="_blank"
rel="noreferrer"
className={styles.cardContent}
onClick={() => makeRequest()}
>
<img src="/icons/server.svg" />
<div>
<h3>fetch('/api/getAuthenticatedUserId')</h3>
<p>
Retrieve the user ID of the signed in user, or null if there is no
user
</p>
</div>
<div className={styles.arrow}>
<img src="/icons/download.svg" />
</div>
</button>
</div>
<h4>
Response
<em>
<SignedIn>
You are signed in, so the request will return your user ID
</SignedIn>
<SignedOut>
You are signed out, so the request will return null
</SignedOut>
</em>
</h4>
<pre>
<code className="language-js">{response}</code>
</pre>
<h4>pages/api/getAuthenticatedUserId.js</h4>
<pre>
<code className="language-js">{apiSample}</code>
</pre>
</div>
)
}
// Footer component
const Footer = () => (
<footer className={styles.footer}>
Powered by{' '}
<a href="https://clerk.dev" target="_blank" rel="noopener noreferrer">
<img src="/clerk.svg" alt="Clerk.dev" className={styles.logo} />
</a>
+
<a href="https://nextjs.org/" target="_blank" rel="noopener noreferrer">
<img src="/nextjs.svg" alt="Next.js" className={styles.logo} />
</a>
</footer>
)
const Home = () => (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
></meta>
</Head>
<Main />
<Footer />
</div>
)
export default Home
|
src/components/GlobalNavigation/NavBar/BackButton.android.js
|
aaron-edwards/Spirit-Guide
|
import React from 'react';
import { I18nManager, Image, StyleSheet, TouchableNativeFeedback, View } from 'react-native'
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
export default NavigationHeaderBackButton = (props: Props) => {
return (
<TouchableNativeFeedback
style={[styles.buttonContainer, props.style]}
useForeground={true}
background={TouchableNativeFeedback.Ripple('#FFFFFF', true)}
onPress={props.onPress}>
<View style={styles.buttonContainer}>
<Icon style={styles.button} name="arrow-left" size={24} color="white" />
</View>
</TouchableNativeFeedback>
);
};
NavigationHeaderBackButton.propTypes = {
onPress: React.PropTypes.func.isRequired
};
const styles = StyleSheet.create({
buttonContainer: {
borderRadius: 12,
},
button: {
borderRadius: 12,
margin: 16,
}
});
|
modules/RouteUtils.js
|
calebmichaelsanchez/react-router
|
import React from 'react'
import warning from 'warning'
function isValidChild(object) {
return object == null || React.isValidElement(object)
}
export function isReactChildren(object) {
return isValidChild(object) || (Array.isArray(object) && object.every(isValidChild))
}
function checkPropTypes(componentName, propTypes, props) {
componentName = componentName || 'UnknownComponent'
for (const propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
const error = propTypes[propName](props, propName, componentName)
if (error instanceof Error)
warning(false, error.message)
}
}
}
function createRoute(defaultProps, props) {
return { ...defaultProps, ...props }
}
export function createRouteFromReactElement(element) {
const type = element.type
const route = createRoute(type.defaultProps, element.props)
if (type.propTypes)
checkPropTypes(type.displayName || type.name, type.propTypes, route)
if (route.children) {
const childRoutes = createRoutesFromReactChildren(route.children, route)
if (childRoutes.length)
route.childRoutes = childRoutes
delete route.children
}
return route
}
/**
* Creates and returns a routes object from the given ReactChildren. JSX
* provides a convenient way to visualize how routes in the hierarchy are
* nested.
*
* import { Route, createRoutesFromReactChildren } from 'react-router'
*
* const routes = createRoutesFromReactChildren(
* <Route component={App}>
* <Route path="home" component={Dashboard}/>
* <Route path="news" component={NewsFeed}/>
* </Route>
* )
*
* Note: This method is automatically used when you provide <Route> children
* to a <Router> component.
*/
export function createRoutesFromReactChildren(children, parentRoute) {
const routes = []
React.Children.forEach(children, function (element) {
if (React.isValidElement(element)) {
// Component classes may have a static create* method.
if (element.type.createRouteFromReactElement) {
const route = element.type.createRouteFromReactElement(element, parentRoute)
if (route)
routes.push(route)
} else {
routes.push(createRouteFromReactElement(element))
}
}
})
return routes
}
/**
* Creates and returns an array of routes from the given object which
* may be a JSX route, a plain object route, or an array of either.
*/
export function createRoutes(routes) {
if (isReactChildren(routes)) {
routes = createRoutesFromReactChildren(routes)
} else if (!Array.isArray(routes)) {
routes = [ routes ]
}
return routes
}
|
src/js/OrderSentPage.js
|
merlox/dapp-transactions
|
import React from 'react'
import Header from './Header'
import {Link} from 'react-router-dom'
import './../stylus/index.styl'
import './../stylus/ordersentpage.styl'
import LINKS from './utils.js'
class OrderSentPage extends React.Component {
constructor(props) {
super(props)
}
render(){
return (
<div style={{height: '100%'}}>
<div className="order-sent-container">
<img src={LINKS.baseUrl + "img/order-sent/check-last.png"} />
<h1>Purchase Order Sent</h1>
<div className="order-sent-buttons-container">
<Link to={LINKS.home} className="order-sent-back">Back to Login</Link>
<Link to={LINKS.retailer}
onClick={() => {this.props.hideRetailers()}}
className="order-sent-login">Login as Wholesaler</Link>
</div>
</div>
</div>
)
}
}
export default OrderSentPage
|
src/routes/Home/components/TopicListing/TopicListing.js
|
spbsamuel/digg-clone
|
import React from 'react'
import classes from './TopicListing.scss'
import TopicCard from '../TopicCard'
import Shuffle from 'react-shuffle'
export const TopicListing = ({topics, visibleTopics, upVoteTopic, downVoteTopic}) => {
return (
<div>
<Shuffle>
{visibleTopics.map(id =>
<div key={id}>
<TopicCard
key={id}
{...topics[id]}
voteUp={upVoteTopic(id)}
voteDown={downVoteTopic(id)}
/>
</div>
)}
</Shuffle>
</div>
)
};
export default TopicListing
|
docs/src/examples/elements/Rail/Types/RailExampleDividing.js
|
Semantic-Org/Semantic-UI-React
|
import React from 'react'
import { Grid, Image, Rail, Segment } from 'semantic-ui-react'
const RailExampleDividing = () => (
<Grid centered columns={3}>
<Grid.Column>
<Segment>
<Image src='/images/wireframe/paragraph.png' />
<Rail dividing position='left'>
<Segment>Left Rail Content</Segment>
</Rail>
<Rail dividing position='right'>
<Segment>Right Rail Content</Segment>
</Rail>
</Segment>
</Grid.Column>
</Grid>
)
export default RailExampleDividing
|
examples/src/components/States.js
|
pedroseac/react-select
|
import React from 'react';
import Select from 'react-select';
const STATES = require('../data/states');
var StatesField = React.createClass({
displayName: 'StatesField',
propTypes: {
label: React.PropTypes.string,
searchable: React.PropTypes.bool,
},
getDefaultProps () {
return {
label: 'States:',
searchable: true,
};
},
getInitialState () {
return {
country: 'AU',
disabled: false,
searchable: this.props.searchable,
selectValue: 'new-south-wales',
clearable: true,
};
},
switchCountry (e) {
var newCountry = e.target.value;
console.log('Country changed to ' + newCountry);
this.setState({
country: newCountry,
selectValue: null
});
},
updateValue (newValue) {
console.log('State changed to ' + newValue);
this.setState({
selectValue: newValue
});
},
focusStateSelect () {
this.refs.stateSelect.focus();
},
toggleCheckbox (e) {
let newState = {};
newState[e.target.name] = e.target.checked;
this.setState(newState);
},
render () {
var options = STATES[this.state.country];
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select ref="stateSelect" autofocus options={options} simpleValue clearable={this.state.clearable} name="selected-state" disabled={this.state.disabled} value={this.state.selectValue} onChange={this.updateValue} searchable={this.state.searchable} />
<div style={{ marginTop: 14 }}>
<button type="button" onClick={this.focusStateSelect}>Focus Select</button>
<label className="checkbox" style={{ marginLeft: 10 }}>
<input type="checkbox" className="checkbox-control" name="searchable" checked={this.state.searchable} onChange={this.toggleCheckbox}/>
<span className="checkbox-label">Searchable</span>
</label>
<label className="checkbox" style={{ marginLeft: 10 }}>
<input type="checkbox" className="checkbox-control" name="disabled" checked={this.state.disabled} onChange={this.toggleCheckbox}/>
<span className="checkbox-label">Disabled</span>
</label>
<label className="checkbox" style={{ marginLeft: 10 }}>
<input type="checkbox" className="checkbox-control" name="clearable" checked={this.state.clearable} onChange={this.toggleCheckbox}/>
<span className="checkbox-label">Clearable</span>
</label>
</div>
<div className="checkbox-list">
<label className="checkbox">
<input type="radio" className="checkbox-control" checked={this.state.country === 'AU'} value="AU" onChange={this.switchCountry}/>
<span className="checkbox-label">Australia</span>
</label>
<label className="checkbox">
<input type="radio" className="checkbox-control" checked={this.state.country === 'US'} value="US" onChange={this.switchCountry}/>
<span className="checkbox-label">United States</span>
</label>
</div>
</div>
);
}
});
module.exports = StatesField;
|
modules/__tests__/createRoutesFromReactChildren-test.js
|
cold-brew-coding/react-router
|
/*eslint-env mocha */
/*eslint react/prop-types: 0*/
import expect from 'expect'
import React from 'react'
import { createRoutesFromReactChildren } from '../RouteUtils'
import IndexRoute from '../IndexRoute'
import Route from '../Route'
describe('createRoutesFromReactChildren', function () {
const Parent = React.createClass({
render() {
return (
<div>
<h1>Parent</h1>
{this.props.children}
</div>
)
}
})
const Hello = React.createClass({
render() {
return <div>Hello</div>
}
})
const Goodbye = React.createClass({
render() {
return <div>Goodbye</div>
}
})
it('works with index routes', function () {
const routes = createRoutesFromReactChildren(
<Route path="/" component={Parent}>
<IndexRoute component={Hello} />
</Route>
)
expect(routes).toEqual([
{
path: '/',
component: Parent,
indexRoute: {
component: Hello
}
}
])
})
it('works with nested routes', function () {
const routes = createRoutesFromReactChildren(
<Route component={Parent}>
<Route path="home" components={{ hello: Hello, goodbye: Goodbye }} />
</Route>
)
expect(routes).toEqual([
{
component: Parent,
childRoutes: [
{
path: 'home',
components: { hello: Hello, goodbye: Goodbye }
}
]
}
])
})
it('works with falsy children', function () {
const routes = createRoutesFromReactChildren([
<Route path="/one" component={Parent} />,
null,
<Route path="/two" component={Parent} />,
undefined
])
expect(routes).toEqual([
{
path: '/one',
component: Parent
}, {
path: '/two',
component: Parent
}
])
})
it('works with comments', function () {
const routes = createRoutesFromReactChildren(
<Route path="/one" component={Parent}>
// This is a comment.
<Route path="/two" component={Hello} />
</Route>
)
expect(routes).toEqual([
{
path: '/one',
component: Parent,
childRoutes: [
{
path: '/two',
component: Hello
}
]
}
])
})
})
|
examples/windows/components/navPane.js
|
gabrielbull/react-desktop
|
import React, { Component } from 'react';
import { NavPane, NavPaneItem, Text } from 'react-desktop/windows';
export default class extends Component {
static defaultProps = {
color: '#cc7f29',
theme: 'light'
};
constructor() {
super();
this.state = {
selected: 'Item 1'
}
}
render() {
return (
<NavPane openLength={200} push color={this.props.color} theme={this.props.theme}>
{this.renderItem('Item 1', 'Content 1')}
{this.renderItem('Item 2', 'Content 2')}
{this.renderItem('Item 3', 'Content 3')}
</NavPane>
);
}
renderItem(title, content) {
return (
<NavPaneItem
title={title}
icon={this.renderIcon(title)}
theme="light"
background="#ffffff"
selected={this.state.selected === title}
onSelect={() => this.setState({ selected: title })}
padding="10px 20px"
push
>
<Text>{content}</Text>
</NavPaneItem>
);
}
renderIcon(name) {
const fill = this.props.theme === 'dark' ? '#ffffff' : '#000000';
switch(name) {
case 'Item 1':
return (
<svg x="0px" y="0px" width="16px" height="14.9px" viewBox="0 0 16 14.9">
<polygon fill={fill} points="16,5.6 10.6,4.7 8,0 5.4,4.7 0,5.7 3.8,9.6 3.1,14.9 8,12.6 13,14.8 12.3,9.5 "/>
</svg>
);
case 'Item 2':
return (
<svg x="0px" y="0px" width="16px" height="13.5px" viewBox="0 0 16 13.5">
<path
fill={fill}
d="M16,4.2C16,1.9,14.1,0,11.7,0c-1.4,0-2.6,0.6-3.4,1.6c0,0,0,0,0,0C8.3,1.7,8.1,1.8,8,1.8
c-0.2,0-0.3-0.1-0.4-0.2c0,0,0,0,0,0C6.8,0.6,5.6,0,4.3,0C1.9,0,0,1.9,0,4.2c0,0,0,0.1,0,0.1l0,0c0,0,0,0.1,0,0.3
C0,4.8,0.1,5,0.1,5.2c0.3,1.4,1.4,4.1,5.1,6.5c2.1,1.4,2.6,1.8,2.8,1.8c0,0,0,0,0,0c0,0,0,0,0,0c0.1,0,0.7-0.4,2.8-1.8
c3.5-2.3,4.6-4.8,5-6.3C15.9,5.1,16,4.8,16,4.5C16,4.3,16,4.2,16,4.2L16,4.2C16,4.2,16,4.2,16,4.2z"
/>
</svg>
);
case 'Item 3':
return (
<svg x="0px" y="0px" width="16px" height="15.6px" viewBox="0 0 16 15.6">
<path
fill={fill}
d="M14.9,3.2c0.7-0.9,1-1.7,1.1-2.4c0-0.2,0-0.4-0.1-0.5c0,0,0-0.1-0.1-0.1c0,0-0.1-0.1-0.1-0.1
C15.6,0,15.4,0,15.2,0c-0.7,0-1.6,0.4-2.4,1c-0.7,0.5-1.4,1.2-2.4,2.3C10.2,3.5,10,3.6,9.8,3.8L8.3,3.4L7.9,3.3C8,3.2,8.1,3.1,8.1,3
c0-0.1,0-0.2-0.1-0.3L7.6,2.3C7.5,2.3,7.4,2.2,7.3,2.2c-0.1,0-0.2,0-0.3,0.1L6.5,2.8L6.2,2.8c0.1-0.1,0.1-0.2,0.1-0.3
c0-0.1,0-0.2-0.1-0.3L5.8,1.9C5.7,1.8,5.6,1.8,5.5,1.8c-0.1,0-0.2,0-0.3,0.1L4.7,2.3L2.8,1.8c0,0-0.1,0-0.1,0
c-0.1,0-0.3,0.1-0.4,0.1L1.6,2.6C1.5,2.6,1.5,2.7,1.5,2.8c0,0.1,0.1,0.3,0.2,0.3l4.1,2.2c0,0,0.1,0.1,0.1,0.1L7,6.6
C6,7.7,5,8.8,4.2,9.7C4.2,9.8,4.1,9.9,4,10L0.9,9.7c0,0,0,0-0.1,0c-0.1,0-0.3,0.1-0.4,0.2l-0.3,0.3C0,10.3,0,10.4,0,10.5
c0,0.1,0.1,0.3,0.2,0.3l2.2,1c0,0,0.1,0,0.1,0.1l0.2,0.2c-0.1,0.2-0.1,0.3-0.1,0.4c0,0.2,0.1,0.3,0.2,0.4C2.9,13,3,13.1,3.2,13.1
c0.1,0,0.3,0,0.4-0.1l0.2,0.2c0,0,0,0.1,0.1,0.1l1.1,2.2c0.1,0.1,0.2,0.2,0.4,0.2c0.1,0,0.2,0,0.3-0.1l0.3-0.3C6,15.1,6,14.9,6,14.8
c0,0-0.3-3.1-0.3-3.1c0.1-0.1,0.2-0.1,0.3-0.2c1-0.7,2.1-1.7,3.2-2.7l1.2,1.1c0,0,0.1,0.1,0.1,0.1l2.3,4c0.1,0.1,0.2,0.2,0.3,0.2
c0.1,0,0.2,0,0.3-0.1l0.7-0.7c0.1-0.1,0.1-0.2,0.1-0.3c0,0,0-0.1,0-0.1l-0.5-1.8L13.6,11l0.5-0.4c0.1-0.1,0.1-0.2,0.1-0.3
c0-0.1,0-0.2-0.1-0.3l-0.3-0.3c-0.1-0.1-0.2-0.1-0.3-0.1c-0.1,0-0.2,0-0.3,0.1l-0.1-0.3l0.5-0.5c0.1-0.1,0.1-0.2,0.1-0.3
c0-0.1,0-0.2-0.1-0.3l-0.3-0.3c-0.1-0.1-0.2-0.1-0.3-0.1c-0.1,0-0.2,0-0.3,0.1L12.1,6c0.2-0.2,0.4-0.4,0.6-0.5
C13.7,4.5,14.4,3.8,14.9,3.2z"
/>
</svg>
);
}
}
}
|
spec/javascripts/jsx/grading/AssignmentPostingPolicyTray/AssignmentPostingPolicyTraySpec.js
|
djbender/canvas-lms
|
/*
* Copyright (C) 2019 - 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 ReactDOM from 'react-dom'
import {waitForElement, wait} from '@testing-library/react'
import AssignmentPostingPolicyTray from 'jsx/grading/AssignmentPostingPolicyTray'
import * as Api from 'jsx/grading/AssignmentPostingPolicyTray/Api'
import * as FlashAlert from 'jsx/shared/FlashAlert'
QUnit.module('AssignmentPostingPolicyTray', suiteHooks => {
let $container
let context
let tray
suiteHooks.beforeEach(() => {
$container = document.body.appendChild(document.createElement('div'))
context = {
assignment: {
id: '2301',
name: 'Math 1.1',
postManually: false
},
onAssignmentPostPolicyUpdated: sinon.spy(),
onExited: sinon.spy()
}
const bindRef = ref => {
tray = ref
}
ReactDOM.render(<AssignmentPostingPolicyTray ref={bindRef} />, $container)
})
suiteHooks.afterEach(async () => {
if (getTrayElement()) {
getCloseButton().click()
await waitForTrayClosed()
}
ReactDOM.unmountComponentAtNode($container)
$container.remove()
})
function getTrayElement() {
return document.querySelector('[role="dialog"][aria-label="Grade posting policy tray"]')
}
function getCancelButton() {
const $tray = getTrayElement()
return [...$tray.querySelectorAll('button')].find($button => $button.textContent === 'Cancel')
}
function getCloseButton() {
const $tray = getTrayElement()
return [...$tray.querySelectorAll('button')].find($button => $button.textContent === 'Close')
}
function getSaveButton() {
const $tray = getTrayElement()
return [...$tray.querySelectorAll('button')].find($button => $button.textContent === 'Save')
}
function getLabel(text) {
const $tray = getTrayElement()
return [...$tray.querySelectorAll('label')].find($label => $label.textContent.includes(text))
}
function getInputByLabel(label) {
const $label = getLabel(label)
if ($label === undefined) return undefined
return document.getElementById($label.htmlFor)
}
function show() {
tray.show(context)
return waitForElement(getTrayElement)
}
function waitForTrayClosed() {
return wait(() => {
if (context.onExited.callCount > 0) {
return
}
throw new Error('Tray is still open')
})
}
QUnit.module('#show()', () => {
test('opens the tray', async () => {
await show()
ok(getTrayElement())
})
test('includes the name of the assignment', async () => {
await show()
const heading = getTrayElement().querySelector('h2')
equal(heading.textContent, 'Grade Posting Policy: Math 1.1')
})
test('disables the "Automatically" input for an anonymous assignment', async () => {
context.assignment.anonymousGrading = true
await show()
strictEqual(getInputByLabel('Automatically').disabled, true)
})
QUnit.module('when the assignment is moderated', hooks => {
hooks.beforeEach(() => {
context.assignment.moderatedGrading = true
})
test('disables the "Automatically" input when grades are not published', async () => {
context.assignment.gradesPublished = false
await show()
strictEqual(getInputByLabel('Automatically').disabled, true)
})
test('enables the "Automatically" input when grades are published', async () => {
context.assignment.gradesPublished = true
await show()
strictEqual(getInputByLabel('Automatically').disabled, false)
})
test('always disables the "Automatically" input when the assignment is anonymous', async () => {
context.assignment.anonymousGrading = true
context.assignment.gradesPublished = true
await show()
strictEqual(getInputByLabel('Automatically').disabled, true)
})
})
test('enables the "Automatically" input if the assignment is not anonymous or moderated', async () => {
await show()
strictEqual(getInputByLabel('Automatically').disabled, false)
})
test('the "Automatically" input is initally selected if an auto-posted assignment is passed', async () => {
await show()
strictEqual(getInputByLabel('Automatically').checked, true)
})
test('the "Manually" input is initially selected if a manual-posted assignment is passed', async () => {
context.assignment.postManually = true
await show()
strictEqual(getInputByLabel('Manually').checked, true)
})
test('enables the "Save" button if the postManually value has changed and no request is in progress', async () => {
await show()
getInputByLabel('Manually').click()
strictEqual(getSaveButton().disabled, false)
})
test('disables the "Save" button if the postManually value has not changed', async () => {
await show()
getInputByLabel('Manually').click()
getInputByLabel('Automatically').click()
strictEqual(getSaveButton().disabled, true)
})
test('disables the "Save" button if a request is already in progress', async () => {
let resolveRequest
const setAssignmentPostPolicyStub = sinon.stub(Api, 'setAssignmentPostPolicy').returns(
new Promise(resolve => {
resolveRequest = () => {
resolve({assignmnentId: '2301', postManually: true})
}
})
)
await show()
getInputByLabel('Manually').click()
getSaveButton().click()
strictEqual(getSaveButton().disabled, true)
resolveRequest()
setAssignmentPostPolicyStub.restore()
})
})
QUnit.module('"Close" Button', hooks => {
hooks.beforeEach(show)
test('closes the tray', async () => {
getCloseButton().click()
await waitForTrayClosed()
notOk(getTrayElement())
})
})
QUnit.module('"Cancel" button', hooks => {
hooks.beforeEach(show)
test('closes the tray', async () => {
getCancelButton().click()
await waitForTrayClosed()
notOk(getTrayElement())
})
test('is enabled when no request is in progress', () => {
strictEqual(getCancelButton().disabled, false)
})
test('is disabled when a request is in progress', () => {
let resolveRequest
const setAssignmentPostPolicyStub = sinon.stub(Api, 'setAssignmentPostPolicy').returns(
new Promise(resolve => {
resolveRequest = () => {
resolve({assignmnentId: '2301', postManually: true})
}
})
)
getInputByLabel('Manually').click()
getSaveButton().click()
strictEqual(getCancelButton().disabled, true)
resolveRequest()
setAssignmentPostPolicyStub.restore()
})
})
QUnit.module('"Save" button', hooks => {
let setAssignmentPostPolicyStub
let showFlashAlertStub
hooks.beforeEach(() => {
return show().then(() => {
getInputByLabel('Manually').click()
showFlashAlertStub = sinon.stub(FlashAlert, 'showFlashAlert')
setAssignmentPostPolicyStub = sinon
.stub(Api, 'setAssignmentPostPolicy')
.resolves({assignmentId: '2301', postManually: true})
})
})
hooks.afterEach(() => {
FlashAlert.destroyContainer()
setAssignmentPostPolicyStub.restore()
showFlashAlertStub.restore()
})
test('calls setAssignmentPostPolicy', () => {
getSaveButton().click()
strictEqual(setAssignmentPostPolicyStub.callCount, 1)
})
test('passes the assignment ID to setAssignmentPostPolicy', () => {
getSaveButton().click()
strictEqual(setAssignmentPostPolicyStub.firstCall.args[0].assignmentId, '2301')
})
test('passes the selected postManually value to setAssignmentPostPolicy', () => {
getSaveButton().click()
strictEqual(setAssignmentPostPolicyStub.firstCall.args[0].postManually, true)
})
QUnit.module('on success', () => {
const waitForSuccess = async () => {
await wait(() => getTrayElement() == null)
}
test('renders a success alert', async () => {
getSaveButton().click()
await waitForSuccess()
strictEqual(showFlashAlertStub.callCount, 1)
})
test('the rendered alert includes a message referencing the assignment', async () => {
getSaveButton().click()
await waitForSuccess()
const message = 'Success! The post policy for Math 1.1 has been updated.'
strictEqual(showFlashAlertStub.firstCall.args[0].message, message)
})
test('calls the provided onAssignmentPostPolicyUpdated function', async () => {
getSaveButton().click()
await waitForSuccess()
strictEqual(context.onAssignmentPostPolicyUpdated.callCount, 1)
})
test('passes the assignmentId to onAssignmentPostPolicyUpdated', async () => {
getSaveButton().click()
await waitForSuccess()
strictEqual(context.onAssignmentPostPolicyUpdated.firstCall.args[0].assignmentId, '2301')
})
test('passes the postManually value to onAssignmentPostPolicyUpdated', async () => {
getSaveButton().click()
await waitForSuccess()
strictEqual(context.onAssignmentPostPolicyUpdated.firstCall.args[0].postManually, true)
})
})
QUnit.module('on failure', failureHooks => {
const waitForFailure = async () => {
await wait(() => FlashAlert.showFlashAlert.callCount > 0)
}
failureHooks.beforeEach(() => {
setAssignmentPostPolicyStub.rejects({error: 'oh no'})
})
test('renders an error alert', async () => {
getSaveButton().click()
await waitForFailure()
strictEqual(showFlashAlertStub.callCount, 1)
})
test('the rendered error alert contains a message', async () => {
getSaveButton().click()
await waitForFailure()
const message = 'An error occurred while saving the assignment post policy'
strictEqual(showFlashAlertStub.firstCall.args[0].message, message)
})
test('the tray remains open', async () => {
getSaveButton().click()
await waitForFailure()
ok(getTrayElement())
})
})
})
})
|
src/index.js
|
zumbara/zumbara-web
|
// @flow
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import createHistory from 'history/createBrowserHistory';
import { injectGlobal } from 'styled-components';
import 'normalize.css/normalize.css';
import configureStore from './redux/configureStore';
import registerServiceWorker from './registerServiceWorker';
import App from './App';
const history = createHistory();
const store = configureStore(undefined, history);
// eslint-disable-next-line
injectGlobal`
body {
margin: 0;
padding: 0;
background: #efefef;
font-family: 'Source Sans Pro', sans-serif;
color: #555;
font-size: 16px;
line-height: 1.5;
}
`;
const render = Component => {
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<Component />
</ConnectedRouter>
</Provider>,
document.getElementById('root'),
);
};
/* istanbul ignore if */
if (process.env.NODE_ENV === 'development' && module.hot) {
module.hot.accept('./App', () => {
// eslint-disable-next-line
const NextApp = require('./App').default;
render(NextApp);
});
}
render(App);
registerServiceWorker();
|
src/Button.story.js
|
prometheusresearch/react-ui
|
/**
* @flow
*/
import React from 'react';
import {storiesOf} from '@kadira/storybook';
import Button from './Button';
import I18N from './I18N';
export function createButtonStories(Button: any) {
storiesOf(`<${Button.displayName || Button.name} />`, module)
.add('Default state', () => <Button>Click me</Button>)
.add('Size: x-small', () => <Button size="x-small">Click me</Button>)
.add('Size: small', () => <Button size="small">Click me</Button>)
.add('Size: normal', () => <Button size="normal">Click me</Button>)
.add('Size: large', () => <Button size="large">Click me</Button>)
.add('With icon', () => <Button icon="+">Add</Button>)
.add('With icon (rtl)', () => (
<I18N dir="rtl">
<Button icon="+">Add</Button>
</I18N>
))
.add('With icon only', () => <Button icon="+" />)
.add('With icon (alternative)', () => <Button iconAlt="+">Add</Button>)
.add('With icon (alternative, rtl)', () => (
<I18N dir="rtl">
<Button iconAlt="+">Add</Button>
</I18N>
))
.add('Grouped horizontally', () => (
<div>
<Button groupHorizontally>Add</Button>
<Button groupHorizontally>No op</Button>
<Button groupHorizontally>Remove</Button>
</div>
))
.add('Grouped horizontally (rtl)', () => (
<I18N dir="rtl">
<div>
<Button groupHorizontally>Add</Button>
<Button groupHorizontally>No op</Button>
<Button groupHorizontally>Remove</Button>
</div>
</I18N>
))
.add('Grouped vertically', () => (
<div style={{display: 'flex', flexDirection: 'column'}}>
<Button groupVertically>Add</Button>
<Button groupVertically>No op</Button>
<Button groupVertically>Remove</Button>
</div>
));
}
createButtonStories(Button);
|
src/svg-icons/navigation/arrow-downward.js
|
andrejunges/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationArrowDownward = (props) => (
<SvgIcon {...props}>
<path d="M20 12l-1.41-1.41L13 16.17V4h-2v12.17l-5.58-5.59L4 12l8 8 8-8z"/>
</SvgIcon>
);
NavigationArrowDownward = pure(NavigationArrowDownward);
NavigationArrowDownward.displayName = 'NavigationArrowDownward';
NavigationArrowDownward.muiName = 'SvgIcon';
export default NavigationArrowDownward;
|
src/page/TimePickerPage.js
|
jerryshew/react-uikits
|
import React, { Component } from 'react';
import {CN, TitleBlock} from '../util/tools';
import {TimePicker} from '../component';
import CodeView from './CodeView';
export class TimePickerPage extends Component {
constructor(props) {
super(props);
this.state = {
value: 4981
}
}
handleTimeChange(value){
this.setState({
value
});
}
render() {
return (
<section>
{TitleBlock('时间选择')}
<h4>默认时间选择</h4>
<CodeView component={<TimePicker onChange={value => {}} />}>
{`<TimePicker onChange={onChangeFunction} />`}
</CodeView>
<br/>
<h4>带默认值的时间选择</h4>
<CodeView component={<TimePicker value={12217} onChange={value => {}} />}>
{`<TimePicker value={12217} onChange={onChangeFunction} />`}
</CodeView>
<br/>
<h4>onChange 事件</h4>
<CodeView component={
<div>
<p>选择的时间秒数为 {this.state.value}</p>
<TimePicker value={this.state.value} onChange={this.handleTimeChange.bind(this)} />
</div>
}>
{`<TimePicker value={4981} onChange={onChangeFunction} />`}
</CodeView>
<br/>
<h4>简单的时间选择</h4>
<CodeView component={<TimePicker simple={true} onChange={value => {}} />}>
{`<TimePicker simple={true} onChange={onChangeFunction} />`}
</CodeView>
<br/>
<h4>时间选择位置</h4>
<CodeView component={<div>
<TimePicker position="top" onChange={value => {}}/>
</div>}>
{`<TimePicker position="top" onChange={onChangeFunction}/>`}
</CodeView>
<br/>
<h4>属性</h4>
<table className="dot table">
<thead>
<tr>
<th>名称</th>
<th>描述</th>
<th>类型</th>
<th>默认值</th>
<th>required</th>
</tr>
</thead>
<tbody>
<tr>
<td>value</td>
<td>值(秒数 0 ~ 86399)</td>
<td>整形(例如:4981 代表 '03:23:37')</td>
<td>0</td>
<td>否</td>
</tr>
<tr>
<td>simple</td>
<td>简洁版</td>
<td>Boolean</td>
<td>false</td>
<td>否</td>
</tr>
<tr>
<td>position</td>
<td>展开位置</td>
<td>'top', 'bottom' 中的一个</td>
<td>bottom</td>
<td>否</td>
</tr>
<tr>
<td>onChange</td>
<td>时间变化触发事件</td>
<td>函数(时间字符串)</td>
<td>
{`onChange(time){
}`}
</td>
<td>是</td>
</tr>
</tbody>
</table>
</section>
);
}
}
|
examples/custom-grid/src/index.js
|
Hellenic/react-hexgrid
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
app/addons/documents/mango/components/ExecutionStats.js
|
popojargo/couchdb-fauxton
|
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
import React from 'react';
import PropTypes from 'prop-types';
import { Popover, OverlayTrigger } from 'react-bootstrap';
const TOO_MANY_DOCS_SCANNED_WARNING = "The number of documents examined is high in proportion to the number of results returned. Consider adding an index to improve this.";
export default class ExecutionStats extends React.Component {
constructor (props) {
super(props);
}
humanizeDuration(milliseconds) {
if (milliseconds < 1000) {
return Math.round(milliseconds) + ' ms';
}
let seconds = milliseconds / 1000;
if (seconds < 60) {
return Math.floor(seconds) + ' seconds';
}
const minutes = Math.floor(seconds / 60);
seconds = seconds - (minutes * 60);
return minutes + 'minute, ' + seconds + 'seconds';
}
getWarning(executionStats, warning) {
if (!executionStats) { return warning; }
// warn if many documents scanned in relation to results returned
if (!warning && executionStats.results_returned) {
const docsExamined = executionStats.total_docs_examined || executionStats.total_quorum_docs_examined;
if (docsExamined / executionStats.results_returned > 10) {
return TOO_MANY_DOCS_SCANNED_WARNING;
}
}
return warning;
}
warningPopupComponent(warningText) {
if (!!warningText) {
return (<div className="warning">
<i className="fonticon-attention-circled"></i> {warningText}
</div>);
}
}
executionStatsLine(title, value, alwaysShow = false, units = "") {
const hasValue = value === 0 && !alwaysShow ? "false" : "true";
return <div data-status={hasValue}>{title + ": "}<span className="value">{value.toLocaleString()} {units}</span></div>;
}
executionStatsPopupComponent(executionStats) {
if (!executionStats) return null;
return (
<div className="execution-stats-popup-component">
{/* keys examined always 0 so hide it for now */}
{/* {this.executionStatsLine("keys examined", executionStats.total_keys_examined)} */}
{this.executionStatsLine("documents examined", executionStats.total_docs_examined)}
{this.executionStatsLine("documents examined (quorum)", executionStats.total_quorum_docs_examined)}
{this.executionStatsLine("results returned", executionStats.results_returned, true)}
{this.executionStatsLine("execution time", executionStats.execution_time_ms, false, "ms")}
</div>
);
}
popup(executionStats, warningText) {
return (
<Popover id="popover-execution-stats" title="Execution Statistics">
<div className="execution-stats-popup">
{this.executionStatsPopupComponent(executionStats)}
{this.warningPopupComponent(warningText)}
</div>
</Popover>
);
}
render() {
const {
executionStats,
warning
} = this.props;
const warningText = this.getWarning(executionStats, warning);
let warningComponent = null;
if (!!warningText) {
warningComponent = <i className="fonticon-attention-circled"></i>;
}
let executionStatsComponent = null;
if (executionStats) {
executionStatsComponent = (
<span className="execution-stats-component">Executed in {this.humanizeDuration(executionStats.execution_time_ms)}</span>
);
} else if (!!warningText) {
executionStatsComponent = (
<span className="execution-stats-component">Warning</span>
);
}
const popup = this.popup(executionStats, warningText);
return (
<OverlayTrigger trigger={['hover', 'focus', 'click']} placement="right" overlay={popup}>
<span className="execution-stats">
{warningComponent}
{executionStatsComponent}
</span>
</OverlayTrigger>
);
}
};
ExecutionStats.propTypes = {
executionStats: PropTypes.object,
warning: PropTypes.string
};
|
web/assets/js/detailpage-need-to-integrate/CarDetail.js
|
xuqiantong/NY_Auto
|
/**
* Created by jeanliu on 4/14/17.
*/
import React, { Component } from 'react';
import './CarDetail2.css';
var Row = require('react-bootstrap/lib/Row');
var Col = require('react-bootstrap/lib/Col');
var Button = require('react-bootstrap/lib/Button');
// const PHOTOS = [
// {id: 0, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-01.jpeg'},
// {id: 1, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-02.jpeg'},
// {id: 2, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-03.jpeg'},
// {id: 3, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-04.jpeg'},
// {id: 4, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-05.jpeg'},
// {id: 6, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-06.jpeg'},
// {id: 7, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-07.jpeg'},
// {id: 8, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-08.jpeg'},
// {id: 9, imgpath: './static/bundles/images/detail-test/2015-maserati-ghibli-sq4-28193mi-09.jpeg'}
// ];
function BannerDivider(props) {
return (
<Row >
<Col md={10} mdPush={1} className="banner-divider"></Col>
</Row>
);
}
class CarPhotoBanner extends Component {
constructor(props) {
super(props);
this.state = {photoIndex: 0};
this.getPrevPhoto = this.getPrevPhoto.bind(this);
this.getNextPhoto = this.getNextPhoto.bind(this);
}
getPrevPhoto(e) {
console.log("get prev photo");
if (this.state.photoIndex != 0) {
this.setState({
photoIndex: (this.state.photoIndex - 1)
});
}
}
getNextPhoto(e) {
console.log("get next photo");
if (this.state.photoIndex != PHOTOS.length-1) {
this.setState({
photoIndex: (this.state.photoIndex + 1)
});
}
}
render() {
const photos = this.props.photos;
var Background = photos[this.state.photoIndex];
var sectionStyle = {
backgroundImage: "url(" + Background + ")",
backgroundSize: "cover",
backgroundPositionY: "50%"
};
return (
<Row id="car-photo-banner">
<Col md={12} id="car-photo" className="car-photo-item" style={sectionStyle}>
<Row className="btn-wrapper">
<Col md={1} className="car-img-btn img-prev" onClick={this.getPrevPhoto}>
<span className="arrow left leftarrow"></span>
</Col>
<Col md={1} className="car-img-btn img-next" onClick={this.getNextPhoto}>
<span className="arrow right rightarrow"></span>
</Col>
</Row>
</Col>
</Row>
);
}
}
function PriceBanner(props) {
//const car = props.car;
const title = props.title;
const price = props.price;
const mileage = props.mileage;
return (
<Row className="price-banner-wrapper">
<Col md={12} className="price-banner">
<Row>
<Col md={11} mdPush={1} sm={11} smPush={1} className="banner-title">
{title}
</Col>
</Row>
<Row>
<Col md={3} mdPush={1} sm={3} smPush={1} xs={4} id="car-price" className="price-banner-text">
<span className="item-title">Price</span>
<span className="item-content">$ {price}</span>
</Col>
<Col md={4} mdPush={1} sm={4} smPush={1} xs={4} id="car-mileage" className="price-banner-text">
<span className="item-title">Mileage</span>
<span className="item-content">{mileage} mi</span>
</Col>
<Col md={5} sm={5} xs={12} id="car-mileage" className="price-banner-text btn-area">
<Col md={6} sm={6} xs={6}>
<Button bsStyle="primary" className="submit-btn" >View CARFAX</Button>
</Col>
<Col md={6} sm={6} xs={6}>
<Button bsStyle="primary" className="submit-btn" >Make An Offer</Button>
</Col>
</Col>
</Row>
</Col>
</Row>
);
}
function ProfileBanner(props) {
const doors = props.doors;
const drive = props.drive;
return (
<Row className="profile-banner-wrapper">
<Row>
<Col md={9} mdPush={1} className="profile-banner">
<Col md={2} sm={2} xs={3} className="profile-item">
<img src="./static/bundles/images/detailpage/icons/door.png" className="profile-icon"/>
<div className="profile-text">{doors} Doors</div>
</Col>
<Col md={2} sm={2} xs={3} className="profile-item">
<img src="./static/bundles/images/detailpage/icons/passengers.png" className="profile-icon"/>
<div className="profile-text">5 Passengers</div>
</Col>
<Col md={2} sm={2} xs={3} className="profile-item">
<img src="./static/bundles/images/detailpage/icons/gearbox.png" className="profile-icon"/>
<div className="profile-text">Automatic</div>
</Col>
<Col md={2} sm={2} xs={3} className="profile-item">
<img src="./static/bundles/images/detailpage/icons/cogwheel-outline.png" className="profile-icon"/>
<div className="profile-text">{drive}</div>
</Col>
</Col>
<Col md={2} smHidden xsHidden className="share-btn disappear-in-md">
<Button bsStyle="primary" className="submit-btn" >Share</Button>
</Col>
</Row>
<Row className="sm-screen-btn-row">
<Col sm={2} smPush={5} xs={4} xsPush={4}>
<Button bsStyle="primary" className="submit-btn">Share</Button>
</Col>
</Row>
</Row>
);
}
function ColorBanner(props) {
const color_ext = props.color_ext;
const color_int = props.color_int;
var ExtBg = "#ffffff";
var IntBg = "#ddd9c5";
var extStyle = {
backgroundColor: color_ext,
};
var intStyle = {
backgroundColor: color_int,
};
return(
<Row className="color-banner-wrapper">
<Col md={12}>
<Row>
<Col md={11} mdPush={1} sm={11} smPush={1} xs={12} className="banner-title">Color</Col>
</Row>
<Row>
<Col md={10} mdPush={1} sm={10} smPush={1} xs={12} className="color-banner">
<Row className="color-items-wrapper">
<Col md={6} sm={6} xs={6}>
<div className="color-circle" style={extStyle}></div>
<div className="color-text-wrapper">
<div className="color-title">Exterior:</div>
<div className="color-content">{color_ext}</div>
</div>
</Col>
<Col md={6} sm={6} xs={6}>
<div className="color-circle" style={intStyle}></div>
<div className="color-text-wrapper">
<div className="color-title">Interior:</div>
<div className="color-content">{color_int}</div>
</div>
</Col>
</Row>
</Col>
</Row>
</Col>
</Row>
);
}
function PkgBanner(props) {
return (
<Row className="pkg-banner-wrapper">
<Col md={12}>
<Row>
<Col md={11} mdPush={1} sm={11} smPush={1} xs={12} className="banner-title">Featured Packages</Col>
</Row>
<Row>
<Col md={11} mdPush={1} sm={11} smPush={1} className="pkg-items-wrapper">
<Col md={1} sm={1} xs={2} className="profile-item">
<img src="./static/bundles/images/detailpage/icons/bluetooth.png" className="pkg-icon"/>
<div className="profile-text">Bluetooth</div>
</Col>
<Col md={1} sm={1} xs={2} className="profile-item">
<img src="./static/bundles/images/detailpage/icons/keyless.png" className="pkg-icon"/>
<div className="profile-text">Keyless Entry</div>
</Col>
<Col md={1} sm={1} xs={2} className="profile-item">
<img src="./static/bundles/images/detailpage/icons/start.png" className="pkg-icon"/>
<div className="profile-text">Keyless Start</div>
</Col>
<Col md={1} sm={1} xs={2} className="profile-item">
<img src="./static/bundles/images/detailpage/icons/aux.png" className="pkg-icon"/>
<div className="profile-text">Aux</div>
</Col>
<Col md={1} sm={1} xs={2} className="profile-item">
<img src="./static/bundles/images/detailpage/icons/leather_seats.png" className="pkg-icon"/>
<div className="profile-text">Leather Seats</div>
</Col>
<Col md={1} sm={1} xs={2} className="profile-item">
<img src="./static/bundles/images/detailpage/icons/heated_seats.png" className="pkg-icon"/>
<div className="profile-text">Heated Seats</div>
</Col>
</Col>
</Row>
</Col>
</Row>
);
}
function PerfBanner(props) {
return (
<Row className="perf-banner-wrapper">
<Col md={12}>
<Row>
<Col md={11} mdPush={1} sm={11} smPush={1} xs={12} className="banner-title">Performance</Col>
</Row>
<Row>
<Col md={11} mdPush={1} sm={11} smPush={1} xs={12}>
<Col md={6} sm={6} xs={6} className="perf-left-col">
<Row className="perf-row">
<Col md={5} className="perf-info-key">Horsepower: </Col>
<Col md={7} className="perf-info-value">320 hp</Col>
</Row>
<Row className="perf-row">
<Col md={5} className="perf-info-key">Displacement: </Col>
<Col md={7} className="perf-info-value">2.0 L</Col>
</Row>
<Row className="perf-row">
<Col md={5} className="perf-info-key">Fuel-type: </Col>
<Col md={7} className="perf-info-value">Gasoline</Col>
</Row>
</Col>
<Col md={6} sm={6} xs={6} className="perf-right-col">
<Row className="perf-row">
<Col md={5} className="perf-info-key">Torque: </Col>
<Col md={7} className="perf-info-value">200 lb-ft</Col>
</Row>
<Row className="perf-row">
<Col md={5} className="perf-info-key">Cylinder: </Col>
<Col md={7} className="perf-info-value">4</Col>
</Row>
<Row className="perf-row">
<Col md={5} className="perf-info-key">Compressor Type: </Col>
<Col md={7} className="perf-info-value">Turbo-charged</Col>
</Row>
</Col>
</Col>
</Row>
</Col>
</Row>
);
}
export default class CarDetail extends Component {
// static propTypes = {
// pages: PropTypes.array,
// active_page_slug: PropTypes.string,
// }
// static contextTypes = {
// router: PropTypes.object.isRequired,
// store: PropTypes.object.isRequired
// };
// activateAndLoadPage = (e) => {
// e.preventDefault();
// let slug = e.target.dataset.slug;
// this.context.router.transitionTo('/page/' + slug);
// }
constructor(props) {
super(props);
this.state = {
vehicle: null,
images: [],
title: null,
price: 0,
mileage: 0,
drive: null,
color_ext: null,
color_int: null,
featured_packages: [],
in_stock_time: null,
location: null,
handler: null,
carfaxPath: null,
interior_type: null,
top_type: null,
body_type: null,
fuel: null,
transmission: null,
engine: null,
owner_num: null,
condition: null,
min_price: null,
trim: null,
status: null,
vin: null
};
}
componentWillMount() {
var vehicle_id = window.location.href.split("/").pop().substring(6);
var vehicle_url = "/api/vehicle/" + vehicle_id;
var image_url = "/api/has_image/";
$.ajax({
url: vehicle_url,
datatype: 'json',
cache: false,
success: function(vehicle) {
const title = vehicle.year + " " +
vehicle.make + " " +
vehicle.model;
const price = vehicle.list_price;
const mileage = vehicle.mileage;
const doors = vehicle.door;
const drive = vehicle.drive;
const color_ext = vehicle.color_ext;
const color_int = vehicle.color_int;
const in_stock_time = vehicle.in_stock_time;
const location = vehicle.location;
const handler = vehicle.handler;
const carfaxPath = vehicle.carfaxPath;
const interior_type = vehicle.interior_type;
const top_type = vehicle.top_type;
const body_type = vehicle.body_type;
const fuel = vehicle.fuel;
const transmission = vehicle.transmission;
const engine = vehicle.engine;
const owner_num = vehicle.owner_num;
const condition = vehicle.condition;
const min_price = vehicle.min_price;
const trim = vehicle.trim;
const status = vehicle.status;
const vin = vehicle.vin;
var featuredPackages = [];
for(var attribute in vehicle) {
if(attribute.substring(0,3) == "es_" ||
attribute.substring(0,3) == "ep_" ||
attribute.substring(0,3) == "eb_") {
if(vehicle[attribute] == true) {
featuredPackages.push(attribute);
}
}
}
this.setState({
vehicle: vehicle,
title: title,
price: price,
mileage: mileage,
doors: doors,
drive: drive,
color_ext: color_ext,
color_int: color_int,
featured_packages: featuredPackages,
in_stock_time: in_stock_time,
location: location,
handler: handler,
carfaxPath: carfaxPath,
interior_type: interior_type,
top_type: top_type,
body_type: body_type,
fuel: fuel,
transmission: transmission,
engine: engine,
owner_num: owner_num,
condition: condition,
min_price: min_price,
trim: trim,
status: status,
vin: vin
});
}.bind(this)
})
$.ajax({
url: image_url,
datatype: 'json',
cache: false,
success: function(image_list) {
for(var image in image_list) {
if(image_list[image].vehicle == vehicle_id) {
var images = this.state.images;
images.push(image_list[image].image);
this.setState({images: images})
}
}
}.bind(this)
})
}
render() {
console.log(this.state);
return (
<div id="car-detail">
<CarPhotoBanner photos={this.state.images} />
<PriceBanner title={this.state.title} price={this.state.price} mileage={this.state.mileage} />
<ProfileBanner doors={this.state.doors} drive={this.state.drive} />
<BannerDivider />
<ColorBanner color_ext={this.state.color_ext} color_int={this.state.color_int} />
<BannerDivider />
<PkgBanner />
<BannerDivider />
<PerfBanner />
</div>
);
}
}
|
app/components/Icon.js
|
nmorel/magic-counter
|
import React from 'react';
import {StyleSheet, Text} from 'react-native';
export const icons = {
new: convertFontCode('e05e'),
addPlayer: convertFontCode('e7f0'),
reset: convertFontCode('e042'),
menu: convertFontCode('e3c7'),
add: convertFontCode('e147'),
remove: convertFontCode('e15c'),
};
function convertFontCode(code) {
return String.fromCharCode(parseInt(code, 16));
}
export function Icon({icon, style}) {
return <Text style={[styles.icon, style]}>{icon}</Text>;
}
const styles = StyleSheet.create({
icon: {
fontFamily: 'icomoon',
},
});
|
src/examples/react/src/editors/InputPet.js
|
nikospara/egkyron
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Pet from 'model/Pet';
import Vaccination from 'model/Vaccination';
import InputText from 'controls/InputText';
import InputGender from './InputGender';
import InputArray from './InputArray';
import InputVaccination from './InputVaccination';
import { attachInput, simpleShouldComponentUpdate } from 'controls/utils';
import Form from 'react-bootstrap/Form';
import Col from 'react-bootstrap/Col';
import uuid from 'uuid';
const GENDER_OPTIONS = [
{ id: 'M', label: 'Male' },
{ id: 'F', label: 'Female' }
];
export default class InputPet extends Component {
_handlers = {
addVaccination: null
};
constructor(props) {
super(props);
this.state = {
value: props.value || new Pet()
};
this._handlers.addVaccination = this.addVaccination.bind(this);
}
handleChange(field, value) {
var newValue = new Pet(this.state.value);
newValue[field] = value;
this.setState({
value: newValue
});
this.props.onChange && this.props.onChange(newValue);
}
addVaccination() {
return new Vaccination({id: uuid.v4()});
}
shouldComponentUpdate(nextProps, nextState) {
return simpleShouldComponentUpdate.call(this, nextProps, nextState);
}
render() {
return (
<Form.Row>
{this.props.label ? <legend>{this.props.label}</legend> : null}
<Col sm={5}>
<InputText label="Name" {...attachInput(this, 'name')} />
</Col>
<Col sm={5}>
<InputText label="Type" {...attachInput(this, 'type')} />
</Col>
<Col sm={2}>
<InputGender label="Gender" {...attachInput(this, 'gender')} options={GENDER_OPTIONS} />
</Col>
<Col sm={12}>
<InputArray label="Vaccinations" {...attachInput(this, 'vaccinations')} innerComponent={InputVaccination}
add={this._handlers.addVaccination} addLabel="Add vaccination" removeLabel="Remove vaccination" />
</Col>
</Form.Row>
);
}
}
InputPet.propTypes = {
value: PropTypes.instanceOf(Pet),
onChange: PropTypes.func,
label: PropTypes.string,
validity: PropTypes.object
};
|
src/components/google_map.js
|
CaseyKelly/react-redux-weather-charts
|
import React, { Component } from 'react';
class GoogleMap extends Component {
componentDidMount() {
new google.maps.Map(this.refs.map, {
zoom: 12,
center: {
lat: this.props.lat,
lng: this.props.lon
}
});
}
render() {
return <div ref="map" />;
}
}
export default GoogleMap;
|
example/src/client.js
|
tizmagik/react-head
|
import React from 'react';
import { hydrate } from 'react-dom';
import { HeadProvider } from 'react-head';
import App from '../App';
hydrate(
<HeadProvider>
<App />
</HeadProvider>,
document.getElementById('root')
);
if (module.hot) {
module.hot.accept();
}
|
packages/react-devtools-shared/src/devtools/views/ReactLogo.js
|
mjackson/react
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import React from 'react';
import styles from './ReactLogo.css';
type Props = {|
className?: string,
|};
export default function ReactLogo({className}: Props) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
className={`${styles.ReactLogo} ${className || ''}`}
viewBox="-11.5 -10.23174 23 20.46348">
<circle cx="0" cy="0" r="2.05" fill="currentColor" />
<g stroke="currentColor" strokeWidth="1" fill="none">
<ellipse rx="11" ry="4.2" />
<ellipse rx="11" ry="4.2" transform="rotate(60)" />
<ellipse rx="11" ry="4.2" transform="rotate(120)" />
</g>
</svg>
);
}
|
src/components/Datepicker/index.js
|
wiki1024/sam-bs
|
import React from 'react'
import moment from 'moment'
import _ from 'lodash'
import Calendar from './Calendar'
import { Collapse } from 'react-bootstrap'
import { updateMonth, selectDate, toggleOpen } from '../../actions/datePickerAction'
import { debounce } from '../../util'
import Header from './header'
import Month from './month'
import classnames from 'classnames'
const DatePicker = (props) =>{
let {id, date, month, year, isOpen} = props
let dates = generateDates(month,year)
let controlClass = classnames({
'control-group':true,
'focused':isOpen
})
return (
<div className='datePicker' onClick={ (e)=>{ e.stopPropagation() } }>
<span className={ controlClass } onClick = { (e) => { toggleOpen({id:id, isOpen:!isOpen});e.stopPropagation() } }>
<input className='form-control'
type='text'
value={ date.format('MM/DD/YYYY') } />
<div className='input-group-addon'><i className='fa fa-calendar' aria-hidden='true'></i></div>
</span>
<Collapse in= { isOpen }>
<div className='calendar' >
<Header month={month} id={id}
year={year}
updateMonth={debounce(updateMonth,100)}/>
<Month month={month} id={id}
year={year}
dates={dates}
selected= {date}
selectDate={selectDate} key={month}/>
</div>
</Collapse>
</div>
)
}
function generateDates(month,year) {
let firstDate = moment([year, month]).weekday(0)
let dates = _.range(42).map((val, index) => {
return firstDate.clone().add(index, 'd')
})
return dates
}
//
export default DatePicker
|
examples/huge-apps/routes/Course/routes/Assignments/components/Sidebar.js
|
cojennin/react-router
|
import React from 'react';
import { Link } from 'react-router';
class Sidebar extends React.Component {
render () {
var assignments = COURSES[this.props.params.courseId].assignments
return (
<div>
<h3>Sidebar Assignments</h3>
<ul>
{assignments.map(assignment => (
<li key={assignment.id}>
<Link to={`/course/${this.props.params.courseId}/assignments/${assignment.id}`}>
{assignment.title}
</Link>
</li>
))}
</ul>
</div>
);
}
}
export default Sidebar;
|
frontend/component/TopicDetail.js
|
wangmuming/node-forum
|
import React from 'react';
import 'highlight.js/styles/github-gist.css';
import {getTopicDetail, addComment, deleteComment, deleteTopic} from '../lib/client';
import {renderMarkdown} from '../lib/utils';
import { Router, Route, Link, browserHistory } from 'react-router';
import CommentEditor from './CommentEditor';
import {redirectURL} from '../lib/utils';
export default class TopicDetail extends React.Component{
constructor(pros){
super(pros);
this.state = {};
}
componentDidMount(){
this.refresh();
}
// 调取话题接口
refresh(){
getTopicDetail(this.props.params.id)
.then(topic => {
topic.html = renderMarkdown(topic.content);
if(topic.comments){
for(const item of topic.comments){
item.html = renderMarkdown(item.content);
}
}
this.setState({topic});
})
.catch(err => console.error(err));
}
// 点击删除评论按钮
handleDeleteComment(cid){
if(!confirm('是否删除评论?')) return;
deleteComment(this.state.topic._id, cid)
.then(comment => {
this.refresh();
})
.catch(err => {
alert(err);
});
}
handleDeleteTopic(){
if(!confirm('是否删除主题?')) return;
deleteTopic(this.state.topic._id)
.then(() => {
redirectURL('/');
})
.catch(err => {
alert(err);
});
}
render(){
const topic = this.state.topic;
if(!topic){
return(
<div>正在加载...</div>
);
}
return(
<div>
<h2>{topic.title}</h2>
<p>{topic.author.nickname || '佚名'} 发表于 {topic.createdAt}</p>
<p>
{!topic.permission.edit ? null :
<Link to={`/topic/${topic._id}/edit`} className="btn btn-xs btn-primary">
<i className="glyphicon glyphicon-edit"></i> 编辑
</Link>
}
{!topic.permission.delete ? null :
<button className="btn btn-xs btn-danger" onClick={this.handleDeleteTopic.bind(this)}>
<i className="glyphicon glyphicon-trash"></i> 删除
</button>
}
</p>
<hr />
<p>标签:
{topic.tags.map((tag, i) => {
return(
<span className="label label-primary" style={{marginRight: 10}} key={i}>{tag}</span>
);
})}
</p>
<section dangerouslySetInnerHTML={{__html: topic.html}}></section>
<CommentEditor
title="发表评论"
onSave={(comment, done) => {
addComment(this.state.topic._id, comment.content)
.then(comment => {
done();
this.refresh();
})
.catch(err => {
done();
alert(err);
});
}}
/>
<ul className="list-group">
{topic.comments.map((item, i) => {
return(
<li className="list-group-item" key={i}>
<span className="pull-right">
{!item.permission.delete ? null :
<button className="btn btn-xs btn-danger" onClick={this.handleDeleteComment.bind(this, item._id)}>
<i className="glyphicon glyphicon-trash"></i>
</button>
}
</span>
{item.author.nickname || '佚名'}于{item.createdAt}说:
<p dangerouslySetInnerHTML={{__html: item.html}}></p>
</li>
);
})}
</ul>
</div>
);
}
}
|
web/client/configdev/src/config/ScreensaverMenu.js
|
project-owner/Peppy
|
/* Copyright 2019 Peppy Player peppy.player@gmail.com
This file is part of Peppy Player.
Peppy Player is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Peppy Player 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with Peppy Player. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react';
import {FormControl} from '@material-ui/core';
import Factory from "../Factory";
export default class ScreensaverMenu extends React.Component {
render() {
const { params, updateState, labels } = this.props;
const items = ["clock", "logo", "slideshow", "peppymeter", "peppyweather", "spectrum", "lyrics", "random"];
return (
<FormControl>
{items.map((v) => {return Factory.createCheckbox(v, params, updateState, labels)})}
</FormControl>
);
}
}
|
src/views/Components/Buttons/Buttons.js
|
corbinpage/react-play
|
import React, { Component } from 'react';
class Buttons extends Component {
render() {
return (
<div className="animated fadeIn">
<div className="row">
<div className="col-md-6">
<div className="card">
<div className="card-header">
<strong>Options</strong>
</div>
<div className="card-block">
<button type="button" className="btn btn-primary">Primary</button>
<button type="button" className="btn btn-secondary">Secondary</button>
<button type="button" className="btn btn-success">Success</button>
<button type="button" className="btn btn-warning">Warning</button>
<button type="button" className="btn btn-danger">Danger</button>
<button type="button" className="btn btn-link">Link</button>
</div>
</div>
<div className="card">
<div className="card-header">
<strong>With Icons</strong>
</div>
<div className="card-block">
<button type="button" className="btn btn-primary"><i className="fa fa-star"></i> Primary</button>
<button type="button" className="btn btn-secondary"><i className="fa fa-lightbulb-o"></i> Secondary</button>
<button type="button" className="btn btn-success"><i className="fa fa-magic"></i> Success</button>
<button type="button" className="btn btn-warning"><i className="fa fa-map-marker"></i> Warning</button>
<button type="button" className="btn btn-danger"><i className="fa fa-rss"></i> Danger</button>
<button type="button" className="btn btn-link"><i className="fa fa-link"></i> Link</button>
</div>
</div>
<div className="card">
<div className="card-header">
<strong>Size Large</strong> <small>Add this class <code>.btn-lg</code></small>
</div>
<div className="card-block">
<button type="button" className="btn btn-primary btn-lg">Primary</button>
<button type="button" className="btn btn-secondary btn-lg">Secondary</button>
<button type="button" className="btn btn-success btn-lg">Success</button>
<button type="button" className="btn btn-info btn-lg">Info</button>
<button type="button" className="btn btn-warning btn-lg">Warning</button>
<button type="button" className="btn btn-danger btn-lg">Danger</button>
<button type="button" className="btn btn-link btn-lg">Link</button>
</div>
</div>
<div className="card">
<div className="card-header">
<strong>Size Small</strong> <small>Add this class <code>.btn-sm</code></small>
</div>
<div className="card-block">
<button type="button" className="btn btn-primary btn-sm">Primary</button>
<button type="button" className="btn btn-secondary btn-sm">Secondary</button>
<button type="button" className="btn btn-success btn-sm">Success</button>
<button type="button" className="btn btn-info btn-sm">Info</button>
<button type="button" className="btn btn-warning btn-sm">Warning</button>
<button type="button" className="btn btn-danger btn-sm">Danger</button>
<button type="button" className="btn btn-link btn-sm">Link</button>
</div>
</div>
<div className="card">
<div className="card-header">
<strong>Disabled state</strong> <small>Add this <code>disabled="disabled"</code></small>
</div>
<div className="card-block">
<button type="button" className="btn btn-primary" disabled="disabled">Primary</button>
<button type="button" className="btn btn-secondary" disabled="disabled">Secondary</button>
<button type="button" className="btn btn-success" disabled="disabled">Success</button>
<button type="button" className="btn btn-info" disabled="disabled">Info</button>
<button type="button" className="btn btn-warning" disabled="disabled">Warning</button>
<button type="button" className="btn btn-danger" disabled="disabled">Danger</button>
<button type="button" className="btn btn-link" disabled="disabled">Link</button>
</div>
</div>
<div className="card">
<div className="card-header">
<strong>Active state</strong> <small>Add this class <code>.active</code></small>
</div>
<div className="card-block">
<button type="button" className="btn btn-primary active">Primary</button>
<button type="button" className="btn btn-secondary active">Secondary</button>
<button type="button" className="btn btn-success active">Success</button>
<button type="button" className="btn btn-info active">Info</button>
<button type="button" className="btn btn-warning active">Warning</button>
<button type="button" className="btn btn-danger active">Danger</button>
<button type="button" className="btn btn-link active">Link</button>
</div>
</div>
<div className="card">
<div className="card-header">
<strong>Block Level Buttons</strong> <small>Add this class <code>.btn-block</code></small>
</div>
<div className="card-block">
<button type="button" className="btn btn-secondary btn-lg btn-block">Block level button</button>
<button type="button" className="btn btn-primary btn-lg btn-block">Block level button</button>
<button type="button" className="btn btn-success btn-lg btn-block">Block level button</button>
<button type="button" className="btn btn-info btn-lg btn-block">Block level button</button>
<button type="button" className="btn btn-warning btn-lg btn-block">Block level button</button>
<button type="button" className="btn btn-danger btn-lg btn-block">Block level button</button>
<button type="button" className="btn btn-link btn-lg btn-block">Block level button</button>
</div>
</div>
</div>
<div className="col-md-6">
<div className="card">
<div className="card-header">
<strong>Options</strong>
</div>
<div className="card-block">
<button type="button" className="btn btn-outline-primary">Primary</button>
<button type="button" className="btn btn-outline-secondary">Secondary</button>
<button type="button" className="btn btn-outline-success">Success</button>
<button type="button" className="btn btn-outline-warning">Warning</button>
<button type="button" className="btn btn-outline-danger">Danger</button>
</div>
</div>
<div className="card">
<div className="card-header">
<strong>With Icons</strong>
</div>
<div className="card-block">
<button type="button" className="btn btn-outline-primary"><i className="fa fa-star"></i> Primary</button>
<button type="button" className="btn btn-outline-secondary"><i className="fa fa-lightbulb-o"></i> Secondary</button>
<button type="button" className="btn btn-outline-success"><i className="fa fa-magic"></i> Success</button>
<button type="button" className="btn btn-outline-warning"><i className="fa fa-map-marker"></i> Warning</button>
<button type="button" className="btn btn-outline-danger"><i className="fa fa-rss"></i> Danger</button>
</div>
</div>
<div className="card">
<div className="card-header">
<strong>Size Large</strong> <small>Add this class <code>.btn-lg</code></small>
</div>
<div className="card-block">
<button type="button" className="btn btn-outline-primary btn-lg">Primary</button>
<button type="button" className="btn btn-outline-secondary btn-lg">Secondary</button>
<button type="button" className="btn btn-outline-success btn-lg">Success</button>
<button type="button" className="btn btn-outline-info btn-lg">Info</button>
<button type="button" className="btn btn-outline-warning btn-lg">Warning</button>
<button type="button" className="btn btn-outline-danger btn-lg">Danger</button>
</div>
</div>
<div className="card">
<div className="card-header">
<strong>Size Small</strong> <small>Add this class <code>.btn-sm</code></small>
</div>
<div className="card-block">
<button type="button" className="btn btn-outline-primary btn-sm">Primary</button>
<button type="button" className="btn btn-outline-secondary btn-sm">Secondary</button>
<button type="button" className="btn btn-outline-success btn-sm">Success</button>
<button type="button" className="btn btn-outline-info btn-sm">Info</button>
<button type="button" className="btn btn-outline-warning btn-sm">Warning</button>
<button type="button" className="btn btn-outline-danger btn-sm">Danger</button>
</div>
</div>
<div className="card">
<div className="card-header">
<strong>Disabled state</strong> <small>Add this <code>disabled="disabled"</code></small>
</div>
<div className="card-block">
<button type="button" className="btn btn-outline-primary" disabled="disabled">Primary</button>
<button type="button" className="btn btn-outline-secondary" disabled="disabled">Secondary</button>
<button type="button" className="btn btn-success" disabled="disabled">Success</button>
<button type="button" className="btn btn-outline-info" disabled="disabled">Info</button>
<button type="button" className="btn btn-outline-warning" disabled="disabled">Warning</button>
<button type="button" className="btn btn-outline-danger" disabled="disabled">Danger</button>
</div>
</div>
<div className="card">
<div className="card-header">
<strong>Active state</strong> <small>Add this class <code>.active</code></small>
</div>
<div className="card-block">
<button type="button" className="btn btn-outline-primary active">Primary</button>
<button type="button" className="btn btn-outline-secondary active">Secondary</button>
<button type="button" className="btn btn-outline-success active">Success</button>
<button type="button" className="btn btn-outline-info active">Info</button>
<button type="button" className="btn btn-outline-warning active">Warning</button>
<button type="button" className="btn btn-outline-danger active">Danger</button>
</div>
</div>
<div className="card">
<div className="card-header">
<strong>Block Level Buttons</strong> <small>Add this class <code>.btn-block</code></small>
</div>
<div className="card-block">
<button type="button" className="btn btn-outline-secondary btn-lg btn-block">Block level button</button>
<button type="button" className="btn btn-outline-primary btn-lg btn-block">Block level button</button>
<button type="button" className="btn btn-outline-success btn-lg btn-block">Block level button</button>
<button type="button" className="btn btn-outline-info btn-lg btn-block">Block level button</button>
<button type="button" className="btn btn-outline-warning btn-lg btn-block">Block level button</button>
<button type="button" className="btn btn-outline-danger btn-lg btn-block">Block level button</button>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default Buttons;
|
js/source/Customizer.js
|
peano-ito/giuseppe
|
/*********************************************************************/
/* Customizer */
/* (c) 2017 Peano System Inc. */
/*********************************************************************/
'use strict';
import React from 'react';
import { store } from './Reducer.js';
import Utility from './Utility.js';
/*********************************************************************/
/* Constants */
/*********************************************************************/
const THEME_COLOR = {
A: {
'--text-color': '#000000',
'--background-color': '#FFFFFF',
'--main-color': '#008000',
'--main-assoc-color': '#FFFFFF',
'--sub-color': '#00EE00',
'--sub-assoc-color': '#FFFFFF',
'--accent-color': '#3333FF',
'--accent-assoc-color': '#FFFFFF',
'--highlighted-color': '#FF33FF',
'--highlighted-assoc-color': '#FFFFFF',
'--ok-color': '#0000FF',
'--ng-color': '#FF0000',
},
B: {
'--text-color': '#000000',
'--background-color': '#FFFFFF',
'--main-color': '#FF0000',
'--main-assoc-color': '#FFFFFF',
'--sub-color': '#000000',
'--sub-assoc-color': '#FFFFFF',
'--accent-color': '#008000',
'--accent-assoc-color': '#FFFFFF',
'--highlighted-color': '#0000FF',
'--highlighted-assoc-color': '#FFFFFF',
'--ok-color': '#0000FF',
'--ng-color': '#FF0000',
},
C: {
'--text-color': '#333333',
'--background-color': '#FAF1F2',
'--main-color': '#7A3849',
'--main-assoc-color': '#EEEEEE',
'--sub-color': '#666666',
'--sub-assoc-color': '#EEEEEE',
'--accent-color': '#305C37',
'--accent-assoc-color': '#EEEEEE',
'--highlighted-color': '#B66BB6',
'--highlighted-assoc-color': '#EEEEEE',
'--ok-color': '#244077',
'--ng-color': '#875548',
},
D: {
'--text-color': '#333333',
'--background-color': '#FCFCF6',
'--main-color': '#4B4238',
'--main-assoc-color': '#FFFFFF',
'--sub-color': '#BAB7A3',
'--sub-assoc-color': '#FFFFFF',
'--accent-color': '#DB7093',
'--accent-assoc-color': '#FFFFFF',
'--highlighted-color': '#82B340',
'--highlighted-assoc-color': '#FFFFFF',
'--ok-color': '#0000FF',
'--ng-color': '#FF0000',
},
};
/*********************************************************************/
/* Switch Theme Color */
/*********************************************************************/
function switchThemeColor(key) {
let color = THEME_COLOR[key];
for (var variable in color) {
document.documentElement.style.setProperty(variable, color[variable]);
}
return;
}
// Initialize
switchThemeColor('A');
/*********************************************************************/
/* Dispatch */
/*********************************************************************/
const dispatch = {
selectThemeColor: (e) => {
e.stopPropagation();
store.dispatch(Utility.createAction('CUSTOMIZER', 'COLOR', { color: e.target.value }));
return;
},
selectNaviDesign: (e) => {
e.stopPropagation();
store.dispatch(Utility.createAction('CUSTOMIZER', 'NAV_DESIGN', { design: e.target.value }));
return;
},
selectNaviStyle: (e) => {
e.stopPropagation();
store.dispatch(Utility.createAction('CUSTOMIZER', 'NAV_STYLE', { style: e.target.value }));
return;
},
};
/*********************************************************************/
/* Reducer */
/*********************************************************************/
export function reducer(state, action) {
var ret = state;
if (action.action == 'COLOR') {
ret = Utility.clone(state);
ret.customizer.color = action.data.color;
switchThemeColor(action.data.color);
} else if (action.action == 'NAV_DESIGN') {
ret = Utility.clone(state);
ret.customizer.navi.design = action.data.design;
ret.customizer.navi.style = state.customizer.navi.old[action.data.design];
} else if (action.action == 'NAV_STYLE') {
ret = Utility.clone(state);
ret.customizer.navi.style = action.data.style;
ret.customizer.navi.old[state.customizer.navi.design] = action.data.style;
}
return ret;
}
/*********************************************************************/
/* [Customizer] Customizer */
/*********************************************************************/
class Customizer extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
<section className="band Customizer">
<div>
<span>
<span>テーマカラー:</span>
<select value={this.props.state.customizer.color} onChange={dispatch.selectThemeColor.bind(this)}>
<option value="A">A案: 新緑</option>
<option value="B">B案: 情熱</option>
<option value="C">C案: あずき</option>
<option value="D">D案: ノスタルジー</option>
</select>
</span>
<span>
<span>ナビ設計:</span>
<select value={this.props.state.customizer.navi.design} onChange={dispatch.selectNaviDesign.bind(this)}>
<option value="a">(a)案: シングルナビゲーション</option>
<option value="b">(b)案: ドロップダウン</option>
</select>
</span>
<span>
<span>ナビスタイル:</span>
{(() => {
if (this.props.state.customizer.navi.design == 'a') {
return(
<select value={this.props.state.customizer.navi.style} onChange={dispatch.selectNaviStyle.bind(this)}>
<option value="D1">(a)-①案:</option>
<option value="D2">(a)-②案:</option>
</select>
);
} else {
return(
<select value={this.props.state.customizer.navi.style} onChange={dispatch.selectNaviStyle.bind(this)}>
<option value="D1">(b)-①案:</option>
<option value="D2">(b)-②案:</option>
<option value="D3">(b)-③案:</option>
</select>
);
}
})()}
</span>
</div>
</section>
);
}
}
/*********************************************************************/
/* Export */
/*********************************************************************/
export default Customizer;
|
client/node_modules/uu5g03/doc/main/client/src/components/component-loader.js
|
UnicornCollege/ucl.itkpd.configurator
|
import React from 'react';
import UU5 from 'uu5';
import './component-loader.css';
export default React.createClass({
//@@viewOn:mixins
mixins: [
UU5.Common.BaseMixin,
UU5.Common.LoadMixin,
UU5.Layout.ContainerMixin
],
//@@viewOff:mixins
//@@viewOn:statics
statics: {
tagName: 'UU5.Doc.Components.ComponentLoader',
classNames: {
main: 'uu5-doc-components-component-loader'
},
defaults: {},
limits: {},
calls: {
onLoad: 'loadComponentData'
},
warnings: {},
errors: {},
lsi: {},
opt: {}
},
//@@viewOff:statics
//@@viewOn:propTypes
//@@viewOff:propTypes
//@@viewOn:getDefaultProps
//@@viewOff:getDefaultProps
//@@viewOn:standardComponentLifeCycle
componentWillReceiveProps(nextProps) {
let dtoIn = this._getReloadDtoIn();
dtoIn.data = { name: nextProps.name };
this.reload('onLoad', dtoIn);
},
//@@viewOff:standardComponentLifeCycle
//@@viewOn:interface
//@@viewOff:interface
//@@viewOn:overridingMethods
getOnLoadData_() {
return {
name: this.getName()
};
},
//@@viewOff:overridingMethods
//@@viewOn:componentSpecificHelpers
//@@viewOff:componentSpecificHelpers
//@@viewOn:render
render() {
return (
<UU5.Layout.Container {...this.getMainPropsToPass()}>
{this.getLoadFeedbackChildren(dtoOut => {
let result = null;
if (this.getName().match(/Mixin$/)) {
result = <UU5.DocKit.Mixin mixinData={dtoOut.data} />;
} else {
result = <UU5.DocKit.Component componentData={dtoOut.data} />;
}
return result;
})}
</UU5.Layout.Container>
);
}
//@@viewOn:render
});
|
packages/mineral-ui-icons/src/IconPlayCircleOutline.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 IconPlayCircleOutline(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M10 16.5l6-4.5-6-4.5v9zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/>
</g>
</Icon>
);
}
IconPlayCircleOutline.displayName = 'IconPlayCircleOutline';
IconPlayCircleOutline.category = 'av';
|
packages/wix-style-react/src/FontUpgrade/test/FontUpgrade.spec.js
|
wix/wix-style-react
|
import React from 'react';
import { createRendererWithUniDriver, cleanup } from '../../../test/utils/unit';
import FontUpgrade from '../FontUpgrade';
import { FontUpgradePrivateDriverFactory } from './FontUpgrade.private.uni.driver';
import { FontUpgradeContext } from '../context';
describe('FontUpgrade', () => {
const render = createRendererWithUniDriver(FontUpgradePrivateDriverFactory);
afterEach(cleanup);
it('should be active', async () => {
const text = 'text';
const { driver } = render(
<FontUpgrade>
<div id="wrapper">
<FontUpgradeContext.Consumer>
{({ active }) => {
return <div data-active={active ? 'active' : null}>{text}</div>;
}}
</FontUpgradeContext.Consumer>
</div>
</FontUpgrade>,
);
expect(await driver.getElement('[data-active=active]').exists()).toBe(true);
expect(await driver.getElement('[data-active=active]').text()).toContain(
text,
);
});
it('should not be active', async () => {
const text = 'text';
const { driver } = render(
<div id="wrapper">
<FontUpgradeContext.Consumer>
{({ active }) => {
return <div data-active={active ? 'active' : null}>{text}</div>;
}}
</FontUpgradeContext.Consumer>
</div>,
);
expect(await driver.getElement('[data-active=active]').exists()).toBe(
false,
);
});
it('should have className', async () => {
const className = 'some-class-name';
const { driver } = render(<FontUpgrade className={className} />);
expect((await driver.element()).className).toContain(className);
});
it.each(['span', 'div'])('should be a %p element', async element => {
const { driver } = render(<FontUpgrade as={element} />);
expect((await driver.element()).tagName).toBe(element.toUpperCase());
});
it('should return true if active', async () => {
const { driver } = render(<FontUpgrade active />);
expect(await driver.isActive()).toBe(true);
});
it('should return false if not active', async () => {
const { driver } = render(<FontUpgrade active={false} />);
expect(await driver.isActive()).toBe(false);
});
});
|
from-zero-to-vertical/src/components/atoms/PApp/PApp2.js
|
Muzietto/react-playground
|
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
// cfr. https://codeburst.io/my-journey-to-make-styling-with-material-ui-right-6a44f7c68113
const useStyles = makeStyles(() => ({
outlinedRoot: { // if the style the root, the fieldset inside will mess up things
'&:hover': {
border: '1px solid red',
},
},
}));
function PApp2() {
const classes = useStyles();
const InputProps = {
classes: {
root: classes.outlinedRoot,
},
};
return (
<TextField
id='outlined-name'
label='Name'
className={classes.textField}
margin='normal'
variant='outlined'
InputProps={InputProps}
/>
);
}
export default PApp2;
|
src/components/Switch/index.js
|
HenriBeck/materialize-react
|
// @flow strict-local
import React from 'react';
import PropTypes from 'prop-types';
import getNotDeclaredProps from 'react-get-not-declared-props';
import Ripple from '../Ripple';
import {
ENTER,
SPACE_BAR,
} from '../../utils/constants';
import Sheet, { type Data } from './Sheet';
type Props = {
toggled: boolean,
onChange: () => void,
className: string,
disabled: boolean,
noink: boolean,
color: 'primary' | 'accent',
};
type State = { isFocused: boolean };
export default class Switch extends React.PureComponent<Props, State> {
static propTypes = {
toggled: PropTypes.bool.isRequired,
onChange: PropTypes.func.isRequired,
className: PropTypes.string,
disabled: PropTypes.bool,
noink: PropTypes.bool,
color: PropTypes.oneOf([
'primary',
'accent',
]),
};
static defaultProps = {
className: '',
disabled: false,
noink: false,
color: 'primary',
};
state = { isFocused: false };
handleFocus = () => {
this.setState({ isFocused: true });
};
handleBlur = () => {
this.setState({ isFocused: false });
};
handleKeyUp = (ev: SyntheticKeyboardEvent<HTMLSpanElement>) => {
if (ev.keyCode === ENTER || ev.keyCode === SPACE_BAR) {
this.props.onChange();
}
};
handleClick = (ev: SyntheticMouseEvent<HTMLSpanElement>) => {
if (ev.target === ev.currentTarget) {
this.props.onChange();
}
};
render() {
const data: Data = {
toggled: this.props.toggled,
disabled: this.props.disabled,
color: this.props.color,
};
return (
<Sheet data={data}>
{({ classes }) => (
<span
{...getNotDeclaredProps(this.props, Switch)}
role="switch"
className={`${classes.switch} ${this.props.className}`}
aria-checked={this.props.toggled}
aria-disabled={this.props.disabled}
tabIndex={this.props.disabled ? -1 : 0}
onKeyUp={this.handleKeyUp}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
onClick={this.handleClick}
>
<span className={classes.track} />
<span className={classes.thumb}>
<Ripple
round
center
nowaves={this.props.noink}
isFocused={this.state.isFocused}
className={classes.ripple}
onPress={this.props.onChange}
/>
</span>
</span>
)}
</Sheet>
);
}
}
|
src/helpers/__tests__/connectData-test.js
|
mattijsbliek/record-client
|
import { expect } from 'chai';
import React from 'react';
import { div } from 'react-dom';
import connectData from '../connectData';
describe('connectData', () => {
let fetchData;
let fetchDataDeferred;
let WrappedComponent;
let DataComponent;
beforeEach(() => {
fetchData = 'fetchDataFunction';
fetchDataDeferred = 'fetchDataDeferredFunction';
WrappedComponent = () =>
<div />;
DataComponent = connectData(fetchData, fetchDataDeferred)(WrappedComponent);
});
it('should set fetchData as a static property of the final component', () => {
expect(DataComponent.fetchData).to.equal(fetchData);
});
it('should set fetchDataDeferred as a static property of the final component', () => {
expect(DataComponent.fetchDataDeferred).to.equal(fetchDataDeferred);
});
});
|
app/jsx/shared/components/CreateOrUpdateUserModal.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 {bool, func, shape, string, element, oneOf} from 'prop-types'
import {Avatar} from '@instructure/ui-elements'
import {Button} from '@instructure/ui-buttons'
import {Checkbox, TextInput} from '@instructure/ui-forms'
import {FormFieldGroup} from '@instructure/ui-form-field'
import update from 'immutability-helper'
import {get, isEmpty} from 'lodash'
import axios from 'axios'
import I18n from 'i18n!account_course_user_search'
import {firstNameFirst, lastNameFirst, nameParts} from 'user_utils'
import preventDefault from 'compiled/fn/preventDefault'
import unflatten from 'compiled/object/unflatten'
import registrationErrors from 'compiled/registration/registrationErrors'
import Modal from './InstuiModal'
import TimeZoneSelect from './TimeZoneSelect'
const trim = (str = '') => str.trim()
const initialState = {
open: false,
data: {
user: {},
pseudonym: {
send_confirmation: true
}
},
errors: {}
}
export default class CreateOrUpdateUserModal extends React.Component {
static propTypes = {
// whatever you pass as the child, when clicked, will open the dialog
children: element.isRequired,
createOrUpdate: oneOf(['create', 'update']).isRequired,
url: string.isRequired,
user: shape({
name: string.isRequired,
sortable_name: string,
short_name: string,
email: string,
time_zone: string
}),
customized_login_handle_name: string,
delegated_authentication: bool.isRequired,
showSIS: bool.isRequired,
afterSave: func.isRequired
}
static defaultProps = {
customized_login_handle_name: window.ENV.customized_login_handle_name,
delegated_authentication: window.ENV.delegated_authentication,
showSIS: window.ENV.SHOW_SIS_ID_IN_NEW_USER_FORM
}
state = {...initialState}
componentWillMount() {
if (this.props.createOrUpdate === 'update') {
// only get the attributes from the user that we are actually going to show in the <input>s
// and send to the server. Because if we send the server extraneous attributes like user[id]
// it throws 401 errors
const userDataFromProps = this.getInputFields().reduce((memo, {name}) => {
const key = name.match(/user\[(.*)\]/)[1] // extracts 'short_name' from 'user[short_name]'
return {...memo, [key]: this.props.user[key]}
}, {})
this.setState(update(this.state, {data: {user: {$set: userDataFromProps}}}))
}
}
onChange = (field, value) => {
this.setState(prevState => {
let newState = update(prevState, {
data: unflatten({[field]: {$set: value}}),
errors: {$set: {}}
})
// set sensible defaults for sortable_name and short_name
if (field === 'user[name]') {
const u = prevState.data.user
// shamelessly copypasted from user_sortable_name.js
const sortableNameParts = nameParts(trim(u.sortable_name))
if (!trim(u.sortable_name) || trim(firstNameFirst(sortableNameParts)) === trim(u.name)) {
const newSortableName = lastNameFirst(nameParts(value, sortableNameParts[1]))
newState = update(newState, {data: {user: {sortable_name: {$set: newSortableName}}}})
}
if (!trim(u.short_name) || trim(u.short_name) === trim(u.name)) {
newState = update(newState, {data: {user: {short_name: {$set: value}}}})
}
}
return newState
})
}
close = () => this.setState({open: false})
onSubmit = () => {
if (!isEmpty(this.state.errors)) return
const method = {create: 'POST', update: 'PUT'}[this.props.createOrUpdate]
axios({url: this.props.url, method, data: this.state.data}).then(
response => {
const getUserObj = o => (o.user ? getUserObj(o.user) : o)
const user = getUserObj(response.data)
const userName = user.name
const wrapper = `<a href='/users/${user.id}'>$1</a>`
$.flashMessage(
response.data.message_sent
? I18n.t(
'*%{userName}* saved successfully! They should receive an email confirmation shortly.',
{userName, wrapper}
)
: I18n.t('*%{userName}* saved successfully!', {userName, wrapper})
)
this.setState({...initialState})
if (this.props.afterSave) this.props.afterSave(response)
},
({response}) => {
const errors = registrationErrors(response.data.errors)
$.flashError('Something went wrong saving user details.')
this.setState({errors})
}
)
}
getInputFields = () => {
const showCustomizedLoginId =
this.props.customized_login_handle_name || this.props.delegated_authentication
return [
{
name: 'user[name]',
label: I18n.t('Full Name'),
hint: I18n.t('This name will be used by teachers for grading.'),
required: I18n.t('Full name is required')
},
{
name: 'user[short_name]',
label: I18n.t('Display Name'),
hint: I18n.t('People will see this name in discussions, messages and comments.')
},
{
name: 'user[sortable_name]',
label: I18n.t('Sortable Name'),
hint: I18n.t('This name appears in sorted lists.')
}
]
.concat(
this.props.createOrUpdate === 'create'
? [
{
name: 'pseudonym[unique_id]',
label: this.props.customized_login_handle_name || I18n.t('Email'),
required: this.props.customized_login_handle_name
? I18n.t('%{login_handle} is required', {
login_handle: this.props.customized_login_handle_name
})
: I18n.t('Email is required')
},
showCustomizedLoginId && {
name: 'pseudonym[path]',
label: I18n.t('Email'),
required: I18n.t('Email is required')
},
this.props.showSIS && {
name: 'pseudonym[sis_user_id]',
label: I18n.t('SIS ID')
},
{
name: 'pseudonym[send_confirmation]',
label: I18n.t('Email the user about this account creation'),
Component: Checkbox
}
]
: [
{
name: 'user[email]',
label: I18n.t('Default Email')
},
{
name: 'user[time_zone]',
label: I18n.t('Time Zone'),
Component: TimeZoneSelect
}
]
)
.filter(Boolean)
}
render = () => (
<span>
<Modal
as="form"
onSubmit={preventDefault(this.onSubmit)}
open={this.state.open}
onDismiss={this.close}
size="medium"
label={
this.props.createOrUpdate === 'create' ? (
I18n.t('Add a New User')
) : (
<span>
<Avatar
size="small"
name={this.state.data.user.name}
src={this.props.user.avatar_url}
data-fs-exclude
/>{' '}
{I18n.t('Edit User Details')}
</span>
)
}
>
<Modal.Body>
<FormFieldGroup layout="stacked" rowSpacing="small" description="">
{this.getInputFields().map(({name, label, hint, required, Component = TextInput}) => (
<Component
key={name}
label={label}
value={get(this.state.data, name)}
checked={get(this.state.data, name)}
onChange={e =>
this.onChange(
name,
e.target.type === 'checkbox' ? e.target.checked : e.target.value
)
}
required={!!required}
layout="inline"
messages={(this.state.errors[name] || [])
.map(errMsg => ({type: 'error', text: errMsg}))
.concat(hint && {type: 'hint', text: hint})
.filter(Boolean)}
/>
))}
</FormFieldGroup>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.close}>{I18n.t('Cancel')}</Button>
<Button type="submit" variant="primary">
{this.props.createOrUpdate === 'create' ? I18n.t('Add User') : I18n.t('Save')}
</Button>
</Modal.Footer>
</Modal>
{React.Children.map(this.props.children, child =>
// when you click whatever is the child element to this, open the modal
React.cloneElement(child, {
onClick: (...args) => {
if (child.props.onClick) child.props.onClick(...args)
this.setState({open: true})
}
})
)}
</span>
)
}
|
src/components/vidoe_detail.js
|
dulik06/ReduxStarter
|
import React from 'react';
const VideoDetail = (props) => {
const video = props.video;
if(!video) {
return <div>Loading...</div>;
}
const videoId = video.id.videoId;
const url = `https://www.youtube.com/embed/${videoId}`;
return(
<div className='video-detail col-md-8'>
<div className='embed-responsive embed-responsive-16by9'>
<iframe className='embed-responsive-item' src={ url }></iframe>
</div>
<div className='details'>
<div>{ video.snippet.title }</div>
<div>{ video.snippet.description }</div>
</div>
</div>
);
}
export default VideoDetail;
|
src/PlayerView.js
|
hannes-hochreiner/more-podcasts
|
import React, { Component } from 'react';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import PlayerPresenter from './PlayerPresenter';
import Toolbar from '@material-ui/core/Toolbar';
import AppBar from '@material-ui/core/AppBar';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import SpeedHighIcon from '@material-ui/icons/FastForward';
import SpeedLowIcon from '@material-ui/icons/PlayArrow';
import VolumeHighIcon from '@material-ui/icons/VolumeUp';
import VolumeLowIcon from '@material-ui/icons/VolumeDown';
import PlayIcon from '@material-ui/icons/PlayCircleFilled';
import PauseIcon from '@material-ui/icons/PauseCircleFilled';
import Slider from '@material-ui/core/Slider';
import MoreVertIcon from '@material-ui/icons/MoreVert';
import './PlayerView.css';
export default class PlayerView extends Component {
state = {
items: [],
selectedItem: null,
playing: false,
volume: 0.5,
speed: 1.0,
currentTime: 0,
duration: 0
};
componentDidMount() {
this._pres = new PlayerPresenter(this);
}
componentWillUnmount() {
this._pres.finalize();
}
set items(value) {
this.setState({
items: value
});
}
set selectedItem(value) {
this.setState({
selectedItem: value
});
}
set playing(value) {
this.setState({
playing: value
});
}
set volume(value) {
this.setState({
volume: value
});
}
set speed(value) {
this.setState({
speed: value
});
}
get currentTime() {
return this.state.currentTime;
}
set currentTime(value) {
this.setState({ currentTime: value });
}
set duration(value) {
this.setState({ duration: value });
}
_handleListItemClick(item) {
this._pres.selectedItemChanged(item);
}
_handleVolumeChange(event, value) {
this.setState({ volume: value });
this._pres.volumeChanged(value);
}
_handleSpeedChange(event, value) {
this.setState({ speed: value });
this._pres.speedChanged(value);
}
_handleCurrentTimeChange(event, value) {
this.setState({ currentTime: value });
this._pres.currentTimeChanged(value);
}
_handleEnclosureRefresh(item, event) {
this._pres.refreshEnclosure(item);
}
_handleEnclosureDelete(item, event) {
this._pres.deleteEnclosure(item);
}
_formatTime(value) {
let sec = `${Math.round(value % 60)}`;
let min = `${Math.floor(value / 60)}`;
if (sec.length === 1) {
sec = '0' + sec;
}
if (min.length === 1) {
min = '0' + min;
}
return `${min}:${sec}`;
}
render() {
const menu = <div>
<IconButton><MenuIcon color={'#FFF'}/></IconButton>
<Menu
anchorOrigin={{horizontal: 'left', vertical: 'top'}}
targetOrigin={{horizontal: 'left', vertical: 'top'}}
>
<MenuItem primaryText="channels" onClick={() => {this._pres.goToChannelListPage();}}/>
<MenuItem primaryText="info" onClick={() => {this._pres.goToInfoPage();}}/>
</Menu>
</div>;
let itemMenu = (item) => {
return (<div>
<IconButton><MoreVertIcon /></IconButton>
<Menu
anchorOrigin={{horizontal: 'right', vertical: 'top'}}
targetOrigin={{horizontal: 'right', vertical: 'top'}}
>
<MenuItem primaryText="refresh" onClick={this._handleEnclosureRefresh.bind(this, item)}/>
<MenuItem primaryText="delete" onClick={this._handleEnclosureDelete.bind(this, item)} />
</Menu>
</div>);
}
const playButton = (
<IconButton
disabled={!this.state.selectedItem || this.state.playing}
onClick={() => {this._pres.start()}}
>
<PlayIcon/>
</IconButton>
);
const pauseButton = (
<IconButton
disabled={!this.state.selectedItem || !this.state.playing}
onClick={() => {this._pres.stop()}}
>
<PauseIcon/>
</IconButton>
);
let pausePlayButton = this.state.playing ? pauseButton : playButton;
return (
<div>
<AppBar title="player" iconElementLeft={menu}/>
<Toolbar>
{pausePlayButton}
{this.state.selectedItem ? this.state.selectedItem.title : ''}
</Toolbar>
<div className="sliderGroup">
<table>
<tbody>
<tr>
<td>{this._formatTime(this.state.currentTime)}</td>
<td className="sliderColumn"><Slider min={0} max={this.state.duration} step={1} value={this.state.currentTime} onChange={this._handleCurrentTimeChange.bind(this)}/></td>
<td>{this._formatTime(this.state.duration)}</td>
</tr>
<tr>
<td><VolumeLowIcon/></td>
<td className="sliderColumn"><Slider min={0} max={1} step={0.01} value={this.state.volume} onChange={this._handleVolumeChange.bind(this)}/></td>
<td><VolumeHighIcon/></td>
</tr>
<tr>
<td><SpeedLowIcon/></td>
<td className="sliderColumn"><Slider min={0.5} max={2} step={0.05} value={this.state.speed} onChange={this._handleSpeedChange.bind(this)}/></td>
<td><SpeedHighIcon/></td>
</tr>
</tbody>
</table>
</div>
<List>
{this.state.items.map(item => {
return <ListItem
key={item.id}
primaryText={item.title}
onClick={this._handleListItemClick.bind(this, item)}
rightIconButton={itemMenu(item)}
/>;
})}
</List>
</div>
);
}
}
|
packages/ringcentral-widgets/components/CircleButton/index.js
|
u9520107/ringcentral-js-widget
|
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import styles from './styles.scss';
/**
* Circle Button with SVG
*/
function CircleButton(props) {
let icon;
if (props.icon) {
const Icon = props.icon;
icon = (
<Icon
className={classnames(styles.icon, props.iconClassName)}
width={props.iconWidth}
height={props.iconHeight}
x={props.iconX}
y={props.iconY}
/>
);
}
const circleClass = classnames(
styles.circle,
props.showBorder ? null : styles.noBorder
);
const onClick = props.disabled ? null : props.onClick;
return (
<svg
xmlns="http://www.w3.org/2000/svg"
className={classnames(styles.btnSvg, props.className)}
viewBox="0 0 500 500"
onClick={onClick}
width={props.width}
height={props.height}
x={props.x}
y={props.y}
>
{props.title ? <title>{props.title}</title> : null}
<g
className={styles.btnSvgGroup}
>
<circle
className={circleClass}
cx="250"
cy="250"
r="245"
/>
{icon}
</g>
</svg>
);
}
CircleButton.propTypes = {
icon: PropTypes.func,
className: PropTypes.string,
showBorder: PropTypes.bool,
iconClassName: PropTypes.string,
onClick: PropTypes.func,
width: PropTypes.string,
height: PropTypes.string,
x: PropTypes.number,
y: PropTypes.number,
disabled: PropTypes.bool,
iconWidth: PropTypes.number,
iconHeight: PropTypes.number,
iconX: PropTypes.number,
iconY: PropTypes.number,
title: PropTypes.string,
};
CircleButton.defaultProps = {
icon: undefined,
className: undefined,
showBorder: true,
iconClassName: undefined,
disabled: false,
onClick: null,
width: '100%',
height: '100%',
x: 0,
y: 0,
iconWidth: 200,
iconHeight: 200,
iconX: 150,
iconY: 150,
title: null,
};
export default CircleButton;
|
src/svg-icons/image/add-a-photo.js
|
kittyjumbalaya/material-components-web
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageAddAPhoto = (props) => (
<SvgIcon {...props}>
<path d="M3 4V1h2v3h3v2H5v3H3V6H0V4h3zm3 6V7h3V4h7l1.83 2H21c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H5c-1.1 0-2-.9-2-2V10h3zm7 9c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-3.2-5c0 1.77 1.43 3.2 3.2 3.2s3.2-1.43 3.2-3.2-1.43-3.2-3.2-3.2-3.2 1.43-3.2 3.2z"/>
</SvgIcon>
);
ImageAddAPhoto = pure(ImageAddAPhoto);
ImageAddAPhoto.displayName = 'ImageAddAPhoto';
ImageAddAPhoto.muiName = 'SvgIcon';
export default ImageAddAPhoto;
|
test/helpers/shallowRenderHelper.js
|
Solshal/solshal-chrome-extension
|
/**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
test/browser/time-picker/time-picker-spec.js
|
rolandpoulter/material-ui
|
import React from 'react';
import TextField from 'text-field';
import TimePicker from 'time-picker/time-picker';
import DateTime from 'utils/date-time';
import TestUtils from 'react-addons-test-utils';
describe('TimePicker', () => {
it('has to give value prop precedence over defaultTime', () => {
const initialTime = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
const valueTime = DateTime.addHours(initialTime, 2);
const render = TestUtils.renderIntoDocument(
<TimePicker value={valueTime} format="ampm" locale="en-US"
initialTime={initialTime}
/>
);
const timeTextField = TestUtils.findRenderedComponentWithType(render, TextField);
expect(timeTextField.props.value, DateTime.formatTime(valueTime));
});
it('takes defaulTime prop to set first value when value prop is missing', () => {
const initialTime = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
const render = TestUtils.renderIntoDocument(
<TimePicker format="ampm" locale="en-US"
defaultTime={initialTime}
/>
);
const timeTextField = TestUtils.findRenderedComponentWithType(render, TextField);
expect(timeTextField.props.value, DateTime.formatTime(initialTime));
});
it('shows value prop if defaultTime is missing', () => {
const initialTime = null;
const valueTime = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GM
const render = TestUtils.renderIntoDocument(
<TimePicker value={valueTime} format="ampm" locale="en-US"
defaultTime={initialTime}
/>
);
const timeTextField = TestUtils.findRenderedComponentWithType(render, TextField);
expect(timeTextField.props.value, DateTime.formatTime(valueTime));
});
});
|
es/Switch/Switch.js
|
uplevel-technology/material-ui-next
|
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
// weak
import React from 'react';
import classNames from 'classnames';
import withStyles from '../styles/withStyles';
import SwitchBase from '../internal/SwitchBase';
export const styles = theme => ({
root: {
display: 'inline-flex',
width: 62,
position: 'relative',
flexShrink: 0
},
bar: {
borderRadius: 7,
display: 'block',
position: 'absolute',
width: 34,
height: 14,
top: '50%',
marginTop: -7,
left: '50%',
marginLeft: -17,
transition: theme.transitions.create(['opacity', 'background-color'], {
duration: theme.transitions.duration.shortest
}),
backgroundColor: theme.palette.type === 'light' ? '#000' : '#fff',
opacity: theme.palette.type === 'light' ? 0.38 : 0.3
},
icon: {
boxShadow: theme.shadows[1],
backgroundColor: 'currentColor',
width: 20,
height: 20,
borderRadius: '50%'
},
// For SwitchBase
default: {
zIndex: 1,
color: theme.palette.type === 'light' ? theme.palette.grey[50] : theme.palette.grey[400],
transition: theme.transitions.create('transform', {
duration: theme.transitions.duration.shortest
})
},
checked: {
color: theme.palette.primary[500],
transform: 'translateX(14px)',
'& + $bar': {
backgroundColor: theme.palette.primary[500],
opacity: 0.5
}
},
disabled: {
color: theme.palette.type === 'light' ? theme.palette.grey[400] : theme.palette.grey[800],
'& + $bar': {
backgroundColor: theme.palette.type === 'light' ? '#000' : '#fff',
opacity: theme.palette.type === 'light' ? 0.12 : 0.1
}
}
});
function Switch(props) {
const { classes, className } = props,
other = _objectWithoutProperties(props, ['classes', 'className']);
const icon = React.createElement('span', { className: classes.icon });
return React.createElement(
'span',
{ className: classNames(classes.root, className) },
React.createElement(SwitchBase, _extends({
icon: icon,
classes: {
default: classes.default,
checked: classes.checked,
disabled: classes.disabled
},
checkedIcon: icon
}, other)),
React.createElement('span', { className: classes.bar })
);
}
export default withStyles(styles, { name: 'MuiSwitch' })(Switch);
|
app/javascript/mastodon/features/list_editor/components/account.js
|
MitarashiDango/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { makeGetAccount } from '../../../selectors';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Avatar from '../../../components/avatar';
import DisplayName from '../../../components/display_name';
import IconButton from '../../../components/icon_button';
import { defineMessages, injectIntl } from 'react-intl';
import { removeFromListEditor, addToListEditor } from '../../../actions/lists';
const messages = defineMessages({
remove: { id: 'lists.account.remove', defaultMessage: 'Remove from list' },
add: { id: 'lists.account.add', defaultMessage: 'Add to list' },
});
const makeMapStateToProps = () => {
const getAccount = makeGetAccount();
const mapStateToProps = (state, { accountId, added }) => ({
account: getAccount(state, accountId),
added: typeof added === 'undefined' ? state.getIn(['listEditor', 'accounts', 'items']).includes(accountId) : added,
});
return mapStateToProps;
};
const mapDispatchToProps = (dispatch, { accountId }) => ({
onRemove: () => dispatch(removeFromListEditor(accountId)),
onAdd: () => dispatch(addToListEditor(accountId)),
});
export default @connect(makeMapStateToProps, mapDispatchToProps)
@injectIntl
class Account extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
intl: PropTypes.object.isRequired,
onRemove: PropTypes.func.isRequired,
onAdd: PropTypes.func.isRequired,
added: PropTypes.bool,
};
static defaultProps = {
added: false,
};
render () {
const { account, intl, onRemove, onAdd, added } = this.props;
let button;
if (added) {
button = <IconButton icon='times' title={intl.formatMessage(messages.remove)} onClick={onRemove} />;
} else {
button = <IconButton icon='plus' title={intl.formatMessage(messages.add)} onClick={onAdd} />;
}
return (
<div className='account'>
<div className='account__wrapper'>
<div className='account__display-name'>
<div className='account__avatar-wrapper'><Avatar account={account} size={36} /></div>
<DisplayName account={account} />
</div>
<div className='account__relationship'>
{button}
</div>
</div>
</div>
);
}
}
|
actor-sdk/sdk-web/src/components/sidebar/HeaderSection.react.js
|
y0ke/actor-platform
|
/*
* Copyright (C) 2015-2016 Actor LLC. <https://actor.im>
*/
import React, { Component } from 'react';
import { Container } from 'flux/utils';
import classnames from 'classnames';
import ActorClient from '../../utils/ActorClient';
import { escapeWithEmoji } from '../../utils/EmojiUtils'
import confirm from '../../utils/confirm'
import SharedContainer from '../../utils/SharedContainer';
import { FormattedMessage } from 'react-intl';
import ProfileActionCreators from '../../actions/ProfileActionCreators';
import CreateGroupActionCreators from '../../actions/CreateGroupActionCreators';
import LoginActionCreators from '../../actions/LoginActionCreators';
import HelpActionCreators from '../../actions/HelpActionCreators';
import AddContactActionCreators from '../../actions/AddContactActionCreators';
import PreferencesActionCreators from '../../actions/PreferencesActionCreators';
import ProfileStore from '../../stores/ProfileStore';
import SvgIcon from '../common/SvgIcon.react';
import AvatarItem from '../common/AvatarItem.react';
class HeaderSection extends Component {
constructor(props) {
super(props);
this.state = {
isOpened: false
}
this.openHelp = this.openHelp.bind(this);
this.openTwitter = this.openTwitter.bind(this);
this.openFacebook = this.openFacebook.bind(this);
this.openHomePage = this.openHomePage.bind(this);
this.setLogout = this.setLogout.bind(this);
this.toggleHeaderMenu = this.toggleHeaderMenu.bind(this);
this.closeHeaderMenu = this.closeHeaderMenu.bind(this);
this.openMyProfile = this.openMyProfile.bind(this);
this.openCreateGroup = this.openCreateGroup.bind(this);
this.openAddContactModal = this.openAddContactModal.bind(this);
this.onSettingsOpen = this.onSettingsOpen.bind(this);
}
static getStores() {
return [ProfileStore];
}
static calculateState() {
return {
profile: ProfileStore.getProfile()
}
}
toggleHeaderMenu() {
const { isOpened } = this.state;
if (!isOpened) {
this.setState({ isOpened: true });
document.addEventListener('click', this.closeHeaderMenu, false);
} else {
this.closeHeaderMenu();
}
}
closeHeaderMenu() {
this.setState({ isOpened: false });
document.removeEventListener('click', this.closeHeaderMenu, false);
}
openMyProfile() {
ProfileActionCreators.show();
}
openCreateGroup() {
CreateGroupActionCreators.open();
}
openAddContactModal() {
AddContactActionCreators.open();
}
onSettingsOpen() {
PreferencesActionCreators.show();
}
openHelp() {
HelpActionCreators.open()
}
openTwitter(event) {
const { twitter } = SharedContainer.get();
event.preventDefault();
if (ActorClient.isElectron()) {
ActorClient.handleLinkClick(event);
} else {
window.open(`https://twitter.com/${twitter}`, '_blank');
}
}
openFacebook(event) {
const { facebook } = SharedContainer.get();
event.preventDefault();
if (ActorClient.isElectron()) {
ActorClient.handleLinkClick(event);
} else {
window.open(`https://facebook.com/${facebook}`, '_blank');
}
}
openHomePage(event) {
const { homePage } = SharedContainer.get();
event.preventDefault();
if (ActorClient.isElectron()) {
ActorClient.handleLinkClick(event);
} else {
window.open(homePage, '_blank');
}
}
setLogout() {
confirm(<FormattedMessage id="modal.confirm.logout"/>).then(
() => LoginActionCreators.setLoggedOut(),
() => {}
);
}
renderTwitterLink() {
const { twitter } = SharedContainer.get();
if (!twitter) return null;
return (
<li className="dropdown__menu__item">
<a href={`https://twitter.com/${twitter}`} onClick={this.openTwitter}>
<SvgIcon className="icon icon--dropdown sidebar__header__twitter" glyph="twitter" />
<FormattedMessage id="menu.twitter"/>
</a>
</li>
);
}
renderFacebookLink() {
const { facebook } = SharedContainer.get();
if (!facebook) return null;
return (
<li className="dropdown__menu__item">
<a href={`https://facebook.com/${facebook}`} onClick={this.openFacebook}>
<SvgIcon className="icon icon--dropdown sidebar__header__facebook" glyph="facebook" />
<FormattedMessage id="menu.facebook"/>
</a>
</li>
);
}
renderHomeLink() {
const { homePage } = SharedContainer.get();
if (!homePage) return null;
return (
<li className="dropdown__menu__item">
<a href={homePage} onClick={this.openHomePage}>
<i className="material-icons">public</i>
<FormattedMessage id="menu.homePage"/>
</a>
</li>
);
}
renderHelpLink() {
const { helpPhone } = SharedContainer.get();
if (!helpPhone) return null;
if (/@/.test(helpPhone)) {
return (
<li className="dropdown__menu__item">
<a href={`mailto:${helpPhone}`}>
<i className="material-icons">help</i>
<FormattedMessage id="menu.helpAndFeedback"/>
</a>
</li>
);
} else {
return (
<li className="dropdown__menu__item" onClick={this.openHelp}>
<i className="material-icons">help</i>
<FormattedMessage id="menu.helpAndFeedback"/>
</li>
);
}
}
render() {
const { profile, isOpened } = this.state;
if (!profile) return null;
const headerClass = classnames('sidebar__header', 'sidebar__header--clickable', {
'sidebar__header--opened': isOpened
});
const menuClass = classnames('dropdown', {
'dropdown--opened': isOpened
});
return (
<header className={headerClass}>
<div className="sidebar__header__user row" onClick={this.toggleHeaderMenu}>
<AvatarItem
className="sidebar__avatar"
image={profile.avatar}
placeholder={profile.placeholder}
size="tiny"
title={profile.name}
/>
<span className="sidebar__header__user__name col-xs"
dangerouslySetInnerHTML={{ __html: escapeWithEmoji(profile.name) }}/>
<div className={menuClass}>
<span className="dropdown__button">
<i className="material-icons">arrow_drop_down</i>
</span>
<ul className="dropdown__menu dropdown__menu--right">
<li className="dropdown__menu__item" onClick={this.openMyProfile}>
<i className="material-icons">edit</i>
<FormattedMessage id="menu.editProfile"/>
</li>
<li className="dropdown__menu__item" onClick={this.openAddContactModal}>
<i className="material-icons">person_add</i>
<FormattedMessage id="menu.addToContacts"/>
</li>
<li className="dropdown__menu__item" onClick={this.openCreateGroup}>
<i className="material-icons">group_add</i>
<FormattedMessage id="menu.createGroup"/>
</li>
<li className="dropdown__menu__separator"/>
<li className="dropdown__menu__item" onClick={this.onSettingsOpen}>
<i className="material-icons">settings</i>
<FormattedMessage id="menu.preferences"/>
</li>
{this.renderHelpLink()}
{this.renderTwitterLink()}
{this.renderFacebookLink()}
{this.renderHomeLink()}
<li className="dropdown__menu__separator"/>
<li className="dropdown__menu__item" onClick={this.setLogout}>
<FormattedMessage id="menu.signOut"/>
</li>
</ul>
</div>
</div>
</header>
);
}
}
export default Container.create(HeaderSection);
|
test/PanelSpec.js
|
yickli/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Panel from '../src/Panel';
import Table from '../src/Table';
describe('Panel', function () {
it('Should have class and body', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Panel>Panel content</Panel>
);
assert.ok(React.findDOMNode(instance).className.match(/\bpanel\b/));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'panel-body'));
});
it('Should have bootstrap style class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Panel bsStyle="default">Panel content</Panel>
);
assert.ok(React.findDOMNode(instance).className.match(/\bpanel-default\b/));
});
it('Should honour additional classes passed in, adding not overriding', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Panel className="bob"/>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbob\b/));
assert.ok(React.findDOMNode(instance).className.match(/\bpanel\b/));
});
it('Should have unwrapped header', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Panel header="Heading">Panel content</Panel>
);
let header = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'panel-heading'));
assert.equal(header.innerHTML, 'Heading');
});
it('Should have custom component header', function () {
let header = <h3>Heading</h3>;
let instance = ReactTestUtils.renderIntoDocument(
<Panel header={header}>Panel content</Panel>
);
header = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'panel-heading'));
assert.equal(header.firstChild.nodeName, 'H3');
assert.ok(header.firstChild.className.match(/\bpanel-title\b/));
assert.equal(header.firstChild.innerHTML, 'Heading');
});
it('Should have custom component header with anchor', function () {
let header = <h3>Heading</h3>;
let instance = ReactTestUtils.renderIntoDocument(
<Panel header={header} collapsible={true}>Panel content</Panel>
);
header = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'panel-heading'));
assert.equal(header.firstChild.nodeName, 'H3');
assert.ok(header.firstChild.className.match(/\bpanel-title\b/));
assert.equal(header.firstChild.firstChild.nodeName, 'A');
assert.equal(header.firstChild.firstChild.innerHTML, 'Heading');
});
it('Should have custom component header with custom class', function () {
let header = <h3 className="custom-class">Heading</h3>;
let instance = ReactTestUtils.renderIntoDocument(
<Panel header={header}>Panel content</Panel>
);
header = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'panel-heading'));
assert.equal(header.firstChild.nodeName, 'H3');
assert.ok(header.firstChild.className.match(/\bpanel-title\b/));
assert.ok(header.firstChild.className.match(/\bcustom-class\b/));
assert.equal(header.firstChild.innerHTML, 'Heading');
});
it('Should have footer', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Panel footer="Footer">Panel content</Panel>
);
let footer = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'panel-footer'));
assert.equal(footer.innerText, 'Footer');
});
it('Should have collapse classes', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Panel collapsible={true} expanded={true}>Panel content</Panel>
);
assert.ok(React.findDOMNode(instance).querySelector('.panel-collapse.collapse.in'));
});
it('Should pass through dom properties', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Panel collapsible={false} id="testid">Panel content</Panel>
);
assert.equal(React.findDOMNode(instance).id, 'testid');
});
it('Should pass id to panel-collapse', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Panel collapsible={true} id="testid" header="Heading">Panel content</Panel>
);
assert.notOk(React.findDOMNode(instance).id);
let collapse = React.findDOMNode(instance).querySelector('.panel-collapse');
let anchor = React.findDOMNode(instance).querySelector('.panel-title a');
assert.equal(collapse.id, 'testid');
assert.equal(anchor.getAttribute('href'), '#testid');
});
it('Should be open', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Panel collapsible={true} expanded={true} header="Heading">Panel content</Panel>
);
let collapse = React.findDOMNode(instance).querySelector('.panel-collapse');
let anchor = React.findDOMNode(instance).querySelector('.panel-title a');
assert.ok(collapse.className.match(/\bin\b/));
assert.notOk(anchor.className.match(/\bcollapsed\b/));
});
it('Should be closed', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Panel collapsible={true} expanded={false} header="Heading">Panel content</Panel>
);
let collapse = React.findDOMNode(instance).querySelector('.panel-collapse');
let anchor = React.findDOMNode(instance).querySelector('.panel-title a');
assert.notOk(collapse.className.match(/\bin\b/));
assert.ok(anchor.className.match(/\bcollapsed\b/));
});
it('Should call onSelect handler', function (done) {
function handleSelect (e, key) {
assert.equal(key, '1');
done();
}
let instance = ReactTestUtils.renderIntoDocument(
<Panel collapsible={true} onSelect={handleSelect} header="Click me" eventKey='1'>Panel content</Panel>
);
let title = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'panel-title');
ReactTestUtils.Simulate.click(React.findDOMNode(title).firstChild);
});
it('Should toggle when uncontrolled', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Panel collapsible={true} defaultExpanded={false} header="Click me">Panel content</Panel>
);
assert.notOk(instance.state.expanded);
ReactTestUtils.Simulate.click(
React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'panel-title')).firstChild
);
assert.ok(instance.state.expanded);
});
it('Should not wrap panel-filling tables in a panel body', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Panel>
Panel content
<Table fill />
More panel content
</Panel>
);
let children = React.findDOMNode(instance).children;
assert.equal(children.length, 3);
assert.equal(children[0].nodeName, 'DIV');
assert.ok(children[0].className.match(/\bpanel-body\b/));
assert.equal(children[1].nodeName, 'TABLE');
assert.notOk(children[1].className.match(/\bpanel-body\b/));
assert.equal(children[2].nodeName, 'DIV');
assert.ok(children[2].className.match(/\bpanel-body\b/));
});
it('Should not wrap single panel-fill table in a panel body', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Panel>
<Table fill />
</Panel>
);
let children = React.findDOMNode(instance).children;
assert.equal(children.length, 1);
assert.equal(children[0].nodeName, 'TABLE');
assert.notOk(children[0].className.match(/\bpanel-body\b/));
});
describe('Web Accessibility', function(){
it('Should be aria-expanded=true', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Panel collapsible={true} expanded={true} header="Heading">Panel content</Panel>
);
let collapse = React.findDOMNode(instance).querySelector('.panel-collapse');
let anchor = React.findDOMNode(instance).querySelector('.panel-title a');
assert.equal(collapse.getAttribute('aria-expanded'), 'true');
assert.equal(anchor.getAttribute('aria-expanded'), 'true');
});
it('Should be aria-expanded=false', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Panel collapsible={true} expanded={false} header="Heading">Panel content</Panel>
);
let collapse = React.findDOMNode(instance).querySelector('.panel-collapse');
let anchor = React.findDOMNode(instance).querySelector('.panel-title a');
assert.equal(collapse.getAttribute('aria-expanded'), 'false');
assert.equal(anchor.getAttribute('aria-expanded'), 'false');
});
it('Should add aria-controls with id', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Panel id='panel-1' collapsible expanded header="Heading">Panel content</Panel>
);
let collapse = React.findDOMNode(instance).querySelector('.panel-collapse');
let anchor = React.findDOMNode(instance).querySelector('.panel-title a');
assert.equal(collapse.getAttribute('id'), 'panel-1');
assert.equal(anchor.getAttribute('aria-controls'), 'panel-1');
});
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.