path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
Js/Ui/Components/DateTime/index.js | Webiny/Webiny | import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'lodash';
import $ from 'jquery';
import Webiny from 'webiny';
class DateTime extends Webiny.Ui.FormComponent {
constructor(props) {
super(props);
this.valueChanged = false;
this.bindMethods('setup,onChange');
}
shouldComponentUpdate(nextProps, nextState) {
if (nextProps['disabledBy']) {
return true;
}
const omit = ['children', 'key', 'ref', 'onChange'];
const oldProps = _.omit(this.props, omit);
const newProps = _.omit(nextProps, omit);
return !_.isEqual(newProps, oldProps) || !_.isEqual(nextState, this.state);
}
componentDidUpdate(prevProps, prevState) {
super.componentDidUpdate();
if (prevState.isValid !== this.state.isValid) {
this.input.setState({
isValid: this.state.isValid,
validationMessage: this.state.validationMessage
});
}
}
setup() {
const dom = ReactDOM.findDOMNode(this);
this.element = $(dom.querySelector('input'));
let format = this.props.inputFormat || Webiny.I18n.getDatetimeFormat();
format = Webiny.I18n.convertPhpToJsDateTimeFormat(format);
this.element.datetimepicker({
format,
stepping: this.props.stepping,
keepOpen: false,
debug: this.props.debug || false,
minDate: this.props.minDate ? new Date(this.props.minDate) : false,
viewMode: this.props.viewMode,
widgetPositioning: {
horizontal: this.props.positionHorizontal || 'auto',
vertical: this.props.positionVertical || 'bottom'
}
}).on('dp.hide', e => {
if (this.valueChanged) {
this.onChange(e.target.value);
}
this.valueChanged = false;
}).on('dp.change', () => {
this.valueChanged = true;
});
}
onChange(newValue) {
if (newValue) {
newValue = Webiny.I18n.datetime(newValue, this.props.modelFormat, this.props.inputFormat || Webiny.I18n.getDatetimeFormat());
}
if (newValue !== this.props.value) {
this.props.onChange(newValue, this.validate);
}
}
renderPreview() {
if (!_.isEmpty(this.props.value)) {
return Webiny.I18n.datetime(this.props.value, this.props.inputFormat, this.props.modelFormat);
}
return this.getPlaceholder();
}
}
DateTime.defaultProps = Webiny.Ui.FormComponent.extendProps({
debug: false,
inputFormat: null,
modelFormat: 'Y-m-d H:i:s',
positionHorizontal: 'auto',
positionVertical: 'bottom',
viewMode: 'days',
renderer() {
const omitProps = ['attachToForm', 'attachValidators', 'detachFromForm', 'validateInput', 'form', 'renderer', 'name', 'onChange'];
const props = _.omit(this.props, omitProps);
const {Input, Icon} = props;
props.value = this.renderPreview();
props.addonRight = <Icon icon="icon-calendar"/>;
props.onComponentDidMount = input => {
this.input = input;
this.setup();
};
return <Input {...props}/>;
}
});
export default Webiny.createComponent(DateTime, {
modules: ['Icon', 'Input', 'Webiny/Vendors/DateTimePicker']
});
|
public/src/index.js | vidyakhadsare/easyUp | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import { Router, browserHistory} from 'react-router';
import routes from './routes';
import reducers from './reducers';
//Creation of Store using Redux-Thunk
const createStoreWithMiddleware = applyMiddleware(
thunk,
createLogger()
)(createStore);
/****************** React routing *************/
//Render Final React DOM elemets
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={browserHistory} routes={routes}/>
</Provider>
, document.querySelector('.container'));
|
src/routes.js | jogacommuri/ReactShoppingCart | "use strict"
//React
import React from 'react';
import {render} from 'react-dom';
//React Router
import {Router, Route, IndexRoute, browserHistory} from 'react-router';
import BooksList from './components/pages/booksList';
import Cart from './components/pages/cart';
import BooksForm from './components/pages/bookForm';
import Main from './main';
const routes = (
<Router history={browserHistory} >
<Route path="/" component={Main}>
<IndexRoute component={BooksList} />
<Route path="/admin" component={BooksForm} />
<Route path="/cart" component={Cart} />
</Route>
</Router>
)
export default routes; |
src/components/IndexPage.js | baker-natalie/lets-react | 'use strict';
import React from 'react';
import PagePreview from './PagePreview';
import pages from '../data/pages';
export default class IndexPage extends React.Component {
render() {
return (
<div className="home">
<div className="page-selector">
{pages.map(pageData => <PagePreview key={pageData.id} {...pageData} />)}
</div>
</div>
);
}
}
|
src/components/topic/wizard/TopicSeedDetailsForm.js | mitmedialab/MediaCloud-Web-Tools | import PropTypes from 'prop-types';
import React from 'react';
import { reduxForm, Field, propTypes } from 'redux-form';
import { Row, Col } from 'react-flexbox-grid/lib';
import withIntlForm from '../../common/hocs/IntlForm';
import TopicAdvancedForm from './TopicAdvancedForm';
const localMessages = {
name: { id: 'topic.form.detail.name', defaultMessage: 'Topic Name (what is this about?)' },
startDate: { id: 'topic.form.detail.startDate', defaultMessage: 'Start Date (inclusive)' },
endDate: { id: 'topic.form.detail.endDate', defaultMessage: 'End Date (inclusive)' },
};
const TopicSeedDetailsForm = (props) => {
const { renderTextField, initialValues } = props;
const { formatMessage } = props.intl;
return (
<div>
<Row>
<Col lg={6}>
<Field
name="start_date"
component={renderTextField}
type="inline"
fullWidth
label={formatMessage(localMessages.startDate)}
/>
</Col>
<Col lg={6}>
<Field
name="end_date"
component={renderTextField}
type="inline"
fullWidth
label={formatMessage(localMessages.endDate)}
helpertext={formatMessage(localMessages.endDate)}
/>
</Col>
</Row>
<TopicAdvancedForm
initialValues={initialValues}
destroyOnUnmount={false}
form="topicForm"
forceUnregisterOnUnmount
/>
</div>
);
};
TopicSeedDetailsForm.propTypes = {
// from compositional chain
intl: PropTypes.object.isRequired,
renderTextField: PropTypes.func.isRequired,
// from parent
initialValues: PropTypes.object,
};
export default
withIntlForm(
reduxForm({ propTypes })(
TopicSeedDetailsForm
)
);
|
src/svg-icons/action/cached.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionCached = (props) => (
<SvgIcon {...props}>
<path d="M19 8l-4 4h3c0 3.31-2.69 6-6 6-1.01 0-1.97-.25-2.8-.7l-1.46 1.46C8.97 19.54 10.43 20 12 20c4.42 0 8-3.58 8-8h3l-4-4zM6 12c0-3.31 2.69-6 6-6 1.01 0 1.97.25 2.8.7l1.46-1.46C15.03 4.46 13.57 4 12 4c-4.42 0-8 3.58-8 8H1l4 4 4-4H6z"/>
</SvgIcon>
);
ActionCached = pure(ActionCached);
ActionCached.displayName = 'ActionCached';
ActionCached.muiName = 'SvgIcon';
export default ActionCached;
|
saleor/static/js/components/categoryPage/NoResults.js | tfroehlich82/saleor | import React from 'react';
import InlineSVG from 'react-inlinesvg';
import noResultsImg from '../../../images/pirate.svg';
const NoResults = () => {
return (
<div className="no-results">
<div className="col-12">
<InlineSVG src={noResultsImg} />
<p>{pgettext('Epty search results', 'Sorry, no matches found for your request.')}</p>
<p>{pgettext('Epty search results', 'Try again or shop new arrivals.')}</p>
</div>
</div>
);
};
export default NoResults;
|
client/index.js | alexdvance/the-watcher | import 'babel-polyfill'
import { trigger } from 'redial'
import React from 'react'
import ReactDOM from 'react-dom'
import Router from 'react-router/lib/Router'
import match from 'react-router/lib/match'
import browserHistory from 'react-router/lib/browserHistory'
import { Provider } from 'react-redux'
import { StyleSheet } from 'aphrodite'
import { configureStore } from '../common/store'
const initialState = window.INITIAL_STATE || {}
// Set up Redux (note: this API requires redux@>=3.1.0):
const store = configureStore(initialState)
const { dispatch } = store
const container = document.getElementById('root')
StyleSheet.rehydrate(window.renderedClassNames)
const render = () => {
const { pathname, search, hash } = window.location
const location = `${pathname}${search}${hash}`
// We need to have a root route for HMR to work.
const createRoutes = require('../common/routes/root').default
const routes = createRoutes(store)
// Pull child routes using match. Adjust Router for vanilla webpack HMR,
// in development using a new key every time there is an edit.
match({ routes, location }, () => {
// Render app with Redux and router context to container element.
// We need to have a random in development because of `match`'s dependency on
// `routes.` Normally, we would want just one file from which we require `routes` from.
ReactDOM.render(
<Provider store={store}>
<Router routes={routes} history={browserHistory} key={Math.random()} />
</Provider>,
container
)
})
return browserHistory.listen(location => {
// Match routes based on location object:
match({ routes, location }, (error, redirectLocation, renderProps) => {
if (error) console.log(error)
// Get array of route handler components:
const { components } = renderProps
// Define locals to be provided to all lifecycle hooks:
const locals = {
path: renderProps.location.pathname,
query: renderProps.location.query,
params: renderProps.params,
// Allow lifecycle hooks to dispatch Redux actions:
dispatch
}
// Don't fetch data for initial route, server has already done the work:
if (window.INITIAL_STATE) {
// Delete initial data so that subsequent data fetches can occur:
delete window.INITIAL_STATE
} else {
// Fetch mandatory data dependencies for 2nd route change onwards:
trigger('fetch', components, locals)
}
// Fetch deferred, client-only data dependencies:
trigger('defer', components, locals)
})
})
}
const unsubscribeHistory = render()
if (module.hot) {
module.hot.accept('../common/routes/root', () => {
unsubscribeHistory()
setTimeout(render)
})
}
|
app/components/landing/HeroMobile/index.js | vkurzweg/aloha | /**
*
* HeroText
*
*/
import React from 'react';
// import styled from 'styled-components';
import Slider from 'react-slick';
import 'slick-carousel';
import { Image } from 'cloudinary-react';
import { Link } from 'react-router';
import Button from './Button';
import styled from 'styled-components';
const StyledImage = styled.div`
background-image: url('http://res.cloudinary.com/kurzweg/image/upload/v1510814149/sunset_surf.jpg');
background-size: cover;
background-repeat: no-repeat;
background-position: center;
height: 520px;
margin-top: -9%;
`;
function Hero() {
const settings = {
autoplay: true,
autoplaySpeed: 4000,
fade: true,
arrows: false,
};
return (
<div style={{ width: '100%', backgroundColor: 'black', top: '0' }}>
<div style={{ zIndex: '10', dispay: 'block', margin: '0 auto', width: '100%', position: 'absolute' }}>
<h4 style={{ fontFamily: 'Josefin Sans', textAlign: 'center', color: '#F3BB58', textTransform: 'uppercase', letterSpacing: '3px', fontWeight: 'bold', marginTop: '87%', fontSize: '26px' }}>Venice Beach <br /> surf lessons</h4>
<hr style={{ color: '#F3BB58', width: '33%', textAlign: 'center', marginTop: '-.5%' }} />
<h4 style={{ fontFamily: 'Josefin Sans', textAlign: 'center', color: '#F3BB58', textTransform: 'uppercase', letterSpacing: '3px', fontWeight: 'bold', fontSize: '26px', marginTop: '-2%' }}>$85+</h4>
<Link to="/contact" style={{ textDecoration: 'none' }}><Button>Sign Up</Button></Link>
</div>
<StyledImage />
</div>
);
}
Hero.propTypes = {
};
export default Hero;
// <h1 style={{ fontSize: '30px', fontFamily: 'Lobster', textAlign: 'center', color: '#FF80AB', letterSpacing: '2px' }}>Let's get you out there</h1>
// <Slider {...settings}>
// <div style={{ width: '100%' }}>
// <Image cloudName="kurzweg" publicId="portugal1" width="250" responsive quality="auto" style={{ height: '200px', width: '100%', paddingTop: '6%', display: 'block', margin: '0 auto', marginTop: '8%' }} />
// </div>
// <div style={{ width: '100%' }}>
// <Image cloudName="kurzweg" publicId="portugal2" width="250" responsive quality="auto" style={{ height: '200px', width: '100%', paddingTop: '6%', display: 'block', margin: '0 auto', marginTop: '8%' }} />
// </div>
// <div style={{ width: '100%' }}>
// <Image cloudName="kurzweg" publicId="portugal3" width="250" responsive quality="auto" style={{ height: '200px', width: '100%', paddingTop: '6%', display: 'block', margin: '0 auto', marginTop: '8%' }} />
// </div>
// </Slider>
|
src/frontend/containers/door/admin/list.js | PiTeam/garage-pi | import React from 'react';
import { connect } from 'react-redux';
import ListItem from 'material-ui/lib/lists/list-item';
import { Link } from 'react-router';
import Avatar from 'material-ui/lib/avatar';
import ActionSettings from 'material-ui/lib/svg-icons/action/settings';
import Divider from 'material-ui/lib/divider';
import List from 'material-ui/lib/lists/list';
import RaisedButton from 'material-ui/lib/raised-button';
import Paper from 'material-ui/lib/paper';
import { getDoorPropType } from 'proptypes';
const DoorList = ({ doors }) => {
const getStyles = () => ({
h1: {
marginBottom: '1em',
},
paper: {
padding: '0 .5em',
marginBottom: '4em',
},
backButton: {
float: 'left',
},
link: {
textDecoration: 'none',
},
bottomButtons: {
bottom: '1em',
left: '1em',
right: '1em',
position: 'absolute',
},
clear: {
clear: 'both',
},
});
const styles = getStyles();
return (
<div>
<h1 style={styles.h1}>{'Manage doors'}</h1>
<Paper style={styles.paper}>
<List>
{doors.get('data').map((door, i) => (
<div key={i}>
<Link
style={styles.link}
to={`/manage/door/${door.get('id')}`}
>
<ListItem
leftAvatar={<Avatar src={door.get('image')} />}
primaryText={door.get('name')}
rightIcon={<ActionSettings />}
/>
</Link>
{i < doors.get('data').size - 1 && <Divider />}
</div>
))
}
</List>
</Paper>
<div style={styles.bottomButtons}>
<Link
to="/manage"
>
<RaisedButton
label="Back"
style={styles.backButton}
/>
</Link>
</div>
</div>
);
};
function mapStateToProps({ doors }) {
return { doors };
}
export default connect(mapStateToProps)(DoorList);
DoorList.propTypes = {
doors: getDoorPropType(),
};
|
ui/src/components/settings/SettingRow.js | yahoo/athenz | /*
* Copyright 2020 Verizon Media
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import styled from '@emotion/styled';
import Switch from '../denali/Switch';
import Input from '../denali/Input';
import RadioButtonGroup from '../denali/RadioButtonGroup';
const TDStyled = styled.td`
background-color: ${(props) => props.color};
text-align: ${(props) => props.align};
padding: 5px 0 5px 15px;
vertical-align: middle;
word-break: break-all;
`;
const TrStyled = styled.tr`
box-sizing: border-box;
margin-top: 10px;
box-shadow: 0 1px 4px #d9d9d9;
border: 1px solid #fff;
-webkit-border-image: none;
border-image: none;
-webkit-border-image: initial;
border-image: initial;
height: 50px;
`;
const StyledDiv = styled.div`
display: flex;
`;
const SettingInput = styled(Input)`
margin-top: 5px;
`;
export default class SettingRow extends React.Component {
constructor(props) {
super(props);
this.onTimeChange = this.onTimeChange.bind(this);
this.toggleSwitchButton = this.toggleSwitchButton.bind(this);
this.onRadioChange = this.onRadioChange.bind(this);
this.saveJustification = this.saveJustification.bind(this);
this.api = props.api;
}
saveJustification(val) {
this.setState({ deleteJustification: val });
}
toggleSwitchButton(evt) {
this.props.onValueChange(this.props.name, evt.currentTarget.checked);
}
onTimeChange(evt) {
this.props.onValueChange(this.props.name, evt.target.value);
}
onRadioChange(event) {
if (event.target.value) {
this.props.onValueChange(this.props.name, event.target.value);
}
}
numRestricted(event) {
const re = /[0-9]+/g;
if (!re.test(event.key)) {
event.preventDefault();
}
}
getSettingButton() {
switch (this.props.type) {
case 'switch':
return (
<Switch
name={'setting' + this.props.name}
value={this.props.value}
checked={this.props.value}
onChange={this.toggleSwitchButton}
/>
);
case 'input':
return (
<StyledDiv>
<SettingInput
pattern='[0-9]*'
placeholder={this.props.unit}
fluid
id={'setting-' + this.props.name}
onChange={this.onTimeChange}
onKeyPress={this.numRestricted}
value={this.props.value}
/>
</StyledDiv>
);
}
}
render() {
let rows = [];
let left = 'left';
let color = this.props.color;
let label = this.props.label;
if (this.props.unit) {
label += this.props.unit ? ` (${this.props.unit})` : '';
}
let name = this.props.name;
let button = this.getSettingButton();
rows.push(
<TrStyled key={name} data-testid='setting-row'>
<TDStyled color={color} align={left}>
{label}
</TDStyled>
<TDStyled color={color} align={left}>
{button}
</TDStyled>
<TDStyled color={color} align={left}>
{this.props.desc}
</TDStyled>
</TrStyled>
);
return rows;
}
}
|
src/routes.js | mihailgaberov/media-library | /**
* Created by Mihail on 1/6/2017.
*/
import React from 'react'
import { IndexRoute, Route } from 'react-router'
import App from './components/App'
import PhotosPage from './components/PhotosPage'
import VideosPage from './components/VideosPage'
export default (
<Route path="/" component={App}>
<IndexRoute component={PhotosPage}/>
<Route path="videos" component={VideosPage}/>
</Route>
) |
docs/src/app/components/pages/components/Drawer/Page.js | rscnt/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import drawerReadmeText from './README';
import DrawerSimpleExample from './ExampleSimple';
import drawerSimpleExampleCode from '!raw!./ExampleSimple';
import DrawerUndockedExample from './ExampleUndocked';
import drawerUndockedExampleCode from '!raw!./ExampleUndocked';
import DrawerOpenSecondaryExample from './ExampleOpenSecondary';
import drawerOpenSecondaryExampleCode from '!raw!./ExampleOpenSecondary';
import drawerCode from '!raw!material-ui/lib/Drawer/Drawer';
const descriptions = {
simple: 'A simple controlled `Drawer`. The Drawer is `docked` by default, ' +
'remaining open unless closed through the `open` prop.',
undocked: 'An undocked controlled `Drawer` with custom width. ' +
'The Drawer can be cancelled by clicking the overlay or pressing the Esc key. ' +
'It closes when an item is selected, handled by controlling the `open` prop.',
right: 'The `openSecondary` prop allows the Drawer to open on the opposite side.',
};
const DrawerPage = () => (
<div>
<Title render={(previousTitle) => `Drawer - ${previousTitle}`} />
<MarkdownElement text={drawerReadmeText} />
<CodeExample
title="Docked example"
description={descriptions.simple}
code={drawerSimpleExampleCode}
>
<DrawerSimpleExample />
</CodeExample>
<CodeExample
title="Undocked example"
description={descriptions.undocked}
code={drawerUndockedExampleCode}
>
<DrawerUndockedExample />
</CodeExample>
<CodeExample
title="Open secondary example"
description={descriptions.right}
code={drawerOpenSecondaryExampleCode}
>
<DrawerOpenSecondaryExample />
</CodeExample>
<PropTypeDescription code={drawerCode} />
</div>
);
export default DrawerPage;
|
front_end/src/pages/Reporting/Reporting-Reports.js | mozilla/splice | import React from 'react';
import {connect} from 'react-redux';
import moment from 'moment';
import Select from 'react-select';
import {Table} from 'react-tabular';
import {fetchCampaigns, fetchCampaign, campaignSetFilter} from 'actions/Campaigns/CampaignActions';
import {fetchAccounts} from 'actions/Accounts/AccountActions';
import {fetchStats} from 'actions/Stats/StatsActions';
import CampaignSummary from './CampaignSummary';
import {
FILTERS,
DEFAULT_REPORT_SETTINGS,
GROUP_BY_OPTIONS,
GROUP_BY_FIELDS,
BASE_FIELDS
} from './reportingConsts';
import {createFieldSet, queryParser} from './reportingUtils';
const ReportingReports = React.createClass({
getInitialState: function() {
return _.assign({}, DEFAULT_REPORT_SETTINGS, {
showEditor: true,
showAllFilters: false
});
},
componentWillMount: function() {
this.props.dispatch(campaignSetFilter('past', true));
this.props.dispatch(fetchAccounts());
const query = queryParser(this.props.location.query);
if (query.account_id) {
this.props.dispatch(fetchCampaigns(query.account_id));
this.setState(_.assign({}, query, {showEditor: false}));
this.generateReport(query);
}
},
componentWillUpdate: function(prevProps) {
if (this.props.Stat.rows !== prevProps.Stat.rows &&
!_.isEqual(queryParser(this.props.location.query), this.state)) {
this.props.history.pushState(
this.props.location.state,
this.props.location.pathname,
queryParser(this.state)
);
}
},
onSelectAccount: function(accountId) {
if (accountId) this.props.dispatch(fetchCampaigns(accountId));
this.setState({account_id: accountId, campaign_id: null});
},
onSelectCampaign: function(campaignId) {
if (!campaignId) return this.setState({campaign_id: null});
const {start_date, end_date} = campaignId ? this.campaignById(campaignId) : null;
this.setState({
campaign_id: campaignId,
start_date: moment(start_date, 'YYYY-MM-DD').format('YYYY-MM-DD'),
end_date: moment(end_date, 'YYYY-MM-DD').format('YYYY-MM-DD')
});
},
render: function() {
const reportSettings = this.state;
const currentCampaign = this.props.Campaign.details;
const stats = this.props.Stat.rows || [];
const query = this.props.Stat.query;
const fields = createFieldSet(query.group_by);
return (<div>
<aside className={'sidebar' + (this.state.showEditor ? '' : ' collapsed')}>
<div className="report-settings">
<section>
<div className="form-group">
<label>Account</label>
{this.props.Account.rows.length && <Select
value={reportSettings.account_id}
options={this.props.Account.rows.map(a => { return {value: a.id, label: a.name}; })}
onChange={this.onSelectAccount} />}
</div>
<div className="form-group" hidden={!reportSettings.account_id || !this.props.Campaign.rows.length}>
<label>Campaign</label>
{this.props.Campaign.rows.length && <Select
value={this.props.Campaign.rows ? reportSettings.campaign_id : ''}
options={this.props.Campaign.rows.map(c => { return {value: c.id, label: c.name}; })}
onChange={this.onSelectCampaign} />}
</div>
</section>
<div hidden={!this.state.campaign_id}>
<section className="flex-wrapper">
<div className="form-group half">
<label>Start Date</label>
<input className="form-control" value={reportSettings.start_date}
onChange={(e) => this.setState({start_date: e.target.value})} />
</div>
<div className="form-group half">
<label>End Date</label>
<input className="form-control" value={reportSettings.end_date}
onChange={(e) => this.setState({end_date: e.target.value})} />
</div>
</section>
<section>
<div className="form-group">
<label>Group By</label>
<div className="form-group">
{this.state.group_by.map((groupBy, index) => {
return (<Select
key={index}
value={groupBy}
options={GROUP_BY_OPTIONS}
onChange={value => this.setGroupBy(value, index)} />);
})}
</div>
<div className="form-group">
<button className="btn btn-default btn-emphasis" onClick={() => this.addGroupBy()}>Add field</button>
</div>
</div>
</section>
<section className="extra" hidden={!this.showAllFilters()}>
<div className="form-group">
<label>Type</label>
<Select
value={reportSettings.adgroup_type}
options={[
{value: null, label: 'All'},
{value: 'directory', label: 'Directory'},
{value: 'suggested', label: 'Suggested'}
]}
placeholder="All"
onChange={(value) => this.setState({adgroup_type: value})} />
</div>
<div className="form-group">
<label>Channel</label>
<Select
value={reportSettings.channel_id}
options={[{value: null, label: 'All'}].concat(this.props.Init.channels.map(c => {
return {value: c.id, label: c.name};
}))}
placeholder="All"
onChange={(value) => this.setState({channel_id: value})} />
</div>
<div className="form-group">
<label>Locale</label>
<Select
value={reportSettings.locale}
options={[{value: null, label: 'All'}].concat(this.props.Init.locales.map(l => {
return {value: l, label: l};
}))}
placeholder="All"
onChange={(value) => this.setState({locale: value})} />
</div>
<div className="form-group">
<label>Country</label>
<Select
value={reportSettings.country_code}
options={[{value: null, label: 'All'}].concat(this.props.Init.countries.map(c => {
return {value: c.country_code, label: c.country_name};
}))}
placeholder="All"
onChange={(value) => this.setState({country_code: value})} />
</div>
<div className="form-group">
<button className="btn btn-default btn-emphasis"
onClick={() => this.setState({
showAllFilters: false, channel_id: null, adgroup_type: null
})}>
Clear extra filters
</button>
</div>
</section>
<section hidden={this.showAllFilters()}>
<button className="btn btn-default btn-emphasis"
onClick={() => this.setState({showAllFilters: true})}>
<span className="fa fa-sliders" /> Show more fitlers
</button>
</section>
<section>
<button onClick={() => this.generateReport(this.state)} className="btn btn-pink btn-emphasis">
Generate Report
</button>
</section>
</div>
</div>
</aside>
<main className="main" hidden={!currentCampaign.id}>
<h2> Report for {currentCampaign.name} by {query.group_by && query.group_by.map(field => GROUP_BY_FIELDS[field].label).join(' / ')}
<div className="pull-right">
<button hidden={this.state.showEditor} className="btn btn-pink btn-emphasis"
onClick={() => this.setState({showEditor: true})}>
<span className="fa fa-pencil" /> Edit report
</button>
<button className="btn btn-default btn-emphasis"
onClick={() => this.refs.table.download(`${currentCampaign.name}-stats.csv`)}>
<span className="fa fa-file-o" /> Download as .csv
</button>
</div>
</h2>
<CampaignSummary campaign={currentCampaign} query={query} />
<Table ref="table" fields={fields} data={stats} fieldsEditable={true} />
</main>
</div>);
},
setGroupBy: function(value, index) {
const groupBy = this.state.group_by.slice();
if (value) {
groupBy[index] = value;
} else {
if (index > 0) groupBy.splice(index, 1);
}
this.setState({group_by: groupBy});
},
addGroupBy: function() {
const groupBy = this.state.group_by.slice();
groupBy.push('date');
this.setState({group_by: groupBy});
},
campaignById: function(id) {
const campaigns = this.props.Campaign.rows;
let result;
campaigns.forEach(c => {
if (+c.id === +id) result = c;
});
return result || {};
},
generateReport: function(query) {
const params = queryParser(query);
Object.keys(params).forEach(param => {
if (!params[param]) delete params[param];
});
this.props.dispatch(fetchStats(params));
if (query.campaign_id) this.props.dispatch(fetchCampaign(query.campaign_id));
},
showAllFilters: function() {
if (this.state.showAllFilters) return true;
if (this.state.adgroup_type || this.state.channel_id) return true;
return false;
}
});
function select(state) {
return {
Account: state.Account,
Campaign: state.Campaign,
Init: state.Init,
Stat: state.Stat
};
}
// Wrap the component to inject dispatch and state into it
export default connect(select)(ReportingReports);
|
app/javascript/mastodon/components/relative_timestamp.js | amazedkoumei/mastodon | import React from 'react';
import { injectIntl, defineMessages } from 'react-intl';
import PropTypes from 'prop-types';
const messages = defineMessages({
just_now: { id: 'relative_time.just_now', defaultMessage: 'now' },
seconds: { id: 'relative_time.seconds', defaultMessage: '{number}s' },
minutes: { id: 'relative_time.minutes', defaultMessage: '{number}m' },
hours: { id: 'relative_time.hours', defaultMessage: '{number}h' },
days: { id: 'relative_time.days', defaultMessage: '{number}d' },
});
const dateFormatOptions = {
hour12: false,
year: 'numeric',
month: 'short',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
};
const shortDateFormatOptions = {
month: 'short',
day: 'numeric',
};
const SECOND = 1000;
const MINUTE = 1000 * 60;
const HOUR = 1000 * 60 * 60;
const DAY = 1000 * 60 * 60 * 24;
const MAX_DELAY = 2147483647;
const selectUnits = delta => {
const absDelta = Math.abs(delta);
if (absDelta < MINUTE) {
return 'second';
} else if (absDelta < HOUR) {
return 'minute';
} else if (absDelta < DAY) {
return 'hour';
}
return 'day';
};
const getUnitDelay = units => {
switch (units) {
case 'second':
return SECOND;
case 'minute':
return MINUTE;
case 'hour':
return HOUR;
case 'day':
return DAY;
default:
return MAX_DELAY;
}
};
export const timeAgoString = (intl, date, now, year) => {
const delta = now - date.getTime();
let relativeTime;
if (delta < 10 * SECOND) {
relativeTime = intl.formatMessage(messages.just_now);
} else if (delta < 7 * DAY) {
if (delta < MINUTE) {
relativeTime = intl.formatMessage(messages.seconds, { number: Math.floor(delta / SECOND) });
} else if (delta < HOUR) {
relativeTime = intl.formatMessage(messages.minutes, { number: Math.floor(delta / MINUTE) });
} else if (delta < DAY) {
relativeTime = intl.formatMessage(messages.hours, { number: Math.floor(delta / HOUR) });
} else {
relativeTime = intl.formatMessage(messages.days, { number: Math.floor(delta / DAY) });
}
} else if (date.getFullYear() === year) {
relativeTime = intl.formatDate(date, shortDateFormatOptions);
} else {
relativeTime = intl.formatDate(date, { ...shortDateFormatOptions, year: 'numeric' });
}
return relativeTime;
};
@injectIntl
export default class RelativeTimestamp extends React.Component {
static propTypes = {
intl: PropTypes.object.isRequired,
timestamp: PropTypes.string.isRequired,
year: PropTypes.number.isRequired,
};
state = {
now: this.props.intl.now(),
};
static defaultProps = {
year: (new Date()).getFullYear(),
};
shouldComponentUpdate (nextProps, nextState) {
// As of right now the locale doesn't change without a new page load,
// but we might as well check in case that ever changes.
return this.props.timestamp !== nextProps.timestamp ||
this.props.intl.locale !== nextProps.intl.locale ||
this.state.now !== nextState.now;
}
componentWillReceiveProps (nextProps) {
if (this.props.timestamp !== nextProps.timestamp) {
this.setState({ now: this.props.intl.now() });
}
}
componentDidMount () {
this._scheduleNextUpdate(this.props, this.state);
}
componentWillUpdate (nextProps, nextState) {
this._scheduleNextUpdate(nextProps, nextState);
}
componentWillUnmount () {
clearTimeout(this._timer);
}
_scheduleNextUpdate (props, state) {
clearTimeout(this._timer);
const { timestamp } = props;
const delta = (new Date(timestamp)).getTime() - state.now;
const unitDelay = getUnitDelay(selectUnits(delta));
const unitRemainder = Math.abs(delta % unitDelay);
const updateInterval = 1000 * 10;
const delay = delta < 0 ? Math.max(updateInterval, unitDelay - unitRemainder) : Math.max(updateInterval, unitRemainder);
this._timer = setTimeout(() => {
this.setState({ now: this.props.intl.now() });
}, delay);
}
render () {
const { timestamp, intl, year } = this.props;
const date = new Date(timestamp);
const relativeTime = timeAgoString(intl, date, this.state.now, year);
return (
<time dateTime={timestamp} title={intl.formatDate(date, dateFormatOptions)}>
{relativeTime}
</time>
);
}
}
|
src/svg-icons/hardware/gamepad.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareGamepad = (props) => (
<SvgIcon {...props}>
<path d="M15 7.5V2H9v5.5l3 3 3-3zM7.5 9H2v6h5.5l3-3-3-3zM9 16.5V22h6v-5.5l-3-3-3 3zM16.5 9l-3 3 3 3H22V9h-5.5z"/>
</SvgIcon>
);
HardwareGamepad = pure(HardwareGamepad);
HardwareGamepad.displayName = 'HardwareGamepad';
HardwareGamepad.muiName = 'SvgIcon';
export default HardwareGamepad;
|
src/component.js | jxnblk/cxs | import _cxs from './index'
import PropTypes from 'prop-types'
import React from 'react'
const h = React.createElement
function cxs (C) {
return (...args) => {
const Comp = (props, context = {}) => {
const stylePropKeys = [
...Object.keys(Comp.propTypes || {}),
'css'
]
const styleProps = Object.assign({ theme: context.theme || {} }, props)
const next = {}
for (let key in props) {
if (stylePropKeys.includes(key)) continue
next[key] = props[key]
}
next.className = [
next.className,
...args.map(a => typeof a === 'function' ? a(styleProps) : a)
.filter(s => !!s)
.map(s => _cxs(s)),
_cxs(props.css || {})
].join(' ').trim()
return h(C, next)
}
Comp.contextTypes = {
theme: PropTypes.oneOfType([
PropTypes.object,
PropTypes.func
])
}
return Comp
}
}
cxs.css = _cxs.css
cxs.reset = _cxs.reset
export default cxs
|
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | bps-in/photo-share | 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'));
|
docs/site/src/demos/tabs/IconTabs.js | und3fined/material-ui | // @flow weak
import React, { Component } from 'react';
import Paper from 'material-ui/Paper';
import Tabs from 'material-ui/Tabs';
import Tab from 'material-ui/Tabs/Tab';
import PhoneIcon from 'material-ui/svg-icons/phone';
import FavoriteIcon from 'material-ui/svg-icons/favorite';
import PersonPinIcon from 'material-ui/svg-icons/person-pin';
export default class IconTabs extends Component {
state = {
index: 0,
};
handleChange = (event, index) => {
this.setState({ index });
};
render() {
return (
<Paper style={{ width: 500 }}>
<Tabs
index={this.state.index}
onChange={this.handleChange}
textColor="accent"
fullWidth
>
<Tab icon={<PhoneIcon />} />
<Tab icon={<FavoriteIcon />} />
<Tab icon={<PersonPinIcon />} />
</Tabs>
</Paper>
);
}
}
|
src/scripts/ui/components/pages/login/form.js | ziflex/react-app-starter | import React from 'react';
import cn from 'classnames';
import DataSourceMixin from '../../mixins/data-source-mixin';
import { signin as signinCss } from './form.css';
const USERNAME_PATH = ['data', 'username'];
const IS_DONE_PATH = ['data', 'authenticated'];
export default React.createClass({
propTypes: {
source: React.PropTypes.object,
actions: React.PropTypes.object
},
mixins: [
DataSourceMixin
],
getInitialState() {
return {
username: this.props.source.getIn(USERNAME_PATH),
password: ''
};
},
_isDone() {
return this.props.source.getIn(IS_DONE_PATH);
},
_onSubmit(e) {
e.preventDefault();
if (!this.isLoading()) {
this.props.actions.login(this.state.username, this.state.password);
}
},
_renderLoader() {
if (this.isLoading()) {
return 'Wait...';
}
return null;
},
_btnLabel() {
if (!this.isLoading()) {
return 'Login';
}
return 'Wait';
},
_handleChange(key, value) {
this.setState({
[key]: value
});
},
render() {
const attrs = {};
if (this.isLoading() || this._isDone()) {
attrs.disabled = true;
}
const className = cn({
container: true,
[signinCss]: true
});
return (
<div className={className}>
<form onSubmit={this._onSubmit}>
<div
className="form-group"
>
<label
htmlFor="inputUsername"
className="sr-only"
>
Username
</label>
<input
type="text"
id="inputUsername"
className="form-control"
placeholder="Username"
required=""
onChange={e => this._handleChange('username', e.target.value)}
{...attrs}
/>
</div>
<div
className="form-group"
>
<label
htmlFor="inputPassword"
className="sr-only"
>
Password
</label>
<input
type="password"
id="inputPassword"
className="form-control"
placeholder="Password"
required=""
onChange={e => this._handleChange('password', e.target.value)}
{...attrs}
/>
</div>
<button className="btn btn-lg btn-primary btn-block" type="submit" {...attrs}>
{this.disabled ? 'Wait...' : 'Login'}
</button>
</form>
</div>
);
}
});
|
docs/src/app/components/pages/components/List/ExampleSimple.js | rscnt/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;
|
packages/faceted-search/src/components/FacetedManager/FacetedManager.component.js | Talend/ui | import React from 'react';
import PropTypes from 'prop-types';
import { useTranslation } from 'react-i18next';
import { I18N_DOMAIN_FACETED_SEARCH } from '../../constants';
import { FacetedSearchProvider } from '../context/facetedSearch.context';
const FacetedManager = ({ children, id, inProgress, error }) => {
const { t } = useTranslation(I18N_DOMAIN_FACETED_SEARCH);
const contextValue = {
error,
id,
inProgress,
t,
};
return <FacetedSearchProvider value={contextValue}>{children}</FacetedSearchProvider>;
};
FacetedManager.propTypes = {
children: PropTypes.oneOfType([PropTypes.element, PropTypes.arrayOf(PropTypes.element)]),
id: PropTypes.string.isRequired,
inProgress: PropTypes.bool,
error: PropTypes.string,
};
// eslint-disable-next-line import/prefer-default-export
export { FacetedManager };
|
packages/xo-web/src/xo-app/jobs/edit/index.js | vatesfr/xo-web | import New from '../new'
import React from 'react'
export default props => <New id={props.routeParams.id} />
|
src/components/Blog/BlogAuthor/BlogAuthor/BlogAuthor.js | easingthemes/notamagic | import React from 'react';
/**
* React pure component.
*
* @author dfilipovic
* @namespace ReactApp
* @class BlogAuthor
* @extends ReactApp
*/
export const BlogAuthor = (props) => (
<div className="blog-post-author mb50 pt30 bt-solid-1">
<img
src={props.author.avatar}
className="img-circle"
alt={props.author.name}
/>
<span className="blog-post-author-name">
{props.author.name}
</span>
<a href={props.author.url}><i className="fa fa-twitter"></i></a>
<p>
{props.author.description}
</p>
</div>
);
BlogAuthor.propTypes = {
author: React.PropTypes.object
};
BlogAuthor.defaultProps = {
author: {
avatar: '',
name: '',
url: '',
description: ''
}
};
export default BlogAuthor;
|
examples/todomvc/index.js | bnwan/redux | import 'babel-core/polyfill';
import React from 'react';
import { Provider } from 'react-redux';
import App from './containers/App';
import configureStore from './store/configureStore';
import 'todomvc-app-css/index.css';
const store = configureStore();
React.render(
<Provider store={store}>
{() => <App />}
</Provider>,
document.getElementById('root')
);
|
library/src/pivotal-ui-react/expander/expander.js | sjolicoeur/pivotal-ui | import React from 'react';
import PropTypes from 'prop-types';
import {Collapsible} from 'pui-react-collapsible';
export class ExpanderTrigger extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {};
}
setTarget = target => this.setState({target})
toggleExpander = event => {
event.preventDefault();
if (this.state.target) {
this.state.target.toggle();
} else {
console.warn('No ExpanderContent provided to ExpanderTrigger.');
}
}
render() {
return React.cloneElement(this.props.children, {onClick: this.toggleExpander});
}
}
export class ExpanderContent extends React.Component {
static propTypes = {
expanded: PropTypes.bool
}
constructor(props, context) {
super(props, context);
this.state = {expanded: this.props.expanded};
}
componentWillReceiveProps(nextProps) {
if (nextProps.expanded !== this.props.expanded) {
this.setState({expanded: nextProps.expanded});
}
}
toggle = () => this.setState({expanded: !this.state.expanded})
render() {
const {expanded} = this.state;
return <Collapsible {...{...this.props, expanded}}/>;
}
}
|
index.android.js | ihor/ReactNativeCodeReuseExample | import React from 'react';
import { AppRegistry } from 'react-native';
import App from './app/components/App';
AppRegistry.registerComponent('ReactNativeCodeReuse', () => App);
|
src/elements/List/ListList.js | shengnian/shengnian-ui-react | import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import {
childrenUtils,
customPropTypes,
getElementType,
getUnhandledProps,
META,
useKeyOnly,
} from '../../lib'
/**
* A list can contain a sub list.
*/
function ListList(props) {
const { children, className, content } = props
const rest = getUnhandledProps(ListList, props)
const ElementType = getElementType(ListList, props)
const classes = cx(
useKeyOnly(ElementType !== 'ul' && ElementType !== 'ol', 'list'),
className,
)
return (
<ElementType {...rest} className={classes}>
{childrenUtils.isNil(children) ? content : children}
</ElementType>
)
}
ListList._meta = {
name: 'ListList',
parent: 'List',
type: META.TYPES.ELEMENT,
}
ListList.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
}
export default ListList
|
imports/ui/components/mes-can-fine.js | gagpmr/app-met | import React from 'react';
import ReactDOM from 'react-dom';
import { Loading } from './loading.js';
export const MesCanFine = React.createClass({
getInitialState() {
return null;
},
getFine() {
var seltext = this.refs.month_dd.selectedOptions[0].innerText;
for (var i = 0; i < this.props.fines.length; i++) {
var elementone = this.props.fines[i];
if (elementone.McMonth === seltext) {
this.refs.output_lbl.innerText = elementone.Mc;
this.setState({ fine: elementone.Mc });
this.setState({ month: seltext });
break;
}
}
},
propTypes: {
loading: React.PropTypes.bool,
fines: React.PropTypes.array,
months: React.PropTypes.array,
date: React.PropTypes.object,
latestmonth: React.PropTypes.string,
latestfine: React.PropTypes.number
},
render() {
if (this.props.loading) {
return <div className="middle">
<Loading/>
</div>
} else {
var options = [];
var fines = [];
var date = "";
var seltext = "";
if (this.props.date !== undefined) {
date = this.props.date.EffectiveDateStr;
}
if (this.props.months.length > 0) {
for (var index = 0; index < this.props.months.length; index++) {
var element = this.props.months[index];
options.push(
<option key={ element._id } value={ element.Value }>{ element.Value }</option>
);
}
}
if (this.state !== null) {
fines.push(
<label key={ 21 } ref="output_lbl">{ this.state.fine }</label>
);
seltext = this.state.month;
} else {
fines.push(
<label key={ 21 } ref="output_lbl">{ this.props.latestfine }</label>
);
seltext = this.props.latestmonth;
}
return (
<div className="col-md-4 col-md-offset-4">
<table className="table table-bordered table-condensed table-striped">
<thead>
<tr>
<th colSpan="3" className="text-center h4">
<strong>Mess Canteen Fine</strong>
</th>
</tr>
</thead>
<tbody>
<tr>
<th className="text-center mes-can-fine">
Effective Date
</th>
<td className="text-center">
{ date }
</td>
</tr>
<tr>
<th className="text-center mes-can-fine">
Bill Month
</th>
<td className="text-center">
<select autoFocus="autofocus" value={ seltext } onChange={ this.getFine } className="text-center" ref="month_dd">
{ options }
</select>
</td>
</tr>
<tr>
<th className="text-center mes-can-fine">
Fine
</th>
<td className="text-center">
{ fines }
</td>
</tr>
</tbody>
</table>
</div>
);
}
}
});
|
src/js/Containers/NavigationContainer.js | RoyalSix/myBiolaApp | import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TextInput,
ListView,
TouchableHighlight
} from 'react-native';
const timer = require('react-native-timer');
import { connect } from 'react-redux'
import ChapelContainer from './ChapelContainer';
import DiningContainer from './DiningContainer';
import EventsContainer from './EventsContainer';
import NewsContainer from './NewsContainer';
import HomeContainer from './HomeContainer';
import ScrollableTabView, { ScrollableTabBar, } from 'react-native-scrollable-tab-view';
import ChapelTab from '../Components/TabBar/ChapelTab';
import DiningTab from '../Components/TabBar/DiningTab';
import CampusTab from '../Components/TabBar/CampusTab';
import EventsTab from '../Components/TabBar/EventsTab';
import HomeTab from '../Components/TabBar/HomeTab';
import * as navigationActions from '../Actions/navigationActions'
import { home_icon } from 'assets';
class NavigationContainer extends Component {
constructor(props) {
super(props);
this.handleChangeTab = this.handleChangeTab.bind(this);
}
componentWillMount() {
this.props.setTime();
this.props.setDay();
timer.setInterval('clockTimer', () => {
this.props.setTime();
}, 50000)
}
renderTab(name, page, isTabActive, onPressHandler, onLayoutHandler) {
switch (name) {
case 'CHAPELS':
return <ChapelTab key={`${name}_${page}`} onPressHandler={onPressHandler} onLayoutHandler={onLayoutHandler} page={page} name={name} />;
case 'EVENTS':
return <EventsTab key={`${name}_${page}`} onPressHandler={onPressHandler} onLayoutHandler={onLayoutHandler} page={page} name={name} />;
case 'DINING':
return <DiningTab key={`${name}_${page}`} onPressHandler={onPressHandler} onLayoutHandler={onLayoutHandler} page={page} name={name} />;
case 'EVENTS':
return <CampusTab key={`${name}_${page}`} onPressHandler={onPressHandler} onLayoutHandler={onLayoutHandler} page={page} name={name} />;
case 'NEWS':
return <CampusTab key={`${name}_${page}`} onPressHandler={onPressHandler} onLayoutHandler={onLayoutHandler} page={page} name={name} />;
case 'HOME':
return <HomeTab key={`${name}_${page}`} onPressHandler={onPressHandler} onLayoutHandler={onLayoutHandler} page={page} name={name} />;
}
}
handleChangeTab(index) {
this.props.changeTab(index.i);
}
render() {
return (
<View style={{ flex: 1, backgroundColor: 'black', }}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', backgroundColor: 'rgba(0,0,0,0)' }}>
<Text style={{ color: 'grey', fontSize: 17, margin: 10, flex: 1 }}>{this.props.day}</Text>
<Text style={{ color: 'grey', fontSize: 17, margin: 10 }}>{this.props.time}</Text>
</View>
<ScrollableTabView tabBarPosition={'bottom'} renderTabBar={() => <ScrollableTabBar renderTab={this.renderTab} />}
onChangeTab={this.handleChangeTab}
tabBarBackgroundColor='black' initialPage={2} locked={false} style={{ flex: 1, marginBottom: -1, backgroundColor: 'black', zIndex: 1 }}
tabBarUnderlineStyle={{ backgroundColor: 'red' }}>
<ChapelContainer tabLabel="CHAPELS" {...this.props} />
<DiningContainer tabLabel="DINING" {...this.props} />
<HomeContainer tabLabel="HOME" {...this.props} />
<NewsContainer tabLabel="NEWS" {...this.props} />
<EventsContainer tabLabel="EVENTS" {...this.props} />
</ScrollableTabView>
</View>
)
}
}
const mapStateToProps = (state) => {
return { ...state.navigationReducer }
}
const mapDispatchToState = (dispatch, ownProps) => {
return {
changeTab: (index) => {
dispatch(navigationActions.changeTab(index));
},
setTime: () => {
dispatch(navigationActions.setTime());
},
setDay: () => {
dispatch(navigationActions.setDay());
}
}
}
export default connect(mapStateToProps, mapDispatchToState)(NavigationContainer) |
frontend/src/app/components/ExperimentCardList.js | mathjazz/testpilot | import React from 'react';
import ExperimentRowCard from './ExperimentRowCard';
import Loading from './Loading';
import LayoutWrapper from './LayoutWrapper';
export default class ExperimentCardList extends React.Component {
getExperiments() {
if (!this.props.except) {
return this.props.experiments;
}
return this.props.experiments.filter(experiment => (
experiment.slug !== this.props.except
));
}
renderLoading() {
return (
<div className="card-list experiments">
<Loading />
</div>
);
}
renderExperiments() {
const { isExperimentEnabled } = this.props;
return (
<LayoutWrapper flexModifier="card-list">
{this.getExperiments().map((experiment, key) => (
<ExperimentRowCard {...this.props}
experiment={experiment}
enabled={isExperimentEnabled(experiment)}
key={key} />
))}
</LayoutWrapper>
);
}
render() {
if (this.props.experiments.length === 0) {
return this.renderLoading();
}
return this.renderExperiments();
}
}
|
Paths/React/05.Building Scalable React Apps/1-react-boilerplate-building-scalable-apps-m1-exercise-files/Before/app/components/List/index.js | phiratio/Pluralsight-materials | import React from 'react';
import styles from './styles.css';
function List(props) {
const ComponentToRender = props.component;
let content = (<div></div>);
// If we have items, render them
if (props.items) {
content = props.items.map((item, index) => (
<ComponentToRender key={`item-${index}`} item={item} />
));
} else {
// Otherwise render a single component
content = (<ComponentToRender />);
}
return (
<div className={styles.listWrapper}>
<ul className={styles.list}>
{content}
</ul>
</div>
);
}
List.propTypes = {
component: React.PropTypes.func.isRequired,
items: React.PropTypes.array,
};
export default List;
|
packages/p2p-chat/src/layouts/DevTools.js | dgeibi/p2p-chat | import React from 'react'
import { createDevTools } from 'redux-devtools'
import LogMonitor from 'redux-devtools-log-monitor'
import DockMonitor from 'redux-devtools-dock-monitor'
export default createDevTools(
<DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q">
<LogMonitor theme="tomorrow" />
</DockMonitor>
)
|
examples/ssr-caching/pages/blog.js | nahue/next.js | 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>
}
}
|
app/jsx/grading/SearchGradingPeriodsField.js | djbender/canvas-lms | /*
* Copyright (C) 2016 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import PropTypes from 'prop-types'
import _ from 'underscore'
import I18n from 'i18n!SearchGradingPeriodsField'
export default class SearchGradingPeriodsField extends React.Component {
static propTypes = {
changeSearchText: PropTypes.func.isRequired
}
onChange = event => {
const trimmedText = event.target.value.trim()
this.search(trimmedText)
}
search = _.debounce(function(trimmedText) {
this.props.changeSearchText(trimmedText)
}, 200)
render() {
return (
<div className="GradingPeriodSearchField ic-Form-control">
<input
type="text"
ref="input"
className="ic-Input"
placeholder={I18n.t('Search grading periods...')}
onChange={this.onChange}
/>
</div>
)
}
}
|
src/js/components/ui/forms/HorizontalTextarea.js | knowncitizen/tripleo-ui | /**
* Copyright 2017 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import ClassNames from 'classnames';
import { withFormsy } from 'formsy-react';
import PropTypes from 'prop-types';
import React from 'react';
import InputDescription from './InputDescription';
import InputErrorMessage from './InputErrorMessage';
class HorizontalTextarea extends React.Component {
changeValue(event) {
this.props.setValue(event.target.value);
}
render() {
let divClasses = ClassNames({
'form-group': true,
'has-error': this.props.showError(),
// 'has-success': this.props.isValid(),
required: this.props.isRequired()
});
return (
<div className={divClasses}>
<label
htmlFor={this.props.name}
className={`${this.props.labelColumnClasses} control-label`}
>
{this.props.title}
</label>
<div className={this.props.inputColumnClasses}>
<textarea
type={this.props.type}
name={this.props.name}
ref={this.props.name}
id={this.props.name}
rows={this.props.rows}
className="form-control"
onChange={this.changeValue.bind(this)}
value={this.props.getValue() || ''}
placeholder={this.props.placeholder}
disabled={this.props.disabled}
/>
<InputErrorMessage getErrorMessage={this.props.getErrorMessage} />
<InputDescription description={this.props.description} />
</div>
</div>
);
}
}
HorizontalTextarea.propTypes = {
description: PropTypes.string,
disabled: PropTypes.bool,
getErrorMessage: PropTypes.func,
getValue: PropTypes.func,
inputColumnClasses: PropTypes.string.isRequired,
isRequired: PropTypes.func,
isValid: PropTypes.func,
labelColumnClasses: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
placeholder: PropTypes.string,
rows: PropTypes.number,
setValue: PropTypes.func,
showError: PropTypes.func,
title: PropTypes.string.isRequired,
type: PropTypes.string
};
HorizontalTextarea.defaultProps = {
inputColumnClasses: 'col-sm-10',
labelColumnClasses: 'col-sm-2',
rows: 3,
type: 'text'
};
export default withFormsy(HorizontalTextarea);
|
packages/bonde-admin/src/community/components/dns/domain-step/index.js | ourcities/rebu-client | import PropTypes from 'prop-types'
import React from 'react'
if (require('exenv').canUseDOM) require('./styles.scss')
const DomainStep = ({ children, title, step, isValid }) => {
const icon = isValid ? (
<span className='circle valid'><i className='fa fa-check' /></span>
) : (
<span className='circle bg-pagenta'><p>{step}</p></span>
)
return (
<div className={`domain--step step-${step}`}>
<div className='header--step'>
{icon}<h2>{title}</h2>
</div>
<div className='content--step'>
{children}
</div>
</div>
)
}
DomainStep.propTypes = {
title: PropTypes.string,
// Injected by <Steps />
step: PropTypes.number,
isValid: PropTypes.bool
}
export default DomainStep
|
rest-ui-scripts/template/src/resources/Comment/crud/list/Grid.js | RestUI/create-rest-ui-app | import React from 'react';
import { DateField, EditButton, ReferenceField, TextField } from 'rest-ui/lib/mui';
import { Card, CardActions, CardHeader, CardText } from 'material-ui/Card';
import PersonIcon from 'material-ui/svg-icons/social/person';
import Avatar from 'material-ui/Avatar';
import { translate } from 'rest-ui';
const cardStyle = {
width: 300,
minHeight: 300,
margin: '0.5em',
display: 'inline-block',
verticalAlign: 'top',
};
const Grid = translate(({ ids, data, basePath, translate }) => (
<div style={{ margin: '1em' }}>
{ids.map(id =>
<Card key={id} style={cardStyle}>
<CardHeader
title={<TextField record={data[id]} source="author.name" />}
subtitle={<DateField record={data[id]} source="created_at" />}
avatar={<Avatar icon={<PersonIcon />} />}
/>
<CardText>
<TextField record={data[id]} source="body" />
</CardText>
<CardText>
{translate('comment.list.about')}
<ReferenceField resource="comments" record={data[id]} source="post_id" reference="posts" basePath={basePath}>
<TextField source="title" />
</ReferenceField>
</CardText>
<CardActions style={{ textAlign: 'right' }}>
<EditButton resource="posts" basePath={basePath} record={data[id]} />
</CardActions>
</Card>,
)}
</div>
));
Grid.defaultProps = {
data: {},
ids: [],
};
export default Grid; |
docs/src/components/CodeSnippet/CodeSnippet.js | fpoumian/react-devicon | import React from 'react'
import PropTypes from 'prop-types'
import Highlight from 'react-highlight'
import 'highlight.js/styles/dracula.css'
const CodeSnippet = ({ children, className }) => {
return <Highlight className={className}> {children} </Highlight>
}
CodeSnippet.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
}
export default CodeSnippet
|
app/javascript/mastodon/components/avatar.js | koba-lab/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { autoPlayGif } from '../initial_state';
export default class Avatar extends React.PureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
size: PropTypes.number.isRequired,
style: PropTypes.object,
inline: PropTypes.bool,
animate: PropTypes.bool,
};
static defaultProps = {
animate: autoPlayGif,
size: 20,
inline: false,
};
state = {
hovering: false,
};
handleMouseEnter = () => {
if (this.props.animate) return;
this.setState({ hovering: true });
}
handleMouseLeave = () => {
if (this.props.animate) return;
this.setState({ hovering: false });
}
render () {
const { account, size, animate, inline } = this.props;
const { hovering } = this.state;
const src = account.get('avatar');
const staticSrc = account.get('avatar_static');
let className = 'account__avatar';
if (inline) {
className = className + ' account__avatar-inline';
}
const style = {
...this.props.style,
width: `${size}px`,
height: `${size}px`,
backgroundSize: `${size}px ${size}px`,
};
if (hovering || animate) {
style.backgroundImage = `url(${src})`;
} else {
style.backgroundImage = `url(${staticSrc})`;
}
return (
<div
className={className}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
style={style}
/>
);
}
}
|
app/javascript/mastodon/features/ui/components/bundle_column_error.js | Craftodon/Craftodon | import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl } from 'react-intl';
import Column from './column';
import ColumnHeader from './column_header';
import ColumnBackButtonSlim from '../../../components/column_back_button_slim';
import IconButton from '../../../components/icon_button';
const messages = defineMessages({
title: { id: 'bundle_column_error.title', defaultMessage: 'Network error' },
body: { id: 'bundle_column_error.body', defaultMessage: 'Something went wrong while loading this component.' },
retry: { id: 'bundle_column_error.retry', defaultMessage: 'Try again' },
});
class BundleColumnError extends React.Component {
static propTypes = {
onRetry: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
}
handleRetry = () => {
this.props.onRetry();
}
render () {
const { intl: { formatMessage } } = this.props;
return (
<Column>
<ColumnHeader icon='exclamation-circle' type={formatMessage(messages.title)} />
<ColumnBackButtonSlim />
<div className='error-column'>
<IconButton title={formatMessage(messages.retry)} icon='refresh' onClick={this.handleRetry} size={64} />
{formatMessage(messages.body)}
</div>
</Column>
);
}
}
export default injectIntl(BundleColumnError);
|
packages/ringcentral-widgets/components/Eula/index.js | u9520107/ringcentral-js-widget | import React from 'react';
import PropTypes from 'prop-types';
import i18n from './i18n';
function Eula(props) {
let labelId = 'eula';
let link;
const isFr = props.currentLocale.substr(0, 2).toLowerCase() === 'fr';
switch (props.brandId) {
case '3420': // att
link = 'https://asecare.att.com/tutorials/ringcentral-officehand-from-att-end-user-licensing-agreement/?product=ringcentral-officehand-from-att-end-user-licensing-agreement';
break;
case '7710': // bt
link = 'http://www.productsandservices.bt.com/products/static/terms/terms-of-use.html';
break;
case '7310': // telus
labelId = 'serviceTerms';
link = isFr ?
'http://business.telus.com/fr/campaigns/business-connect-service-terms?INTCMP=VAN_businessconnect_fr_serviceterms' :
'http://business.telus.com/en/support/global/legal/business-connect-service-terms?INTCMP=VAN_businessconnect_serviceterms';
break;
default:
link = 'https://www.ringcentral.com/legal/eulatos.html';
break;
}
return (
<a
className={props.className}
href={link}
rel="noopener noreferrer"
target="_blank"
>
{i18n.getString(labelId)}
</a>
);
}
Eula.propTypes = {
brandId: PropTypes.string.isRequired,
currentLocale: PropTypes.string.isRequired,
className: PropTypes.string,
};
export default Eula;
|
imports/ui/admin/components/experts.js | dououFullstack/atomic | import React from 'react';
import { browserHistory } from 'react-router';
import Loading from '/imports/ui/loading';
import Table from './expert_table';
class _Component extends React.Component {
constructor(props) {
super(props);
this.state = {type: this.props.type};
this.handleTab.bind(this);
}
handleTab(type) {
this.setState({type: type});
}
render() {
const data = this.props.data;
const aClass = this.state.type === 'a' ? 'active item' : 'item';
const bClass = this.state.type === 'b' ? 'active item' : 'item';
const cClass = this.state.type === 'c' ? 'active item' : 'item';
const a1Class = this.state.type === 'a' ? 'ui bottom attached active tab segment' : 'ui bottom attached tab segment';
const b1Class = this.state.type === 'b' ? 'ui bottom attached active tab segment' : 'ui bottom attached tab segment';
const c1Class = this.state.type === 'c' ? 'ui bottom attached active tab segment' : 'ui bottom attached tab segment';
return (
<div>
<h1>专家列表</h1>
{this.props.ready ?
<div>
<div className="ui top attached tabular menu">
<a onClick={() => this.handleTab('a')} className={aClass}>学术委员</a>
<a onClick={() => this.handleTab('b')} className={bClass}>编辑委员</a>
<a onClick={() => this.handleTab('c')} className={cClass}>审稿专家</a>
</div>
<div className={a1Class}> <Table data={this.props.dataA} type="a"/> </div>
<div className={b1Class}> <Table data={this.props.dataB} type="b"/> </div>
<div className={c1Class}> <Table data={this.props.dataC} type="c"/> </div>
</div>
:
<Loading/>
}
</div>
);
}
}
export default _Component;
|
src/icons/SocialYen.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class SocialYen extends React.Component {
render() {
if(this.props.bare) {
return <g>
<path d="M448,32h-80L256,253.128L144,32H64l112.368,208H128v48h73.564L216,319v17h-88v48h88v96h80v-96h88v-48h-88v-17l14.891-31H384
v-48h-48.289L448,32z"></path>
</g>;
} return <IconBase>
<path d="M448,32h-80L256,253.128L144,32H64l112.368,208H128v48h73.564L216,319v17h-88v48h88v96h80v-96h88v-48h-88v-17l14.891-31H384
v-48h-48.289L448,32z"></path>
</IconBase>;
}
};SocialYen.defaultProps = {bare: false} |
src/js/components/icons/base/Grid.js | linde12/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-grid`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'grid');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M8,1 L8,23 M16,1 L16,23 M1,8 L23,8 M1,16 L23,16 M1,1 L23,1 L23,23 L1,23 L1,1 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Grid';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
client/src/templates/select-field.js | brandiqa/open-lims | import React from 'react';
import { observer } from 'mobx-react';
import { Form } from 'semantic-ui-react';
import classnames from 'classnames';
export default observer(({field}) => (
<Form.Field className={classnames({error:field.error})}>
<label htmlFor={field.id}>
{field.label} {field.rules.indexOf('required') !== -1 ? <span className="red">*</span> : ''}
</label>
<select {...field.bind()}>
<option value="">{field.placeholder}</option>
{field.options.map(option => (<option key={option.toLowerCase()} value={option.toLowerCase()}>{option}</option>) )}
</select>
<span className="error">{field.error}</span>
</Form.Field>
));
|
examples/relay-treasurehunt/js/app.js | gabelevi/relay | /**
* This file provided by Facebook is for non-commercial testing and evaluation
* purposes only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import App from './components/App';
import AppHomeRoute from './routes/AppHomeRoute';
import React from 'react';
import ReactDOM from 'react-dom';
import Relay from 'react-relay';
ReactDOM.render(
<Relay.RootContainer
Component={App}
route={new AppHomeRoute()}
/>,
document.getElementById('root')
);
|
app/javascript/mastodon/features/compose/components/character_counter.js | robotstart/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { length } from 'stringz';
class CharacterCounter extends React.PureComponent {
checkRemainingText (diff) {
if (diff < 0) {
return <span className='character-counter character-counter--over'>{diff}</span>;
}
return <span className='character-counter'>{diff}</span>;
}
render () {
const diff = this.props.max - length(this.props.text);
return this.checkRemainingText(diff);
}
}
CharacterCounter.propTypes = {
text: PropTypes.string.isRequired,
max: PropTypes.number.isRequired
}
export default CharacterCounter;
|
blueprints/view/files/__root__/views/__name__View/__name__View.js | murrayjbrown/react-redux-rxjs-stampit-babylon-universal | import React from 'react'
type Props = {
};
export class <%= pascalEntityName %> extends React.Component {
props: Props;
render () {
return (
<div></div>
)
}
}
export default <%= pascalEntityName %>
|
app/javascript/mastodon/components/domain.js | glitch-soc/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import IconButton from './icon_button';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unblock domain {domain}' },
});
export default @injectIntl
class Account extends ImmutablePureComponent {
static propTypes = {
domain: PropTypes.string,
onUnblockDomain: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleDomainUnblock = () => {
this.props.onUnblockDomain(this.props.domain);
}
render () {
const { domain, intl } = this.props;
return (
<div className='domain'>
<div className='domain__wrapper'>
<span className='domain__domain-name'>
<strong>{domain}</strong>
</span>
<div className='domain__buttons'>
<IconButton active icon='unlock' title={intl.formatMessage(messages.unblockDomain, { domain })} onClick={this.handleDomainUnblock} />
</div>
</div>
</div>
);
}
}
|
src/website/app/BaselineGrid.js | mineral-ui/mineral-ui | /* @flow */
import styled from '@emotion/styled';
import React from 'react';
import { withRouter } from 'react-router';
type Props = {
fontSize?: number, // px
lineHeight?: number, // unitless,
location?: any,
offset?: number // px
};
const Root = styled('div')(({ fontSize, lineHeight, offset, theme }) => {
const rowHeight = fontSize * lineHeight;
return {
backgroundImage: `repeating-linear-gradient(
0deg,
rgba(0,255,255,0.07),
rgba(0,255,255,0.07) ${rowHeight / 2}px,
rgba(0,255,255,0.14) ${rowHeight / 2}px,
rgba(0,255,255,0.14) ${rowHeight}px,
rgba(255,0,255,0.07) ${rowHeight}px,
rgba(255,0,255,0.07) ${rowHeight * 1.5}px,
rgba(255,0,255,0.14) ${rowHeight * 1.5}px,
rgba(255,0,255,0.14) ${rowHeight * 2}px
)`,
backgroundPosition: `0 ${offset}px`,
bottom: 0,
left: 0,
pointerEvents: 'none',
position: 'fixed',
right: 0,
top: 0,
zIndex: theme.zIndex_1600
};
});
function BaselineGrid({
fontSize = 16,
lineHeight = 1.5,
location,
offset = -8
}: Props) {
const rootProps = {
fontSize,
lineHeight,
offset
};
return location && location.search === '?grid' ? (
<Root {...rootProps} />
) : null;
}
export default withRouter(BaselineGrid);
|
src/collections/Form/FormSelect.js | Semantic-Org/Semantic-UI-React | import PropTypes from 'prop-types'
import React from 'react'
import { getElementType, getUnhandledProps } from '../../lib'
import Select from '../../addons/Select'
import Dropdown from '../../modules/Dropdown'
import FormField from './FormField'
/**
* Sugar for <Form.Field control={Select} />.
* @see Form
* @see Select
*/
function FormSelect(props) {
const { control, options } = props
const rest = getUnhandledProps(FormSelect, props)
const ElementType = getElementType(FormSelect, props)
return <ElementType {...rest} control={control} options={options} />
}
FormSelect.propTypes = {
/** An element type to render as (string or function). */
as: PropTypes.elementType,
/** A FormField control prop. */
control: FormField.propTypes.control,
/** Array of Dropdown.Item props e.g. `{ text: '', value: '' }` */
options: PropTypes.arrayOf(PropTypes.shape(Dropdown.Item.propTypes)).isRequired,
}
FormSelect.defaultProps = {
as: FormField,
control: Select,
}
export default FormSelect
|
src/components/VmDetails/cards/DetailsCard/CloudInit/SysprepForm.js | mareklibra/userportal | import React from 'react'
import PropTypes from 'prop-types'
import {
FormControl,
ControlLabel,
FormGroup,
} from 'patternfly-react'
import { msg } from '_/intl'
import SelectBox from '../../../../SelectBox'
import timezones from '_/components/utils/timezones.json'
const SysprepForm = ({ idPrefix, vm, onChange }) => {
const cloudInitHostName = vm.getIn(['cloudInit', 'hostName'])
const cloudInitPassword = vm.getIn(['cloudInit', 'password'])
const cloudInitTimezone = vm.getIn(['cloudInit', 'timezone']) || timezones[0].id
const cloudInitCustomScript = vm.getIn(['cloudInit', 'customScript'])
return (
<React.Fragment>
<FormGroup controlId={`${idPrefix}-cloud-init-hostname`}>
<ControlLabel>
{msg.hostName()}
</ControlLabel>
<FormControl
type='text'
value={cloudInitHostName}
onChange={e => onChange('cloudInitHostName', e.target.value)}
/>
</FormGroup>
<FormGroup controlId={`${idPrefix}-cloud-init-hostname`}>
<ControlLabel>
{msg.password()}
</ControlLabel>
<FormControl
type='password'
value={cloudInitPassword}
onChange={e => onChange('cloudInitPassword', e.target.value)}
/>
</FormGroup>
<FormGroup controlId={`${idPrefix}-cloud-init-timezone`}>
<ControlLabel>
{msg.timezone()}
</ControlLabel>
<SelectBox
id={`${idPrefix}-sysprep-timezone-select`}
items={timezones}
selected={cloudInitTimezone}
onChange={(selectedId) => onChange('cloudInitTimezone', selectedId)}
/>
</FormGroup>
<FormGroup controlId={`${idPrefix}-sysprep-custom-script`}>
<ControlLabel>
{msg.customScript()}
</ControlLabel>
<FormControl
componentClass='textarea'
value={cloudInitCustomScript}
onChange={e => onChange('cloudInitCustomScript', e.target.value)}
/>
</FormGroup>
</React.Fragment>
)
}
SysprepForm.propTypes = {
idPrefix: PropTypes.string.isRequired,
vm: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired,
}
export default SysprepForm
|
react/features/base/toolbox/components/web/ToolboxButtonWithIconPopup.js | jitsi/jitsi-meet | // @flow
import React from 'react';
import { Icon } from '../../../icons';
import { Popover } from '../../../popover';
type Props = {
/**
* Whether the element popup is expanded.
*/
ariaExpanded?: boolean,
/**
* The id of the element this button icon controls.
*/
ariaControls?: string,
/**
* Whether the element has a popup.
*/
ariaHasPopup?: boolean,
/**
* Aria label for the Icon.
*/
ariaLabel?: string,
/**
* The decorated component (ToolboxButton).
*/
children: React$Node,
/**
* Icon of the button.
*/
icon: Function,
/**
* Flag used for disabling the small icon.
*/
iconDisabled: boolean,
/**
* The ID of the icon button.
*/
iconId: string,
/**
* Popover close callback.
*/
onPopoverClose: Function,
/**
* Popover open callback.
*/
onPopoverOpen: Function,
/**
* The content that will be displayed inside the popover.
*/
popoverContent: React$Node,
/**
* Additional styles.
*/
styles?: Object,
/**
* Whether or not the popover is visible.
*/
visible: boolean
};
declare var APP: Object;
/**
* Displays the `ToolboxButtonWithIcon` component.
*
* @param {Object} props - Component's props.
* @returns {ReactElement}
*/
export default function ToolboxButtonWithIconPopup(props: Props) {
const {
ariaControls,
ariaExpanded,
ariaHasPopup,
ariaLabel,
children,
icon,
iconDisabled,
iconId,
onPopoverClose,
onPopoverOpen,
popoverContent,
styles,
visible
} = props;
const iconProps = {};
if (iconDisabled) {
iconProps.className
= 'settings-button-small-icon settings-button-small-icon--disabled';
} else {
iconProps.className = 'settings-button-small-icon';
iconProps.role = 'button';
iconProps.tabIndex = 0;
iconProps.ariaControls = ariaControls;
iconProps.ariaExpanded = ariaExpanded;
iconProps.containerId = iconId;
}
return (
<div
className = 'settings-button-container'
styles = { styles }>
{children}
<div className = 'settings-button-small-icon-container'>
<Popover
content = { popoverContent }
onPopoverClose = { onPopoverClose }
onPopoverOpen = { onPopoverOpen }
position = 'top'
visible = { visible }>
<Icon
{ ...iconProps }
ariaHasPopup = { ariaHasPopup }
ariaLabel = { ariaLabel }
size = { 9 }
src = { icon } />
</Popover>
</div>
</div>
);
}
|
src/screens/NewWorks/UserNewWorks.js | alphasp/pxview | import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
import NewIllusts from './NewIllusts';
import NewMangas from './NewMangas';
import NewNovels from './NewNovels';
import { connectLocalization } from '../../components/Localization';
import Pills from '../../components/Pills';
import { globalStyles } from '../../styles';
const styles = StyleSheet.create({
pills: {
padding: 10,
},
});
class UserNewWorks extends Component {
constructor(props) {
super(props);
this.state = {
index: 0,
};
}
handleOnPressPill = (index) => {
this.setState({ index });
};
renderHeader = () => {
const { i18n } = this.props;
const { index } = this.state;
return (
<Pills
items={[
{
title: i18n.illust,
},
{
title: i18n.manga,
},
{
title: i18n.novel,
},
]}
onPressItem={this.handleOnPressPill}
selectedIndex={index}
style={styles.pills}
/>
);
};
renderContent = () => {
const { active } = this.props;
const { index } = this.state;
switch (index) {
case 0:
return <NewIllusts renderHeader={this.renderHeader} active={active} />;
case 1:
return <NewMangas renderHeader={this.renderHeader} active={active} />;
case 2:
return <NewNovels renderHeader={this.renderHeader} active={active} />;
default:
return null;
}
};
render() {
return <View style={globalStyles.container}>{this.renderContent()}</View>;
}
}
export default connectLocalization(UserNewWorks);
|
tests/api-react/user/1-User.js | keystonejs/keystone-test-project | import Domify from 'react-domify';
import React from 'react';
import api from '../../../client/lib/api';
import styles from '../../../client/lib/styles';
const Test = React.createClass({
displayName: 'Create User',
getInitialState () {
return {
action: 'Start Test',
data: {
name: '',
email: '',
password: '',
},
};
},
componentDidMount () {
this.props.ready();
},
runTest () {
api.post('/keystone/api/users/create', {
json: this.state.data,
}, (err, res, body) => {
this.props.result('Received response:', body);
this.props.assert('status code is 400').truthy(() => res.statusCode === 400);
this.props.assert('error is "validation errors"').truthy(() => body.error === 'validation errors');
if (!this.state.data.password) {
this.props.assert('name is required').truthy(() => body.detail.name.type === 'required');
this.props.assert('email is required').truthy(() => body.detail.email.type === 'required');
this.props.assert('password is required').truthy(() => body.detail.password.type === 'required');
this.setState({
data: {
'name.full': 'first last',
'email': 'not an email',
'password': 'abcd1234',
'password_confirm': 'abcd',
},
});
this.props.ready();
} else {
this.props.assert('name passed validation').truthy(() => !body.detail.name);
this.props.assert('email is required').truthy(() => body.detail.email.type === 'invalid');
this.props.assert('passwords don\'t match').truthy(() => body.detail.password.type === 'invalid');
this.props.complete();
}
});
},
render () {
return (
<div>
<Domify style={styles.data} value={this.state.data} />
</div>
);
},
});
module.exports = Test;
|
src/svg-icons/image/leak-add.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageLeakAdd = (props) => (
<SvgIcon {...props}>
<path d="M6 3H3v3c1.66 0 3-1.34 3-3zm8 0h-2c0 4.97-4.03 9-9 9v2c6.08 0 11-4.93 11-11zm-4 0H8c0 2.76-2.24 5-5 5v2c3.87 0 7-3.13 7-7zm0 18h2c0-4.97 4.03-9 9-9v-2c-6.07 0-11 4.93-11 11zm8 0h3v-3c-1.66 0-3 1.34-3 3zm-4 0h2c0-2.76 2.24-5 5-5v-2c-3.87 0-7 3.13-7 7z"/>
</SvgIcon>
);
ImageLeakAdd = pure(ImageLeakAdd);
ImageLeakAdd.displayName = 'ImageLeakAdd';
ImageLeakAdd.muiName = 'SvgIcon';
export default ImageLeakAdd;
|
jqwidgets/jqwidgets-react/react_jqxdraw.js | UCF/IKM-APIM | /*
jQWidgets v5.6.0 (2018-Feb)
Copyright (c) 2011-2017 jQWidgets.
License: https://jqwidgets.com/license/
*/
import React from 'react';
const JQXLite = window.JQXLite;
export const jqx = window.jqx;
export default class JqxDraw extends React.Component {
componentDidMount() {
let options = this.manageAttributes();
this.createComponent(options);
};
manageAttributes() {
let properties = ['renderEngine'];
let options = {};
for(let item in this.props) {
if(item === 'settings') {
for(let itemTwo in this.props[item]) {
options[itemTwo] = this.props[item][itemTwo];
}
} else {
if(properties.indexOf(item) !== -1) {
options[item] = this.props[item];
}
}
}
return options;
};
createComponent(options) {
if(!this.style) {
for (let style in this.props.style) {
JQXLite(this.componentSelector).css(style, this.props.style[style]);
}
}
if(this.props.className !== undefined) {
let classes = this.props.className.split(' ');
for (let i = 0; i < classes.length; i++ ) {
JQXLite(this.componentSelector).addClass(classes[i]);
}
}
if(!this.template) {
JQXLite(this.componentSelector).html(this.props.template);
}
JQXLite(this.componentSelector).jqxDraw(options);
};
setOptions(options) {
JQXLite(this.componentSelector).jqxDraw('setOptions', options);
};
getOptions() {
if(arguments.length === 0) {
throw Error('At least one argument expected in getOptions()!');
}
let resultToReturn = {};
for(let i = 0; i < arguments.length; i++) {
resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxDraw(arguments[i]);
}
return resultToReturn;
};
on(name,callbackFn) {
JQXLite(this.componentSelector).on(name,callbackFn);
};
off(name) {
JQXLite(this.componentSelector).off(name);
};
renderEngine(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDraw('renderEngine', arg)
} else {
return JQXLite(this.componentSelector).jqxDraw('renderEngine');
}
};
attr(element, attributes) {
JQXLite(this.componentSelector).jqxDraw('attr', element, attributes);
};
circle(cx, cy, r, attributes) {
return JQXLite(this.componentSelector).jqxDraw('circle', cx, cy, r, attributes);
};
clear() {
JQXLite(this.componentSelector).jqxDraw('clear');
};
getAttr(element, attributes) {
return JQXLite(this.componentSelector).jqxDraw('getAttr', element, attributes);
};
getSize() {
return JQXLite(this.componentSelector).jqxDraw('getSize');
};
line(x1, y1, x2, y2, attributes) {
return JQXLite(this.componentSelector).jqxDraw('line', x1, y1, x2, y2, attributes);
};
measureText(text, angle, attributes) {
return JQXLite(this.componentSelector).jqxDraw('measureText', text, angle, attributes);
};
on(element, event, func) {
JQXLite(this.componentSelector).jqxDraw('on', element, event, func);
};
off(element, event, func) {
JQXLite(this.componentSelector).jqxDraw('off', element, event, func);
};
path(path, attributes) {
return JQXLite(this.componentSelector).jqxDraw('path', path, attributes);
};
pieslice(cx, xy, innerRadius, outerRadius, fromAngle, endAngle, centerOffset, attributes) {
return JQXLite(this.componentSelector).jqxDraw('pieslice', cx, xy, innerRadius, outerRadius, fromAngle, endAngle, centerOffset, attributes);
};
refresh() {
JQXLite(this.componentSelector).jqxDraw('refresh');
};
rect(x, y, width, height, attributes) {
return JQXLite(this.componentSelector).jqxDraw('rect', x, y, width, height, attributes);
};
saveAsJPEG(image, url) {
JQXLite(this.componentSelector).jqxDraw('saveAsJPEG', image, url);
};
saveAsPNG(image, url) {
JQXLite(this.componentSelector).jqxDraw('saveAsPNG', image, url);
};
text(text, x, y, width, height, angle, attributes, clip, halign, valign, rotateAround) {
return JQXLite(this.componentSelector).jqxDraw('text', text, x, y, width, height, angle, attributes, clip, halign, valign, rotateAround);
};
render() {
let id = 'jqxDraw' + JQXLite.generateID();
this.componentSelector = '#' + id;
return (
<div id={id}>{this.props.value}{this.props.children}</div>
)
};
};
|
admin/client/App/screens/Item/components/EditFormHeader.js | Pop-Code/keystone | import React from 'react';
import { findDOMNode } from 'react-dom';
import { connect } from 'react-redux';
import Toolbar from './Toolbar';
import ToolbarSection from './Toolbar/ToolbarSection';
import EditFormHeaderSearch from './EditFormHeaderSearch';
import { Link } from 'react-router';
import Drilldown from './Drilldown';
import { GlyphButton, ResponsiveText } from '../../../elemental';
export const EditFormHeader = React.createClass({
displayName: 'EditFormHeader',
propTypes: {
data: React.PropTypes.object,
list: React.PropTypes.object,
toggleCreate: React.PropTypes.func,
},
getInitialState () {
return {
searchString: '',
};
},
toggleCreate (visible) {
this.props.toggleCreate(visible);
},
searchStringChanged (event) {
this.setState({
searchString: event.target.value,
});
},
handleEscapeKey (event) {
const escapeKeyCode = 27;
if (event.which === escapeKeyCode) {
findDOMNode(this.refs.searchField).blur();
}
},
renderDrilldown () {
return (
<ToolbarSection left>
{this.renderDrilldownItems()}
{this.renderSearch()}
</ToolbarSection>
);
},
renderDrilldownItems () {
const { data, list } = this.props;
const items = data.drilldown ? data.drilldown.items : [];
let backPath = `${Keystone.adminPath}/${list.path}`;
const backStyles = { paddingLeft: 0, paddingRight: 0 };
// Link to the list page the user came from
if (this.props.listActivePage && this.props.listActivePage > 1) {
backPath = `${backPath}?page=${this.props.listActivePage}`;
}
// return a single back button when no drilldown exists
if (!items.length) {
return (
<GlyphButton
component={Link}
data-e2e-editform-header-back
glyph="chevron-left"
position="left"
style={backStyles}
to={backPath}
variant="link"
>
{list.plural}
</GlyphButton>
);
}
// prepare the drilldown elements
const drilldown = [];
items.forEach((item, idx) => {
// FIXME @jedwatson
// we used to support relationships of type MANY where items were
// represented as siblings inside a single list item; this got a
// bit messy...
item.items.forEach(link => {
drilldown.push({
href: link.href,
label: link.label,
title: item.list.singular,
});
});
});
// add the current list to the drilldown
drilldown.push({
href: backPath,
label: list.plural,
});
return (
<Drilldown items={drilldown} />
);
},
renderSearch () {
var list = this.props.list;
return (
<form action={`${Keystone.adminPath}/${list.path}`} className="EditForm__header__search">
<EditFormHeaderSearch
value={this.state.searchString}
onChange={this.searchStringChanged}
onKeyUp={this.handleEscapeKey}
/>
{/* <GlyphField glyphColor="#999" glyph="search">
<FormInput
ref="searchField"
type="search"
name="search"
value={this.state.searchString}
onChange={this.searchStringChanged}
onKeyUp={this.handleEscapeKey}
placeholder="Search"
style={{ paddingLeft: '2.3em' }}
/>
</GlyphField> */}
</form>
);
},
renderInfo () {
return (
<ToolbarSection right>
{this.renderCreateButton()}
</ToolbarSection>
);
},
renderCreateButton () {
const { nocreate, autocreate, singular } = this.props.list;
if (nocreate) return null;
let props = {};
if (autocreate) {
props.href = '?new' + Keystone.csrf.query;
} else {
props.onClick = () => { this.toggleCreate(true); };
}
return (
<GlyphButton data-e2e-item-create-button="true" color="success" glyph="plus" position="left" {...props}>
<ResponsiveText hiddenXS={`New ${singular}`} visibleXS="Create" />
</GlyphButton>
);
},
render () {
return (
<Toolbar>
{this.renderDrilldown()}
{this.renderInfo()}
</Toolbar>
);
},
});
export default connect((state) => ({
listActivePage: state.lists.page.index,
}))(EditFormHeader);
|
src/main_prod.js | ShankarSumanth/lean-react | import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
ReactDOM.render(
<App />,
document.getElementById( 'root' )
);
|
docs/app/Examples/views/Comment/Content/CommentExampleActions.js | aabustamante/Semantic-UI-React | import React from 'react'
import { Comment, Icon } from 'semantic-ui-react'
const CommentExampleActions = () => (
<Comment.Group>
<Comment>
<Comment.Avatar as='a' src='/assets/images/avatar/small/joe.jpg' />
<Comment.Content>
<Comment.Author>Tom Lukic</Comment.Author>
<Comment.Text>
This will be great for business reports. I will definitely download this.
</Comment.Text>
<Comment.Actions>
<Comment.Action>Reply</Comment.Action>
<Comment.Action>Save</Comment.Action>
<Comment.Action>Hide</Comment.Action>
<Comment.Action>
<Icon name='expand' />
Full-screen
</Comment.Action>
</Comment.Actions>
</Comment.Content>
</Comment>
</Comment.Group>
)
export default CommentExampleActions
|
lib/notebook-editor-view.js | jupyter/atom-notebook | 'use babel';
import path from 'path';
import fs from 'fs-plus';
import File from 'pathwatcher';
import React from 'react';
import Immutable from 'immutable';
import {CompositeDisposable} from 'atom';
import {$, ScrollView} from 'atom-space-pen-views';
import NotebookCell from './notebook-cell';
export default class NotebookEditorView extends React.Component {
constructor(props) {
super(props);
this.store = props.store;
this.subscriptions = new CompositeDisposable();
//TODO: remove these development handles
global.editorView = this;
}
componentDidMount() {
this.subscriptions.add(this.store.addStateChangeListener(this._onChange));
}
componentDidUpdate(prevProps, prevState) {
}
componentWillUnmount() {
this.subscriptions.dispose();
}
render() {
// console.log('notebookeditorview render called');
let language = this.state.data.getIn(['metadata', 'language_info', 'name']);
// console.log('Language:', language);
let notebookCells = this.state.data.get('cells').map((cell) => {
cell = cell.set('language', language);
return (
<NotebookCell
data={cell}
key={cell.getIn(['metadata', 'id'])}
language={language}
/>
);
});
return (
<div className="notebook-editor">
<header className="notebook-toolbar">
<button className="btn icon inline-block-tight icon-plus add-cell" onClick={this.addCell}></button>
<div className='inline-block btn-group'>
<button className='btn icon icon-playback-play' onClick={this.runActiveCell}></button>
<button className='btn icon icon-primitive-square' onClick={this.interruptKernel}></button>
</div>
</header>
<div className="notebook-cells-container">
<div className="redundant-cells-container">
{notebookCells}
</div>
</div>
</div>
);
}
addCell() {
Dispatcher.dispatch({
actionType: Dispatcher.actions.add_cell
// cellID: this.props.data.getIn(['metadata', 'id'])
});
}
runActiveCell() {
Dispatcher.dispatch({
actionType: Dispatcher.actions.run_active_cell
// cellID: this.props.data.getIn(['metadata', 'id'])
});
}
interruptKernel() {
Dispatcher.dispatch({
actionType: Dispatcher.actions.interrupt_kernel
// cellID: this.props.data.getIn(['metadata', 'id'])
});
}
_fetchState = () => {
// console.log('fetching NE state');
if (this.store !== undefined) {
return this.store.getState();
} else {
return Immutable.Map();
}
};
// private onChange handler for use in callbacks
_onChange = () => {
let newState = this._fetchState();
// console.log('Setting state:', newState.toString());
this.setState({data: newState});
};
// set the initial state
state = {
data: this.props.store.getState()
};
}
|
shared/components/DemoApp/index.js | kennethtruong/react-webapp | import 'normalize.css/normalize.css';
import React from 'react';
import Switch from 'react-router-dom/Switch';
import Redirect from 'react-router-dom/Redirect';
import Route from 'react-router-dom/Route';
import './globals.scss';
import styles from './index.scss';
import AsyncHome from './AsyncHome';
import AsyncAbout from './AsyncAbout';
import AsyncCounter from './AsyncCounter';
import AsyncLogin from './AsyncLogin';
import AsyncLogout from './AsyncLogout';
import Error404 from './Error404';
import Header from './Header';
import getAuth from '../../store/Auth';
const PrivateRoute = ({ component, ...rest }) => { // eslint-disable-line
const auth = getAuth();
return (
<Route
{...rest}
render={props => (
auth.isLoggedIn ? (
React.createElement(component, props)
) : (
<Redirect
to={{
pathname: '/login',
state: { from: props.location }, // eslint-disable-line
}}
/>
))
}
/>
);
};
function DemoApp() {
return (
<div className={styles.root}>
<Header />
<Switch>
<Route exact path="/" component={AsyncHome} />
<Route path="/counter" component={AsyncCounter} />
<Route path="/login" component={AsyncLogin} />
<Route path="/logout" component={AsyncLogout} />
<PrivateRoute path="/about" component={AsyncAbout} />
<Route component={Error404} />
</Switch>
</div>
);
}
export default DemoApp;
|
es/components/PlaylistManager/SearchResults/index.js | welovekpop/uwave-web-welovekpop.club | import _jsx from "@babel/runtime/helpers/builtin/jsx";
import cx from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import { IDLE, LOADING, LOADED } from '../../../constants/LoadingStates';
import NoSearchResults from './NoSearchResults';
import LoadingSearchResults from './LoadingSearchResults';
import SearchResultsList from './SearchResultsList';
var enhance = translate();
var _ref2 =
/*#__PURE__*/
_jsx(NoSearchResults, {});
var _ref3 =
/*#__PURE__*/
_jsx(LoadingSearchResults, {});
var SearchResultsPanel = function SearchResultsPanel(_ref) {
var t = _ref.t,
className = _ref.className,
query = _ref.query,
loadingState = _ref.loadingState,
results = _ref.results,
onOpenAddMediaMenu = _ref.onOpenAddMediaMenu,
onOpenPreviewMediaDialog = _ref.onOpenPreviewMediaDialog;
var list;
if (loadingState === LOADED) {
list = results.length > 0 ? _jsx(SearchResultsList, {
results: results,
onOpenPreviewMediaDialog: onOpenPreviewMediaDialog,
onOpenAddMediaMenu: onOpenAddMediaMenu
}) : _ref2;
} else {
list = _ref3;
}
return _jsx("div", {
className: cx('PlaylistPanel', 'SearchResults', className)
}, void 0, _jsx("div", {
className: "SearchResults-query"
}, void 0, t('playlists.search.results', {
query: query
})), list);
};
SearchResultsPanel.propTypes = process.env.NODE_ENV !== "production" ? {
t: PropTypes.func.isRequired,
className: PropTypes.string,
query: PropTypes.string.isRequired,
loadingState: PropTypes.oneOf([IDLE, LOADING, LOADED]).isRequired,
results: PropTypes.arrayOf(PropTypes.object),
onOpenAddMediaMenu: PropTypes.func.isRequired,
onOpenPreviewMediaDialog: PropTypes.func.isRequired
} : {};
export default enhance(SearchResultsPanel);
//# sourceMappingURL=index.js.map
|
packages/material-ui-icons/src/RemoveCircle.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let RemoveCircle = props =>
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11H7v-2h10v2z" />
</SvgIcon>;
RemoveCircle = pure(RemoveCircle);
RemoveCircle.muiName = 'SvgIcon';
export default RemoveCircle;
|
stories/PoweredBy.stories.js | algolia/react-instantsearch | import React from 'react';
import { storiesOf } from '@storybook/react';
import { PoweredBy } from 'react-instantsearch-dom';
import { WrapWithHits } from './util';
const stories = storiesOf('PoweredBy', module);
stories.add('default', () => (
<WrapWithHits linkedStoryGroup="PoweredBy.stories.js">
<PoweredBy />
</WrapWithHits>
));
|
node_modules/react-navigation/lib-rn/navigators/createNavigator.js | RahulDesai92/PHR | import React from 'react';
var babelPluginFlowReactPropTypes_proptype_NavigationRouteConfigMap = require('../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationRouteConfigMap || require('prop-types').any;
var babelPluginFlowReactPropTypes_proptype_NavigationNavigatorProps = require('../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationNavigatorProps || require('prop-types').any;
var babelPluginFlowReactPropTypes_proptype_NavigationNavigator = require('../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationNavigator || require('prop-types').any;
var babelPluginFlowReactPropTypes_proptype_NavigationRouter = require('../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationRouter || require('prop-types').any;
/**
* Creates a navigator based on a router and a view that renders the screens.
*/
var babelPluginFlowReactPropTypes_proptype_NavigatorType = require('./NavigatorTypes').babelPluginFlowReactPropTypes_proptype_NavigatorType || require('prop-types').any;
const createNavigator = (router, routeConfigs, navigatorConfig, navigatorType) => View => {
class Navigator extends React.Component {
static router = router;
static routeConfigs = routeConfigs;
static navigatorConfig = navigatorConfig;
static navigatorType = navigatorType;
render() {
return <View {...this.props} router={router} />;
}
}
return Navigator;
};
export default createNavigator; |
docs/src/sections/CarouselSection.js | mmarcant/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 CarouselSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="carousels">Carousels</Anchor> <small>Carousel, Carousel.Item, Carousel.Caption</small>
</h2>
<h3><Anchor id="carousels-uncontrolled">Uncontrolled</Anchor></h3>
<p>Allow the component to control its own state.</p>
<ReactPlayground codeText={Samples.CarouselUncontrolled} exampleClassName="bs-example-tabs" />
<h3><Anchor id="carousels-controlled">Controlled</Anchor></h3>
<p>Pass down the active state on render via props.</p>
<ReactPlayground codeText={Samples.CarouselControlled} exampleClassName="bs-example-tabs" />
<h3><Anchor id="carousels-props">Props</Anchor></h3>
<h4><Anchor id="carousels-props-carousel">Carousel</Anchor></h4>
<PropTable component="Carousel"/>
<h4><Anchor id="carousels-props-item">Carousel.Item</Anchor></h4>
<PropTable component="CarouselItem"/>
<h4><Anchor id="carousels-props-caption">Carousel.Caption</Anchor></h4>
<PropTable component="Carousel.Caption"/>
</div>
);
}
|
docs/client/components/pages/Undo/CustomUndoEditor/index.js | dagopert/draft-js-plugins | import React, { Component } from 'react';
import { EditorState } from 'draft-js';
import Editor from 'draft-js-plugins-editor';
import createUndoPlugin from 'draft-js-undo-plugin';
import editorStyles from './editorStyles.css';
import buttonStyles from './buttonStyles.css';
const theme = {
undo: buttonStyles.button,
redo: buttonStyles.button,
};
const undoPlugin = createUndoPlugin({
undoContent: 'Undo',
redoContent: 'Redo',
theme,
});
const { UndoButton, RedoButton } = undoPlugin;
const plugins = [undoPlugin];
export default class CustomUndoEditor extends Component {
state = {
editorState: EditorState.createEmpty(),
};
onChange = (editorState) => {
this.setState({
editorState,
});
};
focus = () => {
this.editor.focus();
};
render() {
return (
<div>
<div className={editorStyles.editor} onClick={this.focus}>
<Editor
editorState={this.state.editorState}
onChange={this.onChange}
plugins={plugins}
ref={(element) => { this.editor = element; }}
/>
</div>
<div className={editorStyles.options}>
<UndoButton />
<RedoButton />
</div>
</div>
);
}
}
|
src/components/ActionParameters/index.js | DeveloperLaPoste/protagonist-react | import PropTypes from 'prop-types';
import React from 'react';
import { ActionParameter } from '../';
import './styles.css';
export default function ActionParameters({ parameters }) {
const content = parameters && parameters.length ? (
<div className="ActionParameters-content">
<h4>Paramètres</h4>
<table className="table">
<tbody>{parameters.map(parameter => <ActionParameter parameter={parameter} key={parameter.name} />)}</tbody>
</table>
</div>
) : <div className="ActionParameters-noContent" />;
return (
<div className="ActionParameters-main">
{content}
</div>
);
}
ActionParameters.propTypes = {
parameters: PropTypes.array,
};
ActionParameters.defaultProps = {
parameters: [],
};
|
src/svg-icons/maps/local-movies.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalMovies = (props) => (
<SvgIcon {...props}>
<path d="M18 3v2h-2V3H8v2H6V3H4v18h2v-2h2v2h8v-2h2v2h2V3h-2zM8 17H6v-2h2v2zm0-4H6v-2h2v2zm0-4H6V7h2v2zm10 8h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V7h2v2z"/>
</SvgIcon>
);
MapsLocalMovies = pure(MapsLocalMovies);
MapsLocalMovies.displayName = 'MapsLocalMovies';
MapsLocalMovies.muiName = 'SvgIcon';
export default MapsLocalMovies;
|
6-material-ui/src/pages/Login.js | pirosikick/react-hands-on-20171023 | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import RaisedButton from 'material-ui/RaisedButton';
import * as firebase from 'firebase';
class Login extends Component {
static propTypes = {
history: PropTypes.shape({
replace: PropTypes.func.isRequired,
}).isRequired,
};
state = {
error: false,
};
componentDidMount() {
const user = firebase.auth().currentUser;
if (user) {
this.props.history.replace('/');
}
}
handleClick = () => {
const provider = new firebase.auth.GoogleAuthProvider();
firebase
.auth()
.signInWithPopup(provider)
.then(() => {
this.props.history.replace('/');
})
.catch(err => {
console.log('failed to log in', err);
this.setState({ error: true });
});
};
render() {
const { error } = this.state;
return (
<div>
{error ? <p>ログインエラー</p> : ''}
<RaisedButton
label="ログイン"
fullWidth={true}
onClick={this.handleClick}
/>
</div>
);
}
}
export default Login;
|
Realization/frontend/czechidm-acc/src/content/connectorserver/RemoteServerTable.js | bcvsolutions/CzechIdMng | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
//
import { Advanced, Basic, Utils } from 'czechidm-core';
import uuid from 'uuid';
import { RemoteServerManager } from '../../redux';
const manager = new RemoteServerManager();
/**
* Remote server with connectors.
*
* @author Radek Tomiška
* @since 10.8.0
*/
export class RemoteServerTable extends Advanced.AbstractTableContent {
constructor(props, context) {
super(props, context);
this.state = {
filterOpened: this.props.filterOpened,
};
}
getContentKey() {
return 'acc:content.remote-servers';
}
getManager() {
return manager;
}
componentDidMount() {
super.componentDidMount();
//
if (this.refs.text) {
this.refs.text.focus();
}
}
useFilter(event) {
if (event) {
event.preventDefault();
}
this.refs.table.useFilterForm(this.refs.filterForm);
}
cancelFilter(event) {
if (event) {
event.preventDefault();
}
this.refs.table.cancelFilter(this.refs.filterForm);
}
showDetail(entity) {
if (Utils.Entity.isNew(entity)) {
const uuidId = uuid.v1();
this.context.store.dispatch(this.getManager().receiveEntity(uuidId, entity));
this.context.history.push(`/remote-servers/${ uuidId }/new?new=1`);
} else {
this.context.history.push(`/remote-servers/${ entity.id }/detail`);
}
}
render() {
const { filterOpened } = this.state;
//
return (
<Basic.Div>
<Advanced.Table
ref="table"
uiKey={ this.getUiKey() }
manager={ this.getManager() }
showRowSelection
filter={
<Advanced.Filter onSubmit={ this.useFilter.bind(this) }>
<Basic.AbstractForm ref="filterForm">
<Basic.Row className="last">
<Basic.Col lg={ 6 }>
<Advanced.Filter.TextField
ref="text"
placeholder={ this.i18n('filter.text.placeholder') }
help={ Advanced.Filter.getTextHelp() }/>
</Basic.Col>
<Basic.Col lg={ 6 } className="text-right">
<Advanced.Filter.FilterButtons cancelFilter={ this.cancelFilter.bind(this) }/>
</Basic.Col>
</Basic.Row>
</Basic.AbstractForm>
</Advanced.Filter>
}
buttons={
[
<Basic.Button
level="success"
key="add_button"
className="btn-xs"
onClick={this.showDetail.bind(this, { useSsl: true })}
rendered={ this.getManager().canSave() }
icon="fa:plus">
{ this.i18n('button.add') }
</Basic.Button>
]
}
filterOpened={ filterOpened }
_searchParameters={ this.getSearchParameters() }>
<Advanced.Column
header=""
className="detail-button"
cell={
({ rowIndex, data }) => {
return (
<Advanced.DetailButton
title={ this.i18n('button.detail') }
onClick={ this.showDetail.bind(this, data[rowIndex]) }/>
);
}
}/>
<Advanced.Column property="host" sort/>
<Advanced.Column property="port" sort/>
<Advanced.Column property="useSsl" face="bool" sort/>
<Advanced.Column property="timeout" sort/>
<Advanced.Column
property="defaultRemoteServer"
header={ this.i18n('acc:entity.RemoteServer.defaultRemoteServer.short') }
face="bool"
rendered={ false } />
<Advanced.Column
property="description"
header={ this.i18n('entity.description.label') }
sort/>
</Advanced.Table>
</Basic.Div>
);
}
}
RemoteServerTable.propTypes = {
uiKey: PropTypes.string.isRequired,
filterOpened: PropTypes.bool
};
RemoteServerTable.defaultProps = {
filterOpened: true
};
function select(state, component) {
return {
_searchParameters: Utils.Ui.getSearchParameters(state, component.uiKey)
};
}
export default connect(select, null, null, { forwardRef: true })(RemoteServerTable);
|
src/components/common/CollectionTable.js | mitmedialab/MediaCloud-Web-Tools | import PropTypes from 'prop-types';
import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import Link from 'react-router/lib/Link';
import FilledStarIcon from './icons/FilledStarIcon';
import LockIcon from './icons/LockIcon';
import messages from '../../resources/messages';
const CollectionTable = props => (
<div className="collection-table">
<table width="100%">
<tbody>
<tr>
<th><FormattedMessage {...messages.collectionNameProp} /></th>
<th><FormattedMessage {...messages.collectionDescriptionProp} /></th>
</tr>
{props.collections.map((c, idx) => (
<tr key={c.tags_id} className={(idx % 2 === 0) ? 'even' : 'odd'}>
<td>
<Link
to={props.absoluteLink ? `https://sources.mediacloud.org/#/collections/${c.tags_id}` : `/collections/${c.tags_id}`}
>
{c.label || c.tag}
</Link>
</td>
<td>
{c.description}
</td>
<td>
{ c.show_on_media === false || c.show_on_media === undefined ? <LockIcon /> : '' }
{ c.isFavorite ? <FilledStarIcon /> : '' }
</td>
</tr>
))}
</tbody>
</table>
</div>
);
CollectionTable.propTypes = {
// from parent
collections: PropTypes.array.isRequired,
absoluteLink: PropTypes.bool,
// from context
intl: PropTypes.object.isRequired,
};
export default
injectIntl(
CollectionTable
);
|
docs/app/Examples/collections/Menu/Content/Inputs.js | ben174/Semantic-UI-React | import React from 'react'
import { Input, Menu } from 'semantic-ui-react'
const Inputs = () => {
return (
<Menu>
<Menu.Item>
<Input className='icon' icon='search' placeholder='Search...' />
</Menu.Item>
<Menu.Item position='right'>
<Input action={{ type: 'submit', content: 'Go' }} placeholder='Navigate to...' />
</Menu.Item>
</Menu>
)
}
export default Inputs
|
packages/react-scripts/fixtures/kitchensink/src/features/webpack/SvgInclusion.js | appier/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 from 'react';
import logo from './assets/logo.svg';
export default () => <img id="feature-svg-inclusion" src={logo} alt="logo" />;
|
index.android.js | stevenpan91/ChemicalEngineerHelper | import React, { Component } from 'react';
import {
AppRegistry,
Text,
View,
StyleSheet,
Button,
TouchableOpacity } from 'react-native';
import { StackNavigator } from 'react-navigation';
// Custom Components
//import IosFonts from './app/components/IosFonts/IosFonts'; //unused
import Logo from './app/components/Logo/Logo';
import Footer from './app/components/Footer/Footer'; //unused
import RouteButton from './app/components/RouteButton/RouteButton';
//Import Scenes
import Home from './app/Home';
import History from './app/History';
import Settings from './app/Settings';
//Import Individual equations
import Density from './app/equations/Density'
import VaporDensity from './app/equations/VaporDensity'
import ReynoldsNumber from './app/equations/ReynoldsNumber'
import PipePressureDrop from './app/equations/PipePressureDrop'
import PipePressureDropCompressible from './app/equations/PipePressureDropCompressible'
import CalculationClass from './app/classes/CalculationClass'
import CPPConnection from './app/classes/CPPConnection'
import CEHFunctions from './app/modules/CEHFunctions'
// For testing if we can automatically route to equation page if user is logged in.
userLoggedIn = true;
function wait(ms) {
var d = new Date();
var d2 = null;
do { d2 = new Date(); }
while(d2-d < ms);
}
class Welcome extends Component {
static navigationOptions = ({ navigation }) => {
const {state, setParams, navigate} = navigation;
return {
title: 'Welcome',
headerRight: <Button
title="Settings" onPress={()=>navigate('Settings')}/>,
}
};
render() {
const { navigate } = this.props.navigation;
const { params } = this.props.navigation.state;
return (
<View style={styles.container}>
<View style={styles.main}>
<Logo style={styles.image}/>
<Text style={styles.welcome}> Welcome to the Chemical Engineer Helper App!</Text>
<View style={styles.row}>
<RouteButton title="Home" navigate={this.props.navigation} text="Get Started!" />
<RouteButton title="Home" navigate={this.props.navigation} text="Sign In" />
</View>
<Text style={styles.quote}> "Quote of Deep thought" </Text>
<Text style={styles.quote}> - Scientist , 1968 </Text>
</View>
</View>
);
}
}
// Declare your routes
const ChemEngHelper = StackNavigator({
Welcome: { screen: Welcome },
Home: { screen: Home },
History: { screen: History },
Settings: { screen: Settings },
Density: { screen: Density },
"Vapor Density": { screen: VaporDensity },
"Reynolds Number": { screen: ReynoldsNumber },
"Pipe Pressure Drop":{ screen: PipePressureDrop },
"Pipe Pressure Drop Compressible":{screen:PipePressureDropCompressible},
"Calculation Class": {screen: CalculationClass}
});
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#03D6F3',
paddingTop : 5,
},
main: {
flex: 1,
justifyContent:'center',
alignItems: 'center'
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
color: '#FFFFFF',
fontWeight: 'bold',
},
button: {
textAlign: 'center',
color: '#FFFFFF',
backgroundColor: '#033BE5',
marginBottom: 5,
padding: 12,
overflow: 'hidden',
borderRadius: 6,
},
quote : {
textAlign: 'center',
color: '#FFFFFF',
fontFamily: 'snell roundhand',
},
image : {
tintColor: '#ffffff',
},
row: {
flexDirection: 'row'
}
});
AppRegistry.registerComponent('ChemEngHelper', () => ChemEngHelper);
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
//import React, { Component } from 'react';
//import {
// AppRegistry,
// StyleSheet,
// Text,
// View,
// Button,
// TouchableHighlight,
// TouchableOpacity,
// Navigator
//} from 'react-native';
//
//
//var MainScreen = require('./MainScreen');
//var EquationScreen = require('./EquationScreen');
//var CalcScreen=require('./CalcScreen');
//
//
//
//
//
//export default class ChemEngHelper extends Component {
// //static navigationOptions = { title: 'Welcome', };
//
// render() {
// return (
// <Navigator
// initialRoute={{id: 'MainScreen', name: 'Index'}}
// renderScene={this.renderScene.bind(this)}
// configureScene={(route) => {
// if (route.sceneConfig) {
// return route.sceneConfig;
// }
// return Navigator.SceneConfigs.FloatFromRight;
// }} />
// );
// }
// renderScene(route, navigator) {
// var routeId = route.id;
//
// if (routeId === 'MainScreen') {
// return (
// <MainScreen
// navigator={navigator} />
// );
// }
// if (routeId === 'EquationScreen') {
// return (
// <EquationScreen
// navigator={navigator} />
// );
// }
// if (routeId === 'CalcScreen') {
// return (
// <CalcScreen
// navigator={navigator} />
// );
// }
//
// return this.noRoute(navigator);
//
// }
// noRoute(navigator) {
// return (
// <View style={{flex: 1, alignItems: 'stretch', justifyContent: 'center'}}>
// <TouchableOpacity style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}
// onPress={() => navigator.pop()}>
// <Text style={{color: 'red', fontWeight: 'bold'}}>Set the route at index.js</Text>
// </TouchableOpacity>
// </View>
// );
// }
//}
//
//
//
//
//
//
//
//
////export default class ChemEngHelper extends Component {
//// static navigationOptions = { title: 'Welcome', };
//// render() {
////
//// const{navigate}=this.props.navigation;
//// return(
//// <Button
//// title="Go to Equation Page"
//// onPress={() =>
//// this.props.navigation.navigate('Equations')
//// }
//// />
//// );
//
//// return (
//// <View style={styles.container}>
//// <Text style={styles.welcome}>
//// Welcome to the Chemical Engineer Helper App!
//// </Text>
//// <Text style={styles.instructions}>
//// To get started, edit index.android.js
//// </Text>
//// <Text style={styles.instructions}>
//// Double tap R on your keyboard to reload,{'\n'}
//// Shake or press menu button for dev menu
//// </Text>
//// </View>
//// );
//// }
////}
//
////class EquationScreen extends React.Component{
////
//// static navigationOptions = ({navigation}) => ({
//// title: navigation.state.params.name,
//// });
//// render() {
//// const { goBack } = this.props.navigation;
//// return (
//// <Button
//// title="Go back"
//// onPress={() => goBack()}
//// />
//// );
//// }
////}
//
//
//
//const styles = StyleSheet.create({
// container: {
// flex: 1,
// justifyContent: 'center',
// alignItems: 'center',
// backgroundColor: '#F5FCFF',
// },
// welcome: {
// fontSize: 20,
// textAlign: 'center',
// margin: 10,
// },
// instructions: {
// textAlign: 'center',
// color: '#333333',
// marginBottom: 5,
// },
//});
//
////const App=StackNavigator({
//// Main: {screen: ChemEngHelper},
//// Equations: {screen: EquationScreen},
////});
////module.exports=EquationScreen;
//AppRegistry.registerComponent('ChemEngHelper', () => ChemEngHelper);
|
internals/templates/app.js | haithemT/app-test | /**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
// Needed for redux-saga es6 generator support
import 'babel-polyfill';
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { useScroll } from 'react-router-scroll';
import 'sanitize.css/sanitize.css';
// Import root app
import App from 'containers/App';
// Import selector for `syncHistoryWithStore`
import { makeSelectLocationState } from 'containers/App/selectors';
// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';
// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-unresolved, import/extensions */
import '!file-loader?name=[name].[ext]!./favicon.ico';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */
import configureStore from './store';
// Import i18n messages
import { translationMessages } from './i18n';
// Import CSS reset and Global Styles
import './global-styles';
// Import root routes
import createRoutes from './routes';
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);
// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: makeSelectLocationState(),
});
// Set up the router, wrapping all Routes in the App component
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
};
const render = (messages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={messages}>
<Router
history={history}
routes={rootRoute}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(useScroll())
}
/>
</LanguageProvider>
</Provider>,
document.getElementById('app')
);
};
// Hot reloadable translation json files
if (module.hot) {
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept('./i18n', () => {
render(translationMessages);
});
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
(new Promise((resolve) => {
resolve(import('intl'));
}))
.then(() => Promise.all([
import('intl/locale-data/jsonp/en.js'),
]))
.then(() => render(translationMessages))
.catch((err) => {
throw err;
});
} else {
render(translationMessages);
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
|
examples/src/components/ListTodos.js | krasimir/hocbox | import React from 'react';
import { wire } from '../../../lib';
import Todo from './Todo';
class ListTodos extends React.Component {
render() {
const { todos } = this.props;
return (
<div className='todoList'>
{ todos.map(todo => <Todo key={ todo.id} todo={ todo } />) }
</div>
)
}
}
export default wire(ListTodos, ['store'], store => ({ todos: store.getTodos() })); |
app/javascript/mastodon/components/load_more.js | danhunsaker/mastodon | import React from 'react';
import { FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
export default class LoadMore extends React.PureComponent {
static propTypes = {
onClick: PropTypes.func,
disabled: PropTypes.bool,
visible: PropTypes.bool,
}
static defaultProps = {
visible: true,
}
render() {
const { disabled, visible } = this.props;
return (
<button className='load-more' disabled={disabled || !visible} style={{ visibility: visible ? 'visible' : 'hidden' }} onClick={this.props.onClick}>
<FormattedMessage id='status.load_more' defaultMessage='Load more' />
</button>
);
}
}
|
demo/src/index.js | subschema/subschema-devel | import React from 'react';
import { loader, ValueManager } from 'subschema';
import Index from './IndexPage.jsx';
import schema from './schema.json';
import createHistory from 'history/createHashHistory';
import { DynamicSchema } from 'subschema-plugin-demo';
import { NavigationForm } from 'subschema-plugin-navigation';
import './demo.css';
//import "./sample.lessp";
const history = createHistory({
basename: '',
hashType: 'slash' // Google's legacy AJAX URL format
});
loader.addType({ Index });
loader.loaderType('Example');
loader.loaderType('Doc');
const typeToOption = ({ name: label }) => ({
label,
val: label
});
const docs = loader.listDocs().map(({ name: val }) => ({
val,
label: val.replace(/_/g, ' ')
}));
const samples = loader.listExamples().map(typeToOption);
const valueManager = ValueManager({
samples,
docs,
/* eslint-disable no-undef */
subschemaVersion: SUBSCHEMA_VERSION,
schema
});
const handleSubmit = (e, error, value) => {
e && e.preventDefault();
valueManager.update('submit', { error, value })
};
export default function App() {
return (<NavigationForm valueManager={valueManager} history={history}
schema={'schema'}
ObjectType={DynamicSchema}
loader={loader}
onSubmit={handleSubmit}
template="FieldSetTemplate"/>);
}
|
src/components/GuideView/TriangleBar.js | recharts/recharts.org | import React from 'react';
import PropTypes from 'prop-types';
const getPath = (x, y, width, height) =>
`M${x},${y + height}
C${x + width / 3},${y + height} ${x + width / 2},${y + height / 3} ${x + width / 2}, ${y}
C${x + width / 2},${y + height / 3} ${x + (2 * width) / 3},${y + height} ${x + width}, ${y + height}
Z`;
const TriangleBar = (props) => {
const { fill, x, y, width, height } = props;
return <path d={getPath(x, y, width, height)} stroke="none" fill={fill} />;
};
TriangleBar.propTypes = {
fill: PropTypes.string,
x: PropTypes.number,
y: PropTypes.number,
width: PropTypes.number,
height: PropTypes.number,
};
export default TriangleBar;
|
packages/cf-component-label/src/Label.js | jroyal/cf-ui | import React from 'react';
import PropTypes from 'prop-types';
import { createComponent } from 'cf-style-container';
const styles = props => {
const theme = props.theme;
return {
borderRadius: theme.borderRadius,
color: theme.color,
display: theme.display,
fontSize: theme.fontSize,
fontWeight: theme.fontWeight,
lineHeight: theme.lineHeight,
paddingTop: theme.paddingTop,
paddingRight: theme.paddingRight,
paddingBottom: theme.paddingBottom,
paddingLeft: theme.paddingLeft,
textTransform: theme.textTransform,
userSelect: theme.userSelect,
verticalAlign: theme.verticalAlign,
'-webkit-text-stroke': theme.webkitTextStroke,
whiteSpace: theme.whiteSpace,
backgroundColor: theme[`${props.type}BackgroundColor`]
};
};
class Label extends React.Component {
render() {
const { children, className } = this.props;
return (
<span className={className}>
{children}
</span>
);
}
}
Label.propTypes = {
className: PropTypes.string,
type: PropTypes.oneOf(['default', 'info', 'success', 'warning', 'error'])
.isRequired,
children: PropTypes.node
};
export default createComponent(styles, Label);
|
src/js/components/SearchFilters/index.js | waagsociety/ams.datahub.client | import React from 'react'
import { Feedback, SearchFiltersGroup, SearchTag } from '../'
export default function SearchFilters({ props }) {
const { search, view, route } = props.store
const { focus } = view.FilterGroup
const { metadata = [] } = search
const className = ['content tags'].join(' ')
const showSearchTag = view.SearchInput.value || search.active
const focusMetadata = focus && metadata.filter(group => group.key === focus)
if (focus && focusMetadata) return <div className='content tags'>
<SearchFiltersGroup key={focus} props={props} content={focusMetadata[0]}/>
</div>
else return <div className='content tags'>
<section className='search group' hidden={!showSearchTag}>
<h1>Search</h1>
<SearchTag props={props} />
</section>
{ metadata.map(group => {
return <SearchFiltersGroup key={group.key} props={props} content={group}/>
})
}
</div>
// else return ""
}
|
frontend/src/Movie/MovieQuality.js | geogolem/Radarr | import PropTypes from 'prop-types';
import React from 'react';
import Label from 'Components/Label';
import { kinds } from 'Helpers/Props';
import formatBytes from 'Utilities/Number/formatBytes';
function getTooltip(title, quality, size, isMonitored, isCutoffNotMet) {
const revision = quality.revision;
if (revision.real && revision.real > 0) {
title += ' [REAL]';
}
if (revision.version && revision.version > 1) {
title += ' [PROPER]';
}
if (size) {
title += ` - ${formatBytes(size)}`;
}
if (!isMonitored) {
title += ' [Not Monitored]';
} else if (isCutoffNotMet) {
title += ' [Cutoff Not Met]';
}
return title;
}
function MovieQuality(props) {
const {
className,
title,
quality,
size,
isMonitored,
isCutoffNotMet
} = props;
let kind = kinds.DEFAULT;
if (!isMonitored) {
kind = kinds.DISABLED;
} else if (isCutoffNotMet) {
kind = kinds.INVERSE;
}
if (!quality) {
return null;
}
return (
<Label
className={className}
kind={kind}
title={getTooltip(title, quality, size, isMonitored, isCutoffNotMet)}
>
{quality.quality.name}
</Label>
);
}
MovieQuality.propTypes = {
className: PropTypes.string,
title: PropTypes.string,
quality: PropTypes.object.isRequired,
size: PropTypes.number,
isMonitored: PropTypes.bool,
isCutoffNotMet: PropTypes.bool
};
MovieQuality.defaultProps = {
title: '',
isMonitored: true
};
export default MovieQuality;
|
js/components/home/index.js | gectorat/react-native-app |
import React, { Component } from 'react';
import { View, Text, TouchableOpacity, Modal } from 'react-native';
import { connect } from 'react-redux';
import firebase from 'firebase';
import Dimensions from 'Dimensions';
import NoItems from '../common/NoItemContentMsg';
import myTheme from '../../themes/base-theme';
import { syncPosts, fetchPosts } from '../../actions/post';
import styles from './styles';
import Swiper from '../swipeCards/swiper';
import Card from '../swipeCards/card';
class Home extends Component {
static propTypes = {
fetchPosts: React.PropTypes.func,
syncPosts: React.PropTypes.func,
name: React.PropTypes.string,
list: React.PropTypes.arrayOf(React.PropTypes.object),
}
constructor(props) {
super(props);
this.state = { posts: props.posts, page: 'home' };
}
componentDidMount() {
const db = firebase.database();
const ref = db.ref('posts');
ref.on('value', snapshot => {
// this.state({list: snapshot.val()})
this.props.fetchPosts();
}, errorObject => console.log(`The read failed: ${errorObject.code}`));
this.props.fetchPosts();
}
handleYup() {
console.log('YES');
}
handleNope() {
console.log('NO');
}
render() {
const { height, width } = Dimensions.get('window');
const swiper = (
<Swiper
containerStyle={styles.cardContainer}
cards={this.props.posts}
renderCard={cardData => (
<Card
width={width}
height={height}
stylesCard={styles.card}
data={cardData}
/>
)}
renderNoMoreCards={() => <NoItems><Text>No More Cards</Text></NoItems>}
handleYup={this.handleYup}
handleNope={this.handleNope}
>
test
</Swiper>);
const mainContent = this.state.page === 'home' ? swiper : (<Text>Not A Home</Text>);
return (
<View style={{ flex: 1 }} theme={myTheme} >
<View style={{ flex: 1 }}>
{mainContent}
</View>
</View>
);
}
}
function bindAction(dispatch) {
return {
syncPosts: () => dispatch(syncPosts()),
fetchPosts: () => dispatch(fetchPosts()),
};
}
function mapStateToProps(state) {
return {
name: state.user.name,
posts: state.posts.posts,
list: state.posts.posts,
};
}
export default connect(mapStateToProps, bindAction)(Home);
|
src/icons/SocialDropboxOutline.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class SocialDropboxOutline extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<path d="M177,77.1L64,151l78.3,63L256,143.2L177,77.1z M91.4,153.3l84.5-56.8l52.9,46L143.4,195L91.4,153.3z"></path>
<path d="M369.8,213L256,284.1l79,66.1l19-12.6v20.2L256,417l-98-58.5V338l19,12.2l79-66.1L142.2,213L64,276.3l78,51.5v39.4
l114,67.8l114-68.5v-39.2l78-51.2L369.8,213z M143.4,230.9l85.4,55.4l-52.9,44.1l-84.5-55.8L143.4,230.9z M283.2,286.3l85.4-55.4
l52.1,43.6l-84.5,55.8L283.2,286.3z"></path>
<path d="M448,151L335,77.1l-79,66.1l113.8,70.8L448,151z M283.2,142.6l52.9-46l84.5,56.8L368.6,195L283.2,142.6z"></path>
</g>
</g>;
} return <IconBase>
<g>
<path d="M177,77.1L64,151l78.3,63L256,143.2L177,77.1z M91.4,153.3l84.5-56.8l52.9,46L143.4,195L91.4,153.3z"></path>
<path d="M369.8,213L256,284.1l79,66.1l19-12.6v20.2L256,417l-98-58.5V338l19,12.2l79-66.1L142.2,213L64,276.3l78,51.5v39.4
l114,67.8l114-68.5v-39.2l78-51.2L369.8,213z M143.4,230.9l85.4,55.4l-52.9,44.1l-84.5-55.8L143.4,230.9z M283.2,286.3l85.4-55.4
l52.1,43.6l-84.5,55.8L283.2,286.3z"></path>
<path d="M448,151L335,77.1l-79,66.1l113.8,70.8L448,151z M283.2,142.6l52.9-46l84.5,56.8L368.6,195L283.2,142.6z"></path>
</g>
</IconBase>;
}
};SocialDropboxOutline.defaultProps = {bare: false} |
src/components/FeatureList/FeatureList.js | jhabdas/lumpenradio-com | import React from 'react';
import styles from './FeatureList.css';
import withStyles from '../../decorators/withStyles';
import Link from '../Link';
import FeatureItem from '../FeatureItem';
@withStyles(styles)
class FeatureList extends React.Component {
render() {
let items = this.props.data.map((item, i) => {
return (
<FeatureItem key={i} data={item} />
)
});
return (
<div className="FeatureList">
<div className="FeatureList-container">
<div className="FeatureList-header">
<h1>Features</h1>
</div>
<div className="FeatureList-items">
{items}
</div>
<a className="FeatureList-moreLink" href="/news">Previous Features →</a>
</div>
</div>
);
}
}
export default FeatureList;
|
src/pages/sections/Intro.js | andrewoh531/pristine-clean | import React from 'react'
import styled from 'styled-components'
import { Flex, Box } from '@rebass/grid'
import { tablet, desktop } from '../../resources/media'
const Container = styled(Flex)`
height: 100vh;
flex-direction: column;
align-items: center;
padding-top: 10rem;
font-family: 'Raleway', sans-serif;
`
const Title = styled(Box)`
color: white;
font-size: 4rem;
font-weight: bold;
text-align: center;
margin-bottom: 1rem;
@media ${tablet} {
font-size: 6rem;
}
@media ${desktop} {
font-size: 8rem;
}
`
const Tagline = styled.div`
color: white;
font-size: 1.5em;
font-weight: 400;
@media ${tablet} {
font-size: 2.5rem;
}
`
const Intro = props => (
<Container className="intro-background">
<Title>Pristine Clean</Title>
<Tagline>Relax</Tagline>
<Tagline>Leave the cleaning to us</Tagline>
</Container>
)
export default Intro
|
app/javascript/mastodon/features/follow_recommendations/index.js | im-in-space/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
import { fetchSuggestions } from 'mastodon/actions/suggestions';
import { changeSetting, saveSettings } from 'mastodon/actions/settings';
import { requestBrowserPermission } from 'mastodon/actions/notifications';
import { markAsPartial } from 'mastodon/actions/timelines';
import Column from 'mastodon/features/ui/components/column';
import Account from './components/account';
import Logo from 'mastodon/components/logo';
import imageGreeting from 'mastodon/../images/elephant_ui_greeting.svg';
import Button from 'mastodon/components/button';
const mapStateToProps = state => ({
suggestions: state.getIn(['suggestions', 'items']),
isLoading: state.getIn(['suggestions', 'isLoading']),
});
export default @connect(mapStateToProps)
class FollowRecommendations extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
dispatch: PropTypes.func.isRequired,
suggestions: ImmutablePropTypes.list,
isLoading: PropTypes.bool,
};
componentDidMount () {
const { dispatch, suggestions } = this.props;
// Don't re-fetch if we're e.g. navigating backwards to this page,
// since we don't want followed accounts to disappear from the list
if (suggestions.size === 0) {
dispatch(fetchSuggestions(true));
}
}
componentWillUnmount () {
const { dispatch } = this.props;
// Force the home timeline to be reloaded when the user navigates
// to it; if the user is new, it would've been empty before
dispatch(markAsPartial('home'));
}
handleDone = () => {
const { dispatch } = this.props;
const { router } = this.context;
dispatch(requestBrowserPermission((permission) => {
if (permission === 'granted') {
dispatch(changeSetting(['notifications', 'alerts', 'follow'], true));
dispatch(changeSetting(['notifications', 'alerts', 'favourite'], true));
dispatch(changeSetting(['notifications', 'alerts', 'reblog'], true));
dispatch(changeSetting(['notifications', 'alerts', 'mention'], true));
dispatch(changeSetting(['notifications', 'alerts', 'poll'], true));
dispatch(changeSetting(['notifications', 'alerts', 'status'], true));
dispatch(saveSettings());
}
}));
router.history.push('/home');
}
render () {
const { suggestions, isLoading } = this.props;
return (
<Column>
<div className='scrollable follow-recommendations-container'>
<div className='column-title'>
<Logo />
<h3><FormattedMessage id='follow_recommendations.heading' defaultMessage="Follow people you'd like to see posts from! Here are some suggestions." /></h3>
<p><FormattedMessage id='follow_recommendations.lead' defaultMessage="Posts from people you follow will show up in chronological order on your home feed. Don't be afraid to make mistakes, you can unfollow people just as easily any time!" /></p>
</div>
{!isLoading && (
<React.Fragment>
<div className='column-list'>
{suggestions.size > 0 ? suggestions.map(suggestion => (
<Account key={suggestion.get('account')} id={suggestion.get('account')} />
)) : (
<div className='column-list__empty-message'>
<FormattedMessage id='empty_column.follow_recommendations' defaultMessage='Looks like no suggestions could be generated for you. You can try using search to look for people you might know or explore trending hashtags.' />
</div>
)}
</div>
<div className='column-actions'>
<img src={imageGreeting} alt='' className='column-actions__background' />
<Button onClick={this.handleDone}><FormattedMessage id='follow_recommendations.done' defaultMessage='Done' /></Button>
</div>
</React.Fragment>
)}
</div>
</Column>
);
}
}
|
examples/babel-plugin-react-hot/index.js | LeoLeBras/redbox-react | import React from 'react'
import App from './components/App'
const root = document.getElementById('root')
React.render(<App />, root)
|
node_modules/react-router/es/MemoryRouter.js | paul-brabet/tinkerlist | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import React from 'react';
import PropTypes from 'prop-types';
import createHistory from 'history/createMemoryHistory';
import Router from './Router';
/**
* The public API for a <Router> that stores location in memory.
*/
var MemoryRouter = function (_React$Component) {
_inherits(MemoryRouter, _React$Component);
function MemoryRouter() {
var _temp, _this, _ret;
_classCallCheck(this, MemoryRouter);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.history = createHistory(_this.props), _temp), _possibleConstructorReturn(_this, _ret);
}
MemoryRouter.prototype.render = function render() {
return React.createElement(Router, { history: this.history, children: this.props.children });
};
return MemoryRouter;
}(React.Component);
MemoryRouter.propTypes = {
initialEntries: PropTypes.array,
initialIndex: PropTypes.number,
getUserConfirmation: PropTypes.func,
keyLength: PropTypes.number,
children: PropTypes.node
};
export default MemoryRouter; |
src/js/axis.js | garygao12580/react_photo_wall | import React from 'react'
import '../css/axis.less'
import Rectangle from './rectangle'
import Circle from './circle'
class Axis extends React.Component {
constructor(props) {
super(props);
}
render() {
let {items, offsetX, onLabelClick} = this.props;
return <div className="axis">
{
items.map((item) => {
if (item.Type === "circle") {
return (
<Circle key={item.key} item={item} offsetX={offsetX} onLabelClick={onLabelClick}/>
);
} else {
return (
<Rectangle key={item.key} item={item} offsetX={offsetX} onLabelClick={onLabelClick}/>
);
}
})
}
</div>
}
}
export default Axis |
docs/client.js | jareth/react-materialize | import React from 'react';
import { Router } from 'react-router';
import ReactDOM from 'react-dom';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import Root from './src/Root';
import routes from './src/Routes';
window.React = React;
Root.propData = window.PROP_DATA;
ReactDOM.render(
<Router history={createBrowserHistory()} children={routes} />,
document
);
|
src/svg-icons/maps/add-location.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsAddLocation = (props) => (
<SvgIcon {...props}>
<path d="M12 2C8.14 2 5 5.14 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.86-3.14-7-7-7zm4 8h-3v3h-2v-3H8V8h3V5h2v3h3v2z"/>
</SvgIcon>
);
MapsAddLocation = pure(MapsAddLocation);
MapsAddLocation.displayName = 'MapsAddLocation';
MapsAddLocation.muiName = 'SvgIcon';
export default MapsAddLocation;
|
src/components/postPanel/postPanel.js | BerndWessels/react-freezer-webpack | /**
* Manapaho (https://github.com/manapaho/)
*
* Copyright © 2015 Manapaho. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
/**
* Import Entities.
*/
import {getEntities, getConnectionWithEntities} from '../../store';
/**
* Import Components.
*/
/**
* Import UX components.
*/
import CommentPanel from '../commentPanel/commentPanel';
/**
* Import styles.
*/
import style from './style';
/**
* Import Internationalization.
*/
import {IntlProvider, FormattedMessage} from 'react-intl';
/**
* The component.
*/
export default class PostPanel extends React.Component {
// Expected properties.
static propTypes = {
post: React.PropTypes.object.isRequired
};
// Initialize the component.
constructor(props) {
super(props);
}
// Invoked before rendering when new props or state are being received.
// This method is not called for the initial render or when forceUpdate is used.
// Use this as an opportunity to return false
// when you're certain that the transition to the new props and state will not require a component update.
// If shouldComponentUpdate returns false, then render() will be completely skipped until the next state change.
// In addition, componentWillUpdate and componentDidUpdate will not be called.
shouldComponentUpdate(nextProps, nextState) {
// This is a pure component.
return React.addons.shallowCompare(this, nextProps, nextState);
}
// Invoked before requesting data for this component.
static getQuery(id, offset = 0, limit = 5) {
return `title
comments (${id !== undefined ? 'id:' + id + ', ' : ""}offset: ${offset}, limit: ${limit}) {
offset
limit
nodes {
${CommentPanel.getQuery()}
}
total
}`;
}
// Render the component.
render() {
// Get the properties.
const {post, comments_range_update} = this.props;
// Get the comments.
var commentsConnection = getConnectionWithEntities('CommentConnection', post.comments);
// Calculate the styles.
let className = style.root;
// Return the component UI.
return (
<div className={className}>
<div>{post.title}</div>
<label>Offset:</label>
<input type="text" defaultValue={commentsConnection.offset} onChange={(e) => comments_range_update(e.target.value, commentsConnection.limit)}/>
<label>Limit:</label>
<input type="text" defaultValue={commentsConnection.limit} onChange={(e) => comments_range_update(commentsConnection.offset, e.target.value)}/>
<label>Total:</label>
<span>{commentsConnection.total}</span>
<ul>
{commentsConnection.nodes.map(comment => {
return (
<li key={comment.id}>
<CommentPanel comment={comment}/>
</li>
);
})}
</ul>
</div>
);
}
}
|
app/static/src/performer/FluidProfileForm.js | vsilent/Vision | import React from 'react';
import FormControl from 'react-bootstrap/lib/FormControl';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import Checkbox from 'react-bootstrap/lib/Checkbox';
import {findDOMNode} from 'react-dom';
import Panel from 'react-bootstrap/lib/Panel';
import Button from 'react-bootstrap/lib/Button';
import Radio from 'react-bootstrap/lib/Radio';
import HelpBlock from 'react-bootstrap/lib/HelpBlock';
import {NotificationContainer, NotificationManager} from 'react-notifications';
var items = [];
var SamplPointSelectField1 = React.createClass({
handleChange: function (event, index, value) {
this.setState({
value: event.target.value,
sam1: event.target.value
})
},
getInitialState: function () {
return {
items: [],
isVisible: false
};
},
isVisible: function () {
return this.state.isVisible;
},
componentDidMount: function () {
this.serverRequest = $.authorizedGet(this.props.source, function (result) {
items = (result['result']);
this.setState({
items: items
});
}.bind(this), 'json');
},
componentWillUnmount: function () {
this.serverRequest.abort();
},
setVisible: function () {
this.state.isVisible = true;
},
render: function () {
var menuItems = [];
for (var key in this.state.items) {
menuItems.push(<option key={this.state.items[key].id}
value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>);
}
return (
<FormGroup controlId="samplingPointSelect1">
<ControlLabel>Sampling Point</ControlLabel>
<FormControl componentClass="select"
placeholder="sampling point"
onChange={this.handleChange}
name="sampling"
>
{menuItems}
</FormControl>
</FormGroup>
);
}
});
var SamplPointSelectField2 = React.createClass({
handleChange: function (event, index, value) {
this.setState({
value: event.target.value,
})
},
getInitialState: function () {
return {
items: [],
isVisible: false
};
},
isVisible: function () {
return this.state.isVisible;
},
componentDidMount: function () {
this.serverRequest = $.authorizedGet(this.props.source, function (result) {
items = (result['result']);
this.setState({
items: items
});
}.bind(this), 'json');
},
componentWillUnmount: function () {
this.serverRequest.abort();
},
setVisible: function () {
this.state.isVisible = true;
},
render: function () {
var menuItems = [];
for (var key in this.state.items) {
menuItems.push(<option key={this.state.items[key].id}
value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>);
}
return (
<FormGroup controlId="samplingPointSelect2">
<ControlLabel>Sampling Point</ControlLabel>
<FormControl componentClass="select"
placeholder="sampling point"
onChange={this.handleChange}
name="sampling_jar"
>
{menuItems}
</FormControl>
</FormGroup>
);
}
});
var SamplPointSelectField3 = React.createClass({
handleChange: function (event, index, value) {
this.setState({
value: event.target.value,
})
},
getInitialState: function () {
return {
items: [],
isVisible: false
};
},
isVisible: function () {
return this.state.isVisible;
},
componentDidMount: function () {
this.serverRequest = $.authorizedGet(this.props.source, function (result) {
items = (result['result']);
this.setState({
items: items
});
}.bind(this), 'json');
},
componentWillUnmount: function () {
this.serverRequest.abort();
},
setVisible: function () {
this.state.isVisible = true;
},
render: function () {
var menuItems = [];
for (var key in this.state.items) {
menuItems.push(<option key={this.state.items[key].id}
value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>);
}
return (
<FormGroup controlId="samplingPointSelect3">
<ControlLabel>Sampling Point</ControlLabel>
<FormControl componentClass="select"
placeholder="sampling point"
name="sampling_vial"
onChange={this.handleChange}
>
{menuItems}
</FormControl>
</FormGroup>
);
}
});
var TestProfileSelectField = React.createClass({
getInitialState: function () {
return {
isVisible: true
};
},
handleChange: function (event) {
this.setState({
value: event.target.value
});
this.loadProfileData(event);
},
loadProfileData: function (event) {
if ('select' == event.target.value) {
this.setState({
saved_profile: null
});
this.props.fillUpForm();
} else {
this.serverRequest = $.authorizedGet('/api/v1.0/fluid_profile/' + event.target.value, function (result) {
this.setState({
saved_profile: result['result']
});
this.props.fillUpForm(this.state.saved_profile);
}.bind(this), 'json');
}
},
componentDidMount: function () {
this.serverRequest = $.authorizedGet(this.props.source, function (result) {
this.setState({
items: result['result']
});
}.bind(this), 'json');
},
componentWillUnmount: function () {
this.serverRequest.abort();
},
setVisible: function () {
this.state.isVisible = true;
},
render: function () {
var options = [];
for (var key in this.state.items) {
var index = Math.random() + '_' + this.state.items[key].id;
options.push(<option key={index}
value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>);
}
return (
<FormGroup>
<FormControl
componentClass="select"
placeholder="select"
value={this.state.value}
onChange={this.handleChange}
name="test_prof">
<option value="select">Choose profile from saved</option>
{options}
</FormControl>
</FormGroup>
)
}
});
const FluidProfileForm = React.createClass({
getInitialState: function () {
return {
loading: false,
data: {},
errors: {},
fields: [
'gas', 'furans', 'pcb', 'water',
'inhibitor', 'dielec', 'dielec_2',
'dielec_d', 'acidity', 'color',
'ift', 'density', 'pf', 'pf_100',
'pcb_jar', 'particles', 'furans_f',
'inhibitor_jar', 'metals', 'water_w',
'point', 'viscosity', 'corr', 'dielec_i',
'visual', 'pcb_vial', 'antioxidant',
'sampling', 'sampling_jar', 'sampling_vial',
'qty_ser', 'qty_jar', 'qty_vial', 'sampling',
'shared', 'name', 'description'
]
}
},
componentDidMount: function () {
},
fillUpForm: function (saved_data) {
if (null == saved_data) {
this.refs.fluid_profile.reset();
} else {
this.setState({
data: saved_data
});
}
},
_save: function () {
var fields = this.state.fields;
var data = {};
for (var i = 0; i < fields.length; i++) {
var key = fields[i];
data[key] = this.state.data[key];
}
// show success message
// if update a profile
var name = this.state.data['name'];
if (name != '' && (typeof name != 'undefined')) {
var url = '/api/v1.0/fluid_profile/';
if (this.props.fluidProfileId) {
url = url + this.props.fluidProfileId;
}
// if profile name is not empty and radio is checked then use this url to save profile
// and save to test_result
// otherwise just use these values for saving test_result
return $.authorizedAjax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (data, textStatus) {
},
beforeSend: function () {
this.setState({loading: true});
}.bind(this)
});
delete data['name'];
delete data['shared'];
}
data['campaign_id'] = this.props.campaignId;
data['equipment_id'] = this.props.equipmentId;
return $.authorizedAjax({
url: '/api/v1.0/test_result/' + this.props.testResultId,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
beforeSend: function () {
this.setState({loading: true});
}.bind(this)
});
},
_onSubmit: function (e) {
e.preventDefault();
e.stopPropagation();
if (!this.is_valid()){
NotificationManager.error('Please correct the errors');
return;
}
var xhr = this._save();
xhr.done(this._onSuccess)
.fail(this._onError)
.always(this.hideLoading)
},
hideLoading: function () {
this.setState({loading: false});
},
_onSuccess: function (data) {
NotificationManager.success('Profile saved successfully');
this.props.handleClose();
this.hideLoading();
},
_onError: function (data) {
var message = "Failed to create";
var res = data.responseJSON;
if (res.message) {
message = data.responseJSON.message;
}
if (res.error) {
// We get list of errors
if (data.status >= 500) {
message = res.error.join(". ");
} else if (res.error instanceof Object){
// We get object of errors with field names as key
for (var field in res.error) {
var errorMessage = res.error[field];
if (Array.isArray(errorMessage)) {
errorMessage = errorMessage.join(". ");
}
res.error[field] = errorMessage;
}
this.setState({
errors: res.error
});
} else {
message = res.error;
}
}
NotificationManager.error(message);
},
calculate_qty: function (data) {
var quantity_ml_syringe = 0;
// Syringe
if ( data['gas'] ) { quantity_ml_syringe += 15 }
if ( data['water'] ) { quantity_ml_syringe += 10 }
if ( data['pcb'] ) { quantity_ml_syringe += 5 }
if ( data['furans'] ) { quantity_ml_syringe += 20 }
var quantity = Math.ceil(quantity_ml_syringe / 30.0);
if ( !quantity_ml_syringe && data['inhibitor'] ) {
quantity = 1;
}
// if quantity != value:
// self._error(field, "Wrong quantity, must be {}".format(quantity))
return quantity;
},
calculate_qty_jar: function (data) {
var quantity_ml_jar = 0;
// POTS. Jar
if ( data['dielec'] ) { quantity_ml_jar += 500 }
if ( data['dielec_2'] ) { quantity_ml_jar += 500 }
if ( data['dielec_d'] ) { quantity_ml_jar += 450 }
if ( data['dielec_i'] ) { quantity_ml_jar += 500 }
if ( data['ift'] ) { quantity_ml_jar += 25 }
if ( data['pf'] ) { quantity_ml_jar += 100 }
if ( data['pf_100'] ) { quantity_ml_jar += 100 }
if ( data['point'] ) { quantity_ml_jar += 50 }
if ( data['viscosity'] ) { quantity_ml_jar += 50 }
if ( data['corr'] ) { quantity_ml_jar += 200 }
if ( data['pcb_jar'] ) { quantity_ml_jar += 5 }
if ( data['particles'] ) { quantity_ml_jar += 500 }
if ( data['metals'] ) { quantity_ml_jar += 50 }
if ( data['water_w'] ) { quantity_ml_jar += 10 }
if ( data['furans_f'] ) { quantity_ml_jar += 20 }
var quantity = Math.ceil(quantity_ml_jar / 750.0)
if (( !quantity_ml_jar ) &&
( data['acidity'] ||
data['color'] ||
data['density'] ||
data['visual'] ||
data['inhibitor_jar']))
{
quantity = 1;
}
// if quantity != value:
// self._error(field, "Wrong quantity, must be {}".format(quantity))
return quantity;
},
calculate_qty_vial: function (data) {
var quantity_ml_vial = 0;
if ( data['pcb_vial'] ) {
quantity_ml_vial += 5;
}
var quantity = Math.ceil(quantity_ml_vial / 5.0)
if ( ! quantity_ml_vial && data['antioxidant'] ) {
quantity = 1;
}
// if quantity != value:
// self._error(field, "Wrong quantity, must be {}".format(quantity))
return quantity;
},
_onChange: function (e) {
var state = {};
state['data'] = this.state.data;
if (e.target.type == 'checkbox') {
state['data'][e.target.name] = e.target.checked;
} else if (e.target.type == 'radio') {
state['data'][e.target.name] = (e.target.value == "1");
} else if (e.target.type == 'select-one') {
state['data'][e.target.name] = e.target.value;
} else {
state['data'][e.target.name] = e.target.value;
}
var errors = this._validate(e);
state = this._updateFieldErrors(e.target.name, state, errors);
state['data']['qty_ser'] = this.calculate_qty(state['data']);
state['data']['qty_jar'] = this.calculate_qty_jar(state['data']);
state['data']['qty_vial'] = this.calculate_qty_vial(state['data']);
this.setState(state);
},
_validate: function (e) {
var errors = [];
var error;
error = this._validateFieldLength(e.target.value, e.target.getAttribute("data-len"));
if (error){
errors.push(error);
}
error = this._validateFieldType(e.target.value, e.target.getAttribute("data-type"));
if (error){
errors.push(error);
}
return errors;
},
_validateFieldLength: function (value, length){
var error = "";
if (value && length){
if (value.length > length){
error = "Value should be maximum " + length + " characters long"
}
}
return error;
},
_validateFieldType: function (value, type){
var error = "";
if (type != undefined && value){
var typePatterns = {
"float": /^(-|\+?)[0-9]+(\.)?[0-9]*$/,
"int": /^(-|\+)?(0|[1-9]\d*)$/
};
if (!typePatterns[type].test(value)){
error = "Invalid " + type + " value";
}
}
return error;
},
_updateFieldErrors: function (fieldName, state, errors){
// Clear existing errors related to the current field as it has been edited
state.errors = this.state.errors;
delete state.errors[fieldName];
// Update errors with new ones, if present
if (Object.keys(errors).length){
state.errors[fieldName] = errors.join(". ");
}
return state;
},
is_valid: function () {
return (Object.keys(this.state.errors).length <= 0);
},
_formGroupClass: function (field) {
var className = "form-group ";
if (field) {
className += " has-error"
}
return className;
},
render: function () {
return (
<div className="form-container">
<form ref="fluid_profile" method="post" action="#" onSubmit={this._onSubmit} onChange={this._onChange}>
<div className="maxwidth">
<Panel header="Fluid profile">
<div className="row">
<div className="col-md-9"></div>
<div className="col-md-3">
<FormGroup>
<TestProfileSelectField fillUpForm={this.fillUpForm}
source="/api/v1.0/fluid_profile"/>
</FormGroup>
</div>
</div>
<div className="scheduler-border">
<fieldset className="scheduler-border">
<legend className="scheduler-border">Syringe - Test requested</legend>
<div className="control-group">
<div className="col-md-8 nopadding padding-right-xs">
<div className="maxwidth">
<div className="col-md-4 nopadding padding-right-xs">
<Checkbox
name="gas"
checked={this.state.data.gas ? 'checked': null}
value="1"
>
Dissolved Gas
</Checkbox>
</div>
<div className="col-md-4 nopadding padding-right-xs">
<Checkbox
name="furans"
checked={this.state.data.furans ? 'checked': null}
value="1"
>Furans</Checkbox>
</div>
<div className="col-md-4 nopadding">
<Checkbox
name="pcb"
checked={this.state.data.pcb ? 'checked': null}
value="1"
>PCB</Checkbox>
</div>
</div>
<div className="maxwidth">
<div className="col-md-4 nopadding padding-right-xs">
<Checkbox
name="water"
checked={this.state.data.water ? 'checked': null}
value="1"
>Water</Checkbox>
</div>
<div className="col-md-4 nopadding padding-right-xs">
<Checkbox
name="inhibitor"
checked={this.state.data.inhibitor ? 'checked': null}
value="1"
>Inhibitor</Checkbox>
</div>
</div>
</div>
<div className="col-md-4 nopadding">
<div className="col-md-2 nopadding padding-right-xs">
<FormGroup validationState={this.state.errors.qty_ser ? 'error' : null}>
<ControlLabel>Quantity</ControlLabel>
<FormControl type="text" ref="qty_ser" name="qty_ser"
value={this.state.data.qty_ser}
data-type="float"/>
<HelpBlock className="warning">{this.state.errors.qty_ser}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
</div>
<div className="col-md-10 nopadding">
<SamplPointSelectField1
source="/api/v1.0/sampling_point"
value={this.state.data.sampling}
/>
</div>
</div>
</div>
</fieldset>
</div>
<div className="scheduler-border">
<fieldset className="scheduler-border">
<legend className="scheduler-border">Jar - Test requested</legend>
<div className="control-group">
<div className="col-md-8 nopadding padding-right-xs">
<div className="maxwidth">
<div className="col-md-4 nopadding padding-right-xs">
<Checkbox
name="dielec"
checked={this.state.data.dielec ? 'checked': null}
value="1"
>Dielec .D1816(1mm)(kV)</Checkbox>
</div>
<div className="col-md-4 nopadding padding-right-xs">
<Checkbox
name="dielec_2"
checked={this.state.data.dielec_2 ? 'checked': null}
value="1"
>Dielec.D1816(2mm)(kV)</Checkbox>
</div>
<div className="col-md-4 nopadding">
<Checkbox
name="dielec_d"
checked={this.state.data.dielec_d ? 'checked': null}
value="1"
>Dielec. D877(kV)</Checkbox>
</div>
</div>
<div className="maxwidth">
<div className="col-md-4 nopadding padding-right-xs">
<Checkbox name="acidity"
checked={this.state.data.acidity ? 'checked': null}
value="1"
>Acidity(D974)</Checkbox>
</div>
<div className="col-md-4 nopadding padding-right-xs">
<Checkbox
name="color"
checked={this.state.data.color ? 'checked': null}
value="1"
>Color(D1500)</Checkbox>
</div>
<div className="col-md-4 nopadding">
<Checkbox
name="ift"
checked={this.state.data.ift ? 'checked': null}
value="1"
>IFT(D971)</Checkbox>
</div>
</div>
<div className="maxwidth">
<div className="col-md-4 nopadding padding-right-xs">
<Checkbox
name="density"
checked={this.state.data.density ? 'checked': null}
value="1"
>Density(D1298)</Checkbox>
</div>
<div className="col-md-4 nopadding padding-right-xs">
<Checkbox
name="pf"
checked={this.state.data.pf ? 'checked': null}
value="1"
>PF25C(D924)</Checkbox>
</div>
<div className="col-md-4 nopadding">
<Checkbox
name="pf_100"
checked={this.state.data.pf_100 ? 'checked': null}
value="1"
>PF100C(D924)</Checkbox>
</div>
</div>
<div className="maxwidth">
<div className="col-md-4 nopadding padding-right-xs">
<Checkbox
name="pcb_jar"
checked={this.state.data.pcb_jar ? 'checked': null}
value="1"
>PCB</Checkbox>
</div>
<div className="col-md-4 nopadding padding-right-xs">
<Checkbox
name="particles"
checked={this.state.data.particles ? 'checked': null}
value="1"
>Particles</Checkbox>
</div>
<div className="col-md-4 nopadding">
<Checkbox
name="furans_f"
checked={this.state.data.furans_f ? 'checked': null}
value="1"
>Furans</Checkbox>
</div>
</div>
<div className="maxwidth">
<div className="col-md-4 nopadding padding-right-xs">
<Checkbox
name="inhibitor_jar"
checked={this.state.data.inhibitor_jar ? 'checked': null}
value="1"
>Inhibitor</Checkbox>
</div>
<div className="col-md-4 nopadding padding-right-xs">
<Checkbox
name="metals"
checked={this.state.data.metals ? 'checked': null}
value="1"
>Metals in oil</Checkbox>
</div>
<div className="col-md-4 nopadding">
<Checkbox
name="water_w"
checked={this.state.data.water_w ? 'checked': null}
value="1"
>Water</Checkbox>
</div>
</div>
<div className="maxwidth">
<div className="col-md-4 nopadding padding-right-xs">
<Checkbox
name="point"
checked={this.state.data.point ? 'checked': null}
value="1"
>PouPoint</Checkbox>
</div>
<div className="col-md-4 nopadding padding-right-xs">
<Checkbox
name="viscosity"
checked={this.state.data.viscosity ? 'checked': null}
value="1"
>Viscosity</Checkbox>
</div>
<div className="col-md-4 nopadding">
<Checkbox
name="corr"
checked={this.state.data.corr ? 'checked': null}
value="1"
>Corr.Sulfur</Checkbox>
</div>
</div>
</div>
<div className="col-md-4 nopadding">
<div className="maxwidth">
<Checkbox
name="dielec_i"
checked={this.state.data.dielec_i ? 'checked': null}
value="1"
>Dielec.IEC-156(kV)</Checkbox>
</div>
<div className="maxwidth">
<Checkbox
name="visual"
checked={this.state.data.visual ? 'checked': null}
value="1"
>Visual(D1524)</Checkbox>
</div>
<div className="maxwidth">
<div className="col-md-2 nopadding padding-right-xs">
<FormGroup validationState={this.state.errors.qty_jar ? 'error' : null}>
<ControlLabel>Quantity</ControlLabel>
<FormControl type="text" name="qty_jar"
value={this.state.data.qty_jar}
data-type="float"/>
<HelpBlock className="warning">{this.state.errors.qty_jar}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
</div>
<div className="col-md-10 nopadding">
<SamplPointSelectField2
source="/api/v1.0/sampling_point"
value={ this.state.data.sampling_jar}
/>
</div>
</div>
</div>
</div>
</fieldset>
</div>
<div className="scheduler-border">
<fieldset className="scheduler-border">
<legend className="scheduler-border">4-ml - Tests requested</legend>
<div className="control-group">
<div className="col-md-8 nopadding padding-right-xs">
<div className="maxwidth">
<Checkbox
name="pcb_vial"
checked={this.state.data.pcb_vial ? 'checked': null}
value="1"
>PCB</Checkbox>
</div>
<div className="maxwidth">
<Checkbox
name="antioxidant"
checked={this.state.data.antioxidant ? 'checked': null}
value="1"
>Antioxydant</Checkbox>
</div>
</div>
<div className="col-md-4 nopadding">
<div className="col-md-2 nopadding padding-right-xs">
<FormGroup validationState={this.state.errors.qty_vial ? 'error' : null}>
<ControlLabel>Quantity</ControlLabel>
<FormControl type="text" name="qty_vial"
value={this.state.data.qty_vial}
data-type="float"/>
<HelpBlock className="warning">{this.state.errors.qty_vial}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
</div>
<div className="col-md-10 nopadding">
<SamplPointSelectField3
source="/api/v1.0/sampling_point"
value={ this.state.data.sampling_vial}/>
</div>
</div>
</div>
</fieldset>
<div className="row">
<div className="col-md-1">
<div>Save As</div>
</div>
<div className="col-md-2">
<div className="row">
<FormGroup validationState={this.state.errors.name ? 'error' : null}>
<FormControl type="text"
placeholder="Fluid profile name"
name="name"
data-len="256"
value={this.state.name}/>
<HelpBlock className="warning">{this.state.errors.name}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
</div>
<div className="row">
<Radio name="shared" value="1" inline={true}>
Global
</Radio>
<Radio name="shared" value="0" inline={true}>
Private
</Radio>
</div>
</div>
<div className="col-md-4">
<FormGroup controlId="descTextarea"
validationState={this.state.errors.description ? 'error' : null}>
<FormControl
componentClass="textarea"
placeholder="Description"
ref="description"
name="description"
data-len="1024"
value={this.state.description}
/>
<HelpBlock className="warning">{this.state.errors.description}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
</div>
</div>
<div className="row">
<div className="col-md-12">
<Button bsStyle="success" type="submit" className="pull-right">Save</Button>
<Button bsStyle="danger"
onClick={this.props.handleClose}
className="pull-right margin-right-xs">Close</Button>
</div>
</div>
</div>
</Panel>
</div>
</form>
</div>
);
}
});
export default FluidProfileForm;
|
react/EducationIcon/EducationIcon.js | seekinternational/seek-asia-style-guide | import svgMarkup from './EducationIcon.svg';
import React from 'react';
import Icon from '../private/Icon/Icon';
export default function EducationIcon(props) {
return <Icon markup={svgMarkup} {...props} />;
}
EducationIcon.displayName = 'EducationIcon';
|
react/react-tutorial/src/components/App/App.js | xmementoit/practiseSamples | import React, { Component } from 'react';
import './App.css';
import Table from '../Table/Table';
import Form from '../Form/Form';
class App extends Component {
state = {
characters: [],
}
removeCharacter = index => {
const { characters } = this.state
this.setState({
characters: characters.filter((character, i) => {
return i !== index
}),
})
}
handleSubmit = character => {
this.setState({ characters: [...this.state.characters, character] })
}
render() {
const { characters } = this.state
return (
<div className="container">
<Table characterData={characters} removeCharacter={this.removeCharacter} />
<Form handleSubmit={this.handleSubmit} />
</div>
)
}
}
export default App;
|
src/index.js | envyN/Algorithms | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals(console.log);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.