path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
envkey-react/src/containers/invoice_list_container.js
|
envkey/envkey-app
|
import React from 'react'
import { connect } from 'react-redux'
import {
billingFetchInvoiceList,
billingFetchInvoicePdf
} from 'actions'
import {
getInvoices,
getIsLoadingInvoices,
getIsLoadingInvoicePdf
} from 'selectors'
import InvoiceRow from 'components/billing/invoice_row'
import SmallLoader from 'components/shared/small_loader'
class InvoiceList extends React.Component {
componentDidMount(){
if (this.props.invoices.length == 0){
this.props.onLoadInvoices()
}
}
render(){
if (this.props.isLoadingInvoices){
return <SmallLoader />
} else if (this.props.invoices){
return <table className="invoice-list">
<thead>
<tr>
<th>Date</th>
<th>Plan</th>
<th>Active Users</th>
<th>Total</th>
<th>Billing Period</th>
<th>Status</th>
<th>Reference</th>
<th></th>
</tr>
</thead>
{this._renderInvoices()}
</table>
} else {
return <table />
}
}
_renderInvoices(){
return this.props.invoices.map(invoice => {
return <InvoiceRow {...this.props} invoice={invoice} />
})
}
}
const mapStateToProps = state => ({
invoices: getInvoices(state),
isLoadingInvoices: getIsLoadingInvoices(state),
isLoadingInvoicePdf: getIsLoadingInvoicePdf(state)
})
const mapDispatchToProps = dispatch => ({
onLoadInvoices: () => dispatch(billingFetchInvoiceList()),
onLoadInvoicePdf: id => dispatch(billingFetchInvoicePdf({id}))
})
export default connect(mapStateToProps, mapDispatchToProps)(InvoiceList)
|
docs/src/app/components/pages/components/TextField/ExampleSimple.js
|
w01fgang/material-ui
|
import React from 'react';
import TextField from 'material-ui/TextField';
const TextFieldExampleSimple = () => (
<div>
<TextField
hintText="Hint Text"
/><br />
<br />
<TextField
hintText="The hint text can be as long as you want, it will wrap."
/><br />
<TextField
id="text-field-default"
defaultValue="Default Value"
/><br />
<TextField
hintText="Hint Text"
floatingLabelText="Floating Label Text"
/><br />
<TextField
defaultValue="Default Value"
floatingLabelText="Floating Label Text"
/><br />
<TextField
hintText="Hint Text"
floatingLabelText="Fixed Floating Label Text"
floatingLabelFixed={true}
/><br />
<TextField
hintText="Password Field"
floatingLabelText="Password"
type="password"
/><br />
<TextField
hintText="MultiLine with rows: 2 and rowsMax: 4"
multiLine={true}
rows={2}
rowsMax={4}
/><br />
<TextField
hintText="Message Field"
floatingLabelText="MultiLine and FloatingLabel"
multiLine={true}
rows={2}
/><br />
<TextField
hintText="Full width"
fullWidth={true}
/>
</div>
);
export default TextFieldExampleSimple;
|
packages/cf-component-card/src/Card.js
|
koddsson/cf-ui
|
import React from 'react';
import PropTypes from 'prop-types';
class Card extends React.Component {
render() {
return (
<section id={this.props.id} className="cf-card">
{this.props.children}
</section>
);
}
}
Card.propTypes = {
id: PropTypes.string,
children: PropTypes.node
};
export default Card;
|
src/app/views/logout.js
|
webcoding/reactui-starter
|
import React from 'react';
import authActions from 'actions/auth';
export default React.createClass( {
componentDidMount () {
authActions.logout();
},
render() {
return (
<div id="logout">
<div className="jumbotron">
<h1>Logged Out</h1>
</div>
</div>
);
}
} );
|
src/routes/Edit/components/Edit.spec.js
|
arcsin037/RGPP-React
|
import React from 'react'
import Edit from './Edit'
import { shallow } from 'enzyme'
describe('(Component) Edit', () => {
let _wrapper
beforeEach(() => {
const _props = {
appName: 'Original Application',
resolutionX: 640,
resolutionY: 480
}
_wrapper = shallow(<Edit {..._props} />)
})
it('Should render as a <div>', () => {
expect(_wrapper.is('div')).to.equal(true)
})
it('Renders a application name', () => {
const welcome = _wrapper.find('h1')
expect(welcome).to.exist
expect(welcome.text()).to.equal('Original Application')
})
})
|
app/javascript/mastodon/features/compose/components/reply_indicator.js
|
codl/mastodon
|
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Avatar from '../../../components/avatar';
import IconButton from '../../../components/icon_button';
import DisplayName from '../../../components/display_name';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { isRtl } from '../../../rtl';
const messages = defineMessages({
cancel: { id: 'reply_indicator.cancel', defaultMessage: 'Cancel' },
});
@injectIntl
export default class ReplyIndicator extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map,
onCancel: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleClick = () => {
this.props.onCancel();
}
handleAccountClick = (e) => {
if (e.button === 0) {
e.preventDefault();
this.context.router.history.push(`/accounts/${this.props.status.getIn(['account', 'id'])}`);
}
}
render () {
const { status, intl } = this.props;
if (!status) {
return null;
}
const content = { __html: status.get('contentHtml') };
const style = {
direction: isRtl(status.get('search_index')) ? 'rtl' : 'ltr',
};
return (
<div className='reply-indicator'>
<div className='reply-indicator__header'>
<div className='reply-indicator__cancel'><IconButton title={intl.formatMessage(messages.cancel)} icon='times' onClick={this.handleClick} /></div>
<a href={status.getIn(['account', 'url'])} onClick={this.handleAccountClick} className='reply-indicator__display-name'>
<div className='reply-indicator__display-avatar'><Avatar account={status.get('account')} size={24} /></div>
<DisplayName account={status.get('account')} />
</a>
</div>
<div className='reply-indicator__content' style={style} dangerouslySetInnerHTML={content} />
</div>
);
}
}
|
node_modules/react-router/es6/Route.js
|
Win-Myint/ReactChallenge2
|
import React from 'react';
import invariant from 'invariant';
import { createRouteFromReactElement } from './RouteUtils';
import { component, components } from './InternalPropTypes';
var _React$PropTypes = React.PropTypes;
var string = _React$PropTypes.string;
var func = _React$PropTypes.func;
/**
* A <Route> is used to declare which components are rendered to the
* page when the URL matches a given pattern.
*
* Routes are arranged in a nested tree structure. When a new URL is
* requested, the tree is searched depth-first to find a route whose
* path matches the URL. When one is found, all routes in the tree
* that lead to it are considered "active" and their components are
* rendered into the DOM, nested in the same order as in the tree.
*/
var Route = React.createClass({
displayName: 'Route',
statics: {
createRouteFromReactElement: createRouteFromReactElement
},
propTypes: {
path: string,
component: component,
components: components,
getComponent: func,
getComponents: func
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Route> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default Route;
|
example/examples/PublicMethodsExample.react.js
|
Neophy7e/react-bootstrap-typeahead
|
import React from 'react';
import {Button, ButtonToolbar} from 'react-bootstrap';
import {Typeahead} from '../../src/';
import options from '../../example/exampleData';
/* example-start */
const PublicMethodsExample = React.createClass({
render() {
return (
<div>
<Typeahead
labelKey="name"
multiple
options={options}
placeholder="Choose a state..."
ref={ref => this._typeahead = ref}
selected={options.slice(0, 4)}
/>
<ButtonToolbar style={{marginTop: '10px'}}>
<Button onClick={() => this._typeahead.getInstance().clear()}>
Clear
</Button>
<Button onClick={() => this._typeahead.getInstance().focus()}>
Focus
</Button>
<Button
onClick={() => {
const instance = this._typeahead.getInstance();
instance.focus();
setTimeout(() => instance.blur(), 1000);
}}>
Focus, then blur after 1 second
</Button>
</ButtonToolbar>
</div>
);
},
});
/* example-end */
export default PublicMethodsExample;
|
app/components/agents/agentPageResourcesItem.js
|
nypl-registry/browse
|
import React from 'react'
import { Link } from 'react-router'
const AgentPageResourcesItem = React.createClass({
getInitialState: function (event) {
return {errored: false}
},
handleError: function (event) {
this.setState({errored: true})
},
render () {
var displayImg = <td />
if (!this.state.errored) {
displayImg = (
<td className='agent-resources-list-item-bookcover'>
<img onError={this.handleError} src={`http://s3.amazonaws.com/data.nypl.org/bookcovers/${this.props.data.idBnum}_ol.jpg`} />
</td>
)
}
return (
<tr className='agent-resources-list-item-row'>
<td>
{this.props.data.startYear}
</td>
{displayImg}
<td className='agent-resources-list-item-title'>
<Link className='agent-resources-list-item-title-link' to={`/resources/${this.props.data.uri}`}>
<div>
{this.props.data.title}
</div>
</Link>
</td>
<td>
<Link className='agent-resources-list-item-title-link' to={`/resources/${this.props.data.uri}`}>
<span className='lg-icon nypl-icon-wedge-right'></span>
</Link>
</td>
</tr>
)
}
})
export default AgentPageResourcesItem
|
frontend/tests/components/register-button.js
|
1905410/Misago
|
import assert from 'assert';
import React from 'react'; // jshint ignore:line
import RegisterButton from 'misago/components/register-button'; // jshint ignore:line
import misago from 'misago/index';
import captcha from 'misago/services/captcha';
import modal from 'misago/services/modal';
import snackbar from 'misago/services/snackbar';
import zxcvbn from 'misago/services/zxcvbn';
import * as testUtils from 'misago/utils/test-utils';
let snackbarStore = null;
describe("RegisterButton", function() {
beforeEach(function() {
snackbarStore = testUtils.snackbarStoreMock();
snackbar.init(snackbarStore);
testUtils.initModal(modal);
testUtils.contextClear(misago);
/* jshint ignore:start */
testUtils.render(<RegisterButton />);
/* jshint ignore:end */
});
afterEach(function() {
delete window.zxcvbn;
testUtils.unmountComponents();
});
it("renders", function() {
let element = $('#test-mount button');
assert.ok(element.length, "component rendered");
});
it("alerts about closed registration", function(done) {
misago._context = {
SETTINGS: {
account_activation: 'closed'
}
};
snackbarStore.callback(function(message) {
assert.deepEqual(message, {
message: "New registrations are currently disabled.",
type: 'info'
}, "valid alert is raised");
done();
});
testUtils.simulateClick('#test-mount button');
});
it("opens registration modal", function(done) {
misago._context = {
SETTINGS: {
captcha_type: 'no',
account_activation: 'none'
}
};
captcha.init(misago, {}, {}, {});
zxcvbn.init({
include: function(file) {
assert.equal(file, 'misago/js/zxcvbn.js', "zxcvbn.js is requested");
window.setTimeout(function() {
window.zxcvbn = function() {
return 0;
};
}, 200);
}
});
testUtils.simulateClick('#test-mount button');
testUtils.onElement('#modal-mount .modal-register', function() {
let element = $('#modal-mount .modal-register');
assert.ok(element.length, "registration modal was opened");
done();
});
});
});
|
src/routes.js
|
KovDimaY/React-Highcharts
|
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/app';
import Bar from './components/charts/bar';
import Home from './components/home';
import Line from './components/charts/line';
// import NotFound from './components/notFound'; // TODO: fix router and use 404 instead of index
import Other from './components/charts/other';
import Pie from './components/charts/pie';
import Playground from './components/charts/playground';
import Scattering from './components/charts/scatter';
export default (
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="/line" component={Line} />
<Route path="/bar" component={Bar} />
<Route path="/pie" component={Pie} />
<Route path="/scatter" component={Scattering} />
<Route path="/other" component={Other} />
<Route path="/playground" component={Playground} />
<Route path="*" component={Home} />
{/* <Route path="*" component={NotFound} /> */}
</Route>
);
|
flask_react/client/test/components/Users.spec.js
|
ebottabi/mmakinde-ebot
|
/* global jest expect */
import React from 'react';
import { shallow } from 'enzyme';
import { Users } from '../../components/users/Users';
describe('Users component', () => {
const props = {
getAllUsers: jest.fn(() => Promise.resolve()),
deleteUserRecord: jest.fn(() => Promise.resolve()),
currentUser: {},
pagination: { pageCount: 3 },
allUsers: [],
searchUserDb: jest.fn()
};
const nextProps = {
allUsers: [],
pagination: { pageCount: 3 }
};
const page = {
selected: 3,
};
const wrapper = shallow(<Users {...props} />);
it('renders as a div', () => {
expect(wrapper.node.type).toEqual('div');
});
it('should contain the method componentDidMount', () => {
const componentDidMountSpy =
jest.spyOn(wrapper.instance(), 'componentDidMount');
wrapper.instance().componentDidMount();
expect(componentDidMountSpy).toHaveBeenCalledTimes(1);
});
it('should contain the method handlePageClick', () => {
const handlePageClickSpy =
jest.spyOn(wrapper.instance(), 'handlePageClick');
wrapper.instance().handlePageClick(page);
expect(handlePageClickSpy).toHaveBeenCalledTimes(1);
});
it('should contain the method deleteUser', () => {
const deleteUserSpy =
jest.spyOn(wrapper.instance(), 'deleteUser');
wrapper.instance().deleteUser(3);
expect(deleteUserSpy).toHaveBeenCalledTimes(1);
});
it('should contain the method componentWillReceiveProps', () => {
const componentWillReceivePropsSpy =
jest.spyOn(wrapper.instance(), 'componentWillReceiveProps');
wrapper.instance().componentWillReceiveProps(nextProps);
expect(componentWillReceivePropsSpy).toHaveBeenCalledTimes(1);
});
});
|
maodou/events/client/components/admin/eventsList.js
|
wuyang910217/meteor-react-redux-base
|
import React, { Component } from 'react';
import {Link} from 'react-router';
import Loading from 'client/components/common/loading';
import moment from 'moment';
import { shortText } from 'lib/helpers';
export default class EventsList extends Component {
render() {
const { data, status } = this.props.events;
return(
<div className="admin-package-wrapper row">
<div className="col-sm-12">
<h1 style={{marginBottom: '20px'}}>管理活动</h1>
{ status === 'ready' ?
data.length > 0 ? this.renderEvents(data) : <div>抱歉,目前还没有活动!</div>
: <Loading />
}
</div>
</div>
);
}
renderEvents(events) {
return (
<div className="table-responsive">
<table className="table table-striped">
<thead>
<tr style={{fontSize: '16px'}}>
<th>活动标题</th>
<th>活动日期</th>
<th>活动地点</th>
<th>人数限制</th>
<th>发布日期</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{events.map((event, index) =>
<tr key={event._id} style={{fontSize: '16px'}}>
<td style={{lineHeight: '50px'}}><Link to={`/event/${event._id}`}>{shortText(event.title)}</Link></td>
<td style={{lineHeight: '50px'}}>{moment(event.time).format('YYYY-MM-DD')}</td>
<td style={{lineHeight: '50px'}}>{shortText(event.location)}</td>
<td style={{lineHeight: '50px'}}>{shortText(event.limit)}</td>
<td style={{lineHeight: '50px'}}>{moment(event.createdAt).format('YYYY-MM-DD')}</td>
<td style={{lineHeight: '50px'}}>
<Link to={`/admin/event/edit/${event._id}`} className="btn btn-success" style={{marginRight: '10px'}}>编辑</Link>
<button className="btn btn-danger" onClick={(e) => this.props.dispatch((this.props.deleteEvent(e, event._id)))}>删除</button>
</td>
</tr>
)}
</tbody>
</table>
</div>
);
}
}
|
public/app/components/player/duration-panel.js
|
feedm3/unhypem
|
/**
* @author Fabian Dietenberger
*/
'use strict';
import React from 'react';
import songDispatcher from '../../dispatcher/song-dispatcher';
class DurationLabel extends React.Component {
constructor(props) {
super(props);
this.state = {
duration: 0,
position: 0
};
}
handleCurrentSongUpdate(songInfo) {
const durationInMillis = songInfo.song.duration;
const positionInPercent = songInfo.position;
const durationInSeconds = durationInMillis / 1000;
const positionInSeconds = (durationInSeconds * positionInPercent) / 100;
this.setState({
duration: durationInSeconds,
position: positionInSeconds
});
}
render() {
const position = secondFormatter(this.state.position);
const duration = secondFormatter(this.state.duration);
return (
<div className="duration">
<div>{position}</div>
<div>{duration}</div>
</div>
);
}
componentDidMount() {
songDispatcher.registerOnCurrentSongUpdate('DurationLabel', this.handleCurrentSongUpdate.bind(this));
}
}
/**
* Converts seconds to mm:ss.
*
* @param second
* @returns {string} mm:ss
*/
function secondFormatter(second) {
const sec_num = parseInt(second, 10); // don't forget the second param
const hours = Math.floor(sec_num / 3600);
let minutes = Math.floor((sec_num - (hours * 3600)) / 60);
let seconds = sec_num - (hours * 3600) - (minutes * 60);
if (minutes < 10) minutes = '0' + minutes;
if (seconds < 10) seconds = '0' + seconds;
return minutes + ':' + seconds;
}
export default DurationLabel;
|
client/components/Player.js
|
Pocket-titan/Tonlist
|
import React from 'react'
import {Slider} from 'material-ui'
import {compose, withState, mapProps} from 'recompose'
import {Audio, View, Text, TextInput} from '../components'
import ThemeManager from 'material-ui/lib/styles/theme-manager';
import MyRawTheme from '../components/Theme.js';
import ThemeDecorator from 'material-ui/lib/styles/theme-decorator';
let bounds = (min, max, value) => {
return Math.min(max, Math.max(min, value))
}
let Player = compose(
ThemeDecorator(ThemeManager.getMuiTheme(MyRawTheme)),
withState('volume', 'setVolume', 0.2),
withState('errorTag', 'setError', 0)
)(({volume, setVolume, time, URL, setError, errorTag}) => {
let onWheel = e => {
e.preventDefault()
let {deltaY} = e
let x = bounds(0, 1, volume - ((deltaY > 0 ? 1 : -1) * 0.01))
setVolume(x)
}
return (
<View onWheel={onWheel}>
<Audio
volume={volume}
src={`${URL}${time}${errorTag.toString()}.mp3`}
onError={() => setError(errorTag + 1)}
autoPlay
/>
<Slider
value={volume}
onChange={(e, value) => setVolume(value)}
style={{
marginBottom: 24
}}
/>
</View>
)
})
export default Player
|
components/OverlayEngine.js
|
nvbf/pepper
|
// @flow
import React from 'react';
import { gql, graphql } from 'react-apollo';
import withData from '../libs/withData';
import Scoreboard from './scoreboard/ApolloScoreboard';
import PlayerList from './playerlist/ApolloPlayerList';
/* we need a component that can subscribe to overlay updates, and change the UI accordingly */
class OverlayEngine extends React.Component {
componentDidMount() {
this.props.subscribeToOverlays();
}
render() {
if (this.props.loading) {
return <div>loading</div>;
}
if (this.props.overlay.id === 'scoreboard') {
return <Scoreboard isShowing={this.props.overlay.isShowing} matchId="123" />;
}
if (this.props.overlay.id === 'playerlist') {
return <PlayerList showHomeTeam isShowing={this.props.overlay.isShowing} matchId="123" />;
}
return `Overlay:${this.props.data.Overlay.id}`;
}
}
const GET_OVERLAY_QUERY = gql`
{
Overlay(id: "playerlist") {
id
isShowing
}
}
`;
const OVERLAY_SUBSCRIPTION = gql`
subscription SubscribeOnShowing {
Overlay {
type
overlay {
id
isShowing
}
}
}
`;
const config = {
props: ({ ownProps, data }) => {
const overlay = data.Overlay;
return {
subscribeToOverlays: () => data.subscribeToMore({ document: OVERLAY_SUBSCRIPTION }),
loading: data.loading,
isShowing: ownProps.isShowing,
overlay: data.Overlay,
};
},
};
export default graphql(GET_OVERLAY_QUERY, config)(OverlayEngine);
|
ReactJS/exam prep/react-starter-kit-master/src/index.js
|
Martotko/JS-Web
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { BrowserRouter as Router } from 'react-router-dom';
ReactDOM.render((
<Router>
<App />
</Router>), document.getElementById('root'));
registerServiceWorker();
|
lib/shared/elements/dynamic-list/container.js
|
relax/relax
|
import Component from 'components/component';
import isElementSelected from 'helpers/page-builder/is-element-selected';
import React from 'react';
import PropTypes from 'prop-types';
import {dataConnect} from 'relate-js';
import DynamicList from './dynamic-list';
@dataConnect(
(state, props) => ({
isLinkingData: state.pageBuilder && isElementSelected(state.pageBuilder.linkingData, {
id: props.relax.element.id,
context: props.relax.context
})
}),
(props) => {
const result = {
variablesTypes: {
schemaList: {
schemaId: 'ID!',
limit: 'Int'
}
}
};
if (props.schemaId) {
result.fragments = {
schemaList: {
_id: 1,
slug: 1,
schemaSlug: 1,
title: 1,
date: 1,
publishedDate: 1,
updatedDate: 1,
state: 1,
properties: 1
}
};
result.initialVariables = {
schemaList: {
schemaId: props.schemaId,
limit: props.limit
}
};
}
return result;
}
)
export default class DynamicListContainer extends Component {
static propTypes = {
renderChildren: PropTypes.func.isRequired,
Element: PropTypes.func.isRequired,
relax: PropTypes.object.isRequired,
schemaId: PropTypes.string,
isLinkingData: PropTypes.bool,
limit: PropTypes.number,
columns: PropTypes.number,
verticalGutter: PropTypes.string,
horizontalGutter: PropTypes.string,
elementsLinks: PropTypes.object,
schemaList: PropTypes.array
};
componentWillReceiveProps (nextProps) {
if (this.props.schemaId !== nextProps.schemaId) {
this.props.relate.refresh(nextProps);
}
}
render () {
const {
relax,
limit,
columns,
verticalGutter,
horizontalGutter,
isLinkingData,
schemaList,
schemaLinks,
Element,
renderChildren
} = this.props;
return (
<DynamicList
entries={schemaList || []}
relax={relax}
Element={Element}
renderChildren={renderChildren}
elementsLinks={schemaLinks}
limit={limit}
columns={columns}
verticalGutter={verticalGutter}
horizontalGutter={horizontalGutter}
isLinkingData={isLinkingData}
/>
);
}
}
|
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
|
UnSpiraTive/radio
|
import React from 'react';
import { render } from 'react-dom';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
render(<HelloWorld />, document.getElementById('react-root'));
|
packages/reactor-kitchensink/src/examples/D3/Hierarchy/ZoomableSunburst/ZoomableSunburst.js
|
dbuhrman/extjs-reactor
|
import React, { Component } from 'react';
import { Panel } from '@extjs/ext-react';
import { D3_Sunburst } from '@extjs/ext-react-d3';
export default class ZoomableSunburst extends Component {
store = Ext.create('Ext.data.TreeStore', {
autoLoad: true,
defaultRootText: 'd3',
fields: [
'name',
'path',
'size',
{
name: 'leaf',
calculate: function (data) {
return data.root ? false : !data.children;
}
},
{
name: 'text',
calculate: function (data) {
return data.name;
}
}
],
proxy: {
type: 'ajax',
url: 'resources/data/tree/tree.json'
},
idProperty: 'path'
})
onTooltip = (component, tooltip, node) => {
const record = node.data,
size = record.get('size'),
n = record.childNodes.length;
tooltip.setHtml(size ?
Ext.util.Format.fileSize(size) :
n + ' file' + (n === 1 ? '' : 's') + ' inside.'
);
}
render() {
return (
<Panel shadow layout="fit">
<D3_Sunburst
padding={20}
store={this.store}
tooltip={{ renderer: this.onTooltip }}
transitions={{ select: false }}
onSelectionChange={(sunburst, node) => sunburst.zoomInNode(node)}
expandEventName={false}
/>
</Panel>
)
}
}
|
actor-apps/app-web/src/app/components/common/Text.react.js
|
berserkertdl/actor-platform
|
import _ from 'lodash';
import React from 'react';
import memoize from 'memoizee';
import emojify from 'emojify.js';
import hljs from 'highlight.js';
import marked from 'marked';
import emojiCharacters from 'emoji-named-characters';
emojify.setConfig({
mode: 'img',
img_dir: 'assets/img/emoji' // eslint-disable-line
});
const mdRenderer = new marked.Renderer();
// target _blank for links
mdRenderer.link = function(href, title, text) {
let external, newWindow, out;
external = /^https?:\/\/.+$/.test(href);
newWindow = external || title === 'newWindow';
out = '<a href=\"' + href + '\"';
if (newWindow) {
out += ' target="_blank"';
}
if (title && title !== 'newWindow') {
out += ' title=\"' + title + '\"';
}
return (out + '>' + text + '</a>');
};
const markedOptions = {
sanitize: true,
breaks: true,
highlight: function (code) {
return hljs.highlightAuto(code).value;
},
renderer: mdRenderer
};
const inversedEmojiCharacters = _.invert(_.mapValues(emojiCharacters, (e) => e.character));
const emojiVariants = _.map(Object.keys(inversedEmojiCharacters), function(name) {
return name.replace(/\+/g, '\\+');
});
const emojiRegexp = new RegExp('(' + emojiVariants.join('|') + ')', 'gi');
const processText = function(text) {
let markedText = marked(text, markedOptions);
// need hack with replace because of https://github.com/Ranks/emojify.js/issues/127
const noPTag = markedText.replace(/<p>/g, '<p> ');
let emojifiedText = emojify
.replace(noPTag.replace(emojiRegexp, (match) => ':' + inversedEmojiCharacters[match] + ':'));
return emojifiedText;
};
const memoizedProcessText = memoize(processText, {
length: 1000,
maxAge: 60 * 60 * 1000,
max: 10000
});
class Text extends React.Component {
static propTypes = {
content: React.PropTypes.object.isRequired,
className: React.PropTypes.string
};
constructor(props) {
super(props);
}
render() {
const { content, className } = this.props;
return (
<div className={className}
dangerouslySetInnerHTML={{__html: memoizedProcessText(content.text)}}>
</div>
);
}
}
export default Text;
|
admin/client/App/screens/Home/components/Lists.js
|
jstockwin/keystone
|
import React from 'react';
import _ from 'lodash';
import { connect } from 'react-redux';
import { plural } from '../../../../utils/string';
import ListTile from './ListTile';
export class Lists extends React.Component {
render () {
return (
<div className="dashboard-group__lists">
{_.map(this.props.lists, (list, key) => {
// If an object is passed in the key is the index,
// if an array is passed in the key is at list.key
const listKey = list.key || key;
const href = list.external ? list.path : `${Keystone.adminPath}/${list.path}`;
const listData = this.props.listsData[list.path];
const isNoCreate = listData ? listData.nocreate : false;
return (
<ListTile
key={list.path}
path={list.path}
label={list.label}
hideCreateButton={isNoCreate}
href={href}
count={plural(this.props.counts[listKey], '* Item', '* Items')}
spinner={this.props.spinner}
/>
);
})}
</div>
);
}
}
Lists.propTypes = {
counts: React.PropTypes.object.isRequired,
lists: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.object,
]).isRequired,
spinner: React.PropTypes.node,
};
export default connect((state) => {
return {
listsData: state.lists.data,
};
})(Lists);
|
modules/dreamview/frontend/src/components/CameraParam/index.js
|
xiaoxq/apollo
|
import React, { Component } from 'react';
import ReactTooltip from 'react-tooltip';
import { inject, observer } from 'mobx-react';
import positionIcon from 'assets/images/icons/position.png';
import rotationIcon from 'assets/images/icons/rotation.png';
const ResetSvg = () => (
<svg viewBox="0 0 1024 1024" width="20" height="20" fill="#999999">
<path d="M978.637 890.58H178.116V1024L0 846.551l176.115-174.78v133.42H933.94c29.353 0 44.696-12.008 44.696-41.36V496.99l88.725-141.426V800.52a88.724 88.724 0 0 1-88.725 88.058z m-88.724-667.101H133.42c-29.352 0-44.696 12.008-44.696 42.027v268.175L0 673.105v-450.96a88.724 88.724 0 0 1 88.724-88.725h800.522V0l178.116 178.116-176.115 176.115V220.81z" />
</svg>
);
const UpArrowSvg = ({ onClick }) => (
<svg viewBox="0 0 1024 1024" width="15" height="15" onClick={onClick} fill="#999999">
<path d="M820.00415442 790.08350547l-617.53286931-1e-8c-34.17530758 0-61.8167847-27.4267503-61.81678473-61.59899038 0-15.89285244 6.0951742-30.25807684 15.89285244-41.14165922l305.39062223-407.4809563c20.4634662-26.98809409 58.98852574-32.65074716 86.20054921-12.19034849 4.79147569 3.48470957 8.92343326 7.61973466 12.19034848 12.19034849L869.19806953 691.69567529c20.24260435 26.99116162 14.79774561 65.73401549-12.40814284 85.97968733C845.68548239 786.16627474 832.84481844 790.08350547 820.00415442 790.08350547L820.00415442 790.08350547z" />
</svg>
);
const DownArrowSvg = ({ onClick }) => (
<svg viewBox="0 0 1024 1024" width="15" height="15" onClick={onClick} fill="#999999">
<path d="M151.477 199.554l718.53099999 0c39.763 0 71.922 31.91 71.92200002 71.674 0 18.485-7.096 35.206-18.48600001 47.872l-355.33 474.125c-23.81 31.4-68.641 37.994-100.297 14.183-5.571-4.052-10.385-8.873-14.183-14.19l-359.398-479.178c-23.547-31.407-17.217-76.48 14.43699999-100.041 12.922-9.881 27.865-14.438 42.80500001-14.439v0l0-0.007zM151.477 199.554z" />
</svg>
);
const FIELDS = {
Position: {
X: 'x',
Y: 'y',
Z: 'z',
},
StaticRotation: {
Pitch: 'x',
Yaw: 'y',
Roll: 'z',
},
DynamicRotation: {
Pitch: 'y',
Yaw: 'z',
Roll: 'x',
},
};
@inject('store') @observer
export default class CameraParam extends Component {
constructor(props) {
super(props);
this.resetParam = this.resetParam.bind(this);
}
resetParam() {
this.props.store.cameraData.reset();
}
renderParamRow(type) {
function getDeltaColorAndText(delta) {
let color = '#FFFFFF';
let text = '-';
if (delta > 0) {
color = '#1C9063';
text = `+${delta}`;
} else if (delta < 0) {
color = '#B43131';
text = delta;
}
return { color, text };
}
const { cameraData } = this.props.store;
let step = undefined;
switch (type) {
case 'Position': {
step = 2;
break;
}
case 'StaticRotation':
case 'DynamicRotation': {
step = 3;
break;
}
default:
console.warn('Unknown parameter type:', type);
return null;
}
const rows = Object.keys(FIELDS[type]).map((field) => {
const axis = FIELDS[type][field];
const adjustStep = Math.pow(0.1, step);
const value = cameraData[`init${type}`].get(axis).toFixed(step);
const delta = cameraData[`delta${type}`].get(axis).toFixed(step);
const { color, text } = getDeltaColorAndText(delta);
return (
<div className="camera-param-row" key={`${type}_${field}`}>
<div className="field">{field}</div>
<div className="value">{value}</div>
<div className="delta" style={{ color }}>{text}</div>
<div className="action">
<UpArrowSvg onClick={() => cameraData.update(
type, axis, adjustStep,
)}
/>
<DownArrowSvg onClick={() => cameraData.update(
type, axis, (-1) * adjustStep,
)}
/>
</div>
</div>
);
});
return rows;
}
renderCameraParam() {
return (
<div className="monitor-content">
<div className="section">
<div
className="section-title"
data-tip="Camera position in world coordinate system"
data-for="param"
>
<img height="20px" width="20px" src={positionIcon} />
<span>Position</span>
</div>
<div className="section-content">
{this.renderParamRow('Position')}
</div>
</div>
<div className="section">
<div className="section-title">
<img height="18px" width="20px" src={rotationIcon} />
<span>Rotation</span>
</div>
<div
className="section-subtitle"
data-tip="Camera rotation in IMU coordinate system, default facing to Z negative direction"
data-for="param"
>
Static
</div>
<div className="section-content">
{this.renderParamRow('StaticRotation')}
</div>
<div
className="section-subtitle"
data-tip="IMU rotation in world coordinate system"
data-for="param"
>
Dynamic
</div>
<div className="section-content">
{this.renderParamRow('DynamicRotation')}
</div>
</div>
<ReactTooltip id="param" place="right" delayShow={300} multiline />
</div>
);
}
render() {
return (
<div className="monitor camera-param">
<div className="monitor-header">
<div className="title">Camera Parameter</div>
<div className="actions">
<div
className="action"
onClick={this.resetParam}
data-tip="Reset"
data-for="action"
>
<ResetSvg />
</div>
<ReactTooltip id="action" place="left" delayShow={100} />
</div>
</div>
{this.renderCameraParam()}
</div>
);
}
}
|
src/screens/SettingsStack/SettingsScreen.js
|
AzSiAz/LN-Reader
|
import React from 'react'
import { View, AsyncStorage, Alert, StyleSheet } from 'react-native'
import { List, ListItem } from 'react-native-elements'
export default class SettingsScreen extends React.PureComponent {
static navigationOptions = {
title: 'Settings',
// headerStyle: {},
headerTitleStyle: {
color: 'black'
}
}
async clearAppInfo() {
await AsyncStorage.removeItem('info')
Alert.alert('Done', 'Cleared App Info reload app for it to take effect', [
{text: 'OK'}
], {
cancelable: false
})
}
render() {
return (
<View style={styles.container}>
<List>
<ListItem
hideChevron
underlayColor='lightgrey'
title='Clear App Information'
subtitle='Reset Intro'
onPress={this.clearAppInfo}
/>
</List>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
}
})
|
src/routes/lossSection/participate.js
|
goldylucks/adamgoldman.me
|
/* eslint-disable react/jsx-curly-brace-presence */
import React from 'react'
import { MESSENGER_LINK_WELCOME } from '../../constants'
import Markdown from '../../components/Markdown'
export default {
title: 'Participate',
description: 'Description here',
html: (
<div>
<Markdown
source={`
I (Adam) am currently at Chiang Mai, Thailand, GMT +7.
I'm available in [messenger](${MESSENGER_LINK_WELCOME}) most days between 10am-11pm.
When you are ready to have a more [resourceful response](/loss/resourceful-response) to your loss, [message](${MESSENGER_LINK_WELCOME}) me the following:
- Brief summary of your loss
- From 0-10, how strong are your feelings of loss/miss/emptiness regarding the loss
- From 0-10, how resourceful you feel regarding the loss
- 3 Available slots for your session
- Any questions, comments, or concerns you might have
[Talk soon](${MESSENGER_LINK_WELCOME}),
‐ **Adam**
`}
/>
</div>
),
}
|
examples/passing-props-to-children/app.js
|
aastey/react-router
|
import React from 'react'
import { createHistory, useBasename } from 'history'
import { Router, Route, Link, History } from 'react-router'
require('./app.css')
const history = useBasename(createHistory)({
basename: '/passing-props-to-children'
})
const App = React.createClass({
mixins: [ History ],
getInitialState() {
return {
tacos: [
{ name: 'duck confit' },
{ name: 'carne asada' },
{ name: 'shrimp' }
]
}
},
addTaco() {
let name = prompt('taco name?')
this.setState({
tacos: this.state.tacos.concat({ name })
})
},
handleRemoveTaco(removedTaco) {
this.setState({
tacos: this.state.tacos.filter(function (taco) {
return taco.name != removedTaco
})
})
this.history.pushState(null, '/')
},
render() {
let links = this.state.tacos.map(function (taco, i) {
return (
<li key={i}>
<Link to={`/taco/${taco.name}`}>{taco.name}</Link>
</li>
)
})
return (
<div className="App">
<button onClick={this.addTaco}>Add Taco</button>
<ul className="Master">
{links}
</ul>
<div className="Detail">
{this.props.children && React.cloneElement(this.props.children, {
onRemoveTaco: this.handleRemoveTaco
})}
</div>
</div>
)
}
})
const Taco = React.createClass({
remove() {
this.props.onRemoveTaco(this.props.params.name)
},
render() {
return (
<div className="Taco">
<h1>{this.props.params.name}</h1>
<button onClick={this.remove}>remove</button>
</div>
)
}
})
React.render((
<Router history={history}>
<Route path="/" component={App}>
<Route path="taco/:name" component={Taco} />
</Route>
</Router>
), document.getElementById('example'))
|
modules/Router.js
|
littlefoot32/react-router
|
import React from 'react'
import warning from 'warning'
import createHashHistory from 'history/lib/createHashHistory'
import { createRoutes } from './RouteUtils'
import RoutingContext from './RoutingContext'
import useRoutes from './useRoutes'
import { routes } from './PropTypes'
const { func, object } = React.PropTypes
/**
* A <Router> is a high-level API for automatically setting up
* a router that renders a <RoutingContext> with all the props
* it needs each time the URL changes.
*/
const Router = React.createClass({
propTypes: {
history: object,
children: routes,
routes, // alias for children
createElement: func,
onError: func,
onUpdate: func,
parseQueryString: func,
stringifyQuery: func
},
getInitialState() {
return {
location: null,
routes: null,
params: null,
components: null
}
},
handleError(error) {
if (this.props.onError) {
this.props.onError.call(this, error)
} else {
// Throw errors by default so we don't silently swallow them!
throw error // This error probably occurred in getChildRoutes or getComponents.
}
},
componentWillMount() {
let { history, children, routes, parseQueryString, stringifyQuery } = this.props
let createHistory = history ? () => history : createHashHistory
this.history = useRoutes(createHistory)({
routes: createRoutes(routes || children),
parseQueryString,
stringifyQuery
})
this._unlisten = this.history.listen((error, state) => {
if (error) {
this.handleError(error)
} else {
this.setState(state, this.props.onUpdate)
}
})
},
componentWillReceiveProps(nextProps) {
warning(
nextProps.history === this.props.history,
"The `history` provided to <Router/> has changed, it will be ignored."
)
},
componentWillUnmount() {
if (this._unlisten)
this._unlisten()
},
render() {
let { location, routes, params, components } = this.state
let { createElement } = this.props
if (location == null)
return null // Async match
return React.createElement(RoutingContext, {
history: this.history,
createElement,
location,
routes,
params,
components
})
}
})
export default Router
|
app/javascript/mastodon/features/account_gallery/components/media_item.js
|
KnzkDev/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Icon from 'mastodon/components/icon';
import { autoPlayGif, displayMedia } from 'mastodon/initial_state';
import classNames from 'classnames';
import { decode } from 'blurhash';
import { isIOS } from 'mastodon/is_mobile';
export default class MediaItem extends ImmutablePureComponent {
static propTypes = {
attachment: ImmutablePropTypes.map.isRequired,
displayWidth: PropTypes.number.isRequired,
onOpenMedia: PropTypes.func.isRequired,
};
state = {
visible: displayMedia !== 'hide_all' && !this.props.attachment.getIn(['status', 'sensitive']) || displayMedia === 'show_all',
loaded: false,
};
componentDidMount () {
if (this.props.attachment.get('blurhash')) {
this._decode();
}
}
componentDidUpdate (prevProps) {
if (prevProps.attachment.get('blurhash') !== this.props.attachment.get('blurhash') && this.props.attachment.get('blurhash')) {
this._decode();
}
}
_decode () {
const hash = this.props.attachment.get('blurhash');
const pixels = decode(hash, 32, 32);
if (pixels) {
const ctx = this.canvas.getContext('2d');
const imageData = new ImageData(pixels, 32, 32);
ctx.putImageData(imageData, 0, 0);
}
}
setCanvasRef = c => {
this.canvas = c;
}
handleImageLoad = () => {
this.setState({ loaded: true });
}
handleMouseEnter = e => {
if (this.hoverToPlay()) {
e.target.play();
}
}
handleMouseLeave = e => {
if (this.hoverToPlay()) {
e.target.pause();
e.target.currentTime = 0;
}
}
hoverToPlay () {
return !autoPlayGif && ['gifv', 'video'].indexOf(this.props.attachment.get('type')) !== -1;
}
handleClick = e => {
if (e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
if (this.state.visible) {
this.props.onOpenMedia(this.props.attachment);
} else {
this.setState({ visible: true });
}
}
}
render () {
const { attachment, displayWidth } = this.props;
const { visible, loaded } = this.state;
const width = `${Math.floor((displayWidth - 4) / 3) - 4}px`;
const height = width;
const status = attachment.get('status');
const title = status.get('spoiler_text') || attachment.get('description');
let thumbnail = '';
let icon;
if (attachment.get('type') === 'unknown') {
// Skip
} else if (attachment.get('type') === 'image') {
const focusX = attachment.getIn(['meta', 'focus', 'x']) || 0;
const focusY = attachment.getIn(['meta', 'focus', 'y']) || 0;
const x = ((focusX / 2) + .5) * 100;
const y = ((focusY / -2) + .5) * 100;
thumbnail = (
<img
src={attachment.get('preview_url')}
alt={attachment.get('description')}
title={attachment.get('description')}
style={{ objectPosition: `${x}% ${y}%` }}
onLoad={this.handleImageLoad}
/>
);
} else if (['gifv', 'video'].indexOf(attachment.get('type')) !== -1) {
const autoPlay = !isIOS() && autoPlayGif;
thumbnail = (
<div className={classNames('media-gallery__gifv', { autoplay: autoPlay })}>
<video
className='media-gallery__item-gifv-thumbnail'
aria-label={attachment.get('description')}
title={attachment.get('description')}
role='application'
src={attachment.get('url')}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
autoPlay={autoPlay}
loop
muted
/>
<span className='media-gallery__gifv__label'>GIF</span>
</div>
);
}
if (!visible) {
icon = (
<span className='account-gallery__item__icons'>
<Icon id='eye-slash' />
</span>
);
}
return (
<div className='account-gallery__item' style={{ width, height }}>
<a className='media-gallery__item-thumbnail' href={status.get('url')} target='_blank' onClick={this.handleClick} title={title}>
<canvas width={32} height={32} ref={this.setCanvasRef} className={classNames('media-gallery__preview', { 'media-gallery__preview--hidden': visible && loaded })} />
{visible && thumbnail}
{!visible && icon}
</a>
</div>
);
}
}
|
1l_React_ET_Lynda/Ex_Files_React_EssT/Ch04/04_03/finish/src/index.js
|
yevheniyc/Autodidact
|
import React from 'react'
import { render } from 'react-dom'
import './stylesheets/ui.scss'
import { SkiDayCount } from './components/SkiDayCount'
window.React = React
render(
<SkiDayCount />,
document.getElementById('react-container')
)
// render(
// <SkiDayList days={
// [
// {
// resort: "Squaw Valley",
// date: new Date("1/2/2016"),
// powder: true,
// backcountry: false
// },
// {
// resort: "Kirkwood",
// date: new Date("3/28/2016"),
// powder: false,
// backcountry: false
// },
// {
// resort: "Mt. Tallac",
// date: new Date("4/2/2016"),
// powder: false,
// backcountry: true
// }
// ]
// }/>,
// document.getElementById('react-container')
// )
|
index.js
|
algolia/react-nouislider
|
import PropTypes from 'prop-types';
import React from 'react';
import nouislider from 'nouislider';
class Nouislider extends React.Component {
componentDidMount() {
if (this.props.disabled) this.sliderContainer.setAttribute('disabled', true);
else this.sliderContainer.removeAttribute('disabled');
this.createSlider();
}
componentDidUpdate() {
if (this.props.disabled) this.sliderContainer.setAttribute('disabled', true);
else this.sliderContainer.removeAttribute('disabled');
this.slider.destroy();
this.createSlider();
}
componentWillUnmount() {
this.slider.destroy();
}
createSlider() {
var slider = (this.slider = nouislider.create(this.sliderContainer, {
...this.props
}));
if (this.props.onUpdate) {
slider.on('update', this.props.onUpdate);
}
if (this.props.onChange) {
slider.on('change', this.props.onChange);
}
if (this.props.onSlide) {
slider.on('slide', this.props.onSlide);
}
if (this.props.onStart) {
slider.on('start', this.props.onStart);
}
if (this.props.onEnd) {
slider.on('end', this.props.onEnd);
}
if (this.props.onSet) {
slider.on('set', this.props.onSet);
}
}
render() {
return (
<div
ref={slider => {
this.sliderContainer = slider;
}}
/>
);
}
}
Nouislider.propTypes = {
// http://refreshless.com/nouislider/slider-options/#section-animate
animate: PropTypes.bool,
// http://refreshless.com/nouislider/behaviour-option/
behaviour: PropTypes.string,
// http://refreshless.com/nouislider/slider-options/#section-Connect
connect: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.bool), PropTypes.bool]),
// http://refreshless.com/nouislider/slider-options/#section-cssPrefix
cssPrefix: PropTypes.string,
// http://refreshless.com/nouislider/slider-options/#section-orientation
direction: PropTypes.oneOf(['ltr', 'rtl']),
// http://refreshless.com/nouislider/more/#section-disable
disabled: PropTypes.bool,
// http://refreshless.com/nouislider/slider-options/#section-limit
limit: PropTypes.number,
// http://refreshless.com/nouislider/slider-options/#section-margin
margin: PropTypes.number,
// http://refreshless.com/nouislider/events-callbacks/#section-change
onChange: PropTypes.func,
// http://refreshless.com/nouislider/events-callbacks/
onEnd: PropTypes.func,
// http://refreshless.com/nouislider/events-callbacks/#section-set
onSet: PropTypes.func,
// http://refreshless.com/nouislider/events-callbacks/#section-slide
onSlide: PropTypes.func,
// http://refreshless.com/nouislider/events-callbacks/
onStart: PropTypes.func,
// http://refreshless.com/nouislider/events-callbacks/#section-update
onUpdate: PropTypes.func,
// http://refreshless.com/nouislider/slider-options/#section-orientation
orientation: PropTypes.oneOf(['horizontal', 'vertical']),
// http://refreshless.com/nouislider/pips/
pips: PropTypes.object,
// http://refreshless.com/nouislider/slider-values/#section-range
range: PropTypes.object.isRequired,
// http://refreshless.com/nouislider/slider-options/#section-start
start: PropTypes.arrayOf(PropTypes.number).isRequired,
// http://refreshless.com/nouislider/slider-options/#section-step
step: PropTypes.number,
// http://refreshless.com/nouislider/slider-options/#section-tooltips
tooltips: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.arrayOf(
PropTypes.shape({
to: PropTypes.func
})
)
])
};
module.exports = Nouislider;
|
test/TooltipSpec.js
|
xsistens/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Tooltip from '../src/Tooltip';
describe('Tooltip', function () {
it('Should output a tooltip with content', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Tooltip positionTop={10} positionLeft={20}>
<strong>Tooltip Content</strong>
</Tooltip>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong'));
const tooltip = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tooltip');
assert.deepEqual(tooltip.props.style, {top: 10, left: 20});
});
describe('When a style property is provided', function () {
it('Should render a tooltip with merged styles', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Tooltip style={{opacity: 0.9}} positionTop={10} positionLeft={20}>
<strong>Tooltip Content</strong>
</Tooltip>
);
const tooltip = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tooltip');
assert.deepEqual(tooltip.props.style, {opacity: 0.9, top: 10, left: 20});
});
});
});
|
public/pages/AdminOverview.js
|
datpham23/datndiana
|
import React from 'react'
import {Modal,Alert} from 'react-bootstrap';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as GuestActions from '../actions/guestActions';
import Griddle from 'griddle-react';
import '../sass/admin-overview.scss';
const AdminOverview = React.createClass({
componentWillMount: function() {
this.actions = bindActionCreators(GuestActions,this.props.dispatch);
},
onGuestFormUpdate(e){
this.actions.updateGuestForm(e.target.value);
},
render() {
let {guestsStore} = this.props;
let rows = guestsStore.guests.map(guest=>{
return {
'Name' : guest.name,
'Email' : guest.email,
'Phone' : guest.phone,
'Number of Guests Allowed' : guest.numberOfGuests,
'Vegetarian' : guest.vegetarian? 'YES' : 'NO',
'Status' : guest,
'Guests' : guest.guests,
'id' : guest.id,
}
});
var columnMeta = [
{
'columnName': 'Status',
'locked': false,
'visible': true,
'customComponent': (props)=>{
return (
<span>
{
props.data.hasRSVP?
`REPLIED (${props.data.guests.length})`
:
''
}
</span>
);
}
},
{
'columnName': 'Guests',
'locked': false,
'visible': true,
'customComponent': (props)=>{
return (
<span>
{
props.data?
props.data.join(', ')
:
null
}
</span>
);
}
}
];
return (
<div className="admin-overview">
<div className="button-container">
<button className="btn btn-default" onClick={this.actions.showModal}>
Import Guests
</button>
<button className="btn btn-default">
Export To Excel
</button>
<Modal show={guestsStore.showModal} onHide={this.actions.hideModal}>
<Modal.Header closeButton>
<Modal.Title>Import Guests</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className="guest-import">
<strong>Sample Row</strong>
<div>Name, Email, Phone Number, Number of Guests</div>
<br/>
{
guestsStore.saveGuestsError?
<Alert bsStyle='danger'>
{guestsStore.saveGuestsErrorMessage}
</Alert>
:
null
}
{
guestsStore.isSavingGuests?
<div className="loader"/>
:
<textarea
value={guestsStore.guestForm}
rows="4"
cols="50"
onChange={this.onGuestFormUpdate}/>
}
</div>
</Modal.Body>
<Modal.Footer>
<button className="btn btn-primary" onClick={this.actions.saveGuests}>
Save
</button>
</Modal.Footer>
</Modal>
</div>
<div>
{
guestsStore.isFetching?
<div className="loader"/>
:
<div>
<Griddle
showFilter={true}
resultsPerPage={1000}
tableClassName='table table-striped table-hover'
results={rows}
columns={['Name', 'Email', 'Phone', 'Number of Guests Allowed','Vegetarian','Status', 'Guests']}
useGriddleStyles={false}
columnMetadata={columnMeta}
/>
</div>
}
</div>
</div>
)
}
})
export default connect(state=>{
return {
guestsStore : state.guests.toJS()
}
})(AdminOverview);
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/RestAndDefault.js
|
ontruck/create-react-app
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function load({ id, ...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>
);
}
}
|
examples/infinite-scrolling/src/components/RepositoryCount.js
|
lore/lore
|
import React from 'react';
import createReactClass from 'create-react-class';
import PropTypes from 'prop-types';
import PayloadStates from '../constants/PayloadStates';
export default createReactClass({
displayName: 'RepositoryCount',
propTypes: {
pages: PropTypes.array.isRequired
},
getStyles: function() {
return {
count: {
textAlign: 'center',
opacity: '0.54'
}
}
},
render: function() {
const pages = this.props.pages;
const styles = this.getStyles();
const numberOfPages = pages.length;
const firstPage = pages[0];
const lastPage = pages[numberOfPages - 1];
const repositoriesPerPage = firstPage.data.length;
let resultCount = 0;
let totalRepositories = 0;
if (lastPage.state === PayloadStates.FETCHING) {
resultCount = (numberOfPages - 1)*repositoriesPerPage;
totalRepositories = firstPage.meta.totalCount;
} else {
resultCount = numberOfPages*repositoriesPerPage;
totalRepositories = lastPage.meta.totalCount;
}
return (
<h4 style={styles.count}>
Showing {resultCount} of {totalRepositories} repositories with > 1000 stars
</h4>
);
}
});
|
js-old/MyTitle.js
|
aramay/complete-intro-to-react-v2
|
import React from 'react'
var MyTitle = React.createClass({
render: function () {
console.log(this.props)
const color = {color: this.props.color}
console.log(color)
return (
<div>
<h1 style={color}>
{this.props.title}
</h1>
</div>
)
}
})
export default MyTitle
|
src/components/ChaptersList/ChaptersList.js
|
suhodolskiy/bsuir-evt-laba-2017
|
import React from 'react';
import { observer } from 'mobx-react';
import { SortableContainer, SortableElement } from 'react-sortable-hoc';
import './chaptersList.scss';
import ChapterCard from '../СhapterCard/ChapterCard';
export default SortableContainer(
observer(({ chapters, moveChapterToBlank }) => (
<ul className="chapters-list">
{chapters.map((chapter, i) => (
<ChapterCard
moveChapterToBlank={moveChapterToBlank}
chapter={chapter}
key={`chapter-${i}`}
index={i}
number={i + 1}
/>
))}
</ul>
))
);
// function ChaptersList({ chapters }) {
// // const List = SortableContainer(({ chapters }) => chapters.map((chapter, index) => <SortableItem chapter={chapter}/>));
// return (
// <SortableContainer>
// {() =>
// chapters.map((chapter, index) => <SortableItem chapter={chapter}/>)
// }
// </SortableContainer>
// )
// }
// const { chapters } = this.props;
//
// if (!chapters || !chapters.length) {
// return (
// <div className="chapters-list chapters-list--empty">Список пуст</div>
// );
// }
|
app/addons/documents/index-results/components/pagination/PaginationFooter.js
|
popojargo/couchdb-fauxton
|
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
import React from 'react';
import PagingControls from './PagingControls.js';
import PerPageSelector from './PerPageSelector.js';
import TableControls from './TableControls';
export default class PaginationFooter extends React.Component {
constructor(props) {
super(props);
}
getPageNumberText () {
const { docs, pageStart, pageEnd } = this.props;
if (docs.length === 0) {
return <span>Showing 0 documents.</span>;
}
return <span>Showing document {pageStart} - {pageEnd}.</span>;
}
perPageChange (amount) {
const { updatePerPageResults, fetchParams, queryOptionsParams } = this.props;
updatePerPageResults(amount, fetchParams, queryOptionsParams);
}
nextClicked (event) {
event.preventDefault();
const { canShowNext, fetchParams, queryOptionsParams, paginateNext, perPage } = this.props;
if (canShowNext) {
paginateNext(fetchParams, queryOptionsParams, perPage);
}
}
previousClicked (event) {
event.preventDefault();
const { canShowPrevious, fetchParams, queryOptionsParams, paginatePrevious, perPage } = this.props;
if (canShowPrevious) {
paginatePrevious(fetchParams, queryOptionsParams, perPage);
}
}
render () {
const {
showPrioritizedEnabled,
hasResults,
prioritizedEnabled,
displayedFields,
perPage,
canShowNext,
canShowPrevious,
toggleShowAllColumns
} = this.props;
return (
<footer className="index-pagination pagination-footer">
<PagingControls
nextClicked={this.nextClicked.bind(this)}
previousClicked={this.previousClicked.bind(this)}
canShowNext={canShowNext}
canShowPrevious={canShowPrevious} />
<div className="footer-controls">
<div className="page-controls">
{showPrioritizedEnabled && hasResults ?
<TableControls
prioritizedEnabled={prioritizedEnabled}
displayedFields={displayedFields}
toggleShowAllColumns={toggleShowAllColumns} /> : null}
</div>
<PerPageSelector perPageChange={this.perPageChange.bind(this)} perPage={perPage} />
<div className="current-docs">
{this.getPageNumberText()}
</div>
</div>
</footer>
);
}
};
|
src/components/doctrine/original/DoctrineOriginal.js
|
fpoumian/react-devicon
|
import React from 'react'
import PropTypes from 'prop-types'
import SVGDeviconInline from '../../_base/SVGDeviconInline'
import iconSVG from './DoctrineOriginal.svg'
/** DoctrineOriginal */
function DoctrineOriginal({ width, height, className }) {
return (
<SVGDeviconInline
className={'DoctrineOriginal' + ' ' + className}
iconSVG={iconSVG}
width={width}
height={height}
/>
)
}
DoctrineOriginal.propTypes = {
className: PropTypes.string,
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
}
export default DoctrineOriginal
|
src/index.js
|
HHPnet/frontend
|
import React from 'react'
import ReactDOM from 'react-dom'
import injectTapEventPlugin from 'react-tap-event-plugin'
import App from './components/common/app/App'
import 'bootstrap/dist/css/bootstrap.css'
//import 'bootstrap/dist/css/bootstrap-theme.css'
//import 'bootstrap-material-design/dist/css/bootstrap-material-design.css'
//import 'bootstrap-material-design/dist/css/ripples.css'
import './index.css'
injectTapEventPlugin()
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/DefaultPropsInline.js
|
jamesgpearce/flow
|
// @flow
import React from 'react';
class MyComponent extends React.Component {
static defaultProps: {a: number, b: number, c: number} = {a: 1, b: 2, c: 3};
props: Props;
defaultProps: T;
static props: T;
static state: T;
a: T;
b = 5;
c: T = 5;
method() {}
}
const expression = () =>
class extends React.Component {
static defaultProps: {a: number, b: number, c: number} = {a: 1, b: 2, c: 3};
props: Props;
defaultProps: T;
static props: T;
static state: T;
a: T;
b = 5;
c: T = 5;
method() {}
}
|
client/views/admin/federationDashboard/OverviewSection.stories.js
|
VoiSmart/Rocket.Chat
|
import React from 'react';
import OverviewSection from './OverviewSection';
export default {
title: 'admin/federationDashboard/OverviewSection',
component: OverviewSection,
};
export const Default = () => <OverviewSection />;
|
docs/app/Examples/elements/Icon/States/index.js
|
mohammed88/Semantic-UI-React
|
import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const IconStatesExamples = () => (
<ExampleSection title='States'>
<ComponentExample
title='Disabled'
description='An icon can show that it is disabled.'
examplePath='elements/Icon/States/IconExampleDisabled'
/>
<ComponentExample
title='Loading'
description='An icon can be used as a simple loader.'
examplePath='elements/Icon/States/IconExampleLoading'
/>
</ExampleSection>
)
export default IconStatesExamples
|
docs-ui/components/emptyMessage.stories.js
|
looker/sentry
|
import React from 'react';
import {Panel, PanelHeader} from 'app/components/panels';
import {storiesOf} from '@storybook/react';
import {withInfo} from '@storybook/addon-info';
import Button from 'app/components/buttons/button';
import EmptyMessage from 'app/views/settings/components/emptyMessage';
storiesOf('EmptyMessage', module)
.add(
'default',
withInfo('Super Generic')(() => (
<div style={{background: '#fff'}}>
<EmptyMessage>Nothing to see here</EmptyMessage>
</div>
))
)
.add(
'in panel',
withInfo('Put this in a panel for maximum effect')(() => (
<Panel>
<PanelHeader>Audit Log</PanelHeader>
<EmptyMessage>No critical actions taken in this period</EmptyMessage>
</Panel>
))
)
.add(
'in panel with icon',
withInfo('Put this in a panel for maximum effect')(() => (
<Panel>
<PanelHeader>Members</PanelHeader>
<EmptyMessage icon="icon-user" size="large">
Sentry is better with friends
</EmptyMessage>
</Panel>
))
)
.add(
'in panel with icon and action',
withInfo('Put this in a panel for maximum effect')(() => (
<Panel>
<PanelHeader>Members</PanelHeader>
<EmptyMessage
icon="icon-user"
action={<Button priority="primary">Invite Members</Button>}
>
Sentry is better with friends
</EmptyMessage>
</Panel>
))
)
.add(
'in panel with sub-description',
withInfo('Put this in a panel for maximum effect')(() => (
<Panel>
<PanelHeader>Members</PanelHeader>
<EmptyMessage
title="Sentry is better with Friends"
description="When you use sentry with friends, you'll find your world of possibilities expands!"
/>
</Panel>
))
);
|
classic/src/scenes/wbui/ULinkOR/ULinkORAccountSection/MailboxListItem/MailboxListItemSubServiceItem.js
|
wavebox/waveboxapp
|
import React from 'react'
import PropTypes from 'prop-types'
import shallowCompare from 'react-addons-shallow-compare'
import { ListItemSecondaryAction, Tooltip, IconButton } from '@material-ui/core'
import { withStyles } from '@material-ui/core/styles'
import ACAvatarCircle2 from '../../../ACAvatarCircle2'
import MailboxServiceBadge from '../../../MailboxServiceBadge'
import classNames from 'classnames'
import TabIcon from '@material-ui/icons/Tab'
import OpenInNewIcon from '@material-ui/icons/OpenInNew'
import ULinkORListItem from '../../ULinkORListItem'
import ULinkORListItemText from '../../ULinkORListItemText'
const privAccountStore = Symbol('privAccountStore')
const styles = {
root: {
paddingTop: 0,
paddingBottom: 0,
paddingRight: 84,
paddingLeft: 32,
height: 48
},
avatarContainer: {
position: 'relative',
width: 28,
minWidth: 28,
height: 28,
minHeight: 28,
marginRight: 4
},
badge: {
position: 'absolute',
fontWeight: process.platform === 'linux' ? 'normal' : '300',
height: 18,
minWidth: 18,
width: 'auto',
lineHeight: '18px',
fontSize: '10px',
top: -3,
right: -7,
boxShadow: ' 0px 0px 1px 0px rgba(0,0,0,0.8)'
},
badgeFAIcon: {
color: 'white',
fontSize: '10px'
},
badgeContainer: {
display: 'flex',
position: 'relative',
justifyContent: 'center',
alignItems: 'center',
width: 28,
height: 28
}
}
@withStyles(styles)
class MailboxListItemSubServiceItem extends React.Component {
/* **************************************************************************/
// Class
/* **************************************************************************/
static propTypes = {
serviceId: PropTypes.string.isRequired,
accountStore: PropTypes.object.isRequired,
avatarResolver: PropTypes.func.isRequired,
onOpenInRunningService: PropTypes.func.isRequired,
onOpenInServiceWindow: PropTypes.func.isRequired
}
/* **************************************************************************/
// Lifecycle
/* **************************************************************************/
constructor (props) {
super(props)
this[privAccountStore] = this.props.accountStore
// Generate state
this.state = {
...this.generateServiceState(this.props.serviceId, this[privAccountStore].getState())
}
}
/* **************************************************************************/
// Component lifecycle
/* **************************************************************************/
componentDidMount () {
this[privAccountStore].listen(this.accountUpdated)
}
componentWillUnmount () {
this[privAccountStore].unlisten(this.accountUpdated)
}
componentWillReceiveProps (nextProps) {
if (this.props.accountStore !== nextProps.accountStore) {
console.warn('Changing props.accountStore is not supported in ULinkORAccountResultListItem and will be ignored')
}
if (this.props.serviceId !== nextProps.serviceId) {
this.setState(
this.generateServiceState(nextProps.serviceId, this[privAccountStore].getState())
)
}
}
/* **************************************************************************/
// Data lifecycle
/* **************************************************************************/
accountUpdated = (accountState) => {
this.setState(
this.generateServiceState(this.props.serviceId, accountState)
)
}
generateServiceState (serviceId, accountState) {
const mailbox = accountState.getMailboxForService(serviceId)
const service = accountState.getService(serviceId)
const serviceData = accountState.getServiceData(serviceId)
if (mailbox && service && serviceData) {
const authData = accountState.getMailboxAuthForServiceId(serviceId)
const isServiceSleeping = accountState.isServiceSleeping(serviceId)
return {
membersAvailable: true,
displayName: accountState.resolvedServiceDisplayName(serviceId),
serviceAvatar: accountState.getServiceAvatarConfig(serviceId),
isServiceSleeping: isServiceSleeping,
supportsUnreadCount: service.supportsUnreadCount,
showBadgeCount: service.showBadgeCount,
unreadCount: serviceData.getUnreadCount(service),
hasUnreadActivity: serviceData.getHasUnreadActivity(service),
supportsUnreadActivity: service.supportsUnreadActivity,
showBadgeActivity: service.showBadgeActivity,
badgeColor: service.badgeColor,
documentTitle: serviceData.documentTitle,
nextUrl: isServiceSleeping
? service.getUrlWithData(serviceData, authData)
: service.url
}
} else {
return {
membersAvailable: false
}
}
}
/* **************************************************************************/
// UI Events
/* **************************************************************************/
/**
* Handles a click somewhere in the list item
* @param evt: the event that fired
*/
handleListItemClick = (evt) => {
const { onClick, onOpenInServiceWindow, serviceId } = this.props
onOpenInServiceWindow(evt, serviceId)
if (onClick) { onClick(evt) }
}
/**
* Handles the open in account button being clicked
* @param evt: the event that fired
*/
handleOpenInAccountClick = (evt) => {
evt.preventDefault()
evt.stopPropagation()
const { onOpenInRunningService, serviceId } = this.props
onOpenInRunningService(evt, serviceId)
}
/**
* Handles the open in window button being clicked
* @param evt: the event that fired
*/
handleOpenInWindowClick = (evt) => {
evt.preventDefault()
evt.stopPropagation()
const { onOpenInServiceWindow, serviceId } = this.props
onOpenInServiceWindow(evt, serviceId)
}
/* **************************************************************************/
// Rendering
/* **************************************************************************/
shouldComponentUpdate (nextProps, nextState) {
return shallowCompare(this, nextProps, nextState)
}
render () {
const {
classes,
serviceId,
avatarResolver,
accountStore,
onOpenInRunningService,
onOpenInServiceWindow,
className,
onClick,
...passProps
} = this.props
const {
membersAvailable,
displayName,
serviceAvatar,
isServiceSleeping,
supportsUnreadCount,
showBadgeCount,
unreadCount,
hasUnreadActivity,
supportsUnreadActivity,
showBadgeActivity,
badgeColor,
documentTitle,
nextUrl
} = this.state
if (!membersAvailable) { return false }
return (
<ULinkORListItem
className={classNames(className, classes.root)}
onClick={this.handleListItemClick}
{...passProps}>
<div className={classes.avatarContainer}>
<MailboxServiceBadge
badgeClassName={classes.badge}
className={classes.badgeContainer}
iconClassName={classes.badgeFAIcon}
supportsUnreadCount={supportsUnreadCount}
showUnreadBadge={showBadgeCount}
unreadCount={unreadCount}
supportsUnreadActivity={supportsUnreadActivity}
showUnreadActivityBadge={showBadgeActivity}
hasUnreadActivity={hasUnreadActivity}
color={badgeColor}
isAuthInvalid={false}>
<ACAvatarCircle2
avatar={serviceAvatar}
size={28}
resolver={avatarResolver}
showSleeping={isServiceSleeping}
circleProps={{ showSleeping: false }} />
</MailboxServiceBadge>
</div>
<ULinkORListItemText
primary={displayName}
primaryTypographyProps={{ noWrap: true }}
secondary={documentTitle && documentTitle !== displayName ? documentTitle : nextUrl}
secondaryTypographyProps={{ noWrap: true }} />
<ListItemSecondaryAction>
<Tooltip title='Open in existing account tab'>
<IconButton onClick={this.handleOpenInAccountClick}>
<TabIcon />
</IconButton>
</Tooltip>
<Tooltip title='Open in new Window'>
<IconButton onClick={this.handleOpenInWindowClick}>
<OpenInNewIcon />
</IconButton>
</Tooltip>
</ListItemSecondaryAction>
</ULinkORListItem>
)
}
}
export default MailboxListItemSubServiceItem
|
node_modules/react-router/es6/Link.js
|
TheeSweeney/ComplexReactReduxMiddlewareReview
|
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
import React from 'react';
import warning from './routerWarning';
import invariant from 'invariant';
import { routerShape } from './PropTypes';
var _React$PropTypes = React.PropTypes;
var bool = _React$PropTypes.bool;
var object = _React$PropTypes.object;
var string = _React$PropTypes.string;
var func = _React$PropTypes.func;
var oneOfType = _React$PropTypes.oneOfType;
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
// TODO: De-duplicate against hasAnyProperties in createTransitionManager.
function isEmptyObject(object) {
for (var p in object) {
if (Object.prototype.hasOwnProperty.call(object, p)) return false;
}return true;
}
function createLocationDescriptor(to, _ref) {
var query = _ref.query;
var hash = _ref.hash;
var state = _ref.state;
if (query || hash || state) {
return { pathname: to, query: query, hash: hash, state: state };
}
return to;
}
/**
* A <Link> is used to create an <a> element that links to a route.
* When that route is active, the link gets the value of its
* activeClassName prop.
*
* For example, assuming you have the following route:
*
* <Route path="/posts/:postID" component={Post} />
*
* You could use the following component to link to that route:
*
* <Link to={`/posts/${post.id}`} />
*
* Links may pass along location state and/or query string parameters
* in the state/query props, respectively.
*
* <Link ... query={{ show: true }} state={{ the: 'state' }} />
*/
var Link = React.createClass({
displayName: 'Link',
contextTypes: {
router: routerShape
},
propTypes: {
to: oneOfType([string, object]),
query: object,
hash: string,
state: object,
activeStyle: object,
activeClassName: string,
onlyActiveOnIndex: bool.isRequired,
onClick: func,
target: string
},
getDefaultProps: function getDefaultProps() {
return {
onlyActiveOnIndex: false,
style: {}
};
},
handleClick: function handleClick(event) {
if (this.props.onClick) this.props.onClick(event);
if (event.defaultPrevented) return;
!this.context.router ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Link>s rendered outside of a router context cannot navigate.') : invariant(false) : void 0;
if (isModifiedEvent(event) || !isLeftClickEvent(event)) return;
// If target prop is set (e.g. to "_blank"), let browser handle link.
/* istanbul ignore if: untestable with Karma */
if (this.props.target) return;
event.preventDefault();
var _props = this.props;
var to = _props.to;
var query = _props.query;
var hash = _props.hash;
var state = _props.state;
var location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
this.context.router.push(location);
},
render: function render() {
var _props2 = this.props;
var to = _props2.to;
var query = _props2.query;
var hash = _props2.hash;
var state = _props2.state;
var activeClassName = _props2.activeClassName;
var activeStyle = _props2.activeStyle;
var onlyActiveOnIndex = _props2.onlyActiveOnIndex;
var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']);
process.env.NODE_ENV !== 'production' ? warning(!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : void 0;
// Ignore if rendered outside the context of router, simplifies unit testing.
var router = this.context.router;
if (router) {
// If user does not specify a `to` prop, return an empty anchor tag.
if (to == null) {
return React.createElement('a', props);
}
var location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
props.href = router.createHref(location);
if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) {
if (router.isActive(location, onlyActiveOnIndex)) {
if (activeClassName) {
if (props.className) {
props.className += ' ' + activeClassName;
} else {
props.className = activeClassName;
}
}
if (activeStyle) props.style = _extends({}, props.style, activeStyle);
}
}
}
return React.createElement('a', _extends({}, props, { onClick: this.handleClick }));
}
});
export default Link;
|
example/App.js
|
BBuzzArt/react-native-infinite
|
import React from 'react';
import { StyleSheet, Text, View, TouchableHighlight, ScrollView } from 'react-native';
import { StackNavigator } from 'react-navigation';
import * as src from './src';
class App extends React.Component {
render() {
const { props } = this;
return (
<View style={css.viewport}>
<ScrollView style={css.index}>
<TouchableHighlight
activeOpacity={1}
underlayColor="rgba(0,0,0,.01)"
onPress={() => props.navigation.navigate('ExampleBasic')}>
<View style={css.item}>
<Text style={css.item__text}>Basic / load items to infinity</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
activeOpacity={1}
underlayColor="rgba(0,0,0,.01)"
onPress={() => props.navigation.navigate('ExampleResize')}>
<View style={css.item}>
<Text style={css.item__text}>Resize / resize screen event</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
activeOpacity={1}
underlayColor="rgba(0,0,0,.01)"
onPress={() => props.navigation.navigate('ExampleScroll')}>
<View style={css.item}>
<Text style={css.item__text}>Scroll / scroll event method</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
activeOpacity={1}
underlayColor="rgba(0,0,0,.01)"
onPress={() => props.navigation.navigate('ExampleGrid')}>
<View style={css.item}>
<Text style={css.item__text}>Grid / random size blocks</Text>
</View>
</TouchableHighlight>
</ScrollView>
</View>
);
}
}
const css = StyleSheet.create({
viewport: {
flex: 1,
},
index: {},
item: {
paddingVertical: 15,
paddingHorizontal: 15,
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: 'rgba(0,0,0,.2)',
},
item__text: {
fontWeight: '600',
fontSize: 16,
color: '#324dff',
},
cardStyle: {
backgroundColor: '#fff'
},
headerStyle: {
backgroundColor: '#fff',
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: '#aaa',
},
});
export default StackNavigator({
Home: { screen: App, navigationOptions: { title: 'Demos', headerStyle: css.headerStyle } },
ExampleBasic: { screen: src.ExampleBasic, navigationOptions: { title: 'Basic', headerStyle: css.headerStyle } },
ExampleResize: { screen: src.ExampleResize, navigationOptions: { title: 'Resize', headerStyle: css.headerStyle } },
ExampleScroll: { screen: src.ExampleScroll, navigationOptions: { title: 'Scroll', headerStyle: css.headerStyle } },
ExampleGrid: { screen: src.ExampleGrid, navigationOptions: { title: 'Grid', headerStyle: css.headerStyle } },
}, {
cardStyle: css.cardStyle,
});
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/TemplateInterpolation.js
|
RobzDoom/frame_trap
|
/**
* 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(name) {
return [
{ id: 1, name: `${name}1` },
{ id: 2, name: `${name}2` },
{ id: 3, name: `${name}3` },
{ id: 4, name: `${name}4` },
];
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = load('user_');
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-template-interpolation">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
source/component/listview/userPostRow.js
|
togayther/react-native-cnblogs
|
import React, { Component } from 'react';
import {
View,
Text,
Image,
TouchableHighlight
} from 'react-native';
import _ from 'lodash';
import moment from 'moment';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import { decodeHTML, getBloggerAvatar } from '../../common';
import { ComponentStyles, CommonStyles, StyleConfig } from '../../style';
class UserPostRow extends Component {
constructor(props) {
super(props);
this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
}
getPostInfo(){
let { post } = this.props;
let postInfo = {};
if (post && post.Id) {
postInfo.Id = post.Id;
postInfo.ViewCount = post.ViewCount;
postInfo.CommentCount = post.CommentCount;
postInfo.Title = decodeHTML(post.Title);
if (post.Description) {
postInfo.Description = _.truncate(decodeHTML(post.Description), { length : 70 });
}
postInfo.DateAdded = moment(post.PostDate).startOf('minute').fromNow();
postInfo.Author = decodeHTML(post.Author);
postInfo.Blogger = post.BlogApp;
postInfo.Avatar = getBloggerAvatar(post.Avatar);
}
return postInfo;
}
renderPostTitle(postInfo){
return (
<View style={ [ CommonStyles.m_b_1 ] }>
<Text style={ [CommonStyles.text_black, CommonStyles.font_sm, CommonStyles.line_height_md ] }>
{ postInfo.Title }
</Text>
</View>
)
}
renderPostDescr(postInfo){
return (
<View style={ [ CommonStyles.m_b_2 ] }>
<Text style={ [ CommonStyles.text_gray, CommonStyles.font_xs, CommonStyles.line_height_sm ] }>
{ postInfo.Description }
</Text>
</View>
)
}
renderPostMeta(postInfo){
return (
<View style={ [ CommonStyles.flexRow, CommonStyles.flexItemsBetween ] }>
<Text style={ [CommonStyles.text_gray, CommonStyles.font_ms] }>
{ postInfo.DateAdded }
</Text>
<View>
<Text style={ [ CommonStyles.text_primary ] }>
{ postInfo.CommentCount + ' / ' + postInfo.ViewCount }
</Text>
</View>
</View>
)
}
render() {
const postInfo = this.getPostInfo();
return (
<TouchableHighlight
onPress={(e)=>{ this.props.onRowPress(postInfo) }}
underlayColor={ StyleConfig.touchable_press_color }
key={ postInfo.Id }>
<View style={ ComponentStyles.list }>
{ this.renderPostTitle(postInfo) }
{ this.renderPostDescr(postInfo) }
{ this.renderPostMeta(postInfo) }
</View>
</TouchableHighlight>
)
}
}
export default UserPostRow;
|
src/components/WorkSummary.js
|
computer-lab/salon94design.com
|
import React from 'react'
import PropTypes from 'prop-types'
import Link from 'gatsby-link'
import styled from 'emotion/react'
import cx from 'classnames'
import {
monoFontFamily,
sansfont,
childLink,
breakpoint1,
breakpoint2,
breakpoint3,
baseUl,
} from '../layouts/emotion-base'
import { designerLink, workTagLink, projectLink, capitalize } from '../util'
const Container = styled.div`
composes: ${sansfont};
font-weight: 300;
max-width: 400px;
&.detailed {
margin-bottom: 20px;
max-width: none;
}
`
const DetailSection = styled.ul`
composes: ${baseUl};
margin-bottom: 20px;
@media (${breakpoint1}) {
margin-bottom: 16px;
}
@media (${breakpoint3}) {
margin-top: 8px;
}
`
const SummaryItem = styled.li`
composes: ${childLink};
margin: 0 0 6px 0;
line-height: 1.25;
font-size: 18px;
&:last-child {
margin-bottom: 0;
}
&.designer {
font-weight: 500;
}
&.project,
&.tag {
font-size: 18px;
font-weight: 500;
}
@media (${breakpoint1}) {
font-size: 16px;
}
`
const WorkSummary = ({ designer, work, detailed, projects }) => (
<Container className={cx({ detailed })}>
<DetailSection>
{designer && (
<SummaryItem className="designer">
<Link style={{'fontWeight': 500}} to={designerLink(designer.slug)}>{designer.name}</Link>
</SummaryItem>
)}
<SummaryItem style={{'fontStyle': 'italic'}}>{work.title}</SummaryItem>
<SummaryItem>{work.when}</SummaryItem>
<SummaryItem>{work.caption}</SummaryItem>
<SummaryItem>{work.medium}</SummaryItem>
<SummaryItem>{work.dimensions}</SummaryItem>
<SummaryItem>{work.edition}</SummaryItem>
<SummaryItem>{work.price}</SummaryItem>
</DetailSection>
<DetailSection>
{projects &&
projects.length > 0 &&
projects.filter(p => !!p).map(project => (
<SummaryItem key={project.slug} className="project">
<Link to={projectLink(project)}>{project.title}</Link>
</SummaryItem>
))}
{detailed &&
work.tags &&
work.tags.map(tag => (
<SummaryItem key={tag} className="tag">
<Link to={workTagLink(tag)}>{capitalize(tag)}</Link>
</SummaryItem>
))}
</DetailSection>
</Container>
)
WorkSummary.propTypes = {
work: PropTypes.object.isRequired,
designer: PropTypes.object,
projects: PropTypes.array,
detailed: PropTypes.bool,
}
export default WorkSummary
|
client/src/components/help/Container.js
|
DjLeChuck/recalbox-manager
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import reactStringReplace from 'react-string-replace';
import { recalboxSupport } from '../../api';
import Help from './Help';
class HelpContainer extends Component {
static propTypes = {
t: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = {
stickyContent: null,
};
}
componentDidMount() {
window.location.hash = window.decodeURIComponent(window.location.hash);
if ('#launch-support' === window.location.hash) {
this.doRecalboxSupport();
}
}
doRecalboxSupport = () => {
this.setState({ callingSupport: true });
recalboxSupport().then(
result => (
this.setState({
callingSupport: false,
downloadUrl: result.url,
})
),
err => (
this.setState({
callingSupport: false,
stickyContent: err.message,
})
)
);
};
render() {
const { t } = this.props;
const supportSentence = reactStringReplace(t("Si on vous demande d'envoyer le résultat du script %s, vous pouvez le faire automatiquement ci-dessous."), '%s', (match, i) => (
<code key={i}>recalbox-support.sh</code>
));
return (
<Help {...this.state} links={[{
label: t('Le forum :'),
link: t("https://forum.recalbox.com/"),
}, {
label: t('Le chan IRC :'),
link: t("https://kiwiirc.com/client/irc.freenode.net/#recalbox"),
}, {
label: t('Le wiki :'),
link: t("https://github.com/recalbox/recalbox-os/wiki/Home-(FR)"),
}]}
callSupport={this.doRecalboxSupport} supportSentence={supportSentence} />
);
}
}
export default translate()(HelpContainer);
|
src/client/react/user/views/Instructions/InstructionCollapse.js
|
bwyap/ptc-amazing-g-race
|
import React from 'react';
import autobind from 'core-decorators/es/autobind';
import { Button, Intent, Collapse } from '@blueprintjs/core';
import MarkdownRenderer from '../../../../../../lib/react/components/MarkdownRenderer';
import '../../scss/components/_instruction-panel.scss';
@autobind
class InstructionCollapse extends React.Component {
state = {
isOpen: false,
}
toggleOpen() {
this.setState((prevState) => {
return { isOpen: !prevState.isOpen }
});
}
render() {
const { title, content } = this.props.article;
return (
<div className='instruction-collapse'>
<Button className='pt-fill' text={title} intent={Intent.PRIMARY}
iconName={this.state.isOpen?'chevron-down':'chevron-right'} onClick={this.toggleOpen}/>
<Collapse isOpen={this.state.isOpen}>
<div className='instruction-panel'>
<MarkdownRenderer className='markdown-content' src={content}/>
</div>
</Collapse>
</div>
);
}
}
export default InstructionCollapse;
|
web/static/js/layouts/main.js
|
wwselleck/Rekrewtor
|
import React from 'react'
import { Link } from 'react-router'
export default class MainLayout extends React.Component {
render () {
return (
<div>
{this.props.children}
</div>
)
}
}
|
src/components/blocks/index.js
|
impact-initiatives/reach-jor-zaatari-webmap
|
import React from 'react';
import styles from '../../styles/index.js';
import Header from '../common/header/index.js';
import Footer from '../common/footer/index.js';
import SidebarHome from '../common/home/index.js';
import MapboxGL from '../common/mapbox-gl/index.js';
import SidebarLayers from './sidebar-layers/index.js';
import SidebarInfo from './sidebar-info/index.js';
import * as language from '../../constants/languages.js';
import img from '../../constants/images.js';
import messages from '../../translations/blocks.js';
export default ({ state }) => (
<div className={`${styles.flex.verticalNormal} ${styles.inline.fontDefault}`}
dir={state.lang === language.AR ? 'rtl' : 'ltr'}>
<Header messages={messages}
state={state} />
<div className={styles.menu.content}>
<SidebarHome state={state} />
<SidebarInfo state={state} />
<SidebarLayers state={state} />
<MapboxGL />
</div>
<Footer donorLogo={img.LOGO_UNHCR} />
</div>
);
|
frontend-app/welcome-app/main/welcome-main.js
|
easybird/easyblog
|
import React from 'react';
import DraftEditor from '../../article/editor/draft-editor.js';
import Article from '../../article/article.js';
import ArticleOverview from '../../article/article-overview.js';
import ArticleList from '../../article/api/article-list/article-list.js';
import ArticlePage from '../../article/api/article-page/article-page.js';
import { getBlockStyle, styleMap, getMediaBlockObject, articleStyle} from '../../article/constants/styles.js';
import { convertToRawDraftContentState } from '../../article/helpers/convert-editor-state.js';
class WelcomeMain extends React.Component {
constructor(props) {
super(props);
this.state = {
rawDraft: props.initialRawDraft
};
this._onSaveDraft = this._onSaveDraft.bind(this);
}
_onSaveDraft(editorState) {
const rawDraft = convertToRawDraftContentState(editorState);
console.log("save raw draft: " + JSON.stringify(rawDraft));
this.setState({
rawDraft: rawDraft
})
}
render() {
const {rawDraft} = this.state;
const {initialRawDraft} = this.props;
const blockStyleFn = getBlockStyle;
const blockRendererFn = getMediaBlockObject;
const customStyleMap = styleMap;
const customArticleStyle = articleStyle;
const onSaveDraft = this._onSaveDraft;
return (
<main>
<div className="section" />
<div className= "container">
<div className= "row">
<div className= "col s12">
<DraftEditor
onSaveDraft={ onSaveDraft }
blockStyleFn={ blockStyleFn}
blockRendererFn={blockRendererFn}
customStyleMap= {customStyleMap}
articleStyle= {customArticleStyle}
initialRawDraft={initialRawDraft}
/>
</div>
<div className= "col s12 l6" style={articleStyle}>
<ArticleOverview
blockStyleFn={blockStyleFn}
blockRendererFn={blockRendererFn}
customStyleMap={customStyleMap}
rawDraft={rawDraft}
title="Small preview:"
articleUrl="http://easybird.be/blog/future-react"
/>
</div>
<div className= "col s12 l6" style={articleStyle}>
<Article
blockStyleFn={blockStyleFn}
blockRendererFn={blockRendererFn}
customStyleMap={customStyleMap}
rawDraft={rawDraft}
title="Rendered result:"
articleUrl="http://easybird.be/blog/future-react"
/>
</div>
</div>
</div>
</main>
)
}
}
WelcomeMain.propTypes = {
initialRawDraft: React.PropTypes.object
};
export default WelcomeMain;
|
view/perspective/app.js
|
salesforce/refocus
|
/**
* Copyright (c) 2016, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or
* https://opensource.org/licenses/BSD-3-Clause
*/
/**
* view/perspective/app.js
*
* When this page is loaded, we call "getPerspectiveNames" to load all the
* perspective names to populate the dropdown.
* If there are no perspectives, we just render the perspective overlay over an
* empty page.
* If there are perspectives, we call "whichPerspective" to figure out which
* perspective to load.
* If it's not in the URL path, either use the DEFAULT_PERSPECTIVE from global
* config OR the first perspective from the list of perspective names
* (alphabetical order), and redirect to the URL using *that* perspective name.
* Once we can identify the perspective in the URL path, we call
* "getPerspective" to load the specified perspective. When we get the
* perspective back from the server, we perform all of this async work in
* parallel:
* (1) call "setupSocketIOClient" to initialize the socket.io client
* (2) call "getHierarchy" to request the hierarchy
* (3) call "getLensPromise" to request the lens library
* (4) call "loadPerspective" to start rendering the perspective-picker
* component
* (5) call "loadExtraStuffForCreatePerspective" to start loading all the extra
* data we'll need for the "CreatePerspective" component
*
* If config var "realtimeEventThrottleMilliseconds" > 0, we start a timer to
* flush the realtime event queue on that defined interval.
*
* Whenever we get the response back with the lens, we dispatch the lens.load
* event to the lens.
*
* Whenever we get the response back with the hierarchy, we dispatch the
* lens.hierarchyLoad event to the lens. (If we happen to get the hierarchy
* back *before* the lens, hold onto it, wait for the lens, *then* dispatch the
* lens.hierarchyLoad event *after* the lens.load event.)
*
* Whenever we get all the extra data we need for "CreatePerspective", we
* re-render the perspective-picker component.
*/
import request from 'superagent';
import React from 'react';
import ReactDOM from 'react-dom';
import PerspectiveController from './PerspectiveController';
import { getValuesObject } from './utils';
const u = require('../utils');
const pu = require('./utils');
const constants = require('../constants');
const eventsQueue = require('./eventsQueue');
const emitUtils = require('../../realtime/emitUtils');
const pcValues = {};
const ZERO = 0;
const ONE = 1;
const DEBUG_REALTIME = window.location.href.split(/[&\?]/)
.includes('debug=REALTIME');
const REQ_HEADERS = {
'X-Requested-With': 'XMLHttpRequest',
Expires: '-1',
'Cache-Control': 'no-cache,no-store,must-revalidate,max-age=-1,private',
};
const DEFAULT_ERROR_MESSAGE = 'An unexpected error occurred.';
const LENS_LIBRARY_REX = /(?:\.([^.]+))?$/;
// Some API endpoints...
const GET_DEFAULT_PERSPECTIVE = '/v1/globalconfig/DEFAULT_PERSPECTIVE';
const GET_PERSPECTIVE_NAMES = '/v1/perspectives?fields=name';
// Some divs on the perspective page...
const LENS_DIV = document.getElementById('lens');
const ERROR_INFO_DIV = document.getElementById('errorInfo');
const PERSPECTIVE_CONTAINER =
document.getElementById('refocus_perspective_dropdown_container');
const SPINNER_ID = 'lens_loading_spinner';
let _realtimeApplication;
let _realtimeEventThrottleMilliseconds;
let _userSession;
let _io;
let lastUpdateTime;
let timeoutCheckInterval;
let lensEventApiVersion = 1;
const trackedAspects = {};
/**
* Add error message to the errorInfo div in the page.
* Remove the spinner.
*
* @param {Object} err - The error object
*/
function handleError(err) {
let msg = DEFAULT_ERROR_MESSAGE;
if (err.response.body.errors[ZERO].description) {
msg = err.response.body.errors[ZERO].description;
}
ERROR_INFO_DIV.innerHTML = msg;
u.removeSpinner(SPINNER_ID);
} // handleError
/**
* Handle event data, push the event data to the event queue.
*
* @param {String} eventData - Data recieved with event
* @param {String} eventTypeName - Event type
* @param {Function} trackEndToEndTime - Callback to send event receipt time back to server
*/
function handleEvent(eventData, eventTypeName, trackEndToEndTime) {
// track event receipt
const now = Date.now();
trackEndToEndTime && trackEndToEndTime(now);
lastUpdateTime = now;
// parse event data
const obj = JSON.parse(eventData)[eventTypeName];
// intercept events to support v1 lenses
if (lensEventApiVersion < 2) {
interceptV1Event(eventTypeName, obj);
}
// log event data
if (DEBUG_REALTIME) {
console.log({ // eslint-disable-line no-console
handleEventTimestamp: new Date(),
eventData: obj,
});
}
// dispatch event to lens
eventsQueue.enqueueEvent(eventTypeName, obj);
if (_realtimeEventThrottleMilliseconds === ZERO) {
eventsQueue.createAndDispatchLensEvent(eventsQueue.queue, LENS_DIV);
eventsQueue.queue.length = ZERO;
}
} // handleEvent
/**
* Intercept events to support v1 lenses.
*
* @param {String} eventTypeName - Event type
* @param {Object} eventData - object that will be sent to the lens
*/
function interceptV1Event(eventTypeName, eventData) {
if (eventTypeName === eventsQueue.eventType.INTRNL_SMPL_ADD) {
eventData.aspect = getTrackedAspectForSample(eventData);
} else if (eventTypeName === eventsQueue.eventType.INTRNL_SMPL_DEL) {
eventData.aspect = getTrackedAspectForSample(eventData);
} else if (eventTypeName === eventsQueue.eventType.INTRNL_SMPL_UPD) {
eventData.new.aspect = getTrackedAspectForSample(eventData.new);
} else if (eventTypeName === eventsQueue.eventType.INTRNL_ASP_ADD) {
trackAspect(eventData);
} else if (eventTypeName === eventsQueue.eventType.INTRNL_ASP_DEL) {
untrackAspect(eventData);
} else if (eventTypeName === eventsQueue.eventType.INTRNL_ASP_UPD) {
trackAspect(eventData.new);
}
}
/**
* Get the tracked aspect for the given sample
* @param {Object} sample - sample object
*/
function getTrackedAspectForSample(sample) {
const [absPath, aspName] = sample.name.split('|');
return trackedAspects[aspName.toLowerCase()];
}
/**
* Get the tracked aspect by name
* @param {String} aspName - aspect name
*/
function getTrackedAspect(aspName) {
return trackedAspects[aspName.toLowerCase()];
}
/**
* Add the aspect to the tracking map.
* @param {Object} aspect - aspect object
*/
function trackAspect(aspect) {
trackedAspects[aspect.name.toLowerCase()] = aspect;
}
/**
* Track all aspects
* @param {Array} aspects - array of aspects
*/
function trackAspects(aspects) {
aspects.forEach(trackAspect);
}
/**
* Remove the aspect from the tracking map.
* @param {Object} aspect - aspect object
*/
function untrackAspect(aspect) {
delete trackedAspects[aspect.name.toLowerCase()];
}
/**
* Setup the socket.io client to listen to a namespace, where the namespace is
* named for the root subject of the perspective.
*
* @param {Object} persBody - Perspective object
*/
function setupSocketIOClient(persBody) {
if (!persBody) {
throw new Error('Cannot set up socket IO client without a perspective');
}
/*
* Add the perspective name as a query param so that it's available server-
* side on connect.
*/
let socket;
if (useNewNamespaceFormat) {
const options = {
query: {
p: persBody.name,
id: u.getNamespaceString('/', persBody),
},
...constants.socketOptions,
};
const namespace = _realtimeApplication.endsWith('/') ? 'perspectives' : '/perspectives';
socket = _io.connect(`${_realtimeApplication}${namespace}`, options)
.on('connect', function() {
this.emit('auth', _userSession);
})
.on('auth error', (err) =>
console.error('Socket auth error:', err)
);
} else {
const namespace = u.getNamespaceString(_realtimeApplication, persBody) +
`?p=${persBody.name}&t=${_userSession}`;
socket = _io.connect(namespace, constants.socketOptions);
}
socket.on('connect', () => {
Object.values(eventsQueue.eventType).forEach((eventType) =>
socket.on(eventType, (data, cb) => handleEvent(data, eventType, cb))
);
/*
* TODO once we build new perspective page, we should have a way to tell
* the user that they have been disconnected from the real-time event
* stream. In the meantime, just log it in the browser.
*/
socket.on('disconnect', (msg) => {
console.log('Disconnected from real-time event stream.');
});
});
} // setupSocketIOClient
/**
* Create style tag for lens css file.
* @param {Object} library From the the lens api
* @param {String} filename name of file in lens library
*/
function injectStyleTag(library, filename) {
const style = document.createElement('style');
style.type = 'text/css';
const t = document.createTextNode(library[filename]);
style.appendChild(t);
const head = document.head ||
document.getElementsByTagName('head')[ZERO];
if (style.styleSheet) {
style.styleSheet.cssText = library[filename];
} else {
style.appendChild(document.createTextNode(library[filename]));
}
head.appendChild(style);
} // injectStyleTag
/**
* Create DOM elements for each of the files in the lens library.
*
* @param {Object} lib - Library of the response from lens api call
*/
function handleLibraryFiles(lib) {
const lensScript = document.createElement('script');
for (const filename in lib) {
const ext = (LENS_LIBRARY_REX.exec(filename)[ONE] || '').toLowerCase();
if (filename === 'lens.js') {
lensScript.appendChild(document.createTextNode(lib[filename]));
} else if (ext === 'css') {
injectStyleTag(lib, filename);
} else if (ext === 'png' || ext === 'jpg' || ext === 'jpeg') {
const image = new Image();
image.src = 'data:image/' + ext + ';base64,' + lib[filename];
document.body.appendChild(image);
} else if (ext === 'js') {
const s = document.createElement('script');
s.appendChild(document.createTextNode(lib[filename]));
document.body.appendChild(s);
}
}
/*
* Note: this 'lens.js' script should always get added as the LAST script
* since it may reference things defined in the other scripts.
*/
document.body.appendChild(lensScript);
} // handleLibraryFiles
/**
* Setup the aspect timeout check. If the lens has already been loaded,
* dispatch the "hierarchyLoad" event. If not, return the hierarchyLoad event.
*
* @param {Object} hierarchy - hierarchy response
* @param {Object} allAspects - aspects response
* @param {Object} perspective - perspective object
* @param {Boolean} gotLens
* @returns {CustomEvent} if lens is received, return undefined,
* else return hierarchyLoadEvent.
*/
function handleHierarchyEvent(hierarchy, allAspects, perspective, gotLens) {
// perspective aspects - all aspects that could potentially be included in this perspective
const perspectiveAspects = filterPerspectiveAspects(allAspects, perspective);
// track aspects to be used for intercepting v1 events
trackAspects(perspectiveAspects);
// setup auto-reload based on the lowest aspect timeout
setupAutoReload(hierarchy);
// prepare hierarchy event
const hierarchyLoadEvent = prepareHierarchyEventForLens(hierarchy, perspectiveAspects);
// dispatch to lens. if not ready, return the event, to be dispatched on lens arrival.
if (gotLens) {
LENS_DIV.dispatchEvent(hierarchyLoadEvent);
} else {
return hierarchyLoadEvent;
}
}
/**
* Filter aspects based on the perspective filters.
*
* @param {Object} allAspects
* @param {Object} perspective
*/
function filterPerspectiveAspects(allAspects, perspective) {
const nspStr = emitUtils.getPerspectiveNamespaceString(perspective);
return allAspects.filter((asp) =>
emitUtils.shouldIEmitThisObj(nspStr, asp)
);
}
function prepareHierarchyEventForLens(hierarchy, aspects) {
let eventDetail;
if (lensEventApiVersion < 2) {
eventDetail = pu.reconstructV1Hierarchy(hierarchy, aspects);
} else {
eventDetail = { hierarchy, aspects };
}
return new window.CustomEvent(
'refocus.lens.hierarchyLoad', { detail: eventDetail }
);
}
/**
* Setup an interval to check that the page is still receiving events,
* based on the lowest timeout for an aspect in the hierarchy.
*
* @param {Object} hierarchy
*/
function setupAutoReload(hierarchy) {
const minAspectTimeout = (
pu.aspectNamesInHierarchy(hierarchy)
.map(getTrackedAspect)
.filter(Boolean)
.map((a) => parseTimeout(a.timeout))
.reduce((a, b) => Math.min(a, b), Infinity)
);
lastUpdateTime = Date.now();
if (minAspectTimeout < Infinity) {
timeoutCheckInterval = setInterval(() => {
if (Date.now() - lastUpdateTime >= minAspectTimeout * 2) {
window.location.reload();
}
}, minAspectTimeout);
}
}
/**
* Parse a timeout string and convert it into ms.
* @param {String} timeoutString - a timeout string from a sample
* @returns {Number} the sample timeout in ms
*/
function parseTimeout(timeoutString) {
let timeout = timeoutString.slice(0, -1) * 1000;
const unit = timeoutString.slice(-1).toLowerCase();
switch (unit) {
case 'm':
timeout *= 60;
break;
case 'h':
timeout *= 3600;
break;
case 'd':
timeout *= 86400;
break;
}
return timeout;
}
/**
* On receiving the lens, load the lens.
* Load the hierarchy if hierarchy event is passed in.
*
* @param {Object} library the perspective's lens's library
* @param {Object} hierarchyLoadEvent undefined or
* a Custom Event
*/
function handleLensDomEvent(lensEventApiVer, library, hierarchyLoadEvent) {
handleLibraryFiles(library); // inject lens library files in perspective view
setLensEventApiVersion(lensEventApiVer); // save lens event api version
u.removeSpinner(SPINNER_ID);
/*
* Load the lens. Pass userId from cookie through to the lens, in case the
* lens wants to do any analytics by userId.
*/
const lensLoadEvent = new window.CustomEvent('refocus.lens.load', {
detail: {
userId: u.getCookie('userId'),
},
});
LENS_DIV.dispatchEvent(lensLoadEvent);
/*
* The order of events matters so if we happened to have gotten the
* hierarchy *before* the lens, then dispatch the lens.hierarchyLoad event
* now.
*/
if (hierarchyLoadEvent) {
LENS_DIV.dispatchEvent(hierarchyLoadEvent);
}
} // handleLensDomEvent
/**
* Returns the default url if page url ends with /perspectives
* Else the perspective name is in url:
* - change the document title to the name of the perspective.
* - return nothing
*
* @returns {String} if on/perspectives page, return default url.
* Else returns nothing
*/
function getPerspectiveUrl() {
let h = window.location.pathname;
let hsplit = h.split('/');
let p = hsplit.pop();
// named perspective
if (p && p !== 'perspectives') {
document.title += ' - ' + p;
return { url: '/v1/perspectives/' + p, named: true };
} else {
const object = { named: false };
object.url = GET_DEFAULT_PERSPECTIVE;
return object;
}
} // whichPerspective
window.onload = () => {
// Note: these are declared in perspective.pug:
_realtimeApplication = realtimeApplication;
_realtimeEventThrottleMilliseconds = realtimeEventThrottleMilliseconds;
_userSession = userSession;
_io = io;
if (_realtimeEventThrottleMilliseconds !== ZERO) {
eventsQueue.scheduleFlushQueue(LENS_DIV, _realtimeEventThrottleMilliseconds);
}
const accumulatorObject = {
getPromiseWithUrl: u.getPromiseWithUrl,
getPerspectiveUrl,
handleHierarchyEvent,
handleLensDomEvent,
customHandleError: (msg) => {
ERROR_INFO_DIV.innerHTML = msg;
u.removeSpinner(SPINNER_ID);
},
setupSocketIOClient,
redirectToUrl: (url) => window.location.href = url,
};
getValuesObject(accumulatorObject)
.then((valuesObject) => {
// skip loading the controller if nothing is returned
if (valuesObject) {
loadController(valuesObject);
}
})
.catch((error) => {
document.getElementById('errorInfo').innerHTML = error;
});
};
/**
* Passes data on to Controller to pass onto renderers.
*
* @param {Object} values Data returned from AJAX.
*/
function loadController(values) {
ReactDOM.render(<PerspectiveController values={ values } />,
PERSPECTIVE_CONTAINER);
}
// For Testing
function getTimeoutValues() {
return {
lastUpdateTime,
timeoutCheckInterval,
};
}
function setLensEventApiVersion(version) {
lensEventApiVersion = version;
}
// For Testing
function resetState() {
clearInterval(timeoutCheckInterval);
timeoutCheckInterval = undefined;
lastUpdateTime = undefined;
Object.keys(trackedAspects).forEach((key) =>
delete trackedAspects[key]
);
eventsQueue.queue.splice(0);
}
module.exports = {
getTimeoutValues,
handleEvent,
parseTimeout,
setupAutoReload,
exportForTesting: {
resetState,
handleHierarchyEvent,
setLensEventApiVersion,
eventsQueue,
},
};
|
app/containers/FeaturePage/index.js
|
KyleAWang/react-boilerplate
|
/*
* FeaturePage
*
* List all the features
*/
import React from 'react';
import Helmet from 'react-helmet';
import { FormattedMessage } from 'react-intl';
import H1 from 'components/H1';
import messages from './messages';
import List from './List';
import ListItem from './ListItem';
import ListItemTitle from './ListItemTitle';
export default class FeaturePage extends React.Component { // eslint-disable-line react/prefer-stateless-function
// Since state and props are static,
// there's no need to re-render this component
shouldComponentUpdate() {
return false;
}
render() {
return (
<div>
<Helmet
title="Feature Page"
meta={[
{ name: 'description', content: 'Feature page of React.js Boilerplate application' },
]}
/>
<H1>
<FormattedMessage {...messages.header} />
</H1>
<List>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.scaffoldingHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.scaffoldingMessage} />
</p>
</ListItem>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.feedbackHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.feedbackMessage} />
</p>
</ListItem>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.routingHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.routingMessage} />
</p>
</ListItem>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.networkHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.networkMessage} />
</p>
</ListItem>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.intlHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.intlMessage} />
</p>
</ListItem>
</List>
</div>
);
}
}
|
src/svg-icons/image/photo-camera.js
|
w01fgang/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImagePhotoCamera = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="12" r="3.2"/><path d="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/>
</SvgIcon>
);
ImagePhotoCamera = pure(ImagePhotoCamera);
ImagePhotoCamera.displayName = 'ImagePhotoCamera';
ImagePhotoCamera.muiName = 'SvgIcon';
export default ImagePhotoCamera;
|
packages/material-ui-icons/src/TurnedIn.js
|
AndriusBil/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let TurnedIn = props =>
<SvgIcon {...props}>
<path d="M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2z" />
</SvgIcon>;
TurnedIn = pure(TurnedIn);
TurnedIn.muiName = 'SvgIcon';
export default TurnedIn;
|
src/app/components/Root.js
|
honzachalupa/portfolio2017
|
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch, browserHistory } from 'react-router-dom';
import update from 'immutability-helper';
import factory from './../factory';
import aspectRatioPreserver from './../modules/aspect-ratio-preserver';
import log from './../modules/logger';
import { setPageTitle } from './../helpers';
import HomePage from './../pages/Home';
import ProjectsPage from './../pages/Projects';
import AboutPage from './../pages/About';
import ProjectDetailPage from './../pages/ProjectDetail';
import ImageViewerPage from './../pages/ImageViewer';
import NotFoundPage from './../pages/NotFound';
import GoogleAnalytics from 'react-ga';
export default class Root extends Component {
constructor(props) {
super(props);
this.navigationToggler = this.navigationToggler.bind(this);
this.setNavigationItem = this.setNavigationItem.bind(this);
this.handleResize = this.handleResize.bind(this);
this.handleScroll = this.handleScroll.bind(this);
const { config } = props.apiData;
let { projects } = props.apiData;
projects = this.filterProjects(projects);
projects = this.sortProjects(projects);
config.navigationOpened = false;
config.scrolledDistance = 0;
config.projectTypes = this.getProjectTypes(projects);
this.state = {
projects,
config,
utilities: {
navigationToggler: this.navigationToggler,
setNavigationItem: this.setNavigationItem
}
};
}
componentDidMount() {
GoogleAnalytics.initialize('UA-47064928-3');
this.updateDimensions();
this.getScrolledDistance();
window.addEventListener('resize', this.handleResize);
window.addEventListener('scroll', this.handleScroll);
}
componentDidUpdate() {
factory(aspectRatioPreserver, document.querySelectorAll('[data-aspect-ratio]'));
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
window.removeEventListener('scroll', this.handleScroll);
}
setNavigationItem(clickedId) {
const { navigationItems } = this.state.config;
const navigationItemsActive = navigationItems.forEach((item) => {
item.active = (item.id === clickedId);
});
this.setState({
navigationItems: update(navigationItems, {
$set: navigationItemsActive
})
});
window.scrollTo(0, 0);
}
getProjectTypes(projects) {
const types = [];
projects.forEach((project) => {
if (types.indexOf(project.type) === -1) {
types.push(project.type);
}
});
return types;
}
getScrolledDistance() {
this.setState({
config: update(this.state.config, {
$merge: {
scrolledDistance: window.pageYOffset
}
})
});
}
handleScroll() {
this.getScrolledDistance();
}
updateDimensions() {
const { screenBreakpoint } = this.state.config;
const dimensions = {
windowDimensions: {
width: window.innerWidth,
height: window.innerHeight
}
};
this.setState({
config: update(this.state.config, {
$merge: dimensions
})
});
if (dimensions.windowDimensions.width >= screenBreakpoint) {
this.setState({
config: update(this.state.config, {
$merge: {
navigationOpened: false
}
})
});
}
}
handleResize() {
this.updateDimensions();
}
navigationToggler(forceClose) {
const { navigationOpened, windowDimensions, screenBreakpoint } = this.state.config;
if (windowDimensions && windowDimensions.width < screenBreakpoint) {
this.setState({
config: update(this.state.config, {
$merge: {
navigationOpened: (forceClose === 'undefined') ? false : !navigationOpened
}
})
});
}
}
trackGoogleAnalytics() {
GoogleAnalytics.pageview(window.location.hash);
}
sortProjects(projects) {
return projects.sort((a, b) => {
return new Date(b.addedDate) - new Date(a.addedDate);
});
}
filterProjects(projects) {
const filtered = [];
projects.forEach((project) => {
if (project.hidden === undefined || project.hidden === false) {
filtered.push(project);
}
});
return filtered;
}
render() {
if (this.state && this.state.config && this.state.utilities) {
const { config, utilities, projects } = this.state;
return (
<Router history={browserHistory} onUpdate={this.trackGoogleAnalytics}>
<Switch>
<Route
exact
path="/"
render={(props) => (
<HomePage config={config} utilities={utilities} projects={projects} />
)}
/>
<Route
exact
path="/projects"
render={(props) => (
<ProjectsPage config={config} utilities={utilities} projects={projects} />
)}
/>
<Route
exact
path="/about-me"
render={(props) => (
<AboutPage config={config} utilities={utilities} />
)}
/>
<Route
exact
path="/image/:id"
render={(props) => (
<ImageViewerPage config={config} utilities={utilities} params={props.match.params} />
)}
/>
<Route
exact
path="/projects/:id"
render={(props) => (
<ProjectDetailPage config={config} utilities={utilities} projects={projects} params={props.match.params} />
)}
/>
<Route
render={() => (
<NotFoundPage config={config} utilities={utilities} />
)}
/>
</Switch>
</Router>
);
}
return (
<div>
Loading...
</div>
);
}
}
|
src/components/Map/AddTitle.js
|
Angular-Toast/habitat
|
import React, { Component } from 'react';
import { StyleSheet, Text, View, Animated, Image, Dimensions, TextInput, Button} from "react-native";
import { StackNavigator, NavigationActions } from 'react-navigation';
export default class Title extends React.Component {
static navigationOptions = {
title: 'Give your ecosystem a name!'
};
constructor(props) {
super(props);
this.state = {
title: '',
description: ''
}
}
render() {
const { navigate } = this.props.navigation;
let avatar = this.props.navigation.state.params.avatar;
let eco = this.props.navigation.state.params.eco;
return (
<View style={styles.container}>
<Image source={images[avatar][1]} style={styles.ecobuds}/>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1, width: 100}}
onChangeText={(e) => this.setState({title: e})}
value={this.state.title}
/>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1, width: 200}}
onChangeText={(e) => this.setState({description: e})}
value={this.state.description}
/>
<Button
onPress={() => navigate('Location', {eco: eco, avatar: avatar, title: this.state.title, description: this.state.description})}
title="Next"
color="#841584"
/>
</View>
);
}
}
const sprites = [
[0, require("../assets/Ecosystem/toast1.png")],
[1, require("../assets/Ecosystem/tree1.png")]
]
const images = [
[0, require("../assets/Ecosystem/home.png")],
[1, require("../assets/Ecosystem/work.png")],
[2, require("../assets/Ecosystem/gym.png")]
]
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
ecobuds: {
width: 100,
height: 100
}
})
|
src/components/ConsoleTidal.js
|
merttoka/Siren
|
import React from 'react';
import { Controlled as CodeMirror } from 'react-codemirror2'
import _ from 'lodash'
import { inject, observer } from 'mobx-react';
import { save } from '../keyFunctions.js';
import 'codemirror/lib/codemirror.css';
import '../utils/lexers/haskell.js';
import '../utils/lexers/haskell.css';
// codemirror addons
import 'codemirror/addon/selection/active-line.js';
import 'codemirror/addon/edit/matchbrackets.js';
@inject('consoleStore')
@observer
export default class ConsoleTidal extends React.Component {
// GHC
handleGHCSubmit = (editor, event) => {
if (event.keyCode === 13 && event.ctrlKey) {
let expr = "";
if (editor.somethingSelected()) {
// selected text
expr = event.target.value;
}
else {
const line = editor.getCursor().line;
if (editor.getLine(line) !== "") {
let startLine = line;
let endLine = line;
// determine line numbers of the code block
while (_.trim(editor.getLine(startLine)) !== '') { startLine -= 1; }
while (_.trim(editor.getLine(endLine)) !== '') { endLine += 1; }
// the text
expr = editor.getRange({ line: startLine, ch: 0 }, { line: endLine, ch: 0 });
// coloring the background
let handle = editor.markText(
{ line: startLine, ch: 0 },
{ line: endLine, ch: 0 },
{ className: 'CodeMirror-execution' });
_.delay(() => { handle.clear(); }, 500);
}
}
// execute the line
if (expr !== "")
this.props.consoleStore.submitGHC(expr);
}
event.preventDefault();
return false;
}
saveStuff = (editor, e) => {
if(e.ctrlKey && (e.which === 83)) {
e.preventDefault();
save();
return false;
}
}
render() {
console.log("RENDER CONSOLETIDAL.JS");
const options = {
mode: '_rule_haskell',
theme: '_style',
fixedGutter: true,
scroll: false,
styleSelectedText: true,
showToken: true,
lineWrapping: true,
lineNumbers: true,
showCursorWhenSelecting: true,
// addon options
styleActiveLine: true,
matchBrackets: true,
maxScanLines: 10
};
return (<div className={'ConsoleTextBox'}>
<p>select -> ctrl+enter</p>
<CodeMirror className={"draggableCancel"}
value={this.props.consoleStore.tidal_text}
options={options}
onBeforeChange={(editor, metadata, value) => {
this.props.consoleStore.onChangeTidal(value);
}}
onChange={() => { }}
onKeyDown={this.saveStuff.bind(this)}
onKeyUp={this.handleGHCSubmit.bind(this)}
/>
</div>);
}
}
|
actor-apps/app-web/src/app/components/modals/CreateGroup.react.js
|
bunnyblue/actor-platform
|
import React from 'react';
import CreateGroupActionCreators from 'actions/CreateGroupActionCreators';
import CreateGroupStore from 'stores/CreateGroupStore';
import CreateGroupForm from './create-group/Form.react';
import Modal from 'react-modal';
import { KeyCodes } from 'constants/ActorAppConstants';
const appElement = document.getElementById('actor-web-app');
Modal.setAppElement(appElement);
const getStateFromStores = () => {
return {
isShown: CreateGroupStore.isModalOpen()
};
};
class CreateGroup extends React.Component {
constructor(props) {
super(props);
this.state = getStateFromStores();
CreateGroupStore.addChangeListener(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
}
componentWillUnmount() {
CreateGroupStore.removeChangeListener(this.onChange);
document.removeEventListener('keydown', this.onKeyDown, false);
}
render() {
const isShown = this.state.isShown;
return (
<Modal className="modal-new modal-new--create-group" closeTimeoutMS={150} isOpen={isShown}>
<header className="modal-new__header">
<a className="modal-new__header__close material-icons" onClick={this.onClose}>clear</a>
<h3 className="modal-new__header__title">Create group</h3>
</header>
<CreateGroupForm/>
</Modal>
);
}
onChange = () => {
this.setState(getStateFromStores());
}
onClose = () => {
CreateGroupActionCreators.closeModal();
}
onKeyDown = (event) => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
}
}
CreateGroup.displayName = 'CreateGroup';
export default CreateGroup;
|
src/svg-icons/image/grid-off.js
|
spiermar/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageGridOff = (props) => (
<SvgIcon {...props}>
<path d="M8 4v1.45l2 2V4h4v4h-3.45l2 2H14v1.45l2 2V10h4v4h-3.45l2 2H20v1.45l2 2V4c0-1.1-.9-2-2-2H4.55l2 2H8zm8 0h4v4h-4V4zM1.27 1.27L0 2.55l2 2V20c0 1.1.9 2 2 2h15.46l2 2 1.27-1.27L1.27 1.27zM10 12.55L11.45 14H10v-1.45zm-6-6L5.45 8H4V6.55zM8 20H4v-4h4v4zm0-6H4v-4h3.45l.55.55V14zm6 6h-4v-4h3.45l.55.54V20zm2 0v-1.46L17.46 20H16z"/>
</SvgIcon>
);
ImageGridOff = pure(ImageGridOff);
ImageGridOff.displayName = 'ImageGridOff';
ImageGridOff.muiName = 'SvgIcon';
export default ImageGridOff;
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/Promises.js
|
lolaent/create-react-app
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function load() {
return Promise.resolve([
{ id: 1, name: '1' },
{ id: 2, name: '2' },
{ id: 3, name: '3' },
{ id: 4, name: '4' },
]);
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
componentDidMount() {
load().then(users => {
this.setState({ users });
});
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-promises">
{this.state.users.map(user => (
<div key={user.id}>
{user.name}
</div>
))}
</div>
);
}
}
|
docs/src/app/components/pages/components/IconMenu/ExampleNested.js
|
IsenrichO/mui-with-arrows
|
import React from 'react';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import IconButton from 'material-ui/IconButton';
import Divider from 'material-ui/Divider';
import Download from 'material-ui/svg-icons/file/file-download';
import ArrowDropRight from 'material-ui/svg-icons/navigation-arrow-drop-right';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
/**
* Example of nested menus within an IconMenu.
*/
const IconMenuExampleNested = () => (
<IconMenu
iconButtonElement={<IconButton><MoreVertIcon /></IconButton>}
anchorOrigin={{horizontal: 'left', vertical: 'top'}}
targetOrigin={{horizontal: 'left', vertical: 'top'}}
>
<MenuItem
primaryText="Copy & Paste"
rightIcon={<ArrowDropRight />}
menuItems={[
<MenuItem primaryText="Cut" />,
<MenuItem primaryText="Copy" />,
<Divider />,
<MenuItem primaryText="Paste" />,
]}
/>
<MenuItem
primaryText="Case Tools"
rightIcon={<ArrowDropRight />}
menuItems={[
<MenuItem primaryText="UPPERCASE" />,
<MenuItem primaryText="lowercase" />,
<MenuItem primaryText="CamelCase" />,
<MenuItem primaryText="Propercase" />,
]}
/>
<Divider />
<MenuItem primaryText="Download" leftIcon={<Download />} />
<Divider />
<MenuItem value="Del" primaryText="Delete" />
</IconMenu>
);
export default IconMenuExampleNested;
|
frontend/src/Components/Form/TextArea.js
|
geogolem/Radarr
|
import classNames from 'classnames';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import styles from './TextArea.css';
class TextArea extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this._input = null;
this._selectionStart = null;
this._selectionEnd = null;
this._selectionTimeout = null;
this._isMouseTarget = false;
}
componentDidMount() {
window.addEventListener('mouseup', this.onDocumentMouseUp);
}
componentWillUnmount() {
window.removeEventListener('mouseup', this.onDocumentMouseUp);
if (this._selectionTimeout) {
this._selectionTimeout = clearTimeout(this._selectionTimeout);
}
}
//
// Control
setInputRef = (ref) => {
this._input = ref;
}
selectionChange() {
if (this._selectionTimeout) {
this._selectionTimeout = clearTimeout(this._selectionTimeout);
}
this._selectionTimeout = setTimeout(() => {
const selectionStart = this._input.selectionStart;
const selectionEnd = this._input.selectionEnd;
const selectionChanged = (
this._selectionStart !== selectionStart ||
this._selectionEnd !== selectionEnd
);
this._selectionStart = selectionStart;
this._selectionEnd = selectionEnd;
if (this.props.onSelectionChange && selectionChanged) {
this.props.onSelectionChange(selectionStart, selectionEnd);
}
}, 10);
}
//
// Listeners
onChange = (event) => {
const {
name,
onChange
} = this.props;
const payload = {
name,
value: event.target.value
};
onChange(payload);
}
onFocus = (event) => {
if (this.props.onFocus) {
this.props.onFocus(event);
}
this.selectionChange();
}
onKeyUp = () => {
this.selectionChange();
}
onMouseDown = () => {
this._isMouseTarget = true;
}
onMouseUp = () => {
this.selectionChange();
}
onDocumentMouseUp = () => {
if (this._isMouseTarget) {
this.selectionChange();
}
this._isMouseTarget = false;
}
//
// Render
render() {
const {
className,
readOnly,
autoFocus,
placeholder,
name,
value,
hasError,
hasWarning,
onBlur
} = this.props;
return (
<textarea
ref={this.setInputRef}
readOnly={readOnly}
autoFocus={autoFocus}
placeholder={placeholder}
className={classNames(
className,
readOnly && styles.readOnly,
hasError && styles.hasError,
hasWarning && styles.hasWarning
)}
name={name}
value={value}
onChange={this.onChange}
onFocus={this.onFocus}
onBlur={onBlur}
onKeyUp={this.onKeyUp}
onMouseDown={this.onMouseDown}
onMouseUp={this.onMouseUp}
/>
);
}
}
TextArea.propTypes = {
className: PropTypes.string.isRequired,
readOnly: PropTypes.bool,
autoFocus: PropTypes.bool,
placeholder: PropTypes.string,
name: PropTypes.string.isRequired,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.array]).isRequired,
hasError: PropTypes.bool,
hasWarning: PropTypes.bool,
onChange: PropTypes.func.isRequired,
onFocus: PropTypes.func,
onBlur: PropTypes.func,
onSelectionChange: PropTypes.func
};
TextArea.defaultProps = {
className: styles.input,
type: 'text',
readOnly: false,
autoFocus: false,
value: ''
};
export default TextArea;
|
node_modules/react-bootstrap/es/NavDropdown.js
|
ivanhristov92/bookingCalendar
|
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import _extends from 'babel-runtime/helpers/extends';
import classNames from 'classnames';
import React from 'react';
import Dropdown from './Dropdown';
import splitComponentProps from './utils/splitComponentProps';
import ValidComponentChildren from './utils/ValidComponentChildren';
var propTypes = _extends({}, Dropdown.propTypes, {
// Toggle props.
title: React.PropTypes.node.isRequired,
noCaret: React.PropTypes.bool,
active: React.PropTypes.bool,
// Override generated docs from <Dropdown>.
/**
* @private
*/
children: React.PropTypes.node
});
var NavDropdown = function (_React$Component) {
_inherits(NavDropdown, _React$Component);
function NavDropdown() {
_classCallCheck(this, NavDropdown);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
NavDropdown.prototype.isActive = function isActive(_ref, activeKey, activeHref) {
var props = _ref.props;
var _this2 = this;
if (props.active || activeKey != null && props.eventKey === activeKey || activeHref && props.href === activeHref) {
return true;
}
if (ValidComponentChildren.some(props.children, function (child) {
return _this2.isActive(child, activeKey, activeHref);
})) {
return true;
}
return props.active;
};
NavDropdown.prototype.render = function render() {
var _this3 = this;
var _props = this.props,
title = _props.title,
activeKey = _props.activeKey,
activeHref = _props.activeHref,
className = _props.className,
style = _props.style,
children = _props.children,
props = _objectWithoutProperties(_props, ['title', 'activeKey', 'activeHref', 'className', 'style', 'children']);
var active = this.isActive(this, activeKey, activeHref);
delete props.active; // Accessed via this.isActive().
delete props.eventKey; // Accessed via this.isActive().
var _splitComponentProps = splitComponentProps(props, Dropdown.ControlledComponent),
dropdownProps = _splitComponentProps[0],
toggleProps = _splitComponentProps[1];
// Unlike for the other dropdowns, styling needs to go to the `<Dropdown>`
// rather than the `<Dropdown.Toggle>`.
return React.createElement(
Dropdown,
_extends({}, dropdownProps, {
componentClass: 'li',
className: classNames(className, { active: active }),
style: style
}),
React.createElement(
Dropdown.Toggle,
_extends({}, toggleProps, { useAnchor: true }),
title
),
React.createElement(
Dropdown.Menu,
null,
ValidComponentChildren.map(children, function (child) {
return React.cloneElement(child, {
active: _this3.isActive(child, activeKey, activeHref)
});
})
)
);
};
return NavDropdown;
}(React.Component);
NavDropdown.propTypes = propTypes;
export default NavDropdown;
|
packages/@vega/layout/src/components/AcceptInvite/AcceptReviewerInvite.js
|
VegaPublish/vega-studio
|
/* eslint-disable max-len */
import React from 'react'
import Button from 'part:@lyra/components/buttons/default'
import lyraClient from 'part:@lyra/base/client'
import styles from './styles/AcceptReviewerInvite.css'
import client from 'part:@lyra/base/client'
import locationStore from 'part:@lyra/base/location'
function markReviewItemAsAccepted(userId) {
const query = `*[_type == "reviewItem" && reviewer._ref == "${userId}"][0]{...}`
return lyraClient.fetch(query).then(reviewItem => {
return lyraClient
.patch(reviewItem._id)
.set({acceptState: 'accepted'})
.commit()
})
}
type Props = {
invite: any,
user: any,
venue: boolean
}
export default class AcceptReviewerInvite extends React.Component<Props> {
handleAcceptInvite = () => {
const {invite, user, venue} = this.props
const claimUrl = `/invitations/claim/${invite._id}?venueId=${venue._id}`
const maybeLogout = user ? client.auth.logout() : Promise.resolve()
maybeLogout
.then(() =>
client.request({
url: claimUrl
})
)
.then(() => markReviewItemAsAccepted(invite.target._ref))
.then(() => locationStore.actions.navigate('/'))
}
render() {
const {invite, user, venue} = this.props
return (
<div className={styles.root}>
<div>
<div className={styles.header}>
<div className={styles.headerInner} />
</div>
<h2>Invitation to review article in {venue.title}</h2>
<p>{invite.message}</p>
{user ? (
<div>
<p>
You are currently logged in as {user.name}. In order to accept
this invitation you will have to log out first.
</p>
<div className={styles.choices}>
<div>
<Button onClick={this.handleAcceptInvite} color="primary">
Logout and accept invitation to become reviewer
</Button>{' '}
</div>
<div>or</div>
<div>
<a href="/">Continue in Vega as {user.name}</a>
</div>
</div>
</div>
) : (
<Button onClick={this.handleAcceptInvite} color="primary">
Accept invitation to become reviewer
</Button>
)}
</div>
</div>
)
}
}
|
src/components/Switcher.js
|
jo12bar/blag
|
import React from 'react';
import { connect } from 'react-redux';
import { TransitionGroup, Transition } from 'transition-group';
import universal from 'react-universal-component';
import Loading from './Loading';
import Err from './Error';
import isLoading from '../selectors/isLoading';
import styles from '../css/Switcher';
const UniversalComponent = universal(({ page }) => import(`../pages/${page}`), {
minDelay: 500,
loading: Loading,
error: Err,
});
const Switcher = ({ page, direction, isLoading }) => (
<TransitionGroup
className={`${styles.switcher} ${direction}`}
duration={500}
prefix='fade'
>
<Transition key={page}>
<UniversalComponent page={page} isLoading={isLoading} />
</Transition>
</TransitionGroup>
);
const mapState = ({ page, direction, ...state }) => {
const isLoad = isLoading(state);
console.log('isLoading:', isLoad);
return ({
page,
direction,
isLoading: isLoad,
});
};
export default connect(mapState)(Switcher);
|
docs/src/sections/ProgressBarSection.js
|
apkiernan/react-bootstrap
|
import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function ProgressBarSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="progress">Progress bars</Anchor> <small>ProgressBar</small>
</h2>
<p className="lead">Provide up-to-date feedback on the progress of a workflow or action with simple yet flexible progress bars.</p>
<h2><Anchor id="progress-basic">Basic example</Anchor></h2>
<p>Default progress bar.</p>
<ReactPlayground codeText={Samples.ProgressBarBasic} />
<h2><Anchor id="progress-label">With label</Anchor></h2>
<p>Add a <code>label</code> prop to show a visible percentage. For low percentages, consider adding a min-width to ensure the label's text is fully visible.</p>
<ReactPlayground codeText={Samples.ProgressBarWithLabel} />
<h2><Anchor id="progress-screenreader-label">Screenreader only label</Anchor></h2>
<p>Add a <code>srOnly</code> prop to hide the label visually.</p>
<ReactPlayground codeText={Samples.ProgressBarScreenreaderLabel} />
<h2><Anchor id="progress-contextual">Contextual alternatives</Anchor></h2>
<p>Progress bars use some of the same button and alert classes for consistent styles.</p>
<ReactPlayground codeText={Samples.ProgressBarContextual} />
<h2><Anchor id="progress-striped">Striped</Anchor></h2>
<p>Uses a gradient to create a striped effect. Not available in IE8.</p>
<ReactPlayground codeText={Samples.ProgressBarStriped} />
<h2><Anchor id="progress-animated">Animated</Anchor></h2>
<p>Add <code>active</code> prop to animate the stripes right to left. Not available in IE9 and below.</p>
<ReactPlayground codeText={Samples.ProgressBarAnimated} />
<h2><Anchor id="progress-stacked">Stacked</Anchor></h2>
<p>Nest <code><ProgressBar /></code>s to stack them.</p>
<ReactPlayground codeText={Samples.ProgressBarStacked} />
<h3><Anchor id="progress-props">ProgressBar</Anchor></h3>
<PropTable component="ProgressBar"/>
</div>
);
}
|
react_layout/setup.js
|
devSC/react-native
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View
} from 'react-native';
import FlexBoxTest from './FlexBoxTest'
import FlexBoxDice from './FlexBoxDice'
export default class setup extends Component {
render() {
return (
<View style={styles.container}>
<FlexBoxDice/>
{/*<FlexBoxTest/>*/}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 64,
backgroundColor: '#F5FCFF',
},
});
|
packages/material-ui-icons/src/LinkedCamera.js
|
dsslimshaddy/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let LinkedCamera = props =>
<SvgIcon {...props}>
<circle cx="12" cy="14" r="3.2" /><path d="M16 3.33c2.58 0 4.67 2.09 4.67 4.67H22c0-3.31-2.69-6-6-6v1.33M16 6c1.11 0 2 .89 2 2h1.33c0-1.84-1.49-3.33-3.33-3.33V6" /><path d="M17 9c0-1.11-.89-2-2-2V4H9L7.17 6H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9h-5zm-5 10c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z" />
</SvgIcon>;
LinkedCamera = pure(LinkedCamera);
LinkedCamera.muiName = 'SvgIcon';
export default LinkedCamera;
|
src/client/routes/Bundle.js
|
Paul-Long/m-gril
|
import React from 'react';
export default class Bundle extends React.Component {
constructor(props) {
super(props);
this.state = {
mod: null
};
}
componentWillMount() {
this.load(this.props)
}
componentWillReceiveProps(nextProps) {
if (nextProps.load !== this.props.load) {
this.load(nextProps)
}
}
load(props) {
this.setState({mod: null});
props.load().then((mod) => {
this.setState({mod: mod.default || mod});
});
}
render() {
return this.state.mod ? this.props.children(this.state.mod) : null;
}
}
|
examples/todomvc/containers/TodoApp.js
|
aheuermann/redux
|
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Header from '../components/Header';
import MainSection from '../components/MainSection';
import * as TodoActions from '../actions/todos';
class TodoApp extends Component {
render() {
const { todos, dispatch } = this.props;
const actions = bindActionCreators(TodoActions, dispatch);
return (
<div>
<Header addTodo={actions.addTodo} />
<MainSection todos={todos} actions={actions} />
</div>
);
}
}
function select(state) {
return {
todos: state.todos
};
}
export default connect(select)(TodoApp);
|
js/signin/src/components/SecretReset.js
|
fogfish/oauth2
|
import React from 'react'
import { Button, Intent } from '@blueprintjs/core'
import { Link } from 'react-router-dom'
import Dialog from 'components/Dialog'
import AccessKey from 'components/AccessKey'
const Actions = () => (
<>
<Link className="bp3-button bp3-minimal bp3-intent-primary" to="/">
<b>Sign In Instead</b>
</Link>
<Button type="submit" intent={Intent.PRIMARY} large>Reset Password</Button>
</>
)
const SecretReset = ({ oauth2 }) => (
<Dialog
icon="fa-lock"
title="Forgot Your Password ?"
url="/oauth2/password"
Actions={Actions}
>
<p className="bp3-ui-text bp3-running-text">
Type you
<b>email</b>
address to reset your password.
We will send recovery instructions over email.
</p>
<AccessKey />
<input name="response_type" type="hidden" value="password_reset" />
<input name="client_id" type="hidden" value={oauth2.clientId} />
<input name="redirect_uri" type="hidden" value={oauth2.redirectUri} />
</Dialog>
)
export default SecretReset
|
examples/ssr-caching/pages/blog.js
|
BlancheXu/test
|
import React from 'react'
export default class extends React.Component {
static getInitialProps ({ query: { id } }) {
return { id }
}
render () {
return (
<div>
<h1>My {this.props.id} blog post</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
</div>
)
}
}
|
fields/components/Checkbox.js
|
pr1ntr/keystone
|
import React from 'react';
import blacklist from 'blacklist';
import classnames from 'classnames';
import { darken, fade } from '../../admin/client/utils/color';
import E from '../../admin/client/constants';
var Checkbox = React.createClass({
displayName: 'Checkbox',
propTypes: {
checked: React.PropTypes.bool,
component: React.PropTypes.node,
onChange: React.PropTypes.func,
readonly: React.PropTypes.bool,
},
getDefaultProps () {
return {
component: 'button',
};
},
getInitialState () {
return {
active: null,
focus: null,
hover: null,
};
},
componentDidMount () {
window.addEventListener('mouseup', this.handleMouseUp, false);
},
componentWillUnmount () {
window.removeEventListener('mouseup', this.handleMouseUp, false);
},
getStyles () {
const { checked, readonly } = this.props;
const { active, focus, hover } = this.state;
const checkedColor = '#3999fc';
let background = (checked && !readonly) ? checkedColor : 'white';
let borderColor = (checked && !readonly) ? 'rgba(0,0,0,0.15) rgba(0,0,0,0.1) rgba(0,0,0,0.05)' : 'rgba(0,0,0,0.3) rgba(0,0,0,0.2) rgba(0,0,0,0.15)';
let boxShadow = (checked && !readonly) ? '0 1px 0 rgba(255,255,255,0.33)' : 'inset 0 1px 0 rgba(0,0,0,0.06)';
let color = (checked && !readonly) ? 'white' : '#bbb';
const textShadow = (checked && !readonly) ? '0 1px 0 rgba(0,0,0,0.2)' : null;
// pseudo state
if (hover && !focus && !readonly) {
borderColor = (checked) ? 'rgba(0,0,0,0.1) rgba(0,0,0,0.15) rgba(0,0,0,0.2)' : 'rgba(0,0,0,0.35) rgba(0,0,0,0.3) rgba(0,0,0,0.25)';
}
if (active) {
background = (checked && !readonly) ? darken(checkedColor, 20) : '#eee';
borderColor = (checked && !readonly) ? 'rgba(0,0,0,0.25) rgba(0,0,0,0.3) rgba(0,0,0,0.35)' : 'rgba(0,0,0,0.4) rgba(0,0,0,0.35) rgba(0,0,0,0.3)';
boxShadow = (checked && !readonly) ? '0 1px 0 rgba(255,255,255,0.33)' : 'inset 0 1px 3px rgba(0,0,0,0.2)';
}
if (focus && !active) {
borderColor = (checked && !readonly) ? 'rgba(0,0,0,0.25) rgba(0,0,0,0.3) rgba(0,0,0,0.35)' : checkedColor;
boxShadow = (checked && !readonly) ? `0 0 0 3px ${fade(checkedColor, 15)}` : `inset 0 1px 2px rgba(0,0,0,0.15), 0 0 0 3px ${fade(checkedColor, 15)}`;
}
// noedit
if (readonly) {
background = 'rgba(255,255,255,0.5)';
borderColor = 'rgba(0,0,0,0.1)';
boxShadow = 'none';
color = checked ? checkedColor : '#bbb';
}
return {
alignItems: 'center',
background: background,
border: '1px solid',
borderColor: borderColor,
borderRadius: E.borderRadius.sm,
boxShadow: boxShadow,
color: color,
display: 'inline-block',
fontSize: 14,
height: 16,
lineHeight: '15px',
outline: 'none',
padding: 0,
textAlign: 'center',
textShadow: textShadow,
verticalAlign: 'middle',
width: 16,
msTransition: 'all 120ms ease-out',
MozTransition: 'all 120ms ease-out',
WebkitTransition: 'all 120ms ease-out',
transition: 'all 120ms ease-out',
};
},
handleKeyDown (e) {
if (e.keyCode !== 32) return;
this.toggleActive(true);
},
handleKeyUp () {
this.toggleActive(false);
},
handleMouseOver () {
this.toggleHover(true);
},
handleMouseDown () {
this.toggleActive(true);
this.toggleFocus(true);
},
handleMouseUp () {
this.toggleActive(false);
},
handleMouseOut () {
this.toggleHover(false);
},
toggleActive (pseudo) {
this.setState({ active: pseudo });
},
toggleHover (pseudo) {
this.setState({ hover: pseudo });
},
toggleFocus (pseudo) {
this.setState({ focus: pseudo });
},
handleChange () {
this.props.onChange(!this.props.checked);
},
render () {
const { checked, readonly } = this.props;
const props = blacklist(this.props, 'checked', 'component', 'onChange', 'readonly');
props.style = this.getStyles();
props.ref = 'checkbox';
props.className = classnames('octicon', {
'octicon-check': checked,
'octicon-x': (typeof checked === 'boolean') && !checked && readonly,
});
props.type = readonly ? null : 'button';
props.onKeyDown = this.handleKeyDown;
props.onKeyUp = this.handleKeyUp;
props.onMouseDown = this.handleMouseDown;
props.onMouseUp = this.handleMouseUp;
props.onMouseOver = this.handleMouseOver;
props.onMouseOut = this.handleMouseOut;
props.onClick = readonly ? null : this.handleChange;
props.onFocus = readonly ? null : () => this.toggleFocus(true);
props.onBlur = readonly ? null : () => this.toggleFocus(false);
const node = readonly ? 'span' : this.props.component;
return React.createElement(node, props);
},
});
module.exports = Checkbox;
|
js/components/card/card-showcase.js
|
YeisonGomez/RNAmanda
|
import React, { Component } from 'react';
import { Image, Dimensions } from 'react-native';
import { connect } from 'react-redux';
import { actions } from 'react-native-navigation-redux-helpers';
import { Container, Header, Title, Content, Button, Icon, Card, CardItem, Text, Thumbnail, Left, Right, Body, IconNB } from 'native-base';
import styles from './styles';
import { Actions } from 'react-native-router-flux';
const deviceWidth = Dimensions.get('window').width;
const logo = require('../../../img/logo.png');
const cardImage = require('../../../img/drawer-cover.png');
const {
popRoute,
} = actions;
class NHCardShowcase extends Component {
static propTypes = {
popRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
popRoute() {
this.props.popRoute(this.props.navigation.key);
}
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button transparent onPress={() => Actions.pop()}>
<Icon name="arrow-back" />
</Button>
</Left>
<Body>
<Title>Card Showcase</Title>
</Body>
<Right />
</Header>
<Content padder>
<Card style={styles.mb}>
<CardItem bordered>
<Left>
<Thumbnail source={logo} />
<Body>
<Text>NativeBase</Text>
<Text note>April 15, 2016</Text>
</Body>
</Left>
</CardItem>
<CardItem>
<Body>
<Image style={{ alignSelf: 'center', height: 150, resizeMode: 'cover', width: deviceWidth / 1.18, marginVertical: 5 }} source={cardImage} />
<Text>
NativeBase is a free and, source framework that enables developers
to build high-quality mobile apps using React Native iOS and Android apps
with a fusion of ES6.
NativeBase builds a layer on top of React Native that provides you with
basic set of components for mobile application development.
</Text>
</Body>
</CardItem>
<CardItem style={{paddingVertical: 0}}>
<Left>
<Button transparent>
<Icon name="logo-github" />
<Text>1,926 stars</Text>
</Button>
</Left>
</CardItem>
</Card>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
popRoute: key => dispatch(popRoute(key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
themeState: state.drawer.themeState,
});
export default connect(mapStateToProps, bindAction)(NHCardShowcase);
|
client/components/BubbleSlider.js
|
IBM-Bluemix/election-insights
|
//------------------------------------------------------------------------------
// Copyright IBM Corp. 2016
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//------------------------------------------------------------------------------
import React from 'react';
import Actions from '../Actions';
export default ({ numBubbles }) =>
<div className="bubble-selector">
<div className="num-bubble-label">{numBubbles + (numBubbles === 1 ? " Circle" : " Circles")}</div>
<input
className="slider"
type="range"
min="1"
max="250"
value={numBubbles}
steps="250"
onChange={e => Actions.changeNumBubbles(e.target.value)} />
<div className="help-text">(might need to adjust for screen size or if animations are laggy)</div>
</div>
|
src/components/common/svg-icons/device/signal-wifi-off.js
|
abzfarah/Pearson.NAPLAN.GnomeH
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalWifiOff = (props) => (
<SvgIcon {...props}>
<path d="M23.64 7c-.45-.34-4.93-4-11.64-4-1.5 0-2.89.19-4.15.48L18.18 13.8 23.64 7zm-6.6 8.22L3.27 1.44 2 2.72l2.05 2.06C1.91 5.76.59 6.82.36 7l11.63 14.49.01.01.01-.01 3.9-4.86 3.32 3.32 1.27-1.27-3.46-3.46z"/>
</SvgIcon>
);
DeviceSignalWifiOff = pure(DeviceSignalWifiOff);
DeviceSignalWifiOff.displayName = 'DeviceSignalWifiOff';
DeviceSignalWifiOff.muiName = 'SvgIcon';
export default DeviceSignalWifiOff;
|
app/views/component/CommentTable.js
|
MaxMEllon/comelon
|
'use strict';
import R from 'ramda';
import React from 'react';
import SettingStore from '../../stores/SettingStore';
import Comment from './Comment';
import {List, Paper} from 'material-ui';
const isNil = (obj) => obj != null;
const ifSystemComment = (comment) => R.test(/^(\/(.*)){1}/, comment.get('text'));
const No = (comment) => comment.getIn(['attr', 'no']);
const Id = (comment) => comment.getIn(['attr', 'id']);
const generateKey = (no, id) => {
if (isNil(no) || isNil(id)) {
return Math.random().toString(36).slice(-8);
} else {
return `${no}${id}`;
}
};
const Key = (comment) => generateKey(No(comment), Id(comment));
const Size = (components) => R.length(components);
export default class CommentTable extends React.Component {
static get propTypes() {
return {
comments: React.PropTypes.array.isRequired
};
}
static get displayName() {
return 'CommentTable';
}
constructor(props) {
super(props);
this.state = {
systemComment: false,
doTalking: false
};
}
componentDidMount() {
SettingStore.addChangeListener(this.onChangeOption);
}
componentWillUnMount() {
SettingStore.addChangeListener(this.onChangeOption);
}
onChangeOption = () => {
this.setState({
systemComment: SettingStore.getOption().systemComment,
doTalking: SettingStore.getOption().doTalking
});
}
renderComments() {
const ToSkip = R.and(! this.state.systemComment);
let components = [];
const renderComment = c => {
if (ToSkip(ifSystemComment(c))) return;
components.push(<Comment key={Key(c)} index={Size(components)} comment={c} />);
};
R.forEach(renderComment, this.props.comments);
return components;
}
render() {
return (
<List
className='CommentTableComponent'
style={{
marginTop: '64px',
marginBottom: '64px',
width: '100%',
posision: 'relative',
overflow: 'scroll'
}}
> <Paper className='CommentTableBody'>
{this.renderComments()}
</Paper>
</List>
);
}
}
// vim:ft=javascript.jsx
|
static/js/components/MapPage.js
|
brianhouse/okavango
|
// import React, { PropTypes } from 'react'
import React from 'react'
import NotificationPanelContainer from '../containers/NotificationPanelContainer'
import ControlPanelContainer from '../containers/ControlPanelContainer.js'
const MapPage = () => {
var height = {height: window.innerWidth > 768 ? window.innerHeight - 100 : window.innerHeight - 120}
return (
<div className='page' id="mapPage" style={height}>
<ControlPanelContainer pathName={location.pathname}/>
<NotificationPanelContainer/>
</div>
)
}
// MapPage.propTypes = {
// active : PropTypes.bool.isRequired
// }
export default MapPage
|
src/app/components/resourses/planet/Components.js
|
mazahell/eve-react-app
|
import React from 'react'
import {connect} from 'react-redux'
import Helper from '../../../helpers'
import { ItemView } from '../../item'
class Components extends React.Component {
render() {
let _inputComponents = this.props.materials.map((val) => {
let itemId = val.item_id
let price = this.props.prices[this.props.type_price_input][itemId]
return (
<ItemView
key={val.item_id}
typeID={val.item_id}
name={val.item_name}
price={price}
quantity={val.quantity}
/>
)
})
let scheme = this.props.scheme
let outputPrice = this.props.prices[this.props.type_price_output][this.props.scheme.typeID]
let blockComponents = (
<div>
<div className='row'>
<div className='col-md-12'>
<table>
<thead>
<tr>
<th>Input materials ({Helper.shortNum(this.props.input_volume)} m3)</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<ul className='components list'>
{_inputComponents}
</ul>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div className="row">
<div className='col-md-12'>
<table>
<thead>
<tr>
<th>Output material ({Helper.shortNum(this.props.output_volume)} m3)</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<ul className='components list'>
<ItemView
typeID={scheme.typeID}
name={scheme.schema_name}
price={outputPrice}
quantity={scheme.quantity}
/>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
)
return _inputComponents.length ? blockComponents : null
}
}
export default connect(state => state.planetReducer, {})(Components)
|
test/ButtonGroupSpec.js
|
azmenak/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import ButtonGroup from '../src/ButtonGroup';
import Button from '../src/Button';
import { shouldWarn } from './helpers';
describe('ButtonGroup', function () {
it('Should output a button group', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ButtonGroup>
<Button>
Title
</Button>
</ButtonGroup>
);
assert.equal(React.findDOMNode(instance).nodeName, 'DIV');
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group\b/));
});
it('Should add size', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ButtonGroup bsSize='large'>
<Button>
Title
</Button>
</ButtonGroup>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group-lg\b/));
});
it('Should add vertical variation', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ButtonGroup vertical>
<Button>
Title
</Button>
</ButtonGroup>
);
assert.equal(React.findDOMNode(instance).className.trim(), 'btn-group-vertical');
});
it('Should add block variation', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ButtonGroup vertical block>
<Button>
Title
</Button>
</ButtonGroup>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-block\b/));
});
it('Should warn about block without vertical', function () {
ReactTestUtils.renderIntoDocument(
<ButtonGroup block>
<Button>
Title
</Button>
</ButtonGroup>
);
shouldWarn('The block property requires the vertical property to be set to have any effect');
});
it('Should add justified variation', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ButtonGroup justified>
<Button>
Title
</Button>
</ButtonGroup>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group-justified\b/));
});
});
|
docs/src/app/components/pages/components/Paper/ExampleCircle.js
|
ArcanisCz/material-ui
|
import React from 'react';
import Paper from 'material-ui/Paper';
const style = {
height: 100,
width: 100,
margin: 20,
textAlign: 'center',
display: 'inline-block',
};
const PaperExampleCircle = () => (
<div>
<Paper style={style} zDepth={1} circle={true} />
<Paper style={style} zDepth={2} circle={true} />
<Paper style={style} zDepth={3} circle={true} />
<Paper style={style} zDepth={4} circle={true} />
<Paper style={style} zDepth={5} circle={true} />
</div>
);
export default PaperExampleCircle;
|
src/shared/components/form/textFieldUrl.js
|
namroodinc/truth-serum
|
import React from 'react';
import { observer } from 'mobx-react';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';
import parseDomain from 'parse-domain';
import {red500} from 'material-ui/styles/colors';
import DeleteForever from 'material-ui/svg-icons/action/delete';
import dataActions from '../../actions/dataActions';
import Styles from '../../../client/main.scss';
const { twitter } = Styles;
@observer
export default class TextFieldForm extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
this.handleOnChange = this.handleOnChange.bind(this);
this.handleOnKeyDown = this.handleOnKeyDown.bind(this);
}
handleOnChange = (event, value) => {
this.setState({
value
});
};
handleOnKeyDown = (event) => {
const { formData } = this.props;
const rawDomain = this.state.value;
const parsedDomain = parseDomain(rawDomain);
switch (event.keyCode) {
case 13:
if (parsedDomain) {
dataActions.addUrl(formData, rawDomain, parsedDomain);
this.setState({
value: ''
});
} else {
dataActions.openSnackbar(`${rawDomain} can not be parsed as a domain`);
}
break;
}
};
handleOnDelete = (i) => {
const { formData } = this.props;
dataActions.removeUrl(formData, i);
}
handleGetAlexa = (website) => {
dataActions.getAlexa(`${website.domain}.${website.tld}`);
};
handleGetTwitterLogoColor = (handle) => {
const splitHandle = handle.split('/');
dataActions.getTwitterLogoColor(splitHandle[splitHandle.length-1]);
};
render() {
const { getAlexa, label, value } = this.props;
return (
<div
className="container__row"
>
<h3>
{label}
</h3>
<TextField
hintText={`Enter ${label}`}
onChange={this.handleOnChange}
onKeyDown={this.handleOnKeyDown}
style={{
width: '100%'
}}
value={this.state.value}
/>
{ value.length > 0 ?
<table>
<tbody>
{ value.map((u, i) =>
<tr
key={i}
>
<td>
{u.parsedDomain.domain}.{u.parsedDomain.tld}
</td>
<td>
<span
className="small-text"
>
{u.rawDomain}
</span>
</td>
{ getAlexa &&
<td>
<FlatButton
label="Alexa Ranking"
onClick={this.handleGetAlexa.bind(this, u.parsedDomain)}
/>
</td>
}
<td>
{u.parsedDomain.domain === 'twitter' &&
<FlatButton
backgroundColor={twitter}
label="Twitter Logo Color"
onClick={this.handleGetTwitterLogoColor.bind(this, u.rawDomain)}
/>
}
</td>
<td
className="with--delete"
>
<button
onClick={this.handleOnDelete.bind(this, i)}
>
<DeleteForever
color={red500}
style={{
height: 20,
padding: 0,
width: 20
}}
/>
</button>
</td>
</tr>
)}
</tbody>
</table>
:
<div
className="no-web-urls-found"
>
<div
className="no-publications-found"
>
No Website URLs found.
</div>
</div>
}
</div>
)
}
}
|
src/images/tooth-icon-small.js
|
kakapo2016-projects/tooth-and-pail
|
import React from 'react'
import IconButton from 'material-ui/lib/icon-button'
const styles = {
button: {
width: 20, height: 20,
padding: 0,
},
icon: {
width: 20, height: 20,
},
};
const ToothIcon = () => (
<IconButton style={styles.button} iconStyle={styles.icon} iconClassName="tooth-icon" />
);
export default ToothIcon
|
docs/src/app/components/pages/components/List/ExampleSimple.js
|
pancho111203/material-ui
|
import React from 'react';
import MobileTearSheet from '../../../MobileTearSheet';
import {List, ListItem} from 'material-ui/List';
import ContentInbox from 'material-ui/svg-icons/content/inbox';
import ActionGrade from 'material-ui/svg-icons/action/grade';
import ContentSend from 'material-ui/svg-icons/content/send';
import ContentDrafts from 'material-ui/svg-icons/content/drafts';
import Divider from 'material-ui/Divider';
import ActionInfo from 'material-ui/svg-icons/action/info';
const ListExampleSimple = () => (
<MobileTearSheet>
<List>
<ListItem primaryText="Inbox" leftIcon={<ContentInbox />} />
<ListItem primaryText="Starred" leftIcon={<ActionGrade />} />
<ListItem primaryText="Sent mail" leftIcon={<ContentSend />} />
<ListItem primaryText="Drafts" leftIcon={<ContentDrafts />} />
<ListItem primaryText="Inbox" leftIcon={<ContentInbox />} />
</List>
<Divider />
<List>
<ListItem primaryText="All mail" rightIcon={<ActionInfo />} />
<ListItem primaryText="Trash" rightIcon={<ActionInfo />} />
<ListItem primaryText="Spam" rightIcon={<ActionInfo />} />
<ListItem primaryText="Follow up" rightIcon={<ActionInfo />} />
</List>
</MobileTearSheet>
);
export default ListExampleSimple;
|
src/index.js
|
jcdesimp/GeoBean
|
"use strict";
/**
* Root entry file
*
* This file instantiates the root React component and
* mounts it to the DOM
*/
// import styles
import 'normalize.css';
import './css/main.scss';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import Store from './js/store';
import App from './js/app';
/**
* Main application entry point
*/
let app_props = {
// set app props
};
ReactDOM.render(
React.createElement(
Provider,
{store: Store},
React.createElement(App, app_props)
),
document.getElementById('app-container')
);
|
src/components/Catalog/Catalog.js
|
LeraSavchenko/Maysternia
|
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import Link from '../Link';
import s from './Catalog.css';
const Catalog = () =>
(
<div >
<h1 className={s.headerincatalog}>
Каталог продукції
</h1>
<div className={s.catalog}>
<div className={s.inLine}>
<div className={s.pharagraphs}>
<div>
<p className={s.title}>Внутрішнє та зовнішнє оздоблення</p>
<p className={s.title}>Складні архітектурні вироби</p>
<p className={s.title}>Садово-паркове мистецтво</p>
</div>
<div>
<Link className={s.contactButton} to="/catalog">
<div className={s.button}>
Каталог продукції
</div>
</Link>
</div>
</div>
<div>
<div className={s.linewithsmallphotos}>
<img src="./firstingallery.jpg" alt="firstingallery" href="/" />
</div>
<Link className={s.link} to='/catalog'>
<div className={s.underlined}>Портрети</div>
</Link>
</div>
<div>
<div className={s.linewithsmallphotos}>
<img src="./secondingallery.jpg" alt="secondingallery" href="/" />
</div>
<Link className={s.link} to='/catalog'>
<div className={s.underlined}> Скульптури </div>
</Link>
</div>
</div>
<div className={s.inLine}>
<div>
<div className={s.linewithbigphotos}>
<img src="./thirdingallery.jpg" alt="thirdingallery" href="/" />
</div>
<Link className={s.link} to='/catalog'>
<div className={s.underlined}>Каміни</div>
</Link>
</div>
<div>
<div className={s.linewithbigphotos}>
<img src="./fourthingallery.jpg" alt="fourthingallery" href="/" />
</div>
<Link className={s.link} to='/catalog'>
<div className={s.underlined}>Столешні</div>
</Link>
</div>
</div>
</div>
</div>
);
export default withStyles(s)(Catalog);
|
node_modules/_antd@2.13.4@antd/es/badge/ScrollNumber.js
|
ligangwolai/blog
|
import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import { createElement, Component } from 'react';
import omit from 'omit.js';
import classNames from 'classnames';
function getNumberArray(num) {
return num ? num.toString().split('').reverse().map(function (i) {
return Number(i);
}) : [];
}
var ScrollNumber = function (_Component) {
_inherits(ScrollNumber, _Component);
function ScrollNumber(props) {
_classCallCheck(this, ScrollNumber);
var _this = _possibleConstructorReturn(this, (ScrollNumber.__proto__ || Object.getPrototypeOf(ScrollNumber)).call(this, props));
_this.state = {
animateStarted: true,
count: props.count
};
return _this;
}
_createClass(ScrollNumber, [{
key: 'getPositionByNum',
value: function getPositionByNum(num, i) {
if (this.state.animateStarted) {
return 10 + num;
}
var currentDigit = getNumberArray(this.state.count)[i];
var lastDigit = getNumberArray(this.lastCount)[i];
// 同方向则在同一侧切换数字
if (this.state.count > this.lastCount) {
if (currentDigit >= lastDigit) {
return 10 + num;
}
return 20 + num;
}
if (currentDigit <= lastDigit) {
return 10 + num;
}
return num;
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var _this2 = this;
if ('count' in nextProps) {
if (this.state.count === nextProps.count) {
return;
}
this.lastCount = this.state.count;
// 复原数字初始位置
this.setState({
animateStarted: true
}, function () {
// 等待数字位置复原完毕
// 开始设置完整的数字
setTimeout(function () {
_this2.setState({
animateStarted: false,
count: nextProps.count
}, function () {
var onAnimated = _this2.props.onAnimated;
if (onAnimated) {
onAnimated();
}
});
}, 5);
});
}
}
}, {
key: 'renderNumberList',
value: function renderNumberList(position) {
var childrenToReturn = [];
for (var i = 0; i < 30; i++) {
var currentClassName = position === i ? 'current' : '';
childrenToReturn.push(React.createElement(
'p',
{ key: i.toString(), className: currentClassName },
i % 10
));
}
return childrenToReturn;
}
}, {
key: 'renderCurrentNumber',
value: function renderCurrentNumber(num, i) {
var position = this.getPositionByNum(num, i);
var removeTransition = this.state.animateStarted || getNumberArray(this.lastCount)[i] === undefined;
return createElement('span', {
className: this.props.prefixCls + '-only',
style: {
transition: removeTransition && 'none',
msTransform: 'translateY(' + -position * 100 + '%)',
WebkitTransform: 'translateY(' + -position * 100 + '%)',
transform: 'translateY(' + -position * 100 + '%)'
},
key: i
}, this.renderNumberList(position));
}
}, {
key: 'renderNumberElement',
value: function renderNumberElement() {
var _this3 = this;
var state = this.state;
if (!state.count || isNaN(state.count)) {
return state.count;
}
return getNumberArray(state.count).map(function (num, i) {
return _this3.renderCurrentNumber(num, i);
}).reverse();
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
prefixCls = _props.prefixCls,
className = _props.className,
style = _props.style,
title = _props.title,
_props$component = _props.component,
component = _props$component === undefined ? 'sup' : _props$component;
// fix https://fb.me/react-unknown-prop
var restProps = omit(this.props, ['count', 'onAnimated', 'component', 'prefixCls']);
var newProps = _extends({}, restProps, { className: classNames(prefixCls, className), title: title });
// allow specify the border
// mock border-color by box-shadow for compatible with old usage:
// <Badge count={4} style={{ backgroundColor: '#fff', color: '#999', borderColor: '#d9d9d9' }} />
if (style && style.borderColor) {
newProps.style.boxShadow = '0 0 0 1px ' + style.borderColor + ' inset';
}
return createElement(component, newProps, this.renderNumberElement());
}
}]);
return ScrollNumber;
}(Component);
export default ScrollNumber;
ScrollNumber.defaultProps = {
prefixCls: 'ant-scroll-number',
count: null,
onAnimated: function onAnimated() {}
};
|
collect-webapp/frontend/src/datamanagement/pages/BackupDataImportPage/NewRecordsDataGrid.js
|
openforis/collect
|
import React from 'react'
import { DataGrid, DataGridValueFormatters } from 'common/components'
export const NewRecordsDataGrid = (props) => {
const { keyAttributeColumns, recordsToImport, selectedRecordsToImportIds, stepColumns, onSelectedIdsChange } = props
return (
<DataGrid
className="data-import-new-records"
rows={recordsToImport}
columns={[
{ field: 'entryId', hide: true },
...keyAttributeColumns,
...stepColumns,
{
field: 'recordCreationDate',
headerName: 'dataManagement.backupDataImport.createdOn',
valueFormatter: DataGridValueFormatters.dateTime,
width: 150,
},
{
field: 'recordModifiedDate',
headerName: 'dataManagement.backupDataImport.modifiedOn',
valueFormatter: DataGridValueFormatters.dateTime,
width: 150,
},
{
field: 'recordFilledAttributesCount',
headerName: 'dataManagement.backupDataImport.filledValues',
width: 120,
align: 'right',
},
]}
getRowId={(row) => row.entryId}
checkboxSelection
onSelectedIdsChange={onSelectedIdsChange}
selectionModel={selectedRecordsToImportIds}
/>
)
}
|
app/javascript/src/components/Progress.js
|
michelson/chaskiq
|
import React from 'react'
import styled from '@emotion/styled'
import { keyframes } from '@emotion/core'
// based on https://codepen.io/Siddharth11/pen/xbGrpG
const spin = keyframes`
100% {
transform: rotate(360deg);
}
`
const Loader = styled.div`
animation: ${spin} 0.5s infinite linear;
border-top-color: white;
`
export default function CircularIndeterminate ({ size }) {
const sizeVariant = size || 16
return (
<div className="flex justify-center items-center">
<Loader
className={`loader ease-linear rounded-full
border-4 border-t-4 border-gray-200 h-${sizeVariant} w-${sizeVariant}`
}
/>
</div>
)
}
|
examples/reset-values/app.js
|
RMSAuto/formsy-react
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Form } from 'formsy-react';
import MyInput from './../components/Input';
import MySelect from './../components/Select';
const user = {
name: 'Sam',
free: true,
hair: 'brown'
};
const App = React.createClass({
submit(data) {
alert(JSON.stringify(data, null, 4));
},
resetForm() {
this.refs.form.reset();
},
render() {
return (
<Formsy.Form ref="form" onSubmit={this.submit} className="form">
<MyInput name="name" title="Name" value={user.name} />
<MyInput name="free" title="Free to hire" type="checkbox" value={user.free} />
<MySelect name="hair" title="Hair" value={user.hair}
options={[
{ value: "black", title: "Black" },
{ value: "brown", title: "Brown" },
{ value: "blonde", title: "Blonde" },
{ value: "red", title: "Red" }
]}
/>
<div className="buttons">
<button type="reset" onClick={this.resetForm}>Reset</button>
<button type="submit">Submit</button>
</div>
</Formsy.Form>
);
}
});
ReactDOM.render(<App/>, document.getElementById('example'));
|
examples/huge-apps/routes/Course/routes/Assignments/components/Sidebar.js
|
chunwei/react-router
|
import React from 'react';
import { Link } from 'react-router';
class Sidebar extends React.Component {
render () {
var assignments = COURSES[this.props.params.courseId].assignments
return (
<div>
<h3>Sidebar Assignments</h3>
<ul>
{assignments.map(assignment => (
<li key={assignment.id}>
<Link to={`/course/${this.props.params.courseId}/assignments/${assignment.id}`}>
{assignment.title}
</Link>
</li>
))}
</ul>
</div>
);
}
}
export default Sidebar;
|
tests/components/Book.spec.js
|
hbaughman/audible-temptations
|
import React from 'react'
import Book from 'components/Book/Book'
describe('(Component) Book', () => {
it('should exist', () => {
})
})
|
client/scripts/subject-form.js
|
stas-vilchik/bdd
|
import React from 'react';
import $ from 'jquery';
import Marked from 'marked';
const URL = '/api/subjects';
export default React.createClass({
handleSubmit: function (e) {
e.preventDefault();
var author = React.findDOMNode(this.refs.author).value.trim();
var title = React.findDOMNode(this.refs.title).value.trim();
var description = React.findDOMNode(this.refs.description).value.trim();
if (!description || !author || !title) {
return;
}
if (this.props.subject) {
this.handleSubjectModify({ id: this.props.subject.id, author: author, description: description, title: title });
} else {
this.handleSubjectCreate({ author: author, description: description, title: title });
}
this.props.onSubmit();
React.findDOMNode(this.refs.author).value = '';
React.findDOMNode(this.refs.title).value = '';
React.findDOMNode(this.refs.description).value = '';
},
handleSubjectCreate: function (subject) {
$.ajax({
url: URL,
dataType: 'json',
type: 'POST',
data: JSON.stringify(subject),
contentType: 'application/json',
error: function (xhr, status, err) {
console.error(URL, status, err.toString());
}.bind(this)
});
},
handleSubjectModify: function (subject) {
$.ajax({
url: URL + '/' + subject.id,
dataType: 'json',
type: 'PUT',
data: JSON.stringify(subject),
contentType: 'application/json',
error: function (xhr, status, err) {
console.error(URL, status, err.toString());
}.bind(this)
});
},
cancel(e) {
e.preventDefault();
this.props.onCancel();
},
render: function () {
var author = this.props.subject ? this.props.subject.author : null;
var title = this.props.subject ? this.props.subject.title : null;
var description = this.props.subject ? this.props.subject.description : null;
var cancelButton = this.props.subject ?
<input onClick={this.cancel} className="btn btn-default" type="submit" value="Cancel"/> : null;
return (
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="form-author">Your Name</label>
<input className="form-control" id="form-author" type="text" ref="author" defaultValue={author}/>
</div>
<div className="form-group">
<label htmlFor="form-title">Title</label>
<input className="form-control" id="form-title" type="text" ref="title" defaultValue={title}/>
</div>
<div className="form-group">
<label htmlFor="form-description">Description</label>
<textarea className="form-control" id="form-description" type="text"
placeholder="Describe the topic you want to present" ref="description"
defaultValue={description}/>
</div>
<input className="btn btn-primary" type="submit" value="Post"/>
{cancelButton}
</form>
);
}
});
|
src/Parser/MistweaverMonk/Modules/Traits/MistsOfSheilun.js
|
Yuyz0112/WoWAnalyzer
|
import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import { formatNumber } from 'common/format';
import Module from 'Parser/Core/Module';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
const debug = false;
class MistsOfSheilun extends Module {
// Implement Mists of Sheilun, Celestial Breath, and Refreshing Jade Wind
procsMistsOfSheilun = 0;
healsMistsOfSheilun = 0;
healingMistsOfSheilun = 0;
overhealingMistsOfSheilun = 0;
on_initialized() {
if(!this.owner.error) {
this.active = this.owner.selectedCombatant.traitsBySpellId[SPELLS.MISTS_OF_SHEILUN_TRAIT.id] === 1;
}
}
on_byPlayer_applybuff(event) {
const spellId = event.ability.guid;
if(spellId === SPELLS.MISTS_OF_SHEILUN_BUFF.id) {
this.procsMistsOfSheilun++;
}
}
on_byPlayer_heal(event) {
const spellId = event.ability.guid;
if(spellId === SPELLS.MISTS_OF_SHEILUN.id) {
this.healsMistsOfSheilun++;
this.healingMistsOfSheilun += event.amount;
if(event.overheal) {
this.overhealingMistsOfSheilun += event.overheal;
}
}
}
statistic() {
const avgMistsOfSheilunHealing = this.healingMistsOfSheilun / this.healsMistsOfSheilun || 0;
const avgMistsOfSheilunTargets = this.healsMistsOfSheilun / this.procsMistsOfSheilun || 0;
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.MISTS_OF_SHEILUN_TRAIT.id} />}
value={`${formatNumber(avgMistsOfSheilunHealing)}`}
label={(
<dfn data-tip={`You healed an average of ${(avgMistsOfSheilunTargets).toFixed(2)} targets per Mists of Sheilun proc over your ${this.procsMistsOfSheilun} procs.`}>
Average Healing
</dfn>
)}
/>
);
}
statisticOrder = STATISTIC_ORDER.OPTIONAL();
on_finished() {
if(debug) {
console.log('Mists of Sheilun Procs: ' + this.procsMistsOfSheilun);
console.log('Avg Heals per Procs: ' + (this.healsMistsOfSheilun / this.procsMistsOfSheilun));
console.log('Avg Heals Amount: ' + (this.healingMistsOfSheilun / this.healsMistsOfSheilun));
}
}
}
export default MistsOfSheilun;
|
images/client/components/image_detail.js
|
cristianobento/udemy-meteor-react
|
// Create our image list component
// Import React
import React from 'react';
import ImageScore from './image_score';
// Create our component
const ImageDetail = (props) => {
// props.image => this is the image object
// props.image.title
// props.image.link
return(
<li className="media list-group-item">
<div className="media-left">
<img src={props.image.link} alt={props.image.title} title={props.image.title} />
</div>
<div className="media-body">
<h4 className="media-heading">{props.image.title}</h4>
<p>{props.image.description}</p>
<ImageScore ups={props.image.ups} downs={props.image.downs} />
</div>
</li>
);
};
// Export our component
export default ImageDetail;
|
src/svg-icons/av/hd.js
|
w01fgang/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvHd = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-8 12H9.5v-2h-2v2H6V9h1.5v2.5h2V9H11v6zm2-6h4c.55 0 1 .45 1 1v4c0 .55-.45 1-1 1h-4V9zm1.5 4.5h2v-3h-2v3z"/>
</SvgIcon>
);
AvHd = pure(AvHd);
AvHd.displayName = 'AvHd';
AvHd.muiName = 'SvgIcon';
export default AvHd;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.