path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
src/components/PostDetail.js
|
ksco/reblog
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Header, Segment } from 'semantic-ui-react';
import marked from 'marked';
import getPostDetail from '../actions/post';
import getPostComments from '../actions/comments';
import { post } from '../selectors';
import Spinner from './Spinner';
import Empty from './Empty';
import Comments from './Comments';
import Labels from './Labels';
class PostDetail extends Component {
componentDidMount() {
this.fetchPost(this.props);
}
fetchPost({ post, selectedPostId, accessToken, fetchPost, fetchComments }) {
if (!post) {
fetchPost(selectedPostId, accessToken);
}
fetchComments(selectedPostId, accessToken);
}
render() {
const { post, postLoading, commentsLoading } = this.props;
if (post === null) {
if (postLoading === true) {
return <Spinner />;
}
return <Empty />;
}
return (
<div>
<Header
as='h2'
textAlign='center'
attached='top'
style={{ marginTop: '1em' }}
>
{post.title}
</Header>
<Segment attached>
<div className='marked' dangerouslySetInnerHTML={{__html: marked(post.body)}}></div>
</Segment>
<Labels labels={post.labels} />
<Comments comments={post.comments} loading={commentsLoading} />
</div>
);
}
}
const mapStateToProps = (state) => ({
post: post(state),
selectedPostId: parseInt(state.router.params.postId, 10),
postLoading: state.state.loading.post,
commentsLoading: state.state.loading.comments,
accessToken: state.state.auth.accessToken,
});
const mapDispatchToProps = (dispatch) => ({
fetchPost: (selectedPostId, accessToken) => dispatch(getPostDetail(selectedPostId, accessToken)),
fetchComments: (selectedPostId, accessToken) => dispatch(getPostComments(selectedPostId, accessToken)),
});
export default connect(mapStateToProps, mapDispatchToProps)(PostDetail);
|
src/components/Currency.js
|
KingKone/oversee
|
import React, { Component } from 'react';
import { ipcRenderer } from 'electron';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';
let data = [];
let lcup = 0;
class Currency extends React.Component {
render() {
return (
<div className="currency">
<div className="cusymb"><h1>{this.props.data.symbol}</h1> </div>
<div className="cutext">
<h4>{this.props.data.name}</h4>
<p>{this.props.data.price_usd} USD</p>
</div>
</div>
);
}
}
export default Currency;
|
docs/app/Examples/elements/Image/index.js
|
jcarbo/stardust
|
import React from 'react'
import Types from './Types'
import States from './States'
import Variations from './Variations'
import Groups from './Groups'
const ImageExamples = () => (
<div>
<Types />
<States />
<Variations />
<Groups />
</div>
)
export default ImageExamples
|
src/elements/Image/ImageGroup.js
|
shengnian/shengnian-ui-react
|
import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import {
childrenUtils,
customPropTypes,
getElementType,
getUnhandledProps,
META,
SUI,
} from '../../lib'
/**
* A group of images.
*/
function ImageGroup(props) {
const { children, className, content, size } = props
const classes = cx('ui', size, className, 'images')
const rest = getUnhandledProps(ImageGroup, props)
const ElementType = getElementType(ImageGroup, props)
return (
<ElementType {...rest} className={classes}>
{childrenUtils.isNil(children) ? content : children}
</ElementType>
)
}
ImageGroup._meta = {
name: 'ImageGroup',
parent: 'Image',
type: META.TYPES.ELEMENT,
}
ImageGroup.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
/** A group of images can be formatted to have the same size. */
size: PropTypes.oneOf(SUI.SIZES),
}
export default ImageGroup
|
packages/wix-style-react/src/Page/test/examples/Breadcrumbs.js
|
wix/wix-style-react
|
import React from 'react';
import { Breadcrumbs } from 'wix-style-react';
export default (
<Breadcrumbs
items={[1, 2, 3].map(i => ({ id: `${i}`, value: `#${i} item` }))}
activeId="3"
size="medium"
theme="onGrayBackground"
onClick={() => {}}
/>
);
|
src/index.js
|
shhaumb/react-redux-subapp
|
import React from 'react';
import PropTypes from 'prop-types';
import hoistStatics from 'hoist-non-react-statics';
import { subspace, namespaced } from 'redux-subspace';
import { subspaced } from 'redux-subspace-saga';
import { addReducer } from 'redux-transient';
import { subAppEnhancer } from './enhancer';
export { subAppEnhancer } from './enhancer';
// Depricated
export const enhancer = subAppEnhancer;
const ACTION_INITIALIZE_REDUCER_TYPE = '@react-redux-subapp/INIT';
const initializeReducer = () => ({
type: ACTION_INITIALIZE_REDUCER_TYPE,
});
const sagaRunForSubAppKeyMap = {};
const mapState = subAppKey => (state) => {
let subState = state;
const keys = subAppKey.split('.');
keys.forEach((key) => {
if (subState !== undefined) {
subState = subState[key];
}
});
return subState;
};
const subAppCreator = (subAppKey, WrappedComponent, reducer, options) => {
const wrappedComponentName = WrappedComponent.displayName
|| WrappedComponent.name
|| 'Component';
const displayName = `SubApp(${wrappedComponentName}, subAppKey=${subAppKey})`;
class SubApp extends React.Component {
getChildContext() {
return {
store: subspace(mapState(subAppKey), subAppKey)(this.getStore()),
};
}
componentWillMount() {
const store = this.getStore();
store.dispatch(addReducer(reducer));
store.dispatch(initializeReducer());
if (options.saga && (!sagaRunForSubAppKeyMap[subAppKey])) {
const subspacedSaga = subspaced(mapState(subAppKey), subAppKey)(options.saga);
store.runSaga(subspacedSaga);
sagaRunForSubAppKeyMap[subAppKey] = true;
}
}
getStore() {
let { store } = this.context;
if (store.rootStore) {
store = store.rootStore;
}
return store;
}
render() {
return <WrappedComponent {...this.props} />;
}
}
SubApp.propTypes = {};
SubApp.contextTypes = {
store: PropTypes.object.isRequired,
};
SubApp.childContextTypes = {
store: PropTypes.object,
};
SubApp.WrappedComponent = WrappedComponent;
SubApp.displayName = displayName;
return hoistStatics(SubApp, WrappedComponent);
};
const refined = (subAppKey, reducer, initialState) => (state, action) => {
let subState = mapState(subAppKey)(state);
if (subState === undefined) {
subState = initialState;
}
const keys = subAppKey.split('.');
const resultState = {
...state,
};
let parentState = resultState;
if (keys.length > 1) {
keys.splice(0, keys.length - 1).forEach((key) => {
if (parentState[key] === undefined) {
parentState[key] = {};
}
parentState = parentState[key];
});
}
parentState[keys[0]] = reducer(subState, action);
return resultState;
};
const mapping = {};
export const createAppFactory = (WrappedComponent, reducer, initialState, options = {}) => (subAppKey) => {
if (subAppKey in mapping) {
if (mapping[subAppKey].wrapped === WrappedComponent) {
return mapping[subAppKey].subApp;
}
throw new Error(`store's key=${subAppKey} is already mapped with another component ${mapping[subAppKey].wrapped}`);
}
const namespacedReducer = namespaced(subAppKey)(reducer);
const refinedReducer = refined(subAppKey, namespacedReducer, initialState);
const subApp = subAppCreator(subAppKey, WrappedComponent, refinedReducer, options);
mapping[subAppKey] = {
wrapped: WrappedComponent,
subApp,
};
return subApp;
};
|
Skins/VetoccitanT3/ReactSrc/node_modules/react-redux/src/hooks/useStore.js
|
ENG-SYSTEMS/Kob-Eye
|
import { useContext } from 'react'
import { ReactReduxContext } from '../components/Context'
import { useReduxContext as useDefaultReduxContext } from './useReduxContext'
/**
* Hook factory, which creates a `useStore` hook bound to a given context.
*
* @param {React.Context} [context=ReactReduxContext] Context passed to your `<Provider>`.
* @returns {Function} A `useStore` hook bound to the specified context.
*/
export function createStoreHook(context = ReactReduxContext) {
const useReduxContext =
context === ReactReduxContext
? useDefaultReduxContext
: () => useContext(context)
return function useStore() {
const { store } = useReduxContext()
return store
}
}
/**
* A hook to access the redux store.
*
* @returns {any} the redux store
*
* @example
*
* import React from 'react'
* import { useStore } from 'react-redux'
*
* export const ExampleComponent = () => {
* const store = useStore()
* return <div>{store.getState()}</div>
* }
*/
export const useStore = /*#__PURE__*/ createStoreHook()
|
src/components/views/elements/AddressSelector.js
|
aperezdc/matrix-react-sdk
|
/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
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.
*/
'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import sdk from '../../../index';
import classNames from 'classnames';
import { UserAddressType } from '../../../UserAddress';
export default React.createClass({
displayName: 'AddressSelector',
propTypes: {
onSelected: PropTypes.func.isRequired,
// List of the addresses to display
addressList: PropTypes.arrayOf(UserAddressType).isRequired,
// Whether to show the address on the address tiles
showAddress: PropTypes.bool,
truncateAt: PropTypes.number.isRequired,
selected: PropTypes.number,
// Element to put as a header on top of the list
header: PropTypes.node,
},
getInitialState: function() {
return {
selected: this.props.selected === undefined ? 0 : this.props.selected,
hover: false,
};
},
componentWillReceiveProps: function(props) {
// Make sure the selected item isn't outside the list bounds
const selected = this.state.selected;
const maxSelected = this._maxSelected(props.addressList);
if (selected > maxSelected) {
this.setState({ selected: maxSelected });
}
},
componentDidUpdate: function() {
// As the user scrolls with the arrow keys keep the selected item
// at the top of the window.
if (this.scrollElement && this.props.addressList.length > 0 && !this.state.hover) {
const elementHeight = this.addressListElement.getBoundingClientRect().height;
this.scrollElement.scrollTop = (this.state.selected * elementHeight) - elementHeight;
}
},
moveSelectionTop: function() {
if (this.state.selected > 0) {
this.setState({
selected: 0,
hover: false,
});
}
},
moveSelectionUp: function() {
if (this.state.selected > 0) {
this.setState({
selected: this.state.selected - 1,
hover: false,
});
}
},
moveSelectionDown: function() {
if (this.state.selected < this._maxSelected(this.props.addressList)) {
this.setState({
selected: this.state.selected + 1,
hover: false,
});
}
},
chooseSelection: function() {
this.selectAddress(this.state.selected);
},
onClick: function(index) {
this.selectAddress(index);
},
onMouseEnter: function(index) {
this.setState({
selected: index,
hover: true,
});
},
onMouseLeave: function() {
this.setState({ hover: false });
},
selectAddress: function(index) {
// Only try to select an address if one exists
if (this.props.addressList.length !== 0) {
this.props.onSelected(index);
this.setState({ hover: false });
}
},
createAddressListTiles: function() {
const self = this;
const AddressTile = sdk.getComponent("elements.AddressTile");
const maxSelected = this._maxSelected(this.props.addressList);
const addressList = [];
// Only create the address elements if there are address
if (this.props.addressList.length > 0) {
for (let i = 0; i <= maxSelected; i++) {
const classes = classNames({
"mx_AddressSelector_addressListElement": true,
"mx_AddressSelector_selected": this.state.selected === i,
});
// NOTE: Defaulting to "vector" as the network, until the network backend stuff is done.
// Saving the addressListElement so we can use it to work out, in the componentDidUpdate
// method, how far to scroll when using the arrow keys
addressList.push(
<div
className={classes}
onClick={this.onClick.bind(this, i)}
onMouseEnter={this.onMouseEnter.bind(this, i)}
onMouseLeave={this.onMouseLeave}
key={this.props.addressList[i].addressType + "/" + this.props.addressList[i].address}
ref={(ref) => { this.addressListElement = ref; }}
>
<AddressTile
address={this.props.addressList[i]}
showAddress={this.props.showAddress}
justified={true}
networkName="vector"
networkUrl="img/search-icon-vector.svg"
/>
</div>,
);
}
}
return addressList;
},
_maxSelected: function(list) {
const listSize = list.length === 0 ? 0 : list.length - 1;
const maxSelected = listSize > (this.props.truncateAt - 1) ? (this.props.truncateAt - 1) : listSize;
return maxSelected;
},
render: function() {
const classes = classNames({
"mx_AddressSelector": true,
"mx_AddressSelector_empty": this.props.addressList.length === 0,
});
return (
<div className={classes} ref={(ref) => {this.scrollElement = ref;}}>
{ this.props.header }
{ this.createAddressListTiles() }
</div>
);
},
});
|
src/components/Button/Button.js
|
guilhermecvm/react-dribbble-components
|
import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
const Button = styled.button`
padding: 5px 20px;
border-radius: 10px;
border: 0;
color: #ffffff;
text-align: left;
text-transform: uppercase;
font-size: 14px;
box-shadow: 0px 0px 20px -5px rgba(0, 0, 0, 0.75);
${props => props.width && `width: ${props.width}px`};
${props => props.background && `background-color: ${props.background}`};
`
const Button2 = ({ Icon, ...props }) => (
<Button {...props}>
<Icon size={32} style={styles.icon} /> {props.children}
</Button>
)
export const PrimaryButton = props => (
<Button2 background="#6f5f5c" {...props} />
)
export const Secondary1Button = props => (
<Button2 background="#815D5C" {...props} />
)
export const Secondary2Button = props => (
<Button2 background="#A16B62" {...props} />
)
export const Secondary3Button = props => (
<Button2 background="#E18F74" {...props} />
)
export const AccentButton = props => <Button2 background="#EFB175" {...props} />
const styles = {
icon: {
marginRight: 10,
},
}
|
admin/client/App/shared/Portal.js
|
ratecity/keystone
|
/**
* Used by the Popout component and the Lightbox component of the fields for
* popouts. Renders a non-react DOM node.
*/
import React from 'react';
import ReactDOM from 'react-dom';
module.exports = React.createClass({
displayName: 'Portal',
portalElement: null, // eslint-disable-line react/sort-comp
componentDidMount () {
const el = document.createElement('div');
document.body.appendChild(el);
this.portalElement = el;
this.componentDidUpdate();
},
componentWillUnmount () {
document.body.removeChild(this.portalElement);
},
componentDidUpdate () {
ReactDOM.render(<div {...this.props} />, this.portalElement);
},
getPortalDOMNode () {
return this.portalElement;
},
render () {
return null;
},
});
|
mobx-src/components/User.js
|
xiedidan/smart-territory-demo
|
import React from 'react'
import {observer} from 'mobx-react'
import _ from 'lodash'
import * as THREE from 'three'
import {Layout, Menu, Breadcrumb, Form, Input, Icon, Checkbox, Button, Row, Col} from 'antd'
import constants from '../utilities/constants'
const { SubMenu } = Menu
const { Header, Content, Sider } = Layout
@observer class User extends React.Component {
constructor() {
super()
// member function
this.render = this.render.bind(this)
}
render() {
return <div>
</div>
}
}
export default User
|
test/mapTree-test.js
|
jaredly/react-motion
|
import mapTree from '../src/mapTree';
import React from 'react';
describe('mapTree', () => {
it('should map numbers leaves correctly', () => {
const add1 = (_, a) => a + 1;
expect(mapTree(add1, 1)).toEqual(2);
expect(mapTree(add1, [])).toEqual([]);
expect(mapTree(add1, {})).toEqual({});
expect(mapTree(add1, {a: 1})).toEqual({a: 2});
expect(mapTree(add1, {a: [1, {b: 2}]})).toEqual({a: [2, {b: 3}]});
});
it('should be not infinitely recurse into structures we provide', () => {
expect(mapTree(() => [1, 2], {a: [1, {b: 2}]}))
.toEqual({a: [[1, 2], {b: [1, 2]}]});
});
it('should not call f on non-ground types', () => {
let add1 = {
f: () => {
throw new Error('asd');
},
};
const now = new Date();
const MyClass = class {};
const inst = new MyClass();
const comp = <div key="a" />;
expect(mapTree(add1.f, now)).toEqual(now);
expect(mapTree(add1.f, MyClass)).toEqual(MyClass);
expect(mapTree(add1.f, inst)).toEqual(inst);
expect(mapTree(add1.f, comp)).toEqual(comp);
expect(mapTree(add1.f, 'hi')).toEqual('hi');
});
});
|
src/svg-icons/communication/chat.js
|
skarnecki/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationChat = (props) => (
<SvgIcon {...props}>
<path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM6 9h12v2H6V9zm8 5H6v-2h8v2zm4-6H6V6h12v2z"/>
</SvgIcon>
);
CommunicationChat = pure(CommunicationChat);
CommunicationChat.displayName = 'CommunicationChat';
export default CommunicationChat;
|
src/scripts/components/button/button.component.js
|
pponugo/react-dev-ops
|
import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
class Button extends React.Component {
constructor(props) {
super(props);
this._onEvent = this._onEvent.bind(this);
}
_onEvent(e, eventName, args) {
this.props.onEvent(eventName, args);
}
render() {
const { ariaLabel, autofocus, className, classNameWrapper,
disabled, form, hidden, label, name, type, value } = this.props;
if (hidden) {
return (<div />);
}
return (
<div className={cn(classNameWrapper)}>
<button
aria-label={ariaLabel || label || value}
autoFocus={autofocus}
className={cn(className)}
disabled={disabled}
form={form}
name={name || value}
type={type}
value={value}
onClick={e => this._onEvent(e, 'click', value)}
onMouseDown={e => this._onEvent(e, 'mouseDown', value)}
onMouseUp={e => this._onEvent(e, 'mouseUp', value)}
onFocus={e => this._onEvent(e, 'focus', value)}
onBlur={e => this._onEvent(e, 'blur', value)}
>
{label || value}
</button>
</div>
);
}
}
Button.propTypes = {
ariaLabel: PropTypes.string,
autofocus: PropTypes.bool,
className: PropTypes.string,
classNameWrapper: PropTypes.string,
disabled: PropTypes.bool,
form: PropTypes.string,
hidden: PropTypes.bool,
label: PropTypes.string,
name: PropTypes.string,
onEvent: PropTypes.func,
type: PropTypes.oneOf(['button', 'reset', 'submit']),
value: PropTypes.string,
};
Button.defaultProps = {
ariaLabel: undefined,
autofocus: false,
className: 'btn-blue',
classNameWrapper: undefined,
disabled: false,
form: undefined,
hidden: false,
label: undefined,
name: undefined,
onEvent: undefined,
type: 'button',
value: 'click',
};
export default Button;
|
test/unit/components/RoutesSpec.js
|
lxanders/react-clientside-example
|
import React from 'react';
import { mount } from 'enzyme';
import { expect } from 'chai';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import reducers from '../../../src/reducers/index';
import App from '../../../src/components/App';
import Routes from '../../../src/components/Routes';
describe('Routes', () => {
const createComponent = () => {
const services = { fetchEntities: () => Promise.resolve([]) };
const store = createStore(
reducers,
applyMiddleware(thunk.withExtraArgument(services))
);
return (
<Provider store={store}>
<Routes />
</Provider>
);
};
it('should render the app component on the default route', () => {
const routes = mount(createComponent());
expect(routes.find(App).length).to.equal(1);
});
});
|
client/src/components/User/Settings.js
|
hutchgrant/react-boilerplate
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions/auth';
class Settings extends Component {
render() {
return (
<div>
<h2>Settings</h2>
<h5>Welcome {this.props.auth.username}</h5>
</div>
);
}
};
function mapStateToProps({ auth }) {
return { auth };
}
export default connect(mapStateToProps, actions)(Settings);
|
src/containers/NotFound/NotFound.js
|
micooz/react-redux-universal-hot-example
|
import React from 'react';
export default function NotFound() {
return (
<div className="container">
<h1>Doh! 404!</h1>
<p>These are <em>not</em> the droids you are looking for!</p>
</div>
);
}
|
actor-apps/app-web/src/app/components/activity/UserProfile.react.js
|
gale320/actor-platform
|
import _ from 'lodash';
import React from 'react';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import classnames from 'classnames';
import ContactActionCreators from 'actions/ContactActionCreators';
import DialogActionCreators from 'actions/DialogActionCreators';
import PeerStore from 'stores/PeerStore';
import DialogStore from 'stores/DialogStore';
import AvatarItem from 'components/common/AvatarItem.react';
//import UserProfileContactInfo from 'components/activity/UserProfileContactInfo.react';
import Fold from 'components/common/Fold.React';
const getStateFromStores = (userId) => {
const thisPeer = PeerStore.getUserPeer(userId);
return {
thisPeer: thisPeer,
isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer)
};
};
@ReactMixin.decorate(IntlMixin)
class UserProfile extends React.Component {
static propTypes = {
user: React.PropTypes.object.isRequired
};
constructor(props) {
super(props);
this.state = _.assign({
isActionsDropdownOpen: false
}, getStateFromStores(props.user.id));
DialogStore.addNotificationsListener(this.onChange);
}
componentWillUnmount() {
DialogStore.removeNotificationsListener(this.onChange);
}
componentWillReceiveProps(newProps) {
this.setState(getStateFromStores(newProps.user.id));
}
addToContacts = () => {
ContactActionCreators.addContact(this.props.user.id);
};
removeFromContacts =() => {
ContactActionCreators.removeContact(this.props.user.id);
};
onNotificationChange = (event) => {
DialogActionCreators.changeNotificationsEnabled(this.state.thisPeer, event.target.checked);
};
onChange = () => {
this.setState(getStateFromStores(this.props.user.id));
};
toggleActionsDropdown = () => {
const isActionsDropdownOpen = this.state.isActionsDropdownOpen;
if (!isActionsDropdownOpen) {
this.setState({isActionsDropdownOpen: true});
document.addEventListener('click', this.closeActionsDropdown, false);
} else {
this.closeActionsDropdown();
}
};
closeActionsDropdown = () => {
this.setState({isActionsDropdownOpen: false});
document.removeEventListener('click', this.closeActionsDropdown, false);
};
render() {
const user = this.props.user;
const isNotificationsEnabled = this.state.isNotificationsEnabled;
let actions;
if (user.isContact === false) {
actions = (
<li className="dropdown__menu__item" onClick={this.addToContacts}>
<FormattedMessage message={this.getIntlMessage('addToContacts')}/>
</li>
);
} else {
actions = (
<li className="dropdown__menu__item" onClick={this.removeFromContacts}>
<FormattedMessage message={this.getIntlMessage('removeFromContacts')}/>
</li>
);
}
let dropdownClassNames = classnames('dropdown pull-left', {
'dropdown--opened': this.state.isActionsDropdownOpen
});
// Mock
const nickname = '@username';
const email = 'username@domain.com';
return (
<div className="activity__body user_profile">
<ul className="profile__list">
<li className="profile__list__item user_profile__meta">
<header>
<AvatarItem image={user.bigAvatar}
placeholder={user.placeholder}
size="big"
title={user.name}/>
<h3 className="user_profile__meta__title">{user.name}</h3>
<div className="user_profile__meta__presence">{user.presence}</div>
</header>
<footer>
<div className={dropdownClassNames}>
<button className="dropdown__button button button--light-blue" onClick={this.toggleActionsDropdown}>
<i className="material-icons">more_horiz</i>
<FormattedMessage message={this.getIntlMessage('actions')}/>
</button>
<ul className="dropdown__menu dropdown__menu--left">
{actions}
</ul>
</div>
</footer>
</li>
<li className="profile__list__item user_profile__contact_info no-p">
<ul className="user_profile__contact_info__list">
<li className="hide">
<svg className="icon icon--pink"
dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#username"/>'}}/>
<span className="title">{nickname}</span>
<span className="description">nickname</span>
</li>
<li>
<i className="material-icons icon icon--green">call</i>
<span className="title">{'+' + user.phones[0].number}</span>
<span className="description">mobile</span>
</li>
<li className="hide">
<i className="material-icons icon icon--blue">mail</i>
<span className="title">{email}</span>
<span className="description">email</span>
</li>
</ul>
</li>
<li className="profile__list__item user_profile__media no-p hide">
<Fold icon="attach_file" iconClassName="icon--gray" title={this.getIntlMessage('sharedMedia')}>
<ul>
<li><a>230 Shared Photos and Videos</a></li>
<li><a>49 Shared Links</a></li>
<li><a>49 Shared Files</a></li>
</ul>
</Fold>
</li>
<li className="profile__list__item user_profile__notifications no-p">
<label htmlFor="notifications">
<i className="material-icons icon icon--squash">notifications_none</i>
<FormattedMessage message={this.getIntlMessage('notifications')}/>
<div className="switch pull-right">
<input checked={isNotificationsEnabled}
id="notifications"
onChange={this.onNotificationChange}
type="checkbox"/>
<label htmlFor="notifications"></label>
</div>
</label>
</li>
</ul>
</div>
);
}
}
export default UserProfile;
|
information/blendle-frontend-react-source/app/modules/sectionsPage/components/PersonalPage/UpsellBanner/index.js
|
BramscoChill/BlendleParser
|
import React from 'react';
import PremiumBannerContainer from 'modules/item/containers/GetPremiumBannerContainer';
import CSS from './style.scss';
function UpsellBanner() {
return (
<div className={CSS.upsellBannerContainer}>
<PremiumBannerContainer
shouldCheckItemConditions={false}
shouldHideOnMobile={false}
analytics={{
internal_location: 'timeline/premium',
location_in_layout: 'sections',
}}
/>
</div>
);
}
export default UpsellBanner;
// WEBPACK FOOTER //
// ./src/js/app/modules/sectionsPage/components/PersonalPage/UpsellBanner/index.js
|
test/SplitButtonSpec.js
|
aparticka/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import SplitButton from '../src/SplitButton';
import MenuItem from '../src/MenuItem';
import Button from '../src/Button';
describe('SplitButton', function () {
let instance;
afterEach(function() {
if (instance && ReactTestUtils.isCompositeComponent(instance) && instance.isMounted()) {
React.unmountComponentAtNode(React.findDOMNode(instance));
}
});
it('Should render button correctly', function () {
instance = ReactTestUtils.renderIntoDocument(
<SplitButton title="Title">
<MenuItem eventKey="1">MenuItem 1 content</MenuItem>
<MenuItem eventKey="2">MenuItem 2 content</MenuItem>
</SplitButton>
);
let button = React.findDOMNode(instance.refs.button);
let dropdownButton = React.findDOMNode(instance.refs.dropdownButton);
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group\b/));
assert.ok(button.className.match(/\bbtn\b/));
assert.equal(button.nodeName, 'BUTTON');
assert.equal(button.type, 'button');
assert.ok(dropdownButton.className.match(/\bdropdown-toggle\b/));
assert.equal(button.innerText.trim(), 'Title');
assert.ok(dropdownButton.childNodes[0].className.match(/\bsr-only\b/));
assert.equal(dropdownButton.childNodes[0].innerText.trim(), 'Toggle dropdown');
assert.ok(dropdownButton.childNodes[1].className.match(/\bcaret\b/));
assert.equal(dropdownButton.childNodes[2].style.letterSpacing, '-0.3em');
assert.equal(dropdownButton.childNodes.length, 3);
});
it('Should render menu correctly', function () {
instance = ReactTestUtils.renderIntoDocument(
<SplitButton title="Title">
<MenuItem eventKey="1">MenuItem 1 content</MenuItem>
<MenuItem eventKey="2">MenuItem 2 content</MenuItem>
</SplitButton>
);
let menu = React.findDOMNode(instance.refs.menu);
assert.ok(menu.className.match(/\bdropdown-menu\b/));
assert.equal(menu.getAttribute('role'), 'menu');
assert.equal(menu.firstChild.nodeName, 'LI');
assert.equal(menu.firstChild.innerText, 'MenuItem 1 content');
assert.equal(menu.lastChild.nodeName, 'LI');
assert.equal(menu.lastChild.innerText, 'MenuItem 2 content');
});
it('Should pass dropdownTitle to dropdown button', function () {
let CustomTitle = React.createClass({ render() { return <span />; } });
instance = ReactTestUtils.renderIntoDocument(
<SplitButton title={<CustomTitle />} dropdownTitle={<CustomTitle />}>
<MenuItem eventKey="1">MenuItem 1 content</MenuItem>
<MenuItem eventKey="2">MenuItem 2 content</MenuItem>
</SplitButton>
);
assert.ok(ReactTestUtils.findRenderedComponentWithType(instance.refs.button, CustomTitle));
assert.ok(ReactTestUtils.findRenderedComponentWithType(instance.refs.dropdownButton, CustomTitle));
});
it('Should pass props to button', function () {
instance = ReactTestUtils.renderIntoDocument(
<SplitButton title="Title" bsStyle="primary">
<MenuItem eventKey="1">MenuItem 1 content</MenuItem>
<MenuItem eventKey="2">MenuItem 2 content</MenuItem>
</SplitButton>
);
let button = React.findDOMNode(instance.refs.button);
assert.ok(button.className.match(/\bbtn-primary\b/));
});
it('Should pass disabled to both buttons', function() {
instance = ReactTestUtils.renderIntoDocument(
<SplitButton title="Test" disabled={true}>
<MenuItem eventKey="1">MenuItem 1 content</MenuItem>
<MenuItem eventKey="2">MenuItem 2 content</MenuItem>
</SplitButton>
);
let button = React.findDOMNode(instance.refs.button);
assert.ok(button.disabled);
let dropdownButton = React.findDOMNode(instance.refs.dropdownButton);
assert.ok(dropdownButton.disabled);
});
it('Should pass id to button group', function () {
instance = ReactTestUtils.renderIntoDocument(
<SplitButton title="Title" bsStyle="primary" id="testId">
<MenuItem eventKey="1">MenuItem 1 content</MenuItem>
<MenuItem eventKey="2">MenuItem 2 content</MenuItem>
</SplitButton>
);
assert.equal(React.findDOMNode(instance).getAttribute('id'), 'testId');
});
it('Should be closed by default', function () {
instance = ReactTestUtils.renderIntoDocument(
<SplitButton title="Title">
<MenuItem eventKey="1">MenuItem 1 content</MenuItem>
<MenuItem eventKey="2">MenuItem 2 content</MenuItem>
</SplitButton>
);
assert.notOk(React.findDOMNode(instance).className.match(/\bopen\b/));
});
it('Should open when clicked', function () {
instance = ReactTestUtils.renderIntoDocument(
<SplitButton title="Title">
<MenuItem eventKey="1">MenuItem 1 content</MenuItem>
<MenuItem eventKey="2">MenuItem 2 content</MenuItem>
</SplitButton>
);
ReactTestUtils.SimulateNative.click(React.findDOMNode(instance.refs.dropdownButton));
assert.ok(React.findDOMNode(instance).className.match(/\bopen\b/));
});
it('should call onSelect with eventKey when MenuItem is clicked', function (done) {
function handleSelect(eventKey) {
assert.equal(eventKey, '2');
done();
}
instance = ReactTestUtils.renderIntoDocument(
<SplitButton title="Title" onSelect={handleSelect}>
<MenuItem eventKey='1'>MenuItem 1 content</MenuItem>
<MenuItem eventKey='2'>MenuItem 2 content</MenuItem>
</SplitButton>
);
let menuItems = ReactTestUtils.scryRenderedComponentsWithType(instance, MenuItem);
assert.equal(menuItems.length, 2);
ReactTestUtils.SimulateNative.click(
ReactTestUtils.findRenderedDOMComponentWithTag(menuItems[1], 'a')
);
});
it('Should have dropup class', function () {
instance = ReactTestUtils.renderIntoDocument(
<SplitButton title="Title" dropdownTitle="New title" dropup>
<MenuItem eventKey="1">MenuItem 1 content</MenuItem>
<MenuItem eventKey="2">MenuItem 2 content</MenuItem>
</SplitButton>
);
assert.ok(React.findDOMNode(instance).className.match(/\bdropup\b/));
});
it('Should pass pullRight prop to menu', function () {
instance = ReactTestUtils.renderIntoDocument(
<SplitButton title="Title" dropdownTitle="New title" pullRight>
<MenuItem eventKey="1">MenuItem 1 content</MenuItem>
<MenuItem eventKey="2">MenuItem 2 content</MenuItem>
</SplitButton>
);
assert.ok(instance.refs.menu.props.pullRight);
});
it('Should set target attribute on anchor', function () {
instance = ReactTestUtils.renderIntoDocument(
<SplitButton title="Title" dropdownTitle="New title" href="/some/unique-thing/" target="_blank">
<MenuItem eventKey="1">MenuItem 1 content</MenuItem>
</SplitButton>
);
let anchors = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'a');
assert.equal(anchors.length, 2);
let linkElement = React.findDOMNode(anchors[0]);
assert.equal(linkElement.target, '_blank');
});
it('Should call `onClick` with target attribute', function (done) {
function handleClick(key, href, target) {
assert.equal(target, '_blank');
done();
}
instance = ReactTestUtils.renderIntoDocument(
<SplitButton title="Title" dropdownTitle="New title" href="/some/unique-thing/" target="_blank" onClick={handleClick}>
<MenuItem eventKey="1">MenuItem 1 content</MenuItem>
</SplitButton>
);
let buttons = ReactTestUtils.scryRenderedComponentsWithType(instance, Button);
ReactTestUtils.Simulate.click(ReactTestUtils.findRenderedDOMComponentWithTag(buttons[0], 'a'));
});
describe('when open', function () {
beforeEach(function () {
instance = ReactTestUtils.renderIntoDocument(
<SplitButton title="Title">
<MenuItem eventKey={1}>MenuItem 1 content</MenuItem>
<MenuItem eventKey={2}>MenuItem 2 content</MenuItem>
</SplitButton>
);
instance.setDropdownState(true);
});
it('should close when button is clicked', function () {
let evt = document.createEvent('HTMLEvents');
evt.initEvent('click', true, true);
document.documentElement.dispatchEvent(evt);
assert.notOk(React.findDOMNode(instance).className.match(/\bopen\b/));
});
});
});
|
src/svg-icons/maps/local-dining.js
|
igorbt/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalDining = (props) => (
<SvgIcon {...props}>
<path d="M8.1 13.34l2.83-2.83L3.91 3.5c-1.56 1.56-1.56 4.09 0 5.66l4.19 4.18zm6.78-1.81c1.53.71 3.68.21 5.27-1.38 1.91-1.91 2.28-4.65.81-6.12-1.46-1.46-4.2-1.1-6.12.81-1.59 1.59-2.09 3.74-1.38 5.27L3.7 19.87l1.41 1.41L12 14.41l6.88 6.88 1.41-1.41L13.41 13l1.47-1.47z"/>
</SvgIcon>
);
MapsLocalDining = pure(MapsLocalDining);
MapsLocalDining.displayName = 'MapsLocalDining';
MapsLocalDining.muiName = 'SvgIcon';
export default MapsLocalDining;
|
step07o/src/index.js
|
panacloud/learn-react
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './containers/app/App';
import './index.css';
import store from './store'
import { Provider } from 'react-redux'
ReactDOM.render(
//Wraping up in Provider
<Provider store={store}>
<div>
<App/>
</div>
</Provider>
,
document.getElementById('root')
);
|
app/components/2_Users/AuthManager.js
|
shug0/Awesomidi
|
// CORE
import React, { Component } from 'react';
var { browserHistory } = require('react-router');
// Components
import LoginBox from './Auth/LoginBox';
class AuthManager extends Component {
constructor(){
super();
this.handleTwitterAuth = this.handleTwitterAuth.bind(this);
}
componentWillUpdate(nextProps, nextState) {
if (nextProps.isLogged === true) {
browserHistory.push('/');
}
}
handleTwitterAuth() {
let authHandler = function(error, user) {
this.props.newUserAuth(user);
};
this.props.base.authWithOAuthPopup('twitter', authHandler.bind(this));
}
render() {
return (
<LoginBox
twitterAuth={this.handleTwitterAuth}
/>
);
}
}
export default AuthManager;
|
scenes/change-account.js
|
APU-Flow/FlowApp
|
// change-account.js
// Flow
'use strict';
import React, { Component } from 'react';
import { StyleSheet, Text, Alert, View, TouchableHighlight } from 'react-native';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import ModalDropdown from 'react-native-modal-dropdown';
export default class ChangeAccount extends Component {
constructor(props) {
super(props);
// Initialize state variables
this.state = {
// TODO: Populate these with real data
switchableAccounts: ['Jim', 'Bill'],
settingsOptions: ['I', 'Am', 'Unsure', 'What', 'Should', 'Be', 'Here']
};
this.dropdownRenderRow = this.dropdownRenderRow.bind(this);
this.confirmDeleteAccount = this.confirmDeleteAccount.bind(this);
}
render() {
return (
<KeyboardAwareScrollView style={styles.container}>
<Text style={styles.title}>Change Account</Text>
<Text style={styles.text}>You're currently logged in as...</Text>
<ModalDropdown style={styles.dropdown}
options={this.state.switchableAccounts}
textStyle={styles.dropdownText}
dropdownStyle={styles.dropdownDropdown}
defaultValue='Switch to Which Account?'
renderRow={this.dropdownRenderRow}
/>
<ModalDropdown style={styles.dropdown}
options={this.state.settingsOptions}
textStyle={styles.dropdownText}
dropdownStyle={styles.dropdownDropdown}
defaultValue='Account Settings'
renderRow={this.dropdownRenderRow}
/>
<TouchableHighlight onPress={this.confirmDeleteAccount}>
<View style={styles.dropdown}>
<Text style={styles.dropdownText}>Delete My Account</Text>
</View>
</TouchableHighlight>
</KeyboardAwareScrollView>
);
}
dropdownRenderRow(rowData, rowID, highlighted) {
let evenRow = rowID % 2;
return (
<TouchableHighlight underlayColor='#6495ED'>
<View style={[styles.dropdownRow, {backgroundColor: evenRow ? '#87CEEB' : '#87CEFA'}]}>
<Text style={styles.dropdownRowText}>{rowData}</Text>
</View>
</TouchableHighlight>
);
}
confirmDeleteAccount() {
Alert.alert(
'Delete Account',
'Are you sure you want to delete your account?',
[
{text: 'Cancel', onPress: null, style: 'cancel' },
{text: 'Yes, Delete my account', onPress: null},
],
{ cancelable: false }
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'column',
flex: 1,
backgroundColor:'rgb(52,152,219)',
},
title: {
textAlign: 'center',
color: 'white',
marginTop: 25,
fontSize: 20,
fontWeight: '400',
marginBottom: 15
},
text: {
textAlign: 'center',
color: 'white',
marginTop: 5,
fontSize: 18,
fontWeight: '400',
marginBottom: 15
},
dropdown: {
margin: 8,
borderColor: 'rgb(31,58,147)',
backgroundColor: 'rgb(31,58,147)',
borderWidth: 1,
borderRadius: 1,
},
dropdownText: {
marginVertical: 10,
marginHorizontal: 6,
fontSize: 18,
color: 'white',
textAlign: 'center',
textAlignVertical: 'center',
},
dropdownDropdown: {
margin: 8,
width: 320,
height: 100,
borderColor: 'rgb(31,58,147)',
borderWidth: 2,
borderRadius: 3,
backgroundColor: 'rgb(31,58,147)',
},
dropdownRow: {
flexDirection: 'row',
height: 40,
alignItems: 'center',
backgroundColor: 'rgb(31,58,147)'
},
dropdownRowText: {
marginHorizontal: 4,
fontSize: 16,
color: 'white',
textAlignVertical: 'center',
textAlign: 'center',
}
});
|
src/svg-icons/social/sentiment-dissatisfied.js
|
rhaedes/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialSentimentDissatisfied = (props) => (
<SvgIcon {...props}>
<circle cx="15.5" cy="9.5" r="1.5"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm0-6c-2.33 0-4.32 1.45-5.12 3.5h1.67c.69-1.19 1.97-2 3.45-2s2.75.81 3.45 2h1.67c-.8-2.05-2.79-3.5-5.12-3.5z"/>
</SvgIcon>
);
SocialSentimentDissatisfied = pure(SocialSentimentDissatisfied);
SocialSentimentDissatisfied.displayName = 'SocialSentimentDissatisfied';
export default SocialSentimentDissatisfied;
|
lib/encoding/MultiBrowser.js
|
waynecraig/encoding-present
|
require('./sass/fullpage.sass');
import React, { Component } from 'react';
export default class Slide extends Component {
render() {
return (
<div className='fullpage'>
<h1>不同浏览器的区别</h1>
<p>待续...</p>
</div>
)
}
}
|
js/components/Header/4.js
|
YeisonGomez/RNAmanda
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Container, Header, Title, Content, Button, Icon, Left, Right, Body, Text } from 'native-base';
import { Actions } from 'react-native-router-flux';
import { actions } from 'react-native-navigation-redux-helpers';
import { openDrawer } from '../../actions/drawer';
import styles from './styles';
const {
popRoute,
} = actions;
class Header4 extends Component { // eslint-disable-line
static propTypes = {
openDrawer: React.PropTypes.func,
popRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
popRoute() {
this.props.popRoute(this.props.navigation.key);
}
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button transparent onPress={() => Actions.pop()}>
<Icon name="arrow-back" />
</Button>
</Left>
<Body>
<Title>Header</Title>
</Body>
<Right>
<Button transparent onPress={() => Actions.pop()}>
<Text>Cancel</Text>
</Button>
</Right>
</Header>
<Content padder>
<Text>
Header With Icon Button & Text Buttons
</Text>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
popRoute: key => dispatch(popRoute(key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
themeState: state.drawer.themeState,
});
export default connect(mapStateToProps, bindAction)(Header4);
|
imports/ui/NotFound.js
|
dandev237/short-lnk
|
/**
* Created by Daniel on 18/06/2017.
*/
import React from 'react';
import {Link} from 'react-router-dom';
export default () => {
return(
<div className="boxed-view">
<div className="boxed-view__box">
<h1>Page Not Found</h1>
<p>Hmmm, we're unable to find that page.</p>
<Link className="button button--link" to="/">HEAD HOME</Link>
</div>
</div>
);
}
|
src/js/components/settings/form/Profile.js
|
barumel/ultritium-radio-player
|
import React from 'react';
import { Form, FormGroup, FormControl, ControlLabel, InputGroup, Col, Button } from 'react-bootstrap';
export class SettingsFormProfile extends React.Component {
constructor() {
super();
}
render() {
const hidden = this.props.locked ? 'hidden' : '';
return(
<Form horizontal>
{ /* Username */ }
<FormGroup>
<Col componentClass={ControlLabel} sm={2}>
Username
</Col>
<Col sm={10}>
<InputGroup>
<InputGroup.Addon><i class="fa fa-users"></i></InputGroup.Addon>
<FormControl
type="text"
placeholder="Username"
disabled={this.props.locked}/>
</InputGroup>
</Col>
</FormGroup>
{ /* First name */ }
<FormGroup>
<Col componentClass={ControlLabel} sm={2}>
First name
</Col>
<Col sm={10}>
<InputGroup>
<InputGroup.Addon><i class="fa fa-user"></i></InputGroup.Addon>
<FormControl
type="text"
placeholder="First name"
disabled={this.props.locked}/>
</InputGroup>
</Col>
</FormGroup>
{ /* Name */ }
<FormGroup>
<Col componentClass={ControlLabel} sm={2}>
Name
</Col>
<Col sm={10}>
<InputGroup>
<InputGroup.Addon><i class="fa fa-user"></i></InputGroup.Addon>
<FormControl
type="text"
placeholder="Name"
disabled={this.props.locked}/>
</InputGroup>
</Col>
</FormGroup>
{ /* Name */ }
<FormGroup>
<Col componentClass={ControlLabel} sm={2}>
Email
</Col>
<Col sm={10}>
<InputGroup>
<InputGroup.Addon><i class="fa fa-envelope"></i></InputGroup.Addon>
<FormControl
type="text"
placeholder="Email"
disabled={this.props.locked}/>
</InputGroup>
</Col>
</FormGroup>
{ /* Password */ }
<FormGroup>
<Col componentClass={ControlLabel} sm={2}>
Password
</Col>
<Col sm={10}>
<InputGroup>
<InputGroup.Addon><i class="fa fa-key"></i></InputGroup.Addon>
<FormControl
type="text"
placeholder="Email"
disabled={this.props.locked}/>
</InputGroup>
</Col>
</FormGroup>
{ /* Password confirm */ }
<FormGroup>
<Col componentClass={ControlLabel} sm={2}>
Confirm Password
</Col>
<Col sm={10}>
<InputGroup>
<InputGroup.Addon><i class="fa fa-key"></i></InputGroup.Addon>
<FormControl
type="text"
placeholder="Confirm Email"
disabled={this.props.locked}/>
</InputGroup>
</Col>
</FormGroup>
<FormGroup>
<Col componentClass={ControlLabel} class={"btn-group btn-block " + hidden} sm={2}>
<Button bsStyle="success" bsSize="medium" block>Save</Button>
</Col>
<Col componentClass={ControlLabel} class={"btn-group btn-block " + hidden} sm={2}>
<Button bsStyle="warning" bsSize="medium" block>Cancel</Button>
</Col>
</FormGroup>
</Form>
);
}
}
|
src/js/components/catalog/app-catalog-item.js
|
rafaelkyrdan/flux-app
|
import React from 'react';
import AppStore from '../../stores/app-store';
import AppActions from '../../actions/app-actions';
import CartButton from '../cart/app-cart-button';
import StoreWatchMixin from '../../mixins/StoreWatchMixin';
import { Link } from 'react-router';
function getCatalogItem(props){
let item = AppStore.getCatalog().find( ({id}) => id === props.id);
return {item};
}
const CatalogItem = (props) => {
let itemStyle = {
borderBottom:'1px solid #ccc',
paddingBottom:'15px',
};
return (
<div className="col-xs-6 col-sm-4 col-md-3" style={itemStyle}>
<h4>{props.item.title}</h4>
<img src="http://placehold.it/250x250" width="100%" className="img-responsive"/>
<p>{props.item.summary}</p>
<p> $ {props.item.cost} <span className="text-success">
{props.item.qty && `(${props.item.qty} in the cart)`}</span>
</p>
<div className="btn-group">
<Link to={ `/item/${props.item.id}` } className="btn btn-default btn-sm">Learn more</Link>
<CartButton handler={ AppActions.addItem.bind(null, props.item)}
txt="Add to Cart" />
</div>
</div>
);
}
export default StoreWatchMixin( CatalogItem, getCatalogItem );
|
src/components/common/svg-icons/device/add-alarm.js
|
abzfarah/Pearson.NAPLAN.GnomeH
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceAddAlarm = (props) => (
<SvgIcon {...props}>
<path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm1-11h-2v3H8v2h3v3h2v-3h3v-2h-3V9z"/>
</SvgIcon>
);
DeviceAddAlarm = pure(DeviceAddAlarm);
DeviceAddAlarm.displayName = 'DeviceAddAlarm';
DeviceAddAlarm.muiName = 'SvgIcon';
export default DeviceAddAlarm;
|
src/server.js
|
webmasterkai/boiler
|
import Express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import config from './config';
import favicon from 'serve-favicon';
import compression from 'compression';
import httpProxy from 'http-proxy';
import path from 'path';
import createStore from './redux/create';
import ApiClient from './helpers/ApiClient';
import Html from './helpers/Html';
import PrettyError from 'pretty-error';
import http from 'http';
import SocketIo from 'socket.io';
import {ReduxRouter} from 'redux-router';
import createHistory from 'history/lib/createMemoryHistory';
import {reduxReactRouter, match} from 'redux-router/server';
import {Provider} from 'react-redux';
import qs from 'query-string';
import getRoutes from './routes';
import getStatusFromRoutes from './helpers/getStatusFromRoutes';
import defaultState from './defaultState';
const pretty = new PrettyError();
const app = new Express();
const server = new http.Server(app);
// Proxy our API server.
const proxy = httpProxy.createProxyServer({
target: 'http://localhost:' + config.apiPort,
ws: true, // activate websocket support.
});
app.use(compression());
app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico')));
app.use(require('serve-static')(path.join(__dirname, '..', 'static')));
// Proxy to API server
app.use('/api', (req, res) => {
proxy.web(req, res);
});
// added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527
proxy.on('error', (error, req, res) => {
let json;
if (error.code !== 'ECONNRESET') {
console.error('proxy error', error);
}
if (!res.headersSent) {
res.writeHead(500, {'content-type': 'application/json'});
}
json = {error: 'proxy_error', reason: error.message};
res.end(JSON.stringify(json));
});
app.use((req, res) => {
if (__DEVELOPMENT__) {
// Do not cache webpack stats: the script file would change since
// hot module replacement is enabled in the development env
webpackIsomorphicTools.refresh();
}
const client = new ApiClient(req);
const store = createStore(reduxReactRouter, getRoutes, createHistory, client, defaultState);
function hydrateOnClient() {
res.send('<!doctype html>\n' +
ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store}/>));
}
if (__DISABLE_SSR__) {
hydrateOnClient();
return;
}
store.dispatch(match(req.originalUrl, (error, redirectLocation, routerState) => {
if (redirectLocation) {
res.redirect(redirectLocation.pathname + redirectLocation.search);
} else if (error) {
console.error('ROUTER ERROR:', pretty.render(error));
res.status(500);
hydrateOnClient();
} else if (!routerState) {
res.status(500);
hydrateOnClient();
} else {
// Workaround redux-router query string issue:
// https://github.com/rackt/redux-router/issues/106
if (routerState.location.search && !routerState.location.query) {
routerState.location.query = qs.parse(routerState.location.search);
}
store.getState().router.then(() => {
const component = (
<Provider store={store} key="provider">
<ReduxRouter/>
</Provider>
);
const status = getStatusFromRoutes(routerState.routes);
if (status) {
res.status(status);
}
res.send('<!doctype html>\n' +
ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>));
}).catch((err) => {
console.error('DATA FETCHING ERROR:', pretty.render(err));
res.status(500);
hydrateOnClient();
});
}
}));
});
if (config.port) {
if (config.isProduction) {
const io = new SocketIo(server);
io.path('/api/ws');
}
server.listen(config.port, (err) => {
if (err) {
console.error(err);
}
console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.name, config.apiPort);
console.info('==> 💻 Open http://localhost:%s in a browser to view the app.', config.port);
});
} else {
console.error('==> ERROR: No PORT environment variable has been specified');
}
|
src/App.js
|
aquiladev/browniecoin
|
import React, { Component } from 'react';
import Wallet from './Wallet'
class App extends Component {
render() {
return (
<div className="App">
<Wallet />
</div>
);
}
}
export default App;
|
admin/client/App/shared/FlashMessages.js
|
frontyard/keystone
|
/**
* Render a few flash messages, e.g. errors, success messages, warnings,...
*
* Use like this:
* <FlashMessages
* messages={{
* error: [{
* title: 'There is a network problem',
* detail: 'Please try again later...',
* }],
* }}
* />
*
* Instead of error, it can also be hilight, info, success or warning
*/
import React from 'react';
import _ from 'lodash';
import FlashMessage from './FlashMessage';
var FlashMessages = React.createClass({
displayName: 'FlashMessages',
propTypes: {
messages: React.PropTypes.oneOfType([
React.PropTypes.bool,
React.PropTypes.shape({
error: React.PropTypes.array,
hilight: React.PropTypes.array,
info: React.PropTypes.array,
success: React.PropTypes.array,
warning: React.PropTypes.array,
}),
]),
},
// Render messages by their type
renderMessages (messages, type) {
if (!messages || !messages.length) return null;
return messages.map((message, i) => {
return <FlashMessage message={message} type={type} key={`i${i}`} />;
});
},
// Render the individual messages based on their type
renderTypes (types) {
return Object.keys(types).map(type => this.renderMessages(types[type], type));
},
render () {
if (!this.props.messages) return null;
return (
<div className="flash-messages">
{_.isPlainObject(this.props.messages) && this.renderTypes(this.props.messages)}
</div>
);
},
});
module.exports = FlashMessages;
|
src/routes/NotFound/NotFound.js
|
Xvakin/quiz
|
import React from 'react'
export default function NotFound() {
return (
<div className="container">
<h1>Doh! 404!</h1>
<p>These are <em>not</em> the droids you are looking for!</p>
</div>
)
}
|
pages/articles/client.js
|
hschlichter/react-redux-pages-demo
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from '../../shared/store/clientstore';
import reducers from './reducers';
import Layout from './components/layout';
const store = configureStore(reducers, context.state);
if (typeof window !== 'undefined') {
window.onload = function() {
ReactDOM.render(
<Provider store={store}>
<Layout articleId={context.params.id}/>
</Provider>,
document.getElementById('main')
);
};
}
|
client-src/components/category/list/compare/ComparePaneClearButton.js
|
minimus/final-task
|
import React from 'react'
import classNames from 'classnames'
import propTypes from 'prop-types'
export default function ComparePaneClearButton({ disabled, onClick }) {
const buttonClass = (disabled) ? 'disabled' : ''
return (
<button className={classNames(buttonClass, 'compare-clear-button')} onClick={onClick}>
<i className="material-icons md-48">delete_forever</i>
</button>
)
}
ComparePaneClearButton.propTypes = {
disabled: propTypes.bool.isRequired,
onClick: propTypes.func.isRequired,
}
|
frontend/react/index.js
|
kamyarg/payments-frontend
|
import React from 'react';
import ReactDOM from 'react-dom';
import PaymentsInspectionComp from './PaymentsInspectionComp';
ReactDOM.render(
<PaymentsInspectionComp />,
document.getElementById('payment-div')
);
|
internals/templates/app.js
|
Frai/Events
|
/**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
// Needed for redux-saga es6 generator support
import 'babel-polyfill';
// 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 'sanitize.css/sanitize.css';
// Import root app
import App from 'containers/App';
// Import selector for `syncHistoryWithStore`
import { makeSelectLocationState } from 'containers/App/selectors';
// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';
// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-unresolved, import/extensions */
import '!file-loader?name=[name].[ext]!./favicon.ico';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */
import configureStore from './store';
// Import i18n messages
import { translationMessages } from './i18n';
// Import CSS reset and Global Styles
import './global-styles';
// Import root routes
import createRoutes from './routes';
// 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);
// 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
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: makeSelectLocationState(),
});
// Set up the router, wrapping all Routes in the App component
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
};
const render = (messages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={messages}>
<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) {
(new Promise((resolve) => {
resolve(import('intl'));
}))
.then(() => Promise.all([
import('intl/locale-data/jsonp/en.js'),
]))
.then(() => render(translationMessages))
.catch((err) => {
throw err;
});
} 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
if (process.env.NODE_ENV === 'production') {
require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
|
packages/react-jsx-highcharts/test/components/AxisProvider/index.spec.js
|
AlexMayants/react-jsx-highcharts
|
import React, { Component } from 'react';
import { mount } from 'enzyme';
import provideAxis from '../../../src/components/AxisProvider';
import { createMockChart, createMockAxis } from '../../test-utils';
const WrappedComponent = props => (
<div />
);
const AxisWrappedComponent = provideAxis(WrappedComponent);
describe('<AxisProvider />', function () {
beforeEach(function () {
this.axis = createMockAxis();
this.chart = createMockChart();
this.chart.get.withArgs('myAxisId').returns(this.axis);
this.context = {
chart: this.chart
};
});
describe('provided prop functions', function () {
beforeEach(function () {
this.axis.update.withArgs({ prop: 'Test9876' }).returns('update method mock');
this.axis.remove.withArgs({ prop: 'Test1234' }).returns('remove method mock');
this.axis.addPlotBand.withArgs({ prop: 'Test4567' }).returns('addPlotBand method mock');
this.axis.removePlotBand.withArgs({ prop: 'Test7654' }).returns('removePlotBand method mock');
this.axis.addPlotLine.withArgs({ prop: 'Test4444' }).returns('addPlotLine method mock');
this.axis.removePlotLine.withArgs({ prop: 'Test5555' }).returns('removePlotLine method mock');
this.axis.getExtremes.withArgs({ prop: 'Test6666' }).returns('getExtremes method mock');
this.axis.setExtremes.withArgs({ prop: 'Test7777' }).returns('setExtremes method mock');
});
it('should pass the `update` function of the axis to the wrapped component', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().update({ prop: 'Test9876' })).to.eql('update method mock');
});
it('should pass the `remove` function of the axis to the wrapped component', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().remove({ prop: 'Test1234' })).to.eql('remove method mock');
});
it('should pass the `addPlotBand` function of the axis to the wrapped component', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().addPlotBand({ prop: 'Test4567' })).to.eql('addPlotBand method mock');
});
it('should pass the `removePlotBand` function of the axis to the wrapped component', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().removePlotBand({ prop: 'Test7654' })).to.eql('removePlotBand method mock');
});
it('should pass the `addPlotLine` function of the axis to the wrapped component', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().addPlotLine({ prop: 'Test4444' })).to.eql('addPlotLine method mock');
});
it('should pass the `removePlotLine` function of the axis to the wrapped component', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().removePlotLine({ prop: 'Test5555' })).to.eql('removePlotLine method mock');
});
it('should pass the `getExtremes` function of the axis to the wrapped component', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().getExtremes({ prop: 'Test6666' })).to.eql('getExtremes method mock');
});
it('should pass the `setExtremes` function of the axis to the wrapped component', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().setExtremes({ prop: 'Test7777' })).to.eql('setExtremes method mock');
});
it('should pass the `getAxis` helper function to the wrapped component', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().getAxis()).to.eql(this.axis);
});
it('should pass all other props through to the WrappedComponent', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" prop1="bob" prop264="dave" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().prop1).to.eql('bob');
expect(wrapper.props().prop264).to.eql('dave');
});
});
describe('properly scoped prop functions', function () {
beforeEach(function () {
this.axis.update.withArgs({ prop: 'Test9876' }).returnsThis();
this.axis.remove.withArgs({ prop: 'Test1234' }).returnsThis();
this.axis.addPlotBand.withArgs({ prop: 'Test4567' }).returnsThis();
this.axis.removePlotBand.withArgs({ prop: 'Test7654' }).returnsThis();
this.axis.addPlotLine.withArgs({ prop: 'Test4444' }).returnsThis();
this.axis.removePlotLine.withArgs({ prop: 'Test5555' }).returnsThis();
this.axis.getExtremes.withArgs({ prop: 'Test6666' }).returnsThis();
this.axis.setExtremes.withArgs({ prop: 'Test7777' }).returnsThis();
});
it('the scope of the `update` function should be bound to the axis', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().update({ prop: 'Test9876' })).to.eql(this.axis);
});
it('the scope of the `remove` function should be bound to the axis', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().remove({ prop: 'Test1234' })).to.eql(this.axis);
});
it('the scope of the `addPlotBand` function should be bound to the axis', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().addPlotBand({ prop: 'Test4567' })).to.eql(this.axis);
});
it('the scope of the `removePlotBand` function should be bound to the axis', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().removePlotBand({ prop: 'Test7654' })).to.eql(this.axis);
});
it('the scope of the `addPlotLine` function should be bound to the axis', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().addPlotLine({ prop: 'Test4444' })).to.eql(this.axis);
});
it('the scope of the `removePlotLine` function should be bound to the axis', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().removePlotLine({ prop: 'Test5555' })).to.eql(this.axis);
});
it('the scope of the `getExtremes` function should be bound to the axis', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().getExtremes({ prop: 'Test6666' })).to.eql(this.axis);
});
it('the scope of the `setExtremes` function should be bound to the axis', function () {
const wrapper = mount(<AxisWrappedComponent axisId="myAxisId" />, {context: this.context}).find(WrappedComponent);
expect(wrapper.props().setExtremes({ prop: 'Test7777' })).to.eql(this.axis);
});
});
});
|
app/javascript/mastodon/features/notifications/components/setting_toggle.js
|
SerCom-KC/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Toggle from 'react-toggle';
export default class SettingToggle extends React.PureComponent {
static propTypes = {
prefix: PropTypes.string,
settings: ImmutablePropTypes.map.isRequired,
settingPath: PropTypes.array.isRequired,
label: PropTypes.node.isRequired,
meta: PropTypes.node,
onChange: PropTypes.func.isRequired,
}
onChange = ({ target }) => {
this.props.onChange(this.props.settingPath, target.checked);
}
render () {
const { prefix, settings, settingPath, label, meta } = this.props;
const id = ['setting-toggle', prefix, ...settingPath].filter(Boolean).join('-');
return (
<div className='setting-toggle'>
<Toggle id={id} checked={settings.getIn(settingPath)} onChange={this.onChange} onKeyDown={this.onKeyDown} />
<label htmlFor={id} className='setting-toggle__label'>{label}</label>
{meta && <span className='setting-meta__label'>{meta}</span>}
</div>
);
}
}
|
client/modules/List/pages/ListDetailPage.js
|
jeojoe/emplist
|
import React, { Component } from 'react';
import { Link, withRouter } from 'react-router';
import moment from 'moment';
import callApi from '../../../util/apiCaller';
import AdminHeader from '../../Admin/components/AdminHeader';
import { LoaderWithText } from '../../App/components/Loader';
import s from './ListDetailPage.css';
import sSkill from '../components/ListItem.css';
import { getToken } from '../../Admin/authToken';
// import HeaderText from '../components/HeaderText';
class ListDetailPage extends Component {
constructor(props) {
super(props);
this.state = {
list: null,
err: null,
};
}
componentDidMount() {
const id = this.props.params.id;
const { pathname } = this.props.location;
const isAdmin = pathname.indexOf('/admin/request/') >= 0;
if (!isAdmin) {
callApi(`/list/${id}`, 'get').then((res, err) => {
if (err) {
this.setState({ err });
} else {
const list = res.list;
if (list) {
this.setState({ list });
} else {
this.setState({ err: 'List not found.' });
}
}
});
} else {
const token = getToken();
if (!token) {
alert('No token.');
return;
}
callApi(`/requests/${id}?token=${token}`, 'get').then((res, err) => {
if (err) {
this.setState({ err });
} else {
const list = res.data;
if (list) {
this.setState({ list });
} else {
this.setState({ err: 'List not found.' });
}
}
});
}
}
renderList(list) {
const {
company_image,
company_name,
company_location,
skills,
salary,
details,
how_to_apply,
updated_at,
} = list;
const Tags = skills.map((skill, i) => <span className={sSkill.skill} key={i}>{skill}</span>);
const Location = `${company_location.city}, ${company_location.country}`;
const LocationDetail = company_location.detail;
const formatCurrency = (num) => parseInt(num, 10).toLocaleString();
const Salary = salary.max === 9999999 ? 'Unspecified' : `${formatCurrency(salary.min)} - ${formatCurrency(salary.max)} THB`;
return (
<div id={s.content}>
<div className={s.companyWrapper}>
<div className={s.companyNameWrapper}>
<img src={company_image} alt={`${company_name}'s logo`} />
<span>{company_name}</span>
</div>
<div className={s.companyDetailRow}>
<strong>Location : </strong> {Location} <span className={s.subDetail}>({LocationDetail})</span>
</div>
<div className={s.companyDetailRow}>
<strong>Skills Wanted : </strong> {Tags}
</div>
<div className={s.companyDetailRow}>
<strong>Salary Offered : </strong> {Salary}
{/*
FOR AUNNNNN
if company didn't insert salary detail i made default min, max salary to 0 and 9999999 respectively (for analytic purpose). So if you need to check whether company has specified salary or not you need to check max salary is equal to 9999999 or not.
*/}
</div>
</div>
<div id={s.detailWrapper}>
<div dangerouslySetInnerHTML={{ __html: details }} />
</div>
<div className={s.howWrapper}>
<h5>How to apply</h5>
<p>{how_to_apply}</p>
</div>
<div>
<p>Updated: {moment(updated_at).fromNow()}</p>
</div>
</div>
);
}
render() {
const { list, err } = this.state;
if (!list) {
return (
<div className="container">
{err ? <div>{err}</div> : <LoaderWithText text="Loading" centerInPage />}
</div>
);
}
const { location: { pathname }, params: { id } } = this.props;
const isAdmin = pathname.indexOf('/admin/request/') >= 0;
return (
<div className="container">
<div>
{isAdmin ?
<AdminHeader list={list} /> : ''
}
<div id={s.titleWrapper}>
<h4 className={s.title}>{list.title}</h4>
</div>
<div id={s.wrapper}>
{this.renderList(list)}
{
!isAdmin &&
<Link to={`/el/${id}/auth`}>
Manage
</Link>
}
<div className={s.divider} />
<sub style={{ color: '#999' }}>All jobs on this site disregard of gender, age, ethnic and disability.</sub>
</div>
</div>
</div>
);
}
}
ListDetailPage.propTypes = {
params: React.PropTypes.object.isRequired,
};
export default withRouter(ListDetailPage);
|
app/src/components/plugins/MenuItem/index.js
|
ouxu/NEUQ-OJ
|
/**
* Created by out_xu on 17/3/19.
*/
import React from 'react'
import { Icon, Menu, Tooltip } from 'antd'
import { Link } from 'react-router'
const MenuItem = {
normal: [
<Menu.Item key={'homepage'}>
<Link to='/homepage' className='showitem'>
<span className='nav-text'><Icon type='home' /> 首页</span>
</Link>
<Link to='/homepage' className='hideitem'>
<Tooltip placement='right' title='首页'>
<span className='sidericon'><Icon type='home' /></span>
</Tooltip>
</Link>
</Menu.Item>,
<Menu.Item key={'problems'}>
<Link to='/problems' className='showitem'>
<span className='nav-text'><Icon type='bars' /> 问题</span>
</Link>
<Link to='/problems' className='hideitem'>
<Tooltip placement='right' title='问题'>
<span className='sidericon'><Icon type='bars' /></span>
</Tooltip>
</Link>
</Menu.Item>,
<Menu.Item key={'contests'}>
<Link to='/contests' className='showitem'>
<span className='nav-text'><Icon type='smile' /> 竞赛&作业</span>
</Link>
<Link to='/contests' className='hideitem'>
<Tooltip placement='right' title='竞赛&作业'>
<span className='sidericon'><Icon type='smile' /></span>
</Tooltip>
</Link>
</Menu.Item>,
<Menu.Item key={'status'}>
<Link to='/status' className='showitem'>
<span className='nav-text'><Icon type='clock-circle' /> 状态</span>
</Link>
<Link to='/status' className='hideitem'>
<Tooltip placement='right' title='状态'>
<span className='sidericon'><Icon type='clock-circle' /></span>
</Tooltip>
</Link>
</Menu.Item>,
<Menu.Item key={'ranklist'}>
<Link to='/ranklist' className='showitem'>
<span className='nav-text'><Icon type='area-chart' /> 排名</span>
</Link>
<Link to='/ranklist' className='hideitem'>
<Tooltip placement='right' title='排名'>
<span className='sidericon'><Icon type='area-chart' /></span>
</Tooltip>
</Link>
</Menu.Item>
],
admin: []
}
export default item => MenuItem[item]
|
pages/join.js
|
aunnnn/open-ideas
|
import React, { Component } from 'react';
import Router from 'next/router'
import { Router as CustomRouter } from '../routes'
import { connect } from 'react-redux';
import { graphql, gql, compose } from 'react-apollo'
import Head from 'next/head'
import { loggedIn } from '../lib/authActions'
import Page from '../layouts/main'
import withData from '../lib/withData'
import { logEvent } from '../lib/analytics'
class LoginPage extends Component {
static async getInitialProps({ asPath }) {
// Either user comes throguh '/join' or '/login'
return {
isInitialLoginMode: asPath === '/login'
}
}
constructor(props) {
super(props)
this.state = {
loginMode: props.isInitialLoginMode ? true : false,
email: '',
password: '',
username: '',
loading: false,
}
}
onConfirm = async (e) => {
e.preventDefault()
this.setState({
loading: true
})
try {
if (this.state.loginMode) {
const { email, password } = this.state
const result = await this.props.signinUserMutation({
variables: {
email,
password
}
})
const _id = result.data.authenticateUser.id
const _token = result.data.authenticateUser.token
const _username = result.data.authenticateUser.username
this._saveUserDataToStore(_token, _id, _username)
} else {
const { username, email, password } = this.state
const result = await this.props.createUserMutation({
variables: {
username,
email,
password
}
})
// const _id = result.data.signupUser.id
// const _token = result.data.signupUser.token
// const _username = result.data.signupUser.username
// this._saveUserDataToStore(_token, _id, _username)
alert('👋 Successfully created account. Please check your email and click on the confirmation link.')
}
Router.push({
pathname: '/'
})
} catch(err) {
alert("Oops: " + (
err.graphQLErrors
&& err.graphQLErrors.length >= 1
&& (err.graphQLErrors[0].functionError || err.graphQLErrors[0].message))
|| err);
this.setState({
loading: false
})
}
}
_saveUserDataToStore = (token, id, username) => {
this.props.onLoggedIn(token, id, username)
}
render() {
const pageTitle = this.state.loginMode ? 'Login' : 'Sign Up'
const confirmDisabled = !this.state.email || !this.state.password || (!this.state.loginMode && !this.state.username)
return (
<Page>
<Head>
<title>{pageTitle}</title>
</Head>
<div className="main">
<h1>{pageTitle}</h1>
<form onSubmit={confirmDisabled ? null : this.onConfirm}>
<br />
{/* If sign up mode */
!this.state.loginMode &&
<input
value={this.state.username}
onChange={(e) => this.setState({ username: e.target.value })}
type="text"
placeholder="username"
/>
}
<input
value={this.state.email}
onChange={(e) => this.setState({ email: e.target.value })}
type="email"
placeholder="email address"
/>
<input
value={this.state.password}
onChange={(e) => this.setState({ password: e.target.value })}
type="password"
placeholder={this.state.loginMode ? 'Your password' : 'Choose a safe password'}
/>
{!this.state.loading ?
<div>
<button
type="submit"
className="primary-button"
disabled={confirmDisabled}
>
{this.state.loginMode ? 'login' : 'create account'}
</button>
<div
className="change-mode-button"
onClick={() => {
logEvent('Join', this.state.loginMode ? 'Signup' : 'Login')
const nextPath = this.state.loginMode ? '/join' : '/login'
CustomRouter.pushRoute(nextPath)
this.setState({ loginMode: !this.state.loginMode })
}}
>
{this.state.loginMode ? 'need to create an account?' : 'already have an account?' }
</div>
</div>
:
<div>
👀
</div>
}
</form>
</div>
<style jsx>{`
.main {
margin: 8px;
}
.main input {
display: block;
margin: 8px 0;
}
.change-mode-button {
cursor: pointer;
margin-top: 20px;
font-size: 16px;
color: blue;
}
`}</style>
</Page>)
}
}
const CREATE_USER_MUTATION = gql`
mutation CreateUserMutation($username: String!, $email: String!, $password: String!) {
signupUser(
email: $email,
password: $password,
username: $username,
) {
id
}
}
`
const SIGNIN_USER_MUTATION = gql`
mutation SigninUserMutation($email: String!, $password: String!) {
authenticateUser(
email: $email,
password: $password
) {
token
id
username
}
}
`
const LoginPageWithState = connect(
null,
(dispatch) => ({
onLoggedIn(token, id, username) {
dispatch(loggedIn(token, id, username))
}
})
)(LoginPage)
export default withData(compose(
graphql(SIGNIN_USER_MUTATION, { name: 'signinUserMutation'}),
graphql(CREATE_USER_MUTATION, { name: 'createUserMutation'}),
)(LoginPageWithState))
|
src/components/Radial.react.js
|
hypriot/kitematic
|
import React from 'react';
import classNames from 'classnames';
var Radial = React.createClass({
render: function () {
var percentage;
if ((this.props.progress !== null && this.props.progress !== undefined) && !this.props.spin && !this.props.error) {
percentage = (
<div className="percentage"></div>
);
} else {
percentage = <div></div>;
}
var classes = classNames({
'radial-progress': true,
'radial-spinner': this.props.spin,
'radial-negative': this.props.error,
'radial-thick': this.props.thick || false,
'radial-gray': this.props.gray || false,
'radial-transparent': this.props.transparent || false
});
return (
<div className={classes} data-progress={this.props.progress}>
<div className="circle">
<div className="mask full">
<div className="fill"></div>
</div>
<div className="mask half">
<div className="fill"></div>
<div className="fill fix"></div>
</div>
<div className="shadow"></div>
</div>
<div className="inset">
{percentage}
</div>
</div>
);
}
});
module.exports = Radial;
|
components/__tests__/Tooltip-tests.js
|
hellobrian/carbon-components-react
|
import React from 'react';
import Icon from '../Icon';
import FloatingMenu from '../../internal/FloatingMenu';
import Tooltip from '../Tooltip';
import { mount } from 'enzyme';
describe('Tooltip', () => {
describe('Renders as expected with defaults', () => {
const wrapper = mount(
<Tooltip triggerText="Tooltip">
<p className="bx--tooltip__label">Tooltip label</p>
<p>Lorem ipsum dolor sit amet</p>
</Tooltip>
);
const trigger = wrapper.find('.bx--tooltip__trigger');
describe('tooltip trigger', () => {
it('renders a tooltip container', () => {
expect(trigger.length).toEqual(1);
});
it('renders the info icon', () => {
const icon = trigger.find(Icon);
expect(icon.length).toBe(1);
expect(icon.props().name).toBe('info--glyph');
});
});
});
describe('Renders as expected with specified properties', () => {
const wrapper = mount(
<Tooltip triggerText="Tooltip" direction="bottom" showIcon={false}>
<p className="bx--tooltip__label">Tooltip label</p>
<p>Lorem ipsum dolor sit amet</p>
</Tooltip>
);
const trigger = wrapper.find('.bx--tooltip__trigger');
const floatingMenu = wrapper.find(FloatingMenu);
describe('tooltip container', () => {
it("sets the tooltip's position", () => {
expect(floatingMenu.prop('menuDirection')).toEqual('bottom');
});
it('does not render info icon', () => {
const icon = trigger.find(Icon);
expect(icon.exists()).toBe(false);
});
});
});
describe('events', () => {
it('hover changes state', () => {
const wrapper = mount(
<Tooltip triggerText="Tooltip">
<p className="bx--tooltip__label">Tooltip label</p>
<p>Lorem ipsum dolor sit amet</p>
</Tooltip>
);
const icon = wrapper.find(Icon);
icon.simulate('mouseover');
expect(wrapper.state().open).toEqual(true);
icon.simulate('mouseout');
expect(wrapper.state().open).toEqual(false);
});
});
});
|
src/components/chart.js
|
frandm182/reactReduxWeather
|
import React, { Component } from 'react';
import { Sparklines, SparklinesLine, SparklinesReferenceLine } from 'react-sparklines';
import _ from 'lodash';
function average(data) {
return _.round(_.sum(data)/data.length);
}
export default (props) => {
return (
<div>
<Sparklines height={120} width={180} data={props.data}>
<SparklinesLine color={props.color} />
<SparklinesReferenceLine type="avg" />
</Sparklines>
<div>{average(props.data)} {props.units}</div>
</div>
);
}
|
lib/Loading/stories/LoadingPane.story.js
|
folio-org/stripes-components
|
import React from 'react';
import Paneset from '../../Paneset';
import LoadingPane from '../LoadingPane';
export default () => (
<Paneset>
<LoadingPane paneTitle="Loading pane" />
</Paneset>
);
|
client/src/lib/i18n.js
|
andris9/mailtrain
|
'use strict';
import React from 'react';
import * as ri18n from 'react-i18next';
import {I18nextProvider} from 'react-i18next';
import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import mailtrainConfig from 'mailtrainConfig';
import moment from 'moment';
import {convertToFake, getLang} from '../../../shared/langs';
import {createComponentMixin} from "./decorator-helpers";
import lang_en_US_common from "../../../locales/en-US/common";
import lang_es_ES_common from "../../../locales/es-ES/common";
import lang_pt_BR_common from "../../../locales/pt-BR/common";
import lang_de_DE_common from "../../../locales/de-DE/common";
import lang_fr_FR_common from "../../../locales/fr-FR/common";
import lang_ru_RU_common from "../../../locales/ru-RU/common";
const resourcesCommon = {
'en-US': lang_en_US_common,
'es-ES': lang_es_ES_common,
'pt-BR': lang_pt_BR_common,
'de-DE': lang_de_DE_common,
'fr-FR': lang_fr_FR_common,
'ru_RU': lang_ru_RU_common,
'fk-FK': convertToFake(lang_en_US_common)
};
const resources = {};
for (const lng of mailtrainConfig.enabledLanguages) {
const langDesc = getLang(lng);
resources[langDesc.longCode] = {
common: resourcesCommon[langDesc.longCode]
};
}
i18n
.use(LanguageDetector)
.init({
resources,
fallbackLng: mailtrainConfig.defaultLanguage,
defaultNS: 'common',
interpolation: {
escapeValue: false // not needed for react
},
react: {
wait: true
},
detection: {
order: ['querystring', 'cookie', 'localStorage', 'navigator'],
lookupQuerystring: 'locale',
lookupCookie: 'i18nextLng',
lookupLocalStorage: 'i18nextLng',
caches: ['localStorage', 'cookie']
},
whitelist: mailtrainConfig.enabledLanguages,
load: 'currentOnly',
debug: false
});
// Show moment text in selected language
moment.locale(i18n.language);
export default i18n;
export const TranslationContext = React.createContext(null);
export const withTranslation = createComponentMixin({
contexts: [{context: TranslationContext, propName: 't'}]
});
const TranslationContextProvider = ri18n.withTranslation()(props => {
return (
<TranslationContext.Provider value={props.t}>
{props.children}
</TranslationContext.Provider>
);
});
export function TranslationRoot(props) {
return (
<I18nextProvider i18n={ i18n }>
<TranslationContextProvider>
{props.children}
</TranslationContextProvider>
</I18nextProvider>
);
}
export function tMark(key) {
return key;
}
|
clients/packages/admin-client/src/intl/helpers/shallow-with-intl.js
|
nossas/bonde-client
|
//
// For reference see: https://github.com/yahoo/react-intl/wiki/Testing-with-React-Intl#enzyme
//
import React from 'react';
import { IntlProvider } from 'react-intl';
import { shallow } from 'enzyme';
import pt from '../../intl/locale-data/pt-BR';
const intlProvider = new IntlProvider({ locale: 'pt-BR', messages: pt }, {});
const { intl } = intlProvider.getChildContext();
const nodeWithIntlProp = (node) => React.cloneElement(node, { intl });
const shallowWithIntl = (node, { context } = {}) =>
shallow(nodeWithIntlProp(node), {
context: Object.assign({}, context, { intl }),
});
export default shallowWithIntl;
|
src/BarGraphGroup/bar_graph_column.js
|
jrfferreira/react-cubedb
|
// @flow
// TODO remove lodash
import _map from 'lodash/map'
import React from 'react'
import BarGraph from '../BarGraph'
export default class BarGraphColumn extends React.Component {
constructor(props) {
super(props)
this.state = {
stretched: [],
search: []
}
}
onStretch = serie => () => {
this.setState({
stretched: Object.assign({}, this.state.stretched, {
[this.props.name + serie]: !this.state.stretched[this.props.name + serie]
})
})
};
onSearch = serie => e => {
const search = e.target.value
if (search.length) {
try {
new RegExp(search, 'i')
this.setState({
search: Object.assign({}, this.state.search, {
[serie]: search
})
})
} catch (e) {
this.setState({
search: Object.assign({}, this.state.search, {
[serie]: false
})
})
}
} else {
this.setState({
search: Object.assign({}, this.state.search, {
[serie]: undefined
})
})
}
};
render() {
return (
<div className="cube_graph__column">
{_map(this.props.data, (serie, key) => {
const description = this.props.dataDescription ? this.props.dataDescription[key] : undefined
return (
<div key={key} className={'bar-graph-group__list'}>
<BarGraph
name={key}
description={description}
data={serie}
comparingTo={this.props.comparingTo && this.props.comparingTo[key]}
selected={this.props.selectedItems && this.props.selectedItems[key]}
onChange={this.props.onChange}
slice={this.props.slice}
group={this.props.group}
lookup={this.props.lookup}
getColor={this.props.getColor}
allData={this.props.allData}
/>
</div>
)
})}
</div>
)
}
}
|
src/components/MainPageWithNav.js
|
zeljkoX/e-learning
|
import React from 'react';
import ReactDOM from'react-dom';
import Header from './layout/Header';
import PageWithNav from './layout/PageWithNav';
import Breadcrumbs from 'react-breadcrumbs';
class MainPageWithNav extends React.Component {
render() {
let menuItems = [
{ route: 'studenti', text: 'Studenti'},
{ route: 'profesori', text: 'Profesori'},
{ route: 'kursevi', text: 'Kursevi'},
{ route: 'program', text: 'Programi'}
];
return (
<Header>
<PageWithNav menuItems={menuItems}>
<Breadcrumbs {...this.props}/>
{this.props.children}
</PageWithNav>
</Header>
)
}
}
export default MainPageWithNav;
|
src/components/Header/Header.js
|
mjasinski5/dashboardWookiees
|
import React from 'react'
import { IndexLink, Link } from 'react-router'
import classes from './Header.scss'
export const Header = () => (
<div>
<h2>DashboardJS</h2>
<Link to='/'> Home </Link>
<Link to='/img'> ImgHome </Link>
</div>
)
export default Header
|
public/client/routes/users/containers/users.js
|
Concorda/concorda-dashboard
|
'use strict'
import React from 'react'
import {connect} from 'react-redux'
import { pushPath } from 'redux-simple-router'
import _ from 'lodash'
// actions
import {getUsers, deleteUser, getUser, closeSession, disableUser, enableUser} from '../../../modules/user/actions/index'
import Panel from '../../components/panel'
export const Users = React.createClass({
componentDidMount () {
this.props.dispatch(getUsers())
},
handleAdd () {
this.props.dispatch(pushPath('/user/add'))
},
handleInviteUser () {
this.props.dispatch(pushPath('/invite_user'))
},
handleEdit (userId) {
this.props.dispatch(getUser(userId, `/user/${userId}/edit`))
},
handleEditClient (clientId) {
this.props.dispatch(pushPath(`/client/${clientId}/edit`))
},
handleEditGroup (groupId) {
this.props.dispatch(pushPath(`/group/${groupId}/edit`))
},
handleDelete (id) {
this.props.dispatch(deleteUser(id))
},
handleDisable (id) {
this.props.dispatch(disableUser(id))
},
handleEnable (id) {
this.props.dispatch(enableUser(id))
},
handleCloseSession (id) {
this.props.dispatch(closeSession(id))
},
render () {
const {users} = this.props
let body = null
if (users) {
body = (
<div className="user-list">
<div className="user-list-heading cf row">
<div className="col-xs-12 col-md-2"><h4 className="m0">Name</h4></div>
<div className="col-xs-12 col-md-2"><h4 className="m0">Email</h4></div>
<div className="col-xs-2 col-md-2"><h4 className="m0">Clients</h4></div>
<div className="col-xs-2 col-md-2"><h4 className="m0">Groups</h4></div>
<div className="col-xs-4 col-md-4"><h4 className="m0">Actions</h4></div>
</div>
{users.map((user) => {
return (
<div key={user.id} className="user-list-row row cf">
<div className="col-xs-12 col-md-2">{user.name}</div>
<div className="col-xs-12 col-md-2">{user.email}</div>
<div className="col-xs-2 col-md-2">{_.map(user.clients, (client) => { return <a onClick={() => { this.handleEditClient(client.id) }}>{client.name}, </a> })}</div>
<div className="col-xs-2 col-md-2">{_.map(user.groups, (group) => { return <a onClick={() => { this.handleEditGroup(group.id) }}>{group.name}, </a> })}</div>
<div className="col-xs-4 col-md-4">
<ul className="list-unstyled list-inline">
<li><a onClick={() => { this.handleEdit(user.id) }}>Edit</a></li>
{(() => {
if (user.active) {
return <li><a onClick={() => { this.handleDisable(user.id) }}>Disable</a></li>
}
else {
return <li><a onClick={() => { this.handleEnable(user.id) }}>Enable</a></li>
}
})()}
<li><a onClick={() => { this.handleDelete(user.id) }}>Delete</a></li>
<li><a onClick={() => { this.handleCloseSession(user.id) }}>Close Session</a></li>
</ul>
</div>
</div>
)
})}
</div>
)
}
return (
<div className="page page-users container-fluid">
<div className="row middle-xs page-heading">
<h2 className="col-xs-6 col-sm-6">Users</h2>
<div className="col-xs-6 col-sm-6 txt-right">
<button onClick={() => { this.handleAdd() }} className="btn btn-primary">Add User</button>
<button onClick={() => { this.handleInviteUser() }} className="btn btn-primary btn-send-invite">Invite
User
</button>
</div>
</div>
<div className="row middle-xs search-wrapper">
<div className="col-xs-12 col-sm-8 col-md-8 search-input-wrapper">
<input type="search" className="input-large" placeholder="Find a user"/>
<ul className="list-unstyled search-dropdown-active">
<li><a href="">Item one</a></li>
<li><a href="">Item two</a></li>
<li><a href="">Item three</a></li>
</ul>
</div>
<div className="col-xs-12 col-sm-4 col-md-4 txt-left">
<button className="btn btn-large btn-search">Search</button>
</div>
</div>
<Panel title={'User List'}>
{body}
</Panel>
<nav role="navigation" className="txt-center">
<ul className="list-unstyled list-inline pagination">
<li><a href="">Prev</a></li>
<li><a href="">1</a></li>
<li><a href="" className="page-current">2</a></li>
<li><a href="">3</a></li>
<li><a href="" className="page-unavailable">Next</a></li>
</ul>
</nav>
</div>
)
}
})
export default connect((state) => {
return {
users: state.user.result
}
})(Users)
|
docs/src/components/index/Content.js
|
HsuTing/cat-components
|
'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import radium from 'radium';
import Markdown from 'react-markdown';
import * as style from './style/index';
@radium
export default class Content extends React.Component {
static propTypes = {
name: PropTypes.string.isRequired,
text: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func
]).isRequired,
component: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.func
]).isRequired,
example: PropTypes.string.isRequired
}
render() {
const {name, text, component, example} = this.props;
return (
<div id={name}
style={style.block}
>
<Markdown source={typeof text === 'string' ? text : text(example)} />
{
!component ?
null: React.createElement(component)
}
</div>
);
}
}
|
examples/04 Sortable/Simple/Container.js
|
pairyo/react-dnd
|
import React, { Component } from 'react';
import update from 'react/lib/update';
import Card from './Card';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd/modules/backends/HTML5';
const style = {
width: 400
};
@DragDropContext(HTML5Backend)
export default class Container extends Component {
constructor(props) {
super(props);
this.moveCard = this.moveCard.bind(this);
this.state = {
cards: [{
id: 1,
text: 'Write a cool JS library'
}, {
id: 2,
text: 'Make it generic enough'
}, {
id: 3,
text: 'Write README'
}, {
id: 4,
text: 'Create some examples'
}, {
id: 5,
text: 'Spam in Twitter and IRC to promote it'
}, {
id: 6,
text: '???'
}, {
id: 7,
text: 'PROFIT'
}]
};
}
moveCard(id, afterId) {
const { cards } = this.state;
const card = cards.filter(c => c.id === id)[0];
const afterCard = cards.filter(c => c.id === afterId)[0];
const cardIndex = cards.indexOf(card);
const afterIndex = cards.indexOf(afterCard);
this.setState(update(this.state, {
cards: {
$splice: [
[cardIndex, 1],
[afterIndex, 0, card]
]
}
}));
}
render() {
const { cards } = this.state;
return (
<div style={style}>
{cards.map(card => {
return (
<Card key={card.id}
id={card.id}
text={card.text}
moveCard={this.moveCard} />
);
})}
</div>
);
}
}
|
demo/src/components/App/components/Examples/components/MultipleSections/MultipleSections.js
|
CoreFiling/react-autosuggest
|
import styles from './MultipleSections.less';
import theme from './theme.less';
import React, { Component } from 'react';
import isMobile from 'ismobilejs';
import Link from 'Link/Link';
import Autosuggest from 'Autosuggest';
import languages from './languages';
import { escapeRegexCharacters } from 'utils/utils';
const focusInputOnSuggestionClick = !isMobile.any;
const getSuggestions = value => {
const escapedValue = escapeRegexCharacters(value.trim());
if (escapedValue === '') {
return [];
}
const regex = new RegExp('^' + escapedValue, 'i');
return languages
.map(section => {
return {
title: section.title,
languages: section.languages.filter(language => regex.test(language.name))
};
})
.filter(section => section.languages.length > 0);
};
const getSuggestionValue = suggestion => suggestion.name;
const renderSuggestion = suggestion => (
<span>{suggestion.name}</span>
);
const renderSectionTitle = section => (
<strong>{section.title}</strong>
);
const getSectionSuggestions = section => section.languages;
export default class MultipleSections extends Component {
constructor() {
super();
this.state = {
value: '',
suggestions: []
};
}
onChange = (event, { newValue }) => {
this.setState({
value: newValue
});
};
onSuggestionsFetchRequested = ({ value }) => {
this.setState({
suggestions: getSuggestions(value)
});
};
onSuggestionsClearRequested = () => {
this.setState({
suggestions: []
});
};
render() {
const { value, suggestions } = this.state;
const inputProps = {
placeholder: 'Type \'c\'',
value,
onChange: this.onChange
};
return (
<div id="multiple-sections-example" className={styles.container}>
<div className={styles.textContainer}>
<div className={styles.title}>
Multiple sections
</div>
<div className={styles.description}>
Suggestions can also be presented in multiple sections.
Note that we highlight the first suggestion by default here.
</div>
<Link
className={styles.codepenLink}
href="http://codepen.io/moroshko/pen/qbRNjV"
underline={false}
>
Codepen
</Link>
</div>
<div className={styles.autosuggest}>
<Autosuggest
multiSection={true}
suggestions={suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
renderSectionTitle={renderSectionTitle}
getSectionSuggestions={getSectionSuggestions}
inputProps={inputProps}
highlightFirstSuggestion={true}
focusInputOnSuggestionClick={focusInputOnSuggestionClick}
theme={theme}
id="multiple-sections-example"
/>
</div>
</div>
);
}
}
|
app/components/Counter.js
|
lynks-p2p/lynks-client
|
// @flow
import React, { Component } from 'react';
import { Link } from 'react-router';
import styles from './Counter.css';
class Counter extends Component {
props: {
increment: () => void,
incrementIfOdd: () => void,
incrementAsync: () => void,
decrement: () => void,
counter: number
};
render() {
const { increment, incrementIfOdd, incrementAsync, decrement, counter } = this.props;
return (
<div>
<div className={styles.backButton}>
<Link to="/">
<i className="fa fa-arrow-left fa-3x" />
</Link>
</div>
<div className={`counter ${styles.counter}`}>
{counter}
</div>
<div className={styles.btnGroup}>
<button className={styles.btn} onClick={increment}>
<i className="fa fa-plus" />
</button>
<button className={styles.btn} onClick={decrement}>
<i className="fa fa-minus" />
</button>
<button className={styles.btn} onClick={incrementIfOdd}>odd</button>
<button className={styles.btn} onClick={() => incrementAsync()}>async</button>
</div>
</div>
);
}
}
export default Counter;
|
app/javascript/mastodon/containers/status_container.js
|
ebihara99999/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import Status from '../components/status';
import { makeGetStatus } from '../selectors';
import {
replyCompose,
mentionCompose,
} from '../actions/compose';
import {
reblog,
favourite,
unreblog,
unfavourite,
} from '../actions/interactions';
import {
blockAccount,
muteAccount,
} from '../actions/accounts';
import { muteStatus, unmuteStatus, deleteStatus } from '../actions/statuses';
import { initReport } from '../actions/reports';
import { openModal } from '../actions/modal';
import { createSelector } from 'reselect';
import { isMobile } from '../is_mobile';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
const messages = defineMessages({
deleteConfirm: { id: 'confirmations.delete.confirm', defaultMessage: 'Delete' },
deleteMessage: { id: 'confirmations.delete.message', defaultMessage: 'Are you sure you want to delete this status?' },
blockConfirm: { id: 'confirmations.block.confirm', defaultMessage: 'Block' },
muteConfirm: { id: 'confirmations.mute.confirm', defaultMessage: 'Mute' },
});
const makeMapStateToProps = () => {
const getStatus = makeGetStatus();
const mapStateToProps = (state, props) => ({
status: getStatus(state, props.id),
me: state.getIn(['meta', 'me']),
boostModal: state.getIn(['meta', 'boost_modal']),
autoPlayGif: state.getIn(['meta', 'auto_play_gif']),
});
return mapStateToProps;
};
const mapDispatchToProps = (dispatch, { intl }) => ({
onReply (status, router) {
dispatch(replyCompose(status, router));
},
onModalReblog (status) {
dispatch(reblog(status));
},
onReblog (status, e) {
if (status.get('reblogged')) {
dispatch(unreblog(status));
} else {
if (e.shiftKey || !this.boostModal) {
this.onModalReblog(status);
} else {
dispatch(openModal('BOOST', { status, onReblog: this.onModalReblog }));
}
}
},
onFavourite (status) {
if (status.get('favourited')) {
dispatch(unfavourite(status));
} else {
dispatch(favourite(status));
}
},
onDelete (status) {
dispatch(openModal('CONFIRM', {
message: intl.formatMessage(messages.deleteMessage),
confirm: intl.formatMessage(messages.deleteConfirm),
onConfirm: () => dispatch(deleteStatus(status.get('id'))),
}));
},
onMention (account, router) {
dispatch(mentionCompose(account, router));
},
onOpenMedia (media, index) {
dispatch(openModal('MEDIA', { media, index }));
},
onOpenVideo (media, time) {
dispatch(openModal('VIDEO', { media, time }));
},
onBlock (account) {
dispatch(openModal('CONFIRM', {
message: <FormattedMessage id='confirmations.block.message' defaultMessage='Are you sure you want to block {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />,
confirm: intl.formatMessage(messages.blockConfirm),
onConfirm: () => dispatch(blockAccount(account.get('id'))),
}));
},
onReport (status) {
dispatch(initReport(status.get('account'), status));
},
onMute (account) {
dispatch(openModal('CONFIRM', {
message: <FormattedMessage id='confirmations.mute.message' defaultMessage='Are you sure you want to mute {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />,
confirm: intl.formatMessage(messages.muteConfirm),
onConfirm: () => dispatch(muteAccount(account.get('id'))),
}));
},
onMuteConversation (status) {
if (status.get('muted')) {
dispatch(unmuteStatus(status.get('id')));
} else {
dispatch(muteStatus(status.get('id')));
}
},
});
export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Status));
|
src/app/components/Layout.js
|
jordanco/drafter-frontend
|
import React, { Component } from 'react';
import '../../assets/css/normalize.css';
import '../../assets/css/webflow.css';
import '../../assets/css/drafter2.webflow.css';
import ActionSidebarMenu from '../components/menu/action-sidebar';
export default (props) => {
return (
<div className="master">
<ActionSidebarMenu />
{props.children}
</div>
);
};
|
src/views/mainPage.js
|
IllegalCreed/pwdsaver_app
|
/**
* @providesModule MainPage
*/
import React, { Component } from 'react';
import {
TouchableWithoutFeedback,
KeyboardAvoidingView,
TouchableOpacity,
SectionList,
ScrollView,
StyleSheet,
Dimensions,
TextInput,
Platform,
Button,
Modal,
Alert,
Image,
Text,
View
} from 'react-native';
import Crypto from 'crypto-js';
import { requestState } from 'ReducerUtils';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import Actions from 'Actions';
export class MainPage extends Component {
static navigationOptions = {
title: '拔粪宝',
headerStyle: {
backgroundColor: '#232323'
},
headerTitleStyle: {
fontSize: 20,
},
headerTintColor: 'white'
}
constructor(props) {
super(props);
this.state = {
addPwdModalVisible: false,
addGroupModalVisible: false,
updateGroupModalVisible: false,
updatePwdModalVisible: false,
key: '',
account: '',
password: '',
newPassword: '',
currentPwdId: '',
currentGroupId: '',
currentGroupName: '',
tempGroupName: '',
currentSelectPwd: '',
}
this.renderSectionHeader = this.renderSectionHeader.bind(this);
this.renderItemComponent = this.renderItemComponent.bind(this);
this.pwdHasSameKey = this.pwdHasSameKey.bind(this);
this.pwdHasSameKeyWithoutSelf = this.pwdHasSameKeyWithoutSelf.bind(this);
this.groupHasSameKey = this.groupHasSameKey.bind(this);
this.groupHasSameKeyWithoutSelf = this.groupHasSameKeyWithoutSelf.bind(this);
this.props.dispatch(Actions.getPwdList());
}
componentWillReceiveProps(nextProps) {
if (nextProps.addPwdState != this.props.addPwdState) {
switch (nextProps.addPwdState) {
case requestState.LOADED:
this.props.dispatch(Actions.getPwdList());
this.props.dispatch(Actions.resetAddPwdState());
console.log('添加密码成功');
break;
case requestState.ERROR:
console.log('添加密码失败');
break;
}
}
if (nextProps.updatePwdState != this.props.updatePwdState) {
switch (nextProps.updatePwdState) {
case requestState.LOADED:
this.props.dispatch(Actions.getPwdList());
this.props.dispatch(Actions.resetUpdatePwdState());
console.log('更新密码成功');
break;
case requestState.ERROR:
console.log('更新密码失败');
break;
}
}
if (nextProps.deletePwdState != this.props.deletePwdState) {
switch (nextProps.deletePwdState) {
case requestState.LOADED:
this.props.dispatch(Actions.getPwdList());
this.props.dispatch(Actions.resetDeletePwdState());
console.log('删除密码成功');
break;
case requestState.ERROR:
console.log('删除密码失败');
break;
}
}
if (nextProps.addGroupState != this.props.addGroupState) {
switch (nextProps.addGroupState) {
case requestState.LOADED:
this.props.dispatch(Actions.getPwdList());
this.props.dispatch(Actions.resetAddGroupState());
console.log('添加分组成功');
break;
case requestState.ERROR:
console.log('添加分组失败');
break;
}
}
if (nextProps.updateGroupState != this.props.updateGroupState) {
switch (nextProps.updateGroupState) {
case requestState.LOADED:
this.props.dispatch(Actions.getPwdList());
this.props.dispatch(Actions.resetUpdateGroupState());
console.log('更新分组成功');
break;
case requestState.ERROR:
console.log('更新分组失败');
break;
}
}
if (nextProps.deleteGroupState != this.props.deleteGroupState) {
switch (nextProps.deleteGroupState) {
case requestState.LOADED:
this.props.dispatch(Actions.getPwdList());
this.props.dispatch(Actions.resetDeleteGroupState());
console.log('删除分组成功');
break;
case requestState.ERROR:
console.log('删除分组失败');
break;
}
}
}
renderSectionHeader({ section }) {
return (
<TouchableOpacity onLongPress={() => {
this.setState({ updateGroupModalVisible: true, currentGroupName: section.groupName, currentGroupId: section.key, tempGroupName: section.groupName })
}}>
<View style={{
justifyContent: 'space-between',
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#3b3b3b',
paddingLeft: 10,
paddingRight: 15,
height: 40
}}>
<Text style={{
color: 'white',
fontSize: 20,
fontWeight: 'bold'
}}>{section.groupName}</Text>
<TouchableOpacity
onPress={() => {
this.setState({ addPwdModalVisible: true, currentGroupName: section.groupName, currentGroupId: section.key })
}} >
<Text style={{ fontSize: 30, color: 'white', marginTop: -4 }}>{'+'}</Text>
</TouchableOpacity>
</View>
</TouchableOpacity >
)
}
renderItemComponent({ item }) {
if (this.state.currentSelectPwd == item.pid) {
let decrypted = Crypto.AES.decrypt(item.pwd, this.props.password);
return (
<TouchableOpacity
onPress={() => {
this.setState({ currentSelectPwd: '' });
}}
onLongPress={() => {
this.setState({ updatePwdModalVisible: true, key: item.key, account: item.account, password: item.pwd, newPassword: '', currentPwdId: item.pid, currentGroupId: item.gid })
}}>
<View style={{
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingLeft: 10,
height: 35
}}>
<Text style={{
color: '#7EC880',
fontSize: 16,
marginLeft: 10,
}}>{item.account}</Text>
<Text style={{
color: '#80C080',
fontSize: 16,
marginRight: 15,
}}>{decrypted.toString(Crypto.enc.Utf8)}</Text>
</View>
</TouchableOpacity>
)
} else {
return (
<TouchableOpacity
onPress={() => {
this.setState({ currentSelectPwd: item.pid });
}}
onLongPress={() => {
this.setState({ updatePwdModalVisible: true, key: item.key, account: item.account, password: item.pwd, newPassword: '', currentPwdId: item.pid, currentGroupId: item.gid })
}}>
<View style={{
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingLeft: 10,
height: 35
}}>
<Text style={{
color: 'white',
fontSize: 16,
marginLeft: 10,
}}>{item.key}</Text>
<Text style={{
color: 'white',
fontSize: 16,
marginRight: 15,
}}>{item.account}</Text>
</View>
</TouchableOpacity>
)
}
}
groupHasSameKey(key) {
for (let group of this.props.pwdList) {
if (group.groupName == key) {
return true;
}
}
return false;
}
groupHasSameKeyWithoutSelf(key, id) {
for (let group of this.props.pwdList) {
if (group.groupName == key && group.key != id) {
return true;
}
}
return false;
}
pwdHasSameKey(key) {
for (let group of this.props.pwdList) {
for (let pwd of group.data) {
if (pwd.key == key) {
return true;
}
}
}
return false;
}
pwdHasSameKeyWithoutSelf(key, id) {
for (let group of this.props.pwdList) {
for (let pwd of group.data) {
if (pwd.key == key && id != pwd.pid) {
return true;
}
}
}
return false;
}
render() {
const Container = Platform.OS === 'ios' ? KeyboardAvoidingView : View;
return (
<View style={{ flex: 1, backgroundColor: '#232323' }}>
<Modal
animationType={"fade"}
transparent={true}
visible={this.state.addPwdModalVisible}>
<Container behavior={'padding'} style={{
flex: 1,
backgroundColor: '#00000088',
justifyContent: 'flex-end',
}}>
<TouchableWithoutFeedback
style={{ flex: 1 }}
onPress={() => {
this.setState({ addPwdModalVisible: false })
}}>
<View style={{ flex: 1 }}></View>
</TouchableWithoutFeedback>
<View style={{
height: 270,
backgroundColor: '#232323',
}}>
<View style={{ height: 1, backgroundColor: '#666666', marginBottom: 15 }} />
<Text style={{
color: 'white',
fontSize: 16,
marginLeft: 12,
marginBottom: 15
}}>{'向' + this.state.currentGroupName + '中添加新密码'}</Text>
<TextInput
placeholderTextColor="#bfbfbf"
underlineColorAndroid="transparent"
style={styles.singleLine}
placeholder="名称"
onChangeText={(text) => this.setState({ key: text })} />
<TextInput
placeholderTextColor="#bfbfbf"
underlineColorAndroid="transparent"
style={styles.singleLine}
placeholder="账号"
onChangeText={(text) => this.setState({ account: text })} />
<TextInput
placeholderTextColor="#bfbfbf"
underlineColorAndroid="transparent"
style={styles.singleLine}
placeholder="密码"
onChangeText={(text) => this.setState({ password: text })} />
<TouchableOpacity style={[styles.button, { marginLeft: 20, marginRight: 20 }]}
onPress={() => {
if (this.pwdHasSameKey(this.state.key)) {
Alert.alert('名称重复');
return;
}
let encrypted = Crypto.AES.encrypt(this.state.password, this.props.password);
this.props.dispatch(Actions.addPwd(this.state.currentGroupId, this.state.key, this.state.account, encrypted.toString()));
this.setState({ addPwdModalVisible: false });
}} >
<Text style={styles.buttonText}>{'添加'}</Text>
</TouchableOpacity>
</View>
</Container>
</Modal>
<Modal
animationType={"fade"}
transparent={true}
visible={this.state.addGroupModalVisible}>
<Container behavior={'padding'} style={{
flex: 1,
backgroundColor: '#00000088',
justifyContent: 'flex-end',
}}>
<TouchableWithoutFeedback
style={{ flex: 1 }}
onPress={() => {
this.setState({ addGroupModalVisible: false })
}}>
<View style={{ flex: 1 }}></View>
</TouchableWithoutFeedback>
<View style={{
height: 130,
backgroundColor: '#232323',
}}>
<View style={{ height: 1, backgroundColor: '#666666', marginBottom: 15 }} />
<TextInput
placeholderTextColor="#bfbfbf"
underlineColorAndroid="transparent"
style={styles.singleLine}
placeholder="分组名称"
onChangeText={(text) => this.setState({ currentGroupName: text })} />
<TouchableOpacity style={[styles.button, { marginLeft: 20, marginRight: 20 }]}
onPress={() => {
if (this.groupHasSameKey(this.state.currentGroupName)) {
Alert.alert('名称重复');
return;
}
this.props.dispatch(Actions.addGroup(this.state.currentGroupName));
this.setState({ addGroupModalVisible: false });
}} >
<Text style={styles.buttonText}>{'添加'}</Text>
</TouchableOpacity>
</View>
</Container>
</Modal>
<Modal
animationType={"fade"}
transparent={true}
visible={this.state.updateGroupModalVisible}>
<Container behavior={'padding'} style={{
flex: 1,
backgroundColor: '#00000088',
justifyContent: 'flex-end',
}}>
<TouchableWithoutFeedback
style={{ flex: 1 }}
onPress={() => {
this.setState({ updateGroupModalVisible: false })
}}>
<View style={{ flex: 1 }}></View>
</TouchableWithoutFeedback>
<View style={{
height: 160,
backgroundColor: '#232323',
}}>
<View style={{ height: 1, backgroundColor: '#666666', marginBottom: 15 }} />
<Text style={{
color: 'white',
fontSize: 16,
marginLeft: 12,
marginBottom: 15
}}>{'修改' + this.state.tempGroupName}</Text>
<TextInput
placeholderTextColor="#bfbfbf"
underlineColorAndroid="transparent"
style={styles.singleLine}
placeholder="名称"
value={this.state.currentGroupName}
onChangeText={(text) => this.setState({ currentGroupName: text })} />
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity style={[styles.button, { marginLeft: 20, marginRight: 10, flex: 1 }]}
onPress={() => {
if (this.groupHasSameKeyWithoutSelf(this.state.currentGroupName, this.state.currentGroupId)) {
Alert.alert('名称重复');
return;
}
this.props.dispatch(Actions.updateGroup(this.state.currentGroupId, this.state.currentGroupName));
this.setState({ updateGroupModalVisible: false });
}} >
<Text style={styles.buttonText}>{'修改'}</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.button, { marginLeft: 10, marginRight: 20, flex: 1 }]}
onPress={() => {
this.props.dispatch(Actions.deleteGroup(this.state.currentGroupId));
this.setState({ updateGroupModalVisible: false });
}} >
<Text style={styles.buttonText}>{'删除'}</Text>
</TouchableOpacity>
</View>
</View>
</Container>
</Modal>
<Modal
animationType={"fade"}
transparent={true}
visible={this.state.updatePwdModalVisible}>
<Container behavior={'padding'} style={{
flex: 1,
backgroundColor: '#00000088',
justifyContent: 'flex-end',
}}>
<TouchableWithoutFeedback
style={{ flex: 1 }}
onPress={() => {
this.setState({ updatePwdModalVisible: false })
}}>
<View style={{ flex: 1 }}></View>
</TouchableWithoutFeedback>
<View style={{
height: 270,
backgroundColor: '#232323',
}}>
<View style={{ height: 1, backgroundColor: '#666666', marginBottom: 15 }} />
<Text style={{
color: 'white',
fontSize: 16,
marginLeft: 12,
marginBottom: 15
}}>{'修改密码'}</Text>
<TextInput
placeholderTextColor="#bfbfbf"
underlineColorAndroid="transparent"
style={styles.singleLine}
placeholder="名称"
value={this.state.key}
onChangeText={(text) => this.setState({ key: text })} />
<TextInput
placeholderTextColor="#bfbfbf"
underlineColorAndroid="transparent"
style={styles.singleLine}
placeholder="账号"
value={this.state.account}
onChangeText={(text) => this.setState({ account: text })} />
<TextInput
placeholderTextColor="#bfbfbf"
underlineColorAndroid="transparent"
style={styles.singleLine}
placeholder="密码"
value={this.state.newPassword}
onChangeText={(text) => this.setState({ newPassword: text })} />
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity style={[styles.button, { marginLeft: 20, marginRight: 10, flex: 1 }]}
onPress={() => {
if (this.pwdHasSameKeyWithoutSelf(this.state.key, this.state.currentPwdId)) {
Alert.alert('名称重复');
return;
}
let pwd = '';
if (this.state.newPassword == '') {
pwd = this.state.password;
} else {
let encrypted = Crypto.AES.encrypt(this.state.newPassword, this.props.password);
pwd = encrypted.toString();
}
this.props.dispatch(Actions.updatePwd(this.state.currentPwdId, this.state.currentGroupId, this.state.key, this.state.account, pwd));
this.setState({ updatePwdModalVisible: false });
}} >
<Text style={styles.buttonText}>{'修改'}</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.button, { marginLeft: 10, marginRight: 20, flex: 1 }]}
onPress={() => {
this.props.dispatch(Actions.deletePwd(this.state.currentPwdId));
this.setState({ updatePwdModalVisible: false });
}} >
<Text style={styles.buttonText}>{'删除'}</Text>
</TouchableOpacity>
</View>
</View>
</Container>
</Modal>
<SectionList
ListFooterComponent={F =>
<TouchableOpacity style={[styles.button, { marginLeft: 20, marginRight: 20, marginBottom: 50, marginTop: 15 }]}
onPress={() => {
this.setState({ addGroupModalVisible: true });
}} >
<Text style={styles.buttonText}>{'添加分组'}</Text>
</TouchableOpacity>
}
SectionSeparatorComponent={() =>
<View style={{ height: 2, backgroundColor: '#232323' }} />
}
ItemSeparatorComponent={() =>
<View style={{ height: 1, backgroundColor: 'black' }} />
}
renderItem={this.renderItemComponent}
renderSectionHeader={this.renderSectionHeader}
sections={this.props.pwdList}
/>
</View>
)
}
}
var styles = StyleSheet.create({
button: {
borderRadius: 4,
marginTop: 10,
height: 35,
backgroundColor: '#6e6e6e',
alignItems: 'center',
},
buttonText: {
color: '#FFFFFF',
fontSize: 16,
lineHeight: 30,
},
singleLine: {
borderRadius: 4,
marginLeft: 10,
marginRight: 10,
marginBottom: 5,
backgroundColor: '#3e3e3e',
color: '#FFFFFF',
fontSize: 16,
padding: 0,
paddingLeft: 15,
height: 50,
},
});
const getPwdList = state => state.pwd.pwdList;
const getPwd = state => state.user.password;
const getAddPwdState = state => state.pwd.addPwdState
const getUpdatePwdState = state => state.pwd.updatePwdState
const getDeletePwdState = state => state.pwd.deletePwdState
const getAddGroupState = state => state.pwd.addGroupState
const getUpdateGroupState = state => state.pwd.updateGroupState
const getDeleteGroupState = state => state.pwd.deleteGroupState
const MainPageSelector = createSelector([getPwdList, getPwd, getAddPwdState, getUpdatePwdState, getDeletePwdState, getAddGroupState, getUpdateGroupState, getDeleteGroupState], (pwdList, password, addPwdState, updatePwdState, deletePwdState, addGroupState, updateGroupState, deleteGroupState) => {
return {
pwdList,
password,
addPwdState,
updatePwdState,
deletePwdState,
addGroupState,
updateGroupState,
deleteGroupState,
}
});
export default connect(MainPageSelector)(MainPage);
|
src/components/frontPageDisplay.js
|
gordongordon/hom
|
import React from 'react'
import { Carousel, WhiteSpace, WingBlank } from 'antd-mobile';
export default class FrontPageDisplay extends React.Component {
state = {
data: ['', '', ''],
initialHeight: 200,
}
componentDidMount() {
// simulate img loading
setTimeout(() => {
this.setState({
data: ['AiyWuByWklrrUDlFignR', 'TekJlZRVCjLFexlOCuWn', 'IJOtIlfsYdTyaDTRVrLI'],
});
}, 100);
}
render() {
const hProp = this.state.initialHeight ? { height: this.state.initialHeight } : {};
return (
<WingBlank>
<Carousel
className="my-carousel"
autoplay={false}
infinite
selectedIndex={1}
swipeSpeed={35}
beforeChange={(from, to) => console.log(`slide from ${from} to ${to}`)}
afterChange={index => console.log('slide to', index)}
>
{this.state.data.map(ii => (
<a href="http://www.baidu.com" key={ii} style={hProp}>
<img
src={`https://zos.alipayobjects.com/rmsportal/${ii || 'QcWDkUhvYIVEcvtosxMF'}.png`}
alt="icon"
onLoad={() => {
// fire window resize event to change height
window.dispatchEvent(new Event('resize'));
this.setState({
initialHeight: null,
});
}}
/>
</a>
))}
</Carousel>
</WingBlank>
);
}
}
|
04/EW/trding/trding/src/components/notfound/NotFound.js
|
rgllm/uminho
|
import React from 'react';
import { Link } from 'react-router-dom';
import './NotFound.css';
const NotFound = () =>{
return(
<div className="NotFound">
<h1 clasName="NotFound-title">Page not found!</h1>
<Link to="/" className="NotFound-link">Go to homepage</Link>
</div>
);
}
export default NotFound;
|
test/integration/image-component/base-path/pages/hidden-parent.js
|
zeit/next.js
|
import Image from 'next/image'
import React from 'react'
const Page = () => {
return (
<div>
<p>Hello World</p>
<div style={{ visibility: 'hidden' }}>
<Image
id="hidden-image"
src="/docs/test.jpg"
width="400"
height="400"
></Image>
</div>
<p id="stubtext">This is the hidden parent page</p>
</div>
)
}
export default Page
|
app/containers/HomePage/index.js
|
litdevelopers/tinder
|
/*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a neccessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
export default class HomePage extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<h1>
<FormattedMessage {...messages.header} />
</h1>
);
}
}
|
src/component/Account.js
|
BristolPound/cyclos-mobile-3-TownPound
|
import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { View, ListView, TouchableHighlight } from 'react-native'
import DefaultText from './DefaultText'
import Colors from '@Colors/colors'
import { logout } from '../store/reducer/login'
import { updateStatus } from '../store/reducer/statusMessage'
import ProfileHeader from './profileScreen/ProfileHeader'
import styles from './AccountStyle'
const renderSeparator = (sectionID, rowID) =>
<View style={styles.separator} key={`sep:${sectionID}:${rowID}`}/>
const renderSectionHeader = (sectionData, sectionID) =>
<View style={styles.sectionHeader.container} key={sectionID}>
<DefaultText style={styles.sectionHeader.text}>
{sectionID.toUpperCase()}
</DefaultText>
</View>
const AccountOption = ({text, secondaryText, onPress, index}) =>
<TouchableHighlight
onPress={() => onPress ? onPress() : undefined}
key={index}
underlayColor={onPress ? Colors.gray5 : Colors.transparent}>
<View style={styles.row.container}>
<DefaultText style={styles.row.label}>{text}</DefaultText>
{ secondaryText
? <DefaultText style={styles.row.secondary}>{secondaryText}</DefaultText>
: undefined }
</View>
</TouchableHighlight>
const Account = (props) => {
let ds = new ListView.DataSource({
rowHasChanged: (a, b) => a.text !== b.text || a.secondaryText !== b.secondaryText,
sectionHeaderHasChanged: (a, b) => a !== b
})
const data = {
'Profile Settings': [{
text: 'Email',
secondaryText: (props.details && props.details.email) || 'Not set'
}, {
text: 'Phone',
secondaryText: (props.details && props.details.phones && props.details.phones.length > 0) ? props.details.phones[0].normalizedNumber : 'Not set'
}, {
text: 'Log out',
onPress: () => {
props.logout()
props.updateStatus('Logged out ✓')
}
}]
}
ds = ds.cloneWithRowsAndSections(data, Object.keys(data))
return (
<View style={styles.container}>
<ProfileHeader
name={props.details.display}
username={props.details.shortDisplay}
image={props.details.image && props.details.image.url}
category='person'/>
<ListView
style={styles.detailsList}
dataSource={ds}
scrollEnabled={false}
renderSeparator={renderSeparator}
renderSectionHeader={renderSectionHeader}
renderRow={(accountOption, i) => <AccountOption {...accountOption} index={i}/> }
removeClippedSubviews={false}/>
</View>
)
}
const mapDispatchToProps = (dispatch) =>
bindActionCreators({ logout, updateStatus }, dispatch)
const mapStateToProps = state => state.account
export default connect(mapStateToProps, mapDispatchToProps)(Account)
|
src/components/Forms/CheckboxOrRadio.js
|
josedigital/koala-app
|
import React from 'react'
const CheckboxOrRadio = (props) => {
return (
<div className="formElement">
<label className="form-label">{props.title}</label>
<div className="checkbox-group">
{props.options.map(opt => {
return (
<label key={opt} className="form-label capitalize">
<input
className="form-checkbox"
name={props.name}
onChange={props.controlFunction}
value={opt}
checked={ props.selectedOptions.indexOf(opt) > -1 }
type={props.type} /> {opt}
</label>
);
})}
</div>
</div>
)
}
CheckboxOrRadio.propTypes = {
title: React.PropTypes.string.isRequired,
type: React.PropTypes.oneOf(['checkbox', 'radio']).isRequired,
name: React.PropTypes.string.isRequired,
options: React.PropTypes.array.isRequired,
selectedOptions: React.PropTypes.array,
controlFunction: React.PropTypes.func.isRequired
};
export default CheckboxOrRadio
|
client/app/components/common/Avatar.js
|
Zuehlke/poinz
|
import React from 'react';
import PropTypes from 'prop-types';
import avatarIcons, {SPECIAL} from '../../assets/avatars';
import {StyledAvatar} from './_styled';
const Avatar = ({user, isOwn, shaded, onClick}) => (
<StyledAvatar
className="avatar"
src={getImageSource(user)}
isOwn={isOwn}
shaded={shaded}
onClick={onClick}
/>
);
function getImageSource(user) {
if (user.email) {
return `https://www.gravatar.com/avatar/${user.emailHash}?size=60`; // the gravatar case
} else if (user.avatar) {
return user.avatar === -1 ? SPECIAL : avatarIcons[user.avatar % avatarIcons.length];
} else {
return avatarIcons[0];
}
}
Avatar.propTypes = {
user: PropTypes.object,
isOwn: PropTypes.bool,
shaded: PropTypes.bool,
onClick: PropTypes.func
};
export default Avatar;
|
src/shared/components/timeline/ViewCount.js
|
sbekti/path-web-client
|
import React from 'react'
import ReactDOM from 'react-dom'
import { Link } from 'react-router'
import Cookies from 'js-cookie'
import request from 'superagent'
class ViewCount extends React.Component {
constructor(props) {
super(props)
this.state = {
expanded: false
}
this.handleViewClick = this.handleViewClick.bind(this)
this.handleEmotionClick = this.handleEmotionClick.bind(this)
}
handleViewClick() {
const newExpanded = !this.state.expanded
this.setState({
expanded: newExpanded
})
}
handleEmotionClick(e) {
const { moment, user, customGeo, realGeo } = this.props
const emotionType = e.target.dataset.tag
this.setState({
expanded: false
})
let body = {
moment_id: moment.get('id'),
emotion_type: emotionType,
token: user.get('oauth_token')
}
const spoofLocation = Cookies.get('spoof_location')
if (spoofLocation === 'true') {
body.lat = customGeo.get('lat')
body.lng = customGeo.get('lng')
} else {
body.lat = realGeo.get('lat')
body.lng = realGeo.get('lng')
}
request
.post('/api/v1/emotion/add')
.send(body)
.end((err, res) => {
this.props.onEmotionClick(moment.get('id'))
})
}
render() {
const { views, dark } = this.props
const { expanded } = this.state
let element = null
if (expanded) {
element = (
<div className='emotion-actions'>
<button className='btn btn-default emotion-button' data-tag='happy' onClick={this.handleEmotionClick}>🙂</button>
<button className='btn btn-default emotion-button' data-tag='laugh' onClick={this.handleEmotionClick}>😂</button>
<button className='btn btn-default emotion-button' data-tag='surprise' onClick={this.handleEmotionClick}>😮</button>
<button className='btn btn-default emotion-button' data-tag='sad' onClick={this.handleEmotionClick}>😢</button>
<button className='btn btn-default emotion-button' data-tag='love' onClick={this.handleEmotionClick}>❤️</button>
</div>
)
}
return (
<div className='view-count'>
<div className='emotion-actions-wrap'>
{element}
<button className='btn btn-default emotion-button' onClick={this.handleViewClick}>
<span className='glyphicon glyphicon-heart'></span> {views}
</button>
</div>
</div>
)
}
}
export default ViewCount
|
src/web/client/src/components/shared/individual-search.js
|
devmynd/cloud-access-manager
|
import React from 'react'
import TypeAheadInput from './type-ahead-input'
import MessagesContainer from './messages-container'
import graphqlApi from '../../graphql-api'
export default class IndividualSearch extends React.Component {
query = async (text, callback) => {
const query = `{ individuals(fuzzySearch:"${text}", limit: ${10})
{
id, primaryEmail, fullName
serviceUserIdentities {
serviceId
userIdentity {
email
userId
fullName
}
}
accessRules {
service {
id
displayName
}
accessRules {
asset
role
}
}
groups
}
}`
const response = await graphqlApi.request(query)
if (response.error) {
this.messagesContainer.push({
title: 'Could not access existing individuals',
body: response.error.message
})
return
}
callback(response.data.individuals)
}
renderIndividual = (individual) => {
const additionalDetails = this.props.additionalDetailsRenderer
? this.props.additionalDetailsRenderer(individual)
: false
return (
<div>
<span>{individual.fullName}</span>
{ individual.primaryEmail &&
<span> ({ individual.primaryEmail })</span>
}
{ additionalDetails }
</div>
)
}
render () {
return (
<div className="indvidual-search">
<TypeAheadInput
placeholder='Search for individual by name or email'
query={this.query}
isMatchDisabled={this.props.shouldDisableIndividual}
matchRenderer={this.renderIndividual}
onMatchSelected={this.props.onIndividualSelected}
/>
<MessagesContainer ref={(container) => { this.messagesContainer = container }} />
</div>
)
}
}
|
test/components/searchbar.spec.js
|
ongmin/cylinder-app
|
/* global describe it */
// import { expect } from 'chai'
// import { shallow } from 'enzyme'
// import React from 'react'
// import Searchbar from '../app/components/Searchbar'
describe('<Searchbar />', () => {
it('should search Youtube for videos', () => {})
it('should list search results with the screenshot and title', () => {})
it('should add search result into playlist', () => {})
})
|
imports/ui/components/CreditNotes/ListCreditNotes/ListCreditNotes.js
|
haraneesh/mydev
|
import React from 'react';
import { Meteor } from 'meteor/meteor';
import PropTypes from 'prop-types';
import {
Button, Row, Table, Col, Panel, Glyphicon,
} from 'react-bootstrap';
import { toast } from 'react-toastify';
import { getFormattedMoney, getDayWithoutTime } from '../../../../modules/helpers';
import './ListCreditNotes.scss';
class ListCreditNotes extends React.Component {
constructor(props) {
super(props);
this.state = {
isCreditNotesLoading: true,
creditNotes: [],
creditNoteDetail: {},
};
this.fetchCreditNotes = this.fetchCreditNotes.bind(this);
this.fetchCreditNote = this.fetchCreditNote.bind(this);
}
fetchCreditNotes() {
Meteor.call('creditNotes.getCreditNotes',
(error, creditNotes) => {
if (error) {
// toast.error(error.reason);
toast.error(error.reason);
} else {
this.setState({
creditNotes,
isCreditNotesLoading: false,
});
}
});
}
fetchCreditNote(creditNoteId) {
Meteor.call('creditNotes.getCreditNote', creditNoteId,
(error, creditNote) => {
if (error) {
// toast.error(error.reason);
toast.error(error.reason);
} else {
this.setState({
creditNoteDetail: creditNote,
});
}
});
}
refundDetails(creditNoteDetail) {
return (
<section className="refund-section">
{
creditNoteDetail.line_items.map((item) => (
<Row className="refund-item">
<Col xs={8}>{item.name}</Col>
<Col xs={4}>{getFormattedMoney(item.item_total)}</Col>
</Row>
))
}
</section>
);
}
render() {
const { creditNotes } = this.state;
const { creditNoteDetail } = this.state;
return !this.state.isCreditNotesLoading ? (
<Panel>
{/* } <Row>
<Button type="button" onClick={this.fetchCreditNotes}>Show Refunds</Button>
</Row>
*/}
{creditNotes.length > 0 && (
<Col xs={12}>
<Row className="refund-heading">
<Col xs={5}><b>Refund Date</b></Col>
<Col xs={5}><b>Refund Amount</b></Col>
<Col xs={2} />
</Row>
{
creditNotes.map((creditNote) => {
const isCurrentRow = creditNote.creditnote_id === creditNoteDetail.creditnote_id;
return (
<Row className="refund-row" key={creditNote.creditnote_id}>
<Col xs={5}>{getDayWithoutTime(new Date(creditNote.date))}</Col>
<Col xs={5}>{getFormattedMoney(creditNote.total)}</Col>
<Col xs={2}>
{(!isCurrentRow) && (<Glyphicon glyph="plus" className="refund-expand" onClick={() => { this.fetchCreditNote(creditNote.creditnote_id); }} />) }
</Col>
<Col xs={12}>
{(isCurrentRow) && this.refundDetails(creditNoteDetail)}
</Col>
</Row>
);
})
}
</Col>
)}
</Panel>
) : (
<Panel>
{' '}
<button className="btn btn-sm btn-default" onClick={this.fetchCreditNotes}> Fetch Refund History </button>
{' '}
</Panel>
);
}
}
export default ListCreditNotes;
|
site/src/components/DemoBox.js
|
apisandipas/elemental
|
import React from 'react';
import classnames from 'classnames';
import E from '../../../src/constants';
const ALIGN_TRANSFORM = {
'center': 'center',
'left': 'flex-start',
'right': 'flex-end',
}
var DemoBox = React.createClass({
propTypes: {
align: React.PropTypes.oneOf(['center', 'left', 'right']),
children: React.PropTypes.node.isRequired,
},
getDefaultProps () {
return {
align: 'center'
};
},
render () {
let boxStyle = {
backgroundColor: 'rgba(0,0,0,0.05)',
borderRadius: 4,
display: 'flex',
justifyContent: ALIGN_TRANSFORM[this.props.align],
msFlexPack: ALIGN_TRANSFORM[this.props.align],
WebkitJustifyContent: ALIGN_TRANSFORM[this.props.align],
marginBottom: E.width.gutter,
padding: '.66em 1.5em',
};
if (this.props.inverted) {
boxStyle['backgroundColor'] = E.color.appPrimary;
}
let className = classnames('DemoBox', this.props.className);
return <div {...this.props} style={Object.assign({}, boxStyle, this.props.style)} className={className} />;
}
});
module.exports = DemoBox;
|
src/client/app/components/app-root.js
|
LINKIWI/apache-auth
|
import Favicon from 'react-favicon';
import React from 'react';
const AppRoot = ({children}) => (
<div className="app-root">
<Favicon
animated={false}
url={['/static/img/favicon.png']}
/>
{children}
</div>
);
export default AppRoot;
|
src/containers/fbpage.js
|
alexcurtis/react-fbpage
|
'use strict';
import React from 'react';
import { connect } from 'react-redux';
import Page from '../components/page';
import {loadPage} from '../actions';
import defaultTheme from '../themes/default';
@connect(state => ({
loading: state.page.loading,
page: state.page.attributes,
feed: state.page.feed
}))
class FbPage extends React.Component {
componentDidMount(){
this.fetch(this.props.name);
}
componentWillReceiveProps(props){
if(props.name !== this.props.name){ this.fetch(props.name); }
}
fetch(name){
this.props.dispatch(loadPage({ name }));
}
render(){
return (
<Page
style={this.props.style}
loading={this.props.loading}
cover={this.props.page.cover}
profile={this.props.page.profile}
actions={this.props.page.actions}
feed={this.props.feed}
/>
);
}
}
FbPage.propTypes = {
style: React.PropTypes.object,
loading: React.PropTypes.bool,
name: React.PropTypes.string,
page: React.PropTypes.object,
feed: React.PropTypes.object,
dispatch: React.PropTypes.func
};
FbPage.defaultProps = {
style: defaultTheme
};
export default FbPage;
|
src/__mocks__/react-native.js
|
jimthedev/snowflake
|
/* eslint-disable react/no-multi-comp */
/**
* @see http://www.schibsted.pl/2015/10/testing-react-native-components-with-jest/
*/
import React from 'react';
const ReactNative = React;
ReactNative.StyleSheet = {
create: function create(styles) {
return styles;
}
};
class View extends React.Component {
render() { return false; }
}
class PixelRatio extends React.Component {
static get() { return 1; }
}
ReactNative.View = View;
ReactNative.ScrollView = View;
ReactNative.Text = View;
ReactNative.TouchableOpacity = View;
ReactNative.TouchableWithoutFeedback = View;
ReactNative.ToolbarAndroid = View;
ReactNative.Image = View;
ReactNative.PixelRatio = PixelRatio;
ReactNative.NativeModules= {};
ReactNative.Platform = {};
module.exports = ReactNative;
|
src/components/Footer/Footer.js
|
jshin47/ireactforyou
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Footer.scss';
import Link from '../Link';
function Footer() {
return (
<div className={s.root}>
<div className={s.container}>
<span className={s.text}>© Your Company</span>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/">Home</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/privacy">Privacy</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/not-found">Not Found</Link>
</div>
</div>
);
}
export default withStyles(Footer, s);
|
src/components/video_list_item.js
|
fzoozai/redux-stephenGrider
|
import React from 'react';
const VideoListItem = ({ video, onVideoSelect }) => {
const imageUrl = video.snippet.thumbnails.default.url;
return (
<li onClick={() => onVideoSelect(video)} className="list-group-item">
<div className="video-list media">
<div className="media-left">
<img className="media-object" src={imageUrl} />
</div>
<div className="media-body">
<div className="media-heading">{video.snippet.title}</div>
</div>
</div>
</li>
);
};
export default VideoListItem;
|
source/generator-apparena-pattern/generators/app/templates/index.js
|
apparena/patterns
|
import React from 'react';
import PropTypes from 'prop-types';
import {ReactComponent} from 'apparena-patterns-react';
import cx from 'classnames';
import styles from './component.scss';
export default class <%= patternName %> extends ReactComponent {
render()
{
return (
<div>
</div>
);
}
}
|
src/views/HotspotSelector.js
|
learnfwd/lfa-printview-hotspot-editor
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Select from 'react-select';
import { Button } from 'react-bootstrap';
import { selectedHotspotChange, createHotspot, deleteHotspot } from '../actions/UIActions';
import styles from './HotspotSelector.css';
class HotspotSelector extends Component {
selectionChanged = ({ value }) => {
this.props.dispatch(selectedHotspotChange(value));
}
createHotspot = () => {
const value = {
atom: 'atom_name',
top: 10,
left: 10,
width: 80,
height: 20,
};
this.props.dispatch(createHotspot(value));
}
deleteHotspot = () => {
this.props.dispatch(deleteHotspot());
}
render() {
const { selectedHotspot, page } = this.props;
const options = page.get('hotspots').map((hotspot, idx) => ({
value: idx,
label: `Hotspot ${idx + 1}`,
})).toJS();
const deleteButton = (selectedHotspot === null) ? null :
<Button onClick={this.deleteHotspot} className={styles.button}>
<i className='fa fa-fw fa-trash'/>
</Button>;
return <div className={styles.container}>
<Select
className={styles.selector}
placeholder='Select a hotspot'
value={selectedHotspot === null ? null : options[selectedHotspot]}
options={options}
onChange={this.selectionChanged}
/>
{deleteButton}
<Button onClick={this.createHotspot} className={styles.button}>
<i className='fa fa-fw fa-plus'/>
</Button>
</div>;
}
}
export default connect(state => ({
selectedHotspot: state.ui.selectedHotspot,
}))(HotspotSelector);
|
app/javascript/mastodon/features/list_editor/components/search.js
|
honpya/taketodon
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { defineMessages, injectIntl } from 'react-intl';
import { fetchListSuggestions, clearListSuggestions, changeListSuggestions } from '../../../actions/lists';
import classNames from 'classnames';
const messages = defineMessages({
search: { id: 'lists.search', defaultMessage: 'Search among people you follow' },
});
const mapStateToProps = state => ({
value: state.getIn(['listEditor', 'suggestions', 'value']),
});
const mapDispatchToProps = dispatch => ({
onSubmit: value => dispatch(fetchListSuggestions(value)),
onClear: () => dispatch(clearListSuggestions()),
onChange: value => dispatch(changeListSuggestions(value)),
});
@connect(mapStateToProps, mapDispatchToProps)
@injectIntl
export default class Search extends React.PureComponent {
static propTypes = {
intl: PropTypes.object.isRequired,
value: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
onClear: PropTypes.func.isRequired,
};
handleChange = e => {
this.props.onChange(e.target.value);
}
handleKeyUp = e => {
if (e.keyCode === 13) {
this.props.onSubmit(this.props.value);
}
}
handleClear = () => {
this.props.onClear();
}
render () {
const { value, intl } = this.props;
const hasValue = value.length > 0;
return (
<div className='list-editor__search search'>
<label>
<span style={{ display: 'none' }}>{intl.formatMessage(messages.search)}</span>
<input
className='search__input'
type='text'
value={value}
onChange={this.handleChange}
onKeyUp={this.handleKeyUp}
placeholder={intl.formatMessage(messages.search)}
/>
</label>
<div role='button' tabIndex='0' className='search__icon' onClick={this.handleClear}>
<i className={classNames('fa fa-search', { active: !hasValue })} />
<i aria-label={intl.formatMessage(messages.search)} className={classNames('fa fa-times-circle', { active: hasValue })} />
</div>
</div>
);
}
}
|
docs/src/app/components/pages/components/Card/ExampleControlled.js
|
hwo411/material-ui
|
import React from 'react';
import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import Toggle from 'material-ui/Toggle';
export default class CardExampleControlled extends React.Component {
constructor(props) {
super(props);
this.state = {
expanded: false,
};
}
handleExpandChange = (expanded) => {
this.setState({expanded: expanded});
};
handleToggle = (event, toggle) => {
this.setState({expanded: toggle});
};
handleExpand = () => {
this.setState({expanded: true});
};
handleReduce = () => {
this.setState({expanded: false});
};
render() {
return (
<Card expanded={this.state.expanded} onExpandChange={this.handleExpandChange}>
<CardHeader
title="URL Avatar"
subtitle="Subtitle"
avatar="images/ok-128.jpg"
actAsExpander={true}
showExpandableButton={true}
/>
<CardText>
<Toggle
toggled={this.state.expanded}
onToggle={this.handleToggle}
labelPosition="right"
label="This toggle controls the expanded state of the component."
/>
</CardText>
<CardMedia
expandable={true}
overlay={<CardTitle title="Overlay title" subtitle="Overlay subtitle" />}
>
<img src="images/nature-600-337.jpg" alt="" />
</CardMedia>
<CardTitle title="Card title" subtitle="Card subtitle" expandable={true} />
<CardText expandable={true}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi.
Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque.
Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio.
</CardText>
<CardActions>
<FlatButton label="Expand" onTouchTap={this.handleExpand} />
<FlatButton label="Reduce" onTouchTap={this.handleReduce} />
</CardActions>
</Card>
);
}
}
|
__tests__/index.ios.js
|
teamfa/react-native-starter-app
|
import 'react-native';
import React from 'react';
import Index from '../index.ios.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
src/workflows/openfoam/tutorials/components/steps/Introduction/index.js
|
Kitware/HPCCloud
|
import React from 'react';
import DocumentationHTML from '../../../../../generic/components/steps/DocumentationHTML';
import staticContent from './content.html';
export default (props) => <DocumentationHTML staticContent={staticContent} />;
|
dashboard/app/components/LoginMfaForm/LoginMfaForm.js
|
tlisonbee/cerberus-management-service
|
import React from 'react'
import { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { reduxForm, touch } from 'redux-form'
import { finalizeMfaLogin } from '../../actions/authenticationActions'
import MfaDeviceSelect from '../MfaDeviceSelect/MfaDeviceSelect'
import './LoginFormMfa.scss'
const formName = 'login-mfa-form'
/**
* This is the smart component for the create new bucket page,
* This component contains the actual for and handle passing needed things into the dumb component views
*/
export const fields = ['otpToken', 'mfaDeviceId']
// define our client side form validation rules
const validate = values => {
const errors = {}
if (! values.otpToken) {
errors.otpToken = 'Required'
}
if (! values.mfaDeviceId) {
errors.mfaDeviceId = 'Required'
}
return errors
}
@connect((state) => {
return {
mfaDevices: state.auth.mfaDevices,
stateToken: state.auth.stateToken,
isAuthenticating: state.auth.isAuthenticating,
statusText: state.auth.statusText,
initialValues: {
redirectTo: state.routing.locationBeforeTransitions.query.next || '/',
}
}
})
// wire up the redux form
@reduxForm(
{
form: formName,
fields: fields,
validate
}
)
export default class LoginMfaForm extends Component {
static propTypes = {
fields: PropTypes.object.isRequired,
stateToken: PropTypes.string.isRequired,
isAuthenticating: PropTypes.bool.isRequired,
dispatch: PropTypes.func.isRequired,
}
render() {
const {fields: {otpToken, mfaDeviceId}, stateToken, handleSubmit, isAuthenticating, mfaDevices, dispatch} = this.props
return (
<div >
<h3 id="mfa-required-header" className="text-color-">MFA is required.</h3>
<form id={formName} onSubmit={handleSubmit( data => {
dispatch(finalizeMfaLogin(data.otpToken, data.mfaDeviceId, stateToken))
})}>
<div>
<label className='ncss-label'>MFA Devices:</label>
<div id='top-section'>
<MfaDeviceSelect {...mfaDeviceId}
mfaDevices={mfaDevices}
handleBeingTouched={() => {dispatch(touch(formName, 'mfaDeviceId'))}} />
</div>
<div id='security-code-div' className='ncss-form-group'>
<div className={((otpToken.touched && otpToken.error) ? 'ncss-input-container error' : 'ncss-input-container')}>
<label className='ncss-label'>Security Code</label>
<input type='text'
className='ncss-input pt2-sm pr4-sm pb2-sm pl4-sm r'
placeholder='Please enter your OTP token'
autoFocus={true}
{...otpToken}/>
{otpToken.touched && otpToken.error && <div className='ncss-error-msg'>{otpToken.error}</div>}
</div>
</div>
</div>
<div id='login-form-submit-container'>
<div id="login-help">
<a target="_blank" href="/dashboard/help/index.html">Need help?</a>
</div>
<button id='login-mfa-btn'
type='submit'
className='ncss-btn-offwhite ncss-brand pt3-sm pr5-sm pb3-sm pl5-sm pt2-lg pb2-lg u-uppercase'
disabled={isAuthenticating}>Login</button>
</div>
</form>
</div>
)
}
}
|
test/unit/beExpandable.spec.js
|
ryym/react-expander
|
import React from 'react';
import {
renderIntoDocument,
findAllInRenderedTree,
findRenderedComponentWithType as findWithType,
findRenderedDOMComponentWithClass as findWithClassName,
scryRenderedDOMComponentsWithClass as scryWithClassName,
isDOMComponent,
Simulate
} from 'react-addons-test-utils';
import assert from 'power-assert';
import sinon from 'sinon';
import beExpandable from '$src/beExpandable';
import Div from './Div';
describe('beExpandable', function() {
function renderExpandable(Wrappee, props) {
const Expandable = beExpandable(Wrappee);
return renderIntoDocument(<Expandable {...props} />);
}
function makeExpander(props, startResizing) {
return {
props, startResizing
};
}
it('requires expander as a prop', () => {
assert.throws(() => {
renderExpandable(Div, {});
});
});
it('does not add external DOM element', () => {
const div = renderIntoDocument(<Div />);
const expandable = renderExpandable(Div, { expander: {} });
const elements = findAllInRenderedTree(
div, e => isDOMComponent(e)
);
const wrappedElements = findAllInRenderedTree(
expandable, e => isDOMComponent(e)
);
const nExpander = 1;
assert.equal(elements.length + nExpander, wrappedElements.length);
});
it('renders a wrapped component', () => {
const expandable = renderExpandable(Div, { expander: {} });
const wrappee = findWithType(expandable, Div);
assert(wrappee);
});
it('gives width and height to the wrapped component', () => {
const size = { width: 100, height: 100 };
const expandable = renderExpandable(Div, { expander: {}, size });
const div = findWithType(expandable, Div);
const { width, height } = div.props;
assert.deepEqual({ width, height }, size);
});
it('passes all the given props to the wrapped component', () => {
const size = { width: 100, height: 100 };
const expander = {
props: { className: 'expander' }
};
const props = {
expander,
size,
foo: 'foo',
bar: 'bar',
style: { color: 'red', margin: 0 },
onClick: e => { e.preventDefault(); }
};
const expandable = renderExpandable(Div, props);
const div = findWithType(expandable, Div);
const expectedProps = Object.assign(props, size);
delete expectedProps.size;
delete expectedProps.expander;
const divProps = Object.assign({}, div.props);
delete divProps.children;
assert.deepEqual(divProps, expectedProps);
});
it('passes its children to the wrapped component', () => {
const ExpandableDiv = beExpandable(Div);
const expandable = renderIntoDocument(
<ExpandableDiv expander={{}}>
<div className="child-div"></div>
</ExpandableDiv>
);
const child = findWithClassName(expandable, 'child-div');
assert(child);
});
it('renders expander element', () => {
const expander = makeExpander({
className: 'expander'
});
const expandable = renderExpandable(Div, { expander });
const _expander = findWithClassName(expandable, 'expander');
assert(_expander);
});
context('when expander is a function', () => {
it('gets expander from its return value', () => {
function expander() {
return { props: { className: 'expander' } };
}
const expandable = renderExpandable(Div, { expander });
const _expander = findWithClassName(expandable, 'expander');
assert(_expander);
});
});
context('when expanders are set', () => {
it('renders all expanders', () => {
const make = props => makeExpander(
Object.assign({ className: 'expander' }, props)
);
const expanders = [
make({ id: 'id1' }),
make({ id: 'id2' }),
make({ id: 'id3' })
];
const expandable = renderExpandable(Div, { expanders });
const _expanders = scryWithClassName(expandable, 'expander');
assert.deepEqual(
_expanders.map(e => e.id),
['id1', 'id2', 'id3']
);
});
});
describe('expander element', () => {
context('by default', () => {
it('has no default style', () => {
const expander = makeExpander({ ref: 'expander' });
const expandable = renderExpandable(Div, { expander });
const { position, cursor } = expandable.refs.expander.style;
assert.deepEqual([position, cursor], ['', '']);
});
});
context('when defaultStyle is set to true', () => {
it('has default styles', () => {
const expander = makeExpander({
ref: 'expander',
defaultStyle: true
});
const expandable = renderExpandable(Div, { expander });
const { position, cursor } = expandable.refs.expander.style;
assert.deepEqual([position, cursor], ['absolute', 'move']);
});
});
it('has a specified props', () => {
const onClick = sinon.spy();
const expander = makeExpander({
className: 'expander',
ref: 'expander',
onClick
});
const expandable = renderExpandable(Div, { expander });
const _expander = expandable.refs.expander;
// NOTE: React warns if we access '.props' of DOM component directly.
assert(_expander.className, 'expander');
Simulate.click(_expander);
assert(onClick.calledOnce);
});
it('starts resizing on mouse down', () => {
const expander = makeExpander({
className: 'expander'
}, sinon.spy());
const expandable = renderExpandable(Div, { expander });
const _expander = findWithClassName(expandable, 'expander');
Simulate.mouseDown(_expander);
assert(expander.startResizing.calledOnce);
});
});
describe('#startResizing()', () => {
it('stores starting state', () => {
const size = { width: 100, height: 100 };
const expander = { startResizing: () => {} };
const cursorPosition = { clientX: 10, clientY: 20 };
const expandable = renderExpandable(Div, { size, expander });
expandable.startResizing(cursorPosition);
assert(expandable.isExpanding());
});
it('notifies allower that resizing started', () => {
const startResizing = sinon.spy();
const expandable = renderExpandable(Div, {
expander: { startResizing }
});
expandable.startResizing({});
assert(startResizing.calledOnce);
});
});
describe('#stopResizing()', () => {
it('clears a stored starting state', () => {
const expandable = renderExpandable(Div, {
expander: { startResizing: () => {} }
});
expandable.startResizing({});
assert(expandable.isExpanding());
expandable.stopResizing();
assert(! expandable.isExpanding());
});
});
describe('#expand()', () => {
it('calculates new width and height and update state', () => {
function asCursorPoint([x, y]) {
return { clientX: x, clientY: y };
}
const points = [
[0, 0],[10, 10], [20, 20], [30, 30]
];
const width = 100;
const height = 100;
const expandable = renderExpandable(Div, {
size: { width, height },
expander: { startResizing: () => {} }
});
expandable.setState = sinon.spy();
expandable.startResizing({
clientX: 0, clientY: 0
});
points.forEach(point => {
expandable.expand(asCursorPoint(point));
});
const expectedArgs = points.map(([x, y]) => {
return [{
width: width + x,
height: height + y,
isExpanding: true
}];
});
assert.deepEqual(expandable.setState.args, expectedArgs);
});
});
});
|
src/components/Main.js
|
fayfei/gallery-by-react
|
require('normalize.css/normalize.css');
require('styles/main.scss');
import React from 'react';
import ReactDOM from 'react-dom';
//获取图片相关的数据
let imageDatas = require('../data/imageDatas.json');
//利用自执行函数,将图片名信息转成图片URL路径信息
imageDatas = (imageDatasArr => {
for (var i = 0; i < imageDatasArr.length; i++) {
let singleImageData = imageDatasArr[i];
singleImageData.imageURL = require('../images/' + singleImageData.fileName);
imageDatasArr[i] = singleImageData;
}
return imageDatasArr;
})(imageDatas);
function getRangeRandom(low, high) {
return Math.ceil(Math.random() * (high - low)) + low;
}
function get30DegRandom() {
return (Math.random() > 0.5 ? '' : '-') + Math.ceil(Math.random() * 30);
}
class ImgFigure extends React.Component {
handleClick(e) {
if (this.props.arrange.isCenter) {
this.props.inverse();
} else {
this.props.center();
}
e.stopPropagation();
e.preventDefault();
}
render() {
let styleObj = {};
if (this.props.arrange.pos) {
styleObj = this.props.arrange.pos;
}
if (this.props.arrange.rotate) {
['-moz-','-ms-','-webkit-',''].forEach(value => {
styleObj[value + 'transform'] = 'rotate(' + this.props.arrange.rotate + 'deg)';
});
}
if (this.props.arrange.isCenter) {
styleObj['zIndex'] = 11;
}
let ImgFigureClassName = 'img-figure';
ImgFigureClassName += this.props.arrange.isInverse ? ' is-inverse' : '';
return (
<figure className={ImgFigureClassName} style={styleObj} onClick={this.handleClick.bind(this)}>
<img src={this.props.data.imageURL} alt={this.props.data.title}/>
<figcaption>
<h2 className="img-title">{this.props.data.title}</h2>
<div className="img-back" onClick={this.handleClick.bind(this)}>
<p>{this.props.data.desc}</p>
</div>
</figcaption>
</figure>
);
}
}
class ControllerUnit extends React.Component {
handleClick(e) {
if (this.props.arrange.isCenter) {
this.props.inverse();
} else {
this.props.center();
}
e.stopPropagation();
e.preventDefault();
}
render() {
let controllerUnitClassName = 'controller-unit';
if (this.props.arrange.isCenter) {
controllerUnitClassName += ' is-center';
if (this.props.arrange.isInverse) {
controllerUnitClassName += ' is-inverse';
}
}
return (
<span className={controllerUnitClassName} onClick={this.handleClick.bind(this)}></span>
)
}
}
class GalleryByReactApp extends React.Component {
constructor() {
super();
this.Constant = {
centerPos: {
left: 0,
top: 0
},
hPosRange: {
leftSecX: [0, 0],
rightSecX: [0, 0],
y: [0, 0]
},
vPosRange: {
x: [0, 0],
topY: [0, 0]
}
};
this.state = {
imgsArrangeArr: []
};
}
inverse(index) {
return () => {
let imgsArrangeArr = this.state.imgsArrangeArr;
imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse;
this.setState({
imgsArrangeArr: imgsArrangeArr
});
};
}
rearrange(centerIndex) {
let imgsArrangeArr = this.state.imgsArrangeArr,
Constant = this.Constant,
centerPos = Constant.centerPos,
hPosRange = Constant.hPosRange,
vPosRange = Constant.vPosRange,
hPosRangeLeftSecX = hPosRange.leftSecX,
hPosRangeRightSecX = hPosRange.rightSecX,
hPosRangeY = hPosRange.y,
vPosRangeTopY = vPosRange.topY,
vPosRangeX = vPosRange.x,
imgsArrangeTopArr = [],
topImgNum = Math.floor(Math.random() * 2),
topImgSpliceIndex = 0,
imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex, 1);
imgsArrangeCenterArr[0] = {
pos: centerPos,
rotate: 0,
isInverse: false,
isCenter: true
};
topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum));
imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex, topImgNum);
imgsArrangeTopArr.forEach((value, index) => {
imgsArrangeTopArr[index] = {
pos: {
top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]),
left: getRangeRandom(vPosRangeX[0], vPosRangeX[1])
},
rotate: get30DegRandom(),
isInverse: false,
isCenter: false
}
});
for (let i = 0; i < imgsArrangeArr.length; i++) {
let hPosRangeLORX = null;
if (i < imgsArrangeArr.length / 2) {
hPosRangeLORX = hPosRangeLeftSecX;
} else {
hPosRangeLORX = hPosRangeRightSecX;
}
imgsArrangeArr[i] = {
pos: {
top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]),
left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1])
},
rotate: get30DegRandom(),
isInverse: false,
isCenter:false
}
}
if (imgsArrangeTopArr && imgsArrangeTopArr[0]) {
imgsArrangeArr.splice(topImgSpliceIndex, 0, imgsArrangeTopArr[0]);
}
imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]);
this.setState({
imgsArrangeArr: imgsArrangeArr
});
}
center(index) {
return () => this.rearrange(index);
}
componentDidMount() {
let stageDom = this.refs.stage,
stageW = stageDom.scrollWidth,
stageH = stageDom.scrollHeight,
halfStageW = Math.ceil(stageW / 2),
halfStageH = Math.ceil(stageH / 2);
let imgFigureObj = this.refs.imgFigure0,
imgFigureDom = ReactDOM.findDOMNode(imgFigureObj),
imgW = imgFigureDom.scrollWidth,
imgH = imgFigureDom.scrollHeight,
halfImgW = Math.ceil(imgW / 2),
halfImgH = Math.ceil(imgH / 2);
this.Constant.centerPos = {
left: halfStageW - halfImgW,
top: halfStageH - halfImgH
};
this.Constant.hPosRange.leftSecX[0] = -halfImgW;
this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3;
this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW;
this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW;
this.Constant.hPosRange.y[0] = -halfImgH;
this.Constant.hPosRange.y[1] = stageH - halfImgH;
this.Constant.vPosRange.topY[0] = -halfImgH;
this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
this.Constant.vPosRange.x[0] = halfStageW - imgW;
this.Constant.vPosRange.x[1] = halfStageW;
this.rearrange(0);
}
render() {
let controllerUnits = [],
imgFigures = [];
imageDatas.forEach((value, index) => {
if (!this.state.imgsArrangeArr[index]) {
this.state.imgsArrangeArr[index] = {
pos: {
left: 0,
top: 0
},
rotate: 0,
isInverse: false,
isCenter: false
}
}
imgFigures.push(<ImgFigure key={index} data={value} ref={'imgFigure' + index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>);
controllerUnits.push(<ControllerUnit key={index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}></ControllerUnit>)
});
return (
<section className="stage" ref="stage">
<section className="img-sec">
{imgFigures}
</section>
<nav className="controller-nav">
{controllerUnits}
</nav>
</section>
);
}
}
GalleryByReactApp.defaultProps = {
};
export default GalleryByReactApp;
|
examples/huge-apps/components/GlobalNav.js
|
joeyates/react-router
|
import React from 'react';
import { Link } from 'react-router';
const styles = {};
class GlobalNav extends React.Component {
static defaultProps = {
user: {
id: 1,
name: 'Ryan Florence'
}
};
constructor (props, context) {
super(props, context);
this.logOut = this.logOut.bind(this);
}
logOut () {
alert('log out');
}
render () {
var { user } = this.props;
return (
<div style={styles.wrapper}>
<div style={{float: 'left'}}>
<Link to="/" style={styles.link}>Home</Link>{' '}
<Link to="/calendar" style={styles.link} activeStyle={styles.activeLink}>Calendar</Link>{' '}
<Link to="/grades" style={styles.link} activeStyle={styles.activeLink}>Grades</Link>{' '}
<Link to="/messages" style={styles.link} activeStyle={styles.activeLink}>Messages</Link>{' '}
</div>
<div style={{float: 'right'}}>
<Link style={styles.link} to="/profile">{user.name}</Link> <button onClick={this.logOut}>log out</button>
</div>
</div>
);
}
}
var dark = 'hsl(200, 20%, 20%)';
var light = '#fff';
styles.wrapper = {
padding: '10px 20px',
overflow: 'hidden',
background: dark,
color: light
};
styles.link = {
padding: 11,
color: light,
fontWeight: 200
}
styles.activeLink = Object.assign({}, styles.link, {
background: light,
color: dark
});
export default GlobalNav;
|
lib/ErrorModal/ErrorModal.js
|
folio-org/stripes-components
|
import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import Button from '../Button';
import Modal from '../Modal';
import ModalFooter from '../ModalFooter';
const ErrorModal = ({
ariaLabel,
bodyTag: Element,
open,
content,
label,
buttonLabel,
onClose,
...rest
}) => {
const footer = (
<ModalFooter>
<Button
data-test-error-modal-close-button
onClick={onClose}
>
{buttonLabel || <FormattedMessage id="stripes-components.close" />}
</Button>
</ModalFooter>
);
return (
<Modal
data-test-error-modal
aria-label={rest['aria-label'] || ariaLabel}
open={open}
size="small"
label={label}
footer={footer}
>
<Element data-test-error-modal-content>
{content}
</Element>
</Modal>
);
};
ErrorModal.propTypes = {
ariaLabel: PropTypes.string,
bodyTag: PropTypes.string,
buttonLabel: PropTypes.oneOfType([
PropTypes.string,
PropTypes.node,
]),
content: PropTypes.node.isRequired,
label: PropTypes.node.isRequired,
onClose: PropTypes.func.isRequired,
open: PropTypes.bool.isRequired,
};
ErrorModal.defaultProps = {
bodyTag: 'div',
};
export default ErrorModal;
|
src/client/components/ui/slider/Slider.js
|
JulienPradet/quizzALJP
|
import React from 'react'
import Error from '../error/Error'
export default class Slider extends React.Component {
render() {
const activeSlide = this.props.children.length > this.props.activeIndex
? this.props.children[activeIndex]
: <Error>Wrong index displayed</Error>
return (
<div>
{ this.props.children[activeIndex] }
</div>
)
}
}
|
app/components/link1.js
|
varunagg45/webpack-react-sample-project
|
import React from 'react';
export default React.createClass({
getInitialState: function() {
return {
'page': 'This is from Link 1'
};
},
render: function() {
return (
<div>{this.state.page}</div>
);
}
});
|
test/client/components/Auth/LoginPageTests.js
|
andela-jmuturi/docman-react-redux
|
import React from 'react';
import { shallow, mount } from 'enzyme';
import { expect } from 'chai';
import sinon from 'sinon';
import { CardTitle } from 'material-ui/Card';
import LoginPage from '../../../../client/src/components/Auth/LoginPage';
import { getContexts, shallowWithContext } from '../utils';
describe('Login Page', () => {
it('renders with a Login title', () => {
const wrapper = shallow(<LoginPage />);
expect(wrapper.containsMatchingElement(
<CardTitle title='Login' />
)).to.be.true;
});
it('renders a username text field', () => {
const wrapper = mount(<LoginPage />, getContexts());
expect(wrapper.text()).to.contain('Enter Username');
});
it('renders a password text field', () => {
const wrapper = mount(<LoginPage />, getContexts());
expect(wrapper.text()).to.contain('Enter Password');
});
it('performs login when the login button is clicked', () => {
const onAuthAction = sinon.stub();
const wrapper = shallowWithContext(
<LoginPage onAuthAction={onAuthAction} />);
wrapper.childAt(2).childAt(0).simulate('click');
expect(onAuthAction.calledOnce).to.be.true;
});
it('toggles registration view when register button is clicked', () => {
const toggleView = sinon.stub();
const wrapper = shallowWithContext(
<LoginPage handleToggleView={toggleView} />);
wrapper
.childAt(2)
.childAt(1)
.childAt(2)
.simulate('click');
expect(toggleView.calledOnce).to.be.true;
});
it('shows a loading animation when posting details to the server', () => {
const wrapper = shallowWithContext(
<LoginPage
auth={{
isFetching: true,
credentials: {},
validations: {}
}}
/>
);
expect(wrapper.childAt(2).is('CircularProgress')).to.be.true;
});
it('shows validation errors when they occur', () => {
const props = {
auth: {
validations: {
password: 'This field should be more than that number of characters'
},
credentials: {},
isFetching: false
}
};
const wrapper = shallowWithContext(<LoginPage {...props} />);
const validationErr = wrapper
.childAt(1)
.childAt(1)
.childAt(1)
.childAt(1);
expect(validationErr.is('ValidationError')).to.be.true;
expect(validationErr.props().error)
.to.equal('This field should be more than that number of characters');
});
});
|
src/svg-icons/action/important-devices.js
|
ruifortes/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionImportantDevices = (props) => (
<SvgIcon {...props}>
<path d="M23 11.01L18 11c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1h5c.55 0 1-.45 1-1v-9c0-.55-.45-.99-1-.99zM23 20h-5v-7h5v7zM20 2H2C.89 2 0 2.89 0 4v12c0 1.1.89 2 2 2h7v2H7v2h8v-2h-2v-2h2v-2H2V4h18v5h2V4c0-1.11-.9-2-2-2zm-8.03 7L11 6l-.97 3H7l2.47 1.76-.94 2.91 2.47-1.8 2.47 1.8-.94-2.91L15 9h-3.03z"/>
</SvgIcon>
);
ActionImportantDevices = pure(ActionImportantDevices);
ActionImportantDevices.displayName = 'ActionImportantDevices';
ActionImportantDevices.muiName = 'SvgIcon';
export default ActionImportantDevices;
|
client/src/components/app.js
|
kat09kat09/GigRTC
|
import React from 'react';
import { Component,PropTypes } from 'react';
import SideBar from './sidebar';
import Header from './header';
import MyRawTheme from '../../public/css/giggTheme';
import ThemeManager from 'material-ui/lib/styles/theme-manager';
import ThemeDecorator from 'material-ui/lib/styles/theme-decorator';
import {determineEnvironment,refreshLoginState} from '../actions';
import {connect} from 'react-redux';
import injectTapEventPlugin from 'react-tap-event-plugin';
import mui from 'material-ui';
import AppBar from 'material-ui/lib/app-bar';
import jwtDecode from 'jwt-decode'
//let ThemeManager = mui.Styles.ThemeManager;
// let Colors = mui.Styles.Colors;
// let Style= mui.Styles.LightRawTheme;
injectTapEventPlugin();
export class App extends Component {
constructor(props) {
super(props);
}
componentWillMount(){
const{dispatch} = this.props
if(localStorage.getItem('token')){
dispatch(refreshLoginState({email : jwtDecode(localStorage.getItem('token')).user_name}))
}
}
getChildContext() {
return {
stores: this.props.stores,
muiTheme: ThemeManager.getMuiTheme(MyRawTheme)
};
}
render() {
return (
<div className="appComponentBody">
<Header/>
<SideBar/>
<div className="videoWrapper">
{this.props.children}
</div>
</div>
);
}
}
App.childContextTypes = {
stores: React.PropTypes.object,
muiTheme: React.PropTypes.object
};
function mapStateToProps(state){
return {
environment : state.environment,
tokenState : state.auth
}
}
export default connect(mapStateToProps)(App)
|
packages/material-ui-icons/src/InsertDriveFile.js
|
AndriusBil/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let InsertDriveFile = props =>
<SvgIcon {...props}>
<path d="M6 2c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6H6zm7 7V3.5L18.5 9H13z" />
</SvgIcon>;
InsertDriveFile = pure(InsertDriveFile);
InsertDriveFile.muiName = 'SvgIcon';
export default InsertDriveFile;
|
frontend/src/System/Backup/BackupsConnector.js
|
lidarr/Lidarr
|
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import * as commandNames from 'Commands/commandNames';
import { executeCommand } from 'Store/Actions/commandActions';
import { deleteBackup, fetchBackups } from 'Store/Actions/systemActions';
import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector';
import Backups from './Backups';
function createMapStateToProps() {
return createSelector(
(state) => state.system.backups,
createCommandExecutingSelector(commandNames.BACKUP),
(backups, backupExecuting) => {
const {
isFetching,
isPopulated,
error,
items
} = backups;
return {
isFetching,
isPopulated,
error,
items,
backupExecuting
};
}
);
}
function createMapDispatchToProps(dispatch, props) {
return {
dispatchFetchBackups() {
dispatch(fetchBackups());
},
onDeleteBackupPress(id) {
dispatch(deleteBackup({ id }));
},
onBackupPress() {
dispatch(executeCommand({
name: commandNames.BACKUP
}));
}
};
}
class BackupsConnector extends Component {
//
// Lifecycle
componentDidMount() {
this.props.dispatchFetchBackups();
}
componentDidUpdate(prevProps) {
if (prevProps.backupExecuting && !this.props.backupExecuting) {
this.props.dispatchFetchBackups();
}
}
//
// Render
render() {
return (
<Backups
{...this.props}
/>
);
}
}
BackupsConnector.propTypes = {
backupExecuting: PropTypes.bool.isRequired,
dispatchFetchBackups: PropTypes.func.isRequired
};
export default connect(createMapStateToProps, createMapDispatchToProps)(BackupsConnector);
|
examples/counter/containers/App.js
|
joshblack/redux
|
import React, { Component } from 'react';
import CounterApp from './CounterApp';
import { createRedux } from 'redux';
import { Provider } from 'redux/react';
import * as stores from '../stores';
const redux = createRedux(stores);
export default class App extends Component {
render() {
return (
<Provider redux={redux}>
{() => <CounterApp />}
</Provider>
);
}
}
|
test/utils/CustomPropTypesSpec.js
|
roderickwang/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import CustomPropTypes from '../../src/utils/CustomPropTypes';
import {shouldWarn} from '../helpers';
function isChainableAndUndefinedOK(validatorUnderTest) {
it('Should validate OK with undefined or null values', function() {
assert.isUndefined(validatorUnderTest({}, 'p', 'Component'));
assert.isUndefined(validatorUnderTest({p: null}, 'p', 'Component'));
});
it('Should be able to chain', function() {
let err = validatorUnderTest.isRequired({}, 'p', 'Component');
assert.instanceOf(err, Error);
assert.include(err.message, 'Required prop');
assert.include(err.message, 'was not specified in');
});
}
describe('CustomPropTypes', function() {
describe('mountable', function () {
function validate(prop) {
return CustomPropTypes.mountable({p: prop}, 'p', 'Component');
}
isChainableAndUndefinedOK(CustomPropTypes.mountable);
it('Should return error with non mountable values', function() {
let err = validate({});
assert.instanceOf(err, Error);
assert.include(err.message, 'expected a DOM element or an object that has a `render` method');
});
it('Should return undefined with mountable values', function() {
assert.isUndefined(validate(document.createElement('div')));
assert.isUndefined(validate(document.body));
assert.isUndefined(validate(ReactTestUtils.renderIntoDocument(<div />)));
});
});
describe('elementType', function () {
function validate(prop) {
return CustomPropTypes.elementType({p: prop}, 'p', 'TestComponent');
}
isChainableAndUndefinedOK(CustomPropTypes.elementType);
it('Should validate OK with elementType values', function() {
assert.isUndefined(validate('span'));
assert.isUndefined(validate(function(){}));
});
it('Should return error with not a string or function values', function() {
let err = validate({});
assert.instanceOf(err, Error);
assert.include(err.message, 'Expected an Element `type` such as a tag name or return value of React.createClass(...)');
});
it('Should return error with react element', function() {
let err = validate(React.createElement('span'));
assert.instanceOf(err, Error);
assert.include(err.message, 'Expected an Element `type`, not an actual Element');
});
});
describe('keyOf', function () {
let obj = {'foo': 1};
function validate(prop) {
return CustomPropTypes.keyOf(obj)({p: prop}, 'p', 'Component');
}
isChainableAndUndefinedOK(CustomPropTypes.keyOf(obj));
it('Should return error with non-key values', function() {
let err = validate('bar');
assert.instanceOf(err, Error);
assert.include(err.message, 'expected one of ["foo"]');
});
it('Should validate OK with key values', function() {
assert.isUndefined(validate('foo'));
obj.bar = 2;
assert.isUndefined(validate('bar'));
});
});
describe('singlePropFrom', function () {
function validate(testProps) {
const propList = ['children', 'value'];
return CustomPropTypes.singlePropFrom(propList)(testProps, 'value', 'Component');
}
it('Should validate OK if only one listed prop in used', function () {
const testProps = {value: 5};
assert.isUndefined(validate(testProps));
});
it('Should return error if multiple of the listed properties have values', function () {
let err = validate({value: 5, children: 5});
assert.instanceOf(err, Error);
assert.include(err.message, 'only one of the following may be provided: value and children');
});
});
describe('all', function() {
let validators;
const props = {
key: 'value'
};
const propName = 'key';
const componentName = 'TestComponent';
beforeEach(function() {
validators = [
sinon.stub(),
sinon.stub(),
sinon.stub()
];
});
it('with no arguments provided', function() {
expect(() => {
CustomPropTypes.all();
}).to.throw(Error, /No validations provided/);
});
it('with no validations provided', function() {
expect(() => {
CustomPropTypes.all([]);
}).to.throw(Error, /No validations provided/);
});
it('with invalid arguments provided', function() {
expect(() => {
CustomPropTypes.all(1);
}).to.throw(Error, /Invalid argument must be an array/);
});
it('validates each validation', function() {
const all = CustomPropTypes.all(validators);
let result = all(props, propName, componentName);
expect(result).to.equal(undefined);
validators.forEach(x => {
x.should.have.been.calledOnce
.and.calledWith(props, propName, componentName);
});
});
it('returns first validation failure', function() {
let err = new Error('Failure');
validators[1].returns(err);
const all = CustomPropTypes.all(validators);
let result = all(props, propName, componentName);
expect(result).to.equal(err);
validators[0].should.have.been.calledOnce
.and.calledWith(props, propName, componentName);
validators[1].should.have.been.calledOnce
.and.calledWith(props, propName, componentName);
validators[2].should.not.have.been.called;
});
});
describe('isRequiredForA11y', function () {
function validate(prop) {
return CustomPropTypes.isRequiredForA11y(React.PropTypes.string)({p: prop}, 'p', 'Component');
}
it('Should validate OK when property is provided', function() {
let err = validate('aria-tag');
assert.notInstanceOf(err, Error);
});
it('Should return custom error message when property is not provided', function() {
let err = validate(null);
assert.instanceOf(err, Error);
assert.include(err.message, 'accessible for users using assistive technologies such as screen readers');
});
});
describe('deprecated', function () {
function validate(prop) {
return CustomPropTypes.deprecated(React.PropTypes.string, 'Read more at link')({pName: prop}, 'pName', 'ComponentName');
}
it('Should warn about deprecation and validate OK', function() {
let err = validate('value');
shouldWarn('"pName" property of "ComponentName" has been deprecated.\nRead more at link');
assert.notInstanceOf(err, Error);
});
it('Should warn about deprecation and throw validation error when property value is not OK', function() {
let err = validate({});
shouldWarn('"pName" property of "ComponentName" has been deprecated.\nRead more at link');
assert.instanceOf(err, Error);
assert.include(err.message, 'Invalid undefined `pName` of type `object` supplied to `ComponentName`');
});
});
});
|
client/src/containers/drived_gate/DrivedGate.js
|
thewizardplusplus/vk-group-stats
|
import React from 'react'
import {fetchLogin} from '../../actions/login'
import {connect} from 'react-redux'
import StatefulGate from '../../components/stateful_gate/StatefulGate'
function mapStateToProps(state) {
return {
state: state.login.state,
open: state.login.isLogged,
}
}
function mapDispatchToProps(dispatch) {
return {
onMount() {
dispatch(fetchLogin())
},
}
}
export const DrivedGate = connect(
mapStateToProps,
mapDispatchToProps
)(StatefulGate)
DrivedGate.propTypes = {
children: React.PropTypes.node.isRequired,
}
|
NavigationReact/sample/isomorphic/index.js
|
grahammendick/navigation
|
import React from 'react';
import ReactDOM from 'react-dom';
import { NavigationHandler } from 'navigation-react';
import getStateNavigator from './getStateNavigator';
import App from './App';
var stateNavigator = getStateNavigator();
registerControllers(stateNavigator);
stateNavigator.start();
ReactDOM.hydrate(
<NavigationHandler stateNavigator={stateNavigator}>
<App />
</NavigationHandler>,
document.getElementById('content')
);
function registerControllers(stateNavigator) {
stateNavigator.states.people.navigating =
stateNavigator.states.person.navigating = function(data, url, navigate) {
fetchData(url, navigate);
}
}
function fetchData(url, navigate) {
if (serverProps) {
navigate(serverProps);
serverProps = null;
return;
}
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState === 4){
navigate(JSON.parse(req.responseText));
}
};
req.open('get', url);
req.setRequestHeader('Content-Type', 'application/json');
req.send(null);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.