path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
react-semi-theme/src/widgets/Confirm.js
|
tsupol/semi-starter
|
/* eslint-disable import/default */
import React, { Component } from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
class Confirm extends Component {
constructor(props, context) {
super(props, context);
this.state = {
open: false,
title: 'Confirm',
description: 'Something happened!'
};
this.close = this.close.bind(this);
this.open = this.open.bind(this);
this.onConfirm = this.onConfirm.bind(this);
}
close(){
if(this.state.callback) this.state.callback(false);
this.setState({ open: false });
// this.props.alertFunction() ;
}
open([description, title, callback, data]){
this.setState({ open: true, description, title, callback});
}
onConfirm() {
// todo : confirm function
if(this.state.callback) this.state.callback(true);
this.setState({ open: false });
}
render() {
let state = this.state;
const actions = [
<FlatButton
label="Cancel"
key="cancelBtn"
primary={true}
onTouchTap={this.close}
/>,
<FlatButton
label="Confirm"
key="okBtn"
primary={true}
onTouchTap={this.onConfirm}
/>
];
return (
<Dialog
style={{zIndex: 99999}}
titleStyle={{ backgroundColor: '#C62828', color: '#FFFFFF' }}
title={state.title}
actions={actions}
modal={false}
open={this.state.open}
onRequestClose={this.close}
bodyStyle={{ marginTop: 20 }}
autoScrollBodyContent={true}
>
{state.description}
</Dialog>
);
}
}
Confirm.propTypes = {};
export default Confirm;
|
client/admin/info/RocketChatSection.js
|
iiet/iiet-chat
|
import { Skeleton } from '@rocket.chat/fuselage';
import React from 'react';
import Subtitle from '../../components/basic/Subtitle';
import { useTranslation } from '../../contexts/TranslationContext';
import { useFormatDateAndTime } from '../../hooks/useFormatDateAndTime';
import { useFormatDuration } from '../../hooks/useFormatDuration';
import { DescriptionList } from './DescriptionList';
export const RocketChatSection = React.memo(function RocketChatSection({ info, statistics, isLoading }) {
const t = useTranslation();
const formatDateAndTime = useFormatDateAndTime();
const formatDuration = useFormatDuration();
const s = (fn) => (isLoading ? <Skeleton width='50%' /> : fn());
const appsEngineVersion = info && info.marketplaceApiVersion;
return <DescriptionList
data-qa='rocket-chat-list'
title={<Subtitle data-qa='rocket-chat-title'>{t('Rocket.Chat')}</Subtitle>}
>
<DescriptionList.Entry label={t('Version')}>{s(() => statistics.version)}</DescriptionList.Entry>
{appsEngineVersion && <DescriptionList.Entry label={t('Apps_Engine_Version')}>{appsEngineVersion}</DescriptionList.Entry>}
<DescriptionList.Entry label={t('DB_Migration')}>{s(() => statistics.migration.version)}</DescriptionList.Entry>
<DescriptionList.Entry label={t('DB_Migration_Date')}>{s(() => formatDateAndTime(statistics.migration.lockedAt))}</DescriptionList.Entry>
<DescriptionList.Entry label={t('Installed_at')}>{s(() => formatDateAndTime(statistics.installedAt))}</DescriptionList.Entry>
<DescriptionList.Entry label={t('Uptime')}>{s(() => formatDuration(statistics.process.uptime))}</DescriptionList.Entry>
<DescriptionList.Entry label={t('Deployment_ID')}>{s(() => statistics.uniqueId)}</DescriptionList.Entry>
<DescriptionList.Entry label={t('PID')}>{s(() => statistics.process.pid)}</DescriptionList.Entry>
<DescriptionList.Entry label={t('Running_Instances')}>{s(() => statistics.instanceCount)}</DescriptionList.Entry>
<DescriptionList.Entry label={t('OpLog')}>{s(() => (statistics.oplogEnabled ? t('Enabled') : t('Disabled')))}</DescriptionList.Entry>
</DescriptionList>;
});
|
example/Example.js
|
quocnguyenvan/react-native-animated-message
|
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
Picker
} from 'react-native';
import Message from 'react-native-animated-message';
export default class Example extends Component {
constructor(props) {
super(props);
this.state = {
position: 'top',
animation: 'slideX'
}
}
render() {
return (
<View style={styles.container}>
<Button title="Top"
onPress={()=> {
this.setState({
position: 'top'
}, ()=> { this.message.showMessage('This is a message - top', 1000) })
}} />
<Button title="Center"
onPress={()=> {
this.setState({
position: 'center'
}, ()=> { this.message.showMessage('This is a message - center', 1000) })
}} />
<Button title="Bottom"
onPress={()=> {
this.setState({
position: 'bottom'
}, ()=> { this.message.showMessage('This is a message - bottom', 1000) })
}} />
<View style={styles.viewAnimation}>
<Text style={styles.textAnimationType}>Animation type: </Text>
<Picker
style={styles.picker}
selectedValue={this.state.animation}
onValueChange={(value) => this.setState({animation: value})}>
<Picker.Item label="Slide X" value="slideX" />
<Picker.Item label="Slide Y" value="slideY" />
<Picker.Item label="Zoom" value="zoom" />
</Picker>
</View>
<Message
ref={(message) => this.message = message }
animation={this.state.animation}
position={this.state.position} >
</Message>
</View>
);
}
}
class Button extends Component {
render() {
return (
<TouchableOpacity
style={styles.button}
onPress={this.props.onPress}>
<Text style={styles.textButton}>{this.props.title}</Text>
</TouchableOpacity>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#CCFFFF',
},
button: {
padding: 10,
width: 100,
height: 45,
marginBottom: 5,
backgroundColor: 'blue',
borderRadius: 8,
justifyContent: 'center'
},
textButton: {
color: 'white',
textAlign: 'center',
fontWeight: 'bold',
fontSize: 16
},
textAnimationType: {
color: 'black',
fontSize: 18,
fontWeight: '700',
marginRight: 5
},
viewAnimation: {
flexDirection: 'row',
marginTop: 10,
justifyContent: 'center',
alignItems: 'center'
},
picker: {
width: 160,
marginLeft: 10
}
});
|
src/internal/__tests__/Selection-test.js
|
jzhang300/carbon-components-react
|
import React from 'react';
import Selection from '../Selection';
import { mount } from 'enzyme';
describe('Selection', () => {
let mockProps;
beforeEach(() => {
mockProps = {
initialSelectedItems: [],
render: jest.fn(() => <div />),
};
});
it('should render', () => {
const wrapper = mount(<Selection {...mockProps} />);
expect(wrapper).toMatchSnapshot();
});
it('should be able to add or remove an item from the callback props', () => {
const wrapper = mount(
<Selection
{...mockProps}
render={({ onItemChange }) => (
<button onClick={() => onItemChange(1)} />
)}
/>
);
expect(wrapper.state('selectedItems').length).toBe(0);
wrapper.find('button').simulate('click');
expect(wrapper.state('selectedItems').length).toBe(1);
wrapper.find('button').simulate('click');
expect(wrapper.state('selectedItems').length).toBe(0);
});
it('should give a list of all selected items from the callback props', () => {
const wrapper = mount(
<Selection
{...mockProps}
render={({ selectedItems, onItemChange }) => (
<div>
<button onClick={() => onItemChange(1)} />
<ul>
{selectedItems.map((item, index) => <li key={index}>{item}</li>)}
</ul>
</div>
)}
/>
);
expect(wrapper.find('li').length).toBe(0);
wrapper.find('button').simulate('click');
expect(wrapper.find('li').length).toBe(1);
});
it('should be able to clear the selection from the callback props', () => {
const wrapper = mount(
<Selection
{...mockProps}
render={({ onItemChange, clearSelection }) => (
<div>
<button id="add-item" onClick={() => onItemChange(1)} />
<button id="clear-selection" onClick={clearSelection} />
</div>
)}
/>
);
expect(wrapper.state('selectedItems')).toEqual([]);
wrapper.find('#add-item').simulate('click');
expect(wrapper.state('selectedItems')).toEqual([1]);
wrapper.find('#clear-selection').simulate('click');
expect(wrapper.state('selectedItems')).toEqual([]);
});
});
|
js-old/src/modals/VaultSelector/vaultSelector.spec.js
|
destenson/ethcore--parity
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import { shallow } from 'enzyme';
import React from 'react';
import sinon from 'sinon';
import VaultSelector from './';
const VAULTS_OPENED = [
{ name: 'A', isOpen: true },
{ name: 'B', isOpen: true }
];
const VAULTS_CLOSED = [
{ name: 'C' },
{ name: 'D' }
];
const VAULTS_ALL = VAULTS_OPENED.concat(VAULTS_CLOSED);
let component;
let instance;
let onClose;
let onSelect;
let vaultStore;
function createVaultStore () {
vaultStore = {
vaults: VAULTS_ALL,
vaultsOpened: VAULTS_OPENED
};
return vaultStore;
}
function render () {
onClose = sinon.stub();
onSelect = sinon.stub();
component = shallow(
<VaultSelector
onClose={ onClose }
onSelect={ onSelect }
selected='firstValue'
vaultStore={ createVaultStore() }
/>
);
instance = component.instance();
return component;
}
describe('ui/VaultSelector', () => {
beforeEach(() => {
render();
});
it('renders defaults', () => {
expect(component).to.be.ok;
});
describe('components', () => {
describe('Portal', () => {
let portal;
beforeEach(() => {
portal = component.find('Portal');
});
it('renders', () => {
expect(portal.get(0)).to.be.ok;
});
it('opens as a child modal', () => {
expect(portal.props().isChildModal).to.be.true;
});
it('passes the instance onClose', () => {
expect(portal.props().onClose).to.equal(instance.onClose);
});
});
describe('SelectionList', () => {
let list;
beforeEach(() => {
list = component.find('SelectionList');
});
it('renders', () => {
expect(list.get(0)).to.be.ok;
});
it('passes the open vaults', () => {
expect(list.props().items).to.deep.equal(VAULTS_OPENED);
});
it('passes internal renderItem', () => {
expect(list.props().renderItem).to.equal(instance.renderVault);
});
it('passes internal isChecked', () => {
expect(list.props().isChecked).to.equal(instance.isSelected);
});
it('passes internal onSelectClick', () => {
expect(list.props().onSelectClick).to.equal(instance.onSelect);
});
});
});
describe('instance methods', () => {
describe('renderVault', () => {
let card;
beforeEach(() => {
card = instance.renderVault({ name: 'testVault' });
});
it('renders VaultCard', () => {
expect(card).to.be.ok;
});
});
describe('isSelected', () => {
it('returns true when vault name matches', () => {
expect(instance.isSelected({ name: 'firstValue' })).to.be.true;
});
it('returns false when vault name does not match', () => {
expect(instance.isSelected({ name: 'testValue' })).to.be.false;
});
});
describe('onSelect', () => {
it('calls into props onSelect', () => {
instance.onSelect({ name: 'testing' });
expect(onSelect).to.have.been.called;
});
it('passes name when new selection made', () => {
instance.onSelect({ name: 'newValue' });
expect(onSelect).to.have.been.calledWith('newValue');
});
it('passes empty name when current selection made', () => {
instance.onSelect({ name: 'firstValue' });
expect(onSelect).to.have.been.calledWith('');
});
});
describe('onClose', () => {
it('calls props onClose', () => {
instance.onClose();
expect(onClose).to.have.been.called;
});
});
});
});
|
app/containers/BattleContainer.js
|
paladinze/testSemantic
|
import React from 'react'
import BattlePrompt from '../components/BattlePrompt'
import CourseHelpers from '../utils/CourseHelpers'
class BattleContainer extends React.Component {
static contextTypes = {
router: React.PropTypes.object.isRequired
}
state = {
isLoading: true,
coursesInfo: []
}
componentDidMount() {
let query = this.props.location.query
let that = this
CourseHelpers.getCoursesInfo([1,2])
.then((courses) => {
that.setState({
isLoading: false,
coursesInfo: [courses[0], courses[1]]
})
})
}
handleStartBattle() {
this.context.router.push({
pathname: '/results',
state: {
coursesInfo: this.state.coursesInfo
}
})
}
render() {
return (
<BattlePrompt
isLoading={this.state.isLoading}
coursesInfo={this.state.coursesInfo}
onStartBattle={this.handleStartBattle.bind(this)}
/>
)
}
}
export default BattleContainer
|
pkg/interface/publish/src/js/components/lib/comment-item.js
|
jfranklin9000/urbit
|
import React, { Component } from 'react';
import moment from 'moment';
import { Sigil } from './icons/sigil';
import { CommentInput } from './comment-input';
import { uxToHex, cite } from '../../lib/util';
export class CommentItem extends Component {
constructor(props) {
super(props);
this.state = {
commentBody: ''
};
this.commentChange = this.commentChange.bind(this);
this.commentEdit = this.commentEdit.bind(this);
moment.updateLocale('en', {
relativeTime: {
past: function(input) {
return input === 'just now'
? input
: input + ' ago';
},
s : 'just now',
future : 'in %s',
m : '1m',
mm : '%dm',
h : '1h',
hh : '%dh',
d : '1d',
dd : '%dd',
M : '1 month',
MM : '%d months',
y : '1 year',
yy : '%d years'
}
});
}
commentEdit() {
const commentPath = Object.keys(this.props.comment)[0];
const commentBody = this.props.comment[commentPath].content;
this.setState({ commentBody });
this.props.onEdit();
}
focusTextArea(text) {
text && text.focus();
}
commentChange(e) {
this.setState({
commentBody: e.target.value
});
}
onUpdate() {
this.props.onUpdate(this.state.commentBody);
}
render() {
const pending = this.props.pending ? 'o-60' : '';
const commentData = this.props.comment[Object.keys(this.props.comment)[0]];
const content = commentData.content.split('\n').map((line, i) => {
return (
<p className="mb2" key={i}>{line}</p>
);
});
const date = moment(commentData['date-created']).fromNow();
const contact = commentData.author.substr(1) in this.props.contacts
? this.props.contacts[commentData.author.substr(1)] : false;
let name = commentData.author;
let color = '#000000';
let classes = 'mix-blend-diff';
let avatar = null;
if (contact) {
name = (contact.nickname.length > 0)
? contact.nickname : commentData.author;
color = `#${uxToHex(contact.color)}`;
classes = '';
avatar = contact.avatar;
}
const img = (avatar !== null)
? <img src={avatar} height={24} width={24} className="dib" />
: <Sigil
ship={commentData.author}
size={24}
color={color}
classes={classes}
/>;
if (name === commentData.author) {
name = cite(commentData.author);
}
const { editing } = this.props;
const disabled = this.props.pending
|| window.ship !== commentData.author.slice(1);
return (
<div className={'mb8 ' + pending}>
<div className="flex mv3 bg-white bg-gray0-d">
{img}
<div className={'f9 mh2 pt1 ' +
(contact.nickname ? null : 'mono')}
title={commentData.author}
>
{name}
</div>
<div className="f9 gray3 pt1">{date}</div>
{ !editing && !disabled && (
<>
<div onClick={this.commentEdit.bind(this)} className="green2 pointer ml2 f9 pt1">
Edit
</div>
<div onClick={this.props.onDelete} className="red2 pointer ml2 f9 pt1">
Delete
</div>
</>
) }
</div>
<div className="f8 lh-solid mb2">
{ !editing && content }
{ editing && (
<CommentInput style={{ resize:'vertical' }}
ref={(el) => {
this.focusTextArea(el);
}}
onChange={this.commentChange}
value={this.state.commentBody}
onSubmit={this.onUpdate.bind(this)}
>
</CommentInput>
)}
</div>
{ editing && (
<div className="flex">
<div onClick={this.onUpdate.bind(this)} className="br1 green2 pointer f9 pt1 b--green2 ba pa2 dib">
Submit
</div>
<div onClick={this.props.onEditCancel} className="br1 black white-d pointer f9 b--gray2 ba pa2 dib ml2">
Cancel
</div>
</div>
)}
</div>
);
}
}
export default CommentItem;
|
src/RouteContainer.js
|
devknoll/relay-nested-routes
|
import PropTypes from 'prop-types';
import React from 'react';
import StaticContainer from 'react-static-container';
import mergeRouteParams from './utils/mergeRouteParams';
const propTypes = {
queries: PropTypes.object.isRequired,
routerProps: PropTypes.object.isRequired,
children: PropTypes.element.isRequired,
};
const contextTypes = {
queryAggregator: PropTypes.object.isRequired,
};
function RouteContainer(
{ queries, routerProps, children, ...extraProps },
{ queryAggregator },
) {
const { key, route, routes } = routerProps;
let params = {};
for (const ancestorRoute of routes) {
params = mergeRouteParams(params, ancestorRoute, routerProps);
if (ancestorRoute === route) {
break;
}
}
const renderArgs =
queryAggregator.getRenderArgs(route, key, queries, params);
const { props } = renderArgs;
let { render } = route;
if (render && typeof render === 'object') {
render = render[key];
}
// The below is largely copied from RelayReadyStateRenderer.
let element;
if (render) {
element = render.call(route, {
...renderArgs,
props: props && {
...routerProps,
...extraProps,
...params,
...props,
},
routerProps: {
...routerProps,
...extraProps,
},
element: children,
});
} else if (props) {
// The child already has routerProps, so just inject the additional props.
element = React.cloneElement(children, {
...extraProps,
...params,
...props,
});
}
let shouldUpdate;
if (element === undefined) {
element = null;
shouldUpdate = false;
} else {
shouldUpdate = true;
}
return (
<StaticContainer shouldUpdate={shouldUpdate}>
{element}
</StaticContainer>
);
}
RouteContainer.propTypes = propTypes;
RouteContainer.contextTypes = contextTypes;
export default RouteContainer;
|
Redux-Async/test/helpers/shallowRenderHelper.js
|
FillInjava/react-redux-webpack
|
/**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
features/app/components/App.native.js
|
jitsi/jitsi-meet-react
|
import React from 'react';
import { Linking, Navigator } from 'react-native';
import { Provider } from 'react-redux';
import { _getRouteToRender } from '../functions';
import { AbstractApp } from './AbstractApp';
/**
* Root application component.
*
* @extends AbstractApp
*/
export class App extends AbstractApp {
/**
* Initializes a new App instance.
*
* @param {Object} props - The read-only React Component props with which
* the new instance is to be initialized.
*/
constructor(props) {
super(props);
// Bind event handlers so they are only bound once for every instance.
this._navigatorRenderScene = this._navigatorRenderScene.bind(this);
this._onLinkingURL = this._onLinkingURL.bind(this);
}
/**
* Subscribe to notifications about activating URLs registered to be handled
* by this app.
*
* @inheritdoc
* @see https://facebook.github.io/react-native/docs/linking.html
* @returns {void}
*/
componentWillMount() {
super.componentWillMount();
Linking.addEventListener('url', this._onLinkingURL);
}
/**
* Unsubscribe from notifications about activating URLs registered to be
* handled by this app.
*
* @inheritdoc
* @see https://facebook.github.io/react-native/docs/linking.html
* @returns {void}
*/
componentWillUnmount() {
Linking.removeEventListener('url', this._onLinkingURL);
super.componentWillUnmount();
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const store = this.props.store;
/* eslint-disable brace-style, react/jsx-no-bind */
return (
<Provider store = { store }>
<Navigator
initialRoute = { _getRouteToRender(store.getState) }
ref = { navigator => { this.navigator = navigator; } }
renderScene = { this._navigatorRenderScene } />
</Provider>
);
/* eslint-enable brace-style, react/jsx-no-bind */
}
/**
* Navigates to a specific Route (via platform-specific means).
*
* @param {Route} route - The Route to which to navigate.
* @returns {void}
*/
_navigate(route) {
const navigator = this.navigator;
// TODO Currently, the replace method doesn't support animation. Work
// towards adding it is done in
// https://github.com/facebook/react-native/issues/1981
// XXX React Native's Navigator adds properties to the route it's
// provided with. Clone the specified route in order to prevent its
// modification.
navigator && navigator.replace({ ...route });
}
/**
* Renders the scene identified by a specific route in the Navigator of this
* instance.
*
* @param {Object} route - The route which identifies the scene to be
* rendered in the associated Navigator. In the fashion of NavigatorIOS, the
* specified route is expected to define a value for its component property
* which is the type of React component to be rendered.
* @private
* @returns {ReactElement}
*/
_navigatorRenderScene(route) {
// We started with NavigatorIOS and then switched to Navigator in order
// to support Android as well. In order to reduce the number of
// modifications, accept the same format of route definition.
return this._createElement(route.component, {});
}
/**
* Notified by React's Linking API that a specific URL registered to be
* handled by this App was activated.
*
* @param {Object} event - The details of the notification/event.
* @param {string} event.url - The URL registered to be handled by this App
* which was activated.
* @private
* @returns {void}
*/
_onLinkingURL(event) {
this._openURL(event.url);
}
}
/**
* App component's property types.
*
* @static
*/
App.propTypes = AbstractApp.propTypes;
|
src/Survey/Complex/Default/Edit/Main/components/SpeciesList/components/SubSample/index.js
|
NERC-CEH/irecord-app
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import {
IonItemOption,
IonItemOptions,
IonItem,
IonItemSliding,
IonButton,
} from '@ionic/react';
import './styles.scss';
@observer
class index extends Component {
static propTypes = {
subSample: PropTypes.object.isRequired,
increaseCount: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
url: PropTypes.string.isRequired,
};
getLocationCommponent = () => {
const { subSample } = this.props;
const location = subSample.attrs.location || {};
const surveylocation = subSample.parent.attrs.location || {};
const isLocating = subSample.isGPSRunning();
const isCustomLocation = surveylocation.gridref !== location.gridref;
const locationString = isCustomLocation ? subSample.printLocation() : '';
let locationComponent;
if (locationString) {
locationComponent = <span>{locationString}</span>;
} else if (isLocating) {
locationComponent = <span className=" warn">Locating...</span>;
} else {
return null;
}
return <div className="location">{locationComponent}</div>;
};
getIncrementButton = occ => {
const { subSample, increaseCount } = this.props;
const survey = subSample.getSurvey();
const incrementShortcut =
survey.occ.attrs.number && survey.occ.attrs.number.incrementShortcut;
const { number } = occ.attrs;
if (!incrementShortcut || !number || Number.isNaN(number)) {
return (
<IonButton className="count-edit-count no-number" fill="clear">
N/A
</IonButton>
);
}
const onNumberIncrementClick = e => {
e.preventDefault();
e.stopPropagation();
increaseCount(occ);
};
return (
<IonButton
class={`count-edit-count ${!number ? 'no-number' : ''}`}
onClick={onNumberIncrementClick}
fill="clear"
>
{number}
</IonButton>
);
};
render() {
const { subSample, onDelete, url } = this.props;
const [occ] = subSample.occurrences;
const specie = occ.attrs.taxon || {};
const scientificName = specie.scientific_name;
let commonName =
specie.found_in_name >= 0 && specie.common_names[specie.found_in_name];
if (specie.found_in_name === 'common_name') {
// This is just to be backwards compatible
// TODO: remove in the next update
commonName = specie.common_name;
}
return (
<IonItemSliding key={occ.cid}>
<IonItem routerLink={`${url}/smp/${subSample.cid}`} detail={false}>
{this.getIncrementButton(occ)}
<div className="details">
{commonName && (
<>
<div className="species">{commonName}</div>
<div className="species scientific">{scientificName}</div>
</>
)}
{!commonName && (
<div className="species">
<i>
<b>{scientificName}</b>
</i>
</div>
)}
{this.getLocationCommponent()}
</div>
</IonItem>
<IonItemOptions side="end">
<IonItemOption color="danger" onClick={onDelete}>
{t('Delete')}
</IonItemOption>
</IonItemOptions>
</IonItemSliding>
);
}
}
export default index;
|
scripts/client/components/Main.js
|
antca/antca.github.io
|
import Header from './Header';
import Footer from './Footer';
import DrawerMenu from './DrawerMenu';
import {mainStore} from '../MainFlux';
import React from 'react';
import Reflux from 'reflux';
import {RouteHandler} from 'react-router';
var Main = React.createClass({
mixins: [Reflux.listenTo(mainStore, "onStoreEvent")],
getInitialState() {
return {
loc: mainStore.loc,
scroll: false,
lang: mainStore.language,
drawerOpen: false
}
},
onStoreEvent(type) {
if(type === 'LANGUAGE_CHANGED') {
this.setState({
loc: mainStore.loc,
lang: mainStore.language
});
}
if(type === 'DRAWER_TOGGLED') {
this.setState({
drawerOpen: mainStore.drawerOpen
});
}
},
componentDidMount() {
window.addEventListener('scroll', () => {
this.onScroll();
});
},
onScroll() {
if(window.scrollY > 250) {
this.setState({
scroll: true
});
} else {
this.setState({
scroll: false
});
}
},
render() {
return (
<div className="main_wrap" >
<Header sections={mainStore.sections} loc={this.state.loc} scroll={this.state.scroll} />
<div className="main_container" >
<RouteHandler loc={this.state.loc} lang={this.state.lang} />
</div>
<Footer loc={this.state.loc} />
<DrawerMenu isOpen={this.state.drawerOpen} sections={mainStore.sections} loc={this.state.loc}/>
</div>
)
}
});
export default Main;
|
src/components/TextInput.js
|
mitchgavan/got-your-money
|
import React, { Component } from 'react';
import styled from 'styled-components';
import { space, width, fontSize, color } from 'styled-system';
import theme from '../theme';
import Block from './Block';
const Label = styled.label`
display: block;
position: relative;
margin: 0;
font-size: 0.875rem;
font-weight: normal;
line-height: 1.8;
color: #0a0a0a;
`;
const InputField = styled.input`
display: block;
box-sizing: border-box;
width: 100%;
height: 2.5rem;
margin: 0 0 1rem;
padding: 0.5rem;
border: 0;
background-color: ${theme.colors.white};
font-family: inherit;
font-size: 1rem;
font-weight: normal;
line-height: 1.5;
color: ${theme.colors.black};
transition: box-shadow 0.5s ease-in-out;
appearance: none;
${space}
${width}
${fontSize}
${color}
`;
const LabelText = styled.span`
position: absolute;
display: block;
left: 10px;
font-size: ${props => (props.isActive ? '11px' : '14px')};
top: ${props => (props.isActive ? '-20px' : '8px')};
`;
export default class TextInput extends Component {
static defaultProps = {
type: 'text',
value: '',
};
state = {
isActive: false,
};
componentDidMount() {
this.setState({
isActive: Boolean(this.props.value),
});
}
handleBlur = event => {
if (!event.target.value) {
this.setState({ isActive: false });
}
};
handleFocus = event => {
this.setState({ isActive: true });
};
render() {
return (
<Block pt={2} pb={1}>
<Label>
<LabelText isActive={this.state.isActive}>
{this.props.displayName}
</LabelText>
<InputField
name={this.props.name}
type={this.props.type}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
value={this.props.value}
onChange={this.props.onChange}
/>
</Label>
</Block>
);
}
}
|
internals/templates/notFoundPage/notFoundPage.js
|
huahuaxiong/console
|
/**
* NotFoundPage
*
* This is the page we show when the user visits a url that doesn't have a 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 necessity 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 NotFound extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<h1>
<FormattedMessage {...messages.header} />
</h1>
);
}
}
|
app/jsx/external_apps/components/TextInput.js
|
djbender/canvas-lms
|
/*
* Copyright (C) 2014 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import createReactClass from 'create-react-class'
import PropTypes from 'prop-types'
import InputMixin from '../mixins/InputMixin'
export default createReactClass({
displayName: 'TextInput',
mixins: [InputMixin],
propTypes: {
defaultValue: PropTypes.string,
label: PropTypes.string,
id: PropTypes.string,
required: PropTypes.bool,
hintText: PropTypes.string,
placeholder: PropTypes.string,
errors: PropTypes.object,
name: PropTypes.string
},
render() {
return (
<div className={this.getClassNames()}>
<label>
{this.props.label}
<input
ref="input"
type="text"
defaultValue={this.state.value}
className="form-control input-block-level"
placeholder={this.props.placeholder || this.props.label}
required={this.props.required ? 'required' : null}
onChange={this.handleChange}
aria-invalid={!!this.getErrorMessage()}
name={this.props.name || null}
/>
{this.renderHint()}
</label>
</div>
)
}
})
|
examples/js/pagination/demo.js
|
echaouchna/react-bootstrap-tab
|
/* eslint max-len: 0 */
import React from 'react';
import DefaultPaginationTable from './default-pagination-table';
import CustomPaginationTable from './custom-pagination-table';
import PaginationHookTable from './pagination-hook-table';
class Demo extends React.Component {
render() {
return (
<div>
<div className='col-md-offset-1 col-md-8'>
<div className='panel panel-default'>
<div className='panel-heading'>Basic Pagination Example</div>
<div className='panel-body'>
<h5>Source in /examples/js/pagination/default-pagination-table.js</h5>
<DefaultPaginationTable />
</div>
</div>
</div>
<div className='col-md-offset-1 col-md-8'>
<div className='panel panel-default'>
<div className='panel-heading'>Custom Pagination Example</div>
<div className='panel-body'>
<h5>Source in /examples/js/pagination/custom-pagination-table.js</h5>
<CustomPaginationTable />
</div>
</div>
</div>
<div className='col-md-offset-1 col-md-8'>
<div className='panel panel-default'>
<div className='panel-heading'>Pagination Hooks(onPageChange) Example</div>
<div className='panel-body'>
<h5>Source in /examples/js/pagination/pagination-hook-table.js</h5>
<PaginationHookTable />
</div>
</div>
</div>
</div>
);
}
}
export default Demo;
|
app/app.js
|
filso/react-components-graph
|
/**
* 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 { ConnectedRouter } from 'react-router-redux';
import createHistory from 'history/createBrowserHistory';
// Import root app
import App from 'containers/App';
// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-unresolved, import/extensions */
import '!file-loader?name=[name].[ext]!./assets/images/favicon.ico';
import '!file-loader?name=[name].[ext]!./assets/images/icon-72x72.png';
import '!file-loader?name=[name].[ext]!./assets/images/icon-96x96.png';
import '!file-loader?name=[name].[ext]!./assets/images/icon-128x128.png';
import '!file-loader?name=[name].[ext]!./assets/images/icon-144x144.png';
import '!file-loader?name=[name].[ext]!./assets/images/icon-152x152.png';
import '!file-loader?name=[name].[ext]!./assets/images/icon-192x192.png';
import '!file-loader?name=[name].[ext]!./assets/images/icon-384x384.png';
import '!file-loader?name=[name].[ext]!./assets/images/icon-512x512.png';
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 './configureStore';
import './assets/styles/app.scss';
// Import CSS reset and Global Styles
import './global-styles';
// Import static files
// import '!file-loader?name=[name].[ext]&outputPath=assets/!./assets/vendor/jquery-2.1.1.min.js';
import '!file-loader?name=[name].[ext]&outputPath=assets/!./assets/vendor/d3.min.js';
import '!file-loader?name=[name].[ext]&outputPath=assets/!./assets/vendor/jquery-2.1.1.min.js';
import '!file-loader?name=[name].[ext]&outputPath=assets/!./assets/vendor/typeahead.jquery.js';
// Create redux store with history
const initialState = {};
const history = createHistory();
const store = configureStore(initialState, history);
const MOUNT_NODE = document.getElementById('app');
const render = () => {
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</Provider>,
MOUNT_NODE
);
};
render();
if (module.hot) {
// Hot reloadable React components and translation json files
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept(['containers/App'], () => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE);
render();
});
}
// 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
}
|
client/app/components/ImpresionesContador/ImpresionesContador.js
|
krouw/T.SIA-electron-blueprint
|
// @flow
import React, { Component } from 'react';
import { Row, Col } from 'react-flexbox-grid';
class ImpresionesContador extends Component {
constructor(props){
super(props);
this.state = {
first: 0,
}
}
onChange(e){
this.setState({[e.target.name]: e.target.value});
}
addFristContador(e){
e.preventDefault();;
const contador = {
contadorInicial: this.state.first,
contadorFinal: this.state.first,
isActive: true,
}
this.props.addContador(contador);
}
addContador(e){
e.preventDefault();
const contador = {
contadorInicial: parseInt(this.props.contador.contadorFinal),
contadorFinal: parseInt(this.props.contador.contadorFinal),
isActive: true,
}
this.props.addContador(contador);
}
expiredContador(e){
e.preventDefault();
const contador = {
contadorFinal: this.props.contador.contadorFinal,
id: this.props.contador.id,
isActive: false,
}
this.props.updateContador(contador);
}
render(){
let content = ''
if(!this.props.contador.isContador){
content = (
<div>
<h4 style={{fontSize:25}}>BIENVENIDO A SIU</h4>
<h2 style={{fontSize:15}}>No existen registros, ingrese el primero</h2>
<input
style={{textAlign:"center"}}
onChange={ (e) => this.onChange(e) }
name="first"
className="pt-input"
type="number"
dir="auto"
min="0"
placeholder="Primer Contador"
required="true"
/>
<button
type="button"
onClick={ (e) => this.addFristContador(e) }
className="pt-button pt-large pt-intent-success">
Primera Jornada!
</button>
</div>
)
}
else{
if(this.props.contador.isActive){
content = (
<div>
<h4>JORNADA INICIADA</h4>
<h2 className="is-active">
{this.props.contador.contadorInicial}
<span>
/{this.props.contador.contadorFinal}
</span>
</h2>
<p className="is-active">cont. Actual</p>
<button
type="button"
onClick={ (e) => this.expiredContador(e) }
className="pt-button pt-large pt-intent-danger">
Cerrar Jornada
</button>
</div>
)
}
else {
content = (
<div>
<h4>ÚLTIMA JORNADA</h4>
<h2>{this.props.contador.contadorFinal}</h2>
<p>{this.props.contador.fecha}</p>
<button
type="button"
onClick={ e => this.addContador(e) }
className="pt-button pt-large pt-intent-success">
Iniciar Jornada
</button>
</div>
)
}
}
return (
<Row style={{marginTop: "10px"}} center="xs">
<Col xs={12}>
{ content }
</Col>
</Row>
)}
}
ImpresionesContador.propTypes = {
contador: React.PropTypes.object.isRequired,
addContador: React.PropTypes.func.isRequired,
updateContador: React.PropTypes.func.isRequired,
}
export default ImpresionesContador;
|
src/routes/error/index.js
|
egut/react-docker-demo
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import ErrorPage from './ErrorPage';
export default {
path: '/error',
action({ error }) {
return {
title: error.name,
description: error.message,
component: <ErrorPage error={error} />,
status: error.status || 500,
};
},
};
|
examples/react-router/app/views/lists/parts/item-form.js
|
leobauza/microcosm
|
import React from 'react'
import ActionForm from 'microcosm/addons/action-form'
import { addItem } from '../../../actions/items'
class ItemForm extends React.PureComponent {
state = {
name: ''
}
reset = () => {
this.setState({ name: '' })
}
setName = e => {
this.setState({ name: e.target.value })
}
render() {
const { name } = this.state
return (
<ActionForm action={addItem} onSubmit={this.reset}>
<input type="hidden" name="list" value={this.props.list} />
<div className="textfield">
<label htmlFor="item-name">Name</label>
<input
id="item-name"
name="name"
value={name}
onChange={this.setName}
required
/>
</div>
<button className="btn">Add Item</button>
</ActionForm>
)
}
}
export default ItemForm
|
src/js/components/Bloglist.js
|
Zmingg/qcblog-react
|
import React, { Component } from 'react';
import style from '../../scss/blog.scss';
import { Link } from 'react-router-dom';
const defaultImg = require('../../img/thumb_default.jpg');
export default class Bloglist extends Component {
constructor(props){
super(props);
this.state = {
blogs:[],
colWidth:'',
};
this.col = this.defaultCol = 3;
this.gapX = 20;
this.gapY = 30;
this.page = 1;
this.heights = []
}
componentDidMount(){
this.init();
this.listener();
this.pushBlog();
}
shouldComponentUpdate(nextProps, nextState) {
if (nextState.blogs!==this.state.blogs) {
return true;
}else if(this.state.blogs.length&&nextState.colWidth!==this.state.colWidth){
return true;
}else{
return false;
}
}
componentDidUpdate(prevProps, prevState) {
let lis = this._list.getElementsByTagName('li');
let lastli = lis[lis.length-1];
let img = lastli.getElementsByTagName('img')[0];
img.onload=()=>{
img.onload = null;
this.water(lastli);
}
}
componentWillUnmount(){
clearTimeout(this.timmerOneByOne);
this.loading.removeEventListener('transitionend',this.transitionEnd);
this.loading.removeEventListener('webkitTransitionEnd',this.transitionEnd);
window.removeEventListener('scroll',this.scrollEve);
window.removeEventListener('resize',this.resizeEve);
}
render(){
const styles = {
li: {
width:this.state.colWidth,
opacity:0,
}
}
return (
<div>
<ul ref={el=>this._list=el} className={style.list}>
{this.state.blogs.map( blog=>
<li key={blog.id} className={style.li} style={styles.li} onClick={()=>this.showBlog(blog.id)}>
<div className={style.pic}>
<img src={'http://zmhjy.xyz/'+blog.thumb_img} />
</div>
<div className={style.content}>
<p className={style.title}>{blog.title}</p>
<p>{blog.abstract}</p>
<div className={style.meta}>
{blog.tagsarr.map( tag=>
<span key={tag} className={style.tag}>{tag}</span>
)}
<span className={style.click}>{blog.click}</span>
</div>
</div>
<div className={style.shade}><span>QC.TEC</span></div>
</li>
)}
</ul>
<div className={style.loading} style={styles.loading} ref={(el)=>{this.loading=el}}>
<i></i><i></i><i></i><i></i><i></i><i></i>
</div>
</div>
)
}
showBlog(id){
this.props.onShow('/app2/show/'+id);
}
pushBlog(){
this.loading.style.display = '';
this.loading.style.opacity = 1;
this.isLoading = true;
this.props.onFetch(this.page,()=>{
this.page++;
this.imgLoaded(this.props.blogs,()=>{
this.page==2&&(window.loading += 30);
this.loading.style.opacity = 0;
this.renderOneByOne(this.props.blogs);
this.isLoading = false;
})
})
}
init(){
if (this._list.clientWidth<640){
this.col = 2;
}else if(this._list.clientWidth<768){
this.col = 2;
}else{
this.col = this.defaultCol;
}
this.setState({colWidth:Math.floor((this._list.clientWidth-(this.col-1)*this.gapX)/this.col)});
this.heights = Array(this.col);
for (let i = 0; i < this.heights.length; i++) {
this.heights[i] = 0;
}
}
listener(){
this.scrollEve = ()=>{
var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
if(scrollTop >= document.body.clientHeight-window.screen.height-200){
if (!this.props.isFetching&&!this.isLoading&&this.props.hasMore) {
if(new Date().getTime()-this.props.lastUpdated>500)
this.pushBlog();
}
}
}
window.addEventListener('scroll',this.scrollEve);
this.resizeEve = ()=>{
if(!this.timerid){
this.timerid = setTimeout(()=>{
this.init();
let lis = this._list.getElementsByTagName('li');
for (let i = 0; i < lis.length; i++) {
this.water(lis[i]);
}
clearTimeout(this.timerid);
this.timerid = null;
},500);
}
}
window.addEventListener('resize',this.resizeEve);
this.transitionEnd = (e)=>{
if(e.propertyName=='opacity'&&this.loading.style.opacity==0){
this.loading.style.display = 'none';
}
}
this.loading.addEventListener('transitionend',this.transitionEnd);
this.loading.addEventListener('webkitTransitionEnd',this.transitionEnd);
}
imgLoaded(datas,cb){
let num = 0;
let length = datas.length;
for (let i in datas) {
let img = new Image();
img.onerror = function(){
datas[i].thumb_img = 'ass_ama/img/thumb_default.jpg';
img.onerror = null;
num++;
num>=length&&cb();
}
img.onload = function(){
img.onload = null;
num++;
num>=length&&cb();
}
img.src = 'http:\/\/zmhjy\.xyz\/'+datas[i].thumb_img;
}
}
water(el){
let minCol = this.findMinHeight()[0];
let minHeight = this.findMinHeight()[1];
el.style.top = minHeight+'px';
el.style.left = (this.state.colWidth+this.gapX)*minCol+'px';
let timerOp = setTimeout(()=>{
el.style.opacity = 1;
clearTimeout(timerOp);
},100)
this.heights[minCol] += (el.clientHeight + this.gapY);
let maxHeight = Math.max.apply(null,this.heights);
this._list.style.height = maxHeight+'px';
}
findMinHeight(){
let minHeight = Math.min.apply(null,this.heights);
for(let i in this.heights){
if (this.heights[i] == minHeight){
return [i,minHeight];
}
}
}
renderOneByOne(data){
let i = 0;
this.timmerOneByOne=setInterval(()=>{
if (i<data.length){
this.setState(
(prevState)=>({blogs:prevState.blogs.concat([data[i]])})
);
i++;
} else {
clearInterval(this.timmerOneByOne);
}
},100);
}
}
|
docs-ui/components/pagination.stories.js
|
beeftornado/sentry
|
import React from 'react';
import PropTypes from 'prop-types';
import {withInfo} from '@storybook/addon-info';
import Pagination from 'app/components/pagination';
export default {
title: 'Core/Pagination',
};
const withBoth = `<https://sentry.io/api/0/organizations/sentry/issues/?cursor=1603798246000:0:1>; rel="previous"; results="true"; cursor="1603798246000:0:1",
<https://sentry.io/api/0/organizations/sentry/issues/?cursor=1603719405000:0:0>; rel="next"; results="true"; cursor="1603719405000:0:0"
`;
const withNext = `<https://sentry.io/api/0/organizations/sentry/issues/?cursor=1603798246000:0:1>; rel="previous"; results="false"; cursor="1603798246000:0:1",
<https://sentry.io/api/0/organizations/sentry/issues/?cursor=1603719405000:0:0>; rel="next"; results="true"; cursor="1603719405000:0:0"
`;
class Container extends React.Component {
static childContextTypes = {
location: PropTypes.object,
};
getChildContext() {
return {location: window.location};
}
render() {
return this.props.children;
}
}
export const Default = withInfo('Pagination')(() => {
return (
<Container>
<div className="section">
<h3>Both enabled</h3>
<Pagination pageLinks={withBoth} />
</div>
<div className="section">
<h3>Only next enabled</h3>
<Pagination pageLinks={withNext} />
</div>
</Container>
);
});
Default.story = {
name: 'default',
};
|
ui/effects/use-combined-refs.js
|
lbryio/lbry-app
|
import React from 'react';
export default function useCombinedRefs(...refs) {
const targetRef = React.useRef();
React.useEffect(() => {
refs.forEach(ref => {
if (!ref) return;
if (typeof ref === 'function') {
ref(targetRef.current);
} else {
ref.current = targetRef.current;
}
});
}, [refs]);
return targetRef;
}
/*
Problem described in
https://itnext.io/reusing-the-ref-from-forwardref-with-react-hooks-4ce9df693dd
*/
|
app/components/events/JoinEventButton.js
|
alexko13/block-and-frame
|
import React, { Component } from 'react';
// import eventHelpers from '../../utils/eventHelpers';
// This component needs id of event as a prop
class JoinEventButton extends Component {
constructor(props) {
super(props);
this.onJoinEventWithContributions = this.onJoinEventWithContributions.bind(this);
}
onJoinEventWithContributions(e) {
e.preventDefault();
// eventHelpers.joinEventWithContributions(this.props.eventId, this.props.contributions);
this.props.handleJoinEventWithContributions(this.props.eventId, this.props.contributions);
browserHistory.push(`/${this.props.eventId}`);
}
render() {
return (
<button
className="ui button"
onClick={this.onJoinEventWithContributions}
>
Join Spread!
</button>
);
}
}
export default JoinEventButton;
|
packages/wix-style-react/src/VerticalTabsItem/test/VerticalTabsItem.visual.js
|
wix/wix-style-react
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import Add from 'wix-ui-icons-common/Add';
import VerticalTabsItem from '../VerticalTabsItem';
const tests = [
{
describe: 'type',
its: [
{
it: 'tab',
props: {
type: 'tab',
},
},
{
it: 'action',
props: {
type: 'action',
},
},
{
it: 'title',
props: {
type: 'title',
},
},
],
},
{
describe: 'disabled',
its: [
{
it: 'true',
props: {
disabled: true,
},
},
{
it: 'false',
props: {
disabled: false,
},
},
],
},
{
describe: 'prefixIcon',
its: [
{
it: 'prefixIcon',
props: {
prefixIcon: <Add />,
},
},
],
},
{
describe: 'suffixIcon',
its: [
{
it: 'suffixIcon',
props: {
suffixIcon: <Add />,
},
},
],
},
];
export const runTests = (
{ themeName, testWithTheme } = { testWithTheme: i => i },
) => {
tests.forEach(({ describe, its }) => {
its.forEach(({ it, props }) => {
storiesOf(
`${themeName ? `${themeName}|` : ''}VerticalTabsItem${
describe ? '/' + describe : ''
}`,
module,
).add(it, () =>
testWithTheme(<VerticalTabsItem {...props}>Tab Item</VerticalTabsItem>),
);
});
});
};
|
client/views/setupWizard/steps/SettingsBasedStep.stories.js
|
iiet/iiet-chat
|
import { boolean, select, text } from '@storybook/addon-knobs';
import React from 'react';
import SettingsBasedStep from './SettingsBasedStep';
export default {
title: 'views/setupWizard/steps/SettingsBasedStep',
component: SettingsBasedStep,
};
export const _default = () =>
<SettingsBasedStep
step={select('step', [1, 2, 3, 4, 'final'], 2)}
title={text('title', 'Settings-Based Step')}
active={boolean('active', true)}
/>;
|
docs/app/Examples/views/Statistic/Content/StatisticExampleValueShorthand.js
|
shengnian/shengnian-ui-react
|
import React from 'react'
import { Statistic } from 'shengnian-ui-react'
const StatisticExampleValueShorthand = () => (
<Statistic.Group>
<Statistic label='Saves' value='22' />
<Statistic label='Signups' value='Three Thousand' text />
<Statistic label='Flights' value='5' />
<Statistic label='Team Members' value='42' />
</Statistic.Group>
)
export default StatisticExampleValueShorthand
|
src/router.js
|
vincentdd/crm
|
import React from 'react'
import PropTypes from 'prop-types'
import {
Router
} from 'dva/router'
import App from 'routes/app'
const registerModel = (app, model) => {
if (!(app._models.filter(m => m.namespace === model.namespace).length === 1)) {
app.model(model)
}
}
const Routers = function({
history,
app
}) {
const routes = [{
path: '/',
component: App,
getIndexRoute(nextState, cb) {
require.ensure([], (require) => {
registerModel(app, require('models/crmaccmanag'))
cb(null, {
component: require('routes/crmaccmanag/')
})
}, 'crmaccmanag')
},
childRoutes: [{
path: 'dashboard',
getComponent(nextState, cb) {
require.ensure([], (require) => {
registerModel(app, require('models/dashboard'))
cb(null, require('routes/dashboard/'))
}, 'dashboard')
},
}, {
path: 'user',
getComponent(nextState, cb) {
require.ensure([], (require) => {
registerModel(app, require('models/user'))
cb(null, require('routes/user/'))
}, 'user')
},
}, {
path: 'user/:id',
getComponent(nextState, cb) {
require.ensure([], (require) => {
registerModel(app, require('models/user/detail'))
cb(null, require('routes/user/detail/'))
}, 'user-detail')
},
}, {
path: 'login',
getComponent(nextState, cb) {
require.ensure([], (require) => {
registerModel(app, require('models/login'))
cb(null, require('routes/login/'))
}, 'login')
},
}, {
path: 'request',
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('routes/request/'))
}, 'request')
},
}, {
path: 'UIElement/iconfont',
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('routes/UIElement/iconfont/'))
}, 'UIElement-iconfont')
},
}, {
path: 'UIElement/search',
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('routes/UIElement/search/'))
}, 'UIElement-search')
},
}, {
path: 'UIElement/dropOption',
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('routes/UIElement/dropOption/'))
}, 'UIElement-dropOption')
},
}, {
path: 'UIElement/layer',
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('routes/UIElement/layer/'))
}, 'UIElement-layer')
},
}, {
path: 'UIElement/dataTable',
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('routes/UIElement/dataTable/'))
}, 'UIElement-dataTable')
},
}, {
path: 'UIElement/editor',
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('routes/UIElement/editor/'))
}, 'UIElement-editor')
},
}, {
path: 'chart/lineChart',
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('routes/chart/lineChart/'))
}, 'chart-lineChart')
},
}, {
path: 'chart/barChart',
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('routes/chart/barChart/'))
}, 'chart-barChart')
},
}, {
path: 'chart/areaChart',
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('routes/chart/areaChart/'))
}, 'chart-areaChart')
},
},
// {
// path: 'post',
// getComponent(nextState, cb) {
// require.ensure([], (require) => {
// registerModel(app, require('models/post'))
// cb(null, require('routes/post/'))
// }, 'post')
// },
// },
{
path: 'industry',
getComponent(nextState, cb) {
require.ensure([], (require) => {
registerModel(app, require('models/industry'))
cb(null, require('routes/industry/'))
}, 'industry')
},
}, {
path: 'crmaccmanag',
getComponent(nextState, cb) {
require.ensure([], (require) => {
registerModel(app, require('models/crmaccmanag'))
cb(null, require('routes/crmaccmanag/'))
}, 'crmaccmanag')
},
}, {
path: 'account',
getComponent(nextState, cb) {
require.ensure([], (require) => {
registerModel(app, require('models/account'))
cb(null, require('routes/account/'))
}, 'account')
},
}, {
path: 'clue',
getComponent(nextState, cb) {
require.ensure([], (require) => {
registerModel(app, require('models/clue'))
cb(null, require('routes/clue/'))
}, 'clue')
},
},
{
path: 'crmaccount',
getComponent(nextState, cb) {
require.ensure([], (require) => {
registerModel(app, require('models/crmaccount'))
cb(null, require('routes/crmaccount/'))
}, 'crmaccount')
},
},{
path: '*',
getComponent(nextState, cb) {
require.ensure([], (require) => {
cb(null, require('routes/error/'))
}, 'error')
},
},
],
}, ]
return <Router history={history} routes={routes} />
}
Routers.propTypes = {
history: PropTypes.object,
app: PropTypes.object,
}
export default Routers
|
src/plot/series/polygon-series.js
|
Apercu/react-vis
|
// Copyright (c) 2016 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import Animation from 'animation';
import {ANIMATED_SERIES_PROPS} from 'utils/series-utils';
import AbstractSeries from './abstract-series';
const predefinedClassName = 'rv-xy-plot__series rv-xy-plot__series--polygon';
const DEFAULT_COLOR = '#12939A';
const generatePath = (data, xFunctor, yFunctor) =>
`${data.reduce((res, row, i) => `${res} ${i ? 'L' : 'M'}${xFunctor(row)} ${yFunctor(row)}`, '')} Z`;
class PolygonSeries extends AbstractSeries {
static get propTypes() {
return {
... AbstractSeries.propTypes
};
}
render() {
const {
animation,
color,
className,
data,
marginLeft,
marginTop,
style
} = this.props;
if (!data) {
return null;
}
if (animation) {
return (
<Animation {...this.props} animatedProps={ANIMATED_SERIES_PROPS}>
<PolygonSeries {...this.props} animation={null}/>
</Animation>
);
}
const xFunctor = this._getAttributeFunctor('x');
const yFunctor = this._getAttributeFunctor('y');
return (
<path {...{
className: `${predefinedClassName} ${className}`,
onMouseOver: this._seriesMouseOverHandler,
onMouseOut: this._seriesMouseOutHandler,
onClick: this._seriesClickHandler,
onContextMenu: this._seriesRightClickHandler,
fill: color || DEFAULT_COLOR,
style,
d: generatePath(data, xFunctor, yFunctor),
transform: `translate(${marginLeft},${marginTop})`,
ref: 'container'
}}/>
);
}
}
PolygonSeries.displayName = 'PolygonSeries';
export default PolygonSeries;
|
src/components/NotFoundPage.js
|
rak2112/movie-base
|
import React from 'react';
import { Link } from 'react-router';
const NotFoundPage = () => {
return (
<div>
<h4>
404 Page Not Found
</h4>
<Link to="/"> Go back to homepage </Link>
</div>
);
};
export default NotFoundPage;
|
src/utils/withWidth.spec.js
|
ichiohta/material-ui
|
/* eslint-env mocha */
import React from 'react';
import {shallow, mount} from 'enzyme';
import {assert} from 'chai';
import withWidth, {MEDIUM, LARGE} from './withWidth';
describe('utils/withWidth', () => {
const Dumb = () => <div />;
const DumbWithWidth = withWidth()(Dumb);
describe('server side rendering', () => {
it('should not render the children as the width is unknown', () => {
const wrapper = shallow(<DumbWithWidth />);
assert.strictEqual(wrapper.type(), null, 'should render nothing');
});
});
describe('prop: width', () => {
it('should be able to override it', () => {
const wrapper = mount(<DumbWithWidth width={MEDIUM} />);
assert.strictEqual(wrapper.find(Dumb).props().width, MEDIUM);
});
});
describe('browser', () => {
it('should provide the right width to the child element', () => {
const wrapper = mount(<DumbWithWidth />);
assert.strictEqual(wrapper.find(Dumb).props().width, LARGE);
});
});
});
|
docs/app/Examples/elements/Header/index.js
|
Rohanhacker/Semantic-UI-React
|
import React from 'react'
import Types from './Types'
import Content from './Content'
import States from './States'
import Variations from './Variations'
const HeaderExamples = () => (
<div>
<Types />
<Content />
<States />
<Variations />
</div>
)
export default HeaderExamples
|
node_modules/rc-calendar/es/decade/DecadePanel.js
|
prodigalyijun/demo-by-antd
|
import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import PropTypes from 'prop-types';
var ROW = 4;
var COL = 3;
import classnames from 'classnames';
function goYear(direction) {
var next = this.state.value.clone();
next.add(direction, 'years');
this.setState({
value: next
});
}
function chooseDecade(year, event) {
var next = this.state.value.clone();
next.year(year);
next.month(this.state.value.month());
this.props.onSelect(next);
event.preventDefault();
}
var DecadePanel = function (_React$Component) {
_inherits(DecadePanel, _React$Component);
function DecadePanel(props) {
_classCallCheck(this, DecadePanel);
var _this = _possibleConstructorReturn(this, (DecadePanel.__proto__ || Object.getPrototypeOf(DecadePanel)).call(this, props));
_this.state = {
value: props.value || props.defaultValue
};
// bind methods
_this.prefixCls = props.rootPrefixCls + '-decade-panel';
_this.nextCentury = goYear.bind(_this, 100);
_this.previousCentury = goYear.bind(_this, -100);
return _this;
}
_createClass(DecadePanel, [{
key: 'render',
value: function render() {
var _this2 = this;
var value = this.state.value;
var locale = this.props.locale;
var currentYear = value.year();
var startYear = parseInt(currentYear / 100, 10) * 100;
var preYear = startYear - 10;
var endYear = startYear + 99;
var decades = [];
var index = 0;
var prefixCls = this.prefixCls;
for (var rowIndex = 0; rowIndex < ROW; rowIndex++) {
decades[rowIndex] = [];
for (var colIndex = 0; colIndex < COL; colIndex++) {
var startDecade = preYear + index * 10;
var endDecade = preYear + index * 10 + 9;
decades[rowIndex][colIndex] = {
startDecade: startDecade,
endDecade: endDecade
};
index++;
}
}
var decadesEls = decades.map(function (row, decadeIndex) {
var tds = row.map(function (decadeData) {
var _classNameMap;
var dStartDecade = decadeData.startDecade;
var dEndDecade = decadeData.endDecade;
var isLast = dStartDecade < startYear;
var isNext = dEndDecade > endYear;
var classNameMap = (_classNameMap = {}, _defineProperty(_classNameMap, prefixCls + '-cell', 1), _defineProperty(_classNameMap, prefixCls + '-selected-cell', dStartDecade <= currentYear && currentYear <= dEndDecade), _defineProperty(_classNameMap, prefixCls + '-last-century-cell', isLast), _defineProperty(_classNameMap, prefixCls + '-next-century-cell', isNext), _classNameMap);
var content = dStartDecade + '-' + dEndDecade;
var clickHandler = void 0;
if (isLast) {
clickHandler = _this2.previousCentury;
} else if (isNext) {
clickHandler = _this2.nextCentury;
} else {
clickHandler = chooseDecade.bind(_this2, dStartDecade);
}
return React.createElement(
'td',
{
key: dStartDecade,
onClick: clickHandler,
role: 'gridcell',
className: classnames(classNameMap)
},
React.createElement(
'a',
{
className: prefixCls + '-decade'
},
content
)
);
});
return React.createElement(
'tr',
{ key: decadeIndex, role: 'row' },
tds
);
});
return React.createElement(
'div',
{ className: this.prefixCls },
React.createElement(
'div',
{ className: prefixCls + '-header' },
React.createElement('a', {
className: prefixCls + '-prev-century-btn',
role: 'button',
onClick: this.previousCentury,
title: locale.previousCentury
}),
React.createElement(
'div',
{ className: prefixCls + '-century' },
startYear,
'-',
endYear
),
React.createElement('a', {
className: prefixCls + '-next-century-btn',
role: 'button',
onClick: this.nextCentury,
title: locale.nextCentury
})
),
React.createElement(
'div',
{ className: prefixCls + '-body' },
React.createElement(
'table',
{ className: prefixCls + '-table', cellSpacing: '0', role: 'grid' },
React.createElement(
'tbody',
{ className: prefixCls + '-tbody' },
decadesEls
)
)
)
);
}
}]);
return DecadePanel;
}(React.Component);
export default DecadePanel;
DecadePanel.propTypes = {
locale: PropTypes.object,
value: PropTypes.object,
defaultValue: PropTypes.object,
rootPrefixCls: PropTypes.string
};
DecadePanel.defaultProps = {
onSelect: function onSelect() {}
};
|
src/TableBody.js
|
prince1809/react-grid
|
import React from 'react';
class TableBody extends React.Component{
constructor(props){
super(props);
}
}
export default TableBody;
|
docs/app/Examples/elements/Label/Types/LabelExamplePointingColored.js
|
koenvg/Semantic-UI-React
|
import React from 'react'
import { Divider, Form, Label } from 'semantic-ui-react'
const LabelExamplePointing = () => (
<Form>
<Form.Field>
<input type='text' placeholder='First name' />
<Label basic color='red' pointing>Please enter a value</Label>
</Form.Field>
<Divider />
<Form.Field>
<Label basic color='red' pointing='below'>Please enter a value</Label>
<input type='text' placeholder='Last Name' />
</Form.Field>
<Divider />
<Form.Field inline>
<input type='text' placeholder='Username' />
<Label basic color='red' pointing='left'>That name is taken!</Label>
</Form.Field>
<Divider />
<Form.Field inline>
<Label basic color='red' pointing='right'>Your password must be 6 characters or more</Label>
<input type='password' placeholder='Password' />
</Form.Field>
</Form>
)
export default LabelExamplePointing
|
src/loader/Loader.js
|
ipfs/webui
|
import React from 'react'
import './Loader.css'
export const Loader = ({ color = 'light', ...props }) => {
const className = `dib la-ball-triangle-path la-${color} la-sm`
return (
<div {...props}>
<div
className={className}
style={{ width: 20, height: 20 }}>
<div />
<div />
<div />
</div>
</div>
)
}
|
stories/Slider.js
|
ecmadao/light-ui
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import SliderWrapper from '../examples/SliderWrapper';
storiesOf('Slider', module)
.add('basical', () => (
<SliderWrapper />
));
|
packages/core/src/icons/components/RadioSelected.js
|
iCHEF/gypcrete
|
import React from 'react';
export default function SvgRadioSelected(props) {
return (
<svg
width="1em"
height="1em"
viewBox="0 0 32 32"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<rect
x={7}
y={7}
width={18}
height={18}
rx={9}
stroke="currentColor"
strokeWidth={2}
fill="none"
/>
<rect
x={11.5}
y={11.5}
width={9}
height={9}
rx={4.5}
stroke="currentColor"
/>
</svg>
);
}
|
app/utils/injectSaga.js
|
pauleonardo/demo-trans
|
import React from 'react';
import PropTypes from 'prop-types';
import hoistNonReactStatics from 'hoist-non-react-statics';
import getInjectors from './sagaInjectors';
/**
* Dynamically injects a saga, passes component's props as saga arguments
*
* @param {string} key A key of the saga
* @param {function} saga A root saga that will be injected
* @param {string} [mode] By default (constants.RESTART_ON_REMOUNT) the saga will be started on component mount and
* cancelled with `task.cancel()` on component un-mount for improved performance. Another two options:
* - constants.DAEMON—starts the saga on component mount and never cancels it or starts again,
* - constants.ONCE_TILL_UNMOUNT—behaves like 'RESTART_ON_REMOUNT' but never runs it again.
*
*/
export default ({ key, saga, mode }) => (WrappedComponent) => {
class InjectSaga extends React.Component {
static WrappedComponent = WrappedComponent;
static contextTypes = {
store: PropTypes.object.isRequired,
};
static displayName = `withSaga(${(WrappedComponent.displayName || WrappedComponent.name || 'Component')})`;
componentWillMount() {
const { injectSaga } = this.injectors;
injectSaga(key, { saga, mode }, this.props);
}
componentWillUnmount() {
const { ejectSaga } = this.injectors;
ejectSaga(key);
}
injectors = getInjectors(this.context.store);
render() {
return <WrappedComponent {...this.props} />;
}
}
return hoistNonReactStatics(InjectSaga, WrappedComponent);
};
|
app/javascript/mastodon/features/home_timeline/components/column_settings.js
|
TootCat/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ColumnCollapsable from '../../../components/column_collapsable';
import SettingToggle from '../../notifications/components/setting_toggle';
import SettingText from './setting_text';
const messages = defineMessages({
filter_regex: { id: 'home.column_settings.filter_regex', defaultMessage: 'Filter out by regular expressions' },
settings: { id: 'home.settings', defaultMessage: 'Column settings' },
});
class ColumnSettings extends React.PureComponent {
static propTypes = {
settings: ImmutablePropTypes.map.isRequired,
onChange: PropTypes.func.isRequired,
onSave: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
render () {
const { settings, onChange, onSave, intl } = this.props;
return (
<ColumnCollapsable icon='sliders' title={intl.formatMessage(messages.settings)} fullHeight={209} onCollapse={onSave}>
<div className='column-settings__outer'>
<span className='column-settings__section'><FormattedMessage id='home.column_settings.basic' defaultMessage='Basic' /></span>
<div className='column-settings__row'>
<SettingToggle settings={settings} settingKey={['shows', 'reblog']} onChange={onChange} label={<FormattedMessage id='home.column_settings.show_reblogs' defaultMessage='Show boosts' />} />
</div>
<div className='column-settings__row'>
<SettingToggle settings={settings} settingKey={['shows', 'reply']} onChange={onChange} label={<FormattedMessage id='home.column_settings.show_replies' defaultMessage='Show replies' />} />
</div>
<span className='column-settings__section'><FormattedMessage id='home.column_settings.advanced' defaultMessage='Advanced' /></span>
<div className='column-settings__row'>
<SettingText settings={settings} settingKey={['regex', 'body']} onChange={onChange} label={intl.formatMessage(messages.filter_regex)} />
</div>
</div>
</ColumnCollapsable>
);
}
}
export default injectIntl(ColumnSettings);
|
src/components/RowContainer.js
|
ttrentham/Griddle
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from '../utils/griddleConnect';
import compose from 'recompose/compose';
import mapProps from 'recompose/mapProps';
import getContext from 'recompose/getContext';
import {
columnIdsSelector,
rowDataSelector,
rowPropertiesSelector,
classNamesForComponentSelector,
stylesForComponentSelector,
} from '../selectors/dataSelectors';
import { valueOrResult } from '../utils/valueUtils';
const ComposedRowContainer = OriginalComponent => compose(
getContext({
components: PropTypes.object,
}),
connect((state, props) => ({
columnIds: columnIdsSelector(state),
rowProperties: rowPropertiesSelector(state),
rowData: rowDataSelector(state, props),
className: classNamesForComponentSelector(state, 'Row'),
style: stylesForComponentSelector(state, 'Row'),
})),
mapProps(props => {
const { components, rowProperties, className, ...otherProps } = props;
return {
Cell: components.Cell,
className: valueOrResult(rowProperties.cssClassName, props) || props.className,
...otherProps,
};
}),
)(props => (
<OriginalComponent
{...props}
/>
));
export default ComposedRowContainer;
|
src/components/common/TextEditor/Nodes/ParagraphNode.js
|
anztrax/simple-image-server-frontend
|
import React from 'react';
export default class ParagraphNode extends React.Component{
constructor(props){
super(props);
}
render(){
return (
<p>{this.props.children}</p>
)
}
}
|
src/svg-icons/editor/format-color-fill.js
|
lawrence-yu/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatColorFill = (props) => (
<SvgIcon {...props}>
<path d="M16.56 8.94L7.62 0 6.21 1.41l2.38 2.38-5.15 5.15c-.59.59-.59 1.54 0 2.12l5.5 5.5c.29.29.68.44 1.06.44s.77-.15 1.06-.44l5.5-5.5c.59-.58.59-1.53 0-2.12zM5.21 10L10 5.21 14.79 10H5.21zM19 11.5s-2 2.17-2 3.5c0 1.1.9 2 2 2s2-.9 2-2c0-1.33-2-3.5-2-3.5z"/><path fillOpacity=".36" d="M0 20h24v4H0z"/>
</SvgIcon>
);
EditorFormatColorFill = pure(EditorFormatColorFill);
EditorFormatColorFill.displayName = 'EditorFormatColorFill';
EditorFormatColorFill.muiName = 'SvgIcon';
export default EditorFormatColorFill;
|
src/Eventplanner/Calendar.js
|
ctco/rosemary-ui
|
import React from 'react';
import PropTypes from 'prop-types';
import uncontrollable from 'uncontrollable';
import cn from 'classnames';
import { accessor, elementType, dateFormat, views as componentViews } from './utils/propTypes';
import localizer from './localizer';
import { notify } from './utils/helpers';
import { navigate, views } from './utils/constants';
import dates from './utils/dates';
import defaultFormats from './formats';
import viewLabel from './utils/viewLabel';
import moveDate from './utils/move';
import VIEWS from './Views';
import Toolbar from './Toolbar';
import omit from 'lodash/omit';
import defaults from 'lodash/defaults';
import transform from 'lodash/transform';
import mapValues from 'lodash/mapValues';
function viewNames(_views) {
return !Array.isArray(_views) ? Object.keys(_views) : _views;
}
function isValidView(view, { views: _views }) {
let names = viewNames(_views);
return names.indexOf(view) !== -1;
}
let now = new Date();
/**
* react-big-calendar is full featured Calendar component for managing events and dates. It uses
* modern `flexbox` for layout making it super responsive and performant. Leaving most of the layout heavy lifting
* to the browser. __note:__ The default styles use `height: 100%` which means your container must set an explicit
* height (feel free to adjust the styles to suit your specific needs).
*
* Big Calendar is unopiniated about editing and moving events, prefering to let you implement it in a way that makes
* the most sense to your app. It also tries not to be prescriptive about your event data structures, just tell it
* how to find the start and end datetimes and you can pass it whatever you want.
*
* One thing to note is that, `react-big-calendar` treats event start/end dates as an _exclusive_ range.
* which means that the event spans up to, but not including, the end date. In the case
* of displaying events on whole days, end dates are rounded _up_ to the next day. So an
* event ending on `Apr 8th 12:00:00 am` will not appear on the 8th, whereas one ending
* on `Apr 8th 12:01:00 am` will. If you want _inclusive_ ranges consider providing a
* function `endAccessor` that returns the end date + 1 day for those events that end at midnight.
*/
const PROPERTY_TYPES = {
/**
* The current date value of the calendar. Determines the visible view range
*
* @controllable onNavigate
*/
date: PropTypes.instanceOf(Date),
defaultDate: PropTypes.instanceOf(Date),
/**
* The current view of the calendar.
*
* @default 'month'
* @controllable onView
*/
view: PropTypes.string,
/**
* An array of event objects to display on the calendar
*/
events: PropTypes.arrayOf(PropTypes.object),
/**
* An array of event objects to display on the calendar
*/
nonWorkingDays: PropTypes.arrayOf(PropTypes.object),
/**
* Callback fired when the `date` value changes.
*
* @controllable date
*/
onNavigate: PropTypes.func,
/**
* Callback fired when the `view` value changes.
*
* @controllable date
*/
onView: PropTypes.func,
/**
* A callback fired when a date selection is made. Only fires when `selectable` is `true`.
*
* ```js
* function(
* slotInfo: object {
* start: date,
* end: date,
* slots: array<date>
* }
* )
* ```
*/
onSelectSlot: PropTypes.func,
/**
* Callback fired when a calendar event is selected.
*
* ```js
* function(event: object)
* ```
*/
onSelectEvent: PropTypes.func,
/**
* Callback fired when dragging a selection in the Time views.
*
* Returning `false` from the handler will prevent a selection.
*
* ```js
* function ({ start: Date, end: Date }) : boolean
* ```
*/
onSelecting: PropTypes.func,
/**
* An array of built-in view names to allow the calendar to display.
*
* @type Calendar.views
* @default ['month', 'week', 'day', 'agenda']
*/
views: componentViews,
/**
* Determines whether the toolbar is displayed
*/
toolbar: PropTypes.bool,
/**
* Show truncated events in an overlay when you click the "+_x_ more" link.
*/
popup: PropTypes.bool,
/**
* Distance in pixels, from the edges of the viewport, the "show more" overlay should be positioned.
*
* ```js
* <BigCalendar popupOffset={30}/>
* <BigCalendar popupOffset={{x: 30, y: 20}}/>
* ```
*/
popupOffset: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ x: PropTypes.number, y: PropTypes.number })]),
/**
* Allows mouse selection of ranges of dates/times.
*/
selectable: PropTypes.bool,
/**
* switch the calendar to a `right-to-left` read direction.
*/
rtl: PropTypes.bool,
/**
* Optionally provide a function that returns an object of className or style props
* to be applied to the the event node.
*
* ```js
* function(
* event: object,
* start: date,
* end: date,
* isSelected: bool
* ) -> { className: string?, style: object? }
* ```
*/
eventPropGetter: PropTypes.func,
/**
* Accessor for the event title, used to display event information. Should
* resolve to a `renderable` value.
*
* @type {(func|string)}
*/
titleAccessor: accessor,
/**
* Determines whether the event should be considered an "all day" event and ignore time.
* Must resolve to a `boolean` value.
*
* @type {(func|string)}
*/
allDayAccessor: accessor,
/**
* The start date/time of the event. Must resolve to a JavaScript `Date` object.
*
* @type {(func|string)}
*/
startAccessor: accessor,
/**
* The end date/time of the event. Must resolve to a JavaScript `Date` object.
*
* @type {(func|string)}
*/
endAccessor: accessor,
/**
* Constrains the minimum _time_ of the Day and Week views.
*/
min: PropTypes.instanceOf(Date),
/**
* Constrains the maximum _time_ of the Day and Week views..
*/
max: PropTypes.instanceOf(Date),
/**
* Localizer specific formats, tell the Calendar how to format and display dates.
*/
formats: PropTypes.shape({
/**
* Format for the day of the month heading in the Month view.
*/
dateFormat,
/**
* A day of the week format for Week and Day headings
*/
dayFormat: dateFormat,
/**
* Week day name format for the Month week day headings.
*/
weekdayFormat: dateFormat,
/**
* Toolbar header format for the Month view.
*/
monthHeaderFormat: dateFormat,
/**
* Toolbar header format for the Week views.
*/
weekHeaderFormat: dateFormat,
/**
* Toolbar header format for the Day view.
*/
dayHeaderFormat: dateFormat,
/**
* Toolbar header format for the Agenda view.
*/
agendaHeaderFormat: dateFormat,
/**
* A time range format for selecting time slots.
*/
selectRangeFormat: dateFormat,
onRangeSelected: PropTypes.func,
draggableSelect: PropTypes.func,
agendaDateFormat: dateFormat,
agendaTimeFormat: dateFormat,
agendaTimeRangeFormat: dateFormat
}),
/**
* Customize how different sections of the calendar render by providing custom Components.
* In particular the `Event` component can be specified for the entire calendar, or you can
* provide an individual component for each view type.
*
* ```jsx
* let components = {
* event: MyEvent, // used by each view (Month, Day, Week)
* toolbar: MyToolbar,
* agenda: {
* event: MyAgendaEvent // with the agenda view use a different component to render events
* }
* }
* <Calendar components={components} />
* ```
*/
components: PropTypes.shape({
event: elementType,
toolbar: elementType,
agenda: PropTypes.shape({
date: elementType,
time: elementType,
event: elementType
}),
day: PropTypes.shape({ event: elementType }),
week: PropTypes.shape({ event: elementType }),
month: PropTypes.shape({ event: elementType })
}),
/**
* String messages used throughout the component, override to provide localizations
*/
messages: PropTypes.shape({
allDay: PropTypes.node,
previous: PropTypes.node,
next: PropTypes.node,
today: PropTypes.node,
month: PropTypes.node,
week: PropTypes.node,
day: PropTypes.node,
agenda: PropTypes.node,
showMore: PropTypes.func
})
};
const DEFAULT_PROPS = {
popup: false,
toolbar: true,
view: views.MONTH,
views: [views.MONTH, views.WEEK, views.DAY, views.AGENDA],
date: now,
titleAccessor: 'title',
allDayAccessor: 'allDay',
startAccessor: 'start',
endAccessor: 'end'
};
class Calendar extends React.Component {
constructor(props) {
super(props);
this.getViews = this.getViews.bind(this);
this.getView = this.getView.bind(this);
this._navigate = this._navigate.bind(this);
this._viewNavigate = this._viewNavigate.bind(this);
this._view = this._view.bind(this);
this._select = this._select.bind(this);
this._selectSlot = this._selectSlot.bind(this);
this._headerClick = this._headerClick.bind(this);
}
getViews() {
const views = this.props.views;
if (Array.isArray(views)) {
return transform(views, (obj, name) => (obj[name] = VIEWS[name]), {});
}
if (typeof views === 'object') {
return mapValues(views, (value, key) => {
if (value === true) {
return VIEWS[key];
}
return value;
});
}
return VIEWS;
}
getView() {
const views = this.getViews();
return views[this.props.view];
}
_navigate(action, newDate) {
let { view, date, onNavigate } = this.props;
date = moveDate(action, newDate || date, view);
onNavigate(date, view);
if (action === navigate.DATE) this._viewNavigate(date);
}
_viewNavigate(nextDate) {
let { view, date, culture } = this.props;
if (dates.eq(date, nextDate, view, localizer.startOfWeek(culture))) {
this._view(views.DAY);
}
}
_view(view) {
if (view !== this.props.view && isValidView(view, this.props)) this.props.onView(view);
}
_select(event) {
notify(this.props.onSelectEvent, event);
}
_selectSlot(slotInfo) {
notify(this.props.onSelectSlot, slotInfo);
}
_headerClick(date) {
let { view } = this.props;
if (view === views.MONTH || view === views.WEEK) this._view(views.day);
this._navigate(navigate.DATE, date);
}
render() {
let {
view,
toolbar,
events,
nonWorkingDays,
culture,
components = {},
formats = {},
style,
className,
date: current,
elementProps,
...props
} = this.props;
formats = defaultFormats(formats);
let View = this.getView();
let names = viewNames(this.props.views);
let viewComponents = defaults(components[view] || {}, omit(components, names));
let ToolbarToRender = components.toolbar || Toolbar;
return (
<div
{...elementProps}
className={cn('rbc-calendar', className, {
'rbc-rtl': props.rtl
})}
style={style}
>
{toolbar && (
<ToolbarToRender
date={current}
view={view}
views={names}
label={viewLabel(current, view, formats, culture)}
onViewChange={this._view}
onNavigate={this._navigate}
messages={this.props.messages}
/>
)}
<View
ref="view"
{...props}
{...formats}
culture={culture}
formats={undefined}
events={events}
nonWorkingDays={nonWorkingDays}
date={current}
components={viewComponents}
onNavigate={this._navigate}
onHeaderClick={this._headerClick}
onSelectEvent={this._select}
onSelectSlot={this._selectSlot}
onShowMore={this._showMore}
/>
</div>
);
}
}
Calendar.propTypes = PROPERTY_TYPES;
Calendar.defaultProps = DEFAULT_PROPS;
export default uncontrollable(Calendar, {
view: 'onView',
date: 'onNavigate',
selected: 'onSelectEvent'
});
|
src/PredefinedRanges.js
|
trueanthem/react-date-range
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import parseInput from './utils/parseInput.js';
import { defaultClasses } from './styles.js';
class PredefinedRanges extends Component {
constructor(props, context) {
super(props, context);
this.styles = this.props.theme;
}
handleSelect(name, event) {
event.preventDefault();
const range = this.props.ranges[name];
this.props.onSelect({
startDate : parseInput(range['startDate']),
endDate : parseInput(range['endDate']),
}, PredefinedRanges);
}
renderRangeList(classes) {
const { ranges, range, onlyClasses } = this.props;
const { styles } = this;
return Object.keys(ranges).map(name => {
const active = (
parseInput(ranges[name].startDate).isSame(range.startDate) &&
parseInput(ranges[name].endDate).isSame(range.endDate)
);
const style = {
...styles['PredefinedRangesItem'],
...(active ? styles['PredefinedRangesItemActive'] : {}),
};
return (
<a
href='#'
key={'range-' + name}
className={classes.predefinedRangesItem + (active ? ' active' : '')}
style={ onlyClasses ? undefined : style }
onClick={this.handleSelect.bind(this, name)}
>
{name}
</a>
);
}.bind(this));
}
render() {
const { style, onlyClasses, classNames } = this.props;
const { styles } = this;
const classes = { ...defaultClasses, ...classNames };
return (
<div
style={onlyClasses ? undefined : { ...styles['PredefinedRanges'], ...style }}
className={ classes.predefinedRanges }
>
{ this.renderRangeList(classes) }
</div>
);
}
}
PredefinedRanges.defaultProps = {
onlyClasses : false,
classNames : {}
};
PredefinedRanges.propTypes = {
ranges : PropTypes.object.isRequired,
onlyClasses : PropTypes.bool,
classNames : PropTypes.object
}
export default PredefinedRanges;
|
packages/react-scripts/fixtures/kitchensink/src/features/webpack/ImageInclusion.js
|
josephfinlayson/create-react-app
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React from 'react'
import tiniestCat from './assets/tiniest-cat.jpg'
export default () => (
<img id="feature-image-inclusion" src={tiniestCat} alt="tiniest cat" />
)
|
src/deprecated/Navbar.js
|
Sipree/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import deprecated from 'react-prop-types/lib/deprecated';
import elementType from 'react-prop-types/lib/elementType';
import Grid from '../Grid';
import NavBrand from '../NavBrand';
import tbsUtils, { bsClass, bsStyles } from '../utils/bootstrapUtils';
import { DEFAULT, INVERSE } from '../styleMaps';
import createChainedFunction from '../utils/createChainedFunction';
import ValidComponentChildren from '../utils/ValidComponentChildren';
const Navbar = React.createClass({
propTypes: {
fixedTop: React.PropTypes.bool,
fixedBottom: React.PropTypes.bool,
staticTop: React.PropTypes.bool,
inverse: React.PropTypes.bool,
fluid: React.PropTypes.bool,
role: React.PropTypes.string,
/**
* You can use a custom element for this component
*/
componentClass: elementType,
brand: deprecated(React.PropTypes.node, 'Use the `NavBrand` component.'),
toggleButton: React.PropTypes.node,
toggleNavKey: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
]),
onToggle: React.PropTypes.func,
navExpanded: React.PropTypes.bool,
defaultNavExpanded: React.PropTypes.bool
},
// TODO Remove in 0.29
childContextTypes: {
$bs_deprecated_navbar: React.PropTypes.bool
},
getChildContext() {
return {
$bs_deprecated_navbar: true
};
},
getDefaultProps() {
return {
role: 'navigation',
componentClass: 'nav',
fixedTop: false,
fixedBottom: false,
staticTop: false,
inverse: false,
fluid: false,
defaultNavExpanded: false
};
},
getInitialState() {
return {
navExpanded: this.props.defaultNavExpanded
};
},
shouldComponentUpdate() {
// Defer any updates to this component during the `onSelect` handler.
return !this._isChanging;
},
handleToggle() {
if (this.props.onToggle) {
this._isChanging = true;
this.props.onToggle();
this._isChanging = false;
}
this.setState({
navExpanded: !this.state.navExpanded
});
},
isNavExpanded() {
return this.props.navExpanded != null ? this.props.navExpanded : this.state.navExpanded;
},
hasNavBrandChild() {
return ValidComponentChildren.findValidComponents(
this.props.children, child => child.props.bsRole === 'brand'
).length > 0;
},
render() {
const {
brand,
toggleButton,
toggleNavKey,
fixedTop,
fixedBottom,
staticTop,
inverse,
componentClass: ComponentClass,
fluid,
className,
children,
...props
} = this.props;
// will result in some false positives but that seems better
// than false negatives. strict `undefined` check allows explicit
// "nulling" of the role if the user really doesn't want one
if (props.role === undefined && ComponentClass !== 'nav') {
props.role = 'navigation';
}
const classes = tbsUtils.getClassSet(this.props);
classes[tbsUtils.prefix(this.props, 'fixed-top')] = this.props.fixedTop;
classes[tbsUtils.prefix(this.props, 'fixed-bottom')] = this.props.fixedBottom;
classes[tbsUtils.prefix(this.props, 'static-top')] = this.props.staticTop;
// handle built-in styles manually to provide the convenience `inverse` prop
classes[tbsUtils.prefix(this.props, INVERSE)] = this.props.inverse;
classes[tbsUtils.prefix(this.props, DEFAULT)] = !this.props.inverse;
const showHeader =
(brand || toggleButton || toggleNavKey != null) &&
!this.hasNavBrandChild();
return (
<ComponentClass {...props} className={classNames(className, classes)}>
<Grid fluid={fluid}>
{showHeader ? this.renderBrandHeader() : null}
{ValidComponentChildren.map(children, this.renderChild)}
</Grid>
</ComponentClass>
);
},
renderBrandHeader() {
let {brand} = this.props;
if (brand) {
brand = <NavBrand>{brand}</NavBrand>;
}
return this.renderHeader(brand);
},
renderHeader(brand) {
const hasToggle = this.props.toggleButton || this.props.toggleNavKey != null;
const headerClass = tbsUtils.prefix(this.props, 'header');
return (
<div className={headerClass}>
{brand}
{hasToggle ? this.renderToggleButton() : null}
</div>
);
},
renderChild(child, index) {
const key = child.key != null ? child.key : index;
if (child.props.bsRole === 'brand') {
return React.cloneElement(this.renderHeader(child), {key});
}
const {toggleNavKey} = this.props;
const collapsible =
toggleNavKey != null && toggleNavKey === child.props.eventKey;
return React.cloneElement(child, {
navbar: true,
collapsible,
expanded: collapsible && this.isNavExpanded(),
key
});
},
renderToggleButton() {
const {toggleButton} = this.props;
const toggleClass = tbsUtils.prefix(this.props, 'toggle');
if (React.isValidElement(toggleButton)) {
return React.cloneElement(toggleButton, {
className: classNames(toggleButton.props.className, toggleClass),
onClick: createChainedFunction(
this.handleToggle, toggleButton.props.onClick
)
});
}
let children;
if (toggleButton != null) {
children = toggleButton;
} else {
children = [
<span className="sr-only" key={0}>Toggle navigation</span>,
<span className="icon-bar" key={1}></span>,
<span className="icon-bar" key={2}></span>,
<span className="icon-bar" key={3}></span>
];
}
return (
<button
type="button"
onClick={this.handleToggle}
className={toggleClass}
>
{children}
</button>
);
}
});
const NAVBAR_STATES = [DEFAULT, INVERSE];
export default bsStyles(NAVBAR_STATES, DEFAULT,
bsClass('navbar',
Navbar
)
);
|
Example/App.js
|
rayshih/react-native-image-picker
|
import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
PixelRatio,
TouchableOpacity,
Image,
} from 'react-native';
import ImagePicker from 'react-native-image-picker';
export default class App extends React.Component {
state = {
avatarSource: null,
videoSource: null
};
selectPhotoTapped() {
const options = {
quality: 1.0,
maxWidth: 500,
maxHeight: 500,
storageOptions: {
skipBackup: true
}
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled photo picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
let source = { uri: response.uri };
// You can also display the image using data:
// let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source
});
}
});
}
selectVideoTapped() {
const options = {
title: 'Video Picker',
takePhotoButtonTitle: 'Take Video...',
mediaType: 'video',
videoQuality: 'medium'
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled video picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
this.setState({
videoSource: response.uri
});
}
});
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}>
<View style={[styles.avatar, styles.avatarContainer, {marginBottom: 20}]}>
{ this.state.avatarSource === null ? <Text>Select a Photo</Text> :
<Image style={styles.avatar} source={this.state.avatarSource} />
}
</View>
</TouchableOpacity>
<TouchableOpacity onPress={this.selectVideoTapped.bind(this)}>
<View style={[styles.avatar, styles.avatarContainer]}>
<Text>Select a Video</Text>
</View>
</TouchableOpacity>
{ this.state.videoSource &&
<Text style={{margin: 8, textAlign: 'center'}}>{this.state.videoSource}</Text>
}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF'
},
avatarContainer: {
borderColor: '#9B9B9B',
borderWidth: 1 / PixelRatio.get(),
justifyContent: 'center',
alignItems: 'center'
},
avatar: {
borderRadius: 75,
width: 150,
height: 150
}
});
|
src/svg-icons/hardware/developer-board.js
|
lawrence-yu/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareDeveloperBoard = (props) => (
<SvgIcon {...props}>
<path d="M22 9V7h-2V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-2h2v-2h-2v-2h2v-2h-2V9h2zm-4 10H4V5h14v14zM6 13h5v4H6zm6-6h4v3h-4zM6 7h5v5H6zm6 4h4v6h-4z"/>
</SvgIcon>
);
HardwareDeveloperBoard = pure(HardwareDeveloperBoard);
HardwareDeveloperBoard.displayName = 'HardwareDeveloperBoard';
HardwareDeveloperBoard.muiName = 'SvgIcon';
export default HardwareDeveloperBoard;
|
src/svg-icons/toggle/star-border.js
|
pancho111203/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ToggleStarBorder = (props) => (
<SvgIcon {...props}>
<path d="M22 9.24l-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03L22 9.24zM12 15.4l-3.76 2.27 1-4.28-3.32-2.88 4.38-.38L12 6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28L12 15.4z"/>
</SvgIcon>
);
ToggleStarBorder = pure(ToggleStarBorder);
ToggleStarBorder.displayName = 'ToggleStarBorder';
ToggleStarBorder.muiName = 'SvgIcon';
export default ToggleStarBorder;
|
tests/components/Header/Header.spec.js
|
chenyang0424/initial-project
|
import React from 'react'
import { Header } from 'components/Header/Header'
import { IndexLink, Link } from 'react-router'
import { shallow } from 'enzyme'
describe('(Component) Header', () => {
let _wrapper
beforeEach(() => {
_wrapper = shallow(<Header />)
})
it('Renders a welcome message', () => {
const welcome = _wrapper.find('h1')
expect(welcome).to.exist
expect(welcome.text()).to.match(/React Redux Starter Kit/)
})
describe('Navigation links...', () => {
it('Should render a Link to Home route', () => {
expect(_wrapper.contains(
<IndexLink activeClassName='route--active' to='/'>
Home
</IndexLink>
)).to.be.true
})
it('Should render a Link to Counter route', () => {
expect(_wrapper.contains(
<Link activeClassName='route--active' to='/counter'>
Counter
</Link>
)).to.be.true
})
})
})
|
src/components/AddStockButton/AddStockButton.js
|
pvijeh/stock-tracking-app-reactjs
|
/**
* 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, { Component } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './AddStockButton.scss';
import AppActions from '../../actions/appActions';
class AddStockButton extends Component {
handleClick = event => {
AppActions.displayPopup(event);
}
render() {
return (
<button className={s.root} onClick={this.handleClick.bind(this, true)}>Add Stock</button>
);
}
}
export default withStyles(AddStockButton, s);
|
packages/cf-component-box/src/Box.js
|
mdno/mdno.github.io
|
import React from 'react';
import PropTypes from 'prop-types';
import { createComponent } from 'cf-style-container';
import propertiesSpec from './propertiesSpec';
const propertyNames = Object.keys(propertiesSpec);
// Generates styles given the provided props.
//
// This is driven by the metadata provided in propertiesSpec
// and produces a data structure like this:
//
// {
// margin: props.margin || props.theme['margin']
// width: props.width || props.theme['width']
// ...
// }
//
// See propertySpec.js for more detail
//
const styles = props => {
let styles = {};
const propKeys = Object.keys(props);
propKeys.forEach(name => {
// Lookup the spec for the property
const spec = propertiesSpec[name];
// Ignore non-style props
if (spec === undefined) {
return;
}
// Get the style value from props
let value = props[name];
// pre-process the value with all pre-processors
if (spec.preprocessWith) {
spec.preprocessWith.forEach(fn => {
value = fn(value);
});
}
styles[name] = value;
});
// Only do checks in dev mode
if (process.env.NODE_ENV !== 'production') {
checkForViolations(styles);
}
return styles;
};
const Box = props => {
const { className, children } = props;
// Render the div with the fela classname
return (
<div className={className}>
{children}
</div>
);
};
const checkForViolations = props => {
// Check for conflicts given the spec's conflictsWith property
// See propertySpec.js for more detail
propertyNames.forEach(propName => {
const spec = propertiesSpec[propName];
if (!props[propName] || !spec.conflictsWith) return;
spec.conflictsWith.forEach(otherPropName => {
if (props[propName] && props[otherPropName]) {
const msg = `${propName} cannot be set in conjunction with ${otherPropName}`;
console.error(msg);
}
});
});
// TODO: To pull this check off, we'll need re-evaluate our baseline.
// current is 22.5px
// checkLineHeightViolations(props);
};
const checkLineHeightViolations = props => {
const rem2px = rem => {
return parseFloat(rem) * props.fontSize;
};
const baseline = props.lineHeight * props.fontSize;
// Calculate total margin, padding, and border
let totalMargin = 0;
if (props.margin) {
totalMargin = rem2px(props.margin);
} else {
totalMargin += rem2px(props.marginTop) || 0;
totalMargin += rem2px(props.marginBottom) || 0;
}
let totalPadding = 0;
if (props.padding) {
totalPadding = rem2px(props.padding);
} else {
totalPadding += rem2px(props.paddingTop) || 0;
totalPadding += rem2px(props.paddingBottom) || 0;
}
let totalBorder = 0;
if (props.borderHeight) {
totalBorder = rem2px(props.borderHeight);
} else {
totalBorder += rem2px(props.borderTopHeight) || 0;
totalBorder += rem2px(props.borderBottomHeight) || 0;
}
// Warn the user if the total spacing isn't a multiple of the baseline
const spacing = totalMargin + totalBorder + totalPadding;
if (spacing && baseline % spacing !== 0) {
console.warn(
`Spacing from padding, border, and margin surrounding element should be a multiple of baseline ${baseline}.`
);
}
};
// Extract proptypes from the propertiesSpec
const extractPropTypes = () => {
let propTypes = {};
// Loop through all property specs and pluck the prop type
propertyNames.forEach(name => {
propTypes[name] = propertiesSpec[name].propType;
});
return propTypes;
};
Box.propTypes = extractPropTypes();
export default createComponent(styles, Box);
|
test/lists/list-item-spec.js
|
tomrosier/material-ui
|
import React from 'react';
import ListItem from 'lists/list-item';
import Checkbox from 'checkbox';
import injectTheme from '../fixtures/inject-theme';
import TestUtils from 'react-addons-test-utils';
describe('ListItem', () => {
let ThemedListItem;
beforeEach(() => {
ThemedListItem = injectTheme(ListItem);
});
it('should display a list-item', () => {
const render = TestUtils.renderIntoDocument(
<ThemedListItem />
);
const nodeTree = TestUtils.scryRenderedDOMComponentsWithTag(render, 'div');
const itemSpan = nodeTree[0].firstChild;
expect(itemSpan.tagName).to.equal('SPAN');
});
it('should display a list-item with text if primaryText is specified', () => {
const testText = 'Primary Text';
const render = TestUtils.renderIntoDocument(
<ThemedListItem
primaryText={testText}
/>
);
const nodeTree = TestUtils.scryRenderedDOMComponentsWithTag(render, 'div');
const itemSpan = nodeTree[0].firstChild;
expect(itemSpan.childNodes[0].innerText).to.equal(testText);
});
it('should display a list-item elment with a class if specified', () => {
const testClass = 'test-class';
const render = TestUtils.renderIntoDocument(
<ThemedListItem
className={testClass}
/>
);
const nodeTree = TestUtils.scryRenderedDOMComponentsWithTag(render, 'div');
const itemSpan = nodeTree[0].firstChild;
expect(itemSpan.hasAttribute('class')).to.be.true;
expect(itemSpan.getAttribute('class')).to.equal(testClass);
});
it('should display a disabled list-item if specified.', () => {
const render = TestUtils.renderIntoDocument(
<ThemedListItem
disabled={true}
/>
);
const nodeTree = TestUtils.scryRenderedDOMComponentsWithTag(render, 'div');
const itemDiv = nodeTree[0].firstChild;
expect(itemDiv.tagName).to.equal('DIV');
});
it('should display a disabled list-item with a class if specified.', () => {
const testClass = 'test-class';
const render = TestUtils.renderIntoDocument(
<ThemedListItem
className={testClass}
disabled={true}
/>
);
const nodeTree = TestUtils.scryRenderedDOMComponentsWithTag(render, 'div');
const itemDiv = nodeTree[0].firstChild;
expect(itemDiv.tagName).to.equal('DIV');
expect(itemDiv.hasAttribute('class')).to.be.true;
expect(itemDiv.getAttribute('class')).to.equal(testClass);
});
it('should display a checkbox in the list-item if specified.', () => {
const render = TestUtils.renderIntoDocument(
<ThemedListItem
leftCheckbox={<Checkbox />}
/>
);
const input = TestUtils.findRenderedDOMComponentWithTag(render, 'input');
expect(input.parentElement.tagName).to.equal('DIV');
expect(input.hasAttribute('checked')).to.be.false;
});
it('should have a class if specified with a checkbox.', () => {
const testClass = 'test-class';
const render = TestUtils.renderIntoDocument(
<ThemedListItem
leftCheckbox={<Checkbox />}
className={testClass}
/>
);
const input = TestUtils.findRenderedDOMComponentWithTag(render, 'input');
const listItemDiv = input.parentElement.parentElement;
expect(listItemDiv.tagName).to.equal('LABEL');
expect(listItemDiv.hasAttribute('class')).to.be.true;
expect(listItemDiv.getAttribute('class')).to.equal(testClass);
});
});
|
node_modules/react-router/es/Switch.js
|
bburnett-cpf/react-intro
|
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import React from 'react';
import PropTypes from 'prop-types';
import warning from 'warning';
import matchPath from './matchPath';
/**
* The public API for rendering the first <Route> that matches.
*/
var Switch = function (_React$Component) {
_inherits(Switch, _React$Component);
function Switch() {
_classCallCheck(this, Switch);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Switch.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
warning(!(nextProps.location && !this.props.location), '<Switch> elements should not change from uncontrolled to controlled (or vice versa). You initially used no "location" prop and then provided one on a subsequent render.');
warning(!(!nextProps.location && this.props.location), '<Switch> elements should not change from controlled to uncontrolled (or vice versa). You provided a "location" prop initially but omitted it on a subsequent render.');
};
Switch.prototype.render = function render() {
var route = this.context.router.route;
var children = this.props.children;
var location = this.props.location || route.location;
var match = void 0,
child = void 0;
React.Children.forEach(children, function (element) {
if (!React.isValidElement(element)) return;
var _element$props = element.props,
pathProp = _element$props.path,
exact = _element$props.exact,
strict = _element$props.strict,
from = _element$props.from;
var path = pathProp || from;
if (match == null) {
child = element;
match = path ? matchPath(location.pathname, { path: path, exact: exact, strict: strict }) : route.match;
}
});
return match ? React.cloneElement(child, { location: location, computedMatch: match }) : null;
};
return Switch;
}(React.Component);
Switch.contextTypes = {
router: PropTypes.shape({
route: PropTypes.object.isRequired
}).isRequired
};
Switch.propTypes = {
children: PropTypes.node,
location: PropTypes.object
};
export default Switch;
|
src/svg-icons/device/devices.js
|
hwo411/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceDevices = (props) => (
<SvgIcon {...props}>
<path d="M4 6h18V4H4c-1.1 0-2 .9-2 2v11H0v3h14v-3H4V6zm19 2h-6c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h6c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1zm-1 9h-4v-7h4v7z"/>
</SvgIcon>
);
DeviceDevices = pure(DeviceDevices);
DeviceDevices.displayName = 'DeviceDevices';
DeviceDevices.muiName = 'SvgIcon';
export default DeviceDevices;
|
src/svg-icons/action/hourglass-empty.js
|
ichiohta/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionHourglassEmpty = (props) => (
<SvgIcon {...props}>
<path d="M6 2v6h.01L6 8.01 10 12l-4 4 .01.01H6V22h12v-5.99h-.01L18 16l-4-4 4-3.99-.01-.01H18V2H6zm10 14.5V20H8v-3.5l4-4 4 4zm-4-5l-4-4V4h8v3.5l-4 4z"/>
</SvgIcon>
);
ActionHourglassEmpty = pure(ActionHourglassEmpty);
ActionHourglassEmpty.displayName = 'ActionHourglassEmpty';
ActionHourglassEmpty.muiName = 'SvgIcon';
export default ActionHourglassEmpty;
|
test/SafeAnchorSpec.js
|
herojobs/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import SafeAnchor from '../src/SafeAnchor';
describe('SafeAnchor', function() {
it('renders an anchor tag', function() {
const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor />);
const node = React.findDOMNode(instance);
node.tagName.should.equal('A');
});
it('forwards arbitrary props to the anchor', function() {
const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor herpa='derpa' />);
const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A');
anchor.props.herpa.should.equal('derpa');
});
it('forwards provided href', function() {
const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor href='http://google.com' />);
const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A');
anchor.props.href.should.equal('http://google.com');
});
it('ensures that an href is provided', function() {
const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor />);
const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A');
anchor.props.href.should.equal('');
});
it('forwards onClick handler', function(done) {
const handleClick = (event) => {
done();
};
const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor onClick={handleClick} />);
const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A');
ReactTestUtils.Simulate.click(anchor);
});
it('prevents default when no href is provided', function(done) {
const handleClick = (event) => {
expect(event.isDefaultPrevented()).to.not.be.ok;
setTimeout(() => {
event.isDefaultPrevented().should.be.true;
done();
}, 100);
};
const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor onClick={handleClick} />);
const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A');
ReactTestUtils.Simulate.click(anchor);
});
it('does not prevent default when href is provided', function(done) {
const handleClick = (event) => {
expect(event.isDefaultPrevented()).to.not.be.ok;
setTimeout(() => {
expect(event.isDefaultPrevented()).to.not.be.ok;
done();
});
};
const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor href='#' onClick={handleClick} />);
const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A');
ReactTestUtils.Simulate.click(anchor);
});
it('forwards provided role', function () {
const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor role='test' />);
const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A');
anchor.props.role.should.equal('test');
});
it('forwards provided role with href', function () {
const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor role='test' href='http://google.com' />);
const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A');
anchor.props.role.should.equal('test');
});
it('set role=button with no provided href', function () {
const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor />);
const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A');
anchor.props.role.should.equal('button');
});
it('sets no role with provided href', function () {
const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor href='http://google.com' />);
const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A');
expect(anchor.props.role).to.be.undefined;
});
});
|
tests/lib/rules/vars-on-top.js
|
mathiasbynens/eslint
|
/**
* @fileoverview Tests for vars-on-top rule.
* @author Danny Fritz
* @author Gyandeep Singh
* @copyright 2014 Danny Fritz. All rights reserved.
* @copyright 2014 Gyandeep Singh. All rights reserved.
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var rule = require("../../../lib/rules/vars-on-top"),
EslintTester = require("../../../lib/testers/rule-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
var ruleTester = new EslintTester();
ruleTester.run("vars-on-top", rule, {
valid: [
[
"var first = 0;",
"function foo() {",
" first = 2;",
"}"
].join("\n"),
[
"function foo() {",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" if (true) {",
" first = true;",
" } else {",
" first = 1;",
" }",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" var third;",
" var fourth = 1, fifth, sixth = third;",
" var seventh;",
" if (true) {",
" third = true;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var i;",
" for (i = 0; i < 10; i++) {",
" alert(i);",
" }",
"}"
].join("\n"),
[
"function foo() {",
" var outer;",
" function inner() {",
" var inner = 1;",
" var outer = inner;",
" }",
" outer = 1;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" //Hello",
" var second = 1;",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" /*",
" Hello Clarice",
" */",
" var second = 1;",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" function bar(){",
" var first;",
" first = 5;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" function bar(){",
" var third;",
" third = 5;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var bar = function(){",
" var third;",
" third = 5;",
" }",
" first = 5;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" first.onclick(function(){",
" var third;",
" third = 5;",
" });",
" first = 5;",
"}"
].join("\n"),
{
code: [
"function foo() {",
" var i = 0;",
" for (let j = 0; j < 10; j++) {",
" alert(j);",
" }",
" i = i + 1;",
"}"
].join("\n"),
parserOptions: {
ecmaVersion: 6
}
},
"'use strict'; var x; f();",
"'use strict'; 'directive'; var x; var y; f();",
"function f() { 'use strict'; var x; f(); }",
"function f() { 'use strict'; 'directive'; var x; var y; f(); }",
{code: "import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }},
{code: "'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }},
{code: "import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }},
{code: "import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }},
{code: "import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }},
{code: "import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }},
{code: "import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }},
{code: "import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }}
],
invalid: [
{
code: [
"var first = 0;",
"function foo() {",
" first = 2;",
" second = 2;",
"}",
"var second = 0;"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first;",
" first = 1;",
" first = 2;",
" first = 3;",
" first = 4;",
" var second = 1;",
" second = 2;",
" first = second;",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first;",
" if (true) {",
" var second = true;",
" }",
" first = second;",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" for (var i = 0; i < 10; i++) {",
" alert(i);",
" }",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" for (i = 0; i < first; i ++) {",
" var second = i;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" switch (first) {",
" case 10:",
" var hello = 1;",
" break;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" try {",
" var hello = 1;",
" } catch (e) {",
" alert('error');",
" }",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" try {",
" asdf;",
" } catch (e) {",
" var hello = 1;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" while (first) {",
" var hello = 1;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" do {",
" var hello = 1;",
" } while (first == 10);",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = [1,2,3];",
" for (var item in first) {",
" item++;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = [1,2,3];",
" var item;",
" for (item in first) {",
" var hello = item;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"var foo = () => {",
" var first = [1,2,3];",
" var item;",
" for (item in first) {",
" var hello = item;",
" }",
"}"
].join("\n"),
parserOptions: { ecmaVersion: 6 },
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: "'use strict'; 0; var x; f();",
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "'use strict'; var x; 'directive'; var y; f();",
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "function f() { 'use strict'; 0; var x; f(); }",
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "function f() { 'use strict'; var x; 'directive'; var y; f(); }",
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
}
]
});
|
app/react-icons/fa/history.js
|
scampersand/sonos-front
|
import React from 'react';
import IconBase from 'react-icon-base';
export default class FaHistory extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m37.3 20q0 3.5-1.4 6.7t-3.6 5.4-5.5 3.7-6.7 1.3q-3.8 0-7.3-1.6t-5.8-4.5q-0.2-0.3-0.2-0.5t0.2-0.5l3.1-3.1q0.2-0.2 0.5-0.2 0.4 0.1 0.5 0.3 1.7 2.1 4 3.3t5 1.1q2.4 0 4.5-0.9t3.6-2.4 2.5-3.7 0.9-4.4-0.9-4.4-2.5-3.7-3.6-2.4-4.5-0.9q-2.1 0-4.2 0.8t-3.5 2.2l3 3.1q0.7 0.7 0.3 1.6-0.3 0.8-1.3 0.8h-10q-0.5 0-1-0.4t-0.4-1v-10q0-0.9 0.9-1.3 0.9-0.4 1.5 0.3l2.9 2.9q2.4-2.3 5.5-3.5t6.3-1.2q3.5 0 6.7 1.3t5.5 3.7 3.6 5.4 1.4 6.7z m-14.3-6.4v10q0 0.3-0.2 0.5t-0.5 0.2h-7.2q-0.3 0-0.5-0.2t-0.2-0.5v-1.5q0-0.3 0.2-0.5t0.5-0.2h5v-7.8q0-0.3 0.2-0.5t0.6-0.2h1.4q0.3 0 0.5 0.2t0.2 0.5z"/></g>
</IconBase>
);
}
}
|
src/main.js
|
RequestTimeout408/alba-task
|
import React from 'react'
import ReactDOM from 'react-dom'
import createStore from './store/createStore'
import AppContainer from './containers/AppContainer'
// ========================================================
// Store Instantiation
// ========================================================
const initialState = window.___INITIAL_STATE__
const store = createStore(initialState)
// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('root')
let render = () => {
const routes = require('./routes/index').default(store)
ReactDOM.render(
<AppContainer store={store} routes={routes} />,
MOUNT_NODE
)
}
// ========================================================
// Developer Tools Setup
// ========================================================
if (__DEV__) {
if (window.devToolsExtension) {
window.devToolsExtension.open()
}
}
// This code is excluded from production bundle
if (__DEV__) {
if (module.hot) {
// Development render functions
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react').default
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
}
// Wrap render in try/catch
render = () => {
try {
renderApp()
} catch (error) {
renderError(error)
}
}
// Setup hot module replacement
module.hot.accept('./routes/index', () =>
setImmediate(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE)
render()
})
)
}
}
// ========================================================
// Go!
// ========================================================
render()
|
src/containers/pages/decks/deck/right-container/sections/comments/comment/header.js
|
vFujin/HearthLounge
|
import React from 'react';
import MoreOptions from "../../../../../../../../components/more-options/more-options";
import {wrapDate} from "../../../../../../../../utils/wrap-date";
export const CommentHeader = ({authenticated, activeUserId, comment, handleCommentOptionsClick}) =>{
const {created, patch, commentId, authorId} = comment;
const commented = wrapDate(created / 1000);
return (
<div className="header">
<div className="commented">{commented}</div>
<div className="header-right">
<div className="patch">{patch}</div>
{authenticated && <MoreOptions commentId={commentId}
activeUserId={activeUserId}
authorId={authorId}
handleCommentOptionsClick={handleCommentOptionsClick}/>}
</div>
</div>
)
};
|
tests/components/SideNav.spec.js
|
longseespace/quickflix
|
import React from 'react'
import { shallow, mount } from 'enzyme'
import sinon from 'sinon'
import SideNav, { SideNavActivator } from 'components/SideNav'
describe('(Component) SideNav', () => {
it('renders as a <div>', () => {
const wrapper = shallow(<SideNav />)
expect(wrapper.type()).to.equal('div')
})
it('binds `collapsible` on mount', () => {
const collapsible = sinon.spy()
window.$ = (sel) => {
return {
collapsible
}
}
mount(<SideNav />)
expect(collapsible.called).to.be.true
})
})
describe('(Component) SideNavActivator', () => {
it('renders as a <a>', () => {
const wrapper = shallow(<SideNavActivator />)
expect(wrapper.type()).to.equal('a')
})
it('renders correct icon', () => {
const wrapper = shallow(<SideNavActivator icon='menu' />)
expect(wrapper.find('i').text()).to.equal('menu')
})
it('binds `sideNav` on mount', () => {
const sideNav = sinon.spy()
let selector = ''
window.$ = (sel) => {
selector = sel
return {
sideNav
}
}
const wrapper = mount(<SideNavActivator />)
expect(sideNav.called).to.be.true
expect(selector).to.equal(`#${wrapper.props().id}`)
})
})
|
assets/javascripts/kitten/components/navigation/header-nav/components/centered.js
|
KissKissBankBank/kitten
|
import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
export const Centered = ({ children, className, display, ...props }) => {
const classNameProps = classNames(
'k-HeaderNav__centered',
{ 'k-HeaderNav__column': display === 'column' },
className,
)
return (
<div {...props} className={classNameProps}>
{children}
</div>
)
}
Centered.propTypes = {
display: PropTypes.oneOf(['column']),
}
Centered.defaultProps = {
display: null,
}
|
app/javascript/mastodon/components/autosuggest_input.js
|
koba-lab/mastodon
|
import React from 'react';
import AutosuggestAccountContainer from '../features/compose/containers/autosuggest_account_container';
import AutosuggestEmoji from './autosuggest_emoji';
import AutosuggestHashtag from './autosuggest_hashtag';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import ImmutablePureComponent from 'react-immutable-pure-component';
import classNames from 'classnames';
const textAtCursorMatchesToken = (str, caretPosition, searchTokens) => {
let word;
let left = str.slice(0, caretPosition).search(/\S+$/);
let right = str.slice(caretPosition).search(/\s/);
if (right < 0) {
word = str.slice(left);
} else {
word = str.slice(left, right + caretPosition);
}
if (!word || word.trim().length < 3 || searchTokens.indexOf(word[0]) === -1) {
return [null, null];
}
word = word.trim().toLowerCase();
if (word.length > 0) {
return [left + 1, word];
} else {
return [null, null];
}
};
export default class AutosuggestInput extends ImmutablePureComponent {
static propTypes = {
value: PropTypes.string,
suggestions: ImmutablePropTypes.list,
disabled: PropTypes.bool,
placeholder: PropTypes.string,
onSuggestionSelected: PropTypes.func.isRequired,
onSuggestionsClearRequested: PropTypes.func.isRequired,
onSuggestionsFetchRequested: PropTypes.func.isRequired,
onChange: PropTypes.func.isRequired,
onKeyUp: PropTypes.func,
onKeyDown: PropTypes.func,
autoFocus: PropTypes.bool,
className: PropTypes.string,
id: PropTypes.string,
searchTokens: PropTypes.arrayOf(PropTypes.string),
maxLength: PropTypes.number,
};
static defaultProps = {
autoFocus: true,
searchTokens: ['@', ':', '#'],
};
state = {
suggestionsHidden: true,
focused: false,
selectedSuggestion: 0,
lastToken: null,
tokenStart: 0,
};
onChange = (e) => {
const [ tokenStart, token ] = textAtCursorMatchesToken(e.target.value, e.target.selectionStart, this.props.searchTokens);
if (token !== null && this.state.lastToken !== token) {
this.setState({ lastToken: token, selectedSuggestion: 0, tokenStart });
this.props.onSuggestionsFetchRequested(token);
} else if (token === null) {
this.setState({ lastToken: null });
this.props.onSuggestionsClearRequested();
}
this.props.onChange(e);
}
onKeyDown = (e) => {
const { suggestions, disabled } = this.props;
const { selectedSuggestion, suggestionsHidden } = this.state;
if (disabled) {
e.preventDefault();
return;
}
if (e.which === 229 || e.isComposing) {
// Ignore key events during text composition
// e.key may be a name of the physical key even in this case (e.x. Safari / Chrome on Mac)
return;
}
switch(e.key) {
case 'Escape':
if (suggestions.size === 0 || suggestionsHidden) {
document.querySelector('.ui').parentElement.focus();
} else {
e.preventDefault();
this.setState({ suggestionsHidden: true });
}
break;
case 'ArrowDown':
if (suggestions.size > 0 && !suggestionsHidden) {
e.preventDefault();
this.setState({ selectedSuggestion: Math.min(selectedSuggestion + 1, suggestions.size - 1) });
}
break;
case 'ArrowUp':
if (suggestions.size > 0 && !suggestionsHidden) {
e.preventDefault();
this.setState({ selectedSuggestion: Math.max(selectedSuggestion - 1, 0) });
}
break;
case 'Enter':
case 'Tab':
// Select suggestion
if (this.state.lastToken !== null && suggestions.size > 0 && !suggestionsHidden) {
e.preventDefault();
e.stopPropagation();
this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestions.get(selectedSuggestion));
}
break;
}
if (e.defaultPrevented || !this.props.onKeyDown) {
return;
}
this.props.onKeyDown(e);
}
onBlur = () => {
this.setState({ suggestionsHidden: true, focused: false });
}
onFocus = () => {
this.setState({ focused: true });
}
onSuggestionClick = (e) => {
const suggestion = this.props.suggestions.get(e.currentTarget.getAttribute('data-index'));
e.preventDefault();
this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestion);
this.input.focus();
}
componentWillReceiveProps (nextProps) {
if (nextProps.suggestions !== this.props.suggestions && nextProps.suggestions.size > 0 && this.state.suggestionsHidden && this.state.focused) {
this.setState({ suggestionsHidden: false });
}
}
setInput = (c) => {
this.input = c;
}
renderSuggestion = (suggestion, i) => {
const { selectedSuggestion } = this.state;
let inner, key;
if (suggestion.type === 'emoji') {
inner = <AutosuggestEmoji emoji={suggestion} />;
key = suggestion.id;
} else if (suggestion.type ==='hashtag') {
inner = <AutosuggestHashtag tag={suggestion} />;
key = suggestion.name;
} else if (suggestion.type === 'account') {
inner = <AutosuggestAccountContainer id={suggestion.id} />;
key = suggestion.id;
}
return (
<div role='button' tabIndex='0' key={key} data-index={i} className={classNames('autosuggest-textarea__suggestions__item', { selected: i === selectedSuggestion })} onMouseDown={this.onSuggestionClick}>
{inner}
</div>
);
}
render () {
const { value, suggestions, disabled, placeholder, onKeyUp, autoFocus, className, id, maxLength } = this.props;
const { suggestionsHidden } = this.state;
return (
<div className='autosuggest-input'>
<label>
<span style={{ display: 'none' }}>{placeholder}</span>
<input
type='text'
ref={this.setInput}
disabled={disabled}
placeholder={placeholder}
autoFocus={autoFocus}
value={value}
onChange={this.onChange}
onKeyDown={this.onKeyDown}
onKeyUp={onKeyUp}
onFocus={this.onFocus}
onBlur={this.onBlur}
dir='auto'
aria-autocomplete='list'
id={id}
className={className}
maxLength={maxLength}
/>
</label>
<div className={`autosuggest-textarea__suggestions ${suggestionsHidden || suggestions.isEmpty() ? '' : 'autosuggest-textarea__suggestions--visible'}`}>
{suggestions.map(this.renderSuggestion)}
</div>
</div>
);
}
}
|
src/controls/FullscreenControl.js
|
gribnoysup/react-yandex-maps
|
import React from 'react';
import PropTypes from 'prop-types';
import { withParentContext } from '../Context';
import withYMaps from '../withYMaps';
import { BaseControl } from './BaseControl';
export function FullscreenControl(props) {
return <BaseControl {...props} name="FullscreenControl" />;
}
if (process.env.NODE_ENV !== 'production') {
FullscreenControl.propTypes = {
/**
* Control [data](https://tech.yandex.com/maps/doc/jsapi/2.1/ref/reference/control.FullscreenControl-docpage/#control.FullscreenControl__param-parameters.data)
*/
data: PropTypes.shape({}),
/**
* Uncontrolled control [data](https://tech.yandex.com/maps/doc/jsapi/2.1/ref/reference/control.FullscreenControl-docpage/#control.FullscreenControl__param-parameters.data)
*/
defaultData: PropTypes.shape({}),
/**
* Control [options](https://tech.yandex.com/maps/doc/jsapi/2.1/ref/reference/control.FullscreenControl-docpage/#control.FullscreenControl__param-parameters.options)
*/
options: PropTypes.shape({}),
/**
* Uncontrolled control [options](https://tech.yandex.com/maps/doc/jsapi/2.1/ref/reference/control.FullscreenControl-docpage/#control.FullscreenControl__param-parameters.options)
*/
defaultOptions: PropTypes.shape({}),
/**
* Control [state](https://tech.yandex.com/maps/doc/jsapi/2.1/ref/reference/control.FullscreenControl-docpage/#control.FullscreenControl__param-parameters.state)
*/
state: PropTypes.shape({}),
/**
* Uncontrolled control [state](https://tech.yandex.com/maps/doc/jsapi/2.1/ref/reference/control.FullscreenControl-docpage/#control.FullscreenControl__param-parameters.state)
*/
defaultState: PropTypes.shape({}),
};
}
export default withParentContext(
withYMaps(FullscreenControl, true, [`control.FullscreenControl`])
);
|
client/src/components/dashboard/Error.js
|
PCGeekBrain/TruckTrack
|
import React from 'react';
import { Alert } from 'react-bootstrap'
/**
* A wrapper for the error alert
* @param {error: {key, message}, onDismiss: (key) => {} } props
*/
const Error = props => {
const dismiss = (event) => {
props.onDismiss(props.error.key)
}
return (
<Alert bsStyle="danger" onDismiss={dismiss}>
<p>{props.error.msg}</p>
</Alert>
);
}
export default Error;
|
browser/app/js/components/Dropzone.js
|
hackintoshrao/minio
|
/*
* Minio Cloud Storage (C) 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react'
import ReactDropzone from 'react-dropzone'
import * as actions from '../actions'
// Dropzone is a drag-and-drop element for uploading files. It will create a
// landing zone of sorts that automatically receives the files.
export default class Dropzone extends React.Component {
onDrop(files) {
// FIXME: Currently you can upload multiple files, but only one abort
// modal will be shown, and progress updates will only occur for one
// file at a time. See #171.
files.forEach(file => {
let req = new XMLHttpRequest()
// Dispatch the upload.
web.dispatch(actions.uploadFile(file, req))
})
}
render() {
// Overwrite the default styling from react-dropzone; otherwise it
// won't handle child elements correctly.
const style = {
height: '100%',
borderWidth: '0',
borderStyle: 'dashed',
borderColor: '#fff'
}
const activeStyle = {
borderWidth: '2px',
borderColor: '#777'
}
const rejectStyle = {
backgroundColor: '#ffdddd'
}
// disableClick means that it won't trigger a file upload box when
// the user clicks on a file.
return (
<ReactDropzone style={ style }
activeStyle={ activeStyle }
rejectStyle={ rejectStyle }
disableClick={ true }
onDrop={ this.onDrop }>
{ this.props.children }
</ReactDropzone>
)
}
}
|
docs/src/app/components/pages/components/FlatButton/ExampleIcon.js
|
ruifortes/material-ui
|
import React from 'react';
import FlatButton from 'material-ui/FlatButton';
import FontIcon from 'material-ui/FontIcon';
import ActionAndroid from 'material-ui/svg-icons/action/android';
import {fullWhite} from 'material-ui/styles/colors';
const style = {
margin: 12,
};
const FlatButtonExampleIcon = () => (
<div>
<FlatButton
icon={<ActionAndroid />}
style={style}
/>
<FlatButton
backgroundColor="#a4c639"
hoverColor="#8AA62F"
icon={<ActionAndroid color={fullWhite} />}
style={style}
/>
<FlatButton
href="https://github.com/callemall/material-ui"
secondary={true}
icon={<FontIcon className="muidocs-icon-custom-github" />}
style={style}
/>
</div>
);
export default FlatButtonExampleIcon;
|
src/parser/warlock/affliction/CONFIG.js
|
ronaldpereira/WoWAnalyzer
|
import React from 'react';
import { Chizu } from 'CONTRIBUTORS';
import SPECS from 'game/SPECS';
import CHANGELOG from './CHANGELOG';
export default {
// The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion.
contributors: [Chizu],
// The WoW client patch this spec was last updated to be fully compatible with.
patchCompatibility: '8.1',
// If set to false`, the spec will show up as unsupported.
isSupported: true,
// Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more.
// If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component.
// TODO: once there is an estabilished "rule of thumb" rotation, put it in the description
description: (
<>
Hello fellow Netherlords! With some help from <strong>Motoko</strong> from Warlock Discord, we've put together this tool to help you improve your gameplay. It should be fine for you generally, but it will be even more useful in an expert's hands. <br /> <br />
If you have any questions about Warlocks, feel free to pay a visit to <a href="https://discord.gg/BlackHarvest" target="_blank" rel="noopener noreferrer">Council of the Black Harvest Discord</a>
or <a href="http://lockonestopshop.com" target="_blank" rel="noopener noreferrer">Lock One Stop Shop</a>, if you'd like to discuss anything about this analyzer, message me @Chizu#2873 on WoWAnalyzer Discord.
</>
),
// A recent example report to see interesting parts of the spec. Will be shown on the homepage.
exampleReport: '/report/TGzmk4bXDZJndpj7/6-Heroic+Opulence+-+Kill+(8:12)/14-Optikz',
// Don't change anything below this line;
// The current spec identifier. This is the only place (in code) that specifies which spec this parser is about.
spec: SPECS.AFFLICTION_WARLOCK,
// The contents of your changelog.
changelog: CHANGELOG,
// The CombatLogParser class for your spec.
parser: () => import('./CombatLogParser' /* webpackChunkName: "AfflictionWarlock" */).then(exports => exports.default),
// The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code.
path: __dirname,
};
|
src/containers/card.story.js
|
francisl/baer-toolkit
|
import React from 'react';
import { containerSizeStyles } from '../../stories/config';
import Card from './card';
import Layout from '../layouts/layout';
import Button from '../widgets/button';
import Label from '../widgets/label';
import Input from '../widgets/input';
export default () => (
<div>
<h2>Simple form in a centered layout</h2>
<Layout center>
<Card style={{padding: '1rem 2rem'}}>
<Layout vertical>
<Label>Username</Label>
<Input></Input>
<Label>Password</Label>
<Input password></Input>
<Button>Login</Button>
</Layout>
</Card>
</Layout>
<pre><code>
{`
<Layout center>
<Card style={{padding: '2rem'}}>
<Layout vertical>
<Input></Input>
<Input></Input>
<Button>Login</Button>
</Layout>
</Card>
</Layout>`}
</code></pre>
<h2>Simple form in a centered layout</h2>
<Card center style={{padding: '1rem 2rem'}}>
<Layout vertical center>
<Layout center>
<Label>Username</Label>
<Input></Input>
</Layout>
<Layout center>
<Label>Password</Label>
<Input password></Input>
</Layout>
<Layout right>
<Button>Login</Button>
</Layout>
</Layout>
</Card>
<pre><code>
{`
<Layout center>
<Card style={{padding: '2rem'}}>
<Layout vertical center>
<Input></Input>
<Input></Input>
<Button>Login</Button>
</Layout>
</Card>
</Layout>`}
</code></pre>
</div>
);
|
src/svg-icons/maps/local-hospital.js
|
pomerantsev/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalHospital = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.1 0-1.99.9-1.99 2L3 19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-1 11h-4v4h-4v-4H6v-4h4V6h4v4h4v4z"/>
</SvgIcon>
);
MapsLocalHospital = pure(MapsLocalHospital);
MapsLocalHospital.displayName = 'MapsLocalHospital';
MapsLocalHospital.muiName = 'SvgIcon';
export default MapsLocalHospital;
|
src/components/App.js
|
CTumminaro/memory-game
|
import React from 'react';
import _ from 'lodash';
import Card from './Card';
import Header from './Header';
import sampleData from '../sample-data';
class App extends React.Component {
constructor() {
super();
this.flipCard = this.flipCard.bind(this);
const gameCards = _.chain(sampleData)
.reduce((memo, card) => {
const id = card.id;
const newId = id + 'a';
const cardDefaults = {
ref: id,
flipped: false,
matched: false,
error: false
};
memo.push(Object.assign({}, card, cardDefaults));
memo.push(Object.assign({}, card, cardDefaults, { id: newId }));
return memo;
}, [])
.shuffle()
.value();
//getinitialstate
this.state = {
cards: gameCards,
flipCount: 0,
playable: true,
attempts: 0
};
}
resetGame() {
let cards = [...this.state.cards];
cards.map((card) => {
Object.assign(card, {
flipped: false,
matched: false,
error: false
});
return card
});
//Flip Over
this.setState({ cards: cards, flipCount: 0, playable: false, attempts: 0 });
//Re-shuffle
cards = _.shuffle(cards);
setTimeout(() => {
this.setState({ cards: cards, playable: true});
}, 800);
}
checkMatch() {
const cards = [...this.state.cards];
const matches = _.filter(cards, { flipped: true, matched: false });
if (matches.length < 2) {
throw('Not enough cards to match');
}
const card1 = matches[0];
const card2 = matches[1];
if (card1.ref === card2.ref) {
card1.matched = true;
card2.matched = true;
}else {
card1.error = true;
card2.error = true;
}
this.setState({ cards: cards });
}
nextTurn() {
//copy state
const cards = [...this.state.cards];
const flipCount = 0;
const playable = true;
_.forEach(cards, (card) => {
if (!card.matched) {
card.flipped = false;
card.error = false;
}
});
this.setState({ cards: cards, flipCount: flipCount, playable: playable });
}
flipCard(id) {
if (this.state.playable) {
//copy state
const cards = [...this.state.cards];
const card = _.find(cards, { id: id });
//stop if card is already matched
if (card.matched) { return };
let flipCount = this.state.flipCount + 1;
let playable = true;
let attempts = this.state.attempts;
card.flipped = true;
if (flipCount === 2) {
this.checkMatch();
playable = false;
attempts = attempts + 1;
setTimeout(() => {
this.nextTurn()
}, 1300);
}
//update state
this.setState({ cards: cards, flipCount: flipCount, playable: playable, attempts: attempts });
}
}
render() {
const cardHTML = this.state.cards
.map(card => <Card key={card.id} card={card} flipCard={this.flipCard} />);
return(
<div>
<Header attempts={this.state.attempts} />
<div className="container">
<div className="cards">
{ cardHTML }
</div>
<hr />
<button className="button" onClick={() => { this.resetGame() }}>Reset</button>
</div>
</div>
)
}
}
export default App;
|
src/components/title.js
|
MichaelMansourati/earCamera
|
import React from 'react'
import '../styles/title.css'
const Title = () => (
<h1 id="title">
<a href="http://ear.camera">ear camera</a>
</h1>
)
export default Title
|
server/sonar-web/tests/apps/overview/components/legend-test.js
|
joansmith/sonarqube
|
import { expect } from 'chai';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import { Legend } from '../../../../src/main/js/apps/overview/components/legend';
const DATE = new Date(2015, 3, 7);
const LABEL = 'since 1.0';
describe('Legend', function () {
it('should render', function () {
let renderer = TestUtils.createRenderer();
renderer.render(<Legend leakPeriodDate={DATE} leakPeriodLabel={LABEL}/>);
let output = renderer.getRenderOutput();
expect(output).to.not.be.null;
});
});
|
packages/material-ui-shell/src/providers/VirtualLists/Context.js
|
TarikHuber/react-most-wanted
|
import React from 'react'
export const Context = React.createContext(null)
export default Context
|
docs/components/DocMenu.js
|
tianyingchun/docs
|
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as DocActions from '../actions/DocActions';
import { Link } from 'react-router';
import UI, { Menu, Icon } from '../../shared/react';
import classNames from 'classnames';
@connect((state) => ({ docMenus: state.docMenu }))
class DockMenu extends Component {
componentWillUpdate() {
console.log('dockMenu....update.');
}
static propTypes = {
component: React.PropTypes.string,
group: React.PropTypes.string
}
static defaultProps = {
component: 'flexlayout',
group: 'layout'
}
// for server rendering, use this feature we must move this into react-router
// components, `` views/ReactDocContent.js
// static needs = [
// (params) => DocActions.loadDocCatalogs(params)
// ]
state = {
current: '',
openKeys: []
}
// binding action creators.
action = bindActionCreators(DocActions, this.props.dispatch)
componentDidMount() {
let { dispatch } = this.props;
console.log('componentDidMount()...');
dispatch(() => this.action.loadDocCatalogs());
}
handleClick = (e) => {
console.log('click ', e);
this.setState({
current: e.key
});
}
getMenuTitle (title, subTitle, iconName) {
let iconClasses = {};
if (iconName) {
iconClasses["glyph-icon"] = true;
iconClasses['glyph-'+iconName] = true
}
return (
<span>
{ iconName ? <i className={classNames(iconClasses)}></i>: null}
<span>{title}</span>
<span className="menu-title-en">{subTitle}</span>
</span>
);
}
render() {
let isLoading = true;
let { docMenus, group, component } = this.props;
isLoading = docMenus.isLoading ? true : false;
if (isLoading === true) {
return (
<span><Icon icon="spinner6" spin /> 加载Doc列表...</span>
);
}
let openKeys = group ? [group] : this.state.openKeys;
let selectedKeys = [this.state.current || component];
if (!docMenus.data) {
return <span>获取列表失败!</span>
}
let groups = docMenus.data.groups;
const SubMenu = Menu.SubMenu;
return (
<Menu inlineIndent={12} onClick={this.handleClick} style={{width:'100%'}} defaultOpenKeys={openKeys} className="nav-left-dock " selectedKeys={selectedKeys} mode="inline">
{
groups.map((group) => {
return (
<SubMenu key={group.key} title={this.getMenuTitle(group.cName, group.enName)}>
{
group.children.map((component)=> {
return (
<Menu.Item key={component.key}>
<Link to={ "/docs/react/" + group.key + '/' + component.key} activeClassName="active">
{this.getMenuTitle(component.cName, component.enName)}
</Link>
</Menu.Item>
);
})
}
</SubMenu>
);
})
}
</Menu>
);
}
}
export default DockMenu;
|
src/ui/Button.js
|
lysfibe/host-cold-adventures
|
// @flow
import React from 'react'
import { TouchableOpacity, TouchableWithoutFeedback, TouchableHighlight, Text } from 'react-native'
type Props = {
onPress?: () => void,
onLongPress?: () => void,
containerStyle?: Object | Array,
style?: Object | Array,
highlight?: boolean,
noFeedback?: boolean,
}
const Button = ({ onPress, onLongPress, containerStyle, noFeedback, highlight, as: As = Text, ...props }: Props) => {
let Touchable = TouchableOpacity
if (noFeedback) {
Touchable = TouchableWithoutFeedback
} else if (highlight) {
Touchable = TouchableHighlight
}
return (
<Touchable onPress={onPress} onLongPress={onLongPress} style={containerStyle}>
<As {...props} />
</Touchable>
)
}
export default Button
|
node_modules/semantic-ui-react/src/views/Statistic/Statistic.js
|
mowbell/clickdelivery-fed-test
|
import cx from 'classnames'
import _ from 'lodash'
import PropTypes from 'prop-types'
import React from 'react'
import {
customPropTypes,
getElementType,
getUnhandledProps,
META,
SUI,
useKeyOnly,
useValueAndKey,
} from '../../lib'
import StatisticGroup from './StatisticGroup'
import StatisticLabel from './StatisticLabel'
import StatisticValue from './StatisticValue'
/**
* A statistic emphasizes the current value of an attribute.
*/
function Statistic(props) {
const {
children,
className,
color,
floated,
horizontal,
inverted,
label,
size,
text,
value,
} = props
const classes = cx(
'ui',
color,
size,
useValueAndKey(floated, 'floated'),
useKeyOnly(horizontal, 'horizontal'),
useKeyOnly(inverted, 'inverted'),
'statistic',
className,
)
const rest = getUnhandledProps(Statistic, props)
const ElementType = getElementType(Statistic, props)
if (!_.isNil(children)) return <ElementType {...rest} className={classes}>{children}</ElementType>
return (
<ElementType {...rest} className={classes}>
<StatisticValue text={text} value={value} />
<StatisticLabel label={label} />
</ElementType>
)
}
Statistic._meta = {
name: 'Statistic',
type: META.TYPES.VIEW,
}
Statistic.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** A statistic can be formatted to be different colors. */
color: PropTypes.oneOf(SUI.COLORS),
/** A statistic can sit to the left or right of other content. */
floated: PropTypes.oneOf(SUI.FLOATS),
/** A statistic can present its measurement horizontally. */
horizontal: PropTypes.bool,
/** A statistic can be formatted to fit on a dark background. */
inverted: PropTypes.bool,
/** Label content of the Statistic. */
label: customPropTypes.contentShorthand,
/** A statistic can vary in size. */
size: PropTypes.oneOf(_.without(SUI.SIZES, 'big', 'massive', 'medium')),
/** Format the StatisticValue with smaller font size to fit nicely beside number values. */
text: PropTypes.bool,
/** Value content of the Statistic. */
value: customPropTypes.contentShorthand,
}
Statistic.Group = StatisticGroup
Statistic.Label = StatisticLabel
Statistic.Value = StatisticValue
export default Statistic
|
internals/templates/containers/LanguageProvider/index.js
|
react-boilerplate/react-boilerplate
|
/*
*
* LanguageProvider
*
* this component connects the redux state language locale to the
* IntlProvider component and i18n messages (loaded from `app/translations`)
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { IntlProvider } from 'react-intl';
import { makeSelectLocale } from './selectors';
export function LanguageProvider(props) {
return (
<IntlProvider
locale={props.locale}
key={props.locale}
messages={props.messages[props.locale]}
>
{React.Children.only(props.children)}
</IntlProvider>
);
}
LanguageProvider.propTypes = {
locale: PropTypes.string,
messages: PropTypes.object,
children: PropTypes.element.isRequired,
};
const mapStateToProps = createSelector(
makeSelectLocale(),
locale => ({
locale,
}),
);
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
export default connect(
mapStateToProps,
mapDispatchToProps,
)(LanguageProvider);
|
src/containers/UserSongs.js
|
kellhellia/vkReduxLast
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import store from '../store';
import { getUserTracks } from '../actions';
class UserSongs extends Component {
componentDidMount() {
this.getTracks();
}
getTracks() {
VK.api('audio.get',{
owner_id: 21040845,
count: 20
}, (data) => {
if (data.response) {
this.props.dispatch(getUserTracks(data.response));
}
});
}
render() {
let tracks = this.props.tracks.map((track, index) => {
if (track.title) {
return (
<div key={index}>
<p>{track.artist} - {track.title}</p>
<audio key={index} preload="none" controls>
<source src={track.url}/>
</audio>
</div>
)
}
return <span key={index} />
});
return (
<div className="row">
<div className="col-xs-4 text-left">
<p>My tracks</p>
{tracks}
</div>
</div>
);
}
}
UserSongs = connect(state => state)(UserSongs);
export default UserSongs;
|
src/internal/BeforeAfterWrapper.js
|
skarnecki/material-ui
|
import React from 'react';
/**
* BeforeAfterWrapper
* An alternative for the ::before and ::after css pseudo-elements for
* components whose styles are defined in javascript instead of css.
*
* Usage: For the element that we want to apply before and after elements to,
* wrap its children with BeforeAfterWrapper. For example:
*
* <Paper>
* <Paper> <div> // See notice
* <BeforeAfterWrapper> renders <div/> // before element
* [children of paper] ------> [children of paper]
* </BeforeAfterWrapper> <div/> // after element
* </Paper> </div>
* </Paper>
*
* Notice: Notice that this div bundles together our elements. If the element
* that we want to apply before and after elements is a HTML tag (i.e. a
* div, p, or button tag), we can avoid this extra nesting by passing using
* the BeforeAfterWrapper in place of said tag like so:
*
* <p>
* <BeforeAfterWrapper> do this instead <BeforeAfterWrapper elementType='p'>
* [children of p] ------> [children of p]
* </BeforeAfterWrapper> </BeforeAfterWrapper>
* </p>
*
* BeforeAfterWrapper features spread functionality. This means that we can
* pass HTML tag properties directly into the BeforeAfterWrapper tag.
*
* When using BeforeAfterWrapper, ensure that the parent of the beforeElement
* and afterElement have a defined style position.
*/
const styles = {
box: {
boxSizing: 'border-box',
},
};
class BeforeAfterWrapper extends React.Component {
static propTypes = {
afterElementType: React.PropTypes.string,
afterStyle: React.PropTypes.object,
beforeElementType: React.PropTypes.string,
beforeStyle: React.PropTypes.object,
children: React.PropTypes.node,
elementType: React.PropTypes.string,
/**
* Override the inline-styles of the root element.
*/
style: React.PropTypes.object,
};
static defaultProps = {
beforeElementType: 'div',
afterElementType: 'div',
elementType: 'div',
};
static contextTypes = {
muiTheme: React.PropTypes.object.isRequired,
};
render() {
const {
beforeStyle,
afterStyle,
beforeElementType, // eslint-disable-line no-unused-vars
afterElementType, // eslint-disable-line no-unused-vars
elementType, // eslint-disable-line no-unused-vars
...other,
} = this.props;
const {prepareStyles} = this.context.muiTheme;
let beforeElement;
let afterElement;
if (beforeStyle) {
beforeElement = React.createElement(this.props.beforeElementType,
{
style: prepareStyles(Object.assign({}, styles.box, beforeStyle)),
key: '::before',
});
}
if (afterStyle) {
afterElement = React.createElement(this.props.afterElementType,
{
style: prepareStyles(Object.assign({}, styles.box, afterStyle)),
key: '::after',
});
}
const children = [beforeElement, this.props.children, afterElement];
const props = other;
props.style = prepareStyles(Object.assign({}, this.props.style));
return React.createElement(this.props.elementType, props, children);
}
}
export default BeforeAfterWrapper;
|
app/src/components/WaitingDisplay.js
|
joshlevy89/pinclone
|
import React, { Component } from 'react';
require('../../styles/WaitingDisplay.scss')
class WaitingDisplay extends Component {
render() {
const { request_status } = this.props
return (
<div>
{request_status==='REQUESTING_RESULTS' ?
<div className="loading"></div>:null
}
</div>
);
}
}
export default WaitingDisplay
|
blueprints/smart/files/__root__/containers/__name__/__name__.js
|
mjasinski5/dashboardWookiees
|
import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
type Props = {
}
export class <%= pascalEntityName %> extends React.Component {
props: Props;
render () {
return (
<div></div>
)
}
}
const mapStateToProps = (state) => {
return {}
}
const mapDispatchToProps = (dispatch) => {
return {}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(<%= pascalEntityName %>)
|
Mr.Mining/MikeTheMiner/dist/Santas_helpers/Sia_wallet/resources/app/plugins/Terminal/js/components/commandline.js
|
patel344/Mr.Miner
|
import React from 'react'
import CommandHistoryList from '../containers/commandhistorylist.js'
import CommandInput from '../containers/commandinput.js'
import WalletPasswordPrompt from '../containers/walletpasswordprompt.js'
import WalletSeedPrompt from '../containers/seedprompt.js'
const CommandLine = ({showCommandOverview, actions}) => {
const toggleCommandOverview = () => {
if (showCommandOverview) {
actions.hideCommandOverview()
} else {
actions.showCommandOverview()
}
}
return (
<div className={'command-history ' + (showCommandOverview ? 'overview' : '')}>
<CommandHistoryList />
<footer className="commandFooter">
<div className={'command-overview ' + (showCommandOverview ? 'expanded' : '')} >
<div className="help-button" onClick={toggleCommandOverview}>?</div>
<div className="command-overview-inner">
<h3>Available Commands:</h3>
<p>
consensus Print the current state of consensus<br />
gateway Perform gateway actions<br />
host Perform host actions<br />
hostdb View or modify the host database<br />
miner Perform miner actions<br />
renter Perform renter actions<br />
stop Stop the Sia daemon<br />
update Update Sia<br />
version Print version information<br />
wallet Perform wallet actions<br /><br />
Use '[command] --help' for more information about a command.<br />
</p>
</div>
</div>
<CommandInput />
</footer>
<WalletPasswordPrompt />
<WalletSeedPrompt />
</div>
)
}
export default CommandLine
|
static/src/containers/DevTools/DevTools.dev.js
|
detailyang/cas-server
|
/**
* @Author: BingWu Yang <detailyang>
* @Date: 2016-04-20T23:43:35+08:00
* @Email: detailyang@gmail.com
* @Last modified by: detailyang
* @Last modified time: 2016-04-21T00:34:39+08:00
* @License: The MIT License (MIT)
*/
import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q" defaultIsVisible={false}>
<LogMonitor theme="tomorrow" />
</DockMonitor>
);
|
techCurriculum/ui/solutions/5.3/src/components/User.js
|
jennybkim/engineeringessentials
|
/**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
import React from 'react';
function User(props) {
return (
<div className='user'>
<i className='fa fa-user-o'/>
<p>{props.name}</p>
</div>
);
}
export default User;
|
packages/react-server-examples/bike-share/components/network-card.js
|
szhou8813/react-server
|
import React from 'react';
import {logging, Link} from 'react-server';
const logger = logging.getLogger(__LOGGER__);
const NetworkCard = ({id, name, location, company}) => {
logger.info(`rendering card for network ${name}`);
return (
<div><Link path={`/network?network=${id}`}>{name}</Link> in {location.city}, {location.country}, run by {company}</div>
);
};
NetworkCard.propTypes = {
company: React.PropTypes.any,
href: React.PropTypes.string,
id: React.PropTypes.string,
location: React.PropTypes.shape({
city: React.PropTypes.string,
country: React.PropTypes.string,
latitude: React.PropTypes.number,
longitude: React.PropTypes.number,
}),
name: React.PropTypes.string,
stations: React.PropTypes.array,
};
NetworkCard.displayName = 'NetworkCard';
export default NetworkCard;
|
webapp/src/containers/search/filterSelector/filterSelector.js
|
nathandunn/agr
|
import React, { Component } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import style from './style.css';
import SingleFilterSelector from './singleFilterSelector';
import { getQueryParamWithValueChanged } from '../../../lib/searchHelpers';
import CategoryLabel from '../categoryLabel';
import {
selectActiveCategory,
selectAggregations,
selectIsPending,
selectQueryParams,
} from '../../../selectors/searchSelectors';
class FilterSelectorComponent extends Component {
renderFilters() {
let aggs = this.props.aggregations;
if (aggs.length === 0) {
return <p>No filters available.</p>;
}
// if on cat selector and pending, render nothing
if (this.props.activeCategory === 'none' && this.props.isPending) {
return null;
}
return aggs.map( d => {
return <div key={`filter${d.name}`}><SingleFilterSelector {...d} queryParams={this.props.queryParams} /></div>;
});
}
renderCatSelector() {
let cat = this.props.activeCategory;
if (cat === 'none') {
return null;
}
let newQp = getQueryParamWithValueChanged('category', [], this.props.queryParams, true);
let newHref = { pathname: '/search', query: newQp };
return (
<div>
<p><CategoryLabel category={this.props.activeCategory} /></p>
<p>
<Link to={newHref}><i className='fa fa-chevron-left' /> Show all Categories</Link>
</p>
</div>
);
}
render() {
return (
<div className={style.aggContainer} >
{this.renderCatSelector()}
{this.renderFilters()}
</div>
);
}
}
FilterSelectorComponent.propTypes = {
activeCategory: React.PropTypes.string,
aggregations: React.PropTypes.array,
isPending: React.PropTypes.bool,
queryParams: React.PropTypes.object
};
function mapStateToProps(state) {
return {
activeCategory: selectActiveCategory(state),
aggregations: selectAggregations(state),
isPending: selectIsPending(state),
queryParams: selectQueryParams(state)
};
}
export { FilterSelectorComponent as FilterSelectorComponent };
export default connect(mapStateToProps)(FilterSelectorComponent);
|
client/component/schema/filter/index.js
|
johngodley/search-regex
|
/**
* External dependencies
*/
import React from 'react';
import { translate as __ } from 'i18n-calypso';
import classnames from 'classnames';
/**
* Internal dependencies
*/
import apiFetch from 'wp-plugin-lib/api-fetch';
import { Select, Button, Badge } from 'wp-plugin-components';
import SearchRegexApi from 'lib/api-request';
import FilterType from './types';
import './style.scss';
const MAX_OR_FILTERS = 10;
function getOptionsForColumn( columns ) {
return columns.map( ( column ) => ( { label: column.title, value: column.column } ) );
}
function FilterItem( { item, columns, disabled, onChange, schema, fetchData, onRemove } ) {
if ( ! schema ) {
return null;
}
return (
<div className={ classnames( 'searchregex-filter__item', `searchregex-filter__type__${ schema.type }` ) }>
<Select
name="filter_type"
items={ getOptionsForColumn( columns ) }
value={ item.column }
disabled={ disabled }
onChange={ ( ev ) => onChange( { column: ev.target.value } ) }
/>
<span
onClick={ disabled ? () => {} : onRemove }
className={ classnames( 'dashicons', 'dashicons-trash', disabled && 'dashicons__disabled' ) }
/>
<FilterType
schema={ schema }
item={ item }
disabled={ disabled }
fetchData={ fetchData }
onChange={ ( values ) => onChange( { ...item, ...values } ) }
/>
</div>
);
}
function Filter( props ) {
const { schema, items, disabled, onChange, onRemove, source } = props;
if ( ! schema ) {
return null;
}
function addFilter() {
onChange( items.concat( [ { column: items[ items.length - 1 ].column } ] ) );
}
function removeItem( pos ) {
if ( items.length === 1 ) {
onRemove();
} else {
onChange( [ ...items.slice( 0, pos ), ...items.slice( pos + 1 ) ] );
}
}
function fetchData( column, value ) {
return apiFetch( SearchRegexApi.source.complete( source, column, value ) );
}
return (
<div className="searchregex-filter__column">
<div className="searchregex-filter__name">
<span>{ schema.name }</span>
<span
onClick={ disabled ? () => {} : onRemove }
className={ classnames( 'dashicons', 'dashicons-trash', disabled && 'dashicons__disabled' ) }
/>
</div>
<div
className={ classnames(
'searchregex-filter__content',
items.length > 1 && 'searchregex-filter__content__multiple'
) }
>
{ items.map( ( item, columnPosition ) => (
<React.Fragment key={ `${ schema.name }-${ item.column }-${ columnPosition }` }>
<FilterItem
item={ item }
schema={ schema.columns.find( ( finding ) => item.column === finding.column ) }
columns={ schema.columns }
disabled={ disabled }
fetchData={ ( value ) => fetchData( item.column, value ) }
onChange={ ( filter ) =>
onChange( [
...items.slice( 0, columnPosition ),
filter,
...items.slice( columnPosition + 1 ),
] )
}
onRemove={ () => removeItem( columnPosition ) }
/>
{ columnPosition !== items.length - 1 && (
<Badge disabled={ disabled }>{ __( 'OR' ) }</Badge>
) }
</React.Fragment>
) ) }
</div>
<div className="searchregex-filter__action">
<Button disabled={ disabled || items.length === MAX_OR_FILTERS } onClick={ addFilter }>
{ __( 'Add sub-filter (OR)' ) }
</Button>
</div>
</div>
);
}
export default Filter;
|
src/components/WrapperLayers.js
|
GGGGino/react-event-layer
|
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { Motion } from 'react-motion';
import { getAnimation } from '../helpers/animations';
class WrapperLayers extends React.Component {
constructor(props) {
super(props);
this.state = {
left: 0,
y: 0,
activeLayer: 0
};
this.layers = {};
this.onMouseLeave = this.onMouseLeave.bind(this);
}
componentDidMount() {
for (let key in this.layers) {
const domEl = ReactDOM.findDOMNode(this.layers[key]);
const domQueried = this.layers[key].props.selector ? domEl.querySelector(this.layers[key].props.selector) : domEl;
domQueried.addEventListener(this.layers[key].props.event, this.eventOnLayer.bind(this, key, this.layers[key]));
}
}
render() {
const childrenOrdered = React.Children.toArray(this.props.children).sort((a, b) => a.props.z - b.props.z);
const wrapperStyle = this.getWrapperStyle();
return (
<div
style={wrapperStyle}
onMouseLeave={this.onMouseLeave}
className="reactEventLayer"
>
{childrenOrdered.map((item, i) => {
const childProps = {
ref: (input) => { this.layers[`layer${i}`] = input },
...item.props
};
const clonedChild = React.cloneElement(
item,
childProps
);
const animRequested = item.props.animation;
const { defaultStyle, activeStyle, nonActiveStyle, anim } = getAnimation(animRequested);
const customStyle = this.controlEnterMode(i) ? activeStyle : nonActiveStyle;
return (
<Motion key={item.props.z} defaultStyle={defaultStyle} style={customStyle}>
{(currStyle) => {
// children is a callback which should accept the current value of style
const styleLayer = i === 0 ? {
position: 'relative'
} : anim(currStyle);
return (<div className="wrapperLayer" style={styleLayer}>
{clonedChild}
</div>);
}}
</Motion>
)
})}
</div>
);
}
/**
* Number of the layer
*
* @returns {Number}
*/
countLayer() {
return Object.keys(this.layers).length;
}
/**
* Event. Event attached to the eventListener and change the state.
*
* @param ref
*/
eventOnLayer(ref) {
const intLayer = parseInt(ref.replace('layer', '')),
nextLayer = intLayer + 1;
if( this.countLayer() > nextLayer )
this.setState({activeLayer: nextLayer});
}
/**
*
*
* @param row
* @returns {boolean}
*/
controlEnterMode(row) {
if (this.props.enterMode === 'replace') {
return row === 0 || row === this.state.activeLayer;
}
if (this.props.enterMode === 'push') {
return row === 0 || row <= this.state.activeLayer;
}
}
/**
* Do merge between the object passed and the obligatory styles
*
* @returns {{width: number}}
*/
getWrapperStyle() {
return {
position: 'relative',
overflow: 'hidden',
display: 'inline-block',
...this.props.style
};
}
/**
* Event.
* When i leave the wrapper, it return to the layer 0
*/
onMouseLeave() {
this.setState({ activeLayer: 0 });
}
}
WrapperLayers.defaultProps = {
enterMode: 'replace'
};
WrapperLayers.propTypes = {
/**
* The style of the wrapper
*/
style: PropTypes.object,
/**
* string push|replace Tells if the next layer will go on the prev layer or it will replace the layer
*/
enterMode: PropTypes.oneOf(['push', 'replace'])
};
export default WrapperLayers;
|
src/app/components/item/ItemView.js
|
mazahell/eve-react-app
|
import React from 'react';
import Helper from '../../helpers';
import './ItemView.css';
const ItemView = props => {
const { typeID, name, quantity, price } = props;
const sum = Helper.price(price * quantity);
return (
<li>
<div className="item-view-cont">
<div className="img-box">
<img alt={name} src={`https://image.eveonline.com/Type/${typeID}_32.png`} />
</div>
<div className="item-descr">
<div className="item-row-first">
<div className="item-name">
{name}
</div>
<div className="item-amount">
{'x'} {Helper.qty(quantity)}
</div>
<div className="item-price txt-lime">
{Helper.price(price)}
</div>
</div>
<span className="txt-yellow b">{sum} ISK</span>
</div>
</div>
</li>
);
};
export default ItemView;
|
src/shared/components/socialMedia/socialMedia.js
|
NestorSegura/operationcode_frontend
|
import React from 'react';
import fbImage from 'images/icons/Facebook-Icon.svg';
import ghImage from 'images/icons/GitHub-Icon.svg';
import twtImage from 'images/icons/Twitter-Icon.svg';
import liImage from 'images/icons/LinkedIn-Icon.svg';
import SocialMediaContainer from './socialMediaContainer/socialMediaContainer';
import SocialMediaItem from './socialMediaItem/socialMediaItem';
const SocialMedia = () => (
<SocialMediaContainer>
<SocialMediaItem
smImage={fbImage}
smText="Facebook"
link="https://facebook.com/operationcode.org"
/>
<SocialMediaItem
smImage={ghImage}
smText="Github"
link="https://github.com/operationcode"
/>
<SocialMediaItem
smImage={twtImage}
smText="Twitter"
link="https://twitter.com/operation_code"
/>
<SocialMediaItem
smImage={liImage}
smText="LinkedIn"
link="https://www.linkedin.com/groups/13400924"
/>
</SocialMediaContainer>
);
export default SocialMedia;
|
app/scripts/views/UserEffectivePermissionsModal.react.js
|
darbio/auth0-roles-permissions-dashboard-sample
|
import _ from 'lodash';
import React from 'react';
import Router from 'react-router';
import BS from 'react-bootstrap';
import BaseView from '../components/BaseView.react';
import UserActions from '../actions/UserActions';
import ApplicationActions from '../actions/ApplicationActions';
import ApplicationStore from '../stores/ApplicationStore';
import UserEffectivePermissionsStore from '../stores/UserEffectivePermissionsStore';
export default class UserEffectivePermissionsModal extends BaseView {
constructor(props) {
super(props);
// Load initial state.
this.stores = [ApplicationStore, UserEffectivePermissionsStore];
this.state = {
loading: true,
title: 'Effective Roles and Permissions for ' + (this.props.user.name)
};
// Load the user's permissions.
ApplicationActions.load();
UserActions.loadEffectivePermissions(this.props.user.user_id);
}
getStateFromStores() {
return {
loading: UserEffectivePermissionsStore.loading,
roles: UserEffectivePermissionsStore.effective_roles,
permissions: UserEffectivePermissionsStore.effective_permissions
};
}
render() {
if (this.state.loading) {
return (
<BS.Modal {...this.props} bsStyle='primary' backdrop={true} animation={true} title={this.state.title}>
<div className="modal-body">
Loading...
</div>
<div className="modal-footer">
<BS.Button onClick={this.props.onRequestHide}>Close</BS.Button>
</div>
</BS.Modal>
);
}
return (
<BS.Modal {...this.props} bsStyle='primary' backdrop={true} animation={true} title={this.state.title}>
<div className="modal-body">
<h5>Roles</h5>
<table className="table table-striped table-responsive">
<thead>
<tr>
<td>Name</td>
<td>Description</td>
</tr>
</thead>
<tbody>
{this.state.roles.map((r, i) => {
return (
<tr key={r.id}>
<td>{r.name}</td>
<td>{r.description}</td>
</tr>
);
})}
</tbody>
</table>
<h5>Permissions</h5>
<table className="table table-striped table-responsive">
<thead>
<tr>
<td>Application</td>
<td>Permission</td>
<td>Description</td>
</tr>
</thead>
<tbody>
{this.state.permissions.map((permission, i) => {
return (
<tr key={permission.id}>
<td>{ApplicationStore.getName(permission.application)}</td>
<td>{permission.name}</td>
<td>{permission.description}</td>
</tr>
);
})}
</tbody>
</table>
</div>
<div className="modal-footer">
<BS.Button onClick={this.props.onRequestHide}>Close</BS.Button>
</div>
</BS.Modal>
);
}
}
|
app/components/Geschaeft/KontakteExternItems.js
|
barbalex/kapla3
|
import React from 'react'
import PropTypes from 'prop-types'
import { Glyphicon } from 'react-bootstrap'
import _ from 'lodash'
import Linkify from 'react-linkify'
import styled from 'styled-components'
import { observer, inject } from 'mobx-react'
import compose from 'recompose/compose'
const verantwortlichData = (gKE, externeOptions) => {
function addValueToInfo(info, value) {
if (!value) return info
if (info) return `${info}, ${value}`
return value
}
const data = externeOptions.find(o => o.id === gKE.idKontakt)
if (!data) return ''
let info = ''
const name = `${data.name || '(kein Name)'} ${data.vorname || '(kein Vorname)'}`
info = addValueToInfo(info, name)
info = addValueToInfo(info, data.firma)
info = addValueToInfo(info, data.eMail)
info = addValueToInfo(info, data.telefon)
return <Linkify>{info}</Linkify>
}
const titleText = (idKontakt, externeOptions) => {
const data = externeOptions.find(o => o.id === idKontakt)
if (!data) return 'Kontakt entfernen'
return `${data.name} ${data.vorname} entfernen`
}
const Container = styled.div`
grid-column: 1 / span 2;
display: grid;
grid-template-columns: 100%;
grid-gap: 0;
`
// eslint-disable-next-line no-unused-vars
const Row = styled.div`
grid-column: 1 / span 1;
display: grid;
grid-template-columns: ${props => (props['data-ispdf'] ? 'calc(100% - 10px)' : 'calc(100% - 20px) 20px')};
grid-gap: 0;
padding: 3px;
margin-right: ${props => (props['data-ispdf'] ? '9px' : 'inherit')};
align-items: center;
min-height: ${props => (props['data-ispdf'] ? 0 : '35px')};
font-size: ${props => (props['data-ispdf'] ? '10px' : 'inherit')};
border-bottom: thin solid #cecbcb;
&:first-of-type {
border-top: thin solid #cecbcb;
}
&:hover {
background-color: rgba(208, 255, 202, 0.5);
}
`
// eslint-disable-next-line no-unused-vars
const Field = styled.div`
grid-column: 1 / span 1;
/**
* prevent pushing of following kontakt
* when text breaks to next line
*/
&p {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
padding: ${props => (props['data-ispdf'] ? 0 : '7px')};
}
`
// eslint-disable-next-line no-unused-vars
const GlyphiconDiv = styled.div`
grid-column: 2 / span 1;
margin-top: -2px;
display: ${props => (props['data-ispdf'] ? 'none' : 'inherit')};
`
const StyledGlyphicon = styled(Glyphicon)`
color: red;
font-size: 18px;
cursor: pointer;
`
const enhance = compose(inject('store'), observer)
const GeschaefteKontakteExtern = ({ store }) => {
const { geschaeftKontaktExternRemove } = store
const { externeOptions, activeId } = store.geschaefte
const path = store.history.location.pathname
const { geschaefteKontakteExtern } = store.geschaefteKontakteExtern
const isPdf = path === '/geschaeftPdf'
// filter for this geschaeft
const gkIFiltered = geschaefteKontakteExtern.filter(g => g.idGeschaeft === activeId)
const gKISorted = _.sortBy(gkIFiltered, g => {
const intOption = externeOptions.find(o => o.id === g.idKontakt)
return `${intOption.name} ${intOption.vorname}`.toLowerCase()
})
return (
<Container>
{gKISorted.map(gKE => (
<Row key={`${gKE.idGeschaeft}${gKE.idKontakt}`} data-ispdf={isPdf}>
<Field data-ispdf={isPdf}>{verantwortlichData(gKE, externeOptions)}</Field>
<GlyphiconDiv data-ispdf={isPdf}>
<StyledGlyphicon
glyph="remove-circle"
onClick={() => geschaeftKontaktExternRemove(activeId, gKE.idKontakt)}
title={titleText(gKE.idKontakt, externeOptions)}
/>
</GlyphiconDiv>
</Row>
))}
</Container>
)
}
GeschaefteKontakteExtern.displayName = 'GeschaefteKontakteExtern'
GeschaefteKontakteExtern.propTypes = {
store: PropTypes.object.isRequired,
}
export default enhance(GeschaefteKontakteExtern)
|
ui/src/main/js/components/__tests__/StateMachine-test.js
|
apache/aurora
|
import React from 'react';
import { shallow } from 'enzyme';
import StateMachine, { StateMachineToggle } from '../StateMachine';
describe('StateMachineToggle', () => {
it('Should toggle the display state when clicked', () => {
const states = [{
state: 'One',
timestamp: 0
}, {
state: 'Two',
timestamp: 0
}];
const el = shallow(<StateMachineToggle states={states} toggleState={states[1]} />);
expect(el.state().expanded).toBe(false);
expect(el.contains(<StateMachine className={undefined} states={[states[1]]} />)).toBe(true);
el.simulate('click');
expect(el.state().expanded).toBe(true);
expect(el.contains(<StateMachine className={undefined} states={states} />)).toBe(true);
});
});
|
packages/react-ui-components/src/TextArea/index.story.js
|
neos/neos-ui
|
import React from 'react';
import {storiesOf, action} from '@storybook/react';
import {withKnobs, boolean} from '@storybook/addon-knobs';
import {StoryWrapper} from './../_lib/storyUtils';
import TextArea from '.';
storiesOf('TextArea', module)
.addDecorator(withKnobs)
.addWithInfo(
'default',
() => {
const isValid = boolean('Is valid?', true);
return (
<StoryWrapper>
<TextArea
validationErrors={isValid ? null : ['This input is invalid']}
placeholder={isValid ? 'Valid input' : 'Invalid input'}
onChange={action('onChange')}
onFocus={action('onFocus')}
onBlur={action('onBlur')}
highlight={boolean('Highlight', false)}
/>
</StoryWrapper>
);
},
{inline: true}
);
|
client/src/components/topicselector.js
|
HenrikGr/redux-book
|
/*!
* Description: TopicSelector component
*
* The component renders an input field to enter search terms
*
* The app component hierarchy looks like this:
*
* App
* - ControlsContainer
* - TopicSelectorContainer
* - TopicSelector (*)
* - DisplayModeContainer
* - DisplayMode
* - HistoryContainer
* - History
* - BooksContainer
* - Book
* - Book
* - ...
* - StateViewerContainer
*
* The component gets props from the TopicSelectorContainer component;
* - topic, string containing the current value of the input field.
* - setTopic, action creator function to bind value entered to the Redux store.
* - fetchTopic, action creator to be invoked when performing a nre search.
*
*
* Author: Henrik Grönvall
* File:
* Version: 0.0.1
* Created on 2016-10-16
*/
import React from 'react';
/**
* TopicSelector Component.
*/
export default class TopicSelector extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
}
// Put the cursor at the end of the input field
componentDidMount() {
function putCursorAtEnd(input) {
const value = input.value;
input.value = '';
input.value = value;
}
const input = this.refs.input;
input.focus();
putCursorAtEnd(input);
}
// Event handler to bind the value to topic state.
handleChange(event) {
this.props.setTopic(event.target.value);
}
// Event handler to dispatch a fetch if Enter key is pressed
handleKeyPress(event) {
if (event.key === 'Enter') {
this.props.fetchTopic(event.target.value);
}
}
// Render component
render() {
const styles = {
topic: {
marginRight: '10px',
fontFamily: 'tahoma',
fontSize: '18px',
},
input: {
fontFamily: 'tahoma',
fontSize: '16px',
marginRight: '10px',
},
};
return (
<span>
<span style={styles.topic}>
Topic
</span>
<input
type="text"
ref="input"
style={styles.input}
value={this.props.topic}
onChange={this.handleChange}
onKeyPress={this.handleKeyPress}
/>
</span>
);
}
}
/**
* TopicSelector props
* @type {{topic: *, setTopic: *, fetchTopic: *}}
*/
TopicSelector.propTypes = {
topic: React.PropTypes.string.isRequired,
setTopic: React.PropTypes.func.isRequired,
fetchTopic: React.PropTypes.func.isRequired,
};
|
src/svg-icons/editor/border-left.js
|
frnk94/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorBorderLeft = (props) => (
<SvgIcon {...props}>
<path d="M11 21h2v-2h-2v2zm0-4h2v-2h-2v2zm0-12h2V3h-2v2zm0 4h2V7h-2v2zm0 4h2v-2h-2v2zm-4 8h2v-2H7v2zM7 5h2V3H7v2zm0 8h2v-2H7v2zm-4 8h2V3H3v18zM19 9h2V7h-2v2zm-4 12h2v-2h-2v2zm4-4h2v-2h-2v2zm0-14v2h2V3h-2zm0 10h2v-2h-2v2zm0 8h2v-2h-2v2zm-4-8h2v-2h-2v2zm0-8h2V3h-2v2z"/>
</SvgIcon>
);
EditorBorderLeft = pure(EditorBorderLeft);
EditorBorderLeft.displayName = 'EditorBorderLeft';
EditorBorderLeft.muiName = 'SvgIcon';
export default EditorBorderLeft;
|
tests/site6/src/blocks/feedback.js
|
dominikwilkowski/cuttlebelle
|
import PropTypes from 'prop-types';
import React from 'react';
/**
* The Feedback component to be used after all content blocks
*/
const Feedback = ( page ) => {
const HeadingTag = `h${ page.level }`;
return (
<div className="uikit-body uikit-grid feedback">
<div className="container">
<div className="row">
<div className="col-sm-12">
<HeadingTag className="feedback__title display-3">{ page.title }</HeadingTag>
<div className="textwrapper">
<p className="feedback__caption1">{ page.caption1 }</p>
<p className="feedback__button">
<a href="https://www.surveymonkey.com/r/XFWJ5TC" className="uikit-btn">
Give feedback
</a>
</p>
<span>{ page._body }</span>
</div>
</div>
</div>
</div>
</div>
);
};
Feedback.propTypes = {
/**
* caption: This is the first release of Gov.au Service Manual. We'd love to know what's missing or could be done better
*/
caption: PropTypes.string,
/**
* buttonUrl: /feedback
*/
buttonUrl: PropTypes.string.isRequired,
/**
* buttonText: Send us feedback
*/
buttonText: PropTypes.string.isRequired,
};
Feedback.defaultProps = {};
export default Feedback;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.