path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/nodes/Node.js | ebenpack/patches.js | import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {removeNode, nodeDragStart, connectStart, connectAttempt, widgetUpdate} from './actions';
const Node = ({node, removeNode, nodeDragStart, connectStart, connectAttempt, widgetUpdate}) => {
const title = node.get('title');
const body = node.get('body');
const left = node.get('left');
const top = node.get('top');
const inputs = node.get('inputs');
const outputs = node.get('outputs');
const width = node.get('width');
const height = node.get('height');
const id = node.get('id');
const transform = `translate(${left}, ${top})`;
const bodyText = body(inputs, outputs);
const Widgets = node.get('widgets');
const state = node.get('state');
return (
<g transform={transform} className="node draggable">
<rect
className="body"
x="0"
y="0"
width={width}
height={height}></rect>
<rect
className="handle title"
x="0"
y="0"
width={width}
height={height * 0.2}
onMouseDown={(e) => nodeDragStart(id, e.pageX, e.pageY)}></rect>
{/* mouseDown might cause an ordering change, so `onClick` would be unreliable here */}
<text
x={width - 2}
y="2"
className="close"
alignmentBaseline="hanging"
textAnchor="end"
onMouseUp={() => removeNode(id)}>
✕
</text>
<text
className="title"
x="4"
y="4"
alignmentBaseline="hanging">{title}</text>
<text
className="body"
alignmentBaseline="hanging"
y={(height * 0.2) + 4}
x="4">
{bodyText}
</text>
{Widgets ? <g>{Widgets.map((W, index) => <W inputs={inputs} outputs={outputs} state={state} update={widgetUpdate.bind(null, id)} key={index} />)}</g> : null}
{inputs.valueSeq().map((input, index) =>
<g className="input" key={input.get('id')}>
<circle
cx={ input.get('offsetLeft')}
cy={input.get('offsetTop')}
r="4"
key={input.get('title')}
onMouseUp={(e) =>
connectAttempt(id, input.get('id'), e.pageX, e.pageY)}>
</circle>
<text
x={input.get('offsetLeft') + 5}
y={input.get('offsetTop') + 5}
>{input.get('title')}</text>
</g>
)}
{outputs.valueSeq().map((output, index) =>
<g className="output" key={output.get('id')}>
<circle
cx={ output.get('offsetLeft')}
cy={ output.get('offsetTop')}
r="4"
key={output.get('title')}
onMouseDown={(e) =>
connectStart(id, output.get('id'), e.pageX, e.pageY)}>
</circle>
<text
x={output.get('offsetLeft') - 5}
y={output.get('offsetTop') + 5}
textAnchor="end"
>{output.get('title')}</text>
</g>
)}
</g>
);
};
Node.propTypes = {
//PropTypes
};
const mapDispatchToProps = {
removeNode,
nodeDragStart,
connectStart,
connectAttempt,
widgetUpdate
};
export default connect(
null,
mapDispatchToProps
)(Node); |
src/common/components/Button.js | reedlaw/read-it | // @flow
import type { ColorProps, Theme } from '../themes/types';
import type { TextProps } from './Text';
import Box from './Box';
import React from 'react';
import Text, { computeTextStyle } from './Text';
import isReactNative from '../../common/app/isReactNative';
export type ButtonProps = ColorProps & TextProps & {
// For blindness accessibility features. Consider making it mandatory.
accessibilityLabel?: string,
boxStyle?: (theme: Theme) => Object,
children?: any,
disabled?: boolean,
onPress?: (e?: SyntheticMouseEvent) => any,
outline?: boolean,
textStyle?: (theme: Theme) => Object,
};
type ButtonContext = {
Button: () => React.Element<*>,
theme: Theme,
};
const Button = (
{
as,
accessibilityLabel,
boxStyle,
children,
disabled,
onPress,
outline,
textStyle,
...props
}: ButtonProps,
{
Button: PlatformButton,
theme,
}: ButtonContext,
) => {
const platformProps = isReactNative
? {
accessibilityComponentType: 'button',
accessibilityLabel,
accessibilityTraits: ['button'],
activeOpacity: theme.states.active.opacity,
onPress,
}
: {
onClick: onPress,
};
const colorProps = Object.keys(theme.colors);
// <Button primary
// any is needed probably because Array find is not yet fully typed.
const propColor: any = colorProps.find(color => props[color]);
if (propColor) {
props = {
...props,
backgroundColor: propColor,
bold: true,
color: 'white',
paddingHorizontal: 1,
};
}
// <Button primary outline
if (propColor && outline) {
delete props.backgroundColor;
props = {
...props,
bold: false,
borderColor: props.backgroundColor,
borderStyle: 'solid',
borderWidth: 1,
color: props.backgroundColor,
paddingHorizontal: 1,
};
}
// Give button some vertical space.
const { size = 0 } = props;
if (size >= 0) {
props = {
marginVertical: 0.3,
paddingVertical: 0.2,
...props,
};
} else {
props = {
marginVertical: 0.5,
...props,
};
if (props.borderWidth) {
props = {
// Ensure vertical Rhythm for Button size < 0. The lineHeight is the
// only possible way how to do it. It doesn't work for multilines
lineHeight: theme.typography.lineHeight - 2 * props.borderWidth,
...props,
};
}
}
// Button consists of two components, Box and Text. That's because Button can
// render not only text, but any component, and React Native Text can't
// contain View based components.
// Therefore, we have to split props for Box and props for Text. Fortunately,
// that's what computeTextStyle does by design. It picks own props and return
// the rest. We can also use boxStyle and textStyle props for further styling.
const [computedTextStyle, allBoxProps] = computeTextStyle(theme, props);
// To prevent "Unknown prop" warning, we have to remove color props.
const boxProps = colorProps.reduce(
(props, prop) => {
delete props[prop];
return props;
},
allBoxProps,
);
const childrenIsText = typeof children === 'string';
const {
borderRadius = theme.button.borderRadius,
} = props;
return (
<Box
as={as || PlatformButton}
borderRadius={borderRadius}
disabled={disabled} // Do we need that?
flexDirection="row"
justifyContent="center"
opacity={disabled ? theme.states.disabled.opacity : 1}
{...platformProps}
{...boxProps}
style={boxStyle}
>
{childrenIsText
? <Text
// Pass backgroundColor to Text for maybeFixFontSmoothing function.
backgroundColor={props.backgroundColor}
style={theme => ({
...computedTextStyle,
...(textStyle && textStyle(theme, computedTextStyle)),
})}
>
{children}
</Text>
: children}
</Box>
);
};
Button.contextTypes = {
Button: React.PropTypes.func,
theme: React.PropTypes.object,
};
export default Button;
|
src/js/pages/index.js | waagsociety/ams.datahub.client | import React from 'react'
import { connect } from 'react-redux'
import axios from 'axios'
import * as action from '../store'
import {
GlobalNavigation,
SearchPanel,
ResultPanel,
ResultBrowser,
RelatedPanel,
Item,
} from '../containers'
@connect ((store) => ({ store }))
export default class Index extends React.Component {
componentWillMount() {
const { props } = this
const { dispatch } = props
dispatch(action.route.initialise())
onhashchange = event => dispatch(action.route.initialise())
}
componentDidUpdate() {
// Route
const { store, dispatch } = this.props
const { route, search, dataset } = store
const { query, hash } = route
if (Object.keys(query).length === 1 && query.scope) location.hash = ''
else if (query.handle) { // Open a dataset
const handle = query.handle.join('')
if (dataset.handle !== handle) {
dispatch(action.dataset.fetch(dispatch)(handle))
}
}
else if (search.hash !== hash) {
if (hash) dispatch(action.search.fetch(dispatch)(route)) // Search-query in place
else dispatch(action.search.clear()) // We’re home
}
}
render() {
const { props } = this
const { search, dataset, route, view } = props.store
const { query } = route
const hasResults = route.query.results !== undefined
switch(true) {
case !!query.handle: return <div id='article' className='page container cover'>
<Item props={props}/>
<RelatedPanel props={props}/>
</div>
case !!search.hash: return <div id='search' className='page container cover'>
<SearchPanel props={props}/>
<ResultPanel props={props}/>
</div>
default: return <div id='search' className='page container cover clear'>
<SearchPanel props={props}/>
</div>
}
}
}
|
react/Strong/Strong.demo.js | seek-oss/seek-style-guide | import React from 'react';
import Strong from './Strong';
import Text from '../Text/Text';
export default {
route: '/strong',
title: 'Strong',
category: 'Typography',
component: Text,
initialProps: {
headline: true,
regular: true,
children: ['This text is ', <Strong key="strong">strong</Strong>]
},
options: []
};
|
index.android.js | jlebensold/peckish | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class peckish extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('peckish', () => peckish);
|
jobs/screens/AuthScreen.js | haaswill/ReactNativeCourses | import React, { Component } from 'react';
import { View } from 'react-native';
import { connect } from 'react-redux';
import { facebookLogin } from '../actions';
class AuthScreen extends Component {
componentDidMount() {
this.props.facebookLogin();
// if we had logged before
//this.onAuthComplete(this.props);
}
componentWillReceiveProps(nextProps) {
this.onAuthComplete(nextProps);
}
onAuthComplete(props) {
if (props.token) {
this.props.navigation.navigate('map');
}
}
render() {
return (
<View />
);
}
}
function mapStateToProps({ auth }) {
return { token: auth.token };
}
export default connect(mapStateToProps, { facebookLogin })(AuthScreen);
|
js/controls/KendoDropDownList.js | wingspan/wingspan-forms | import React from 'react'
import SelectWidgetMixin from '../mixins/SelectWidgetMixin'
const PropTypes = React.PropTypes;
const KendoDropDownList = React.createClass({
mixins: [SelectWidgetMixin('kendoDropDownList')],
propTypes: {
id: PropTypes.string,
value: PropTypes.any,
onChange: PropTypes.func,
autoBind: PropTypes.bool,
dataSource: PropTypes.oneOfType([PropTypes.array, PropTypes.object]),
displayField: PropTypes.string,
valueField: PropTypes.string,
disabled: PropTypes.bool,
readonly: PropTypes.bool,
options: PropTypes.object,
filter: PropTypes.string,
optionLabel: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
template: PropTypes.oneOfType([PropTypes.string, PropTypes.func])
},
statics: {
fieldClass: function () { return 'formFieldCombobox'; }
},
/*jshint ignore:start */
render: function () {
return (this.props.noControl
? (<span id={this.props.id}>{this.renderValue()}</span>)
: (<input id={this.props.id}/>));
}
/*jshint ignore:end */
});
export default KendoDropDownList; |
app/javascript/mastodon/components/status_action_bar.js | salvadorpla/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import IconButton from './icon_button';
import DropdownMenuContainer from '../containers/dropdown_menu_container';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { me, isStaff } from '../initial_state';
const messages = defineMessages({
delete: { id: 'status.delete', defaultMessage: 'Delete' },
redraft: { id: 'status.redraft', defaultMessage: 'Delete & re-draft' },
direct: { id: 'status.direct', defaultMessage: 'Direct message @{name}' },
mention: { id: 'status.mention', defaultMessage: 'Mention @{name}' },
mute: { id: 'account.mute', defaultMessage: 'Mute @{name}' },
block: { id: 'account.block', defaultMessage: 'Block @{name}' },
reply: { id: 'status.reply', defaultMessage: 'Reply' },
share: { id: 'status.share', defaultMessage: 'Share' },
more: { id: 'status.more', defaultMessage: 'More' },
replyAll: { id: 'status.replyAll', defaultMessage: 'Reply to thread' },
reblog: { id: 'status.reblog', defaultMessage: 'Boost' },
reblog_private: { id: 'status.reblog_private', defaultMessage: 'Boost to original audience' },
cancel_reblog_private: { id: 'status.cancel_reblog_private', defaultMessage: 'Unboost' },
cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be boosted' },
favourite: { id: 'status.favourite', defaultMessage: 'Favourite' },
open: { id: 'status.open', defaultMessage: 'Expand this status' },
report: { id: 'status.report', defaultMessage: 'Report @{name}' },
muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' },
unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' },
pin: { id: 'status.pin', defaultMessage: 'Pin on profile' },
unpin: { id: 'status.unpin', defaultMessage: 'Unpin from profile' },
embed: { id: 'status.embed', defaultMessage: 'Embed' },
admin_account: { id: 'status.admin_account', defaultMessage: 'Open moderation interface for @{name}' },
admin_status: { id: 'status.admin_status', defaultMessage: 'Open this status in the moderation interface' },
copy: { id: 'status.copy', defaultMessage: 'Copy link to status' },
});
const obfuscatedCount = count => {
if (count < 0) {
return 0;
} else if (count <= 1) {
return count;
} else {
return '1+';
}
};
export default @injectIntl
class StatusActionBar extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
onReply: PropTypes.func,
onFavourite: PropTypes.func,
onReblog: PropTypes.func,
onDelete: PropTypes.func,
onDirect: PropTypes.func,
onMention: PropTypes.func,
onMute: PropTypes.func,
onBlock: PropTypes.func,
onReport: PropTypes.func,
onEmbed: PropTypes.func,
onMuteConversation: PropTypes.func,
onPin: PropTypes.func,
withDismiss: PropTypes.bool,
intl: PropTypes.object.isRequired,
};
// Avoid checking props that are functions (and whose equality will always
// evaluate to false. See react-immutable-pure-component for usage.
updateOnProps = [
'status',
'withDismiss',
]
handleReplyClick = () => {
if (me) {
this.props.onReply(this.props.status, this.context.router.history);
} else {
this._openInteractionDialog('reply');
}
}
handleShareClick = () => {
navigator.share({
text: this.props.status.get('search_index'),
url: this.props.status.get('url'),
}).catch((e) => {
if (e.name !== 'AbortError') console.error(e);
});
}
handleFavouriteClick = () => {
if (me) {
this.props.onFavourite(this.props.status);
} else {
this._openInteractionDialog('favourite');
}
}
handleReblogClick = e => {
if (me) {
this.props.onReblog(this.props.status, e);
} else {
this._openInteractionDialog('reblog');
}
}
_openInteractionDialog = type => {
window.open(`/interact/${this.props.status.get('id')}?type=${type}`, 'mastodon-intent', 'width=445,height=600,resizable=no,menubar=no,status=no,scrollbars=yes');
}
handleDeleteClick = () => {
this.props.onDelete(this.props.status, this.context.router.history);
}
handleRedraftClick = () => {
this.props.onDelete(this.props.status, this.context.router.history, true);
}
handlePinClick = () => {
this.props.onPin(this.props.status);
}
handleMentionClick = () => {
this.props.onMention(this.props.status.get('account'), this.context.router.history);
}
handleDirectClick = () => {
this.props.onDirect(this.props.status.get('account'), this.context.router.history);
}
handleMuteClick = () => {
this.props.onMute(this.props.status.get('account'));
}
handleBlockClick = () => {
this.props.onBlock(this.props.status);
}
handleOpen = () => {
this.context.router.history.push(`/statuses/${this.props.status.get('id')}`);
}
handleEmbed = () => {
this.props.onEmbed(this.props.status);
}
handleReport = () => {
this.props.onReport(this.props.status);
}
handleConversationMuteClick = () => {
this.props.onMuteConversation(this.props.status);
}
handleCopy = () => {
const url = this.props.status.get('url');
const textarea = document.createElement('textarea');
textarea.textContent = url;
textarea.style.position = 'fixed';
document.body.appendChild(textarea);
try {
textarea.select();
document.execCommand('copy');
} catch (e) {
} finally {
document.body.removeChild(textarea);
}
}
render () {
const { status, intl, withDismiss } = this.props;
const mutingConversation = status.get('muted');
const anonymousAccess = !me;
const publicStatus = ['public', 'unlisted'].includes(status.get('visibility'));
let menu = [];
let reblogIcon = 'retweet';
let replyIcon;
let replyTitle;
menu.push({ text: intl.formatMessage(messages.open), action: this.handleOpen });
if (publicStatus) {
menu.push({ text: intl.formatMessage(messages.copy), action: this.handleCopy });
menu.push({ text: intl.formatMessage(messages.embed), action: this.handleEmbed });
}
menu.push(null);
if (status.getIn(['account', 'id']) === me || withDismiss) {
menu.push({ text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMuteClick });
menu.push(null);
}
if (status.getIn(['account', 'id']) === me) {
if (publicStatus) {
menu.push({ text: intl.formatMessage(status.get('pinned') ? messages.unpin : messages.pin), action: this.handlePinClick });
} else {
if (status.get('visibility') === 'private') {
menu.push({ text: intl.formatMessage(status.get('reblogged') ? messages.cancel_reblog_private : messages.reblog_private), action: this.handleReblogClick });
}
}
menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDeleteClick });
menu.push({ text: intl.formatMessage(messages.redraft), action: this.handleRedraftClick });
} else {
menu.push({ text: intl.formatMessage(messages.mention, { name: status.getIn(['account', 'username']) }), action: this.handleMentionClick });
menu.push({ text: intl.formatMessage(messages.direct, { name: status.getIn(['account', 'username']) }), action: this.handleDirectClick });
menu.push(null);
menu.push({ text: intl.formatMessage(messages.mute, { name: status.getIn(['account', 'username']) }), action: this.handleMuteClick });
menu.push({ text: intl.formatMessage(messages.block, { name: status.getIn(['account', 'username']) }), action: this.handleBlockClick });
menu.push({ text: intl.formatMessage(messages.report, { name: status.getIn(['account', 'username']) }), action: this.handleReport });
if (isStaff) {
menu.push(null);
menu.push({ text: intl.formatMessage(messages.admin_account, { name: status.getIn(['account', 'username']) }), href: `/admin/accounts/${status.getIn(['account', 'id'])}` });
menu.push({ text: intl.formatMessage(messages.admin_status), href: `/admin/accounts/${status.getIn(['account', 'id'])}/statuses/${status.get('id')}` });
}
}
if (status.get('visibility') === 'direct') {
reblogIcon = 'envelope';
} else if (status.get('visibility') === 'private') {
reblogIcon = 'lock';
}
if (status.get('in_reply_to_id', null) === null) {
replyIcon = 'reply';
replyTitle = intl.formatMessage(messages.reply);
} else {
replyIcon = 'reply-all';
replyTitle = intl.formatMessage(messages.replyAll);
}
const shareButton = ('share' in navigator) && status.get('visibility') === 'public' && (
<IconButton className='status__action-bar-button' title={intl.formatMessage(messages.share)} icon='share-alt' onClick={this.handleShareClick} />
);
return (
<div className='status__action-bar'>
<div className='status__action-bar__counter'><IconButton className='status__action-bar-button' title={replyTitle} icon={status.get('in_reply_to_account_id') === status.getIn(['account', 'id']) ? 'reply' : replyIcon} onClick={this.handleReplyClick} /><span className='status__action-bar__counter__label' >{obfuscatedCount(status.get('replies_count'))}</span></div>
<IconButton className='status__action-bar-button' disabled={!publicStatus} active={status.get('reblogged')} pressed={status.get('reblogged')} title={!publicStatus ? intl.formatMessage(messages.cannot_reblog) : intl.formatMessage(messages.reblog)} icon={reblogIcon} onClick={this.handleReblogClick} />
<IconButton className='status__action-bar-button star-icon' animate active={status.get('favourited')} pressed={status.get('favourited')} title={intl.formatMessage(messages.favourite)} icon='star' onClick={this.handleFavouriteClick} />
{shareButton}
<div className='status__action-bar-dropdown'>
<DropdownMenuContainer disabled={anonymousAccess} status={status} items={menu} icon='ellipsis-h' size={18} direction='right' title={intl.formatMessage(messages.more)} />
</div>
</div>
);
}
}
|
app/javascript/mastodon/components/gifv.js | d6rkaiz/mastodon | import React from 'react';
import PropTypes from 'prop-types';
export default class GIFV extends React.PureComponent {
static propTypes = {
src: PropTypes.string.isRequired,
alt: PropTypes.string,
width: PropTypes.number,
height: PropTypes.number,
onClick: PropTypes.func,
};
state = {
loading: true,
};
handleLoadedData = () => {
this.setState({ loading: false });
}
componentWillReceiveProps (nextProps) {
if (nextProps.src !== this.props.src) {
this.setState({ loading: true });
}
}
handleClick = e => {
const { onClick } = this.props;
if (onClick) {
e.stopPropagation();
onClick();
}
}
render () {
const { src, width, height, alt } = this.props;
const { loading } = this.state;
return (
<div className='gifv' style={{ position: 'relative' }}>
{loading && (
<canvas
width={width}
height={height}
role='button'
tabIndex='0'
aria-label={alt}
title={alt}
onClick={this.handleClick}
/>
)}
<video
src={src}
width={width}
height={height}
role='button'
tabIndex='0'
aria-label={alt}
title={alt}
muted
loop
autoPlay
playsInline
onClick={this.handleClick}
onLoadedData={this.handleLoadedData}
style={{ position: loading ? 'absolute' : 'static', top: 0, left: 0 }}
/>
</div>
);
}
}
|
packages/shared/forks/object-assign.umd.js | rricard/react | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import React from 'react';
const ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
export default ReactInternals.assign;
|
test/helpers/shallowRenderHelper.js | partner0125/hualang | /**
* 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();
}
|
src/modules/designerServer 2/index.js | 2941972057/flower-react | /**
* Created by dllo on 17/8/23.
*/
import React from 'react'
import ReactDOM from 'react-dom'
import DesignerServer from './DesignerServer'
ReactDOM.render(
<DesignerServer />,
document.getElementById('app')
)
|
src/routes/Home/components/HomeView.js | codingarchitect/react-counter-pair | import React from 'react'
import { connect } from 'react-redux'
import DuckImage from '../assets/Duck.jpg'
import './HomeView.scss'
import HomeView from './home-view.rt'
const mapStateToProps = (state) => ({
DuckImage : DuckImage
})
export default connect(mapStateToProps)(HomeView) |
src/shared/theme/navBar.js | CharlesMangwa/Chloe | /* @flow */
import React from 'react'
import { NavigationExperimental } from 'react-native'
import { SFUIDISPLAY_REGULAR } from '@theme/fonts'
const {
Header: NavigationHeader,
} = NavigationExperimental
export const TRANSPARENT_NAV_BAR = {
backgroundColor: 'transparent',
borderBottomWidth: 0,
}
export const DEFAULT_NAV_BAR_STYLE = {
backgroundColor: 'orange',
borderBottomWidth: 0,
}
export const DEFAULT_NAV_BAR_TITLE_STYLE = {
top: .75,
...SFUIDISPLAY_REGULAR,
color: 'white',
fontSize: 15,
letterSpacing: .75,
}
export const renderTitle = (titleProps: { title: String, titleStyle: any }): React$Element<any> => {
const { title, titleStyle } = titleProps
return (
<NavigationHeader.Title textStyle={titleStyle}>
{title.toUpperCase()}
</NavigationHeader.Title>
)
}
|
docs/src/app/components/pages/components/Paper/ExampleSimple.js | skarnecki/material-ui | import React from 'react';
import Paper from 'material-ui/Paper';
const style = {
height: 100,
width: 100,
margin: 20,
textAlign: 'center',
display: 'inline-block',
};
const PaperExampleSimple = () => (
<div>
<Paper style={style} zDepth={1} />
<Paper style={style} zDepth={2} />
<Paper style={style} zDepth={3} />
<Paper style={style} zDepth={4} />
<Paper style={style} zDepth={5} />
</div>
);
export default PaperExampleSimple;
|
analysis/roguesubtlety/src/CONFIG.js | anom0ly/WoWAnalyzer | import { Tyndi } from 'CONTRIBUTORS';
import SPECS from 'game/SPECS';
import React from 'react';
import CHANGELOG from './CHANGELOG';
export default {
// The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion.
contributors: [Tyndi],
// The WoW client patch this spec was last updated.
patchCompatibility: '9.0.1',
isPartial: true,
// Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more.
// If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component.
description: (
<>
Hey Subtlety Rogues! <br /> <br />
The Subtlety Rogue module is still being worked on. Currently, it gives a good analysis of the
single target rotation, and highlights major mistakes.
<br /> <br />
All recommendations and analysis should be in line with{' '}
<a href="http://www.ravenholdt.net/subtlety-guide/"> wEak's guide </a> and Simcraft APL.
<br /> <br />
If there is something missing, incorrect, or inaccurate, please report it on{' '}
<a href="https://github.com/WoWAnalyzer/WoWAnalyzer/issues/new">GitHub</a> or contact{' '}
<kbd>@Tyndi</kbd> on <a href="https://discord.gg/AxphPxU">Discord</a>.<br />
<br />
</>
),
// A recent example report to see interesting parts of the spec. Will be shown on the homepage.
exampleReport: '/report/BKWZ4PvqFArtgXHd/1-Heroic+Grong+-+Kill+(5:05)/4-Phíl',
// Don't change anything below this line;
// The current spec identifier. This is the only place (in code) that specifies which spec this parser is about.
spec: SPECS.SUBTLETY_ROGUE,
// The contents of your changelog.
changelog: CHANGELOG,
// The CombatLogParser class for your spec.
parser: () =>
import('./CombatLogParser' /* webpackChunkName: "SubtletyRogue" */).then(
(exports) => exports.default,
),
// The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code.
path: __dirname,
};
|
src/containers/Asians/TabControls/_components/AppBar/LargeAppBar/BreakRoundsButtons/index.js | westoncolemanl/tabbr-web | import React from 'react'
import { connect } from 'react-redux'
import Instance from './Instance'
export default connect(mapStateToProps)(({
breakCategories
}) => {
return (
<div
className={'flex flex-row'}
>
{breakCategories.sort((a, b) => b.default).map(breakCategory =>
<Instance
key={breakCategory._id}
breakCategory={breakCategory}
/>
)}
</div>
)
})
function mapStateToProps (state, ownProps) {
return {
breakCategories: Object.values(state.breakCategories.data)
}
}
|
ui/src/components/role/RoleTable.js | yahoo/athenz | /*
* Copyright 2020 Verizon Media
*
* 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 styled from '@emotion/styled';
import RoleRow from './RoleRow';
import RoleGroup from './RoleGroup';
const StyleTable = styled.table`
width: 100%;
border-spacing: 0 15px;
display: table;
border-collapse: separate;
border-color: grey;
`;
const TableHeadStyled = styled.th`
text-align: ${(props) => props.align};
border-bottom: 2px solid #d5d5d5;
color: #9a9a9a;
font-weight: 600;
font-size: 0.8rem;
padding-bottom: 5px;
vertical-align: top;
text-transform: uppercase;
padding: 5px 0 5px 15px;
word-break: break-all;
`;
const TableHeadStyledRoleName = styled.th`
text-align: ${(props) => props.align};
border-bottom: 2px solid #d5d5d5;
color: #9a9a9a;
font-weight: 600;
font-size: 0.8rem;
padding-bottom: 5px;
vertical-align: top;
text-transform: uppercase;
padding: 5px 0 5px 35px;
word-break: break-all;
`;
export default class RoleTable extends React.Component {
constructor(props) {
super(props);
this.api = props.api;
let subRows = [];
if (props.prefixes) {
props.prefixes.map((prefix) => {
let rows = props.roles.filter((item) =>
item.name.startsWith(props.domain + prefix.prefix)
);
subRows[prefix.name] = rows;
});
}
this.state = {
roles: props.roles || [],
rows: subRows,
};
}
componentDidUpdate = (prevProps) => {
if (prevProps.domain !== this.props.domain) {
this.setState({
rows: {},
});
} else if (prevProps.roles !== this.props.roles) {
let subRows = [];
if (this.props.prefixes) {
this.props.prefixes.map((prefix) => {
let rows = this.props.roles.filter((item) =>
item.name.startsWith(this.props.domain + prefix.prefix)
);
subRows[prefix.name] = rows;
});
}
this.setState({
roles: this.props.roles || [],
rows: subRows,
});
}
};
render() {
const center = 'center';
const left = 'left';
const { domain } = this.props;
const adminRole = domain + ':role.admin';
let rows = [];
if (this.state.roles && this.state.roles.length > 0) {
let remainingRows = this.state.roles.filter((item) => {
if (item.name === adminRole) {
return false;
}
let included = false;
if (this.props.prefixes) {
this.props.prefixes.forEach((prefix) => {
if (
item.name.startsWith(
this.props.domain + prefix.prefix
)
) {
included = true;
}
});
}
return !included;
});
// put admin role at first place
let adminRow = this.state.roles
.filter((item) => {
return item.name == adminRole;
})
.map((item, i) => {
return (
<RoleRow
details={item}
idx={i}
domain={domain}
api={this.api}
key={item.name}
onUpdateSuccess={this.props.onSubmit}
_csrf={this.props._csrf}
justificationRequired={
this.props.justificationRequired
}
userProfileLink={this.props.userProfileLink}
/>
);
});
rows.push(adminRow);
if (this.state.rows) {
for (let name in this.state.rows) {
// group rows
let roleGroup = (
<RoleGroup
key={'group:' + name}
api={this.api}
domain={domain}
name={name}
roles={this.state.rows[name]}
onUpdateSuccess={this.props.onSubmit}
_csrf={this.props._csrf}
/>
);
rows.push(roleGroup);
}
}
let otherRows = remainingRows
.sort((a, b) => {
return a.name.localeCompare(b.name);
})
.map((item, i) => {
return (
<RoleRow
details={item}
idx={i}
domain={domain}
api={this.api}
key={item.name}
onUpdateSuccess={this.props.onSubmit}
_csrf={this.props._csrf}
justificationRequired={
this.props.justificationRequired
}
userProfileLink={this.props.userProfileLink}
/>
);
});
rows.push(otherRows);
}
return (
<StyleTable key='role-table' data-testid='roletable'>
<thead>
<tr>
<TableHeadStyledRoleName align={left}>
Role
</TableHeadStyledRoleName>
<TableHeadStyled align={left}>
Modified Date
</TableHeadStyled>
<TableHeadStyled align={left}>
Reviewed Date
</TableHeadStyled>
<TableHeadStyled align={center}>
Members
</TableHeadStyled>
<TableHeadStyled align={center}>Review</TableHeadStyled>
<TableHeadStyled align={center}>
Policy Rule
</TableHeadStyled>
<TableHeadStyled align={center}>
Settings
</TableHeadStyled>
<TableHeadStyled align={center}>Delete</TableHeadStyled>
</tr>
</thead>
<tbody>{rows}</tbody>
</StyleTable>
);
}
}
|
react/features/welcome/components/native/settings/components/SettingsView.js | gpolitis/jitsi-meet | // @flow
import React from 'react';
import {
Alert,
NativeModules,
Platform,
ScrollView,
Text
} from 'react-native';
import { Divider, Switch, TextInput, withTheme } from 'react-native-paper';
import { translate } from '../../../../../base/i18n';
import JitsiScreen from '../../../../../base/modal/components/JitsiScreen';
import { connect } from '../../../../../base/redux';
import { renderArrowBackButton }
from '../../../../../mobile/navigation/components/welcome/functions';
import { screen } from '../../../../../mobile/navigation/routes';
import {
AbstractSettingsView,
_mapStateToProps as _abstractMapStateToProps,
type Props as AbstractProps
} from '../../../../../settings/components/AbstractSettingsView';
import { normalizeUserInputURL, isServerURLChangeEnabled } from '../../../../../settings/functions';
import FormRow from './FormRow';
import FormSectionAccordion from './FormSectionAccordion';
import styles, {
DISABLED_TRACK_COLOR,
ENABLED_TRACK_COLOR,
THUMB_COLOR
} from './styles';
/**
* Application information module.
*/
const { AppInfo } = NativeModules;
type State = {
/**
* State variable for the disable call integration switch.
*/
disableCallIntegration: boolean,
/**
* State variable for the disable p2p switch.
*/
disableP2P: boolean,
/**
* State variable for the disable crash reporting switch.
*/
disableCrashReporting: boolean,
/**
* State variable for the display name field.
*/
displayName: string,
/**
* State variable for the email field.
*/
email: string,
/**
* State variable for the server URL field.
*/
serverURL: string,
/**
* State variable for the start with audio muted switch.
*/
startWithAudioMuted: boolean,
/**
* State variable for the start with video muted switch.
*/
startWithVideoMuted: boolean
}
/**
* The type of the React {@code Component} props of
* {@link SettingsView}.
*/
type Props = AbstractProps & {
/**
* Flag indicating if URL can be changed by user.
*
* @protected
*/
_serverURLChangeEnabled: boolean,
/**
* Default prop for navigating between screen components(React Navigation).
*/
navigation: Object,
/**
* Theme used for styles.
*/
theme: Object
}
/**
* The native container rendering the app settings page.
*
* @augments AbstractSettingsView
*/
class SettingsView extends AbstractSettingsView<Props, State> {
_urlField: Object;
/**
* Initializes a new {@code SettingsView} instance.
*
* @inheritdoc
*/
constructor(props) {
super(props);
const {
disableCallIntegration,
disableCrashReporting,
disableP2P,
displayName,
email,
serverURL,
startWithAudioMuted,
startWithVideoMuted
} = props._settings || {};
this.state = {
disableCallIntegration,
disableCrashReporting,
disableP2P,
displayName,
email,
serverURL,
startWithAudioMuted,
startWithVideoMuted
};
// Bind event handlers so they are only bound once per instance.
this._onBlurServerURL = this._onBlurServerURL.bind(this);
this._onClose = this._onClose.bind(this);
this._onDisableCallIntegration = this._onDisableCallIntegration.bind(this);
this._onDisableCrashReporting = this._onDisableCrashReporting.bind(this);
this._onDisableP2P = this._onDisableP2P.bind(this);
this._setURLFieldReference = this._setURLFieldReference.bind(this);
this._showURLAlert = this._showURLAlert.bind(this);
}
/**
* Implements React's {@link Component#componentDidMount()}. Invoked
* immediately after mounting occurs.
*
* @inheritdoc
* @returns {void}
*/
componentDidMount() {
const {
navigation
} = this.props;
navigation.setOptions({
headerLeft: () =>
renderArrowBackButton(() =>
navigation.jumpTo(screen.welcome.main))
});
}
/**
* Implements React's {@link Component#render()}, renders the settings page.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const {
disableCallIntegration,
disableCrashReporting,
disableP2P,
displayName,
email,
serverURL,
startWithAudioMuted,
startWithVideoMuted
} = this.state;
const { palette } = this.props.theme;
const textInputTheme = {
colors: {
background: palette.ui01,
placeholder: palette.text01,
primary: palette.screen01Header,
underlineColor: 'transparent',
text: palette.text01
}
};
return (
<JitsiScreen
style = { styles.settingsViewContainer }>
<ScrollView>
<FormSectionAccordion
accordion = { false }
expandable = { false }
label = 'settingsView.profileSection'>
<TextInput
autoCorrect = { false }
label = { this.props.t('settingsView.displayName') }
mode = 'outlined'
onChangeText = { this._onChangeDisplayName }
placeholder = 'John Doe'
spellCheck = { false }
style = { styles.textInputContainer }
textContentType = { 'name' } // iOS only
theme = { textInputTheme }
value = { displayName } />
<Divider style = { styles.fieldSeparator } />
<TextInput
autoCapitalize = 'none'
autoCorrect = { false }
keyboardType = { 'email-address' }
label = { this.props.t('settingsView.email') }
mode = 'outlined'
onChangeText = { this._onChangeEmail }
placeholder = 'email@example.com'
spellCheck = { false }
style = { styles.textInputContainer }
textContentType = { 'emailAddress' } // iOS only
theme = { textInputTheme }
value = { email } />
</FormSectionAccordion>
<FormSectionAccordion
accordion = { false }
expandable = { false }
label = 'settingsView.conferenceSection'>
<TextInput
autoCapitalize = 'none'
autoCorrect = { false }
editable = { this.props._serverURLChangeEnabled }
keyboardType = { 'url' }
label = { this.props.t('settingsView.serverURL') }
mode = 'outlined'
onBlur = { this._onBlurServerURL }
onChangeText = { this._onChangeServerURL }
placeholder = { this.props._serverURL }
spellCheck = { false }
style = { styles.textInputContainer }
textContentType = { 'URL' } // iOS only
theme = { textInputTheme }
value = { serverURL } />
<Divider style = { styles.fieldSeparator } />
<FormRow
label = 'settingsView.startWithAudioMuted'>
<Switch
onValueChange = { this._onStartAudioMutedChange }
thumbColor = { THUMB_COLOR }
trackColor = {{
true: ENABLED_TRACK_COLOR,
false: DISABLED_TRACK_COLOR
}}
value = { startWithAudioMuted } />
</FormRow>
<Divider style = { styles.fieldSeparator } />
<FormRow label = 'settingsView.startWithVideoMuted'>
<Switch
onValueChange = { this._onStartVideoMutedChange }
thumbColor = { THUMB_COLOR }
trackColor = {{
true: ENABLED_TRACK_COLOR,
false: DISABLED_TRACK_COLOR
}}
value = { startWithVideoMuted } />
</FormRow>
</FormSectionAccordion>
<FormSectionAccordion
accordion = { false }
expandable = { false }
label = 'settingsView.buildInfoSection'>
<FormRow
label = 'settingsView.version'>
<Text style = { styles.text }>
{`${AppInfo.version} build ${AppInfo.buildNumber}`}
</Text>
</FormRow>
</FormSectionAccordion>
<FormSectionAccordion
accordion = { true }
expandable = { true }
label = 'settingsView.advanced'>
{ Platform.OS === 'android' && (
<>
<FormRow
label = 'settingsView.disableCallIntegration'>
<Switch
onValueChange = { this._onDisableCallIntegration }
thumbColor = { THUMB_COLOR }
trackColor = {{
true: ENABLED_TRACK_COLOR,
false: DISABLED_TRACK_COLOR
}}
value = { disableCallIntegration } />
</FormRow>
<Divider style = { styles.fieldSeparator } />
</>
)}
<FormRow
label = 'settingsView.disableP2P'>
<Switch
onValueChange = { this._onDisableP2P }
thumbColor = { THUMB_COLOR }
trackColor = {{
true: ENABLED_TRACK_COLOR,
false: DISABLED_TRACK_COLOR
}}
value = { disableP2P } />
</FormRow>
<Divider style = { styles.fieldSeparator } />
{AppInfo.GOOGLE_SERVICES_ENABLED && (
<FormRow
fieldSeparator = { true }
label = 'settingsView.disableCrashReporting'>
<Switch
onValueChange = { this._onDisableCrashReporting }
thumbColor = { THUMB_COLOR }
trackColor = {{
true: ENABLED_TRACK_COLOR,
false: DISABLED_TRACK_COLOR
}}
value = { disableCrashReporting } />
</FormRow>
)}
</FormSectionAccordion>
</ScrollView>
</JitsiScreen>
);
}
_onBlurServerURL: () => void;
/**
* Handler the server URL lose focus event. Here we validate the server URL
* and update it to the normalized version, or show an error if incorrect.
*
* @private
* @returns {void}
*/
_onBlurServerURL() {
this._processServerURL(false /* hideOnSuccess */);
}
/**
* Callback to update the display name.
*
* @param {string} displayName - The new value to set.
* @returns {void}
*/
_onChangeDisplayName(displayName) {
super._onChangeDisplayName(displayName);
this.setState({
displayName
});
}
/**
* Callback to update the email.
*
* @param {string} email - The new value to set.
* @returns {void}
*/
_onChangeEmail(email) {
super._onChangeEmail(email);
this.setState({
email
});
}
/**
* Callback to update the server URL.
*
* @param {string} serverURL - The new value to set.
* @returns {void}
*/
_onChangeServerURL(serverURL) {
super._onChangeServerURL(serverURL);
this.setState({
serverURL
});
}
_onDisableCallIntegration: (boolean) => void;
/**
* Handles the disable call integration change event.
*
* @param {boolean} disableCallIntegration - The new value
* option.
* @private
* @returns {void}
*/
_onDisableCallIntegration(disableCallIntegration) {
this._updateSettings({
disableCallIntegration
});
this.setState({
disableCallIntegration
});
}
_onDisableP2P: (boolean) => void;
/**
* Handles the disable P2P change event.
*
* @param {boolean} disableP2P - The new value
* option.
* @private
* @returns {void}
*/
_onDisableP2P(disableP2P) {
this._updateSettings({
disableP2P
});
this.setState({
disableP2P
});
}
_onDisableCrashReporting: (boolean) => void;
/**
* Handles the disable crash reporting change event.
*
* @param {boolean} disableCrashReporting - The new value
* option.
* @private
* @returns {void}
*/
_onDisableCrashReporting(disableCrashReporting) {
if (disableCrashReporting) {
this._showCrashReportingDisableAlert();
} else {
this._disableCrashReporting(disableCrashReporting);
}
}
_onClose: () => void;
/**
* Callback to be invoked on closing the modal. Also invokes normalizeUserInputURL to validate
* the URL entered by the user.
*
* @returns {boolean} - True if the modal can be closed.
*/
_onClose() {
return this._processServerURL(true /* hideOnSuccess */);
}
/**
* Callback to update the start with audio muted value.
*
* @param {boolean} startWithAudioMuted - The new value to set.
* @returns {void}
*/
_onStartAudioMutedChange(startWithAudioMuted) {
super._onStartAudioMutedChange(startWithAudioMuted);
this.setState({
startWithAudioMuted
});
}
/**
* Callback to update the start with video muted value.
*
* @param {boolean} startWithVideoMuted - The new value to set.
* @returns {void}
*/
_onStartVideoMutedChange(startWithVideoMuted) {
super._onStartVideoMutedChange(startWithVideoMuted);
this.setState({
startWithVideoMuted
});
}
/**
* Processes the server URL. It normalizes it and an error alert is
* displayed in case it's incorrect.
*
* @param {boolean} hideOnSuccess - True if the dialog should be hidden if
* normalization / validation succeeds, false otherwise.
* @private
* @returns {void}
*/
_processServerURL(hideOnSuccess: boolean) {
const { serverURL } = this.props._settings;
const normalizedURL = normalizeUserInputURL(serverURL);
if (normalizedURL === null) {
this._showURLAlert();
return false;
}
this._onChangeServerURL(normalizedURL);
return hideOnSuccess;
}
_setURLFieldReference: (React$ElementRef<*> | null) => void;
/**
* Stores a reference to the URL field for later use.
*
* @param {Object} component - The field component.
* @protected
* @returns {void}
*/
_setURLFieldReference(component) {
this._urlField = component;
}
_showURLAlert: () => void;
/**
* Shows an alert telling the user that the URL he/she entered was invalid.
*
* @returns {void}
*/
_showURLAlert() {
const { t } = this.props;
Alert.alert(
t('settingsView.alertTitle'),
t('settingsView.alertURLText'),
[
{
onPress: () => this._urlField.focus(),
text: t('settingsView.alertOk')
}
]
);
}
/**
* Shows an alert warning the user about disabling crash reporting.
*
* @returns {void}
*/
_showCrashReportingDisableAlert() {
const { t } = this.props;
Alert.alert(
t('settingsView.alertTitle'),
t('settingsView.disableCrashReportingWarning'),
[
{
onPress: () => this._disableCrashReporting(true),
text: t('settingsView.alertOk')
},
{
text: t('settingsView.alertCancel')
}
]
);
}
_updateSettings: (Object) => void;
/**
* Updates the settings and sets state for disableCrashReporting.
*
* @param {boolean} disableCrashReporting - Whether crash reporting is disabled or not.
* @returns {void}
*/
_disableCrashReporting(disableCrashReporting) {
this._updateSettings({ disableCrashReporting });
this.setState({ disableCrashReporting });
}
}
/**
* Maps part of the Redux state to the props of this component.
*
* @param {Object} state - The Redux state.
* @returns {Props}
*/
function _mapStateToProps(state) {
return {
..._abstractMapStateToProps(state),
_serverURLChangeEnabled: isServerURLChangeEnabled(state)
};
}
export default translate(connect(_mapStateToProps)(withTheme(SettingsView)));
|
app/components/HeadsUpDisplay.js | lotgd/client-react-native | 'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View, } from 'react-native';
import _ from 'lodash';
class HeadsUpDisplay extends Component {
render() {
const values = _.map(this.props.values, function(value, key) {
return (
<View key={key} style={styles.hudGroup}>
<Text style={styles.hudValue}>{value}</Text>
<Text style={styles.hudLabel}>{key}</Text>
</View>
)
});
return (
<View style={styles.hud}>
{values}
</View>
);
}
}
module.exports = HeadsUpDisplay;
const styles = StyleSheet.create({
hud: {
flexDirection: 'row',
backgroundColor: '#E0E0E0',
alignItems: 'center',
justifyContent: 'space-around',
height: 34,
borderTopColor: '#979797',
borderTopWidth: 1,
borderBottomColor: '#C7C7C7',
borderBottomWidth: 1,
padding: 5,
},
hudGroup: {
flexDirection: 'row',
alignItems: 'flex-end',
},
hudValue: {
color: '#787878',
fontSize: 14,
},
hudLabel: {
marginLeft: 2,
color: '#787878',
fontSize: 12,
}
});
|
src/containers/Navigator.js | scottdj92/t7-chicken-native | import React from 'react';
import { Provider, connect } from 'react-redux';
// dependencies
import { StackNavigator, DrawerNavigator } from 'react-navigation';
import Router from './Router';
// components
import InitialLoading from './InitialLoading/';
import DrawerNavMenu from '../components/DrawerNavMenu/';
// Main Stack Navigators
const MainNavigator = StackNavigator(Router.MainRoutes, { initialRouteName: "characterSelect", headerMode: 'screen'});
const AboutNavigator = StackNavigator(Router.AboutRoute, { initialRouteName: "about", headerMode: 'screen' });
const HelpNavigator = StackNavigator(Router.HelpRoute, { initialRouteName: 'help', headerMode: 'screen' });
const FrameDataFAQNavigator = StackNavigator(Router.FrameDataFAQRoute, { initialRouteName: 'faq', headerMode: 'screen' });
const SupportNavigator = StackNavigator(Router.SupportRoute, { initialRouteName: 'support', headerMode: 'screen'});
const SponsorsNavigator = StackNavigator(Router.SponsorsRoute, { initialRouteName: 'sponsors', headerMode: 'screen'});
const DrawerRoutes = {
Characters: {
name: 'Tekken Characters',
screen: MainNavigator
},
FrameData: {
name: 'Frame Data',
screen: FrameDataFAQNavigator
},
// Help: {
// name: 'Help',
// screen: HelpNavigator
// },
About: {
name: 'About',
screen: AboutNavigator
},
Sponsors: {
name: 'Sponsors / Deals',
screen: SponsorsNavigator
},
Support: {
name: 'Support',
screen: SupportNavigator
}
};
const DrawerConfig = {
drawerWidth: 200,
contentComponent: ({navigation}) => <DrawerNavMenu navigation />,
};
// Hacky solution to nesting stack navigator in drawer but still having stack header configuring abilities
const RootNavigator = StackNavigator(
{
InitialLoading: {
name: "Loading",
screen: InitialLoading,
},
Main: {
name: 'Main',
screen: DrawerNavigator(DrawerRoutes, {drawerWidth: 200, contentComponent: DrawerNavMenu})
}
},
{
initialRouteName: "InitialLoading",
headerMode: 'none',
cardStyle: {backgroundColor: '#111'}
}
);
const mapStateToProps = (state) => ({
nav: state.nav
});
export default connect(mapStateToProps)(RootNavigator);
|
packages/cf-component-header/example/basic/component.js | jroyal/cf-ui | import React from 'react';
import { Box } from 'cf-component-box';
import { Header, NavList, NavItem, Hamburger } from 'cf-component-header';
import { Logo } from 'cf-component-logo';
const ViewComponent = () => (
<Header>
<Box display="flex">
<Hamburger onClick={() => console.log('Yum! Hamburger')} />
<a href="#">
<Logo />
</a>
</Box>
<NavList>
<NavItem>One</NavItem>
<NavItem>Two</NavItem>
<NavItem>Three</NavItem>
</NavList>
</Header>
);
export default ViewComponent;
|
src/components/header.js | siddharthkp/siddharthkp.github.io | import React from 'react'
import { Twitter, Github, Medium, Youtube } from './social-icons'
// const CourseBanner = () => (
// <section id="course">
// <img alt="" src="https://frontend.army/react-game/logo.png" /> Working on a new course:{' '}
// <a href="https://frontend.army/react-game" target="_blank" rel="noopener noreferrer">
// Learn React while building a game!
// </a>
// </section>
// )
const Social = () => (
<section id="social">
<ul>
<a
target="_blank"
rel="noopener noreferrer"
href="https://twitter.com/siddharthkp"
id="twitter"
>
<Twitter />
</a>
<a
target="_blank"
rel="noopener noreferrer"
href="https://github.com/siddharthkp"
id="github"
>
<Github />
</a>
<a
target="_blank"
rel="noopener noreferrer"
href="https://medium.com/@siddharthkp"
id="medium"
>
<Medium />
</a>
<a
target="_blank"
rel="noopener noreferrer"
href="https://www.youtube.com/sid-show"
id="youtube"
>
<Youtube />
</a>
</ul>
</section>
)
const Header = () => (
<div>
<Social />
</div>
)
export default Header
|
src/widgets/Charger/index.js | mydearxym/mastani | /*
*
* Charger
*
*/
import React from 'react'
// import T from 'prop-types'
import { ICON_CMD } from '@/config'
import { buildLog } from '@/utils/logger'
import { Wrapper, Battery, Liquid, MoneySign } from './styles'
/* eslint-disable-next-line */
const log = buildLog('c:Charger:index')
// battery effect: https://www.codeseek.co/hudsonkm/battery-charging-animation-with-liquid-azMJmY
// bubbles effect: https://codepen.io/Johnm__/pen/qZqgGJ
const Charger = () => {
return (
<Wrapper testid="charger">
<Battery>
<Liquid />
<MoneySign src={`${ICON_CMD}/battery_heart.svg`} />
</Battery>
</Wrapper>
)
}
Charger.propTypes = {
// https://www.npmjs.com/package/prop-types
// attr: PropTypes.string,
}
Charger.defaultProps = {
// attr: 'charger',
}
export default React.memo(Charger)
|
packages/material-ui-icons/src/Brightness6.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M20 15.31L23.31 12 20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69zM12 18V6c3.31 0 6 2.69 6 6s-2.69 6-6 6z" /></g>
, 'Brightness6');
|
app/utils/injectReducer.js | andyzeli/Bil | import React from 'react';
import PropTypes from 'prop-types';
import hoistNonReactStatics from 'hoist-non-react-statics';
import getInjectors from './reducerInjectors';
/**
* Dynamically injects a reducer
*
* @param {string} key A key of the reducer
* @param {function} reducer A reducer that will be injected
*
*/
export default ({ key, reducer }) => (WrappedComponent) => {
class ReducerInjector extends React.Component {
static WrappedComponent = WrappedComponent;
static contextTypes = {
store: PropTypes.object.isRequired,
};
static displayName = `withReducer(${(WrappedComponent.displayName || WrappedComponent.name || 'Component')})`;
componentWillMount() {
const { injectReducer } = this.injectors;
injectReducer(key, reducer);
}
injectors = getInjectors(this.context.store);
render() {
return <WrappedComponent {...this.props} />;
}
}
return hoistNonReactStatics(ReducerInjector, WrappedComponent);
};
|
src/Table/TableHead.js | dsslimshaddy/material-ui | // @flow
import React, { Component } from 'react';
import type { Element } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import withStyles from '../styles/withStyles';
export const styles = (theme: Object) => ({
root: {
fontSize: 12,
fontWeight: theme.typography.fontWeightMedium,
color: theme.palette.text.secondary,
},
});
type DefaultProps = {
classes: Object,
component: string,
};
export type Props = {
/**
* The content of the component, normally `TableRow`.
*/
children?: Element<*>,
/**
* Useful to extend the style applied to components.
*/
classes?: Object,
/**
* @ignore
*/
className?: string,
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
*/
component?: string | Function,
};
type AllProps = DefaultProps & Props;
class TableHead extends Component<DefaultProps, AllProps, void> {
props: AllProps;
static defaultProps: DefaultProps = {
classes: {},
component: 'thead',
};
getChildContext() {
// eslint-disable-line class-methods-use-this
return {
table: {
head: true,
},
};
}
render() {
const {
classes,
className: classNameProp,
children,
component: ComponentProp,
...other
} = this.props;
const className = classNames(classes.root, classNameProp);
return (
<ComponentProp className={className} {...other}>
{children}
</ComponentProp>
);
}
}
TableHead.contextTypes = {
table: PropTypes.object,
};
TableHead.childContextTypes = {
table: PropTypes.object,
};
export default withStyles(styles, { name: 'MuiTableHead' })(TableHead);
|
src/routes/Landing/components/LandingPage/StartButton/StartButton.js | nobt-io/frontend | import PropTypes from 'prop-types';
import React from 'react';
import styles from './StartButton.scss';
const StartButton = ({ active, ...props }) => {
let className = active ? styles.activeButton : styles.button;
return (
<a className={className} href="create" {...props}>
Get started - Create a Nobt
</a>
);
};
StartButton.propTypes = {
active: PropTypes.bool,
};
export default StartButton;
|
src/admin/components/history/index.js | ccetc/platform | import React from 'react'
import { connect } from 'react-redux'
import * as actions from './actions'
export class History extends React.Component {
static childContextTypes = {
history: React.PropTypes.object
}
static contextTypes = {
router: React.PropTypes.object
}
static propTypes = {
history: React.PropTypes.array,
goBack: React.PropTypes.func,
push: React.PropTypes.func
}
render() {
return this.props.children
}
componentDidMount() {
this.props.onPush(this.props.location.pathname)
}
componentDidUpdate(prevProps) {
const { location, history, onPush } = this.props
if(history.length === 0) {
onPush({ pathname: '/admin', state: 'static' })
} else {
const route = history[history.length - 1]
const pathname = route.pathname || route
if(history.length < prevProps.history.length) {
this.context.router.push({ pathname, state: 'back' })
} else if(history.length > prevProps.history.length) {
const state = route.state || 'next'
this.context.router.push({ pathname, state })
} else if(location.pathname !== prevProps.location.pathname && location.pathname !== pathname && location.state !== 'back') {
onPush({ pathname: location.pathname, state: location.state })
}
}
}
getChildContext() {
return {
history: {
goBack: this.props.onGoBack,
push: this.props.onPush,
reset: this.props.onReset
}
}
}
}
const mapStateToProps = state => ({
history: state.history
})
const mapDispatchToProps = {
onPush: actions.push,
onGoBack: actions.goBack,
onReset: actions.reset
}
export default connect(mapStateToProps, mapDispatchToProps)(History)
|
src/svg-icons/maps/flight.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsFlight = (props) => (
<SvgIcon {...props}>
<path d="M10.18 9"/><path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/>
</SvgIcon>
);
MapsFlight = pure(MapsFlight);
MapsFlight.displayName = 'MapsFlight';
MapsFlight.muiName = 'SvgIcon';
export default MapsFlight;
|
src/interface/statistics/StatisticGroup.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import STATISTIC_CATEGORY from 'interface/others/STATISTIC_CATEGORY';
const StatisticGroup = ({ children, large, wide, style, ...others }) => (
<div
className={wide ? 'col-md-6 col-sm-12 col-xs-12' : 'col-lg-3 col-md-4 col-sm-6 col-xs-12'}
style={{ padding: 0, ...style }}
{...others}
>
{children}
</div>
);
StatisticGroup.propTypes = {
children: PropTypes.node.isRequired,
large: PropTypes.bool,
wide: PropTypes.bool,
style: PropTypes.object,
// eslint-disable-next-line react/no-unused-prop-types
category: PropTypes.oneOf(Object.values(STATISTIC_CATEGORY)),
// eslint-disable-next-line react/no-unused-prop-types
position: PropTypes.number,
};
export default StatisticGroup;
|
actor-apps/app-web/src/app/components/modals/MyProfile.react.js | Just-D/actor-platform | //import _ from 'lodash';
import React from 'react';
import { KeyCodes } from 'constants/ActorAppConstants';
import MyProfileActions from 'actions/MyProfileActions';
import MyProfileStore from 'stores/MyProfileStore';
import AvatarItem from 'components/common/AvatarItem.react';
import Modal from 'react-modal';
import { Styles, TextField, FlatButton } from 'material-ui';
import ActorTheme from 'constants/ActorTheme';
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return {
profile: MyProfileStore.getProfile(),
name: MyProfileStore.getName(),
isOpen: MyProfileStore.isModalOpen(),
isNameEditable: false
};
};
class MyProfile extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
this.state = getStateFromStores();
this.unsubscribe = MyProfileStore.listen(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
button: {
minWidth: 60
},
textField: {
textColor: 'rgba(0,0,0,.87)',
focusColor: '#68a3e7',
backgroundColor: 'transparent',
borderColor: '#68a3e7',
disabledTextColor: 'rgba(0,0,0,.4)'
}
});
}
componentWillUnmount() {
this.unsubscribe();
document.removeEventListener('keydown', this.onKeyDown, false);
}
onClose = () => {
MyProfileActions.modalClose();
};
onKeyDown = event => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
};
onChange = () => {
this.setState(getStateFromStores());
};
onNameChange = event => {
this.setState({name: event.target.value});
};
onNameSave = () => {
MyProfileActions.setName(this.state.name);
this.onClose();
};
render() {
const isOpen = this.state.isOpen;
const profile = this.state.profile;
if (profile !== null && isOpen === true) {
return (
<Modal className="modal-new modal-new--profile"
closeTimeoutMS={150}
isOpen={isOpen}
style={{width: 340}}>
<header className="modal-new__header">
<a className="modal-new__header__icon material-icons">person</a>
<h4 className="modal-new__header__title">Profile</h4>
<div className="pull-right">
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Done"
labelStyle={{padding: '0 8px'}}
onClick={this.onNameSave}
secondary={true}
style={{marginTop: -6}}/>
</div>
</header>
<div className="modal-new__body row">
<AvatarItem image={profile.bigAvatar}
placeholder={profile.placeholder}
size="big"
title={profile.name}/>
<div className="col-xs">
<div className="name">
<TextField className="login__form__input"
floatingLabelText="Username"
fullWidth
onChange={this.onNameChange}
type="text"
value={this.state.name}/>
</div>
<div className="phone">
<TextField className="login__form__input"
disabled
floatingLabelText="Phone number"
fullWidth
type="tel"
value={this.state.profile.phones[0].number}/>
</div>
</div>
</div>
</Modal>
);
} else {
return null;
}
}
}
export default MyProfile;
|
src/esm/components/graphics/icons/shield-icon/index.js | KissKissBankBank/kitten | import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["color", "title"];
import React from 'react';
import PropTypes from 'prop-types';
export var ShieldIcon = function ShieldIcon(_ref) {
var color = _ref.color,
title = _ref.title,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
return /*#__PURE__*/React.createElement("svg", _extends({
width: "20",
height: "25",
viewBox: "0 0 20 25",
xmlns: "http://www.w3.org/2000/svg"
}, props), title && /*#__PURE__*/React.createElement("title", null, title), /*#__PURE__*/React.createElement("path", {
d: "M10 0c2.667 2.667 6 3.667 10 3v13c0 1.24-1.281 2.864-3.844 4.873l-.512.394c-.264.199-.54.402-.828.608l-.592.418-.308.212-.64.432-.672.442-.704.451-.736.461-.768.47L10 25l-.784-.475-.752-.466a82.073 82.073 0 01-.364-.229l-.704-.451-.672-.442-.64-.432-.608-.422-.292-.208-.56-.408-.528-.398C1.365 18.97 0 17.28 0 16V3c4 .667 7.333-.333 10-3zm0 2.652l-.271.203C7.579 4.406 5.108 5.19 2.367 5.199L2 5.195V16c0 .278.26.709.778 1.27l.237.248.269.263.3.278.332.293.363.308.394.321.425.334.456.347.488.36.518.371.55.384.58.395.302.201.951.62.673.426.384.239.384-.239.673-.426.643-.416.309-.205.596-.4.565-.389.271-.191.519-.372.487-.359.457-.348.425-.334.394-.321.363-.307.332-.293.3-.279.269-.263c.126-.128.241-.25.344-.366l.19-.224c.29-.36.449-.651.475-.865L18 16V5.195l-.367.004c-2.741-.009-5.212-.793-7.362-2.344L10 2.652zm-.001 4.567l1.033 3.197c.015.048.06.08.11.08l3.358-.007-2.721 1.969a.115.115 0 00-.042.13l1.045 3.193-2.714-1.98a.116.116 0 00-.137 0l-2.713 1.98 1.045-3.193a.115.115 0 00-.042-.13L5.5 10.489l3.358.007c.05 0 .095-.033.11-.08l1.031-3.197z",
fill: color
}));
};
ShieldIcon.propTypes = {
color: PropTypes.string,
title: PropTypes.string
};
ShieldIcon.defaultProps = {
color: '#222',
title: ''
}; |
src/svg-icons/editor/format-bold.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatBold = (props) => (
<SvgIcon {...props}>
<path d="M15.6 10.79c.97-.67 1.65-1.77 1.65-2.79 0-2.26-1.75-4-4-4H7v14h7.04c2.09 0 3.71-1.7 3.71-3.79 0-1.52-.86-2.82-2.15-3.42zM10 6.5h3c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5h-3v-3zm3.5 9H10v-3h3.5c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5z"/>
</SvgIcon>
);
EditorFormatBold = pure(EditorFormatBold);
EditorFormatBold.displayName = 'EditorFormatBold';
EditorFormatBold.muiName = 'SvgIcon';
export default EditorFormatBold;
|
src/encoded/static/components/static-pages/StaticPage.js | hms-dbmi/fourfront | 'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import _ from 'underscore';
import memoize from 'memoize-one';
import { compiler } from 'markdown-to-jsx';
import { MarkdownHeading } from '@hms-dbmi-bgm/shared-portal-components/es/components/static-pages/TableOfContents';
import { console, object, isServerSide } from '@hms-dbmi-bgm/shared-portal-components/es/components/util';
import { StaticPageBase } from '@hms-dbmi-bgm/shared-portal-components/es/components/static-pages/StaticPageBase';
import { CSVMatrixView, EmbeddedHiglassActions } from './components';
import { HiGlassPlainContainer } from './../item-pages/components/HiGlass/HiGlassPlainContainer';
import { replaceString as replacePlaceholderString } from './placeholders';
/**
* Converts context.content into different format if necessary and returns copy of context with updated 'content'.
* Currently only converts Markdown content (if a context.content[] item has 'filetype' === 'md'). Others may follow.
*
* @param {Object} context - Context provided from back-end, including all properties.
*/
export const parseSectionsContent = memoize(function(context){
const markdownCompilerOptions = {
// Override basic header elements with MarkdownHeading to allow it to be picked up by TableOfContents
'overrides' : _.object(_.map(['h1','h2','h3','h4', 'h5', 'h6'], function(type){ // => { type : { component, props } }
return [type, {
'component' : MarkdownHeading,
'props' : { 'type' : type }
}];
}))
};
function parse(section){
if (Array.isArray(section['@type']) && section['@type'].indexOf('StaticSection') > -1){
// StaticSection Parsing
if (section.filetype === 'md' && typeof section.content === 'string'){
section = _.extend({}, section, {
'content' : compiler(section.content, markdownCompilerOptions)
});
} else if (section.filetype === 'html' && typeof section.content === 'string'){
section = _.extend({}, section, {
'content' : object.htmlToJSX(section.content)
});
} // else: retain plaintext or HTML representation
} else if (Array.isArray(section['@type']) && section['@type'].indexOf('HiglassViewConfig') > -1){
// HiglassViewConfig Parsing
if (!section.viewconfig) throw new Error('No viewconfig setup for this section.');
let hiGlassComponentHeight;
if (section.instance_height && section.instance_height > 0) {
hiGlassComponentHeight = section.instance_height;
}
section = _.extend({}, section, {
'content' : (
<React.Fragment>
<EmbeddedHiglassActions context={section} style={{ marginTop : -10 }} />
<HiGlassPlainContainer viewConfig={section.viewconfig} mountDelay={4000} height={hiGlassComponentHeight} />
</React.Fragment>
)
});
} else if (Array.isArray(section['@type']) && section['@type'].indexOf('JupyterNotebook') > -1){
// TODO
}
return section;
}
if (!Array.isArray(context.content)) throw new Error('context.content is not an array.');
return _.extend(
{}, context, {
'content' : _.map(
_.filter(context.content || [], function(section){ return section && (section.content || section.viewconfig) && !section.error; }),
parse
)
});
});
export const StaticEntryContent = React.memo(function StaticEntryContent(props){
const { section, className } = props;
const { content = null, options = {}, filetype = null } = section;
let renderedContent;
if (!content) return null;
// Handle JSX
if (typeof content === 'string' && filetype === 'jsx'){
renderedContent = replacePlaceholderString(content.trim(), _.omit(props, 'className', 'section', 'content'));
} else if (typeof content === 'string' && filetype === 'txt' && content.slice(0,12) === 'placeholder:'){
// Deprecated older method - to be removed once data.4dn uses filetype=jsx everywhere w/ placeholder
renderedContent = replacePlaceholderString(content.slice(12).trim(), _.omit(props, 'className', 'section', 'content'));
} else {
renderedContent = content;
}
const cls = "section-content clearfix " + (className? ' ' + className : '');
if (filetype === 'csv'){
// Special case
return <CSVMatrixView csv={renderedContent} options={options} />;
} else {
// Common case - markdown, plaintext, etc.
return <div className={cls}>{ renderedContent }</div>;
}
});
/**
* This component shows an alert on mount if have been redirected from a different page, and
* then renders out a list of StaticEntry components within a Wrapper in its render() method.
* May be used by extending and then overriding the render() method.
*/
export default class StaticPage extends React.PureComponent {
static Wrapper = StaticPageBase.Wrapper;
render(){
return <StaticPageBase {...this.props} childComponent={StaticEntryContent} contentParseFxn={parseSectionsContent} />;
}
}
|
lib/components/Tooltip/Tooltip.js | vandreleal/react-social-github | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import './Tooltip.css';
class Tooltip extends Component {
constructor() {
super();
this.state = {};
}
render() {
let isOpen = this.props.open === true;
let content = null;
let anchor = {
right: 0,
left: 0,
bottom: 0,
top: 0,
height: 0,
width: 0
};
let windowWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
let windowHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
let styleMargin = 8;
if (this.props.anchor) {
anchor = this.props.anchor.getBoundingClientRect();
}
let style = {};
if (windowHeight - anchor.bottom > anchor.top) {
style.top = anchor.top + anchor.height + styleMargin;
} else {
style.bottom = (windowHeight + anchor.height + styleMargin) - anchor.bottom;
}
if (windowWidth - anchor.right > anchor.left) {
style.left = anchor.left;
} else {
style.right = (windowWidth - anchor.right);
}
if (this.props.position === 'left') {
style.right = windowWidth - anchor.right;
delete style.left;
} else if (this.props.position === 'right') {
style.left = anchor.left;
delete style.right;
} else if (this.props.position === 'top') {
style.bottom = windowHeight - anchor.bottom;
delete style.top;
} else if (this.props.position === 'bottom') {
style.top = anchor.top;
delete style.bottom;
}
if (isOpen) {
content = (
<div
className="rsg-github-tooltip rsg-animation-container"
key={isOpen}
style={style}
>
{this.props.children}
</div>
);
}
return (
<div
className="rsg-github-tooltip"
onBlur={this.props.onBlur}
onClick={this.props.onClick}
onMouseEnter={this.props.onMouseEnter}
onMouseLeave={this.props.onMouseLeave}
>
<ReactCSSTransitionGroup
transitionEnterTimeout={100}
transitionLeaveTimeout={100}
transitionName="rsg-github-tooltip-animation"
>
{content}
</ReactCSSTransitionGroup>
</div>
);
}
}
Tooltip.propTypes = {
// anchor
anchor: PropTypes.object,
// children
children: PropTypes.object,
// onBlur
onBlur: PropTypes.bool,
// onClick
onClick: PropTypes.func,
// onMouseEnter
onMouseEnter: PropTypes.func,
// OonMouseLeave
onMouseLeave: PropTypes.func,
// open
open: PropTypes.bool,
// position
position: PropTypes.string
};
export default Tooltip;
|
src/client/components/test/list.js | adamgruber/mochawesome-report-generator | import React from 'react';
import PropTypes from 'prop-types';
import { Test } from 'components/test';
import classNames from 'classnames/bind';
import styles from './test.css';
const cx = classNames.bind(styles);
const TestList = ({
className,
tests,
beforeHooks,
afterHooks,
enableCode,
}) => (
<ul className={cx('list', className)}>
{!!beforeHooks &&
beforeHooks.map(test => (
<Test key={test.uuid} test={test} enableCode={enableCode} />
))}
{!!tests &&
tests.map(test => (
<Test key={test.uuid} test={test} enableCode={enableCode} />
))}
{!!afterHooks &&
afterHooks.map(test => (
<Test key={test.uuid} test={test} enableCode={enableCode} />
))}
</ul>
);
TestList.propTypes = {
className: PropTypes.string,
tests: PropTypes.array,
beforeHooks: PropTypes.array,
afterHooks: PropTypes.array,
enableCode: PropTypes.bool,
};
TestList.displayName = 'TestList';
export default TestList;
|
site/pages/ExamplePage.js | colbyr/react-dnd | import React from 'react';
import Header from '../components/Header';
import PageBody from '../components/PageBody';
import SideBar from '../components/SideBar';
import { ExamplePages } from '../Constants';
export default class ExamplesPage {
render() {
return (
<div>
<Header/>
<PageBody hasSidebar>
<SideBar
groups={ExamplePages}
example={this.props.example}
/>
{this.props.children}
</PageBody>
</div>
);
}
} |
src/components/dot-net/plain-wordmark/DotNetPlainWordmark.js | fpoumian/react-devicon | import React from 'react'
import PropTypes from 'prop-types'
import SVGDeviconInline from '../../_base/SVGDeviconInline'
import iconSVG from './DotNetPlainWordmark.svg'
/** DotNetPlainWordmark */
function DotNetPlainWordmark({ width, height, className }) {
return (
<SVGDeviconInline
className={'DotNetPlainWordmark' + ' ' + className}
iconSVG={iconSVG}
width={width}
height={height}
/>
)
}
DotNetPlainWordmark.propTypes = {
className: PropTypes.string,
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
}
export default DotNetPlainWordmark
|
example/entry.js | rpominov/react-joyful-testing | import React from 'react'
import TestUtils from 'react-addons-test-utils'
import createJoy from '../src/index'
const {
renderToRelevant,
eventsToLog,
mapOverRenders,
eventCreators: {triggerCallback, setProps},
} = createJoy(React, TestUtils)
// Stateless component example
import MyStateless from './targets/Stateless'
const renderMyStateless = renderToRelevant(MyStateless)
console.log(renderMyStateless({value: 1, max: 10}).value.props.children) // 1
console.log(renderMyStateless({value: 11, max: 10}).value.props.children) // 10+
// Stateful component expamle
import MyStateful from './targets/Stateful'
const clickInc = triggerCallback('incBtn', 'onClick')
const clickDec = triggerCallback('decBtn', 'onClick')
const setMax = max => setProps({initialValue: 0, max})
const events = [setMax(10), clickInc, clickInc, clickInc, setMax(2), setMax(10), clickDec]
const log = eventsToLog(MyStateful)(events)
console.log(mapOverRenders(els => els.value.props.children)(log)) // [0, 1, 2, 3, "2+", 3, 2]
|
packages/react-error-overlay/src/components/NavigationBar.js | Clearcover/web-build | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* @flow */
import React from 'react';
import { red, redTransparent } from '../styles';
const navigationBarStyle = {
marginBottom: '0.5rem',
};
const buttonContainerStyle = {
marginRight: '1em',
};
const _navButtonStyle = {
backgroundColor: redTransparent,
color: red,
border: 'none',
borderRadius: '4px',
padding: '3px 6px',
cursor: 'pointer',
};
const leftButtonStyle = {
..._navButtonStyle,
borderTopRightRadius: '0px',
borderBottomRightRadius: '0px',
marginRight: '1px',
};
const rightButtonStyle = {
..._navButtonStyle,
borderTopLeftRadius: '0px',
borderBottomLeftRadius: '0px',
};
type Callback = () => void;
type NavigationBarPropsType = {|
currentError: number,
totalErrors: number,
previous: Callback,
next: Callback,
|};
function NavigationBar(props: NavigationBarPropsType) {
const { currentError, totalErrors, previous, next } = props;
return (
<div style={navigationBarStyle}>
<span style={buttonContainerStyle}>
<button onClick={previous} style={leftButtonStyle}>
←
</button>
<button onClick={next} style={rightButtonStyle}>
→
</button>
</span>
{`${currentError} of ${totalErrors} errors on the page`}
</div>
);
}
export default NavigationBar;
|
yycomponent/col/Col.js | 77ircloud/yycomponent | import React from 'react';
import { Col as _Col } from 'antd';
class Col extends React.Component{
constructor(props){
super(props);
}
render(){
return (<_Col {...this.props}/>);
}
}
export default Col
|
src/Navbar/index.js | Erazihel/react-wp | // @flow
import React from 'react';
import {
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
NavItem,
NavLink,
Collapse,
} from 'reactstrap';
import { Link } from 'react-router-dom';
import config from '../../config';
type Data = {
name: string,
};
class NavbarComponent extends React.Component<any, any> {
toggle: Function;
constructor() {
super();
this.toggle = this.toggle.bind(this);
this.state = {
isOpen: false,
title: '',
};
}
toggle() {
this.setState({
isOpen: !this.state.isOpen,
});
}
componentDidMount() {
fetch(`${config.API_URLS.base}`)
.then(response => response.json())
.then((data: Data) => {
this.setState({
title: data.name,
});
})
.catch((e: Error) =>
console.error(`Failed to recover data: ${e.message}`)
);
}
render() {
return (
<div>
<Navbar color="dark" dark expand="md">
<NavbarBrand tag={Link} to="/">
{this.state.title}
</NavbarBrand>
<NavbarToggler onClick={this.toggle} />
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="ml-auto" navbar>
<NavItem>
<NavLink tag={Link} to="/">
Posts
</NavLink>
</NavItem>
<NavItem>
<NavLink tag={Link} to="/comments/">
Comments
</NavLink>
</NavItem>
<NavItem>
<NavLink tag={Link} to="/archives/">
Archives
</NavLink>
</NavItem>
<NavItem>
<NavLink tag={Link} to="/categories/">
Categories
</NavLink>
</NavItem>
</Nav>
</Collapse>
</Navbar>
</div>
);
}
}
export default NavbarComponent;
|
src/slides/seven/decorators.js | brudil/slides-es6andbeyond | import React from 'react';
import Radium from 'radium';
import Snippet from '../../Snippet';
import {bindShowHelper} from '../../utils';
const styles = {
inlinePre: {
display: 'inline'
},
slide: {
textAlign: 'center'
}
};
const examplesSource = [
`
class Person {
name() {return \`\${this.first} \${this.last}\`}
}
`,
`
class Person {
@readonly
name() {return \`\${this.first} \${this.last}\`}
}
`,
`
(target) => {}
(target, name, descriptor) => {}
`
]
;
@Radium
export default class Decorators extends React.Component {
static actionCount = 2;
static propTypes = {
actionIndex: React.PropTypes.number.isRequired,
style: React.PropTypes.object.isRequired
}
render() {
const {actionIndex} = this.props;
const show = bindShowHelper(actionIndex);
return (
<div style={[this.props.style, styles.slide]}>
<h1>@decorators</h1>
<Snippet source={show.withArray(examplesSource)} />
</div>
);
}
}
|
src/Shared/intl-enzyme-test-helper.js | psychobolt/react-native-boilerplate | /**
* Components using the react-intl module require access to the intl context.
* This is not available when mounting single components in Enzyme.
* These helper functions aim to address that and wrap a valid,
* English-locale intl context around them.
*/
import React from 'react';
import { IntlProvider, intlShape } from 'react-intl';
import { mount, shallow } from 'enzyme'; // eslint-disable-line import/no-extraneous-dependencies
/** Create the IntlProvider to retrieve context for wrapping around. */
function createIntlContext(messages, locale) {
const intlProvider = new IntlProvider({ messages, locale }, {});
const { intl } = intlProvider.getChildContext();
return intl;
}
/** When using React-Intl `injectIntl` on components, props.intl is required. */
function nodeWithIntlProp(node, messages = {}, locale = 'en') {
return React.cloneElement(node, { intl: createIntlContext(messages, locale) });
}
/**
* Create a shadow renderer that wraps a node with Intl provider context.
* @param {ReactComponent} node - Any React Component
* @param {Object} context
* @param {Object} messages - A map with keys (id) and messages (value)
* @param {string} locale - Locale string
*/
export function shallowWithIntl(node, { context } = {}, messages = {}, locale = 'en') {
return shallow(
nodeWithIntlProp(node),
{
context: Object.assign({}, context, { intl: createIntlContext(messages, locale) }),
}
);
}
/**
* Mount the node with Intl provider context.
* @param {Component} node - Any React Component
* @param {Object} context
* @param {Object} messages - A map with keys (id) and messages (value)
* @param {string} locale - Locale string
*/
export function mountWithIntl(node, { context, childContextTypes } = {}, messages = {}, locale = 'en') {
return mount(
nodeWithIntlProp(node),
{
context: Object.assign({}, context, { intl: createIntlContext(messages, locale) }),
childContextTypes: Object.assign({}, { intl: intlShape }, childContextTypes)
}
);
}
|
docs/src/index.js | zackharley/react-colours | import React from 'react';
import { render } from 'react-dom';
import Colours from '../../dist/react-colours.min';
import colours from './colours';
render(
<Colours colours={colours}/>,
document.getElementById('app')
)
|
src0/components/Trade.js | yaswanthsvist/openCexTrade | import React from 'react';
import {connect} from 'react-redux';
import * as bitfinexActions from './../actions/bitfinex';
import { StyleSheet, Text,Button, View,ScrollView,StatusBar,Image } from 'react-native';
import wsBitfinex from './../services/webSocket';
import MarketDepth from './ui/MarketDepth';
let BOOK = {
bids : {},
asks : {},
psnap : {},
mcnt : 0,
}
let bookChannelid=null;
const checkCross = (msg) => {
let bid = BOOK.psnap.bids[0]
let ask = BOOK.psnap.asks[0]
if (bid >= ask) {
console.log( "bid(" + bid + ")>=ask(" + ask + ")");
}
}
const handleBook =(msg,dispatch,chanId)=> {
if(msg[0]!=chanId||msg[1]=='hb'){
return;
}
// console.log(msg[1]);
if (BOOK.mcnt === 0) {
msg[1].forEach( (pp)=>{
pp = { price: pp[0], cnt: pp[1], amount: pp[2] }
const side = pp.amount >= 0 ? 'bids' : 'asks'
pp.amount = Math.abs(pp.amount)
BOOK[side][pp.price] = pp
})
}
else {
let pp = { price: msg[1][0], cnt: msg[1][1], amount: msg[1][2] }
if (!pp.cnt) {
let found = true
if (pp.amount > 0) {
if (BOOK['bids'][pp.price]) {
delete BOOK['bids'][pp.price]
} else {
found = false
}
} else if (pp.amount < 0) {
if (BOOK['asks'][pp.price]) {
delete BOOK['asks'][pp.price]
} else {
found = false
}
}
if (!found) {
console.log(JSON.stringify(pp) + " BOOK delete fail side not found\n");
}
} else {
let side = pp.amount >= 0 ? 'bids' : 'asks'
pp.amount = Math.abs(pp.amount)
BOOK[side][pp.price] = pp
}
}
let sides=['bids', 'asks'];
let presentableData={};
sides.forEach( (side)=>{
let sbook = BOOK[side]
let bprices = Object.keys(sbook)
let prices = bprices.sort(function(a, b) {
if (side === 'bids') {
return +a >= +b ? -1 : 1
} else {
return +a <= +b ? -1 : 1
}
})
BOOK.psnap[side] = prices;
//console.log("num price points", side, prices.length)
// console.log(prices.map((price)=>BOOK[side][price].amount));
let list=[],amount=0;
for (let price of prices){
list.push([price, ( amount += BOOK[side][price].amount ) ] );
};
presentableData[side]=list;
});
BOOK.mcnt++
checkCross(msg)
dispatch( bitfinexActions.updateBooksData({presentableData,chanId}) );
}
class Trade extends React.Component{
constructor(props){
super(props)
const candleChannleHandler=(msg)=>{
const {bitfinex,dispatch}=this.props;
if( !Array.isArray( msg ) && msg.event == "subscribed" ){
if( msg.channel == "candles" ){
dispatch( bitfinexActions.subscribeToCandles( msg ) );
}
if( msg.channel == "book" ){
console.log(msg.channel);
dispatch( bitfinexActions.subscribedToBook( msg ) );
}
} else if( Array.isArray( msg ) ){
handleBook(msg,dispatch,bitfinex.books.chanId);
return;
const data = msg[1];
const chanId = msg[0];
if( Array.isArray( data ) && chanId == bitfinex.candles.chanId ){
if( Array.isArray(data[0]) ){
dispatch( bitfinexActions.initializeCandlesData( { data , chanId } ) )
}else{
dispatch (bitfinexActions.updateCandlesData( { data , chanId } ) );
}
}
}
}
this.state={};
wsBitfinex.addListener(candleChannleHandler);
wsBitfinex.init().then(()=>{
wsBitfinex.send({
"event": "subscribe",
"channel": "candles",
"key": "trade:1m:tBTCUSD"
});
wsBitfinex.send({
event: "subscribe",
channel: "book",
pair:"tBTCUSD" ,
prec: "P0",
"freq": "F3",
"len": 25
});
}
);
}
componentWillReceiveProps(nextProps) {
const {data}=this.props.bitfinex.candles;
// console.log(nextProps.bitfinex.books);
if(
nextProps.bitfinex.candles.data!=null &&
data != null &&
data.length != nextProps.bitfinex.candles.data.length
){
// console.log(nextProps.bitfinex.candles.data[0]);
}
}
static navigationOptions={
title:"Trade",
drawerLabel: 'Home',
tabBarLabel: 'Trade',
}
render(){
const {presentableData}=this.props.bitfinex.books;
return(
<View>
<MarketDepth data={presentableData}></MarketDepth>
<Text>Trade here</Text>
</View>
)
}
}
const mapStateToProps = state => ({
bitfinex:state.bitfinex,
});
export default connect(mapStateToProps)(Trade);
|
src/components/DecoratorHelper/DropDownMenuDecorator/DropDownMenuDecorator.js | dreambo8563/RSK | import React, { Component } from 'react';
import { observer } from 'mobx-react'
import { observable, action } from 'mobx'
export const dropDownMenu = PopComponent =>
Target =>
@observer class DropDownMenuDecorator extends Component {
@observable show = false;
@action
showMenu() {
this.show = true
}
@action
hideMenu() {
this.show = false
}
render() {
return (
<Target
onMouseOver={::this.showMenu}
onMouseLeave = {::this.hideMenu } >
{ this.show ? <PopComponent /> : undefined }
</Target >
)
}
}
|
app/app.js | arnaudmolo/awkward-list | /**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
import 'babel-polyfill'
/* eslint-disable import/no-unresolved */
// Load the manifest.json file and the .htaccess file
import '!file?name=[name].[ext]!./manifest.json'
import 'file?name=[name].[ext]!./.htaccess'
/* eslint-enable import/no-unresolved */
// Import all the third party stuff
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { applyRouterMiddleware, Router, browserHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
import useScroll from 'react-router-scroll'
import LanguageProvider from 'containers/LanguageProvider'
import configureStore from './store'
import ReactGA from 'react-ga'
// Import i18n messages
import { translationMessages } from './i18n'
// Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder
import 'sanitize.css/sanitize.css'
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)()`
const initialState = {}
const store = configureStore(initialState, browserHistory)
// import sagas from './sagas'
import TweetsSaga from 'containers/Tweets/sagas'
import InstagramSagas from 'containers/Instagram/sagas'
const sagas = [...TweetsSaga, ...InstagramSagas]
sagas.forEach(store.runSaga)
// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
import { selectLocationState } from 'containers/App/selectors'
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: selectLocationState()
})
// Set up the router, wrapping all Routes in the App component
import App from 'containers/App'
import createRoutes from './routes'
const rootRoute = {
component: App,
childRoutes: createRoutes(store)
}
const render = (translatedMessages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={translatedMessages}>
<Router
history={history}
routes={rootRoute}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(useScroll())
}
/>
</LanguageProvider>
</Provider>,
document.getElementById('app')
)
}
// Hot reloadable translation json files
if (module.hot) {
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept('./i18n', () => {
render(translationMessages)
})
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
System.import('intl').then(() => render(translationMessages))
} else {
render(translationMessages)
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
import { install } from 'offline-plugin/runtime'
install()
|
element-react-test/src/containers/NoneedLogin.js | fengnovo/fengnovo-react-test | import React from 'react'
import {
Layout,
Menu,
Breadcrumb,
Table,Form,
DateRangePicker,
Button,
Select,
Input,
Pagination
} from 'element-react'
import { mockData } from '../mock'
class NoneedLogin extends React.Component {
constructor(...args){
super(...args)
this.state = mockData
}
onOpen() {
}
onClose() {
}
onSubmit() {
}
onChange() {
}
rowClassName(row, index) {
if (index%2 === 0) {
return '';
} else{
return 'yzt-table-bg';
}
}
render() {
return <div className="yzt-container">
<p className="content-nav-title">
<span>免登录查询</span>
</p>
<div className="yzt-container-content">
<Form inline={true} model={this.state.form} onSubmit={this.onSubmit.bind(this)} className="demo-form-inline">
<Form.Item>
<div className="yzt-form-item-input">
<Input value={this.state.form.user}
placeholder="输入广告主pin查询"
onChange={this.onChange.bind(this, 'user')}
className="yzt-form-item-btn-one"
></Input>
</div>
</Form.Item>
<Form.Item>
<Button nativeType="submit" type="primary" className="yzt-form-item-btn-one">查询</Button>
</Form.Item>
</Form>
</div>
</div>
}
}
export default NoneedLogin |
src/SplitButton.js | omerts/react-bootstrap | /* eslint react/prop-types: [2, {ignore: "bsSize"}] */
/* BootstrapMixin contains `bsSize` type validation */
import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import DropdownStateMixin from './DropdownStateMixin';
import Button from './Button';
import ButtonGroup from './ButtonGroup';
import DropdownMenu from './DropdownMenu';
const SplitButton = React.createClass({
mixins: [BootstrapMixin, DropdownStateMixin],
propTypes: {
pullRight: React.PropTypes.bool,
title: React.PropTypes.node,
href: React.PropTypes.string,
id: React.PropTypes.string,
target: React.PropTypes.string,
dropdownTitle: React.PropTypes.node,
dropup: React.PropTypes.bool,
onClick: React.PropTypes.func,
onSelect: React.PropTypes.func,
disabled: React.PropTypes.bool,
className: React.PropTypes.string,
children: React.PropTypes.node
},
getDefaultProps() {
return {
dropdownTitle: 'Toggle dropdown'
};
},
render() {
let groupClasses = {
'open': this.state.open,
'dropup': this.props.dropup
};
let button = (
<Button
{...this.props}
ref="button"
onClick={this.handleButtonClick}
title={null}
id={null}>
{this.props.title}
</Button>
);
let dropdownButton = (
<Button
{...this.props}
ref="dropdownButton"
className={classNames(this.props.className, 'dropdown-toggle')}
onClick={this.handleDropdownClick}
title={null}
href={null}
target={null}
id={null}>
<span className="sr-only">{this.props.dropdownTitle}</span>
<span className="caret" />
<span style={{letterSpacing: '-.3em'}}> </span>
</Button>
);
return (
<ButtonGroup
bsSize={this.props.bsSize}
className={classNames(groupClasses)}
id={this.props.id}>
{button}
{dropdownButton}
<DropdownMenu
ref="menu"
onSelect={this.handleOptionSelect}
aria-labelledby={this.props.id}
pullRight={this.props.pullRight}>
{this.props.children}
</DropdownMenu>
</ButtonGroup>
);
},
handleButtonClick(e) {
if (this.state.open) {
this.setDropdownState(false);
}
if (this.props.onClick) {
this.props.onClick(e, this.props.href, this.props.target);
}
},
handleDropdownClick(e) {
e.preventDefault();
this.setDropdownState(!this.state.open);
},
handleOptionSelect(key) {
if (this.props.onSelect) {
this.props.onSelect(key);
}
this.setDropdownState(false);
}
});
export default SplitButton;
|
client/sidebar/header/actions/CreateRoomList.js | VoiSmart/Rocket.Chat | import { Box, Margins } from '@rocket.chat/fuselage';
import { useMutableCallback } from '@rocket.chat/fuselage-hooks';
import React from 'react';
import { modal, popover } from '../../../../app/ui-utils/client';
import { useAtLeastOnePermission, usePermission } from '../../../contexts/AuthorizationContext';
import { useSetModal } from '../../../contexts/ModalContext';
import { useSetting } from '../../../contexts/SettingsContext';
import { useTranslation } from '../../../contexts/TranslationContext';
import CreateTeamModal from '../../../views/teams/CreateTeamModal';
import CreateChannelWithData from '../CreateChannelWithData';
import CreateRoomListItem from './CreateRoomListItem';
const CREATE_CHANNEL_PERMISSIONS = ['create-c', 'create-p'];
const CREATE_TEAM_PERMISSIONS = ['create-team'];
const CREATE_DISCUSSION_PERMISSIONS = ['start-discussion', 'start-discussion-other-user'];
const style = {
textTransform: 'uppercase',
};
const useAction = (title, content) =>
useMutableCallback((e) => {
e.preventDefault();
popover.close();
modal.open({
title,
content,
data: {
onCreate() {
modal.close();
},
},
modifier: 'modal',
showConfirmButton: false,
showCancelButton: false,
confirmOnEnter: false,
});
});
const useReactModal = (Component) => {
const setModal = useSetModal();
return useMutableCallback((e) => {
popover.close();
e.preventDefault();
const handleClose = () => {
setModal(null);
};
setModal(() => <Component onClose={handleClose} />);
});
};
function CreateRoomList() {
const t = useTranslation();
const canCreateChannel = useAtLeastOnePermission(CREATE_CHANNEL_PERMISSIONS);
const canCreateTeam = useAtLeastOnePermission(CREATE_TEAM_PERMISSIONS);
const canCreateDirectMessages = usePermission('create-d');
const canCreateDiscussion = useAtLeastOnePermission(CREATE_DISCUSSION_PERMISSIONS);
const createChannel = useReactModal(CreateChannelWithData);
const createTeam = useReactModal(CreateTeamModal);
const createDirectMessage = useAction(t('Direct_Messages'), 'CreateDirectMessage');
const createDiscussion = useAction(t('Discussion_title'), 'CreateDiscussion');
const discussionEnabled = useSetting('Discussion_enabled');
return (
<div className='rc-popover__column'>
<Margins block='x8'>
<Box is='p' style={style} fontScale='micro'>
{t('Create_new')}
</Box>
</Margins>
<ul className='rc-popover__list'>
<Margins block='x8'>
{canCreateChannel && (
<CreateRoomListItem icon='hashtag' text={t('Channel')} action={createChannel} />
)}
{canCreateTeam && <CreateRoomListItem icon='team' text={t('Team')} action={createTeam} />}
{canCreateDirectMessages && (
<CreateRoomListItem
icon='balloon'
text={t('Direct_Messages')}
action={createDirectMessage}
/>
)}
{discussionEnabled && canCreateDiscussion && (
<CreateRoomListItem
icon='discussion'
text={t('Discussion')}
action={createDiscussion}
/>
)}
</Margins>
</ul>
</div>
);
}
export default CreateRoomList;
|
examples/counter/src/index.js | tjdavies/RDX | import React from 'react';
import ReactDOM from 'react-dom';
import copal from 'copal';
export const TodoApp = copal(
(state, actions) =>
<div>
<button onClick={actions.decrement}>-</button>
<div>{state.value}</div>
<button onClick={actions.increment}>+</button>
</div>
,
{
initialize: a => a.map( s => ({value: 0})),
increment: a => a.map( s => ({value: s.value + 1})),
decrement: a => a.map( s => ({value: s.value - 1})),
}
)
ReactDOM.render(TodoApp, document.getElementById('root')); |
components/profile/runhistory/runHistory.js | akashnautiyal013/ImpactRun01 | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableHighlight,
Image,
ListView,
ScrollView,
AppRegistry,
Dimensions,
ActivityIndicatorIOS,
RefreshControl,
AsyncStorage,
TouchableOpacity,
AlertIOS,
TextInput,
} from 'react-native';
import apis from '../../apis';
import styleConfig from '../../styleConfig';
var deviceWidth = Dimensions.get('window').width;
var deviceHeight = Dimensions.get('window').height;
import Icon from 'react-native-vector-icons/MaterialIcons';
import Icon2 from 'react-native-vector-icons/FontAwesome';
import Icon3 from 'react-native-vector-icons/Ionicons';
import LoginBtns from '../../login/LoginBtns';
import commonStyles from '../../styles';
import BackgroundFetch from "react-native-background-fetch";
import Modal from '../../downloadsharemeal/CampaignModal'
import KeyboardSpacer from 'react-native-keyboard-spacer';
class RunHistory extends Component {
constructor(props) {
super(props);
this.getWeightLocal();
var ds = new ListView.DataSource({
rowHasChanged: (row1, row2) => row1.version !== row2.version,
sectionHeaderHasChanged: (section1, section2) => section1.version !== section2.version,
});
this.state = {
rowData:[],
runHistoryData: ds.cloneWithRowsAndSections([]),
loaded: false,
refreshing: false,
open:false,
user:null ,
loadingFirst:false,
enterWeightmodel:false,
newarray:false,
someData:null,
};
this.renderRunsRow = this.renderRunsRow.bind(this);
this.fetchRunhistoryupdataData = this.fetchRunhistoryupdataData.bind(this);
this.covertmonthArrayToMap = this.covertmonthArrayToMap.bind(this);
}
componentDidMount() {
// console.log('RawData', this.props.rawData);
this.state.someData = this.props.rawData
AsyncStorage.getItem('runversion', (err, result) => {
this.setState({
runversion:JSON.parse(result),
})
})
if (this.state.someData != null) {
// console.log("this.state.runHistoryData",this.state.runHistoryData);
this.setState({
runHistoryData:this.state.runHistoryData.cloneWithRowsAndSections(this.covertmonthArrayToMap(this.props.rawData)),
})
// console.log("this.state.runHistoryData",this.state.runHistoryData);
}else{
console.log("elsepart");
}
}
getUserData(){
AsyncStorage.multiGet(['UID234'], (err, stores) => {
stores.map((result, i, store) => {1
let key = store[i][0];
let val = store[i][1];
let user = JSON.parse(val);
this.setState({
user:user,
rawData: [],
})
})
})
}
isFlagedRun(rowData){
if (rowData.is_flag === false) {
return(
<Icon style={{color:'black',fontSize:20,margin:10}} name ="error_outline">error_outline</Icon>
)
}else{
return;
}
}
removeallRun(){
AsyncStorage.removeItem('fetchRunhistoryData',(err) => {
console.log("fetchRunhistoryDataerr",err);
});
}
onPressFlagedRun(rowData){
AlertIOS.alert('Flagged Run','We found some error with this run, this will not be recorded. Do give feedback for this run, if you have any.',
[
{text: 'OK',},
{text: 'FEEDBACK', onPress: () => this.GiveFeedback(rowData)}
],);
}
renderSectionHeader(sectionData, category) {
return (
<View style={[commonStyles.Navbar,{height:30,width:deviceWidth,justifyContent:'flex-start',paddingTop:0,paddingLeft:5}]}>
<Text style={commonStyles.menuTitle2}>{category}</Text>
</View>
)
}
GiveFeedback(rowData){
this.setState({
open:true,
runpostdata:JSON.stringify(rowData),
})
}
postRunFeedback(){
var user_id = this.props.user.user_id;
var date = new Date();
var feebback = 'Feedback by user: '+"Date :"+date+" "+this.state.runpostdata+" Feedback Message: "+this.state.text;
fetch(apis.UserFeedBack, {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body:JSON.stringify({
"feedback":feebback,
"user_id":user_id,
})
})
.then((response) => response.json())
.then((response) => {
this.closemodel();
AlertIOS.alert('Thank you for giving your feedback');
})
.catch((err) => {
console.log('err',err);
})
}
modelView(){
return(
<Modal
style={[styles.modelStyle,{backgroundColor:'rgba(12,13,14,0.1)'}]}
isOpen={this.state.open}
>
<View style={styles.modelWrap}>
<Text style={{textAlign:'center', marginBottom:5,color:styleConfig.greyish_brown_two,fontWeight:'500',fontFamily: styleConfig.FontFamily,width:deviceWidth-100,}}>FEEDBACK</Text>
<View style={{flex:1,justifyContent: 'center',alignItems: 'center',}}>
<View>
<TextInput
placeholder="Enter your feedback here"
style={{width:deviceWidth-100,height:(deviceHeight/10)-20,borderColor:'grey',borderWidth:1,padding:1,paddingLeft:5,fontSize:12}}
multiline = {true}
numberOfLines = {6}
onChangeText={(text) => this.setState({text})}
value={this.state.text}
/>
</View>
<View style={styles.modelBtnWrap}>
<TouchableOpacity style={styles.modelbtn} onPress ={()=>this.closemodel()}><Text style={styles.btntext}>CLOSE</Text></TouchableOpacity>
<TouchableOpacity style={styles.modelbtn}onPress ={()=>this.postRunFeedback()}><Text style={styles.btntext}>SUBMIT</Text></TouchableOpacity>
</View>
</View>
</View>
<KeyboardSpacer/>
</Modal>
)
}
getWeightLocal(){
AsyncStorage.getItem('userWeight', (err, result) => {
var weight = JSON.parse(result)
if (weight != null) {
console.log('resultcalori',weight);
this.setState({
weight:weight
})
}else{
this.setState({
enterWeightmodel:true,
})
}
})
}
putUserWeight(){
var user_id = this.props.user.user_id;
var auth_token = this.props.user.auth_token;
this.closemodel();
fetch(apis.userDataapi + user_id + "/", {
method: "put",
headers: {
'Authorization':"Bearer "+ auth_token,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body:JSON.stringify({
"body_weight":this.state.bodyweight,
})
})
.then((response) => response.json())
.then((response) => {
console.log('submited',response);
var userWeight = response.body_weight;
AsyncStorage.mergeItem('userWeight',JSON.stringify(userWeight),()=>{
this.setState({
weight:userWeight,
})
});
})
.catch((err) => {
console.log('err',err);
if (err != null) {
this.setState({
enterWeightmodel:true,
})
};
})
}
modelViewEnterWeight(){
return(
<Modal
style={[styles.modelStyle,{backgroundColor:'rgba(12,13,14,0.1)'}]}
isOpen={this.state.enterWeightmodel}
>
<View style={styles.modelWrap}>
<Text style={{marginBottom:5,color:styleConfig.greyish_brown_two,fontWeight:'500',width:deviceWidth-100,fontFamily: styleConfig.FontFamily,}}>Enter your weight to calculate calories.</Text>
<View>
<TextInput
placeholder="Enter Your weight in KG"
style={{width:deviceWidth-100,height:40,borderColor:'grey',borderWidth:1,padding:1,paddingLeft:5,fontSize:12}}
multiline = {true}
numberOfLines = {1}
keyboardType = "numeric"
onChangeText={(bodyweight) => this.setState({bodyweight})}
value={this.state.bodyweight}
/>
<View style={styles.modelBtnWrap}>
<TouchableOpacity style={styles.modelbtn} onPress ={()=>this.closemodel()}><Text style={styles.btntext}>CLOSE</Text></TouchableOpacity>
<TouchableOpacity style={styles.modelbtn}onPress ={()=>this.putUserWeight()}><Text style={styles.btntext}>SUBMIT</Text></TouchableOpacity>
</View>
</View>
</View>
<KeyboardSpacer/>
</Modal>
)
}
closemodel(){
this.setState({
open:false,
enterWeightmodel:false,
text:'',
})
}
EnterWeight(){
this.setState({
enterWeightmodel:true,
})
}
whyIamNotSeeingCaloriePopup(){
AlertIOS.alert(
'No calorie data',
"We couldn't count calories as we didn't have your weight then. But no worries! We will count calories from now on :)",
{text: 'OK', onPress: () => console.log('OK'), style: 'cancel'}
)
}
renderRunsRow(rowData) {
if (rowData) {
if (this.state.weight != null) {
var colorie = (rowData.calories_burnt === null)? <TouchableOpacity onPress={()=> this.whyIamNotSeeingCaloriePopup()}><Text>--</Text></TouchableOpacity>:<Text style={styles.runContentText}>{parseFloat(rowData.calories_burnt).toFixed(1)} cal</Text>;
}else{
var colorie = (rowData.calories_burnt === null)? <TouchableOpacity onPress={()=> this.EnterWeight()}><Text>--</Text></TouchableOpacity>:<Text style={styles.runContentText}>{parseFloat(rowData.calories_burnt).toFixed(1)} cal</Text>;
}
var RunAmount=parseFloat(rowData.run_amount).toFixed(0);
var RunDistance = parseFloat(rowData.distance).toFixed(1);
var RunDate = rowData.start_time;
var day = RunDate.split("-")[2];
var time = rowData.run_duration;
var hours = time.split(":")[0];
var minutes = time.split(":")[1];
var seconds = time.split(":")[2];
var hrsAndMins = (hours != '00')? hours+" hrs "+ minutes+" mins "+ seconds +" sec":(minutes != '00')? minutes+" mins " + seconds+" sec":seconds+" sec";
var monthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var MyRunMonth = monthShortNames[RunDate.split("-")[1][0]+ RunDate.split("-")[1][1]-1];
var day = RunDate.split("-")[2][0]+RunDate.split("-")[2][1]+' '+MyRunMonth+' ' + RunDate.split("-")[0];
var backgroundColor = (rowData.is_flag)?'#f0f0f0':'white';
var textDecoration = (rowData.is_flag)?'line-through':'none';
if (rowData.is_flag) {
return (
<TouchableHighlight onPress={()=> this.onPressFlagedRun(rowData)}underlayColor="#dddddd">
<View style={[styles.container,{backgroundColor:backgroundColor}]}>
<View style={styles.rightContainer}>
<View style={styles.runDetail}>
<View style={styles.cause_run_titleWrap}>
<View>
<Text style={styles.StartTime}>{day}</Text>
<Text style={styles.title}>{rowData.cause_run_title}</Text>
</View>
<Icon style={{color:'grey',fontSize:20,margin:10,marginRight:20,}} name ={'error'}></Icon>
</View>
<View style={{flexDirection:'row',flex:1}}>
<View style={styles.runContent}>
<Text style={[styles.runContentText,{textDecorationLine:textDecoration}]}>{RunDistance} Km</Text>
</View>
<View style={styles.runContent}>
<Text style={[styles.runContentText,{textDecorationLine:textDecoration}]}>{RunAmount} <Icon2 style={{color:styleConfig.greyish_brown_two,fontSize:styleConfig.FontSize3,fontWeight:'400'}}name="inr"></Icon2></Text>
</View>
<View onPress={()=> this.EnterWeight()}style={styles.runContent}>
{colorie}
</View>
<View style={styles.runContent}>
<Text style={[styles.runContentText,{textDecorationLine:textDecoration}]}>{hrsAndMins}</Text>
</View>
</View>
</View>
</View>
</View>
</TouchableHighlight>
);
}else{
return (
<TouchableHighlight underlayColor="#dddddd">
<View style={[styles.container,{backgroundColor:backgroundColor}]}>
<View style={styles.rightContainer}>
<View style={styles.runDetail}>
<View style={styles.cause_run_titleWrap}>
<View>
<Text style={styles.StartTime}>{day}</Text>
<Text style={styles.title}>{rowData.cause_run_title}</Text>
</View>
</View>
<View style={{flexDirection:'row',flex:1}}>
<View style={styles.runContent}>
<Text style={styles.runContentText}>{RunDistance} Km</Text>
</View>
<View style={styles.runContent}>
<Text style={styles.runContentText}>{RunAmount} <Icon2 style={{color:styleConfig.greyish_brown_two,fontSize:styleConfig.FontSize3,fontWeight:'400'}}name="inr"></Icon2> </Text>
</View>
<View onPress={()=> this.EnterWeight()}style={styles.runContent}>
{colorie}
</View>
<View style={styles.runContent}>
<Text style={styles.runContentText}>{hrsAndMins}</Text>
</View>
</View>
</View>
</View>
</View>
</TouchableHighlight>
);
}
};
}
NotLoginView(){
if(this.props.user && Object.keys(this.props.user).length === 0 ){
}else{
return (
<View style={{height:deviceHeight/2,width:deviceWidth,top:(deviceHeight/2)-210,}}>
<LoginBtns getUserData={this.getUserData()}/>
</View>
)
}
}
fetchRunhistoryupdataData(){
var mergerowData = [];
var token = this.props.user.auth_token;
var runversionfetch =this.state.runversion;
var url ='http://dev.impactrun.com/api/runs/'+'?client_version='+runversionfetch;
console.log('mydataurl',url);
fetch(url,{
method: "GET",
headers: {
'Authorization':"Bearer "+ token,
'Content-Type':'application/x-www-form-urlencoded',
}
})
.then( response => response.json() )
.then( jsonData => {
console.log('response: ',jsonData)
if(jsonData.count > 0 ){
var runversion = jsonData.results;
var array = this.props.rawData;
runversion.forEach(function(item) {
console.log("array",array)
objIndex = array.findIndex(obj => obj.start_time == item.start_time);
var arrray1 = array[objIndex] = item;
})
this.rows = array
console.log("runHistoryData",this.rows);
this.setState({
runHistoryData:this.state.runHistoryData.cloneWithRowsAndSections(this.covertmonthArrayToMap(this.rows)),
refreshing:false,
});
let fetchRunhistoryData = this.rows;
AsyncStorage.setItem('fetchRunhistoryData', JSON.stringify(fetchRunhistoryData), () => {
})
// console.log('Rows :' , this.rows);
this.props.getRunCount();
this.props.fetchAmount();
if (jsonData != null || undefined) {
AsyncStorage.removeItem('runversion',(err) => {
});
var newDate = new Date();
var convertepoch = newDate.getTime()/1000
var epochtime = parseFloat(convertepoch).toFixed(0);
let responceversion = epochtime;
AsyncStorage.setItem("runversion",JSON.stringify(responceversion),()=>{
this.setState({
runversion:responceversion
})
});
}
}else{
this.setState({
refreshing:false,
})
}
})
.catch(function(err) {
this.setState({
refreshing:false,
})
console.log('err123',err);
return err;
})
}
nextPage(){
if (this.state.nextPage != null) {
var token = this.props.user.auth_token;
var url = this.state.nextPage;
fetch(url,{
method: "GET",
headers: {
'Authorization':"Bearer "+ token,
'Content-Type':'application/x-www-form-urlencoded',
}
})
.then( response => response.json() )
.then( jsonData => {
this.setState({
rawData: this.state.rawData.concat(jsonData.results),
runHistoryData:this.state.runHistoryData.cloneWithRowsAndSections(this.covertmonthArrayToMap(this.state.rawData.concat(jsonData.results))),
loaded: true,
refreshing:false,
nextPage:jsonData.next,
loadingFirst:true,
RunCount:jsonData.count,
});
AsyncStorage.removeItem('runversion',(err) => {
});
var newDate = new Date();
var convertepoch = newDate.getTime()/1000
var epochtime = parseFloat(convertepoch).toFixed(0);
let responceversion = epochtime;
AsyncStorage.setItem("runversion",JSON.stringify(responceversion),()=>{
this.setState({
runversion:responceversion
})
});
let RunCount = this.state.RunCount;
AsyncStorage.setItem('RunCount', JSON.stringify(RunCount));
AsyncStorage.removeItem('fetchRunhistoryData',(err) => {
});
AsyncStorage.removeItem('nextpage',(err) => {
});
let nextpage = this.state.nextPage;
AsyncStorage.setItem('nextpage', JSON.stringify(nextpage));
let fetchRunhistoryData = this.state.rawData.concat();
AsyncStorage.setItem('fetchRunhistoryData', JSON.stringify(fetchRunhistoryData), () => {
})
this.LoadmoreView();
})
.catch( error => console.log('Error fetching: ' + error) );
}else{
this.setState({
loadingFirst:false,
})
this.props.getRunCount();
this.props.fetchAmount();
}
}
covertmonthArrayToMap(rowData) {
if (rowData) {
let _this = this;
var rundateCategory = {}; // Create the blank map
var rows = rowData;
rows.forEach(function(runItem) {
var RunDate = runItem.start_time;
var monthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var MyRunMonth = monthShortNames[RunDate.split("-")[1][0]+ RunDate.split("-")[1][1]-1];
var day = RunDate.split("-")[2][0]+RunDate.split("-")[2][1]+' '+MyRunMonth+' ' + RunDate.split("-")[0];
if (!rundateCategory[day]) {
// Create an entry in the map for the category if it hasn't yet been created
rundateCategory[day] = [];
}
rundateCategory[day].push(runItem);
});
return rundateCategory;
}else{
return this.covertmonthArrayToMap();
}
}
_onRefresh() {
this.setState({refreshing: true});
this.fetchRunhistoryupdataData();
}
LoadmoreView(){
this.nextPage();
}
goBack(){
this.props.navigator.pop({});
}
render(rowData) {
var fetchingRun = this.props.fetchRunData;
var user = this.props.user || 0;
if (Object.keys(user).length) {
return (
<View>
<View style={commonStyles.Navbar}>
<TouchableOpacity style={{left:0,position:'absolute',height:60,width:60,backgroundColor:'transparent',justifyContent: 'center',alignItems: 'center',}} onPress={()=>this.goBack()} >
<Icon3 style={{color:'white',fontSize:30,fontWeight:'bold'}}name={(this.props.data === 'fromshare')?'md-home':'ios-arrow-back'}></Icon3>
</TouchableOpacity>
<Text numberOfLines={1} style={commonStyles.menuTitle}>{'Run History'}</Text>
</View>
<View style={{height:deviceHeight}}>
<ListView
renderSectionHeader={this.renderSectionHeader}
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this._onRefresh.bind(this)}
/>}
style={styles.listView}
dataSource={this.state.runHistoryData}
renderRow={this.renderRunsRow}/>
{this.runLodingFirstTime()}
{this.modelView()}
{this.modelViewEnterWeight()}
</View>
</View>
)
}else {
return (
<View style={{paddingTop:10,width:deviceWidth,justifyContent: 'center',alignItems: 'center',}}>
{this.NotLoginView()}
</View>
)
};
}
runLodingFirstTime(){
if (this.state.loadingFirst) {
return(
<View style={styles.RunlodingFirstTimeView}>
<ActivityIndicatorIOS color={'white'} size="small" ></ActivityIndicatorIOS>
<Text style={styles.btntext} >Loading all runs ...</Text>
</View>
)
}else{
return;
}
}
};
const styles = StyleSheet.create({
modelStyle:{
height:deviceHeight,
justifyContent: 'center',
alignItems: 'center',
},
RunlodingFirstTimeView:{
justifyContent: 'center',
alignItems: 'center',
width:deviceWidth,
height:60,
top:-50,
backgroundColor:styleConfig.bright_blue,
},
modelBtnWrap:{
width:deviceWidth-100,
flexDirection:'row',
justifyContent: 'space-between',
},
modelbtn:{
marginTop:(deviceHeight/10)-50,
padding:8,
width:((deviceWidth-120)/2)-10,
alignItems: 'center',
borderRadius:5,
backgroundColor:styleConfig.bright_blue,
},
btntext:{
color:'white',
fontFamily: styleConfig.FontFamily,
},
modelWrap:{
top:-100,
borderRadius:5,
padding:10,
justifyContent: 'center',
alignItems: 'center',
backgroundColor:'white',
width:deviceWidth-50,
},
container: {
width:deviceWidth-10,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
padding:10,
borderRadius:5,
paddingTop:0,
paddingBottom:0,
borderBottomWidth:1,
marginBottom:5,
marginLeft:5,
borderColor:'#e1e1e8',
shadowColor: '#000000',
shadowOpacity: 0.2,
shadowRadius: 4,
shadowOffset: {
height: 3,
},
},
rightContainer: {
flex: 1,
},
morebtn:{
width:deviceWidth,
position:'absolute',
bottom:50,
height:30,
justifyContent: 'center',
alignItems: 'center',
backgroundColor:styleConfig.bright_blue,
},
Moretxt:{
color:'white',
fontFamily:styleConfig.FontFamily,
},
title: {
fontSize: 16,
marginLeft:3,
color:styleConfig.greyish_brown_two,
fontWeight:'400',
backgroundColor:'transparent',
fontFamily: styleConfig.FontFamily,
},
StartTime: {
fontSize: 14,
marginLeft:4,
color:styleConfig.brownish_grey,
fontWeight:'400',
backgroundColor:'transparent',
fontFamily: styleConfig.FontFamily,
},
runDetail:{
flexDirection: 'column',
width:deviceWidth-10,
padding:5,
paddingRight:0
},
runContent: {
flex:1,
justifyContent: 'center',
alignItems: 'flex-start',
padding:5,
},
runContentText: {
color:styleConfig.greyish_brown_two,
fontWeight:'500',
fontSize:16,
left:-1,
fontFamily:styleConfig.FontFamily,
},
thumbnail: {
width: 53,
height: 81,
},
listView: {
backgroundColor: 'white',
},
ListViewPage:{
paddingTop:5,
justifyContent: 'center',
alignItems: 'center',
flex:1,
},
cause_run_titleWrap:{
justifyContent:'space-between',
flexDirection:'row',
flex:2,
},
});
export default RunHistory; |
app/src/Frontend/modules/weui/pages/button/index.js | ptphp/ptphp | /**
* Created by jf on 15/12/10.
*/
"use strict";
import React from 'react';
import {Button} from '../../../../index';
import Page from '../../component/page';
import './button.less';
export default class ButtonDemo extends React.Component {
render() {
return (
<Page className="button" title="Button" spacing>
<Button>按钮1</Button>
<Button disabled>按钮</Button>
<Button type="warn">按钮</Button>
<Button type="warn" disabled>按钮</Button>
<Button type="default">按钮</Button>
<Button type="default" disabled>按钮</Button>
<div className="button_sp_area">
<Button type="primary" plain>按钮</Button>
<Button type="default" plain>按钮</Button>
<Button size="small">按钮</Button>
<Button type="default" size="small">按钮</Button>
</div>
</Page>
);
}
}; |
src/svg-icons/image/photo-camera.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImagePhotoCamera = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="12" r="3.2"/><path d="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/>
</SvgIcon>
);
ImagePhotoCamera = pure(ImagePhotoCamera);
ImagePhotoCamera.displayName = 'ImagePhotoCamera';
ImagePhotoCamera.muiName = 'SvgIcon';
export default ImagePhotoCamera;
|
src/app/about/aboutPage.js | sonnylazuardi/natal-ppl-app | import React from 'react';
import RaisedButton from 'material-ui/lib/raised-button';
import Router from 'react-router';
import Header from '../header';
class About extends React.Component {
handleTransition () {
this.context.router.transitionTo('instagram');
}
handleAbout () {
// window.open('http://sonnylab.com', '_blank');
navigator.app.loadUrl('http://sonnylab.com/', { openExternal:true });
}
render () {
return (
<div>
<Header back={true}/>
<div className="page">
<div className="padding">
<h1>
Natal PPL App
</h1>
<p>
Natal GBI PPL 2015
</p>
<RaisedButton label="@sonnylazuardi" linkButton={true} labelStyle={{textTransform: 'inherit'}} onClick={this.handleAbout.bind(this)} />
</div>
</div>
</div>
);
}
};
About.contextTypes = {
router: React.PropTypes.func,
};
module.exports = About; |
client/src/components/GalleryItem/GalleryItem.js | open-sausages/silverstripe-asset-admin | import i18n from 'i18n';
import React, { Component } from 'react';
import classnames from 'classnames';
import CONSTANTS from 'constants/index';
import fileShape from 'lib/fileShape';
import draggable from 'components/GalleryItem/draggable';
import droppable from 'components/GalleryItem/droppable';
import Badge from 'components/Badge/Badge';
import configShape from 'lib/configShape';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { createSelectable } from 'react-selectable';
import * as imageLoadActions from 'state/imageLoad/ImageLoadActions';
import IMAGE_STATUS from 'state/imageLoad/ImageLoadStatus';
import PropTypes from 'prop-types';
/**
* Determine if image loading should be performed
*
* @param {Object} props - Props to inspect
*/
function shouldLoadImage(props) {
return props.item.thumbnail
&& props.item.category === 'image'
&& props.item.exists
// Don't load images for uploaded images (retain client thumbnail)
&& !props.item.queuedId
&& props.sectionConfig.imageRetry.minRetry
&& props.sectionConfig.imageRetry.maxRetry;
}
/**
* Avoids the browser's default focus state when selecting an item.
*
* @param {Object} event Event object.
*/
const preventFocus = (event) => {
event.preventDefault();
};
class GalleryItem extends Component {
constructor(props) {
super(props);
this.handleSelect = this.handleSelect.bind(this);
this.handleActivate = this.handleActivate.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.handleCancelUpload = this.handleCancelUpload.bind(this);
}
componentWillReceiveProps(nextProps) {
if (shouldLoadImage(nextProps)) {
// Tell backend to start loading the image
nextProps.actions.imageLoad.loadImage(
nextProps.item.thumbnail,
nextProps.sectionConfig.imageRetry
);
}
}
/**
* Gets props for thumbnail
*
* @returns {Object}
*/
getThumbnailStyles() {
// Don't fall back to this.props.item.url since it might be huge
const thumbnail = this.props.item.thumbnail;
if (!this.isImage() || !thumbnail || this.missing()) {
return {};
}
// Check loading status of thumbnail
switch (this.props.loadState) {
// Use thumbnail if successfully loaded, or preloading isn't enabled
case IMAGE_STATUS.SUCCESS:
case IMAGE_STATUS.DISABLED:
return {
backgroundImage: `url(${thumbnail})`,
};
default:
return {};
}
}
/**
* Returns markup for an error message if one is set.
*
* @returns {Object}
*/
getErrorMessage() {
let message = null;
const { item, loadState } = this.props;
if (this.hasError()) {
message = item.message.value;
} else if (this.missing()) {
message = i18n._t('AssetAdmin.FILE_MISSING', 'File cannot be found');
} else if (loadState === IMAGE_STATUS.FAILED) {
message = i18n._t('AssetAdmin.FILE_LOAD_ERROR', 'Thumbnail not available');
}
if (message !== null) {
const updateErrorMessage = this.getItemFunction('updateErrorMessage');
message = updateErrorMessage(message, this.props);
return (
<span className="gallery-item__error-message">
{message}
</span>
);
}
return null;
}
/**
* Retrieve list of thumbnail classes
*
* @returns {string}
*/
getThumbnailClassNames() {
const thumbnailClassNames = ['gallery-item__thumbnail'];
if (this.isImageSmallerThanThumbnail()) {
thumbnailClassNames.push('gallery-item__thumbnail--small');
}
if (!this.props.item.thumbnail && this.isImage()) {
thumbnailClassNames.push('gallery-item__thumbnail--no-preview');
}
// Check loading status of thumbnail
switch (this.props.loadState) {
// Show loading indicator for preloading images
case IMAGE_STATUS.LOADING: // Beginning first load
case IMAGE_STATUS.WAITING: // Waiting for subsequent load to retry
thumbnailClassNames.push('gallery-item__thumbnail--loading');
break;
// Show error styles if failed to load thumbnail
case IMAGE_STATUS.FAILED:
thumbnailClassNames.push('gallery-item__thumbnail--error');
break;
default:
break;
}
return thumbnailClassNames.join(' ');
}
/**
* Retrieves class names for the item
*
* @returns {string}
*/
getItemClassNames() {
const category = this.props.item.category || 'false';
const selected = this.props.selectable && (this.props.item.selected || this.props.isDragging);
return classnames({
'gallery-item': true,
[`gallery-item--${category}`]: true,
'gallery-item--max-selected': this.props.maxSelected && !selected,
'gallery-item--missing': this.missing(),
'gallery-item--selectable': this.props.selectable,
'gallery-item--selected': selected,
'gallery-item--dropping': this.props.isDropping,
'gallery-item--highlighted': this.props.item.highlighted,
'gallery-item--error': this.hasError(),
'gallery-item--dragging': this.props.isDragging,
});
}
/**
* Gets a function that may be overloaded at the item level
* @param {string} functionName
* @returns {Function}
*/
getItemFunction(functionName) {
const { item } = this.props;
return (typeof item[functionName] === 'function')
? item[functionName]
: this.props[functionName];
}
/**
* Get flags for statuses that apply to this item
*
* @returns {Array}
*/
getStatusFlags() {
let flags = [];
const { item } = this.props;
if (item.type !== 'folder') {
if (item.draft) {
flags.push({
node: 'span',
key: 'status-draft',
title: i18n._t('File.DRAFT', 'Draft'),
className: 'gallery-item--draft',
});
} else if (item.modified) {
flags.push({
node: 'span',
key: 'status-modified',
title: i18n._t('File.MODIFIED', 'Modified'),
className: 'gallery-item--modified',
});
}
}
const updateStatusFlags = this.getItemFunction('updateStatusFlags');
flags = updateStatusFlags(flags, this.props);
return flags.map(({ node: Tag, ...attributes }) => <Tag {...attributes} />);
}
/**
* Gets upload progress bar
*
* @returns {Object}
*/
getProgressBar() {
let progressBar = null;
const { item } = this.props;
const progressBarProps = {
className: 'gallery-item__progress-bar',
style: {
width: `${item.progress}%`,
},
};
if (!this.hasError() && this.uploading() && !this.complete()) {
progressBar = (
<div className="gallery-item__upload-progress">
<div {...progressBarProps} />
</div>
);
}
const updateProgressBar = this.getItemFunction('updateProgressBar');
progressBar = updateProgressBar(progressBar, this.props);
return progressBar;
}
/**
* Determine that this record is an image, and the thumbnail is smaller than the given
* thumbnail area
*
* @returns {boolean}
*/
isImageSmallerThanThumbnail() {
if (!this.isImage() || this.missing()) {
return false;
}
const width = this.props.item.width;
const height = this.props.item.height;
// Note: dimensions will be null if the back-end image is lost
return (
height
&& width
&& height < CONSTANTS.THUMBNAIL_HEIGHT
&& width < CONSTANTS.THUMBNAIL_WIDTH
);
}
/**
* Check if this item has been successfully uploaded.
* Excludes items not uploaded in this request.
*
* @returns {Boolean}
*/
complete() {
// Uploading is complete if saved with a DB id
return this.props.item.queuedId && this.saved();
}
/**
* Check if this item has been saved, either in this request or in a prior one
*
* @return {Boolean}
*/
saved() {
return this.props.item.id > 0;
}
/**
* Check if this item should have a file, but is missing.
*
* @return {Boolean}
*/
missing() {
return !this.exists() && this.saved();
}
/**
* Validate that the file is in upload progress, but not saved yet
*
* @returns {boolean}
*/
uploading() {
return this.props.item.queuedId && !this.saved();
}
/**
* Validate that the file backing this record is not missing
*
* @returns {boolean}
*/
exists() {
return this.props.item.exists;
}
/**
* Determine if this is an image type
*
* @returns {boolean}
*/
isImage() {
return this.props.item.category === 'image';
}
/**
* Determine if the item has enabled checkbox
*
* @return {Boolean}
*/
canBatchSelect() {
return this.props.selectable && this.props.item.canEdit;
}
/**
* Checks if the component has an error set.
*
* @return {boolean}
*/
hasError() {
let hasError = false;
if (this.props.item.message) {
hasError = this.props.item.message.type === 'error';
}
return hasError;
}
/**
* Wrapper around this.props.onActivate
*
* @param {Object} event - Event object.
*/
handleActivate(event) {
event.stopPropagation();
if (typeof this.props.onActivate === 'function' && this.saved()) {
this.props.onActivate(event, this.props.item);
}
}
/**
* Wrapper around this.props.onSelect
*
* @param {Object} event Event object.
*/
handleSelect(event) {
event.stopPropagation();
event.preventDefault();
if (typeof this.props.onSelect === 'function') {
this.props.onSelect(event, this.props.item);
}
}
/**
* To capture keyboard actions, such as selecting or activating an item
*
* @param {Object} event
*/
handleKeyDown(event) {
// If space is pressed, select file
if (CONSTANTS.SPACE_KEY_CODE === event.keyCode) {
event.preventDefault(); // Stop page scrolling if spaceKey is pressed
if (this.canBatchSelect()) {
this.handleSelect(event);
}
}
// If return is pressed, navigate folder
if (CONSTANTS.RETURN_KEY_CODE === event.keyCode) {
this.handleActivate(event);
}
}
/**
* Callback for cancelling or removing (if failed) this item when it's still uploading.
*
* @param event
*/
handleCancelUpload(event) {
event.stopPropagation();
event.preventDefault();
if (this.hasError()) {
this.props.onRemoveErroredUpload(this.props.item);
} else if (this.props.onCancelUpload) {
this.props.onCancelUpload(this.props.item);
}
}
render() {
let action = null;
let actionIcon = null;
let overlay = null;
const { id, queuedId } = this.props.item;
const htmlID = id ? `item-${id}` : `queued-${queuedId}`;
if (this.props.selectable) {
if (this.canBatchSelect()) {
action = this.handleSelect;
}
actionIcon = 'font-icon-tick';
}
if (this.uploading()) {
action = this.handleCancelUpload;
actionIcon = 'font-icon-cancel';
} else if (this.exists()) {
const label = i18n._t('AssetAdmin.DETAILS', 'Details');
overlay = <div className="gallery-item--overlay font-icon-edit">{label}</div>;
}
const badge = this.props.badge;
const inputProps = {
className: 'gallery-item__checkbox',
type: 'checkbox',
title: i18n._t('AssetAdmin.SELECT', 'Select'),
tabIndex: -1,
onMouseDown: preventFocus,
id: htmlID,
};
const inputLabelClasses = [
'gallery-item__checkbox-label',
actionIcon,
];
if (!this.canBatchSelect()) {
inputProps.disabled = true;
inputLabelClasses.push('gallery-item__checkbox-label--disabled');
}
const inputLabelProps = {
className: inputLabelClasses.join(' '),
onClick: action,
};
return (
<div
className={this.getItemClassNames()}
data-id={this.props.item.id}
tabIndex={0}
role="button"
onKeyDown={this.handleKeyDown}
onClick={this.handleActivate}
>
{!!badge &&
<Badge
className="gallery-item__badge"
status={badge.status}
message={badge.message}
/>
}
<div
ref={(thumbnail) => { this.thumbnail = thumbnail; }}
className={this.getThumbnailClassNames()}
style={this.getThumbnailStyles()}
>
{overlay}
{this.getStatusFlags()}
</div>
{this.getProgressBar()}
{this.getErrorMessage()}
{this.props.children}
<div className="gallery-item__title" ref={(title) => { this.title = title; }}>
<label {...inputLabelProps} htmlFor={htmlID}>
<input {...inputProps} />
</label>
{this.props.item.title}
</div>
</div>
);
}
}
GalleryItem.propTypes = {
sectionConfig: configShape,
item: fileShape,
loadState: PropTypes.oneOf(Object.values(IMAGE_STATUS)),
// Can be used to highlight a currently edited file
highlighted: PropTypes.bool,
// Styles according to the checkbox selection state
selected: PropTypes.bool,
// Whether the item should be enlarged for more prominence than "highlighted"
isDropping: PropTypes.bool,
isDragging: PropTypes.bool,
message: PropTypes.shape({
value: PropTypes.string,
type: PropTypes.string,
}),
selectable: PropTypes.bool,
onActivate: PropTypes.func,
onSelect: PropTypes.func,
onCancelUpload: PropTypes.func,
onRemoveErroredUpload: PropTypes.func,
badge: PropTypes.shape({
status: PropTypes.string,
message: PropTypes.string,
}),
updateStatusFlags: PropTypes.func,
updateProgressBar: PropTypes.func,
updateErrorMessage: PropTypes.func,
};
GalleryItem.defaultProps = {
item: {},
sectionConfig: {
imageRetry: {},
},
updateStatusFlags: flags => flags,
updateProgressBar: progressBar => progressBar,
updateErrorMessage: message => message,
};
function mapStateToProps(state, ownprops) {
// If image is broken, replace with placeholder
if (shouldLoadImage(ownprops)) {
// Find state of this file
const imageLoad = state.assetAdmin.imageLoad;
const file = imageLoad.files.find((next) => ownprops.item.thumbnail === next.url);
// Use file state, or mark none prior to loadFile being called
const loadState = (file && file.status) || IMAGE_STATUS.NONE;
return { loadState };
}
// None implies disabled preloading
return { loadState: IMAGE_STATUS.DISABLED };
}
function mapDispatchToProps(dispatch) {
return {
actions: {
imageLoad: bindActionCreators(imageLoadActions, dispatch),
},
};
}
const ConnectedGalleryItem = connect(mapStateToProps, mapDispatchToProps)(GalleryItem);
const type = 'GalleryItem';
const File = createSelectable(draggable(type)(ConnectedGalleryItem));
const Folder = createSelectable(droppable(type)(File));
export {
GalleryItem as Component,
Folder,
File,
};
export default ConnectedGalleryItem;
|
src/utils/ValidComponentChildren.js | PeterDaveHello/react-bootstrap | import React from 'react';
/**
* Maps children that are typically specified as `props.children`,
* but only iterates over children that are "valid components".
*
* The mapFunction provided index will be normalised to the components mapped,
* so an invalid component would not increase the index.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} mapFunction.
* @param {*} mapContext Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapValidComponents(children, func, context) {
let index = 0;
return React.Children.map(children, function (child) {
if (React.isValidElement(child)) {
let lastIndex = index;
index++;
return func.call(context, child, lastIndex);
}
return child;
});
}
/**
* Iterates through children that are typically specified as `props.children`,
* but only iterates over children that are "valid components".
*
* The provided forEachFunc(child, index) will be called for each
* leaf child with the index reflecting the position relative to "valid components".
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc.
* @param {*} forEachContext Context for forEachContext.
*/
function forEachValidComponents(children, func, context) {
let index = 0;
return React.Children.forEach(children, function (child) {
if (React.isValidElement(child)) {
func.call(context, child, index);
index++;
}
});
}
/**
* Count the number of "valid components" in the Children container.
*
* @param {?*} children Children tree container.
* @returns {number}
*/
function numberOfValidComponents(children) {
let count = 0;
React.Children.forEach(children, function (child) {
if (React.isValidElement(child)) { count++; }
});
return count;
}
/**
* Determine if the Child container has one or more "valid components".
*
* @param {?*} children Children tree container.
* @returns {boolean}
*/
function hasValidComponent(children) {
let hasValid = false;
React.Children.forEach(children, function (child) {
if (!hasValid && React.isValidElement(child)) {
hasValid = true;
}
});
return hasValid;
}
export default {
map: mapValidComponents,
forEach: forEachValidComponents,
numberOf: numberOfValidComponents,
hasValidComponent
};
|
src/components/courses/CourseContainer.js | kipp0/course_directory | import React from 'react';
import Course from './Course';
const CourseContainer = ({data}) => {
let courses = data.map((course) => {
return <Course title={course.title}
desc={course.description}
img={course.img_src}
key={course.id} />
});
return (
<div>
<ul>
{courses}
</ul>
</div>
);
}
export default CourseContainer;
|
src/components/Grid.js | alanrsoares/redux-game-of-life | import React from 'react'
import PropTypes from 'prop-types'
import Tile from './Tile'
const renderTile = (toggle, y) => (alive, x) => (
<Tile
key={x}
alive={alive}
toggle={(alive) => toggle({
coordinates: { y, x },
current: alive
})}
/>
)
const renderRow = (toggle) => (row, y) => (
<div className='grid-row' key={y}>
{row.map(renderTile(toggle, y))}
</div>
)
const Grid = ({ data, toggle }) => (
<div className='grid'>
{data.map(renderRow(toggle))}
</div>
)
export const GridShape = PropTypes.arrayOf(
PropTypes.arrayOf(PropTypes.bool)
)
Grid.propTypes = {
data: GridShape.isRequired,
toggle: PropTypes.func.isRequired
}
export default Grid
|
src_back/index.js | noframes/react-youtube-search | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import App from './components/app';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware()(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.querySelector('.container'));
|
admin/client/App/screens/Item/components/RelatedItemsList/RelatedItemsList.js | brianjd/keystone | import React from 'react';
import { Link } from 'react-router';
import { Alert, BlankState, Center, Spinner } from '../../../../elemental';
import DragDrop from './RelatedItemsListDragDrop';
import ListRow from './RelatedItemsListRow';
import { loadRelationshipItemData } from '../../actions';
import { TABLE_CONTROL_COLUMN_WIDTH } from '../../../../../constants';
const RelatedItemsList = React.createClass({
propTypes: {
dispatch: React.PropTypes.func.isRequired,
dragNewSortOrder: React.PropTypes.number,
items: React.PropTypes.array,
list: React.PropTypes.object.isRequired,
refList: React.PropTypes.object.isRequired,
relatedItemId: React.PropTypes.string.isRequired,
relationship: React.PropTypes.object.isRequired,
},
getInitialState () {
return {
columns: this.getColumns(),
err: null,
items: null,
};
},
componentDidMount () {
this.__isMounted = true;
this.loadItems();
},
componentWillUnmount () {
this.__isMounted = false;
},
isSortable () {
// Check if the related items should be sortable. The referenced list has to
// be sortable and it has to set the current list as it's sortContext.
const { refList, list, relationship } = this.props;
const sortContext = refList.sortContext;
if (refList.sortable && sortContext) {
const parts = sortContext.split(':');
if (parts[0] === list.key && parts[1] === relationship.path) {
return true;
}
}
return false;
},
getColumns () {
const { relationship, refList } = this.props;
const columns = refList.expandColumns(refList.defaultColumns);
return columns.filter(i => i.path !== relationship.refPath);
},
loadItems () {
const { refList, relatedItemId, relationship } = this.props;
const { columns } = this.state;
// TODO: Move error to redux store
if (!refList.fields[relationship.refPath]) {
const err = (
<Alert color="danger">
<strong>Error:</strong> Related List <strong>{refList.label}</strong> has no field <strong>{relationship.refPath}</strong>
</Alert>
);
return this.setState({ err });
}
this.props.dispatch(loadRelationshipItemData({ columns, refList, relatedItemId, relationship }));
},
renderItems () {
const tableBody = (this.isSortable()) ? (
<DragDrop
columns={this.state.columns}
items={this.props.items}
{...this.props}
/>
) : (
<tbody>
{this.props.items.results.map((item) => {
return (<ListRow
key={item.id}
columns={this.state.columns}
item={item}
refList={this.props.refList}
/>);
})}
</tbody>
);
return this.props.items.results.length ? (
<div className="ItemList-wrapper">
<table cellPadding="0" cellSpacing="0" className="Table ItemList">
{this.renderTableCols()}
{this.renderTableHeaders()}
{tableBody}
</table>
</div>
) : (
<BlankState
heading={`No related ${this.props.refList.plural.toLowerCase()}...`}
style={{ marginBottom: '3em' }}
/>
);
},
renderTableCols () {
const cols = this.state.columns.map((col) => <col width={col.width} key={col.path} />);
return <colgroup>{cols}</colgroup>;
},
renderTableHeaders () {
const cells = this.state.columns.map((col) => {
return <th key={col.path}>{col.label}</th>;
});
// add sort col when available
if (this.isSortable()) {
cells.unshift(
<th width={TABLE_CONTROL_COLUMN_WIDTH} key="sortable" />
);
}
return <thead><tr>{cells}</tr></thead>;
},
render () {
if (this.state.err) {
return <div className="Relationship">{this.state.err}</div>;
}
const listHref = `${Keystone.adminPath}/${this.props.refList.path}`;
const loadingElement = (
<Center height={100}>
<Spinner />
</Center>
);
return (
<div className="Relationship">
<h3 className="Relationship__link"><Link to={listHref}>{this.props.refList.label}</Link></h3>
{this.props.items ? this.renderItems() : loadingElement}
</div>
);
},
});
module.exports = RelatedItemsList;
|
src/components/ReplEntry.js | princejwesley/Mancy | import React from 'react';
import ReplEntryIcon from './ReplEntryIcon';
import ReplEntryMessage from './ReplEntryMessage';
import ReplEntryStatus from './ReplEntryStatus';
import ReplActions from '../actions/ReplActions';
import ReplNotebook from './ReplNotebook';
import _ from 'lodash';
export default class ReplEntry extends React.Component {
constructor(props) {
super(props);
_.each([
'onToggle', 'onReload',
'onCommandCollapse', 'onRemove',
], (field) => {
this[field] = this[field].bind(this);
});
}
onToggle() {
ReplActions.toggleEntryView(this.props.index);
}
onReload() {
ReplActions.reloadPromptByIndex(this.props.index);
}
onRemove() {
ReplActions.removeEntry(this.props.index, this.props.log);
}
onCommandCollapse() {
ReplActions.toggleCommandEntryView(this.props.index);
}
renderNotebook() {
return (
<div className='repl-entry repl-notebook'>
<ReplNotebook message={this.props.log} index={this.props.index}/>
</div>
);
}
renderREPL() {
return (
<div className='repl-entry'>
<ReplEntryIcon collapse={this.props.log.commandCollapsed}
onCollapse={this.onCommandCollapse}/>
<ReplEntryMessage message={this.props.log} collapse={this.props.log.collapsed}
commandCollapse={this.props.log.commandCollapsed}/>
<ReplEntryStatus message={this.props.log} collapse={this.props.log.collapsed}
onReload={this.onReload}
onRemove={this.onRemove}
onToggle={this.onToggle}/>
</div>
);
}
render() {
return global.Mancy.preferences.editor === 'REPL' ? this.renderREPL() : this.renderNotebook();
}
}
|
app/javascript/mastodon/features/following/index.js | mstdn-jp/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import LoadingIndicator from '../../components/loading_indicator';
import {
fetchAccount,
fetchFollowing,
expandFollowing,
} from '../../actions/accounts';
import { ScrollContainer } from 'react-router-scroll-4';
import AccountContainer from '../../containers/account_container';
import Column from '../ui/components/column';
import HeaderContainer from '../account_timeline/containers/header_container';
import LoadMore from '../../components/load_more';
import ColumnBackButton from '../../components/column_back_button';
import ImmutablePureComponent from 'react-immutable-pure-component';
const mapStateToProps = (state, props) => ({
accountIds: state.getIn(['user_lists', 'following', props.params.accountId, 'items']),
hasMore: !!state.getIn(['user_lists', 'following', props.params.accountId, 'next']),
});
@connect(mapStateToProps)
export default class Following extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
accountIds: ImmutablePropTypes.list,
hasMore: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchAccount(this.props.params.accountId));
this.props.dispatch(fetchFollowing(this.props.params.accountId));
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) {
this.props.dispatch(fetchAccount(nextProps.params.accountId));
this.props.dispatch(fetchFollowing(nextProps.params.accountId));
}
}
handleScroll = (e) => {
const { scrollTop, scrollHeight, clientHeight } = e.target;
if (scrollTop === scrollHeight - clientHeight && this.props.hasMore) {
this.props.dispatch(expandFollowing(this.props.params.accountId));
}
}
handleLoadMore = (e) => {
e.preventDefault();
this.props.dispatch(expandFollowing(this.props.params.accountId));
}
render () {
const { accountIds, hasMore } = this.props;
let loadMore = null;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
if (hasMore) {
loadMore = <LoadMore onClick={this.handleLoadMore} />;
}
return (
<Column>
<ColumnBackButton />
<ScrollContainer scrollKey='following'>
<div className='scrollable' onScroll={this.handleScroll}>
<div className='following'>
<HeaderContainer accountId={this.props.params.accountId} hideTabs />
{accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)}
{loadMore}
</div>
</div>
</ScrollContainer>
</Column>
);
}
}
|
app/components/List/index.js | jdm85kor/sentbe | import React from 'react';
import Ul from './Ul';
import Wrapper from './Wrapper';
function List(props) {
const ComponentToRender = props.component;
let content = (<div></div>);
// If we have items, render them
if (props.items) {
content = props.items.map((item, index) => (
<ComponentToRender key={`item-${index}`} item={item} />
));
} else {
// Otherwise render a single component
content = (<ComponentToRender />);
}
return (
<Wrapper>
<Ul>
{content}
</Ul>
</Wrapper>
);
}
List.propTypes = {
component: React.PropTypes.func.isRequired,
items: React.PropTypes.array,
};
export default List;
|
react-flux-mui/js/material-ui/docs/src/app/components/pages/components/GridList/ExampleSingleLine.js | pbogdan/react-flux-mui | import React from 'react';
import {GridList, GridTile} from 'material-ui/GridList';
import IconButton from 'material-ui/IconButton';
import StarBorder from 'material-ui/svg-icons/toggle/star-border';
const styles = {
root: {
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-around',
},
gridList: {
display: 'flex',
flexWrap: 'nowrap',
overflowX: 'auto',
},
titleStyle: {
color: 'rgb(0, 188, 212)',
},
};
const tilesData = [
{
img: 'images/grid-list/00-52-29-429_640.jpg',
title: 'Breakfast',
author: 'jill111',
},
{
img: 'images/grid-list/burger-827309_640.jpg',
title: 'Tasty burger',
author: 'pashminu',
},
{
img: 'images/grid-list/camera-813814_640.jpg',
title: 'Camera',
author: 'Danson67',
},
{
img: 'images/grid-list/morning-819362_640.jpg',
title: 'Morning',
author: 'fancycrave1',
},
{
img: 'images/grid-list/hats-829509_640.jpg',
title: 'Hats',
author: 'Hans',
},
{
img: 'images/grid-list/honey-823614_640.jpg',
title: 'Honey',
author: 'fancycravel',
},
{
img: 'images/grid-list/vegetables-790022_640.jpg',
title: 'Vegetables',
author: 'jill111',
},
{
img: 'images/grid-list/water-plant-821293_640.jpg',
title: 'Water plant',
author: 'BkrmadtyaKarki',
},
];
/**
* This example demonstrates the horizontal scrollable single-line grid list of images.
*/
const GridListExampleSingleLine = () => (
<div style={styles.root}>
<GridList style={styles.gridList} cols={2.2}>
{tilesData.map((tile) => (
<GridTile
key={tile.img}
title={tile.title}
actionIcon={<IconButton><StarBorder color="rgb(0, 188, 212)" /></IconButton>}
titleStyle={styles.titleStyle}
titleBackground="linear-gradient(to top, rgba(0,0,0,0.7) 0%,rgba(0,0,0,0.3) 70%,rgba(0,0,0,0) 100%)"
>
<img src={tile.img} />
</GridTile>
))}
</GridList>
</div>
);
export default GridListExampleSingleLine;
|
src/components/DataTable/AnimTableBody.js | terryli1643/thinkmore | import React from 'react'
import PropTypes from 'prop-types'
import { TweenOneGroup } from 'rc-tween-one'
const enterAnim = [
{
opacity: 0,
x: 30,
backgroundColor: '#fffeee',
duration: 0,
}, {
height: 0,
duration: 200,
type: 'from',
delay: 250,
ease: 'easeOutQuad',
onComplete: (e) => {
e.target.style.height = 'auto'
},
}, {
opacity: 1,
x: 0,
duration: 250,
ease: 'easeOutQuad',
}, {
delay: 1000,
backgroundColor: '#fff',
},
]
const leaveAnim = [
{
duration: 250,
x: -30,
opacity: 0,
}, {
height: 0,
duration: 200,
ease: 'easeOutQuad',
},
]
const AnimTableBody = ({ body, page = 1, current }) => {
if (current !== +page) {
return body
}
return (
<TweenOneGroup
component="tbody"
className={body.props.className}
enter={enterAnim}
leave={leaveAnim}
appear={false}
>
{body.props.children}
</TweenOneGroup>
)
}
AnimTableBody.propTypes = {
body: PropTypes.element,
page: PropTypes.any,
current: PropTypes.number.isRequired,
}
export default AnimTableBody
|
src/svg-icons/image/crop-portrait.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCropPortrait = (props) => (
<SvgIcon {...props}>
<path d="M17 3H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H7V5h10v14z"/>
</SvgIcon>
);
ImageCropPortrait = pure(ImageCropPortrait);
ImageCropPortrait.displayName = 'ImageCropPortrait';
ImageCropPortrait.muiName = 'SvgIcon';
export default ImageCropPortrait;
|
geonode/contrib/monitoring/frontend/src/components/cels/alerts/index.js | simod/geonode | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import HoverPaper from '../../atoms/hover-paper';
import actions from '../../organisms/alert-list/actions';
import styles from './styles';
const mapStateToProps = (state) => ({
alertList: state.alertList.response,
interval: state.interval.interval,
timestamp: state.interval.timestamp,
});
@connect(mapStateToProps, actions)
class Alerts extends React.Component {
static propTypes = {
alertList: PropTypes.object,
get: PropTypes.func.isRequired,
interval: PropTypes.number,
style: PropTypes.object,
timestamp: PropTypes.instanceOf(Date),
}
static contextTypes = {
router: PropTypes.object.isRequired,
}
constructor(props) {
super(props);
this.handleClick = () => {
this.context.router.push('/alerts');
};
this.get = (interval = this.props.interval) => {
this.props.get(interval);
};
}
componentWillMount() {
this.get();
}
componentWillReceiveProps(nextProps) {
if (nextProps) {
if (nextProps.timestamp && nextProps.timestamp !== this.props.timestamp) {
this.get(nextProps.interval);
}
}
}
render() {
const alertList = this.props.alertList;
const alertNumber = alertList && alertList.data
? alertList.data.problems.length
: 0;
const extraStyle = alertNumber > 0
? { backgroundColor: '#ffa031', color: '#fff' }
: {};
const style = {
...styles.content,
...this.props.style,
...extraStyle,
};
return (
<HoverPaper style={style}>
<div onClick={this.handleClick} style={styles.clickable}>
<h3>Alerts</h3>
<span style={styles.stat}>{alertNumber} Alerts to show</span>
</div>
</HoverPaper>
);
}
}
export default Alerts;
|
src/svg-icons/image/leak-remove.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageLeakRemove = (props) => (
<SvgIcon {...props}>
<path d="M10 3H8c0 .37-.04.72-.12 1.06l1.59 1.59C9.81 4.84 10 3.94 10 3zM3 4.27l2.84 2.84C5.03 7.67 4.06 8 3 8v2c1.61 0 3.09-.55 4.27-1.46L8.7 9.97C7.14 11.24 5.16 12 3 12v2c2.71 0 5.19-.99 7.11-2.62l2.5 2.5C10.99 15.81 10 18.29 10 21h2c0-2.16.76-4.14 2.03-5.69l1.43 1.43C14.55 17.91 14 19.39 14 21h2c0-1.06.33-2.03.89-2.84L19.73 21 21 19.73 4.27 3 3 4.27zM14 3h-2c0 1.5-.37 2.91-1.02 4.16l1.46 1.46C13.42 6.98 14 5.06 14 3zm5.94 13.12c.34-.08.69-.12 1.06-.12v-2c-.94 0-1.84.19-2.66.52l1.6 1.6zm-4.56-4.56l1.46 1.46C18.09 12.37 19.5 12 21 12v-2c-2.06 0-3.98.58-5.62 1.56z"/>
</SvgIcon>
);
ImageLeakRemove = pure(ImageLeakRemove);
ImageLeakRemove.displayName = 'ImageLeakRemove';
ImageLeakRemove.muiName = 'SvgIcon';
export default ImageLeakRemove;
|
client/components/AuthFormSignup.js | escape-hatch/escapehatch | import React from 'react';
import PropTypes from 'prop-types';
import signupLoginScss from './scss/SignupLogin.scss';
const AuthFormSignup = props => {
const { name, displayName, handleSignupSubmit, error, prevPath } = props;
return (
<div className="container">
<div className="row">
<div className="col-md-12">
<div id="legend">
<img src="img/loginSignup.png" />
<legend className="">Sign Up </legend>
</div>
<form
className="form-horizontal"
onSubmit={values =>
{ handleSignupSubmit(values, props.prevPath.pathname); } }
name={name}>
<fieldset>
<div className="control-group">
<div className="controls">
<input type="text" id="firstName" name="firstName" placeholder="First Name" className="form-control input-lg" />
</div>
</div>
<div className="control-group">
<div className="controls">
<input type="text" id="lastName" name="lastName" placeholder="Last Name" className="form-control input-lg" />
</div>
</div>
<div className="control-group">
<div className="controls">
<input type="text" id="email" name="email" placeholder="E-mail" className="form-control input-lg" />
</div>
</div>
<div className="control-group">
<div className="controls">
<input type="text" id="password" name="password" type="password" className="form-control input-lg" placeholder="Password" />
<label className="control-label" htmlFor="password">Password should be at least 6 characters</label>
</div>
</div>
<div className="control-group">
<div className="controls">
<button className="btn btn-success btn-lg"type="submit">{ displayName }</button>
</div>
</div>
</fieldset>
{ error && <div> { error.response.data } </div> }
</form>
</div>
<div className="col-md-12">
<a href={'/auth/google?returnTo=' + prevPath.pathname} className="btn btn-block btn-social btn-google">
<span className= "fa fa-google" /> { displayName } with Google</a>
<br />
<a href={'/auth/github?returnTo=' + prevPath.pathname} className="btn btn-block btn-social btn-github">
<span className= "fa fa-github" /> { displayName } with GitHub</a>
<br />
<a href={'/auth/stack?returnTo=' + prevPath.pathname} className="btn btn-block btn-social btn-stackExchange">
<span className= "fa fa-stack-exchange" />{ displayName } with StackExchange</a>
</div>
</div>
</div>
);
};
export default AuthFormSignup;
AuthFormSignup.propTypes = {
name: PropTypes.string.isRequired,
displayName: PropTypes.string.isRequired,
handleSignupSubmit: PropTypes.func.isRequired,
error: PropTypes.object
};
|
node_modules/react-native/local-cli/templates/HelloNavigation/views/welcome/WelcomeText.ios.js | gunaangs/Feedonymous | 'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
} from 'react-native';
export default class WelcomeText extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
This app shows the basics of navigating between a few screens,
working with ListView and handling text input.
</Text>
<Text style={styles.instructions}>
Modify any files to get started. For example try changing the
file{'\n'}views/welcome/WelcomeText.ios.js.
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu.
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
padding: 20,
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 16,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 12,
},
});
|
app/javascript/mastodon/components/avatar.js | d6rkaiz/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { autoPlayGif } from '../initial_state';
export default class Avatar extends React.PureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
size: PropTypes.number.isRequired,
style: PropTypes.object,
inline: PropTypes.bool,
animate: PropTypes.bool,
};
static defaultProps = {
animate: autoPlayGif,
size: 20,
inline: false,
};
state = {
hovering: false,
};
handleMouseEnter = () => {
if (this.props.animate) return;
this.setState({ hovering: true });
}
handleMouseLeave = () => {
if (this.props.animate) return;
this.setState({ hovering: false });
}
render () {
const { account, size, animate, inline } = this.props;
const { hovering } = this.state;
const src = account.get('avatar');
const staticSrc = account.get('avatar_static');
let className = 'account__avatar';
if (inline) {
className = className + ' account__avatar-inline';
}
const style = {
...this.props.style,
width: `${size}px`,
height: `${size}px`,
backgroundSize: `${size}px ${size}px`,
};
if (hovering || animate) {
style.backgroundImage = `url(${src})`;
} else {
style.backgroundImage = `url(${staticSrc})`;
}
return (
<div
className={className}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
style={style}
/>
);
}
}
|
docs/app/Examples/collections/Form/Content/index.js | mohammed88/Semantic-UI-React | import React from 'react'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
const FormTypesExamples = () => (
<ExampleSection title='Content'>
<ComponentExample
title='Field'
description='A field is a form element containing a label and an input.'
examplePath='collections/Form/Content/FormExampleField'
/>
</ExampleSection>
)
export default FormTypesExamples
|
src/svg-icons/image/center-focus-strong.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCenterFocusStrong = (props) => (
<SvgIcon {...props}>
<path d="M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm-7 7H3v4c0 1.1.9 2 2 2h4v-2H5v-4zM5 5h4V3H5c-1.1 0-2 .9-2 2v4h2V5zm14-2h-4v2h4v4h2V5c0-1.1-.9-2-2-2zm0 16h-4v2h4c1.1 0 2-.9 2-2v-4h-2v4z"/>
</SvgIcon>
);
ImageCenterFocusStrong = pure(ImageCenterFocusStrong);
ImageCenterFocusStrong.displayName = 'ImageCenterFocusStrong';
ImageCenterFocusStrong.muiName = 'SvgIcon';
export default ImageCenterFocusStrong;
|
client/scripts/components/entity-relationship-summary/index.js | kuali/research-coi | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import styles from './style';
import React from 'react';
import {formatDate} from '../../format-date';
import numeral from 'numeral';
import {
getRelationshipPersonTypeString,
getRelationshipCategoryTypeString,
getRelationshipTypeString,
getRelationshipAmountString
} from '../../stores/config-store';
import {ENTITY_RELATIONSHIP} from '../../../../coi-constants';
export default class EntityRelationshipSummary extends React.Component {
constructor() {
super();
this.remove = this.remove.bind(this);
}
remove() {
this.props.onRemove(this.props.relationship.id, this.props.entityId);
}
render() {
const { configState } = this.context;
let commentSection;
if (this.props.relationship.comments) {
commentSection = (
<div>
<div className={styles.commentValue}>
{this.props.relationship.comments}
</div>
</div>
);
}
let removeButton;
if (!this.props.readonly) {
removeButton = (
<button onClick={this.remove} className={styles.removeButton}>
<i className={`fa fa-times ${styles.x}`} />
</button>
);
}
if (this.props.relationship.relationshipCd === ENTITY_RELATIONSHIP.TRAVEL) {
const dateRange = `${formatDate(this.props.relationship.travel.startDate)} - ${formatDate(this.props.relationship.travel.endDate)}`;
const relationshipPerson = getRelationshipPersonTypeString(
configState,
this.props.relationship.personCd,
configState.config.id
);
const relationshipCategory = getRelationshipCategoryTypeString(
configState,
this.props.relationship.relationshipCd,
configState.config.id
);
return (
<div className={`${styles.container} ${this.props.className}`}>
<div className={styles.summary}>
{removeButton}
<span>
{`${relationshipPerson} • `}
{`${relationshipCategory} • `}
{this.props.relationship.travel.amount ? `${numeral(this.props.relationship.travel.amount).format('$0,0.00')} • ` : ''}
{this.props.relationship.travel.destination ? `${this.props.relationship.travel.destination} • ` : ''}
{dateRange ? `${dateRange} • ` : ''}
{this.props.relationship.travel.reason ? this.props.relationship.travel.reason : ''}
</span>
</div>
{commentSection}
</div>
);
}
const relationshipPerson = getRelationshipPersonTypeString(
configState,
this.props.relationship.personCd,
configState.config.id
);
const relationshipCategory = getRelationshipCategoryTypeString(
configState,
this.props.relationship.relationshipCd,
configState.config.id
);
let relationship;
if (
this.props.relationship.typeCd &&
this.props.relationship.typeCd !== ''
) {
relationship = getRelationshipTypeString(
configState,
this.props.relationship.relationshipCd,
this.props.relationship.typeCd,
configState.config.id
);
}
let relationshipAmount;
if (
this.props.relationship.amountCd &&
this.props.relationship.amountCd !== ''
) {
relationshipAmount = getRelationshipAmountString(
configState,
this.props.relationship.relationshipCd,
this.props.relationship.amountCd,
configState.config.id
);
}
return (
<div className={`${styles.container} ${this.props.className}`}>
<div className={styles.summary}>
{removeButton}
<span>
<span style={{display: 'inline'}}>
{`${relationshipPerson} • `}
</span>
<span style={{display: 'inline'}}>
{`${relationshipCategory} • `}
</span>
<span style={{display: 'inline'}}>
{this.props.relationship.typeCd ? `${relationship} • ` : ''}
</span>
<span style={{display: 'inline'}}>
{this.props.relationship.amountCd ? relationshipAmount : ''}
</span>
</span>
</div>
{commentSection}
</div>
);
}
}
EntityRelationshipSummary.contextTypes = {
configState: React.PropTypes.object
};
|
src/components/chatrooms/suggestions/SuggestionsStats.js | AleksandrRogachev94/chat-vote-go-frontend | import React from 'react'
import PropTypes from 'prop-types'
import { ResponsiveContainer, PieChart, Pie, Tooltip } from 'recharts';
const SuggestionsStats = (props) => {
const { suggestions } = props
const data = suggestions.filter(sug => sug.voters.length)
.map(sug => (
{ name: sug.title, value: sug.voters.length }
))
return (
<ResponsiveContainer height={400} width='100%'>
<PieChart>
<Pie data={data} innerRadius='70%' outerRadius='85%' fill="#f79b04" paddingAngle={5} label={(obj) => obj.payload.name} />
<Tooltip/>
</PieChart>
</ResponsiveContainer>
)
}
SuggestionsStats.propTypes = {
suggestions: PropTypes.array
}
SuggestionsStats.defaultProps = {
suggestions: []
}
export default SuggestionsStats
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/DefaultParameters.js | gutenye/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function load(id = 0) {
return [
{ id: id + 1, name: '1' },
{ id: id + 2, name: '2' },
{ id: id + 3, name: '3' },
{ id: id + 4, name: '4' },
];
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = load();
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-default-parameters">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
frontend/js/components/pages/404.js | skeswa/equitize | import React from 'react';
import {Navigation, Link} from 'react-router';
const NotFound = React.createClass({
render: () => {
return (
<div>
<h1>404</h1>
</div>
);
}
});
export default NotFound;
|
docs/src/app/components/pages/components/AppBar/Page.js | rscnt/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import appBarReadmeText from './README';
import AppBarExampleIcon from './ExampleIcon';
import appBarExampleIconCode from '!raw!./ExampleIcon';
import AppBarExampleIconButton from './ExampleIconButton';
import appBarExampleIconButtonCode from '!raw!./ExampleIconButton';
import AppBarExampleIconMenu from './ExampleIconMenu';
import appBarExampleIconMenuCode from '!raw!./ExampleIconMenu';
import appBarCode from '!raw!material-ui/lib/AppBar/AppBar';
const descriptions = {
icon: 'A simple example of `AppBar` with an icon on the right. ' +
'By default, the left icon is a navigation-menu.',
iconButton: 'This example uses an [IconButton](/#/components/icon-button) on the left, has a clickable `title` ' +
'through the `onTouchTap` property, and a [FlatButton](/#/components/flat-button) on the right.',
iconMenu: 'This example uses an [IconMenu](/#/components/icon-menu) for `iconElementRight`.',
};
const AppBarPage = () => (
<div>
<Title render={(previousTitle) => `App Bar - ${previousTitle}`} />
<MarkdownElement text={appBarReadmeText} />
<CodeExample
code={appBarExampleIconCode}
title="Simple example"
description={descriptions.icon}
>
<AppBarExampleIcon />
</CodeExample>
<CodeExample
code={appBarExampleIconButtonCode}
title="Buttons"
description={descriptions.iconButton}
>
<AppBarExampleIconButton />
</CodeExample>
<CodeExample
code={appBarExampleIconMenuCode}
title="Icon Menu"
description={descriptions.iconMenu}
>
<AppBarExampleIconMenu />
</CodeExample>
<PropTypeDescription code={appBarCode} />
</div>
);
export default AppBarPage;
|
app/javascript/mastodon/features/list_editor/components/account.js | pinfort/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>
);
}
}
|
modules/dreamview/frontend/src/components/Tasks/QuickStart.js | ycool/apollo | import React from 'react';
import { inject, observer } from 'mobx-react';
import classNames from 'classnames';
import UTTERANCE from 'store/utterance';
import WS from 'store/websocket';
class CommandGroup extends React.Component {
render() {
const {
name, commands, disabled,
extraCommandClass, extraButtonClass,
} = this.props;
const entries = Object.keys(commands).map((key) => (
<button
className={classNames('command-button', extraButtonClass)}
disabled={disabled}
key={key}
onClick={commands[key]}
>
{key}
</button>
));
const text = name ? <span className="name">{`${name}:`}</span> : null;
return (
<div className={classNames('command-group', extraCommandClass)}>
{text}
{entries}
</div>
);
}
}
@inject('store') @observer
export default class QuickStarter extends React.Component {
constructor(props) {
super(props);
this.setup = {
Setup: () => {
WS.executeModeCommand('SETUP_MODE');
UTTERANCE.speakOnce('Setup');
},
};
this.reset = {
'Reset All': () => {
WS.executeModeCommand('RESET_MODE');
UTTERANCE.speakOnce('Reset All');
},
};
this.auto = {
'Start Auto': () => {
WS.executeModeCommand('ENTER_AUTO_MODE');
UTTERANCE.speakOnce('Start Auto');
},
};
}
componentWillUpdate() {
UTTERANCE.cancelAllInQueue();
}
render() {
const { hmi } = this.props.store;
const { lockTaskPanel } = this.props.store.options;
return (
<div className="card">
<div className="card-header"><span>Quick Start</span></div>
<div className="card-content-column">
<CommandGroup disabled={lockTaskPanel} commands={this.setup} />
<CommandGroup disabled={lockTaskPanel} commands={this.reset} />
<CommandGroup
disabled={!hmi.enableStartAuto || lockTaskPanel}
commands={this.auto}
extraButtonClass="start-auto-button"
extraCommandClass="start-auto-command"
/>
</div>
</div>
);
}
}
|
client/src/components/SideMenu.js | esausilva/profile-updater | import React, { Component } from 'react';
import { Container, Header, Icon } from 'semantic-ui-react';
import { Link, withRouter } from 'react-router-dom';
import update from 'immutability-helper';
import SocialProfileList from './SocialProfileList';
import SocialButtonList from './SocialButtonList';
import firebase from '../firebase';
import API from '../api';
import { SOCIAL_BUTTON_SIZE_SMALL } from '../library/constants';
import { bl } from '../library/buttonListInitial';
import { readUserFromFirebase } from '../library/firebaseMethods';
import { h1, layout, logout as logoutStyle } from './SideMenu.css';
class SideMenu extends Component {
state = {
buttonList: bl(firebase, 'grey'),
profiles: [],
userCredentials: {}
};
/**
* Checks if user is logged in, if so then reads connected social providers, changes
* the visibility of the social button icons, reads user's tokens from Firebase database,
* sets the user's tokens to state and gets connected profiles info.
*/
componentDidMount() {
firebase.auth().onAuthStateChanged(async user => {
if (user) {
const updatedButtonList = user.providerData.reduce(
(acc, providerObj) => {
const providerId = providerObj.providerId.split('.')[0];
acc = update(acc, {
[providerId]: {
visible: {
$set: false
}
}
});
return acc;
},
{ ...this.state.buttonList }
);
const userCredentials = await readUserFromFirebase(
firebase.database(),
user.uid
);
this.setState(
{
buttonList: updatedButtonList,
userCredentials
},
() => this.getProfilesInfo()
);
} else {
this.props.history.push('/');
}
});
}
isUndefinedOrBlank = property =>
property === undefined || property === '' || property === null
? 'N/A'
: property;
buildUrl = link =>
`<a href='${link}' target='_blank' rel='noopener noreferrer'>${link}</a>`;
/**
* Calls provider APIs to read user's profile information
*/
getProfilesInfo = async () => {
const { userCredentials } = this.state;
const promisesArr = Object.keys(userCredentials).map(providerId => {
if (providerId === 'github') {
return API.fetchGithubUser(userCredentials.github);
}
if (providerId === 'twitter') {
return API.fetchTwitterUser(
userCredentials.twitter.username,
userCredentials.twitter
);
}
if (providerId === 'facebook') {
return API.fetchFacebookUser(userCredentials.facebook);
}
});
const resolved = await Promise.all(
promisesArr.filter(promise => promise !== undefined)
);
const profiles = resolved.map(profile => {
if (profile.provider === 'github') {
return {
github: {
location: this.isUndefinedOrBlank(profile.location),
url:
this.isUndefinedOrBlank(profile.blog) === 'N/A'
? 'N/A'
: this.buildUrl(profile.blog),
company: this.isUndefinedOrBlank(profile.company),
bio: this.isUndefinedOrBlank(profile.bio),
profilePhoto: profile.avatar_url,
homepage: profile.html_url
}
};
}
if (profile.provider === 'twitter') {
return {
twitter: {
location: this.isUndefinedOrBlank(profile.location),
url:
this.isUndefinedOrBlank(profile.entities.url) === 'N/A'
? 'N/A'
: this.buildUrl(profile.entities.url.urls[0].expanded_url),
company: 'N/A',
bio: this.isUndefinedOrBlank(profile.description),
profilePhoto: profile.profile_image_url,
homepage: `https://twitter.com/${profile.screen_name}`
}
};
}
if (profile.provider === 'facebook') {
return {
facebook: {
location:
this.isUndefinedOrBlank(profile.location) === 'N/A'
? 'N/A'
: profile.location.name,
url:
this.isUndefinedOrBlank(profile.website) === 'N/A'
? 'N/A'
: this.buildUrl(profile.website),
company:
this.isUndefinedOrBlank(profile.work) === 'N/A'
? 'N/A'
: profile.work[0].employer.name,
bio: this.isUndefinedOrBlank(profile.about),
profilePhoto: profile.picture.data.url,
homepage: profile.link
}
};
}
});
this.setState({ profiles });
};
/**
* Update the visibility of a provider's button
* @param {bool} visibility
* @param {string} providerId
*/
updateProviderVisibility = (visibility, providerId) => {
this.setState({
buttonList: update(this.state.buttonList, {
[providerId]: {
visible: {
$set: visibility
}
}
})
});
};
/**
* Updates profiles and buttons when user unlinks or connects a provider
* @param {bool} visibility
* @param {object} - userCredentials - User's connected profile tokens
* @param {string} providerId
*/
updateSideMenuItems = (visibility, userCredentials, providerId) => {
this.setState({ userCredentials }, () => {
this.getProfilesInfo();
this.updateProviderVisibility(visibility, providerId);
});
};
logOut = () => {
firebase
.auth()
.signOut()
.then(() => {
console.log('logged out');
this.props.history.push('/');
})
.catch(err => console.error(err));
};
render() {
return (
<Container fluid className={layout}>
<Link to="/updater">
<Header as="h1" className={h1} inverted>
profile<br />updater
</Header>
</Link>
<SocialProfileList
firebase={firebase}
profiles={this.state.profiles}
userCredentials={this.state.userCredentials}
updateSideMenuItems={this.updateSideMenuItems}
/>
<SocialButtonList
size={SOCIAL_BUTTON_SIZE_SMALL}
orientation="vertical"
firebase={firebase}
buttonList={this.state.buttonList}
updateSideMenuItems={this.updateSideMenuItems}
/>
<Icon
name="log out"
size="large"
color="red"
circular={true}
inverted
onClick={this.logOut}
className={logoutStyle}
/>
</Container>
);
}
}
export default withRouter(SideMenu);
|
node_modules/react-icons/ti/directions.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const TiDirections = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m34.8 15.8l-4.5-4.3c-1-0.9-2.5-1.5-3.8-1.5h-4.8v-0.8c0-1.4-1.2-2.5-2.5-2.5s-2.5 1.1-2.5 2.5v0.8h-5.9c-3.2 0-5.8 2.6-5.8 5.8 0 2.4 1.4 4.4 3.4 5.3l-3.1 3.1 4.3 4.2c0.9 1 2.4 1.6 3.7 1.6h3.7l1.3 6.7h1.7l1.3-6.7h4.5c3.3 0 5.9-2.6 5.9-5.8 0-1.5-0.6-2.9-1.6-3.9 0.1-0.1 0.1-0.1 0.2-0.1l4.5-4.4z m-9 10.9h-12.5c-0.4 0-1.1-0.3-1.4-0.6l-1.9-1.9 1.9-1.9c0.3-0.4 1-0.6 1.4-0.6h12.5c1.4 0 2.5 1.1 2.5 2.5s-1.1 2.5-2.5 2.5z m2.2-8.9c-0.4 0.3-1 0.5-1.5 0.5h-15.7c-1.3 0-2.5-1.1-2.5-2.5s1.2-2.5 2.5-2.5h15.7c0.5 0 1.1 0.3 1.5 0.6l2 1.9-2 2z"/></g>
</Icon>
)
export default TiDirections
|
modules/dreamview/frontend/src/components/Navigation/index.js | ycool/apollo | import React from 'react';
import MAP_NAVIGATOR from 'components/Navigation/MapNavigator';
import WS from 'store/websocket';
import { MAP_SIZE } from 'store/dimension';
import loadScriptAsync from 'utils/script_loader';
import WindowResizeControl from 'components/Navigation/WindowResizeControl';
export default class Navigation extends React.Component {
constructor(props) {
super(props);
this.scriptOnLoadHandler = this.scriptOnLoadHandler.bind(this);
if (!MAP_NAVIGATOR.mapAPILoaded) {
let onLoad = () => {
console.log('Map API script loaded.');
};
if (PARAMETERS.navigation.map === 'BaiduMap') {
// For Baidu Map, the callback function is set in the window Object level
window.initMap = this.scriptOnLoadHandler;
} else if (PARAMETERS.navigation.map === 'GoogleMap') {
// For Google Map, the callback function is set from the <Script>
onLoad = this.scriptOnLoadHandler;
}
loadScriptAsync({
url: PARAMETERS.navigation.mapAPiUrl,
onLoad,
onError: () => {
console.log('Failed to load map api');
},
});
}
}
componentDidMount() {
if (MAP_NAVIGATOR.mapAPILoaded) {
this.scriptOnLoadHandler();
}
}
componentDidUpdate() {
const { hasRoutingControls, size } = this.props;
if (hasRoutingControls && size === MAP_SIZE.FULL) {
MAP_NAVIGATOR.enableControls();
} else {
MAP_NAVIGATOR.disableControls();
}
}
scriptOnLoadHandler() {
import(`components/Navigation/${PARAMETERS.navigation.map}Adapter`).then(
(mapAdapterModule) => {
const MapAdapterClass = mapAdapterModule.default;
const mapAdapter = new MapAdapterClass();
MAP_NAVIGATOR.mapAPILoaded = true;
MAP_NAVIGATOR.initialize(WS, mapAdapter);
MAP_NAVIGATOR.disableControls();
},
);
}
componentWillUnmount() {
MAP_NAVIGATOR.reset();
}
render() {
const {
width, height, size, onResize,
} = this.props;
if (!['GoogleMap', 'BaiduMap'].includes(PARAMETERS.navigation.map)) {
console.error(`Map API ${PARAMETERS.navigation.map} is not supported.`);
return null;
}
return (
<div displayname="navigation" className="navigation-view" style={{ width, height }}>
<div id="map_canvas" />
<WindowResizeControl type={size} onClick={onResize} />
</div>
);
}
}
|
src/js/components/table/table_header.js | working-minds/realizejs | import React, { Component } from 'react';
import PropTypes from '../../prop_types';
import Realize from '../../realize';
import { mixin } from '../../utils/decorators';
import { CssClassMixin, LocalizedResourceFieldMixin } from '../../mixins';
const validFormats = [
'text',
'currency',
'number',
'percentage',
'boolean',
'date',
'datetime',
'time',
];
@mixin(
CssClassMixin,
LocalizedResourceFieldMixin
)
export default class TableHeader extends Component {
static propTypes = {
label: PropTypes.localizedString,
format: PropTypes.oneOf(validFormats),
sortable: PropTypes.bool,
sortDirection: PropTypes.string,
sortFieldName: PropTypes.string,
onSort: PropTypes.func,
};
static defaultProps = {
themeClassKey: 'table.header',
sortable: true,
sortDirection: null,
sortFieldName: null,
onSort() { return true; },
};
constructor(props) {
super(props);
this.sortColumn = this.sortColumn.bind(this);
}
getLabel() {
if (!!this.props.label && this.props.label.length > 0) {
return Realize.i18n.t(this.props.label);
}
return this.localizeResourceField();
}
labelClassName() {
let className = '';
const { clearTheme, sortable, sortDirection } = this.props;
if (!clearTheme) {
className += Realize.themes.getCssClass('table.header.label');
}
if (sortable) {
className += ' sortable';
if (sortDirection !== null) {
className += ` ${sortDirection}`;
}
}
return className;
}
sortColumn() {
return this.props.sortable
? this.props.onSort(this.buildSortData())
: null;
}
buildSortData() {
const sortField = this.getSortFieldName();
const sortDirection = this.getSortDirection();
return {
field: sortField,
direction: sortDirection,
};
}
getSortFieldName() {
return this.props.sortFieldName || this.props.name;
}
getSortDirection() {
const currentSortDirection = this.props.sortDirection;
return (currentSortDirection === null || currentSortDirection === 'desc')
? 'asc'
: 'desc';
}
headerClassName() {
let className = this.className();
if (!!this.props.format) {
className += ` table-header--${this.props.format}`;
}
if (!!this.props.name) {
className += ` table-header--${this.props.name}`;
}
return className;
}
render() {
return (
<th className={this.headerClassName()}>
<span onClick={this.sortColumn} className={this.labelClassName()}>
{this.getLabel()}
</span>
</th>
);
}
}
|
example/App.js | zzzkk2009/react-native-leancloud-sdk | /**
* Created by zachary on 2017/3/1.
*/
import React, { Component } from 'react';
import {Actions, Scene, Router} from 'react-native-router-flux';
import PushDemo from './PushDemo'
import PushDemoCallback from './PushDemoCallback'
const scenes = Actions.create(
<Scene key="root">
<Scene key="PushDemo" initial={true} component={PushDemo} title="PushDemo"/>
<Scene key="PushDemoCallback" component={PushDemoCallback} title="PushDemoCallback"/>
</Scene>
);
export default class App extends React.Component {
render() {
return <Router scenes={scenes}/>
}
} |
definitions/npm/styled-components_v2.x.x/flow_v0.25.x-v0.41.x/test_styled-components_v2.x.x.js | orlandoc01/flow-typed | // @flow
import {renderToString} from 'react-dom/server'
import styled, {ThemeProvider, withTheme, keyframes, ServerStyleSheet, StyleSheetManager} from 'styled-components'
import React from 'react'
import type {Theme} from 'styled-components'
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
const ExtendedTitle = styled(Title)`
font-size: 2em;
`
const Wrapper = styled.section`
padding: 4em;
background: ${({theme}) => theme.background};
`;
const theme: Theme = {
background: "papayawhip"
}
const Component = () => (
<ThemeProvider theme={theme}>
<Wrapper>
<Title>Hello World, this is my first styled component!</Title>
</Wrapper>
</ThemeProvider>
)
const ComponentWithTheme = withTheme(Component)
const Component2 = () => (
<ThemeProvider theme={outerTheme => outerTheme}>
<Wrapper>
<Title>Hello World, this is my first styled component!</Title>
</Wrapper>
</ThemeProvider>
)
const OpacityKeyFrame = keyframes`
0% { opacity: 0; }
100% { opacity: 1; }
`;
// $ExpectError
const NoExistingElementWrapper = styled.nonexisting`
padding: 4em;
background: papayawhip;
`;
const num = 9
// $ExpectError
const NoExistingComponentWrapper = styled()`
padding: 4em;
background: papayawhip;
`;
// $ExpectError
const NumberWrapper = styled(num)`
padding: 4em;
background: papayawhip;
`;
const sheet = new ServerStyleSheet()
const html = renderToString(sheet.collectStyles(<Component />))
const css = sheet.getStyleTags()
const sheet2 = new ServerStyleSheet()
const html2 = renderToString(
<StyleSheetManager sheet={sheet}>
<Component />
</StyleSheetManager>
)
const css2 = sheet.getStyleTags()
const css3 = sheet.getStyleElement()
class TestReactClass extends React.Component {
render() { return <div />; }
}
const StyledClass = styled(TestReactClass)`
color: red;
`;
|
assets/Project/src/views/Start/Start.js | believer/atom-react-alt-templates | import React from 'react'
import CSSModules from 'react-css-modules'
import styles from './Start.css'
export const Start = () =>
<div />
export default CSSModules(Start, styles)
|
src/svg-icons/notification/ondemand-video.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationOndemandVideo = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12zm-5-6l-7 4V7z"/>
</SvgIcon>
);
NotificationOndemandVideo = pure(NotificationOndemandVideo);
NotificationOndemandVideo.displayName = 'NotificationOndemandVideo';
NotificationOndemandVideo.muiName = 'SvgIcon';
export default NotificationOndemandVideo;
|
src/components/TouchableWrapper/index.ios.js | aaron-edwards/Spirit-Guide | import React from 'react';
import { TouchableHighlight } from 'react-native';
export default TouchableWrapper = props => {
const touchableProps = {
onPress: props.onPress,
underlayColor: props.underlayColor || '#CCCCCC',
};
return (<TouchableHighlight { ... touchableProps }>
{props.children}
</TouchableHighlight>)
}
|
react-flux-mui/js/material-ui/src/svg-icons/editor/title.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorTitle = (props) => (
<SvgIcon {...props}>
<path d="M5 4v3h5.5v12h3V7H19V4z"/>
</SvgIcon>
);
EditorTitle = pure(EditorTitle);
EditorTitle.displayName = 'EditorTitle';
EditorTitle.muiName = 'SvgIcon';
export default EditorTitle;
|
react/dashboard_example/src/vendor/recharts/demo/component/Sector.js | webmaster444/webmaster444.github.io | import React from 'react';
import { Surface, Sector } from 'recharts';
export default React.createClass({
render () {
return (
<Surface width={500} height={500}>
<Sector fill="#ff7902" cx={200} cy={300} innerRadius={150} outerRadius={200} endAngle={90} />
</Surface>
);
}
});
|
public/js/components/trends/trendactivitySharedList.react.js | TRomesh/Coupley | import React from 'react';
import Card from 'material-ui/lib/card/card';
import CardMedia from 'material-ui/lib/card/card-media';
import CardText from 'material-ui/lib/card/card-text';
import ListItem from 'material-ui/lib/lists/list-item';
import Divider from 'material-ui/lib/divider';
import Avatar from 'material-ui/lib/avatar';
const style1 = {
width: 700,
margin: 40,
};
const ActivitySharedList = React.createClass({
render: function () {
return (
<div style={style1}>
<div>
<Card>
<ListItem
leftAvatar={<Avatar src="https://s-media-cache-ak0.pinimg.com/236x/dc/15/f2/dc15f28faef36bc55e64560d000e871c.jpg" />}
primaryText={this.props.sfirstname}
secondaryText={
<p>
<b>{this.props.screated_at}</b>
</p>
}
secondaryTextLines={1} />
<CardText>
{this.props.spost_text}
</CardText>
<CardMedia expandable={true}>
<img src={this.props.sattachment} />
</CardMedia>
<Divider inset={true} />
</Card>
</div>
</div>
);
}
});
export default ActivitySharedList;
|
example/src/Screens/Docs/AnimatedSwitch/Props.js | maisano/react-router-transition | import React from 'react';
import { css } from 'glamor';
import Footer from '../shared/Footer';
const propTypesRule = css`
font-size: 1.6rem;
border-bottom: 1px solid #eee;
padding-bottom: 1rem;
margin: 3rem 0 1rem;
`;
const Props = () => (
<div>
<h2>Props</h2>
<div css={propTypesRule}>
<code>atEnter</code>, <code>atLeave</code>, <code>atActive</code>
</div>
<p>Objects with numerical values, expressing the interpolatable states a component will have when mounting, unmounting and mounted, respectively. Note that <code>spring</code> objects are valid only for <code>atActive</code> and <code>atLeave</code>.</p>
<div css={propTypesRule}><code>didLeave</code></div>
<p>An optional function that will be called when animation is done.</p>
<div css={propTypesRule}><code>mapStyles</code></div>
<p>An optional function for transforming values that don't map 1:1 with styles (e.g. <code>translateX</code> or other values of the <code>transform</code> style property).</p>
<div css={propTypesRule}><code>runOnMount</code></div>
<p>A boolean flag to signal whether or not to apply a transition to the child component while mounting the parent.</p>
<div css={propTypesRule}><code>wrapperComponent</code></div>
<p>The element type (<code>'div'</code>, <code>'span'</code>, etc.) to wrap the transitioning routes with. Use <code>false</code> to transition child components themselves, though <strong>this requires consuming a <code>style</code> prop that gets injected into your component</strong>.</p>
<div css={propTypesRule}><code>className</code></div>
<p>A class name to apply to the root node of the transition.</p>
<Footer />
</div>
);
export default Props;
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/AsyncAwait.js | gutenye/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
async function load() {
return [
{ id: 1, name: '1' },
{ id: 2, name: '2' },
{ id: 3, name: '3' },
{ id: 4, name: '4' },
];
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = await load();
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-async-await">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
frontend/src/Album/Delete/DeleteAlbumModal.js | lidarr/Lidarr | import PropTypes from 'prop-types';
import React from 'react';
import Modal from 'Components/Modal/Modal';
import { sizes } from 'Helpers/Props';
import DeleteAlbumModalContentConnector from './DeleteAlbumModalContentConnector';
function DeleteAlbumModal(props) {
const {
isOpen,
onModalClose,
...otherProps
} = props;
return (
<Modal
isOpen={isOpen}
size={sizes.MEDIUM}
onModalClose={onModalClose}
>
<DeleteAlbumModalContentConnector
{...otherProps}
onModalClose={onModalClose}
/>
</Modal>
);
}
DeleteAlbumModal.propTypes = {
isOpen: PropTypes.bool.isRequired,
onModalClose: PropTypes.func.isRequired
};
export default DeleteAlbumModal;
|
src/video_list_item.js | nikitadeshmukh02/testVsCode | import React from 'react'
const VideoListItem=({video,onVideoSelect})=>{
//debugger
//const video=video;
//debugger
const imageURL=video.snippet.thumbnails.default.url;
//let onVideoSelect=onVideoSelect
return(
<li onClick={()=>onVideoSelect(video)} className="list-group-item">
<div className='video-list media'>
<div className='media-left'>
<img className='media-object' url={imageURL}>
</img>
</div>
<div className='media-body'>
<div className='media-heading'>{video.snippet.title}
</div>
</div>
</div>
</li>
)
}
export default VideoListItem; |
demo/src/stories/Menu/MenuExample/Menu.js | tannerlinsley/react-story | import React from 'react'
import PropTypes from 'prop-types'
const Menu = ({ children }) => (
<ul>{children}</ul>
)
Menu.propTypes = {
children: PropTypes.node
}
export default Menu
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.