path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
src/library/Menu/__tests__/MenuGroup.spec.js
|
mineral-ui/mineral-ui
|
/* @flow */
import React from 'react';
import { shallow } from 'enzyme';
import MenuGroup from '../MenuGroup';
import examples from '../../../website/app/demos/Menu/MenuGroup/examples';
import testDemoExamples from '../../../../utils/testDemoExamples';
function shallowMenuGroup(props = {}) {
const menuGroupProps = {
...props
};
return shallow(<MenuGroup {...menuGroupProps} />);
}
describe('MenuGroup', () => {
testDemoExamples(examples);
describe('renders', () => {
it('root', () => {
const menuGroup = shallowMenuGroup();
expect(menuGroup.exists()).toEqual(true);
});
});
});
|
src/components/status.js
|
openregister/specification
|
import React from 'react';
import PropTypes from 'prop-types';
import { css } from 'emotion';
const wipStyle = css`
background-color: tomato;
color: ivory;
text-transform: uppercase;
line-height: 1.1;
font-size: 16px;
vertical-align: middle;
padding: 0 2px;
`;
const expStyle = css`
background-color: deepskyblue;
color: ivory;
text-transform: uppercase;
line-height: 1.1;
font-size: 16px;
vertical-align: middle;
padding: 0 2px;
`;
const Tag = ({style, title}) => {
return <small className={style}>{title}</small>;
};
Tag.propTypes = {
style: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
};
const Status = ({label}) => {
switch (label) {
case 'wip':
return <Tag style={wipStyle} title="Work in progress" />;
case 'exp':
return <Tag style={expStyle} title="Experimental" />;
default:
return null;
}
};
Status.propTypes = {
label: PropTypes.string,
};
export default Status;
|
app/config/routes.js
|
natac13/london-ontario-data
|
import React from 'react'
import { Route, IndexRoute } from 'react-router'
import App from '../containers/App'
import Search from '../components/Search/'
import RouteTimesWrapper from '../components/RouteTimesWrapper/'
export default (
<Route path='/' component={App}>
<IndexRoute component={Search} />
<Route path='/routeTimes/:routeNumber/:direction/:stopID' component={RouteTimesWrapper} />
</Route>
)
|
packages/icons/src/md/navigation/ChevronRight.js
|
suitejs/suitejs
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdChevronRight(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<polygon points="19.83 12 17 14.83 26.17 24 17 33.17 19.83 36 31.83 24" />
</IconBase>
);
}
export default MdChevronRight;
|
tools/public-components.js
|
pivotal-cf/react-bootstrap
|
import React from 'react';
import * as index from '../src/index';
let components = [];
Object.keys(index).forEach(function (item) {
if (index[item] instanceof React.Component.constructor) {
components.push(item);
}
});
export default components;
|
admin/client/components/ItemsTableRow.js
|
riyadhalnur/keystone
|
import React from 'react';
import classnames from 'classnames';
import Columns from '../columns';
import CurrentListStore from '../stores/CurrentListStore';
import ListControl from './ListControl';
import { DropTarget, DragSource } from 'react-dnd';
const ItemsRow = React.createClass({
propTypes: {
columns: React.PropTypes.array,
items: React.PropTypes.object,
list: React.PropTypes.object,
index: React.PropTypes.number,
id: React.PropTypes.any,
// Injected by React DnD:
isDragging: React.PropTypes.bool,
connectDragSource: React.PropTypes.func,
connectDropTarget: React.PropTypes.func,
connectDragPreview: React.PropTypes.func,
},
renderRow (item) {
let itemId = item.id;
let rowClassname = classnames({
'ItemList__row--dragging': this.props.isDragging,
'ItemList__row--selected': this.props.checkedItems[itemId],
'ItemList__row--manage': this.props.manageMode,
'ItemList__row--success': this.props.rowAlert.success === itemId,
'ItemList__row--failure': this.props.rowAlert.fail === itemId,
});
// item fields
var cells = this.props.columns.map((col, i) => {
var ColumnType = Columns[col.type] || Columns.__unrecognised__;
var linkTo = !i ? `${Keystone.adminPath}/${this.props.list.path}/${itemId}` : undefined;
return <ColumnType key={col.path} list={this.props.list} col={col} data={item} linkTo={linkTo} />;
});
// add sortable icon when applicable
if (this.props.list.sortable) {
cells.unshift(<ListControl key="_sort" type="sortable" dragSource={this.props.connectDragSource} />);
}
// add delete/check icon when applicable
if (!this.props.list.nodelete) {
cells.unshift(this.props.manageMode ? (
<ListControl key="_check" type="check" active={this.props.checkedItems[itemId]} />
) : (
<ListControl key="_delete" onClick={(e) => this.props.deleteTableItem(item, e)} type="delete" />
));
}
var addRow = (<tr key={'i' + item.id} onClick={this.props.manageMode ? (e) => this.props.checkTableItem(item, e) : null} className={rowClassname}>{cells}</tr>);
if(this.props.list.sortable) {
return (
// we could add a preview container/image
// this.props.connectDragPreview(this.props.connectDropTarget(addRow))
this.props.connectDropTarget(addRow)
);
} else {
return (addRow);
}
},
render () {
return this.renderRow(this.props.item);
},
});
module.exports = exports = ItemsRow;
// Expose Sortable
/**
* Implements drag source.
*/
const dragItem = {
beginDrag (props) {
let send = { ...props };
CurrentListStore.setDragBase(props.item, props.index);
return { ...send };
},
endDrag (props, monitor, component) {
if (!monitor.didDrop()) {
return CurrentListStore.resetItems(CurrentListStore.findClonedItemById(props.id).index);
}
const base = CurrentListStore.getDragBase();
const page = CurrentListStore.getCurrentPage();
const droppedOn = monitor.getDropResult();
// some drops provide the data for us in prevSortOrder
const prevSortOrder = droppedOn.prevSortOrder ? droppedOn.prevSortOrder : props.sortOrder;
// use a given newSortOrder prop or retrieve from the cloned items list
let newSortOrder = droppedOn.newSortOrder ? droppedOn.newSortOrder : CurrentListStore.findClonedItemByIndex(droppedOn.index).sortOrder;
// self
if (prevSortOrder === newSortOrder) {
if(base.page !== page) {
// we were dropped on ourself, but not on our original page
if(droppedOn.index === 0) {
// item is first in the list
// save to the sortOrder of the 2nd item - 1
newSortOrder = CurrentListStore.findClonedItemByIndex(1).sortOrder - 1;
droppedOn.goToPage = Number(page) - 1;
} else {
// item is last in the list
// save to the sortOrder of the 2nd to last item - 1
newSortOrder = CurrentListStore.findClonedItemByIndex(droppedOn.index - 1).sortOrder + 1;
droppedOn.goToPage = Number(page) + 1;
}
if (!newSortOrder || !droppedOn.goToPage) {
// something is wrong so reset
return CurrentListStore.resetItems(CurrentListStore.findClonedItemById(props.id).index);
}
} else {
return CurrentListStore.resetItems(CurrentListStore.findClonedItemById(props.id).index);
}
}
// dropped on a target
// droppedOn.goToPage is an optional page override for dropping items on a new page target
CurrentListStore.reorderItems(props.item, prevSortOrder, newSortOrder, Number(droppedOn.goToPage));
},
};
/**
* Implements drag target.
*/
const dropItem = {
drop (props, monitor, component) {
return { ...props };
},
hover (props, monitor, component) {
// reset row alerts
if (props.rowAlert.success || props.rowAlert.fail) {
CurrentListStore.rowAlert('reset');
}
const dragged = monitor.getItem().index;
const over = props.index;
// self
if (dragged === over) {
return;
}
CurrentListStore.moveItem(dragged, over, props);
monitor.getItem().index = over;
},
};
/**
* Specifies the props to inject into your component.
*/
function dragProps (connect, monitor) {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging(),
connectDragPreview: connect.dragPreview(),
};
}
function dropProps (connect) {
return {
connectDropTarget: connect.dropTarget(),
};
};
exports.Sortable = DragSource('item', dragItem, dragProps)(DropTarget('item', dropItem, dropProps)(ItemsRow));
|
src/svg-icons/editor/merge-type.js
|
ArcanisCz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorMergeType = (props) => (
<SvgIcon {...props}>
<path d="M17 20.41L18.41 19 15 15.59 13.59 17 17 20.41zM7.5 8H11v5.59L5.59 19 7 20.41l6-6V8h3.5L12 3.5 7.5 8z"/>
</SvgIcon>
);
EditorMergeType = pure(EditorMergeType);
EditorMergeType.displayName = 'EditorMergeType';
EditorMergeType.muiName = 'SvgIcon';
export default EditorMergeType;
|
docs/app/Examples/addons/Radio/Types/RadioExampleToggle.js
|
shengnian/shengnian-ui-react
|
import React from 'react'
import { Radio } from 'shengnian-ui-react'
const RadioExampleToggle = () => (
<Radio toggle />
)
export default RadioExampleToggle
|
src/scripts/views/HomeView.js
|
IronNation/NCI-trial-search
|
import Header from './header'
import React from 'react'
import ResultsList from './map'
class HomeView extends React.Component {
render() {
return (
<div className = 'homeView'>
<Header />
<Home />
</div>
)
}
}
class Home extends React.Component {
render() {
return (
<div className = 'home'>
<h1>Search for clinical drug trials near you!</h1>
</div>
)
}
}
export default HomeView
|
Tutorial/ReactVersion/src/index.js
|
tableau/extensions-api
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './Main';
ReactDOM.render(<App />, document.getElementById('root'));
|
src/components/Menubar.js
|
r-portas/robogals-brisbane-pwa
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
NavLink
} from 'react-router-dom';
import './Menubar.css';
class Menubar extends Component {
parseLink(link) {
if (link.object === 'page') {
return link.object_slug;
}
return link.object;
}
renderSubLinks(link) {
if(!link) {
return;
}
const subHeadings = link.map((subLink) => {
return (
<li>
<NavLink
className = "sub-heading"
to={`/${this.parseLink(subLink)}`}
dangerouslySetInnerHTML={{__html: subLink.title}}
/>
</li>
);
});
return subHeadings;
}
/**
* Renders all links from the props.links object
*/
renderAllLinks() {
return this.renderLinks(this.props.links, 0);
}
/**
* Renders a list of links
* Will recurse through children object
*
* @param {object} links A json object of links
*/
renderLinks(links) {
if (links == null) {
return (
<p>Server offline</p>
);
}
const linkObjects = links.map((link) => {
return (
<li className="tab">
<span>{link.title}</span>
<ul id= "dropdown" className="menudrop sub">
{this.renderSubLinks(link.children)}
</ul>
</li>
);
});
return linkObjects;
}
render() {
return (
<ul className="menutab">
{this.renderAllLinks()}
</ul>
)
}
}
export default Menubar;
|
packages/react-server-examples/bike-share/components/station-card.js
|
davidalber/react-server
|
import React from 'react';
import {logging} from 'react-server';
const logger = logging.getLogger(__LOGGER__);
const timeSinceTimestamp = s => {
const parsed = Date.parse(s);
const timeSince = (new Date()) - parsed;
const minutesSince = Math.floor(timeSince / 60000);
const secondsSince = Math.floor((timeSince / 1000) % 60);
return `${minutesSince} min, ${secondsSince} sec`;
};
const StationCard = ({station}) => {
logger.info(`rendering card for station ${JSON.stringify(station)}`);
return (
<div>{station.name} had {station.empty_slots} empty slots {timeSinceTimestamp(station.timestamp)} ago.</div>
);
};
StationCard.propTypes = {
station: React.PropTypes.shape({
empty_slots: React.PropTypes.number, // eslint-disable-line
extra: React.PropTypes.object,
free_bikes: React.PropTypes.number, // eslint-disable-line
id: React.PropTypes.string,
latitude: React.PropTypes.number,
longitude: React.PropTypes.number,
name: React.PropTypes.string,
timestamp: React.PropTypes.string,
}),
};
StationCard.displayName = 'StationCard';
export default StationCard;
|
app/javascript/mastodon/features/domain_blocks/index.js
|
salvadorpla/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { debounce } from 'lodash';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import DomainContainer from '../../containers/domain_container';
import { fetchDomainBlocks, expandDomainBlocks } from '../../actions/domain_blocks';
import ScrollableList from '../../components/scrollable_list';
const messages = defineMessages({
heading: { id: 'column.domain_blocks', defaultMessage: 'Hidden domains' },
unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unhide {domain}' },
});
const mapStateToProps = state => ({
domains: state.getIn(['domain_lists', 'blocks', 'items']),
hasMore: !!state.getIn(['domain_lists', 'blocks', 'next']),
});
export default @connect(mapStateToProps)
@injectIntl
class Blocks extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
hasMore: PropTypes.bool,
domains: ImmutablePropTypes.orderedSet,
intl: PropTypes.object.isRequired,
};
componentWillMount () {
this.props.dispatch(fetchDomainBlocks());
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandDomainBlocks());
}, 300, { leading: true });
render () {
const { intl, domains, shouldUpdateScroll, hasMore } = this.props;
if (!domains) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
const emptyMessage = <FormattedMessage id='empty_column.domain_blocks' defaultMessage='There are no hidden domains yet.' />;
return (
<Column icon='minus-circle' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<ScrollableList
scrollKey='domain_blocks'
onLoadMore={this.handleLoadMore}
hasMore={hasMore}
shouldUpdateScroll={shouldUpdateScroll}
emptyMessage={emptyMessage}
>
{domains.map(domain =>
<DomainContainer key={domain} domain={domain} />
)}
</ScrollableList>
</Column>
);
}
}
|
src/components/user/ChangePasswordSuccessMessage.js
|
mitmedialab/MediaCloud-Web-Tools
|
import PropTypes from 'prop-types';
import React from 'react';
import { Grid, Row, Col } from 'react-flexbox-grid/lib';
import { FormattedMessage, injectIntl } from 'react-intl';
const localMessages = {
title: { id: 'success.email', defaultMessage: 'Password Changed' },
intro: { id: 'success.emailInfo', defaultMessage: 'We changed your password. We emailed you just to confirm that you did this on purpose - don\'t be suprised.' },
};
const ChangePasswordSuccessMessage = () => (
<div className="change-password-success">
<Grid>
<Row>
<Col lg={12}>
<h1><FormattedMessage {...localMessages.title} /></h1>
<p><FormattedMessage {...localMessages.intro} /></p>
</Col>
</Row>
</Grid>
</div>
);
ChangePasswordSuccessMessage.propTypes = {
intl: PropTypes.object.isRequired,
};
export default injectIntl(ChangePasswordSuccessMessage);
|
demo/component/Legend.js
|
scostaqb/recharts
|
import React from 'react';
import { Surface, Legend } from 'recharts';
const data = [
{ value: 'Apple', color: '#ff7300' },
{ value: 'Samsung', color: '#bb7300' },
{ value: 'Huawei', color: '#887300' },
{ value: 'Sony', color: '#667300' },
];
const data2 = [
{ value: 'Apple', type: 'scatter', color: '#ff7300' },
{ value: 'Samsung', type: 'scatter', color: '#bb7300' },
{ value: 'Huawei', type: 'scatter', color: '#bb0067' },
{ value: 'Sony', type: 'scatter', color: '#167300' },
];
const data3 = [
{ value: 'Apple', type: 'line', color: '#ff7300' },
{ value: 'Samsung', type: 'line', color: '#bb7300' },
{ value: 'Huawei', type: 'line', color: '#bb7300' },
{ value: 'Sony', type: 'line', color: '#ff7812' },
];
export default React.createClass({
render () {
return (
<div>
<div style={{ position: 'relative', height: 200 }}>
<Legend width={500} height={30} payload={data} />
</div>
<div style={{ position: 'relative', height: 200 }}>
<Legend layout='vertical' width={200} height={100} payload={data2} />
</div>
<div style={{ position: 'relative', height: 200 }}>
<Legend width={200} height={30} payload={data3} />
</div>
</div>
);
}
});
|
tests/views/HomeView.spec.js
|
obfk/buildmaster
|
import React from 'react'
import TestUtils from 'react-addons-test-utils'
import { bindActionCreators } from 'redux'
import { HomeView } from 'views/HomeView/HomeView'
import { mount } from 'enzyme'
function shallowRender (component) {
const renderer = TestUtils.createRenderer()
renderer.render(component)
return renderer.getRenderOutput()
}
function renderWithProps (props = {}) {
return TestUtils.renderIntoDocument(<HomeView {...props} />)
}
function shallowRenderWithProps (props = {}) {
return shallowRender(<HomeView {...props} />)
}
describe('(View) Home', function () {
let _component, _rendered, _props, _spies
beforeEach(function () {
_spies = {}
_props = {
counter: 0,
...bindActionCreators({
doubleAsync: (_spies.doubleAsync = sinon.spy()),
increment: (_spies.increment = sinon.spy())
}, _spies.dispatch = sinon.spy())
}
_component = shallowRenderWithProps(_props)
_rendered = renderWithProps(_props)
})
it('Should render as a <div>.', function () {
expect(_component.type).to.equal('div')
})
it('Should include an <h1> with welcome text.', function () {
const h1 = TestUtils.findRenderedDOMComponentWithTag(_rendered, 'h1')
expect(h1).to.exist
expect(h1.textContent).to.match(/Welcome to the React Redux Starter Kit/)
})
it('Should render with an <h2> that includes Sample Counter text.', function () {
const h2 = TestUtils.findRenderedDOMComponentWithTag(_rendered, 'h2')
expect(h2).to.exist
expect(h2.textContent).to.match(/Sample Counter/)
})
it('Should render props.counter at the end of the sample counter <h2>.', function () {
const h2 = TestUtils.findRenderedDOMComponentWithTag(
renderWithProps({ ..._props, counter: 5 }), 'h2'
)
expect(h2).to.exist
expect(h2.textContent).to.match(/5$/)
})
it('Should render exactly two buttons.', function () {
const wrapper = mount(<HomeView />)
expect(wrapper).to.have.descendants('.btn')
})
describe('An increment button...', function () {
let _btn
beforeEach(() => {
_btn = TestUtils.scryRenderedDOMComponentsWithTag(_rendered, 'button')
.filter(a => /Increment/.test(a.textContent))[0]
})
it('should be rendered.', function () {
expect(_btn).to.exist
})
it('should dispatch an action when clicked.', function () {
_spies.dispatch.should.have.not.been.called
TestUtils.Simulate.click(_btn)
_spies.dispatch.should.have.been.called
})
})
describe('A Double (Async) button...', function () {
let _btn
beforeEach(() => {
_btn = TestUtils.scryRenderedDOMComponentsWithTag(_rendered, 'button')
.filter(a => /Double/.test(a.textContent))[0]
})
it('should be rendered.', function () {
expect(_btn).to.exist
})
it('should dispatch an action when clicked.', function () {
_spies.dispatch.should.have.not.been.called
TestUtils.Simulate.click(_btn)
_spies.dispatch.should.have.been.called
})
})
})
|
src/client/components/base/Share/Share.js
|
DBCDK/content-first
|
import React from 'react';
import facebook from './facebook.svg';
import './Share.css';
/**
Social media share button
- Currently only supporting facebook
* @param {String} href (!Required) The url to the page you want the user to share
* @param {String or Object} children The button text
* @param {bool} preventCash (true as default) Prevent facebook from cashing the shared post
* @param {String} title The button hover title
* @param {String} target (_blank as default) Share modal opens in new tab
* @returns {React.Component} The share button
* @example
<Share
title={'My hover title goes here'}
href={'https://laesekompas.dk/lister/4747595903-34532...'}
className="align-self-center"
>
Del
</Share>
**/
const Share = ({
href,
children,
className = '',
target = '_blank',
preventCash = true,
onClick = null,
title = null
}) => {
const url = 'https://www.facebook.com/sharer/sharer.php?display=page&u=';
const cash = preventCash ? `?${Date.now()}` : '';
return (
<a
href={`${url}${href}${cash}`}
title={title}
target={target}
onClick={onClick}
className={`Share petroleum ${className}`}
>
<img src={facebook} width="13" height="auto" alt="" />
<p className="Share__title">{children}</p>
</a>
);
};
export default Share;
|
src/components/OptimisticSlider/OptimisticSlider.js
|
bhj/karaoke-forever
|
import React from 'react'
import PropTypes from 'prop-types'
import Slider from 'rc-slider'
import { lockScrolling } from 'store/modules/ui'
// depends on styles/global/rc-slider
export default class OptimisticSlider extends React.Component {
static propTypes = {
className: PropTypes.string,
handle: PropTypes.func.isRequired, // custom handle render prop
min: PropTypes.number.isRequired,
max: PropTypes.number.isRequired,
onChange: PropTypes.func.isRequired,
step: PropTypes.number.isRequired,
value: PropTypes.number.isRequired,
}
state = {
val: this.props.value,
isDragging: false,
isStable: true,
}
timerId = null
componentDidUpdate (prevProps) {
if (!this.state.isStable && this.state.val === this.props.value) {
clearTimeout(this.timerId)
this.setState({ isStable: true })
}
}
shouldComponentUpdate (nextProps, nextState) {
if (!nextState.isDragging && !nextState.isStable && nextProps.value !== nextState.val) {
return false
}
return true
}
render () {
return (
<Slider
className={this.props.className}
handleRender={this.props.handle}
max={this.props.max}
min={this.props.min}
onAfterChange={this.handleAfterChange}
onBeforeChange={this.handleBeforeChange}
onChange={this.handleChange}
step={this.props.step}
value={this.state.isDragging ? this.state.val : this.props.value}
/>
)
}
handleChange = val => {
this.setState({ val }, () => {
this.props.onChange(val)
})
}
handleBeforeChange = () => {
lockScrolling(true)
clearTimeout(this.timerId)
this.setState({ isDragging: true })
}
handleAfterChange = val => {
lockScrolling(false)
this.setState({
isStable: val === this.props.value,
isDragging: false,
})
// revert to the prop after a time since there could be value changes from outside
if (val !== this.props.value) {
this.timerId = setTimeout(() => this.setState({ val: this.props.value }), 2000)
}
}
}
|
src/main/resources/static/bower_components/jqwidgets/jqwidgets-react/react_jqxlayout.js
|
dhawal9035/WebPLP
|
/*
jQWidgets v4.5.0 (2017-Jan)
Copyright (c) 2011-2017 jQWidgets.
License: http://jqwidgets.com/license/
*/
import React from 'react';
let jqxLayout = React.createClass ({
getInitialState: function () {
return { value: '' };
},
componentDidMount: function () {
let options = this.manageAttributes();
this.createComponent(options);
},
manageAttributes: function () {
let properties = ['contextMenu','height','layout','minGroupHeight','minGroupWidth','resizable','rtl','theme','width'];
let options = {};
for(let item in this.props) {
if(item === 'settings') {
for(let itemTwo in this.props[item]) {
options[itemTwo] = this.props[item][itemTwo];
}
} else {
if(properties.indexOf(item) !== -1) {
options[item] = this.props[item];
}
}
}
return options;
},
createComponent : function (options) {
if(!this.style) {
for (let style in this.props.style) {
$('#' +this.componentSelector).css(style, this.props.style[style]);
}
}
if(this.props.className !== undefined) {
let classes = this.props.className.split(' ');
for (let i = 0; i < classes.length; i++ ) {
$('#' +this.componentSelector).addClass(classes[i]);
}
}
if(!this.template) {
$('#' +this.componentSelector).html(this.props.template);
}
$('#' +this.componentSelector).jqxLayout(options);
},
generateID : function () {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
},
setOptions: function (options) {
$('#' +this.componentSelector).jqxLayout('setOptions', options);
},
getOptions: function () {
if(arguments.length === 0) {
throw Error('At least one argument expected in getOptions()!');
}
let resultToReturn = {};
for(let i = 0; i < arguments.length; i++) {
resultToReturn[arguments[i]] = $('#' +this.componentSelector).jqxLayout(arguments[i]);
}
return resultToReturn;
},
on: function (name,callbackFn) {
$('#' +this.componentSelector).on(name,callbackFn);
},
off: function (name) {
$('#' +this.componentSelector).off(name);
},
contextMenu: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxLayout("contextMenu", arg)
} else {
return $("#" +this.componentSelector).jqxLayout("contextMenu");
}
},
height: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxLayout("height", arg)
} else {
return $("#" +this.componentSelector).jqxLayout("height");
}
},
layout: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxLayout("layout", arg)
} else {
return $("#" +this.componentSelector).jqxLayout("layout");
}
},
minGroupHeight: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxLayout("minGroupHeight", arg)
} else {
return $("#" +this.componentSelector).jqxLayout("minGroupHeight");
}
},
minGroupWidth: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxLayout("minGroupWidth", arg)
} else {
return $("#" +this.componentSelector).jqxLayout("minGroupWidth");
}
},
resizable: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxLayout("resizable", arg)
} else {
return $("#" +this.componentSelector).jqxLayout("resizable");
}
},
rtl: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxLayout("rtl", arg)
} else {
return $("#" +this.componentSelector).jqxLayout("rtl");
}
},
theme: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxLayout("theme", arg)
} else {
return $("#" +this.componentSelector).jqxLayout("theme");
}
},
width: function (arg) {
if (arg !== undefined) {
$("#" +this.componentSelector).jqxLayout("width", arg)
} else {
return $("#" +this.componentSelector).jqxLayout("width");
}
},
destroy: function () {
$("#" +this.componentSelector).jqxLayout("destroy");
},
loadLayout: function (Layout) {
$("#" +this.componentSelector).jqxLayout("loadLayout", Layout);
},
refresh: function () {
$("#" +this.componentSelector).jqxLayout("refresh");
},
performRender: function () {
$("#" +this.componentSelector).jqxLayout("render");
},
saveLayout: function () {
return $("#" +this.componentSelector).jqxLayout("saveLayout");
},
render: function () {
let id = 'jqxLayout' + this.generateID() + this.generateID();
this.componentSelector = id; return (
<div id={id}>{this.value ? null : this.props.value}{this.props.children}</div>
)
}
});
module.exports = jqxLayout;
|
src/components/ImportEpwing.js
|
rsimmons/immersion-player
|
import React, { Component } from 'react';
import './ImportEpwing.css';
import SecondaryScreen from './SecondaryScreen.js';
import SystemBrowserLink from './SystemBrowserLink.js';
import Button from './Button.js';
import { importEpwing } from '../dictionary';
const { ipcRenderer } = window.require('electron'); // use window to avoid webpack
export default class ImportEpwing extends Component {
constructor(props) {
super(props);
this.state = {
epwingDirectory: undefined,
importing: false,
statusType: 'working',
statusText: '',
};
ipcRenderer.on('chose-directory', this.handleIpcChoseDirectory);
}
componentWillUnmount() {
ipcRenderer.removeListener('chose-directory', this.handleIpcChoseDirectory);
}
handleIpcChoseDirectory = (e, dir) => {
this.setState({epwingDirectory: dir});
};
handleClickChooseDirectory = (e) => {
e.preventDefault();
ipcRenderer.send('choose-directory', 'Choose EPWING folder');
};
handleImport = async () => {
this.setState({
importing: true,
statusType: 'working',
statusText: 'Importing ' + this.state.epwingDirectory + '... (may take a while)',
});
try {
await importEpwing(this.state.epwingDirectory);
await this.props.onReloadDictionaries(progressMsg => {
this.setState({
statusText: 'Reloading dictionaries: ' + progressMsg,
});
});
this.setState({
importing: false,
statusType: 'success',
statusText: 'EPWING imported successfully',
epwingDirectory: undefined,
});
} catch (e) {
console.log(e.message);
let statusText = 'Something went wrong';
if (e.message.includes('unrecognized dictionary format')) {
statusText = 'The folder you selected does not appear to be an EPWING dictionary';
} else if (e.message.includes('failed to find compatible extractor')) {
statusText = 'The EPWING you selected is not supported (see instructions above)';
}
this.setState({
importing: false,
statusType: 'error',
statusText: statusText,
});
}
};
render() {
const { onExit } = this.props;
return (
<SecondaryScreen title="Import EPWING Dictionary">
<div>If your EPWING dictionary is archived (e.g. a ZIP or RAR file), first unarchive it. Then choose its root folder, the one that contains the CATALOGS file. Note that Voracious relies on Yomichan Importer to import EPWINGS, and only certain specific dictionaries are supported (<SystemBrowserLink href="https://foosoft.net/projects/yomichan-import/">see the list here</SystemBrowserLink>).</div>
<br />
<div>Folder: {this.state.epwingDirectory || <span><i>None selected</i></span>} <button disabled={this.state.importing} onClick={this.handleClickChooseDirectory}>Choose Folder</button></div>
<br />
<div className={'ImportEpwing-status ImportEpwing-status-' + this.state.statusType}>{this.state.statusText} </div>
<br />
<div>
<Button disabled={!this.state.epwingDirectory || this.state.importing} onClick={this.handleImport}>Import Selected Folder</Button>
<Button disabled={this.state.importing} onClick={onExit}>Back</Button>
</div>
</SecondaryScreen>
);
}
}
|
src/components/meetings/questions/QuestionsList.js
|
VGraupera/1on1tracker
|
import React from 'react';
import { List, ListItem } from 'material-ui/List';
import Paper from 'material-ui/Paper';
import QuestionAnswer from 'material-ui/svg-icons/action/question-answer';
import PropTypes from 'prop-types';
/**
* @description PropTypes for QuestionsList
* @type {{questions}}
*/
const propTypes = {
questions: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string.isRequired,
question: PropTypes.string.isRequired,
})).isRequired,
};
/**
* @function QuestionsList
* @param {Array} questions
* @returns {XML}
*/
function QuestionsList({ questions }) {
return (
<Paper style={{ maxHeight: 200, overflow: 'auto', margin: 5 }}>
<List>
{questions.map((singleQuestion) => {
return (
<ListItem
key={singleQuestion.id}
leftIcon={<QuestionAnswer />}
primaryText={singleQuestion.question}
disabled={true}
/>
);
})}
</List>
</Paper>
);
}
QuestionsList.propTypes = propTypes;
export default QuestionsList;
|
redux-form/src/index.js
|
murielg/react-redux
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { Router, browserHistory } from 'react-router';
import promise from 'redux-promise';
import reducers from './reducers';
import routes from './routes';
const createStoreWithMiddleware = applyMiddleware(
promise
)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={browserHistory} routes={routes} />
</Provider>
, document.querySelector('.container'));
|
test/ButtonInputSpec.js
|
deerawan/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import ButtonInput from '../src/ButtonInput';
import {shouldWarn} from './helpers';
describe('ButtonInput', () => {
it('renders an input button element with type=button', function () {
const instance = ReactTestUtils.renderIntoDocument(
<ButtonInput value="button" bsStyle="danger" wrapperClassName="test" />
);
const node = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'input'));
assert.equal(node.getAttribute('type'), 'button');
assert.equal(node.getAttribute('class'), 'btn btn-danger');
});
it('supports type=reset and type=submit', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ButtonInput value="button" type="reset" />
);
let node = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'input'));
assert.equal(node.getAttribute('type'), 'reset');
instance = ReactTestUtils.renderIntoDocument(
<ButtonInput value="button" type="submit" />
);
node = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'input'));
assert.equal(node.getAttribute('type'), 'submit');
});
it('throws warning about unsupported type', function () {
ReactTestUtils.renderIntoDocument(
<ButtonInput value="button" type="password" />
);
shouldWarn('propType: Invalid');
});
it('must not throw warning when bsStyle=danger', function () {
ReactTestUtils.renderIntoDocument(
<ButtonInput value="button" bsStyle="danger" />
);
});
it('throws warning about wrong type for bsStyle=error', function () {
ReactTestUtils.renderIntoDocument(
<ButtonInput value="button" bsStyle="submit" />
);
shouldWarn('propType: Invalid');
});
it('throws a warning if given both children and a value property', function () {
const testData = { value: 5, children: 'button' };
const result = ButtonInput.propTypes.value(testData, 'value', 'ButtonInput');
result.should.be.instanceOf(Error);
result.message.should.have.string('value and children');
});
it('does not throw an error for strings and numbers', function () {
let testData = { children: 'EUREKA' };
let result = ButtonInput.propTypes.children(testData, 'children', 'ButtonInput');
assert.notInstanceOf(result, Error);
testData = { value: 4 };
result = ButtonInput.propTypes.value(testData, 'children', 'ButtonInput');
assert.notInstanceOf(result, Error);
});
it('allows elements as children', function () {
ReactTestUtils.renderIntoDocument(
<ButtonInput><span>blah</span></ButtonInput>
);
});
});
|
src/components/characterCard/CharacterCardEdit.js
|
Beardles/novelizr
|
import React from 'react'
import { Button, Header, Icon, Modal } from 'semantic-ui-react'
import CharacterCardForm from './CharacterCardForm'
const CharacterCardEdit = ({ open, characters, selectedCharacterCard, updateSelectedCharacterCard, handleCreateComplete, handleEditCancel }) => {
if (selectedCharacterCard === null) {
return null
}
return (
<Modal open={open} closeIcon={true} onClose={handleEditCancel}>
<Header icon='plus'
content='Create a New Characterization' />
<Modal.Content>
<CharacterCardForm
characters={characters}
characterCard={selectedCharacterCard}
updateSelectedCharacterCard={updateSelectedCharacterCard} />
</Modal.Content>
<Modal.Actions>
<Button color='green'
onClick={() => handleCreateComplete(selectedCharacterCard)}>
<Icon name='checkmark' /> Save Characterization
</Button>
<Button color='yellow'
onClick={handleEditCancel}>
<Icon name='close' /> Cancel
</Button>
</Modal.Actions>
</Modal>
)
}
export default CharacterCardEdit
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/RestAndDefault.js
|
dsopel94/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, { Component } from 'react';
import PropTypes from 'prop-types';
function load({ id, ...rest } = { id: 0, user: { id: 42, name: '42' } }) {
return [
{ id: id + 1, name: '1' },
{ id: id + 2, name: '2' },
{ id: id + 3, name: '3' },
rest.user,
];
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = load();
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-rest-and-default">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
__tests__/index.ios.js
|
m7775223/MyRNProject
|
import 'react-native';
import React from 'react';
import Index from '../index.ios.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
src/svg-icons/action/spellcheck.js
|
pancho111203/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSpellcheck = (props) => (
<SvgIcon {...props}>
<path d="M12.45 16h2.09L9.43 3H7.57L2.46 16h2.09l1.12-3h5.64l1.14 3zm-6.02-5L8.5 5.48 10.57 11H6.43zm15.16.59l-8.09 8.09L9.83 16l-1.41 1.41 5.09 5.09L23 13l-1.41-1.41z"/>
</SvgIcon>
);
ActionSpellcheck = pure(ActionSpellcheck);
ActionSpellcheck.displayName = 'ActionSpellcheck';
ActionSpellcheck.muiName = 'SvgIcon';
export default ActionSpellcheck;
|
blueprints/dumb/files/__test__/components/__name__.spec.js
|
nicolas-amabile/counter
|
import React from 'react'
import <%= pascalEntityName %> from 'components/<%= pascalEntityName %>/<%= pascalEntityName %>'
describe('(Component) <%= pascalEntityName %>', () => {
it('should exist', () => {
})
})
|
packages/material-ui-icons/src/AirlineSeatReclineNormal.js
|
cherniavskii/material-ui
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M7.59 5.41c-.78-.78-.78-2.05 0-2.83.78-.78 2.05-.78 2.83 0 .78.78.78 2.05 0 2.83-.79.79-2.05.79-2.83 0zM6 16V7H4v9c0 2.76 2.24 5 5 5h6v-2H9c-1.66 0-3-1.34-3-3zm14 4.07L14.93 15H11.5v-3.68c1.4 1.15 3.6 2.16 5.5 2.16v-2.16c-1.66.02-3.61-.87-4.67-2.04l-1.4-1.55c-.19-.21-.43-.38-.69-.5-.29-.14-.62-.23-.96-.23h-.03C8.01 7 7 8.01 7 9.25V15c0 1.66 1.34 3 3 3h5.07l3.5 3.5L20 20.07z" /></g>
, 'AirlineSeatReclineNormal');
|
src/routes/dashboard/components/completed.js
|
hhj679/mybition-web
|
import React from 'react'
import PropTypes from 'prop-types'
import styles from './completed.less'
import classnames from 'classnames'
import { color } from '../../../utils'
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'
function Completed ({ data }) {
return (
<div className={styles.sales}>
<div className={styles.title}>TEAM TOTAL COMPLETED</div>
<ResponsiveContainer minHeight={360}>
<AreaChart data={data}>
<Legend verticalAlign="top"
content={prop => {
const { payload } = prop
return (<ul className={classnames({ [styles.legend]: true, clearfix: true })}>
{payload.map((item, key) => <li key={key}><span className={styles.radiusdot} style={{ background: item.color }} />{item.value}</li>)}
</ul>)
}}
/>
<XAxis dataKey="name" axisLine={{ stroke: color.borderBase, strokeWidth: 1 }} tickLine={false} />
<YAxis axisLine={false} tickLine={false} />
<CartesianGrid vertical={false} stroke={color.borderBase} strokeDasharray="3 3" />
<Tooltip
wrapperStyle={{ border: 'none', boxShadow: '4px 4px 40px rgba(0, 0, 0, 0.05)' }}
content={content => {
const list = content.payload.map((item, key) => <li key={key} className={styles.tipitem}><span className={styles.radiusdot} style={{ background: item.color }} />{`${item.name}:${item.value}`}</li>)
return <div className={styles.tooltip}><p className={styles.tiptitle}>{content.label}</p><ul>{list}</ul></div>
}}
/>
<Area type="monotone" dataKey="Task complete" stroke={color.grass} fill={color.grass} strokeWidth={2} dot={{ fill: '#fff' }} activeDot={{ r: 5, fill: '#fff', stroke: color.green }} />
<Area type="monotone" dataKey="Cards Complete" stroke={color.sky} fill={color.sky} strokeWidth={2} dot={{ fill: '#fff' }} activeDot={{ r: 5, fill: '#fff', stroke: color.blue }} />
</AreaChart>
</ResponsiveContainer>
</div>
)
}
Completed.propTypes = {
data: PropTypes.array,
}
export default Completed
|
src/renderer/components/requests/request-stats.js
|
niklasi/halland-proxy
|
import React from 'react'
import {CardText} from 'material-ui/Card'
import prettyBytes from 'pretty-bytes'
import prettyMs from 'pretty-ms'
const RequestStats = ({ metadata = {} }) => {
return <CardText>
<div>Response time: {prettyMs(metadata.responseTime || 0)}</div>
<div>Response size: {prettyBytes(metadata.responseSize || 0)}</div>
<div>Dns lookup time: {prettyMs(metadata.dnsLookupTime || 0)}</div>
</CardText>
}
export default RequestStats
|
client/views/setupWizard/Pager.js
|
Sing-Li/Rocket.Chat
|
import { Button, ButtonGroup } from '@rocket.chat/fuselage';
import React from 'react';
import { useTranslation } from '../../contexts/TranslationContext';
export function Pager({ disabled, onBackClick, isContinueEnabled = true }) {
const t = useTranslation();
return <ButtonGroup align='end'>
{onBackClick ? <Button type='button' disabled={disabled} onClick={onBackClick} data-qa='previous-step'>
{t('Back')}
</Button> : null}
<Button type='submit' primary disabled={!isContinueEnabled || disabled} data-qa='next-step'>
{t('Continue')}
</Button>
</ButtonGroup>;
}
|
src/components/flows/thirdPillar/ThirdPillarSetup/ThirdPillarSetup.js
|
TulevaEE/onboarding-client
|
import React from 'react';
import Types from 'prop-types';
import { Link, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
export const ThirdPillarSetup = ({ nextPath, isThirdPillarActive }) => (
<div>
{isThirdPillarActive && <Redirect to={nextPath} />}
<p>
<FormattedMessage id="thirdPillarFlowSetup.text" />
</p>
<p>
<FormattedMessage id="thirdPillarFlowSetup.subtext" />
</p>
<div>
<Link to={nextPath}>
<button type="button" className="btn btn-primary mt-2">
<FormattedMessage id="thirdPillarFlowSetup.buttonText" />
</button>
</Link>
</div>
</div>
);
ThirdPillarSetup.propTypes = {
nextPath: Types.string,
isThirdPillarActive: Types.bool,
};
ThirdPillarSetup.defaultProps = {
nextPath: '',
isThirdPillarActive: false,
};
const mapStateToProps = (state) => ({
isThirdPillarActive: !!(
state.login.token &&
state.login.user &&
state.login.user.thirdPillarActive
),
});
export default connect(mapStateToProps)(ThirdPillarSetup);
|
src/cell/index.js
|
HVF/franchise
|
import React from 'react'
import ReactDOM from 'react-dom'
import * as State from '../state'
import * as U from '../state/update'
import ReactCodeMirror from '@skidding/react-codemirror'
import CodeMirror from 'codemirror'
// import 'codemirror/mode/sql/sql'
import 'codemirror/mode/markdown/markdown'
import 'codemirror/keymap/sublime'
import 'codemirror/addon/display/placeholder'
import 'codemirror/addon/comment/comment'
import 'codemirror/addon/comment/continuecomment'
import 'codemirror/addon/edit/matchbrackets'
import 'codemirror/addon/edit/closebrackets'
import 'codemirror/addon/selection/active-line'
import 'codemirror/addon/search/match-highlighter'
import './prediction'
import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/addon/hint/show-hint'
import './sql-hint'
import 'codemirror/addon/display/placeholder'
import './md.less'
import { EditableText } from '@blueprintjs/core'
import swal from 'sweetalert2'
import { addCell } from '../notebook'
import { DB, getDB } from '../db/configure'
import _ from 'lodash'
import { Intent, Popover, Position, Switch, Tooltip as BlueprintTooltip } from '@blueprintjs/core'
function Tooltip(props) {
return (
<BlueprintTooltip
position={Position.RIGHT}
tetherOptions={{ constraints: [{ attachment: 'together', to: 'scrollParent' }] }}
{...props}
/>
)
}
export class Cell extends React.Component {
shouldComponentUpdate(nextProps) {
return (
nextProps.view !== this.props.view ||
nextProps.connect !== this.props.connect ||
nextProps.deltas !== this.props.deltas ||
nextProps.forceRenderToken !== this.props.forceRenderToken
)
}
componentDidMount() {
var cm = this.cmr.getCodeMirror()
var el = document.createElement('span')
cm.addWidget({ line: 0, ch: 0 }, el, false)
el.style.left = ''
el.style.top = ''
el.style.position = ''
el.className = 'slice-editor-widget'
this.widget = el
this.componentDidUpdate()
}
componentDidUpdate() {
ReactDOM.render(
<SnippetWidget
updateView={(e) => this.props.updateView(e)}
view={this.props.view}
cmr={this.cmr}
connect={this.props.connect}
config={this.props.config}
/>,
this.widget
)
}
render() {
let { view, updateView, connect, deltas, virtualSchema, config } = this.props
let db = DB(connect.active)
let fresh =
((view.result && view.result.query) || '').trim() === (view.query || '').trim() ||
view.error ||
(view.query || '').trim() === '' ||
view.loading ||
connect.status != 'connected'
const sql_options = {
mode: db.syntax || 'text/plain',
theme: 'hipster',
// continueComments: true,
highlightSelectionMatches: {
// showToken: /\w/,
trim: true,
},
lineWrapping: true,
extraKeys: {
'Cmd-Enter': (cm) => runCell(view.id),
'Ctrl-Enter': (cm) => runCell(view.id),
'Ctrl-Space': 'autocomplete',
},
// styleActiveLine: true,
autoCloseBrackets: true,
matchBrackets: true,
addModeClass: true,
placeholder:
connect.status == 'connected' ? 'Type query here, or click a bubble below.' : '',
tabSize: 2,
indentUnit: 2,
showPredictions: true,
...(db.CodeMirrorOptions ? db.CodeMirrorOptions(connect, virtualSchema) : {}),
keyMap: 'sublime',
}
const md_options = {
mode: 'markdown',
keyMap: 'sublime',
lineWrapping: true,
theme: 'md',
placeholder: 'Type Markdown here...',
showPredictions: false,
}
let md = view.markdown
return (
<div className="slice-wrap">
<div
className={
'slice ' +
(fresh || md ? 'fresh ' : 'stale ') +
(md ? 'markdown ' : 'code ')
}
>
<div className="input-wrap">
<ReactCodeMirror
value={view.query}
key="a"
ref={(e) => (this.cmr = e)}
onChange={(query) => {
// this is a silly patch for a graphql-codemirror bug
// https://github.com/graphql/graphiql/issues/735
updateView({ query: query.replace(/\xa0/g, ' ') })
}}
options={md ? md_options : sql_options}
/>
{db.reference && (
<BlueprintTooltip
content={
<span>
Refer to the results of this cell with{' '}
<strong>
{db.reference(view.name || view.suggestedName)}
</strong>
</span>
}
className="pt-tooltip-indicator"
>
<div
className={
'name ' +
(view.result && view.result.nameable && db.reference
? 'shown'
: '')
}
>
<span style={{ color: '#adb7bf' }}>
{db.reference('SPLITTER').split('SPLITTER')[0] || ''}
</span>
<EditableText
value={view.name}
onChange={(name) =>
updateView({ name: name.replace(/[^\w]/g, '') })
}
placeholder={view.suggestedName}
minWidth={30}
/>
<span style={{ color: '#adb7bf' }}>
{db.reference('SPLITTER').split('SPLITTER')[1] || ''}
</span>
</div>
</BlueprintTooltip>
)}
<div className="controls" onMouseDown={this.props.beginDrag}>
<Tooltip content="Archive Cell">
<button onClick={this.props.close} title="Archive Cell">
<i className="fa fa-close" aria-hidden="true" />
</button>
</Tooltip>
{md ? null : (
<Tooltip content="Clone Cell">
<button onClick={this.props.fork}>
<i className="fa fa-clone" aria-hidden="true" />
</button>
</Tooltip>
)}
<div className="spacer" />
{md ? null : connect.status === 'connected' ? (
<Tooltip content="Run Query (Cmd-Enter)" intent={Intent.SUCCESS}>
<button onClick={(e) => runCell(view.id)}>
{view.loading ? (
<i className="fa fa-gear fa-spin" aria-hidden="true" />
) : (
<i
className={
'fa fa-play ' +
((view.query || '').trim() ? 'runnable' : '')
}
aria-hidden="true"
/>
)}
</button>
</Tooltip>
) : (
<Tooltip content="No database connected" intent={Intent.WARNING}>
<button
title="No database connected"
data-tip="No database connected"
onClick={(e) => runCell(view.id)}
>
<i
className="fa fa-exclamation-triangle"
aria-hidden="true"
/>
</button>
</Tooltip>
)}
</div>
</div>
{md ? null : view.error ? (
<div className="error">{view.error}</div>
) : view.result ? (
<ErrorBoundary updateView={updateView}>
<ResultVisualizerLoader
view={view}
deltas={deltas}
connect={connect}
forceRenderToken={this.props.forceRenderToken}
config={config}
updateView={updateView}
beginDrag={this.props.beginDrag}
result={view.result}
/>
</ErrorBoundary>
) : null}
</div>
</div>
)
}
}
// './visualizer'
var VisualizerModule,
VisualizerReadyQueue = []
setTimeout(async function() {
VisualizerModule = await import('./visualizer')
while (VisualizerReadyQueue.length > 0) {
try {
VisualizerReadyQueue.pop()()
} catch (err) {}
}
}, 0)
class ErrorBoundary extends React.Component {
componentDidCatch(error, info) {
this.props.updateView({
error: error.toString(),
})
}
render() {
return this.props.children
}
}
class ResultVisualizerLoader extends React.PureComponent {
componentWillUpdate() {
this.checkModule()
}
componentWillMount() {
this.checkModule()
}
checkModule() {
if (!VisualizerModule) {
VisualizerReadyQueue.push((e) => this.setState({ visualizer: VisualizerModule }))
}
}
render() {
if (VisualizerModule) {
return <VisualizerModule.ResultVisualizer {...this.props} />
}
return (
<div className="visualizer-loading">
<i className="fa fa-circle-o-notch fa-spin fa-fw" /> Loading...
</div>
)
}
}
export function cellById(cellId) {
return ['notebook', 'layout', U.each, 'items', U.id(cellId)]
}
export function updateCell(cellId, update) {
State.apply(...cellById(cellId), U.merge(update))
}
export function getCell(cellId) {
return State.get(...cellById(cellId))
}
export async function runCell(cellId) {
if (getCell(cellId).markdown) return
if (State.get('connect', 'status') !== 'connected') {
// immediately invoking swal causes it to be automatically dismissed
// when runCell is triggered by Cmd-Enter
requestAnimationFrame((_) =>
swal.fire(
'Oops...',
'No database connected! Please connect to a database before running queries. ',
'error'
)
)
return
}
updateCell(cellId, { loading: true })
try {
let cell = getCell(cellId)
var result = await getDB().run(cell.query, cellId)
updateCell(cellId, {
loading: false,
result: result,
error: null,
suggestedName: cell.suggestedName || result.suggestedName,
})
} catch (err) {
updateCell(cellId, { loading: false, result: null, error: err.message })
}
}
import { Select } from '@blueprintjs/labs'
import { Classes, MenuItem } from '@blueprintjs/core'
function SnippetWidget({ connect, view, cmr, updateView, config }) {
let db = DB(connect.active)
var is_empty = (view.query || '').trim() === ''
// if(!connect.schema) return null;
if (connect.status !== 'connected') return null
if (view.markdown) return null
function replaceText(text, tokenize = false) {
let cm = cmr.getCodeMirror()
updateView({ query: text })
cm.setValue(text)
if (tokenize) {
let markMap = {}
for (let [start, end, text] of derange(/(\".*?\")/g, text)) {
let el = document.createElement('span')
el.innerText = text
el.className = 'schema-token'
let mark = cm.markText(cm.posFromIndex(start), cm.posFromIndex(end), {
atomic: true,
replacedWith: el,
})
if (!markMap[text]) markMap[text] = []
markMap[text].push(mark)
el.onclick = function() {
let pos = mark.find()
cm.setSelections(
markMap[text].map((k) => {
let p = k.find()
return { anchor: p.from, head: p.to }
})
)
cm.focus()
}
}
}
cm.setCursor(1e8, 1e8)
cm.focus()
}
let visible_schema = connect.schema
? connect.schema.filter((k) => !(k.schema && k.schema.startsWith('_')))
: []
return (
<div className={'slice-editor-widget ' + (is_empty ? 'slice-visible' : 'slice-hidden')}>
{visible_schema.length > 8
? _.map(_.groupBy(connect.schema, 'schema'), (k, i) => (
<Select
key={i}
items={k}
noResults={<MenuItem disabled text="No results." />}
onItemSelect={(film) =>
setTimeout(
(j) => replaceText(db.select_table_snippet(film, config)),
0
)
}
itemPredicate={(query, film, index) =>
film.name.toLowerCase().indexOf(query.toLowerCase().trim()) != -1
}
itemRenderer={({ handleClick, item: film, isActive }) => (
<MenuItem
className={isActive ? Classes.ACTIVE : ''}
key={film.name}
onClick={handleClick}
label={film.columns.join(', ')}
text={film.name}
/>
)}
>
<div className="token">
{i || 'default'}
<span className="pt-icon-standard pt-icon-caret-down" />
</div>
</Select>
))
: visible_schema.map((table) => (
<BlueprintTooltip
key={table.name}
content={table.columns.join(', ')}
position={Position.BOTTOM}
intent={Intent.PRIMARY}
>
<div
className="token"
onClick={(e) => replaceText(db.select_table_snippet(table, config))}
>
{table.name}
</div>
</BlueprintTooltip>
))}
{db.create_table_snippet && (
<BlueprintTooltip
content={'Create Table'}
position={Position.BOTTOM}
intent={Intent.WARNING}
>
<div
className="token create-table"
onClick={(e) => replaceText(db.create_table_snippet(connect.schema), true)}
>
<span className="pt-icon-standard pt-icon-plus" />
</div>
</BlueprintTooltip>
)}
<BlueprintTooltip content={'Convert to Markdown Cell'} position={Position.BOTTOM}>
<div
className="token create-text"
onClick={(e) => {
updateView({ markdown: true })
// this works around a bug in the codemirror placeholder library
// which doesn't update placeholder text if the thing has focus
requestAnimationFrame((e) => {
let cm = cmr.getCodeMirror()
cm.setCursor(1e8, 1e8)
cm.focus()
})
}}
>
<i className="fa fa-comment" />
</div>
</BlueprintTooltip>
</div>
)
}
// code originally written for hypernote
function derange(re, text) {
var match,
ranges = [],
pos = 0
while ((match = re.exec(text))) {
ranges.push([match.index, re.lastIndex, match[1]])
}
return ranges
}
function rangesub(ranges, replaceWith) {
var offset = 0
ranges.sort((a, b) => a[0] - b[0])
for (var i = 0; i < ranges.length; i++) {
var [start, end, sub] = ranges[i]
offset += replaceWith(start + offset, end + offset, sub) - (end - start)
}
}
function rangesubtext(ranges, text, replacer) {
rangesub(ranges, (start, end, sub) => {
var flag = replacer(sub)
text = text.slice(0, start) + flag + text.slice(end)
return flag.length
})
return text
}
export class ArchivedCell extends React.PureComponent {
render() {
let { view, connect } = this.props
let db = DB(connect.active)
return (
<div className="slice-wrap">
<div className="slice">
<div className="input-wrap">
<ReactCodeMirror
value={view.query}
options={{
readOnly: true,
mode: db.syntax || 'text/plain',
theme: 'hipster',
addModeClass: true,
lineWrapping: true,
}}
/>
<div className="controls">
<Tooltip content="Unarchive">
<button onClick={(e) => untrashCell(view.id)}>
<i className="fa fa-level-up" aria-hidden="true" />
</button>
</Tooltip>
<Tooltip content="Remove Permanently" intent={Intent.DANGER}>
<button onClick={(e) => removeTrash(view.id)}>
<i className="fa fa-trash" aria-hidden="true" />
</button>
</Tooltip>
</div>
</div>
</div>
</div>
)
}
}
function removeTrash(cellId) {
State.batch((_) => {
State.apply('trash', 'cells', U.removeId(cellId))
if (State.get('trash', 'cells').length === 0) {
State.apply('trash', 'open', U.replace(false))
}
})
}
function untrashCell(cellId) {
State.batch((_) => {
let cell = State.get('trash', 'cells', U.id(cellId))
removeTrash(cellId)
addCell(cell)
})
}
|
app/javascript/mastodon/features/ui/components/confirmation_modal.js
|
rutan/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl, FormattedMessage } from 'react-intl';
import Button from '../../../components/button';
@injectIntl
export default class ConfirmationModal extends React.PureComponent {
static propTypes = {
message: PropTypes.node.isRequired,
confirm: PropTypes.string.isRequired,
onClose: PropTypes.func.isRequired,
onConfirm: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
componentDidMount() {
this.button.focus();
}
handleClick = () => {
this.props.onClose();
this.props.onConfirm();
}
handleCancel = () => {
this.props.onClose();
}
setRef = (c) => {
this.button = c;
}
render () {
const { message, confirm } = this.props;
return (
<div className='modal-root__modal confirmation-modal'>
<div className='confirmation-modal__container'>
{message}
</div>
<div className='confirmation-modal__action-bar'>
<Button onClick={this.handleCancel} className='confirmation-modal__cancel-button'>
<FormattedMessage id='confirmation_modal.cancel' defaultMessage='Cancel' />
</Button>
<Button text={confirm} onClick={this.handleClick} ref={this.setRef} />
</div>
</div>
);
}
}
|
src/components/Home.js
|
Jalissa/rss-feed-client
|
import React from 'react';
const Home = (props) => {
return (
<div>
<h1 className="text-center">Feedr</h1>
<p className="text-center">Your offline rss reader</p>
<div className="jumbotron">
{props.children}
</div>
</div>
);
};
export default Home;
|
src/parser/demonhunter/havoc/modules/talents/Demonic.js
|
sMteX/WoWAnalyzer
|
import React from 'react';
import SPELLS from 'common/SPELLS';
import TalentStatisticBox from 'interface/others/TalentStatisticBox';
import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER';
import Events from 'parser/core/Events';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import SpellLink from 'common/SpellLink';
/**
* Example Report: https://www.warcraftlogs.com/reports/23dHWCrT18qhaJbz/#fight=1&source=16
*/
const META_BUFF_DURATION_EYEBEAM = 10000;
class Demonic extends Analyzer{
eyeBeamCasts = 0;
goodDeathSweep = 0;
eyeBeamTimeStamp = undefined;
deathsweepsInMetaCounter = undefined;
badCasts = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.DEMONIC_TALENT.id);
if (!this.active) {
return;
}
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.EYE_BEAM), this.onEyeBeamCast);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.DEATH_SWEEP), this.onDeathSweepCast);
}
onEyeBeamCast(event) {
const hasMetaBuff = this.selectedCombatant.hasBuff(SPELLS.METAMORPHOSIS_HAVOC_BUFF.id, event.timestamp - 1000);
if (hasMetaBuff) {
return;
}
this.eyeBeamCasts += 1;
this.eyeBeamTimeStamp = event.timestamp;
if (this.deathsweepsInMetaCounter === undefined) {
this.deathsweepsInMetaCounter = 0;
return;
}
if (this.deathsweepsInMetaCounter < 2) {
this.badCasts += 1;
}
this.deathsweepsInMetaCounter = 0;
}
onDeathSweepCast(event) {
if (this.eyeBeamTimeStamp !== undefined && (event.timestamp - this.eyeBeamTimeStamp) < META_BUFF_DURATION_EYEBEAM) {
this.goodDeathSweep += 1;
this.deathsweepsInMetaCounter += 1;
}
}
get suggestionThresholds() {
return {
actual: this.badCasts,
isGreaterThan: {
minor: 0,
average: 0,
major: 1,
},
style: 'number',
};
}
suggestions(when) {
when(this.suggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<>Try to have <SpellLink id={SPELLS.BLADE_DANCE.id} /> almost off cooldown before casting <SpellLink id={SPELLS.EYE_BEAM.id} />. This will allow for two casts of <SpellLink id={SPELLS.DEATH_SWEEP.id} /> during the <SpellLink id={SPELLS.METAMORPHOSIS_HAVOC.id} /> buff you get from the <SpellLink id={SPELLS.DEMONIC_TALENT.id} /> talent.</>)
.icon(SPELLS.DEMONIC_TALENT.icon)
.actual(<>{actual} time(s) during <SpellLink id={SPELLS.METAMORPHOSIS_HAVOC.id} /> <SpellLink id={SPELLS.DEATH_SWEEP.id} /> wasn't casted twice.</>)
.recommended(`No bad casts is recommended.`);
});
}
statistic(){
return (
<TalentStatisticBox
talent={SPELLS.DEMONIC_TALENT.id}
position={STATISTIC_ORDER.OPTIONAL(6)}
value={(<>
{this.badCasts} <small>Bad casts</small><br />
</>)}
tooltip={`A bad cast is triggered when you don't do atleast 2 Death Sweep casts inside
the Metamorphosis window you get from Eye Beam due to the Demonic talent.`}
/>
);
}
}
export default Demonic;
|
src/mui/layout/Responsive.spec.js
|
matteolc/admin-on-rest
|
import assert from 'assert';
import { shallow } from 'enzyme';
import React from 'react';
import { Responsive } from './Responsive';
describe('<Responsive>', () => {
const Small = () => <div />;
const Medium = () => <div />;
const Large = () => <div />;
it('should render the small component on small screens', () => {
const wrapper = shallow(<Responsive small={<Small />} medium={<Medium />} large={<Large />} width={1} />);
const component = wrapper.find('Small');
assert.equal(component.length, 1);
});
it('should render the medium component on medium screens', () => {
const wrapper = shallow(<Responsive small={<Small />} medium={<Medium />} large={<Large />} width={2} />);
const component = wrapper.find('Medium');
assert.equal(component.length, 1);
});
it('should render the large component on large screens', () => {
const wrapper = shallow(<Responsive small={<Small />} medium={<Medium />} large={<Large />} width={3} />);
const component = wrapper.find('Large');
assert.equal(component.length, 1);
});
it('should render the small component on all screens when no other component is passed', () => {
assert.equal(shallow(<Responsive small={<Small />} width={1} />).find('Small').length, 1);
assert.equal(shallow(<Responsive small={<Small />} width={2} />).find('Small').length, 1);
assert.equal(shallow(<Responsive small={<Small />} width={3} />).find('Small').length, 1);
});
it('should render the medium component on all screens when no other component is passed', () => {
assert.equal(shallow(<Responsive medium={<Medium />} width={1} />).find('Medium').length, 1);
assert.equal(shallow(<Responsive medium={<Medium />} width={2} />).find('Medium').length, 1);
assert.equal(shallow(<Responsive medium={<Medium />} width={3} />).find('Medium').length, 1);
});
it('should render the large component on all screens when no other component is passed', () => {
assert.equal(shallow(<Responsive large={<Large />} width={1} />).find('Large').length, 1);
assert.equal(shallow(<Responsive large={<Large />} width={2} />).find('Large').length, 1);
assert.equal(shallow(<Responsive large={<Large />} width={3} />).find('Large').length, 1);
});
it('should fallback to the large component on medium screens', () => {
const wrapper = shallow(<Responsive small={<Small />} large={<Large />} width={2} />);
const component = wrapper.find('Large');
assert.equal(component.length, 1);
});
it('should fallback to the medium component on small screens', () => {
const wrapper = shallow(<Responsive medium={<Medium />} large={<Large />} width={1} />);
const component = wrapper.find('Medium');
assert.equal(component.length, 1);
});
it('should fallback to the medium component on large screens', () => {
const wrapper = shallow(<Responsive small={<Small />} medium={<Medium />} width={3} />);
const component = wrapper.find('Medium');
assert.equal(component.length, 1);
});
});
|
app/components/SignupForm.js
|
trussworks/DoDidDone
|
import React from 'react';
import TextField from 'material-ui/TextField';
const SignupForm = () => (
<div>
<TextField
hintText="Name"
id="nameField"
/><br />
<TextField
hintText="Email"
errorText="This field is required."
id="emailField"
type="email"
/><br />
<TextField
hintText="Password"
errorText="This field is required."
id="passwordField"
type="password"
/><br />
</div>
);
export default SignupForm;
|
node_modules/react-bootstrap/es/utils/ValidComponentChildren.js
|
hsavit1/gosofi_webpage
|
// TODO: This module should be ElementChildren, and should use named exports.
import React from 'react';
/**
* Iterates through children that are typically specified as `props.children`,
* but only maps over children that are "valid components".
*
* The mapFunction provided index will be normalised to the components mapped,
* so an invalid component would not increase the index.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func.
* @param {*} context Context for func.
* @return {object} Object containing the ordered map of results.
*/
function map(children, func, context) {
var index = 0;
return React.Children.map(children, function (child) {
if (!React.isValidElement(child)) {
return child;
}
return func.call(context, child, index++);
});
}
/**
* Iterates through children that are "valid components".
*
* The provided forEachFunc(child, index) will be called for each
* leaf child with the index reflecting the position relative to "valid components".
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func.
* @param {*} context Context for context.
*/
function forEach(children, func, context) {
var index = 0;
React.Children.forEach(children, function (child) {
if (!React.isValidElement(child)) {
return;
}
func.call(context, child, index++);
});
}
/**
* Count the number of "valid components" in the Children container.
*
* @param {?*} children Children tree container.
* @returns {number}
*/
function count(children) {
var result = 0;
React.Children.forEach(children, function (child) {
if (!React.isValidElement(child)) {
return;
}
++result;
});
return result;
}
/**
* Finds children that are typically specified as `props.children`,
* but only iterates over children that are "valid components".
*
* The provided forEachFunc(child, index) will be called for each
* leaf child with the index reflecting the position relative to "valid components".
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func.
* @param {*} context Context for func.
* @returns {array} of children that meet the func return statement
*/
function filter(children, func, context) {
var index = 0;
var result = [];
React.Children.forEach(children, function (child) {
if (!React.isValidElement(child)) {
return;
}
if (func.call(context, child, index++)) {
result.push(child);
}
});
return result;
}
function find(children, func, context) {
var index = 0;
var result = undefined;
React.Children.forEach(children, function (child) {
if (result) {
return;
}
if (!React.isValidElement(child)) {
return;
}
if (func.call(context, child, index++)) {
result = child;
}
});
return result;
}
function every(children, func, context) {
var index = 0;
var result = true;
React.Children.forEach(children, function (child) {
if (!result) {
return;
}
if (!React.isValidElement(child)) {
return;
}
if (!func.call(context, child, index++)) {
result = false;
}
});
return result;
}
function some(children, func, context) {
var index = 0;
var result = false;
React.Children.forEach(children, function (child) {
if (result) {
return;
}
if (!React.isValidElement(child)) {
return;
}
if (func.call(context, child, index++)) {
result = true;
}
});
return result;
}
function toArray(children) {
var result = [];
React.Children.forEach(children, function (child) {
if (!React.isValidElement(child)) {
return;
}
result.push(child);
});
return result;
}
export default {
map: map,
forEach: forEach,
count: count,
find: find,
filter: filter,
every: every,
some: some,
toArray: toArray
};
|
docs/src/app/components/pages/components/Snackbar/ExampleAction.js
|
w01fgang/material-ui
|
import React from 'react';
import Snackbar from 'material-ui/Snackbar';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
export default class SnackbarExampleSimple extends React.Component {
constructor(props) {
super(props);
this.state = {
autoHideDuration: 4000,
message: 'Event added to your calendar',
open: false,
};
}
handleTouchTap = () => {
this.setState({
open: true,
});
};
handleActionTouchTap = () => {
this.setState({
open: false,
});
alert('Event removed from your calendar.');
};
handleChangeDuration = (event) => {
const value = event.target.value;
this.setState({
autoHideDuration: value.length > 0 ? parseInt(value) : 0,
});
};
handleRequestClose = () => {
this.setState({
open: false,
});
};
render() {
return (
<div>
<RaisedButton
onTouchTap={this.handleTouchTap}
label="Add to my calendar"
/>
<br />
<TextField
floatingLabelText="Auto Hide Duration in ms"
value={this.state.autoHideDuration}
onChange={this.handleChangeDuration}
/>
<Snackbar
open={this.state.open}
message={this.state.message}
action="undo"
autoHideDuration={this.state.autoHideDuration}
onActionTouchTap={this.handleActionTouchTap}
onRequestClose={this.handleRequestClose}
/>
</div>
);
}
}
|
client/components/App.js
|
axax/lunuc
|
import React from 'react'
import PropTypes from 'prop-types'
import Routes from './routing/Routes'
import UserDataContainer from 'client/containers/UserDataContainer'
/*
* The Provider component provides
* the React store to all its child
* components so we don't need to pass
* it explicitly to all the components.
*/
import {Provider} from 'react-redux'
class App extends React.PureComponent {
render() {
return <Provider store={this.props.store}>
<UserDataContainer>
<Routes/>
</UserDataContainer>
</Provider>
}
}
App.propTypes = {
store: PropTypes.object.isRequired
}
export default App
|
client/src/h.js
|
ChenH0ng/blog
|
import React from 'react';
export default React.createElement;
|
app/components/Institution/DeletePermissionMsg.js
|
klpdotorg/tada-frontend
|
import React from 'react';
const DeletePermissionMsg = () => {
return (
<div className="alert alert-info">
<i className="fa fa-info-circle fa-lg" aria-hidden="true" /> You cannot delete this
institution until its classes are deleted
</div>
);
};
export { DeletePermissionMsg };
|
fields/types/date/DateColumn.js
|
Freakland/keystone
|
import React from 'react';
import moment from 'moment';
import ItemsTableCell from '../../../admin/src/components/ItemsTableCell';
import ItemsTableValue from '../../../admin/src/components/ItemsTableValue';
var DateColumn = React.createClass({
displayName: 'DateColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
let value = this.props.data.fields[this.props.col.path];
if (!value) return null;
let format = (this.props.col.path === 'dateTime') ? 'MMMM Do YYYY, h:mm:ss a' : 'MMMM Do YYYY';
let formattedValue = moment(value).format(format);
return (
<ItemsTableValue title={formattedValue} field={this.props.col.type}>
{formattedValue}
</ItemsTableValue>
);
},
render () {
return (
<ItemsTableCell>
{this.renderValue()}
</ItemsTableCell>
);
}
});
module.exports = DateColumn;
|
src/common/Socket/Channel.js
|
Syncano/syncano-dashboard
|
import React from 'react';
import { colors as Colors } from 'material-ui/styles/';
import SocketWrapper from './SocketWrapper';
export default React.createClass({
displayName: 'ChannelSocket',
getDefaultProps() {
return {
tooltip: 'Create a Channel Socket'
};
},
getStyles() {
return {
iconStyle: {
color: Colors.blue300
}
};
},
render() {
const styles = this.getStyles();
const {
style,
iconStyle,
...other
} = this.props;
return (
<SocketWrapper
{...other}
iconClassName="synicon-socket-channel"
style={style}
iconStyle={{ ...styles.iconStyle, ...iconStyle }}
/>
);
}
});
|
app/javascript/components/HandoverAutocomplete.js
|
leihs/leihs_legacy
|
// TODO: cleanup
/* eslint-disable react/no-string-refs */
/* global _ */
/* global _jed */
import React from 'react'
import createReactClass from 'create-react-class'
import PropTypes from 'prop-types'
import Autocomplete from '@eins78/react-autocomplete'
export const HandoverAutocomplete = createReactClass({
propTypes: {
placeholder: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
onSelect: PropTypes.func.isRequired,
isLoading: PropTypes.bool.isRequired,
searchResults: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string.isRequired,
availability: PropTypes.string,
type: PropTypes.string.isRequired,
record: PropTypes.object.isRequired
})
)
},
getInitialState() {
return { value: '' }
},
_handleChange(event, value) {
// update internal state to reflect new input:
this.setState({ value: value })
// callback to controller:
this.props.onChange(value)
},
_handleSelect(value, item) {
// reset the input field
this.setState({ value: '' })
// callback
this.props.onSelect(item)
},
// public methods
resetInput() {
// reset the input field
this.setState({ value: '' })
},
// mirror jQueryAutocomplete API
val(str) {
this.setState({ value: str })
},
// "partials"
_renderMenu(items, value, givenStyles, props = this.props) {
// show nothing when no search:
if (value === '') {
return <div style={{ display: 'none' }} />
}
const menuProps = {
className: 'ui-autocomplete ui-autocomplete-scrollable ui-front ui-menu',
style: {
display: 'inline-block',
position: 'absolute',
top: '31px',
width: '100%'
}
}
if (props.isLoading) {
return (
<div {...menuProps}>
<div className="loading-bg-small margin-top-m margin-bottom-m" />
</div>
)
}
const models = _.sortBy(
_.filter(items, i => i.props.item.type === _jed('Model')),
i => i.props.item.name
)
const options = _.sortBy(
_.filter(items, i => i.props.item.type === _jed('Option')),
i => i.props.item.name
)
const templates = _.sortBy(
_.filter(items, i => i.props.item.type === _jed('Template')),
i => i.props.item.name
)
// searched but no results:
if (props.searchResults && _.all([models, options, templates], _.isEmpty)) {
return (
<ul {...menuProps}>
<li className="padding-left-s margin-top-m margin-bottom-m">{_jed('No results')}</li>
</ul>
)
}
return (
<ul {...menuProps}>
{_.isEmpty(models) ? null : this._renderMenuSubSection(_jed('Models'), models)}
{_.isEmpty(options) ? null : this._renderMenuSubSection(_jed('Options'), options)}
{_.isEmpty(templates) ? null : this._renderMenuSubSection(_jed('Templates'), templates)}
</ul>
)
},
_renderMenuSubSection(heading, list) {
return [
<li className="submenu-header" key={heading + '-header'}>
<b>{heading}</b>
</li>,
<li className="submenu-scroll" key={heading + '-list'}>
<ul>{list}</ul>
</li>
]
},
_renderMenuItem(item) {
return (
<li
key={item.type + item.name + item.record.cid}
item={item}
id={item.abbr}
className="separated-bottom exclude-last-child">
<a className={'row' + (!item.available ? ' light-red' : '')} title={item.name}>
<div className="row">
<div className="col3of4" title={item.name}>
<strong className="wrap">{item.name}</strong>
</div>
<div className="col1of4 text-align-right">
<div className="row">{item.availability}</div>
<div className="row">
<span className="grey-text">{item.type}</span>
</div>
</div>
</div>
</a>
</li>
)
},
render() {
const props = this.props
var inputProps = {
type: 'text',
className: 'row has-addone',
style: { position: 'absolute' },
placeholder: props.placeholder
}
var wrapperProps = {
style: {}
}
return (
<Autocomplete
ref="autocomplete"
value={this.state.value}
items={props.searchResults || []}
wrapperProps={wrapperProps}
inputProps={inputProps}
renderMenu={this._renderMenu}
selectOnInputClick={false}
getItemValue={item => item.name}
onSelect={this._handleSelect}
onChange={this._handleChange}
renderItem={this._renderMenuItem}
/>
)
}
})
|
__tests__/index.ios.js
|
kharron/photoapp
|
import 'react-native';
import React from 'react';
import Index from '../index.ios.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
docs/app/Examples/collections/Form/Types/FormExampleForm.js
|
aabustamante/Semantic-UI-React
|
import React from 'react'
import { Button, Checkbox, Form } from 'semantic-ui-react'
const FormExampleForm = () => (
<Form>
<Form.Field>
<label>First Name</label>
<input placeholder='First Name' />
</Form.Field>
<Form.Field>
<label>Last Name</label>
<input placeholder='Last Name' />
</Form.Field>
<Form.Field>
<Checkbox label='I agree to the Terms and Conditions' />
</Form.Field>
<Button type='submit'>Submit</Button>
</Form>
)
export default FormExampleForm
|
app/classifier/tasks/combo/editor.spec.js
|
jelliotartz/Panoptes-Front-End
|
import { mount } from 'enzyme';
import React from 'react';
import assert from 'assert';
import ComboEditor from './editor';
import { workflow } from '../../../pages/dev-classifier/mock-data';
const task = {
type: 'combo',
loosen_requirements: true,
tasks: ['write', 'ask', 'features', 'draw', 'survey', 'slider']
};
describe('ComboEditor', () => {
const wrapper = mount(<ComboEditor workflow={workflow} task={task} />);
it('should render for a workflow and task', () => {
assert.equal(wrapper.instance() instanceof ComboEditor, true);
});
it('should add new tasks to the combo when selected', () => {
wrapper.find('select[value="stuck"]').simulate('change', { target: { value: 'dropdown' }});
const { props } = wrapper.instance();
assert.notEqual(props.task.tasks.indexOf('dropdown'), -1);
});
it('should allow tasks to be deleted from the combo', () => {
wrapper.find('ul.drag-reorderable button').first().simulate('click');
const { props } = wrapper.instance();
assert.equal(props.task.tasks.indexOf('write'), -1);
});
});
describe('deleting a workflow task', () => {
const workflowCopy = Object.assign({}, workflow);
const tasks = Object.assign({}, workflow.tasks);
delete tasks.ask;
workflowCopy.tasks = tasks;
it('should render and update the combo task', () => {
const wrapper = mount(<ComboEditor workflow={workflowCopy} task={task} />);
const { props } = wrapper.instance();
assert.equal(props.task.tasks.indexOf('ask'), -1);
});
});
|
components/SVG/FacebookSvg.js
|
numieco/numie
|
import React from 'react'
export default class FacebookSvg extends React.Component {
render () {
return (
<svg width="40px" height="40px" viewBox="0 0 40 40" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink">
<title>facebook-logo-button</title>
<desc>Created with Sketch.</desc>
<defs></defs>
<g id="Contact" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
<g id="Desktop---Thoughts" transform="translate(-1150.000000, -537.000000)">
<g id="Group-8" transform="translate(1030.000000, 192.000000)">
<g id="facebook-logo-button" transform="translate(120.000000, 345.000000)">
<g id="Group-7">
<path d="M19.8608,0 C8.9096,0 0,8.9096 0,19.8608 C0,30.8112 8.9096,39.7216 19.8608,39.7216 C30.8112,39.7216 39.7216,30.8112 39.7216,19.8608 C39.7216,8.9096 30.8128,0 19.8608,0 Z M24.8,20.56 L21.5688,20.56 L21.5688,32.0768 L16.7808,32.0768 L16.7808,20.56 L14.5048,20.56 L14.5048,16.4896 L16.7808,16.4896 L16.7808,13.8568 C16.7808,11.9712 17.6768,9.0248 21.6128,9.0248 L25.1608,9.0384 L25.1608,12.9896 L22.5856,12.9896 C22.1664,12.9896 21.5704,13.1992 21.5704,14.0984 L21.5704,16.4904 L25.2184,16.4904 L24.8,20.56 Z" id="Shape" fill="#FFFFFF" fillRule="nonzero"></path>
<path d="M24.801419,20.5620208 L21.570219,20.5620208 L21.570219,32.0788208 L16.782219,32.0788208 L16.782219,20.5620208 L14.506219,20.5620208 L14.506219,16.4916208 L16.782219,16.4916208 L16.782219,13.8588208 C16.782219,11.9732208 17.678219,9.02682077 21.614219,9.02682077 L25.162219,9.04042077 L25.162219,12.9916208 L22.587019,12.9916208 C22.167819,12.9916208 21.571819,13.2012208 21.571819,14.1004208 L21.571819,16.4924208 L25.219819,16.4924208 L24.801419,20.5620208 Z" id="Combined-Shape" fill="#E0394A"></path>
</g>
</g>
</g>
</g>
</g>
</svg>
)
}
}
|
src/svg-icons/device/signal-cellular-no-sim.js
|
pancho111203/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalCellularNoSim = (props) => (
<SvgIcon {...props}>
<path d="M18.99 5c0-1.1-.89-2-1.99-2h-7L7.66 5.34 19 16.68 18.99 5zM3.65 3.88L2.38 5.15 5 7.77V19c0 1.1.9 2 2 2h10.01c.35 0 .67-.1.96-.26l1.88 1.88 1.27-1.27L3.65 3.88z"/>
</SvgIcon>
);
DeviceSignalCellularNoSim = pure(DeviceSignalCellularNoSim);
DeviceSignalCellularNoSim.displayName = 'DeviceSignalCellularNoSim';
DeviceSignalCellularNoSim.muiName = 'SvgIcon';
export default DeviceSignalCellularNoSim;
|
examples/huge-apps/routes/Course/routes/Announcements/components/Sidebar.js
|
malte-wessel/react-router
|
/*globals COURSES:true */
import React from 'react'
import { Link } from 'react-router'
class AnnouncementsSidebar extends React.Component {
render() {
let { announcements } = COURSES[this.props.params.courseId]
return (
<div>
<h3>Sidebar Assignments</h3>
<ul>
{announcements.map(announcement => (
<li key={announcement.id}>
<Link to={`/course/${this.props.params.courseId}/announcements/${announcement.id}`}>
{announcement.title}
</Link>
</li>
))}
</ul>
</div>
)
}
}
module.exports = AnnouncementsSidebar
|
__tests__/components/App-test.js
|
kylebyerly-hp/grommet
|
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React from 'react';
import renderer from 'react-test-renderer';
import App from '../../src/js/components/App';
// needed because this:
// https://github.com/facebook/jest/issues/1353
jest.mock('react-dom');
describe('App', () => {
it('has correct default options', () => {
const component = renderer.create(
<App><h2>App Body</h2></App>
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
it('has correct inline=true rendering', () => {
const component = renderer.create(
<App inline={true} />
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
it('has correct lang="pt=BR" rendering', () => {
const component = renderer.create(
<App lang='pt-BR' />
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
it('has correct className rendering', () => {
const component = renderer.create(
<App className='testing' />
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
it('has microdata properties rendering', () => {
const component = renderer.create(
<App itemScope={true} itemType="http://schema.org/Article"
itemProp="test"/>
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
});
|
packages/mcs-lite-ui/src/LandingHeader/LandingHeader.js
|
MCS-Lite/mcs-lite
|
/* global window */
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import rafThrottle from 'raf-throttle';
import getScrollTop from '../utils/getScrollTop';
const ZINDEX = 1;
export const Container = styled.header`
height: ${props => props.theme.height.header};
`;
export const Fixed = styled.div`
z-index: ${ZINDEX};
position: fixed;
top: 0;
left: 0;
right: 0;
background-color: ${props => props.theme.color.grayLight};
height: ${props => props.theme.height.header};
box-shadow: ${props =>
props.isTop ? 'none' : '0 1px 0 0 rgba(0, 0, 0, 0.05)'};
transition: box-shadow cubic-bezier(0.47, 0, 0.75, 0.72) 0.2s;
user-select: none;
`;
class LandingHeader extends React.PureComponent {
static propTypes = {
children: PropTypes.node.isRequired,
offset: PropTypes.number,
};
static defaultProps = {
offset: 40,
};
state = { isTop: true };
componentDidMount = () => {
window.addEventListener('scroll', this.onScroll);
this.onScroll();
};
componentWillUnmount = () => {
window.removeEventListener('scroll', this.onScroll);
this.onScroll.cancel();
};
onScroll = rafThrottle(() => {
this.setState({ isTop: getScrollTop() < this.props.offset });
});
render() {
const { children, ...otherProps } = this.props;
const { isTop } = this.state;
return (
<Container {...otherProps}>
<Fixed isTop={isTop}>{children}</Fixed>
</Container>
);
}
}
export default LandingHeader;
|
test/store.spec.js
|
pavelivanov/redaction
|
import React from 'react'
import Enzyme, { shallow } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import { createStore, combineReducers, connect } from '../lib'
Enzyme.configure({ adapter: new Adapter() })
describe('store', () => {
it('connect', () => {
const reducers = {
me: {
initialState: {
name: 'John Doe',
avatar: null,
stats: [
{ type: 'reviews', value: 10 },
{ type: 'orders', value: 20 },
],
}
},
set: (state, payload) => payload,
}
const store = createStore({
reducers: combineReducers(reducers),
initialState: {},
})
const ComponentView = () => (
<div />
)
const Component = connect({
me: 'me',
myStats: 'me.stats',
avatar: 'me.avatar',
})(ComponentView)
const component = shallow(<Component store={store} />).dive()
const props = component.props()
const expected = {
name: 'John Doe',
avatar: null,
stats: [
{ type: 'reviews', value: 10 },
{ type: 'orders', value: 20 },
],
}
expect(props.me).toEqual(expected)
expect(props.myStats).toEqual(expected.stats)
expect(props.avatar).toEqual(expected.avatar)
})
})
|
ui/app.js
|
JamenMarz/cluster
|
import React, { Component } from 'react';
import { Bar } from '.';
class App extends Component {
render() {
return (
<div className="app">
<Bar />
<div>{this.props.children}</div>
</div>
);
}
}
export default App;
|
src/svg-icons/social/school.js
|
kasra-co/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialSchool = (props) => (
<SvgIcon {...props}>
<path d="M5 13.18v4L12 21l7-3.82v-4L12 17l-7-3.82zM12 3L1 9l11 6 9-4.91V17h2V9L12 3z"/>
</SvgIcon>
);
SocialSchool = pure(SocialSchool);
SocialSchool.displayName = 'SocialSchool';
SocialSchool.muiName = 'SvgIcon';
export default SocialSchool;
|
actor-apps/app-web/src/app/components/modals/AddContact.react.js
|
v2tmobile/actor-platform
|
import _ from 'lodash';
import React from 'react';
import Modal from 'react-modal';
import pureRender from 'pure-render-decorator';
import { Styles, TextField, FlatButton } from 'material-ui';
import AddContactStore from 'stores/AddContactStore';
import AddContactActionCreators from 'actions/AddContactActionCreators';
import classNames from 'classnames';
import { KeyCodes } from 'constants/ActorAppConstants';
import ActorTheme from 'constants/ActorTheme';
const ThemeManager = new Styles.ThemeManager();
const appElement = document.getElementById('actor-web-app');
Modal.setAppElement(appElement);
const getStateFromStores = () => {
return {
isShown: AddContactStore.isModalOpen(),
message: AddContactStore.getMessage()
};
};
@pureRender
class AddContact extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
this.state = _.assign({
phone: ''
}, getStateFromStores());
AddContactStore.addChangeListener(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
textField: {
textColor: 'rgba(0,0,0,.87)',
focusColor: '#68a3e7',
backgroundColor: 'transparent',
borderColor: '#68a3e7'
}
});
}
componentWillUnmount() {
AddContactStore.removeChangeListener(this.onChange);
document.removeEventListener('keydown', this.onKeyDown, false);
}
render() {
const messageClassName = classNames({
'error-message': true,
'error-message--shown': this.state.message
});
return (
<Modal className="modal-new modal-new--add-contact"
closeTimeoutMS={150}
isOpen={this.state.isShown}
style={{width: 320}}>
<header className="modal-new__header">
<a className="modal-new__header__close modal-new__header__icon material-icons"
onClick={this.onClose}>clear</a>
<h3 className="modal-new__header__title">Add contact</h3>
</header>
<div className="modal-new__body">
<TextField className="login__form__input"
floatingLabelText="Phone number"
fullWidth
onChange={this.onPhoneChange}
type="text"
value={this.state.phone}/>
</div>
<span className={messageClassName}>{this.state.message}</span>
<footer className="modal-new__footer text-right">
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Add"
onClick={this.onAddContact}
secondary={true} />
</footer>
</Modal>
);
}
onClose = () => {
AddContactActionCreators.closeModal();
}
onPhoneChange = event => {
this.setState({phone: event.target.value});
}
onAddContact = () => {
AddContactActionCreators.findUsers(this.state.phone);
}
onChange = () => {
this.setState(getStateFromStores());
}
onKeyDown = (event) => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
}
}
export default AddContact;
|
packages/cf-builder-card/example/basic/component.js
|
koddsson/cf-ui
|
import React from 'react';
import { CardBuilder } from 'cf-builder-card';
import { Table, TableBody, TableRow, TableCell } from 'cf-component-table';
import { Button } from 'cf-component-button';
const EXAMPLE_CARD = 'EXAMPLE_CARD';
const MyButton = (
<Button type="default" onClick={() => console.log('Button clicked!')}>
Click me!
</Button>
);
const BuilderCard = () => (
<CardBuilder
cardName={EXAMPLE_CARD}
title="This is a Card"
description="This is the description of a card."
control={MyButton}
table={
<Table striped>
<TableBody>
<TableRow>
<TableCell>One</TableCell>
<TableCell>Two</TableCell>
</TableRow>
<TableRow>
<TableCell>Three</TableCell>
<TableCell>Four</TableCell>
</TableRow>
</TableBody>
</Table>
}
drawers={[
{
id: 'api',
name: 'API',
content: 'API Content'
},
{
id: 'help',
name: 'Help',
content: 'Help Content'
}
]}
/>
);
export default BuilderCard;
|
test/ImageSpec.js
|
egauci/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import ReactDOM from 'react-dom';
import Image from '../src/Image';
describe('Image', () => {
it('should be an image', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Image />
);
let image = ReactDOM.findDOMNode(instance);
image.nodeName.should.equal('IMG');
});
it('should provide src and alt prop', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Image src="image.jpg" alt="this is alt" />
);
let image = ReactDOM.findDOMNode(instance);
assert.equal(image.getAttribute('src'), 'image.jpg');
assert.equal(image.getAttribute('alt'), 'this is alt');
});
it('should have correct class when responsive prop is set', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Image responsive />
);
let imageClassName = ReactDOM.findDOMNode(instance).className;
imageClassName.should.match(/\bimg-responsive\b/);
});
it('should have correct class when rounded prop is set', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Image rounded />
);
let imageClassName = ReactDOM.findDOMNode(instance).className;
imageClassName.should.match(/\bimg-rounded\b/);
});
it('should have correct class when circle prop is set', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Image circle />
);
let imageClassName = ReactDOM.findDOMNode(instance).className;
imageClassName.should.match(/\bimg-circle\b/);
});
it('should have correct class when thumbnail prop is set', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Image thumbnail />
);
let imageClassName = ReactDOM.findDOMNode(instance).className;
imageClassName.should.match(/\bimg-thumbnail\b/);
});
});
|
PuppyPlayDate/UserEdit.js
|
Tooconfident/Puppy_PlayDate
|
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
TextInput,
View,
ListView,
NavigatorIOS,
Image,
TouchableHighlight
} from 'react-native';
import UserDogs from './UserDogs';
const styles = require('./style.js');
// URL to the API to get a specific user if you append an id
var REQUEST_URL = 'http://localhost:3000/users/';
class UserEdit extends Component {
constructor(props) {
super(props);
// Initialize Playdate Attributes
this.state = {
id: "",
username: "",
name: "",
email: "",
password: "",
loaded: false,
};
}
componentDidMount() {
// As soon as the component is mounted, go and fetch the data for the user
this.fetchData();
}
// Performs an Ajax call to retrieve information about the user
fetchData(){
console.log("fetchData: UserEdit: user_id " + this.props.user_id)
fetch(REQUEST_URL + this.props.user_id)
.then((response) => response.json())
.then((responseData) => {
// Update the state with the information about the playdate
this.setState({
id: responseData.id,
name: responseData.name,
username: responseData.username,
email: responseData.email,
loaded: true,
});
})
.done();
}
onPressEdit() {
// TODO: perform an update request to update the
// playdate information in the backend
fetch(REQUEST_URL + this.state.id, {
method: 'PATCH',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: this.state.username,
name: this.state.name,
email: this.state.email,
password: this.state.password,
})
})
.then((response) => response.json())
.then((responseData) => {
console.log(responseData)
if (responseData.success != false){
this.props.navigator.pop({
title: 'Profile',
component: UserDogs,
passProps: {
loaded: false,
},
});
} else {
AlertIOS.alert(
'Something went wrong!'
);
}
})
.done();
}
render() {
var user = this.state;
return (
<View style={styles.container}>
<View style={[styles.innerContainer, {justifyContent: 'flex-start', marginTop: 114}]}>
<TextInput
placeholder="Username"
style={styles.inputText}
value={user.username}
onChangeText={(text) => this.setState({username: text})}
/>
<TextInput
placeholder="Name"
style={styles.inputText}
value={user.name}
onChangeText={(text) => this.setState({name: text})}
/>
<TextInput
placeholder="Email"
style={styles.inputText}
value={user.email}
onChangeText={(text) => this.setState({email: text})}
/>
<TextInput
placeholder="Password"
style={styles.inputText}
value={user.password}
password={true}
onChangeText={(text) => this.setState({password: text})}
/>
<TouchableHighlight
style={styles.submitButton}
onPress={this.onPressEdit.bind(this)}
underlayColor='#99d9f4'
>
<Text style={styles.buttonText}>Edit</Text>
</TouchableHighlight>
</View>
</View>
);
}
}
// const styles = StyleSheet.create({
// container: {
// flex: 1,
// alignItems: 'center',
// justifyContent: 'center',
// },
// text: {
// fontSize: 40,
// },
// button: {
// height: 36,
// backgroundColor: "#48bbec",
// borderWidth: 1,
// borderRadius: 8,
// marginBottom: 10,
// alignSelf: "stretch",
// },
// buttonText: {
// fontSize: 18,
// color: "white",
// alignSelf: "center",
// },
// inputLabel: {
// fontWeight: 'bold',
// },
// inputText: {
// height: 30,
// borderColor: 'gray',
// borderWidth: 1,
// borderRadius: 16,
// padding: 10,
// backgroundColor: '#EBFAFF',
// marginBottom: 10,
// },
// textArea: {
// height: 100,
// },
// input: {
// height: 40,
// },
// pageTitle: {
// marginTop: 20,
// },
// title: {
// fontWeight: 'bold',
// fontSize: 20,
// },
// subtitle: {
// fontWeight: 'bold',
// fontSize: 14,
// },
// navbar: {
// flexDirection: 'row',
// justifyContent: 'space-around',
// marginTop: 20,
// backgroundColor: 'skyblue',
// marginBottom: 6,
// },
// });
module.exports = UserEdit;
|
src/components/List/ListItem.js
|
wfp/ui
|
import PropTypes from 'prop-types';
import React from 'react';
import classnames from 'classnames';
import Icon from '../Icon';
export const ListItem = ({ children, className, title, kind, ...other }) => {
const classNames = classnames('wfp--list__element', className, {
'wfp--list-item--checkmark': kind === 'checkmark',
'wfp--list-item--cross': kind === 'cross',
});
return (
<li className={classNames} {...other}>
{kind === 'cross' && (
<Icon
className="wfp--list-item__icon"
icon={{
styles: '',
viewBox: '0 0 320 512',
width: '15',
height: '15',
svgData: {
circles: '',
ellipses: '',
paths: [
{
fill: 'currentColor',
d:
'M207.6 256l107.72-107.72c6.23-6.23 6.23-16.34 0-22.58l-25.03-25.03c-6.23-6.23-16.34-6.23-22.58 0L160 208.4 52.28 100.68c-6.23-6.23-16.34-6.23-22.58 0L4.68 125.7c-6.23 6.23-6.23 16.34 0 22.58L112.4 256 4.68 363.72c-6.23 6.23-6.23 16.34 0 22.58l25.03 25.03c6.23 6.23 16.34 6.23 22.58 0L160 303.6l107.72 107.72c6.23 6.23 16.34 6.23 22.58 0l25.03-25.03c6.23-6.23 6.23-16.34 0-22.58L207.6 256z',
},
],
polygons: '',
polylines: '',
rects: '',
},
}}
/>
)}
{kind === 'checkmark' && (
<Icon
className="wfp--list-item__icon"
icon={{
styles: '',
viewBox: '0 0 512 512',
width: '13',
height: '13',
svgData: {
circles: '',
ellipses: '',
paths: [
{
fill: 'currentColor',
d:
'M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z',
},
],
polygons: '',
polylines: '',
rects: '',
},
}}
/>
)}
{title && <span className="wfp--list__element__title">{title}</span>}
<span className="wfp--list__element__content">{children}</span>
</li>
);
};
ListItem.propTypes = {
/**
* Provide multiple `ListItem` components
*/
children: PropTypes.node,
/**
* Specify a custom className
*/
className: PropTypes.string,
/**
* Specify a kind.
*/
kind: PropTypes.oneOf(['checkmark', 'cross']),
/**
* Specify if the List should be small
*/
small: PropTypes.bool,
};
export default ListItem;
|
app/index.js
|
lachok/react-starter
|
import 'react-hot-loader/patch'
import React from 'react'
import { render } from 'react-dom'
import './main.less'
import App from './App'
import { AppContainer } from 'react-hot-loader'
const renderApp = (AppComponent) => {
render(<AppContainer><AppComponent /></AppContainer>, document.getElementById('app'))
}
renderApp(App)
if (module.hot) {
module.hot.accept('./App', () => {
renderApp(require('./App').default)
})
}
|
packages/material-ui-icons/src/Battery20Sharp.js
|
lgollut/material-ui
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M7 17v5h10v-5H7z" /><path fillOpacity=".3" d="M17 4h-3V2h-4v2H7v13h10V4z" /></React.Fragment>
, 'Battery20Sharp');
|
pages/_document.js
|
AptoGen/AptoGen-Website
|
import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
import flush from 'styled-jsx/server';
import { COLORS } from '../lib/styles';
export default class MyDocument extends Document {
static getInitialProps({ renderPage }) {
const {
html, head, errorHtml, chunks
} = renderPage();
const styles = flush();
return {
html, head, errorHtml, chunks, styles,
};
}
render() {
return (
<html>
<Head>
{/* <link rel="stylesheet" href="/static/react-md.brown-deep_orange.min.css" /> */}
{/* <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto:300,400,500' /> */}
{/* <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Material+Icons' /> */}
<link href="https://fonts.googleapis.com/css?family=Catamaran:300,400,500,600,700,800|Exo:300,300i,400,400i,500,500i,600,600i|Gentium+Book+Basic:400,400i|Amata|Wire+One" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Great+Vibes|Marck+Script|Sacramento|Yellowtail" rel="stylesheet" />
<link rel="stylesheet" href="/static/css/base.css" />
</Head>
<body id="body">
{this.props.customValue}
<Main />
<NextScript />
</body>
<style jsx global>{`
#body {
margin: 0;
background-color: #fff;
font-size: 16px;
}
`}</style>
</html>
)
}
}
|
src/app/homelessness/HomelessnessSummary.js
|
cityofasheville/simplicity2
|
import React from 'react';
import PropTypes from 'prop-types';
import HomelessnessCounts from './HomelessnessCounts';
import HomelessnessDemographics from './HomelessnessDemographics';
import HomelessnessEnrollment from './HomelessnessEnrollment';
import PageHeader from '../../shared/PageHeader';
import ButtonGroup from '../../shared/ButtonGroup';
import LinkButton from '../../shared/LinkButton';
import Icon from '../../shared/Icon';
import { IM_BED } from '../../shared/iconConstants';
const HomelessnessSummary = props => (
<div>
<div className="row" style={{ marginTop: '15px' }}>
<div className="col-sm-12">
<div className="alert alert-danger h1" style={{ marginBottom: '0px' }}>
Warning: this dashboard is out of date! We're working on updating and refreshing it. Please contact help@ashevillenc.gov if you have any questions.
</div>
</div>
</div>
<PageHeader
h1="Homelessness in Asheville / Buncombe County"
dataLinkPath="/homelessness/data"
externalLink="http://www.ashevillenc.gov/civicax/filebank/blobdload.aspx?blobid=27777"
externalLinkText="Five Year Strategic Plan on Homelessness in Buncombe County"
icon={<Icon path={IM_BED} size={50} />}
>
<ButtonGroup alignment="">
<LinkButton pathname="/homelessness" query={{ entity: props.location.query.entity, id: props.location.query.id, label: props.location.query.label, hideNavbar: props.location.query.hideNavbar }} active positionInGroup="left">Overview</LinkButton>
<LinkButton pathname="/homelessness/veterans" query={{ entity: props.location.query.entity, id: props.location.query.id, label: props.location.query.label, hideNavbar: props.location.query.hideNavbar }} positionInGroup="right">Veterans</LinkButton>
</ButtonGroup>
</PageHeader>
<div className="row" style={{ marginTop: '15px' }}>
<div className="col-sm-12">
<a href="http://www.nc211.org" title="NC 211 homelessness resourses" target="_blank">
<div className="alert alert-warning" style={{ marginBottom: '0px' }}>
Are you homeless? Do you need help finding housing? Click here for resources.
</div>
</a>
</div>
</div>
<div className="row">
<div className="col-sm-12">
<HomelessnessCounts />
</div>
</div>
<hr />
<div className="row">
<div className="col-sm-12">
<HomelessnessDemographics />
</div>
</div>
<hr />
<div className="row">
<div className="col-sm-12">
<h2>What is being done about homelessness?</h2>
<p>
The Homeless Initiative Advisory Committee (HIAC), a joint committee of the City of Asheville and Buncombe County in North Carolina, completed a Five Year Strategic Plan on Homelessness for the Buncombe County Continuum of Care (NC-501) following a year of intensive planning and collaboration throughout the entire community. The City of Asheville and Buncombe County unanimously voted to adopt the Asheville-Buncombe Homeless Initiative Advisory Committee’s <a className="inText" href="http://www.ashevillenc.gov/civicax/filebank/blobdload.aspx?blobid=27777" target="_blank">Five Year Strategic Plan on Homelessness in Buncombe County</a> in the spring of 2017.
</p>
</div>
</div>
<div className="row">
<div className="col-sm-12">
<HomelessnessEnrollment />
</div>
</div>
</div>
);
HomelessnessSummary.propTypes = {
location: PropTypes.object, // eslint-disable-line react/forbid-prop-types
};
export default HomelessnessSummary;
|
investninja-web-ui-admin/src/components/Header/Header.js
|
InvestNinja/InvestNinja-web-ui
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import {
Nav,
NavItem,
NavDropdown,
MenuItem,
ProgressBar,
} from 'react-bootstrap';
import Navbar, {Brand} from 'react-bootstrap/lib/Navbar';
import history from '../../core/history';
import $ from "jquery";
import Sidebar from '../Sidebar';
const logo = require('./logo.png');
function Header() {
return (
<div id="wrapper" className="content">
<Navbar fluid={true} style={ {margin: 0} }>
<Brand>
<span>
<img src={logo} alt="Start React" title="Start React" />
<span> SB Admin React - </span>
<a href="http://startreact.com/" title="Start React" rel="home">StartReact.com</a>
<button type="button" className="navbar-toggle" onClick={() => {toggleMenu();}} style={{position: 'absolute', right: 0, top: 0}}>
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
</span>
</Brand>
<ul className="nav navbar-top-links navbar-right">
<NavDropdown bsClass="dropdown" title={<span><i className="fa fa-envelope fa-fw"></i></span>} id="navDropdown1">
<MenuItem style={ {width: 300} } eventKey="1">
<div> <strong>John Smith</strong> <span className="pull-right text-muted"> <em>Yesterday</em> </span> </div>
<div> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="2">
<div> <strong>John Smith</strong> <span className="pull-right text-muted"> <em>Yesterday</em> </span> </div>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="3">
<div> <strong>John Smith</strong> <span className="pull-right text-muted"> <em>Yesterday</em> </span> </div>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="4" className="text-center">
<strong>Read All Messages</strong> <i className="fa fa-angle-right"></i>
</MenuItem>
</NavDropdown>
<NavDropdown title={<span><i className="fa fa-tasks fa-fw"></i> </span>} id = 'navDropdown2222'>
<MenuItem eventKey="1" style={ {width: 300} }>
<div>
<p> <strong>Task 1</strong> <span className="pull-right text-muted">40% Complete</span> </p>
<div>
<ProgressBar bsStyle="success" now={40} />
</div>
</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="2">
<div>
<p> <strong>Task 2</strong> <span className="pull-right text-muted">20% Complete</span> </p>
<div>
<ProgressBar bsStyle="info" now={20} />
</div>
</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="3">
<div>
<p> <strong>Task 3</strong> <span className="pull-right text-muted">60% Complete</span> </p>
<div>
<ProgressBar bsStyle="warning" now={60} />
</div>
</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="4">
<div>
<p> <strong>Task 4</strong> <span className="pull-right text-muted">80% Complete</span> </p>
<div>
<ProgressBar bsStyle="danger" now={80} />
</div>
</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="5">
<strong>See All Tasks</strong> <i className="fa fa-angle-right"></i>
</MenuItem>
</NavDropdown>
<NavDropdown title={<i className="fa fa-bell fa-fw"></i>} id = 'navDropdown3'>
<MenuItem eventKey="1" style={ {width: 300} }>
<div> <i className="fa fa-comment fa-fw"></i> New Comment <span className="pull-right text-muted small">4 minutes ago</span> </div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="2">
<div> <i className="fa fa-twitter fa-fw"></i> 3 New Followers <span className="pull-right text-muted small">12 minutes ago</span> </div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="3">
<div> <i className="fa fa-envelope fa-fw"></i> Message Sent <span className="pull-right text-muted small">4 minutes ago</span> </div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="4">
<div> <i className="fa fa-tasks fa-fw"></i> New Task <span className="pull-right text-muted small">4 minutes ago</span> </div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="5">
<div> <i className="fa fa-upload fa-fw"></i> Server Rebooted <span className="pull-right text-muted small">4 minutes ago</span> </div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="6">
<strong>See All Alerts</strong> <i className="fa fa-angle-right"></i>
</MenuItem>
</NavDropdown>
<NavDropdown title={<i className="fa fa-user fa-fw"></i> } id = 'navDropdown4'>
<MenuItem eventKey="1">
<span> <i className="fa fa-user fa-fw"></i> User Profile </span>
</MenuItem>
<MenuItem eventKey="2">
<span><i className="fa fa-gear fa-fw"></i> Settings </span>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey = "3" href = 'http://www.strapui.com' >
<span> <i className = "fa fa-eye fa-fw" /> Premium React Themes </span>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey = "4" onClick = {(event) => { history.push('/login');}}>
<span> <i className = "fa fa-sign-out fa-fw" /> Logout </span>
</MenuItem>
</NavDropdown>
</ul>
<Sidebar />
</Navbar>
</div>
);
}
function toggleMenu(){
if($(".navbar-collapse").hasClass('collapse')){
$(".navbar-collapse").removeClass('collapse');
}
else{
$(".navbar-collapse").addClass('collapse');
}
}
export default Header;
|
frontend/src/Settings/Profiles/Metadata/ReleaseStatusItems.js
|
lidarr/Lidarr
|
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import FormGroup from 'Components/Form/FormGroup';
import FormInputHelpText from 'Components/Form/FormInputHelpText';
import FormLabel from 'Components/Form/FormLabel';
import ReleaseStatusItem from './ReleaseStatusItem';
import styles from './TypeItems.css';
class ReleaseStatusItems extends Component {
//
// Render
render() {
const {
metadataProfileItems,
errors,
warnings,
...otherProps
} = this.props;
return (
<FormGroup>
<FormLabel>Release Statuses</FormLabel>
<div>
{
errors.map((error, index) => {
return (
<FormInputHelpText
key={index}
text={error.message}
isError={true}
isCheckInput={false}
/>
);
})
}
{
warnings.map((warning, index) => {
return (
<FormInputHelpText
key={index}
text={warning.message}
isWarning={true}
isCheckInput={false}
/>
);
})
}
<div className={styles.albumTypes}>
{
metadataProfileItems.map(({ allowed, releaseStatus }, index) => {
return (
<ReleaseStatusItem
key={releaseStatus.id}
albumTypeId={releaseStatus.id}
name={releaseStatus.name}
allowed={allowed}
sortIndex={index}
{...otherProps}
/>
);
})
}
</div>
</div>
</FormGroup>
);
}
}
ReleaseStatusItems.propTypes = {
metadataProfileItems: PropTypes.arrayOf(PropTypes.object).isRequired,
errors: PropTypes.arrayOf(PropTypes.object),
warnings: PropTypes.arrayOf(PropTypes.object),
formLabel: PropTypes.string
};
ReleaseStatusItems.defaultProps = {
errors: [],
warnings: []
};
export default ReleaseStatusItems;
|
components/scenes/stairs.js
|
dbow/89-steps
|
import React from 'react';
class Stairs extends React.Component {
render() {
return (
<div>
<h2>The Stairs</h2>
<p>This will be good!!</p>
</div>
);
}
}
export default Stairs;
|
src/components/AnimatedWrapper/AnimatedWrapper.js
|
denichodev/personal-web
|
import React, { Component } from 'react';
import * as Animated from 'animated/lib/targets/react-dom';
const AnimatedWrapper = WrappedComponent =>
class AnimatedWrapper extends Component {
constructor(props) {
super(props);
this.state = {
animate: new Animated.Value(0)
};
}
componentWillAppear(cb) {
Animated.spring(this.state.animate, { toValue: 1 }).start();
cb();
}
componentWillEnter(cb) {
setTimeout(
() => Animated.spring(this.state.animate, { toValue: 1 }).start(),
250
);
cb();
}
componentWillLeave(cb) {
Animated.spring(this.state.animate, { toValue: 0 }).start();
setTimeout(() => cb(), 175);
}
render() {
const style = {
opacity: Animated.template`${this.state.animate}`,
transform: Animated.template`
translate3d(0,${this.state.animate.interpolate({
inputRange: [0, 1],
outputRange: ['12px', '0px']
})},0)
`
};
return (
<Animated.div style={style} className="animated-page-wrapper">
<WrappedComponent {...this.props} />
</Animated.div>
);
}
};
export default AnimatedWrapper;
|
cm19/ReactJS/your-first-react-app-exercises-master/exercise-16/shared/Card.js
|
Brandon-J-Campbell/codemash
|
import React from 'react';
import classNames from 'classnames';
import theme from '../theme/static';
import styles from './Card.css';
export default function Card({ children }) {
return (
<div className={classNames(styles.card, styles[theme])}>{children}</div>
);
}
|
client/views/room/components/MessageTemplate/Header.js
|
VoiSmart/Rocket.Chat
|
import { Box, Margins } from '@rocket.chat/fuselage';
import React from 'react';
function Header({ children }) {
return (
<Box rcx-message__header display='flex' flexGrow={0} flexShrink={1} withTruncatedText>
<Box
mi='neg-x2'
display='flex'
flexDirection='row'
alignItems='baseline'
withTruncatedText
flexGrow={1}
flexShrink={1}
>
<Margins inline='x2'> {children} </Margins>
</Box>
</Box>
);
}
export default Header;
|
src/routes.js
|
dorono/wecansavedemocracy
|
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './containers/app';
import ActivitiesList from './containers/ActivitiesList/activities_index';
import ActivitiesNew from './containers/ActivitiesNew/activities_new';
import FindRep from './containers/FindRep/findRepresentative';
export default (
<Route path="/" component={App}>
<IndexRoute component={ActivitiesList} />
<Route path="actions/new" component={ActivitiesNew} />
<Route path="find-representative" component={FindRep} />
</Route>
);
|
src/views/DashboardManager/components/widgets/BtnControlWidget.js
|
giux78/daf-dataportal
|
import React from 'react';
import {Modal} from 'react-modal-bootstrap';
import App from '../InfinityScrollWidgets/App.js'
class BtnControlWidget extends React.Component {
constructor() {
super();
this.state = {
isModalAddOpen: false,
isModalOpen: false
}
this.addWidgetOpenModal = this.addWidgetOpenModal.bind(this)
this.addWidget = this.addWidget.bind(this)
this.openModal = this.openModal.bind(this)
this.closeModal = this.closeModal.bind(this)
}
moveDown = function(index) {
let rows = this.props.layout.rows;
let from = index;
let to = index + 1;
rows.splice(to, 0, rows.splice(from, 1)[0]);
this.props.setLayout(this.props.layout);
}
moveUp = function(index) {
let rows = this.props.layout.rows;
let from = index;
let to = index - 1;
rows.splice(to, 0, rows.splice(from, 1)[0]);
this.props.setLayout(this.props.layout);
}
removeCol = function () {
let rows = this.props.layout.rows;
let row = rows[this.props.index]
let columns = row.columns;
for(let i=0; i < columns.length; i++) {
let column = columns[i];
if(column.widgets){
for(let j=0; j < column.widgets.length; j++) {
let widget = column.widgets[j];
if(widget.key !='BtnControlWidget_0'){
let widgetsArr = this.props.dashboardWidgets;
if(widgetsArr[widget.key]){
delete widgetsArr[widget.key];
}
}
}
}
}
rows.splice(this.props.index, 1);
this.props.setLayout(this.props.layout, true);
}
openModal = function(e){
e.stopPropagation();
e.preventDefault();
e.nativeEvent.stopImmediatePropagation();
this.setState({
isModalOpen: true
})
}
closeModal = function (){
this.setState({
isModalOpen: false
})
}
addWidgetOpenModal = function() {
this.setState({
isModalAddOpen: true
});
}
addWidget = function(widgetName) {
this.props.addWidget(widgetName, this.props.index);
this.onRequestClose();
}
onRequestClose = () => {
this.setState({
isModalAddOpen: false,
});
}
setCol = function (size, index, align) {
let sizeClass = "col-xs-12";
//set size class
if (size == 1) {
sizeClass = "col-lg-12 col-md-12 col-sm-12 col-xs-12";
} else if (size == 2) {
sizeClass = "col-lg-6 col-md-6 col-sm-6 col-xs-6";
} else if (size == 3) {
sizeClass = "col-lg-4 col-md-4 col-sm-4 col-xs-4";
} else if (size == 4) {
sizeClass = "col-lg-3 col-md-3 col-sm-3 col-xs-3";
}
//add or remove columns on row
let max = size;
if (max < this.props.layout.rows[index].columns.length) {
max = this.props.layout.rows[index].columns.length;
}
let control = this.props.layout.rows[index].columns.pop();
for(let i=0; i < max; i++) {
//set column 30/70
if (size == 2 && align == 1 && i == 0) {
sizeClass = "col-lg-4 col-md-4 col-sm-4 col-xs-4";
}
if (size == 2 && align == 1 && i == 1) {
sizeClass = "col-lg-8 col-md-8 col-sm-8 col-xs-8";
}
//set column 70/30
if (size == 2 && align == 2 && i == 1) {
sizeClass = "col-lg-4 col-md-4 col-sm-4 col-xs-4";
}
if (size == 2 && align == 2 && i == 0) {
sizeClass = "col-lg-8 col-md-8 col-sm-8 col-xs-8";
}
if (i <= size) {
//crea colonna
if (!this.props.layout.rows[index].columns[i]) {
this.props.layout.rows[index].columns[i] = {
className: sizeClass,
widgets: []
}
} else {
//update size col
this.props.layout.rows[index].columns[i].className=sizeClass;
}
}
//rimuovi colonna
if (i >= size && this.props.layout.rows[index].columns[i]) {
this.props.layout.rows[index].columns.splice(i);
}
}
this.props.layout.rows[index].columns.push(control);
this.props.setLayout(this.props.layout, true);
this.closeModal();
}
render() {
return (
<div className="btn-control-widget">
<button type="button" className="btn btn-sm btn-gray-200" aria-label="Add Widget"
onClick={this.addWidgetOpenModal}>
<span className="fa fa-plus" aria-hidden="true"></span>
</button>
{ this.props.index != 0 &&
<button type="button" className="btn btn-sm btn-gray-200" aria-label="Move Up"
onClick={() => this.moveUp(this.props.index)}>
<span className="fa fa-chevron-up" aria-hidden="true"></span>
</button>
}
{ this.props.index != this.props.layout.rows.length - 1 &&
<button type="button" className="btn btn-sm btn-gray-200" aria-label="Move Down"
onClick={() => this.moveDown(this.props.index)}>
<span className="fa fa-chevron-down" aria-hidden="true"></span>
</button>
}
<button type="button" className="btn btn-sm btn-gray-200" aria-label="Remove"
onClick={() => this.removeCol()}>
<span className="fa fa-trash" aria-hidden="true"></span>
</button>
<button type="button" className="btn btn-sm btn-gray-200" aria-label="Change witdh"
onClick={this.openModal}>
<span className="fa fa-edit" aria-hidden="true"></span>
</button>
<App
widgets={this.props.widgets}
isModalOpen={this.state.isModalAddOpen}
onWidgetSelect={this.addWidget}
onRequestClose={this.onRequestClose}
/>
<Modal
contentLabel="Set width columns"
className="Modal__Bootstrap modal-dialog"
isOpen={this.state.isModalOpen}>
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" onClick={this.closeModal}>
<span aria-hidden="true">×</span>
<span className="sr-only">Close</span>
</button>
<h4 className="modal-title">Scegli il layout</h4>
</div>
<div className="modal-body">
<div className="row p-s-10">
<div className="layout-container col-xs-4 col-sm-4 col-md-4 col-lg-4">
<div className="row layout-box" onClick={() => this.setCol(1, this.props.index)}>
<div className="col-xs-12 col-sm-12 col-md-12 col-lg-12">
100%
</div>
</div>
</div>
<div className="layout-container col-xs-4 col-sm-4 col-md-4 col-lg-4">
<div className="row layout-box" onClick={() => this.setCol(3, this.props.index)}>
<div className="col-xs-4 col-sm-4 col-md-4 col-lg-4">
33%
</div>
<div className="col-xs-4 col-sm-4 col-md-4 col-lg-4">
33%
</div>
<div className="col-xs-4 col-sm-4 col-md-4 col-lg-4">
33%
</div>
</div>
</div>
<div className="layout-container col-xs-4 col-sm-4 col-md-4 col-lg-4">
<div className="row layout-box" onClick={() => this.setCol(4, this.props.index)}>
<div className="col-xs-3 col-sm-3 col-md-3 col-lg-3">
25%
</div>
<div className="col-xs-3 col-sm-3 col-md-3 col-lg-3">
25%
</div>
<div className="col-xs-3 col-sm-3 col-md-3 col-lg-3">
25%
</div>
<div className="col-xs-3 col-sm-3 col-md-3 col-lg-3">
25%
</div>
</div>
</div>
</div>
<div className="row p-s-10">
<div className="layout-container col-xs-4 col-sm-4 col-md-4 col-lg-4">
<div className="row layout-box" onClick={() => this.setCol(2, this.props.index, 1)}>
<div className="col-xs-4 col-sm-4 col-md-4 col-lg-4">
30%
</div>
<div className="col-xs-8 col-sm-8 col-md-8 col-lg-8">
70%
</div>
</div>
</div>
<div className="layout-container col-xs-4 col-sm-4 col-md-4 col-lg-4">
<div className="row layout-box" onClick={() => this.setCol(2, this.props.index)}>
<div className="col-xs-6 col-sm-6 col-md-6 col-lg-6">
50%
</div>
<div className="col-xs-6 col-sm-6 col-md-6 col-lg-6">
50%
</div>
</div>
</div>
<div className="layout-container col-xs-4 col-sm-4 col-md-4 col-lg-4">
<div className="row layout-box" onClick={() => this.setCol(2, this.props.index, 2)}>
<div className="col-xs-8 col-sm-8 col-md-8 col-lg-8">
70%
</div>
<div className="col-xs-4 col-sm-4 col-md-4 col-lg-4">
30%
</div>
</div>
</div>
</div>
</div>
<div className="modal-footer">
<button onClick={this.closeModal} type="button" className="btn btn-gray-200" >Chiudi</button>
</div>
</div>
</Modal>
</div>
);
}
}
export default BtnControlWidget;
|
src/routes.js
|
yangli1990/Isomorphic-Universal-React-Template
|
import React from 'react';
import App from './Components/App';
import { Route } from 'react-router';
import Counter from './Components/Counter/Counter';
export default <Route path="/" component={App}>
<Route path="counter" component={Counter} />
</Route>;
|
src/components/AbstractSystemComponent.js
|
brochington/Akkad
|
import React from 'react';
import _ from 'lodash';
// import Immutable from 'immutable';
class AbstractSystemComponent extends React.Component {
constructor(props, context) {
super(props, context);
this.id = Math.floor((1 + Math.random()) * 10000000000).toString(16);
this._propsChanged = true;
}
static abstractType = "AbstractSystemComponent";
static contextTypes = {
appState: React.PropTypes.object,
actions: React.PropTypes.object,
entityID: React.PropTypes.string
}
/**
* Accepts a non-complex map of props, and compares it to the previous batch.
* Needed because hot reloading doesn't always trigger shouldComponentUpdate().
*/
/* eslint-disable */
propsChanged = (nextProps) => {
// const InextProps = Immutable.Map(nextProps);
// const areSame = Immutable.is(this.oldProps, InextProps);
//
// this.oldProps = InextProps;
//
// return areSame;
this._propsChanged = !_.isEqual(nextProps, this.props);
return this._propsChanged;
}
/* eslint-enable */
render() {
// return this.props.children ? this.props.children : null;
return this.props.children ? (
<div>
{this.props.children}
</div>
) : null;
}
}
export default AbstractSystemComponent;
|
client/components/error/ServerError.js
|
andela-jmacharia/hati-DMS
|
import React from 'react';
import { Route } from 'react-router';
import AppError from './AppError';
const ServerError = () => (
<AppError>
<center>
<h2 className="title">The Proverbial Internal Server Error :/</h2>
<div className="container-fluid">
<p>The minions broke something :(</p>
<p>Go back maybe? <i className="material-icons">mood</i></p>
<button type="button" className="btn btn-block"><Route path="/">HOME</Route></button>
</div>
</center>
</AppError>
);
export default ServerError;
|
src/parser/rogue/shared/azeritetraits/SharpenedBlades.js
|
FaideWW/WoWAnalyzer
|
import React from 'react';
import { formatNumber } from 'common/format';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import SPECS from 'game/SPECS';
import Analyzer from 'parser/core/Analyzer';
class SharpenedBlades extends Analyzer {
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTrait(SPELLS.SHARPENED_BLADES.id);
this.wastedStacks = 0;
if(this.selectedCombatant.spec === SPECS.ASSASSINATION_ROGUE) {
this.sharpenedBladesConsumer = SPELLS.POISONED_KNIFE;
} else {
this.sharpenedBladesConsumer = SPELLS.SHURIKEN_TOSS;
}
}
on_byPlayer_cast(event) {
if (event.ability.guid !== SPELLS.MELEE.id) {
return;
}
const buff = this.selectedCombatant.getBuff(SPELLS.SHARPENED_BLADES_BUFF.id);
if(buff !== undefined && buff.stacks === 30) {
this.wastedStacks++;
}
}
get wastedStacksPm() {
return this.wastedStacks / (this.owner.fightDuration / 1000) * 60;
}
get suggestionThresholds() {
return {
actual: this.wastedStacksPm,
isGreaterThan: {
minor: 10,
average: 20,
major: 30,
},
};
}
suggestions(when) {
when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => {
return suggest(<>You are wasting <SpellLink id={SPELLS.SHARPENED_BLADES.id} icon /> stacks. Try to cast <SpellLink id={this.sharpenedBladesConsumer.id} icon /> at 29+ stacks.</>)
.icon(SPELLS.SHARPENED_BLADES.icon)
.actual(`${formatNumber(this.wastedStacksPm)} stacks wasted per minute.`)
.recommended(`<10 is recommended`);
});
}
}
export default SharpenedBlades;
|
node_modules/babel-plugin-react-transform/test/fixtures/code-class-extends-component-with-render-method/expected.js
|
lzm854676408/big-demo
|
import _transformLib from 'transform-lib';
const _components = {
Foo: {
displayName: 'Foo'
}
};
const _transformLib2 = _transformLib({
filename: '%FIXTURE_PATH%',
components: _components,
locals: [],
imports: []
});
function _wrapComponent(id) {
return function (Component) {
return _transformLib2(Component, id);
};
}
import React, { Component } from 'react';
const Foo = _wrapComponent('Foo')(class Foo extends Component {
render() {}
});
|
src/ButtonInput.js
|
xiaoking/react-bootstrap
|
import React from 'react';
import Button from './Button';
import FormGroup from './FormGroup';
import InputBase from './InputBase';
import childrenValueValidation from './utils/childrenValueInputValidation';
class ButtonInput extends InputBase {
renderFormGroup(children) {
let {bsStyle, value, ...other} = this.props;
return <FormGroup {...other}>{children}</FormGroup>;
}
renderInput() {
let {children, value, ...other} = this.props;
let val = children ? children : value;
return <Button {...other} componentClass="input" ref="input" key="input" value={val} />;
}
}
ButtonInput.types = ['button', 'reset', 'submit'];
ButtonInput.defaultProps = {
type: 'button'
};
ButtonInput.propTypes = {
type: React.PropTypes.oneOf(ButtonInput.types),
bsStyle() {
// defer to Button propTypes of bsStyle
return null;
},
children: childrenValueValidation,
value: childrenValueValidation
};
export default ButtonInput;
|
scripts/components/App.js
|
LulzAugusto/catch-of-the-day
|
/*
App
*/
import React from 'react';
import Rebase from 're-base';
const base = Rebase.createClass('https://catch-of-the-day-lulz.firebaseio.com/');
import Catalyst from 'react-catalyst';
import sampleFishes from '../sample-fishes';
import Inventory from './Inventory';
import Order from './Order';
import Header from './Header';
import Fish from './Fish';
var App = React.createClass({
mixins: [Catalyst.LinkedStateMixin],
getInitialState: function() {
return {
fishes: {},
order: {}
};
},
componentDidMount: function() {
base.syncState(this.props.params.storeId + '/fishes', {
context: this,
state: 'fishes'
});
var state = localStorage.getItem('order-' + this.props.params.storeId);
if (state) {
this.setState({ order: JSON.parse(state) });
}
},
componentWillUpdate: function(nextProps, nextState) {
localStorage.setItem('order-' + this.props.params.storeId, JSON.stringify(nextState.order));
},
addToOrder: function(key) {
this.state.order[key] = this.state.order[key] + 1 || 1;
this.setState({ order: this.state.order });
},
removeFromOrder: function(key) {
delete this.state.order[key];
this.setState({ order: this.state.order });
},
addFish: function(fish) {
var timestamp = new Date().getTime();
this.state.fishes['fish-' + timestamp] = fish;
this.setState({ fishes: this.state.fishes });
},
removeFish: function(key) {
if (confirm('Are you sure you wanto to remove this fish?!')) {
this.state.fishes[key] = null;
this.setState({ fishes: this.state.fishes });
}
},
loadSamples: function() {
this.setState({ fishes: sampleFishes });
},
renderFish: function(key) {
return <Fish key={key} index={key} details={this.state.fishes[key]} addToOrder={this.addToOrder}/>
},
render: function() {
return (
<div className="catch-of-the-day">
<div className="menu">
<Header tagline="Fresh Seafod Market"/>
<ul className="list-of-fishes">
{Object.keys(this.state.fishes).map(this.renderFish)}
</ul>
</div>
<Order order={this.state.order} fishes={this.state.fishes} removeFromOrder={this.removeFromOrder}/>
<Inventory fishes={this.state.fishes} addFish={this.addFish} loadSamples={this.loadSamples} linkState={this.linkState} removeFish={this.removeFish} />
</div>
)
}
});
export default App;
|
modules/Redirect.js
|
leeric92/react-router
|
import React from 'react';
import invariant from 'invariant';
import { createRouteFromReactElement } from './RouteUtils';
import { formatPattern } from './URLUtils';
import { falsy } from './PropTypes';
var { string, object } = React.PropTypes;
export var Redirect = React.createClass({
statics: {
createRouteFromReactElement(element) {
var route = createRouteFromReactElement(element);
if (route.from)
route.path = route.from;
route.onEnter = function (nextState, transition) {
var { location, params } = nextState;
var pathname = route.to ? formatPattern(route.to, params) : location.pathname;
transition.to(
pathname,
route.query || location.query,
route.state || location.state
);
};
return route;
}
},
propTypes: {
path: string,
from: string, // Alias for path
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
render() {
invariant(
false,
'<Redirect> elements are for router configuration only and should not be rendered'
);
}
});
export default Redirect;
|
local-cli/templates/HelloWorld/App.js
|
Bhullnatik/react-native
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View
} from 'react-native';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' +
'Cmd+D or shake for dev menu',
android: 'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
export default class App extends Component<{}> {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit App.js
</Text>
<Text style={styles.instructions}>
{instructions}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
|
src/Navigation.js
|
wangliguang/myRNTools
|
import React, { Component } from 'react';
import { StackNavigator } from 'react-navigation';
import { useAPIWeaver } from './tools/API/API.js';
import {
initNetEventListener,
} from './tools/API/NetManager.js';
import {
registerNavigator,
unRegisterNavigator,
InitailRoute,
getRouteMap,
} from './Route';
initNetEventListener();
// HomePage: { screen: HomePage, navigationOptions: ({navigation}) => StackOptions({navigation}) },
// GGTimer: { screen: GGTimerScene, navigationOptions: ({navigation}) => StackOptions({navigation})},
// GGLimitDoubleClickBtn: { screen: GGLimitDoubleClickBtnScene, navigationOptions: ({navigation}) => StackOptions({navigation}) },
// Storage: { screen: StorageScene, navigationOptions: ({navigation}) => StackOptions({navigation})},
// keyBoard: { screen: KeyBoardScene, navigationOptions: ({navigation}) => StackOptions({navigation})},
// TypeTab: { screen: TypeTabScene, navigationOptions: ({navigation}) => StackOptions({navigation})},
// FirstScene: { screen: FirstScene, navigationOptions: ({navigation}) => StackOptions({navigation})},
// ScendScene: { screen: ScendScene, navigationOptions: ({navigation}) => StackOptions({navigation})},
// ThirdScene: { screen: ThirdScene, navigationOptions: ({navigation}) => StackOptions({navigation})},
// StackOptions = (navigator) => {
// registerNavigator(navigator);
// }
// 注册导航
const AppNavigator = StackNavigator(
getRouteMap(),
{
initialRouteName: InitailRoute.routeName, // 默认显示界面
navigationOptions: { header: null },
mode: 'card', // 页面切换模式, 左右是card(相当于iOS中的push效果), 上下是modal(相当于iOS中的modal效果)
headerMode: 'screen', // 导航栏的显示模式, screen: 有渐变透明效果, float: 无透明效果, none: 隐藏导航栏
onTransitionEnd: (() => {
if (global.scenes) {
const currentScene = global.scenes[global.scenes.length - 1];
if (currentScene.componentWillAppear) {
currentScene.componentWillAppear();
}
}
}),
});
class App extends React.Component {
componentDidMount(){
registerNavigator(this.navigator);
}
componentWillUnmount() {
unRegisterNavigator();
}
render() {
return (
<AppNavigator
ref={nav => { this.navigator = nav; }}
/>
);
}
}
export default App;
|
fields/types/html/HtmlField.js
|
BlakeRxxk/keystone
|
import _ from 'underscore';
import Field from '../Field';
import React from 'react';
import tinymce from 'tinymce';
import { FormInput } from 'elemental';
/**
* TODO:
* - Remove dependency on underscore
*/
var lastId = 0;
function getId() {
return 'keystone-html-' + lastId++;
}
module.exports = Field.create({
displayName: 'HtmlField',
getInitialState () {
return {
id: getId(),
isFocused: false
};
},
initWysiwyg () {
if (!this.props.wysiwyg) return;
var self = this;
var opts = this.getOptions();
opts.setup = function (editor) {
self.editor = editor;
editor.on('change', self.valueChanged);
editor.on('focus', self.focusChanged.bind(self, true));
editor.on('blur', self.focusChanged.bind(self, false));
};
this._currentValue = this.props.value;
tinymce.init(opts);
},
componentDidUpdate (prevProps, prevState) {
if (prevState.isCollapsed && !this.state.isCollapsed) {
this.initWysiwyg();
}
if (_.isEqual(this.props.dependsOn, this.props.currentDependencies)
&& !_.isEqual(this.props.currentDependencies, prevProps.currentDependencies)) {
var instance = tinymce.get(prevState.id);
if (instance) {
tinymce.EditorManager.execCommand('mceRemoveEditor', true, prevState.id);
this.initWysiwyg();
} else {
this.initWysiwyg();
}
}
},
componentDidMount () {
this.initWysiwyg();
},
componentWillReceiveProps (nextProps) {
if (this.editor && this._currentValue !== nextProps.value) {
this.editor.setContent(nextProps.value);
}
},
focusChanged (focused) {
this.setState({
isFocused: focused
});
},
valueChanged () {
var content;
if (this.editor) {
content = this.editor.getContent();
} else if (this.refs.editor) {
content = this.refs.editor.getDOMNode().value;
} else {
return;
}
this._currentValue = content;
this.props.onChange({
path: this.props.path,
value: content
});
},
getOptions () {
var plugins = ['code', 'link'],
options = _.defaults(
{},
this.props.wysiwyg,
Keystone.wysiwyg.options
),
toolbar = options.overrideToolbar ? '' : 'bold italic | alignleft aligncenter alignright | bullist numlist | outdent indent | link',
i;
if (options.enableImages) {
plugins.push('image');
toolbar += ' | image';
}
if (options.enableCloudinaryUploads || options.enableS3Uploads) {
plugins.push('uploadimage');
toolbar += options.enableImages ? ' uploadimage' : ' | uploadimage';
}
if (options.additionalButtons) {
var additionalButtons = options.additionalButtons.split(',');
for (i = 0; i < additionalButtons.length; i++) {
toolbar += (' | ' + additionalButtons[i]);
}
}
if (options.additionalPlugins) {
var additionalPlugins = options.additionalPlugins.split(',');
for (i = 0; i < additionalPlugins.length; i++) {
plugins.push(additionalPlugins[i]);
}
}
if (options.importcss) {
plugins.push('importcss');
var importcssOptions = {
content_css: options.importcss,
importcss_append: true,
importcss_merge_classes: true
};
_.extend(options.additionalOptions, importcssOptions);
}
if (!options.overrideToolbar) {
toolbar += ' | code';
}
var opts = {
selector: '#' + this.state.id,
toolbar: toolbar,
plugins: plugins,
menubar: options.menubar || false,
skin: options.skin || 'keystone'
};
if (this.shouldRenderField()) {
opts.uploadimage_form_url = options.enableS3Uploads ? '/keystone/api/s3/upload' : '/keystone/api/cloudinary/upload';
} else {
_.extend(opts, {
mode: 'textareas',
readonly: true,
menubar: false,
toolbar: 'code',
statusbar: false
});
}
if (options.additionalOptions){
_.extend(opts, options.additionalOptions);
}
return opts;
},
getFieldClassName () {
var className = this.props.wysiwyg ? 'wysiwyg' : 'code';
return className;
},
renderField () {
var className = this.state.isFocused ? 'is-focused' : '';
var style = {
height: this.props.height
};
return (
<div className={className}>
<FormInput multiline ref='editor' style={style} onChange={this.valueChanged} id={this.state.id} className={this.getFieldClassName()} name={this.props.path} value={this.props.value} />
</div>
);
},
renderValue () {
return <FormInput multiline noedit value={this.props.value} />;
}
});
|
packages/icons/src/md/image/SlideShow.js
|
suitejs/suitejs
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdSlideShow(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M20 16v16l10-8-10-8zM38 6c2.21 0 4 1.79 4 4v28c0 2.21-1.79 4-4 4H10c-2.21 0-4-1.79-4-4V10c0-2.21 1.79-4 4-4h28zm0 32V10H10v28h28z" />
</IconBase>
);
}
export default MdSlideShow;
|
home/app.js
|
trisys3/combook
|
import io from 'socket.io-client';
import React from 'react';
import ReactDOM from 'react-dom';
import {prevPage, nextPage, opened} from './app.css';
const Book = window.comBook.default;
const socket = io(__dirname);
const book = {
author: {
full: 'S. O. Meone',
first: 's',
last: 'meone',
},
title: 'The Home-Bound Hero',
shortTitle: 'home-bound-hero',
pages: [
{
start: 1,
end: 2,
},
{
start: -2,
end: -1,
},
],
};
if(module.hot) {
module.hot.accept();
socket.once('hot-update', () => module.hot.check(true));
}
class Home extends React.Component {
constructor() {
super();
this.state = {
startPage: 1,
endPage: 1,
};
this.isBookend = this.isBookend.bind(this);
}
render() {
let openedClass;
if(!this.state.isFirstPage && !this.state.isLastPage) {
openedClass = opened;
}
const {startPage, endPage = startPage} = this.state;
return <home-comp>
<page-changer class={prevPage} onClick={() => this.getPrevPage()} disabled={this.state.isFirstPage} />
<book className={openedClass}>
<Book book={book} startPage={startPage} endPage={endPage} isBookend={this.isBookend} />
</book>
<page-changer class={nextPage} onClick={() => this.getNextPage()} disabled={this.state.isLastPage} />
</home-comp>;
}
isBookend({isFirst, isLast} = {}) {
let isFirstPage;
let isLastPage;
if(isFirst) {
isFirstPage = 'disabled';
}
if(isLast) {
isLastPage = 'disabled';
}
this.setState({isFirstPage, isLastPage});
}
getPrevPage() {
if(this.state.isFirstPage) {
return;
}
const newEnd = this.state.startPage - 1;
const newStart = newEnd - 1;
this.setState({startPage: newStart, endPage: newEnd});
}
getNextPage() {
if(this.state.isLastPage) {
return;
}
const newStart = this.state.endPage + 1;
const newEnd = newStart + 1;
this.setState({startPage: newStart, endPage: newEnd});
}
}
ReactDOM.render(<Home />, document.querySelector('home-page'));
|
test/pages/search.js
|
MoveOnOrg/mop-frontend
|
import React from 'react'
import { expect } from 'chai'
import { shallow } from 'enzyme'
import { createMockStore } from 'redux-test-utils'
import SearchPage from '../../src/containers/search'
describe('<SearchPage />', () => {
const baseStore = createMockStore({ userStore: {} })
it('renders default values with no search query', () => {
const searchPageProps = { query: {}, location: { query: { } } }
const context = shallow(<SearchPage {...searchPageProps} store={baseStore} />)
expect(context.props().query).to.equal('')
expect(context.props().pageNumber).to.equal('1')
expect(context.props().selectState).to.equal('')
})
it('parses out query', () => {
const searchPageProps = { query: {}, location: { query: { q: 'cats' } } }
const context = shallow(<SearchPage {...searchPageProps} store={baseStore} />)
expect(context.props().query).to.equal('cats')
expect(context.props().pageNumber).to.equal('1')
expect(context.props().selectState).to.equal('')
})
it('parses out page number', () => {
const searchPageProps = { query: {}, location: { query: { q: 'cats', page: '2' } } }
const context = shallow(<SearchPage {...searchPageProps} store={baseStore} />)
expect(context.props().query).to.equal('cats')
expect(context.props().pageNumber).to.equal('2')
expect(context.props().selectState).to.equal('')
})
it('parses out selected state', () => {
const searchPageProps = { query: {}, location: { query: { q: 'cats', page: '2', state: 'VA' } } }
const context = shallow(<SearchPage {...searchPageProps} store={baseStore} />)
expect(context.props().query).to.equal('cats')
expect(context.props().pageNumber).to.equal('2')
expect(context.props().selectState).to.equal('VA')
})
})
|
src/Parser/Warlock/Destruction/Modules/Features/DimensionalRift.js
|
enragednuke/WoWAnalyzer
|
import React from 'react';
import Analyzer from 'Parser/Core/Analyzer';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import { formatNumber, formatPercentage } from 'common/format';
import { STATISTIC_ORDER } from 'Main/StatisticBox';
import StatisticsListBox from 'Main/StatisticsListBox';
const FLAME_RIFT = 'Flame Rift';
const CHAOS_TEAR = 'Chaos Tear';
const SHADOWY_TEAR = 'Shadowy Tear';
const UNSTABLE_TEAR = 'Unstable Tear';
class DimensionalRift extends Analyzer {
_riftDetails = {
[FLAME_RIFT]: {
...SPELLS.SEARING_BOLT_RIFT,
},
[CHAOS_TEAR]: {
...SPELLS.CHAOS_BOLT_RIFT,
},
[SHADOWY_TEAR]: {
...SPELLS.SHADOW_BOLT_RIFT,
},
[UNSTABLE_TEAR]: {
...SPELLS.CHAOS_BARRAGE_RIFT,
},
};
_rifts = {};
on_initialized() {
this.owner.playerPets.filter(pet => this._riftDetails[pet.name]).forEach((pet) => {
this._rifts[pet.id] = {
...this._riftDetails[pet.name],
damage: 0,
};
});
}
on_damage(event) {
if (!this._rifts[event.sourceID]) {
return;
}
this._rifts[event.sourceID].damage += (event.amount || 0) + (event.absorbed || 0);
}
statistic() {
const rifts = Object.keys(this._rifts).map(id => this._rifts[id]);
const totalDmg = rifts.reduce((sum, rift) => sum + rift.damage, 0);
return (
<StatisticsListBox
title={<span><SpellIcon id={SPELLS.DIMENSIONAL_RIFT_CAST.id} /> Dimensional Rift</span>}
tooltip={`Your Dimensional Rifts did ${formatNumber(totalDmg)} total damage (${this.owner.formatItemDamageDone(totalDmg)}).`}
>
{rifts.map(rift => (
<div className="flex">
<div className="flex-main">
<SpellLink id={rift.id}>
<SpellIcon id={rift.id} noLink /> {rift.name}
</SpellLink>
</div>
<div className="flex-sub text-right">
{formatNumber(rift.damage)} ({formatPercentage(rift.damage / totalDmg)} %)
</div>
</div>
))}
</StatisticsListBox>
);
}
statisticOrder = STATISTIC_ORDER.OPTIONAL(6);
}
export default DimensionalRift;
|
examples/with-loading/components/Header.js
|
kevmannn/next.js
|
import React from 'react'
import Head from 'next/head'
import Link from 'next/link'
import NProgress from 'nprogress'
import Router from 'next/router'
Router.onRouteChangeStart = (url) => {
console.log(`Loading: ${url}`)
NProgress.start()
}
Router.onRouteChangeComplete = () => NProgress.done()
Router.onRouteChangeError = () => NProgress.done()
const linkStyle = {
margin: '0 10px 0 0'
}
export default () => (
<div style={{ marginBottom: 20 }}>
<Head>
{/* Import CSS for nprogress */}
<link rel='stylesheet' type='text/css' href='/static/nprogress.css' />
</Head>
<Link href='/'><a style={linkStyle}>Home</a></Link>
<Link href='/about'><a style={linkStyle}>About</a></Link>
<Link href='/forever'><a style={linkStyle}>Forever</a></Link>
<Link href='/non-existing'><a style={linkStyle}>Non Existing Page</a></Link>
</div>
)
|
src/svg-icons/social/public.js
|
mit-cml/iot-website-source
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialPublic = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/>
</SvgIcon>
);
SocialPublic = pure(SocialPublic);
SocialPublic.displayName = 'SocialPublic';
SocialPublic.muiName = 'SvgIcon';
export default SocialPublic;
|
react/pages/Signup.js
|
Seanskiver/b2b_application
|
import React from 'react';
//import { Table } from 'react-bootstrap';
import {Form, FormControl, FormGroup, ControlLabel, Button, Table, Carousel, Jumbotron, Panel, Col} from 'react-bootstrap';
import { HashRouter as Router, Route, Link, Redirect } from 'react-router-dom';
class Signup extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
businessName: '',
businessType: '',
businessCategory: '',
phone: '',
address: '',
country: 'Senegal',
city: '',
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
//handlesubmit
handleSubmit(event) {
event.preventDefault();
$.ajax({
type: 'post',
url: '/signup',
data: {
'_token': $('input[name=_token]').val(),
...this.email,
...this.businessName,
...this.businessType,
...this.businessCategory,
...this.phone,
...this.address,
...this.country,
...this.city,
},
success: function(data) {
alert('Form was submited');
location.reload();
}
});
}
render() {
const style = {
width: '450px'
};
return (
<div className="register" id="custom-container">
<Col xsHidden>
<div class="container" style={style}>
<div class="panel panel-default">
<div class="panel-heading" align="center"><b>Business Information</b></div>
<div class="panel-body">
<form onSubmit={this.handleSubmit}>
<div class="form-group col-md-12">
<label for="businessName">Business Name</label>
<input type="text" class="form-control" id="businessName" name="businessName" placeholder="Business Name" onChange={this.handleChange}/>
</div>
<div class="form-group col-md-12">
<label class="control-label">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="name@example.com" onChange={this.handleChange}/>
</div>
<div class="form-group col-md-12">
<label class="control-label">Phone</label>
<input type="text" required="required" class="form-control" id="phone" name="phone" placeholder="Enter Phone" onChange={this.handleChange}/>
</div>
<div class="form-group col-md-12">
<label for="businessType">Business Type</label>
<select class="form-control" id="businessType" name="businessType" onChange={this.handleChange}>
<option>Supplier</option>
<option>Buyer</option>
<option>Both</option>
</select>
</div>
<div class="form-group col-md-12">
<label for="businessCategory">Business Category</label>
<select class="form-control" id="businessCategory" name="businessCategory" onChange={this.handleChange}>
<option>Electronics & Appliance</option>
<option>Sport</option>
<option>Fashion</option>
<option>Food & Beverage</option>
<option>Automotive</option>
<option>Home Appliance</option>
<option>Furniture</option>
</select>
</div>
<div class="form-group col-md-12">
<label for="streetAddress">Street Address</label>
<input type="text" class="form-control" id="address" name="address" placeholder="Street Address" onChange={this.handleChange}/>
</div>
<div class="form-group col-md-12">
<label for="city">City</label>
<select class="form-control" id="exampleFormControlSelect1" name="city" onChange={this.handleChange}>
<option>Dakar</option>
<option>Touba</option>
<option>Thiès</option>
<option>Rufisque</option>
<option>Kaolack</option>
<option>M'Bour</option>
<option>Ziguinchor</option>
<option>Saint-Louis</option>
<option>Diourbel</option>
<option>Louga</option>
<option>Tambacounda</option>
<option>Richard Toll</option>
<option>Kolda</option>
<option>Mbacké</option>
<option>Tivaouane</option>
<option>Joal-Fadiouth</option>
<option>Kaffrine</option>
<option>Dahra</option>
<option>Bignona</option>
<option>Fatick</option>
<option>Dagana</option>
<option>Bambey</option>
<option>Vélingara</option>
<option>Sédhiou</option>
<option>Sébikhotane</option>
<option>Kédougou</option>
<option>Nguékhokh</option>
<option>Kayar</option>
<option>Pout</option>
<option>Mékhé</option>
<option>Matam</option>
<option>Ouro Sogui</option>
<option>Nioro du Rip</option>
<option>Kébémer</option>
<option>Koungheul</option>
<option>Guinguinéo</option>
<option>Bakel</option>
<option>Mboro</option>
<option>Linguère</option>
<option>Sokone</option>
<option>Goudomp</option>
<option>Thiadiaye</option>
<option>Ndioum</option>
<option>Damniadio</option>
<option>Khombole</option>
<option>Gossas</option>
<option>Kanel</option>
</select>
</div>
<div class="form-group col-md-12">
<button type="submit" class="btn btn-primary pull-right">Continue</button>
</div>
</form>
</div>
</div>
</div>
</Col>
{/*Mobile Form*/}
<Col smHidden mdHidden lgHidden>
<form onSubmit={this.handleSubmit}>
<div class="form-group col-md-12">
<label for="businessName">Business Name</label>
<input type="text" class="form-control" id="businessName" name="businessName" placeholder="Business Name" onChange={this.handleChange}/>
</div>
<div class="form-group col-md-12">
<label class="control-label">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="name@example.com" onChange={this.handleChange}/>
</div>
<div class="form-group col-md-12">
<label class="control-label">Phone</label>
<input type="text" required="required" class="form-control" id="phone" name="phone" placeholder="Enter Phone" onChange={this.handleChange}/>
</div>
<div class="form-group col-md-12">
<label for="businessType">Business Type</label>
<select class="form-control" id="businessType" name="businessType" onChange={this.handleChange}>
<option>Supplier</option>
<option>Buyer</option>
<option>Both</option>
</select>
</div>
<div class="form-group col-md-12">
<label for="businessCategory">Business Category</label>
<select class="form-control" id="businessCategory" name="businessCategory" onChange={this.handleChange}>
<option>Electronics & Appliance</option>
<option>Sport</option>
<option>Fashion</option>
<option>Food & Beverage</option>
<option>Automotive</option>
<option>Home Appliance</option>
<option>Furniture</option>
</select>
</div>
<div class="form-group col-md-12">
<label for="streetAddress">Street Address</label>
<input type="text" class="form-control" id="address" name="address" placeholder="Street Address" onChange={this.handleChange}/>
</div>
<div class="form-group col-md-12">
<label for="city">City</label>
<select class="form-control" id="exampleFormControlSelect1" name="city" onChange={this.handleChange}>
<option>Dakar</option>
<option>Touba</option>
<option>Thiès</option>
<option>Rufisque</option>
<option>Kaolack</option>
<option>M'Bour</option>
<option>Ziguinchor</option>
<option>Saint-Louis</option>
<option>Diourbel</option>
<option>Louga</option>
<option>Tambacounda</option>
<option>Richard Toll</option>
<option>Kolda</option>
<option>Mbacké</option>
<option>Tivaouane</option>
<option>Joal-Fadiouth</option>
<option>Kaffrine</option>
<option>Dahra</option>
<option>Bignona</option>
<option>Fatick</option>
<option>Dagana</option>
<option>Bambey</option>
<option>Vélingara</option>
<option>Sédhiou</option>
<option>Sébikhotane</option>
<option>Kédougou</option>
<option>Nguékhokh</option>
<option>Kayar</option>
<option>Pout</option>
<option>Mékhé</option>
<option>Matam</option>
<option>Ouro Sogui</option>
<option>Nioro du Rip</option>
<option>Kébémer</option>
<option>Koungheul</option>
<option>Guinguinéo</option>
<option>Bakel</option>
<option>Mboro</option>
<option>Linguère</option>
<option>Sokone</option>
<option>Goudomp</option>
<option>Thiadiaye</option>
<option>Ndioum</option>
<option>Damniadio</option>
<option>Khombole</option>
<option>Gossas</option>
<option>Kanel</option>
</select>
</div>
<div class="form-group col-md-12">
<button type="submit" class="btn btn-primary pull-right">Continue</button>
</div>
</form>
<br/>
</Col>
{/*//Mobile Form*/}
</div>
);
}
}
export default Signup;
|
src/svg-icons/toggle/star.js
|
ichiohta/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ToggleStar = (props) => (
<SvgIcon {...props}>
<path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/>
</SvgIcon>
);
ToggleStar = pure(ToggleStar);
ToggleStar.displayName = 'ToggleStar';
ToggleStar.muiName = 'SvgIcon';
export default ToggleStar;
|
src/Avatar/Avatar.spec.js
|
mmrtnz/material-ui
|
/* eslint-env mocha */
import React from 'react';
import {shallow} from 'enzyme';
import {assert} from 'chai';
import Avatar from './Avatar';
import getMuiTheme from '../styles/getMuiTheme';
describe('<Avatar />', () => {
const muiTheme = getMuiTheme();
const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});
const testChildren = <div className="unique">Hello World</div>;
it('renders children by default', () => {
const wrapper = shallowWithContext(
<Avatar>{testChildren}</Avatar>
);
assert.ok(wrapper.contains(testChildren), 'should contain the children');
});
it('renders children and an icon if passed in', () => {
const icon = <div className="testIcon" />;
const wrapper = shallowWithContext(
<Avatar icon={icon}>{testChildren}</Avatar>
);
assert.ok(wrapper.contains(testChildren), 'should contain the children');
// Finding by class as avatar clones element and changes the props
assert.ok(wrapper.find('.testIcon').length, 'should contain the icon');
});
it('only renders an image when the src prop is set', () => {
const wrapper = shallowWithContext(
<Avatar src="face.jpg">{testChildren}</Avatar>
);
assert.notOk(!wrapper.contains(testChildren), 'should not contain the children');
assert.ok(wrapper.is('img'), 'should be an image');
assert.ok(wrapper.is({src: 'face.jpg'}), 'should have the src passed into props');
wrapper.setProps({src: 'meow.jpg'});
assert.ok(wrapper.is({src: 'meow.jpg'}), 'should have changed the src');
});
});
|
src/dummy-component.js
|
macropodhq/axolotl
|
import React from 'react';
export default class DummyComponent extends React.Component {
render() {
throw 'this test has no visual component';
}
}
|
src/components/Loading.js
|
mangal49/HORECA
|
import React from 'react';
import RefreshIndicator from 'material-ui/RefreshIndicator';
const style = {
container: {
position: 'relative',
marginTop: 30,
},
refresh: {
display: 'inline-block',
position: 'relative',
},
};
const Loading = () => (
<div style={style.container}>
<RefreshIndicator
size={40}
left={10}
top={0}
status="loading"
style={style.refresh}
/>
</div>
);
export default Loading;
|
src/components/Row/Row.js
|
aaronvanston/react-flexa
|
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { themeProvider } from '../../theme';
import { filterProps, mediaQuery, gutter, CSSProperty } from '../../helpers';
const Row = styled(props =>
React.createElement(props.elementType, filterProps(props, Row.propTypes)),
)`
// Initial component property
box-sizing: border-box;
${props => themeProvider.breakpointsKeys(props).map(breakpoint => mediaQuery(props)[breakpoint]`
// Generate gutter
${gutter.row(props, breakpoint)}
// Responsive Flexbox properties
${CSSProperty(props, breakpoint, 'display')}
${CSSProperty(props, breakpoint, 'flex-direction')}
${CSSProperty(props, breakpoint, 'flex-wrap')}
${CSSProperty(props, breakpoint, 'justify-content')}
${CSSProperty(props, breakpoint, 'align-items')}
${CSSProperty(props, breakpoint, 'align-content')}
`)}
`;
Row.defaultProps = {
display: 'flex',
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'flex-start',
alignItems: 'stretch',
alignContent: 'stretch',
elementType: 'div',
};
const displayOptions = ['flex', 'inline-flex'];
const flexDirectionOptions = ['row', 'row-reverse', 'column', 'column-reverse'];
const flexWrapOptions = ['nowrap', 'wrap', 'wrap-reverse'];
const justifyContentOptions = ['flex-start', 'flex-end', 'center', 'space-between', 'space-around'];
const alignItemsOptions = ['flex-start', 'flex-end', 'center', 'baseline', 'stretch'];
const alignContentOptions = ['flex-start', 'flex-end', 'center', 'space-between', 'space-around', 'stretch'];
Row.propTypes = {
gutter: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
PropTypes.shape({
xs: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
]),
sm: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
]),
md: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
]),
lg: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
]),
}),
]),
display: PropTypes.oneOfType([
PropTypes.oneOf(displayOptions),
PropTypes.shape({
xs: PropTypes.oneOf(displayOptions),
sm: PropTypes.oneOf(displayOptions),
md: PropTypes.oneOf(displayOptions),
lg: PropTypes.oneOf(displayOptions),
}),
]),
flexDirection: PropTypes.oneOfType([
PropTypes.oneOf(flexDirectionOptions),
PropTypes.shape({
xs: PropTypes.oneOf(flexDirectionOptions),
sm: PropTypes.oneOf(flexDirectionOptions),
md: PropTypes.oneOf(flexDirectionOptions),
lg: PropTypes.oneOf(flexDirectionOptions),
}),
]),
flexWrap: PropTypes.oneOfType([
PropTypes.oneOf(flexWrapOptions),
PropTypes.shape({
xs: PropTypes.oneOf(flexWrapOptions),
sm: PropTypes.oneOf(flexWrapOptions),
md: PropTypes.oneOf(flexWrapOptions),
lg: PropTypes.oneOf(flexWrapOptions),
}),
]),
justifyContent: PropTypes.oneOfType([
PropTypes.oneOf(justifyContentOptions),
PropTypes.shape({
xs: PropTypes.oneOf(justifyContentOptions),
sm: PropTypes.oneOf(justifyContentOptions),
md: PropTypes.oneOf(justifyContentOptions),
lg: PropTypes.oneOf(justifyContentOptions),
}),
]),
alignItems: PropTypes.oneOfType([
PropTypes.oneOf(alignItemsOptions),
PropTypes.shape({
xs: PropTypes.oneOf(alignItemsOptions),
sm: PropTypes.oneOf(alignItemsOptions),
md: PropTypes.oneOf(alignItemsOptions),
lg: PropTypes.oneOf(alignItemsOptions),
}),
]),
alignContent: PropTypes.oneOfType([
PropTypes.oneOf(alignContentOptions),
PropTypes.shape({
xs: PropTypes.oneOf(alignContentOptions),
sm: PropTypes.oneOf(alignContentOptions),
md: PropTypes.oneOf(alignContentOptions),
lg: PropTypes.oneOf(alignContentOptions),
}),
]),
elementType: PropTypes.string,
children: PropTypes.node,
};
Row.displayName = 'Row';
export default Row;
|
static/src/components/AirhornCounter.js
|
hammerandchisel/airhornbot
|
// @flow
import React from 'react';
import Constants from '../Constants';
export default (): React.Element => (
<object data={Constants.Image.AIRHORN_COUNTER} />
);
|
app/src/pages/SignUp/index.js
|
fikrimuhal/animated-potato
|
import React from 'react'
import {Link} from 'react-router'
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
const styles = {
button: {
marginRight: 12,
}, contente: {
width: '100%',
marginLeft: 200
},
container: {
display: 'flex',
height: '100%',
},
};
export default React.createClass({
render() {
return (
<div style={styles.contente}>
<br/><br/>
?Lütfen aşağıdaki bilgileri eksiksiz bir şekilde doldurunuz.
<div>
<h3>Kayıt Ol</h3>
<div>
<TextField hintText="Ad" floatingLabelText="Ad"/>
<TextField hintText="Soyad" floatingLabelText="Soyad"/> <br/>
<TextField hintText="E mail" floatingLabelText="E mail"/>
<TextField hintText="Telefon" floatingLabelText="Telefon"/><br/>
</div>
</div>
<div style={styles.button}>
<Link to="/adminpanel"><RaisedButton label="Kayıt Ol" primary={true}/></Link>
<RaisedButton label="Temizle" secondary={true}/>
</div>
</div>
)
}
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.